title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Rive animations in Flutter
15 Jul, 2020 Rive is a very useful animation tool that can create beautiful animations and we can add these in our Application. In flutter, we can add animations by writing so many lines of code but this is not a good practice for a developer. Instead of writing lines of code to create animation, we can create one using this powerful Rive animation tool. Please read all the below points in sequence to understand the topic clearly. Create a new Flutter application using command Prompt. For creating a new app, write flutter create YOUR_APP_NAME and run this command. Open the app in VS Code or in Android Studio. I am using VS Code. Delete the default code from main.dart file for now. Now to create new animation go ahead to https://rive.app/explore/popular/trending/all . You can also export animations that were created by some other users. Click any animation and Click “Open in Rive”. Then download it by clicking the export button. The file extension should be .flr and format should be Binary. Now, open VS Code and create new folder “assets” in the root directory of the application and paste the files which you have downloaded from rive. I have 4 files in the assets folder. -android -assets -my.flr -teddy.flr -test2.flr -test3.flr -build -ios -lib -main.dart -test -web -pubspec.lock -pubspec.yaml -README.md -rive_flutter.iml Now, edit pubspec.yaml file :Add rive in dependencies :Add assets in flutter: Add rive in dependencies : Add assets in flutter: After that, open main.dart file as we are going to write the code in this file. Delete all the code from the main.dart file and write the below code to add animations to our application. Dart import 'package:flutter/material.dart';import 'package:flare_flutter/flare_actor.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("GeeksForGeeks")), body: Container( child: ListView( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( "assets/test3.flr", animation: "day_and_night", ), ), ), Padding( padding: const EdgeInsets.all(10.0), child: Container( width: 700, height: 300, child: FlareActor( "assets/my.flr", animation: "left2right", ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( "assets/teddy.flr", //test, success,idle,fail animation: "success", ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( "assets/test2.flr", animation: "Demo Mode", ), ), ), ], ), ), ); }} We will display these animations on our Home Screen. Don’t forget to give the type of animation in FlareActor Widget otherwise, you will not get any animation effect. Run the app by writing command flutter run in terminal and see the output. Output: Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2020" }, { "code": null, "e": 475, "s": 52, "text": "Rive is a very useful animation tool that can create beautiful animations and we can add these in our Application. In flutter, we can add animations by writing so many lines of code but this is not a good practice for a developer. Instead of writing lines of code to create animation, we can create one using this powerful Rive animation tool. Please read all the below points in sequence to understand the topic clearly. " }, { "code": null, "e": 611, "s": 475, "text": "Create a new Flutter application using command Prompt. For creating a new app, write flutter create YOUR_APP_NAME and run this command." }, { "code": null, "e": 677, "s": 611, "text": "Open the app in VS Code or in Android Studio. I am using VS Code." }, { "code": null, "e": 730, "s": 677, "text": "Delete the default code from main.dart file for now." }, { "code": null, "e": 818, "s": 730, "text": "Now to create new animation go ahead to https://rive.app/explore/popular/trending/all ." }, { "code": null, "e": 982, "s": 818, "text": "You can also export animations that were created by some other users. Click any animation and Click “Open in Rive”. Then download it by clicking the export button." }, { "code": null, "e": 1045, "s": 982, "text": "The file extension should be .flr and format should be Binary." }, { "code": null, "e": 1229, "s": 1045, "text": "Now, open VS Code and create new folder “assets” in the root directory of the application and paste the files which you have downloaded from rive. I have 4 files in the assets folder." }, { "code": null, "e": 1404, "s": 1229, "text": "-android\n-assets\n -my.flr\n -teddy.flr\n -test2.flr\n -test3.flr\n-build\n-ios\n-lib\n -main.dart\n-test\n-web\n-pubspec.lock\n-pubspec.yaml\n-README.md\n-rive_flutter.iml\n" }, { "code": null, "e": 1482, "s": 1404, "text": "Now, edit pubspec.yaml file :Add rive in dependencies :Add assets in flutter:" }, { "code": null, "e": 1509, "s": 1482, "text": "Add rive in dependencies :" }, { "code": null, "e": 1532, "s": 1509, "text": "Add assets in flutter:" }, { "code": null, "e": 1612, "s": 1532, "text": "After that, open main.dart file as we are going to write the code in this file." }, { "code": null, "e": 1719, "s": 1612, "text": "Delete all the code from the main.dart file and write the below code to add animations to our application." }, { "code": null, "e": 1724, "s": 1719, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:flare_flutter/flare_actor.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(\"GeeksForGeeks\")), body: Container( child: ListView( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( \"assets/test3.flr\", animation: \"day_and_night\", ), ), ), Padding( padding: const EdgeInsets.all(10.0), child: Container( width: 700, height: 300, child: FlareActor( \"assets/my.flr\", animation: \"left2right\", ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( \"assets/teddy.flr\", //test, success,idle,fail animation: \"success\", ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 700, height: 300, child: FlareActor( \"assets/test2.flr\", animation: \"Demo Mode\", ), ), ), ], ), ), ); }}", "e": 3828, "s": 1724, "text": null }, { "code": null, "e": 3995, "s": 3828, "text": "We will display these animations on our Home Screen. Don’t forget to give the type of animation in FlareActor Widget otherwise, you will not get any animation effect." }, { "code": null, "e": 4071, "s": 3995, "text": "Run the app by writing command flutter run in terminal and see the output. " }, { "code": null, "e": 4079, "s": 4071, "text": "Output:" }, { "code": null, "e": 4084, "s": 4079, "text": "Dart" } ]
Java Program to Implement Type Casting and Type Conversion
28 Oct, 2021 There are many situations that come when we have to change the functionality of the output as well as the type of output according to the need of the requirements. For e.g. Entered PI value in decimal format should be converted in the decimal format so that value can be used efficiently without any kind of errors and wrong output. There are two ways we can change the type from one to another. Type castingType conversion Type casting Type conversion Type Casting means to change one state to another state and is done by the programmer using the cast operator. Type Casting is done during the program design time by the programmer. Typecasting also refers to Narrow Conversion. Because in many cases, We have to Cast large datatype values into smaller datatype values according to the requirement of the operations. We can also convert large datatype values into smaller datatype values that’s why Type Casting called Narrow Casting. Syntax: () is Cast Operator RequiredDatatype=(TargetType)Variable Example 1: Java // Java Program to Implement Type Casting of the Datatype // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an Integer datatype int a = 3; // Casting to Large datatype double db = (double)a; // Print and display the casted value System.out.println(db); // Narrow Casting conversion int db1 = (int)db; // Print an display narrow casted value System.out.println(db1); }} 3.0 3 Type Conversion is a type conversion that is done by compiler done by a compiler without the intention of the programmer during the compile time. This Conversion sometimes creates an error or incorrect answer if the proper resultant data type does not mention at the end of the multiple expression of the datatype that’s why Type Conversion is less efficient than Type Casting. The working mechanism of type conversion is as follows: double > float > long > int > short > byte Example 1: Error during type conversion Java // Java Program to illustrate Type Conversion // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables to values // with different return type long a = 3; byte b = 2; double c = 2.0; // Type Conversion int final_datatype = (a + b + c); // Print statement System.out.print(final_datatype); }} Output: prog.java:9: error: incompatible types: possible lossy conversion from double to int int final_datatype = (a + b + c); ^ 1 error Output explanation: When you assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example, assigning an int value to a long variable. Example 2: Java // Java Program to illustrate Type Conversion // Importing input output classesimport java.io.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables to values // but to different data types long a = 3; byte b = 2; double c = 2.0; // Type Conversion // As long and byte data types are converted to // double return type double final_datatype = (a + b + c); // Printing the sum of all three initialized values System.out.print(final_datatype); }} 7.0 simmytarika5 ruhelaa48 akshaysingh98088 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 361, "s": 28, "text": "There are many situations that come when we have to change the functionality of the output as well as the type of output according to the need of the requirements. For e.g. Entered PI value in decimal format should be converted in the decimal format so that value can be used efficiently without any kind of errors and wrong output." }, { "code": null, "e": 424, "s": 361, "text": "There are two ways we can change the type from one to another." }, { "code": null, "e": 452, "s": 424, "text": "Type castingType conversion" }, { "code": null, "e": 465, "s": 452, "text": "Type casting" }, { "code": null, "e": 481, "s": 465, "text": "Type conversion" }, { "code": null, "e": 965, "s": 481, "text": "Type Casting means to change one state to another state and is done by the programmer using the cast operator. Type Casting is done during the program design time by the programmer. Typecasting also refers to Narrow Conversion. Because in many cases, We have to Cast large datatype values into smaller datatype values according to the requirement of the operations. We can also convert large datatype values into smaller datatype values that’s why Type Casting called Narrow Casting." }, { "code": null, "e": 993, "s": 965, "text": "Syntax: () is Cast Operator" }, { "code": null, "e": 1031, "s": 993, "text": "RequiredDatatype=(TargetType)Variable" }, { "code": null, "e": 1042, "s": 1031, "text": "Example 1:" }, { "code": null, "e": 1047, "s": 1042, "text": "Java" }, { "code": "// Java Program to Implement Type Casting of the Datatype // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an Integer datatype int a = 3; // Casting to Large datatype double db = (double)a; // Print and display the casted value System.out.println(db); // Narrow Casting conversion int db1 = (int)db; // Print an display narrow casted value System.out.println(db1); }}", "e": 1620, "s": 1047, "text": null }, { "code": null, "e": 1626, "s": 1620, "text": "3.0\n3" }, { "code": null, "e": 2004, "s": 1626, "text": "Type Conversion is a type conversion that is done by compiler done by a compiler without the intention of the programmer during the compile time. This Conversion sometimes creates an error or incorrect answer if the proper resultant data type does not mention at the end of the multiple expression of the datatype that’s why Type Conversion is less efficient than Type Casting." }, { "code": null, "e": 2060, "s": 2004, "text": "The working mechanism of type conversion is as follows:" }, { "code": null, "e": 2103, "s": 2060, "text": "double > float > long > int > short > byte" }, { "code": null, "e": 2143, "s": 2103, "text": "Example 1: Error during type conversion" }, { "code": null, "e": 2148, "s": 2143, "text": "Java" }, { "code": "// Java Program to illustrate Type Conversion // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables to values // with different return type long a = 3; byte b = 2; double c = 2.0; // Type Conversion int final_datatype = (a + b + c); // Print statement System.out.print(final_datatype); }}", "e": 2647, "s": 2148, "text": null }, { "code": null, "e": 2655, "s": 2647, "text": "Output:" }, { "code": null, "e": 2828, "s": 2655, "text": "prog.java:9: error: incompatible types: possible lossy conversion from double to int\n int final_datatype = (a + b + c);\n ^\n1 error" }, { "code": null, "e": 2848, "s": 2828, "text": "Output explanation:" }, { "code": null, "e": 3198, "s": 2848, "text": "When you assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example, assigning an int value to a long variable." }, { "code": null, "e": 3209, "s": 3198, "text": "Example 2:" }, { "code": null, "e": 3214, "s": 3209, "text": "Java" }, { "code": "// Java Program to illustrate Type Conversion // Importing input output classesimport java.io.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables to values // but to different data types long a = 3; byte b = 2; double c = 2.0; // Type Conversion // As long and byte data types are converted to // double return type double final_datatype = (a + b + c); // Printing the sum of all three initialized values System.out.print(final_datatype); }}", "e": 3827, "s": 3214, "text": null }, { "code": null, "e": 3831, "s": 3827, "text": "7.0" }, { "code": null, "e": 3844, "s": 3831, "text": "simmytarika5" }, { "code": null, "e": 3854, "s": 3844, "text": "ruhelaa48" }, { "code": null, "e": 3871, "s": 3854, "text": "akshaysingh98088" }, { "code": null, "e": 3878, "s": 3871, "text": "Picked" }, { "code": null, "e": 3883, "s": 3878, "text": "Java" }, { "code": null, "e": 3897, "s": 3883, "text": "Java Programs" }, { "code": null, "e": 3902, "s": 3897, "text": "Java" } ]
mindepth and maxdepth in Linux find() command for limiting search to a specific directory.
08 May, 2019 How to limit search a specified directory in Linux?There is a command in Linux to search for files in a directory hierarchy known as ‘find’. It searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence, until the outcome is known (the left-hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.’ is assumed.The find command by default travels down the entire directory tree recursively, which is time and resource consuming. However the depth of directory traversal can be specified(which are mindepth and maxdepth). What are mindepth and maxdepth levels? maxdepth levels : Descend at most levels (a non-negative integer) levels of directories below the starting-points. -maxdepth 0 means only apply the tests and actions to the starting-points themselves. mindepth levels : Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the starting-points. Given below some examples to illustrate how depth of the directory traversal can be specified using mindepth and maxdepth Find the passwd file under all sub-directories starting from the root directory.find / -name passwd find / -name passwd Find the passwd file under root and one level down. (i.e root — level 1, and one sub-directory — level 2)find / -maxdepth 2 -name passwd find / -maxdepth 2 -name passwd Find the passwd file under root and two levels down. (i.e root — level 1, and two sub-directories — level 2 and 3 )find / -maxdepth 3 -name passwd find / -maxdepth 3 -name passwd Find the password file between sub-directory level 2 and 4.find / -mindepth 3 -maxdepth 5 -name passwd find / -mindepth 3 -maxdepth 5 -name passwd There are two other ways to limit search a directory in linux : grep Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN.By default, grep prints the matching lines.Examples of grep :You can search the current directory with grep as follows: To check whether a directory exists or not Find the directory under root directory. Find the directory under root and one levels down. ack Ack is designed as a replacement for 99% of the uses of grep. Ack searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, ack prints the matching lines.Ack can also list files that would be searched, without actually searching them, to let you take advantage of ack’s file-type filtering capabilities. Ack does not have a max-depth optionExamples of ack :To check a particular directory under the root Reference : Linux manual pageThis article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave grep Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN.By default, grep prints the matching lines. Examples of grep : You can search the current directory with grep as follows: To check whether a directory exists or not Find the directory under root directory. Find the directory under root and one levels down. ack Ack is designed as a replacement for 99% of the uses of grep. Ack searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, ack prints the matching lines.Ack can also list files that would be searched, without actually searching them, to let you take advantage of ack’s file-type filtering capabilities. Ack does not have a max-depth option Examples of ack : To check a particular directory under the root Reference : Linux manual page This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai linux-command Linux-Unix Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 May, 2019" }, { "code": null, "e": 755, "s": 52, "text": "How to limit search a specified directory in Linux?There is a command in Linux to search for files in a directory hierarchy known as ‘find’. It searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence, until the outcome is known (the left-hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.’ is assumed.The find command by default travels down the entire directory tree recursively, which is time and resource consuming. However the depth of directory traversal can be specified(which are mindepth and maxdepth)." }, { "code": null, "e": 794, "s": 755, "text": "What are mindepth and maxdepth levels?" }, { "code": null, "e": 995, "s": 794, "text": "maxdepth levels : Descend at most levels (a non-negative integer) levels of directories below the starting-points. -maxdepth 0 means only apply the tests and actions to the starting-points themselves." }, { "code": null, "e": 1164, "s": 995, "text": "mindepth levels : Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the starting-points." }, { "code": null, "e": 1286, "s": 1164, "text": "Given below some examples to illustrate how depth of the directory traversal can be specified using mindepth and maxdepth" }, { "code": null, "e": 1386, "s": 1286, "text": "Find the passwd file under all sub-directories starting from the root directory.find / -name passwd" }, { "code": null, "e": 1406, "s": 1386, "text": "find / -name passwd" }, { "code": null, "e": 1543, "s": 1406, "text": "Find the passwd file under root and one level down. (i.e root — level 1, and one sub-directory — level 2)find / -maxdepth 2 -name passwd" }, { "code": null, "e": 1575, "s": 1543, "text": "find / -maxdepth 2 -name passwd" }, { "code": null, "e": 1722, "s": 1575, "text": "Find the passwd file under root and two levels down. (i.e root — level 1, and two sub-directories — level 2 and 3 )find / -maxdepth 3 -name passwd" }, { "code": null, "e": 1754, "s": 1722, "text": "find / -maxdepth 3 -name passwd" }, { "code": null, "e": 1857, "s": 1754, "text": "Find the password file between sub-directory level 2 and 4.find / -mindepth 3 -maxdepth 5 -name passwd" }, { "code": null, "e": 1901, "s": 1857, "text": "find / -mindepth 3 -maxdepth 5 -name passwd" }, { "code": null, "e": 1965, "s": 1901, "text": "There are two other ways to limit search a directory in linux :" }, { "code": null, "e": 3405, "s": 1965, "text": "grep Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN.By default, grep prints the matching lines.Examples of grep :You can search the current directory with grep as follows:\n\n\n\nTo check whether a directory exists or not\n\n\nFind the directory under root directory.\n\n\nFind the directory under root and one levels down.\n\n\n\n\n\nack Ack is designed as a replacement for 99% of the uses of grep. Ack searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, ack prints the matching lines.Ack can also list files that would be searched, without actually searching them, to let you take advantage of ack’s file-type filtering capabilities. Ack does not have a max-depth optionExamples of ack :To check a particular directory under the root\n\n\n\n\n\n\n\nReference : Linux manual pageThis article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 3611, "s": 3405, "text": "grep Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN.By default, grep prints the matching lines." }, { "code": null, "e": 3630, "s": 3611, "text": "Examples of grep :" }, { "code": null, "e": 3837, "s": 3630, "text": "You can search the current directory with grep as follows:\n\n\n\nTo check whether a directory exists or not\n\n\nFind the directory under root directory.\n\n\nFind the directory under root and one levels down.\n\n\n\n\n\n" }, { "code": null, "e": 4289, "s": 3837, "text": "ack Ack is designed as a replacement for 99% of the uses of grep. Ack searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, ack prints the matching lines.Ack can also list files that would be searched, without actually searching them, to let you take advantage of ack’s file-type filtering capabilities. Ack does not have a max-depth option" }, { "code": null, "e": 4307, "s": 4289, "text": "Examples of ack :" }, { "code": null, "e": 4362, "s": 4307, "text": "To check a particular directory under the root\n\n\n\n\n\n\n\n" }, { "code": null, "e": 4392, "s": 4362, "text": "Reference : Linux manual page" }, { "code": null, "e": 4693, "s": 4392, "text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4818, "s": 4693, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4831, "s": 4818, "text": "Akanksha_Rai" }, { "code": null, "e": 4845, "s": 4831, "text": "linux-command" }, { "code": null, "e": 4856, "s": 4845, "text": "Linux-Unix" }, { "code": null, "e": 4874, "s": 4856, "text": "Operating Systems" }, { "code": null, "e": 4892, "s": 4874, "text": "Operating Systems" } ]
Score of Parentheses in C++
Suppose we have a balanced parentheses string S, we have to compute the score of the string based on the following rule − The () has score 1 AB has score A + B, where A and B are two balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. So if the input is like “(()(()))”, then the output will be 6. To solve this, we will follow these steps − ans := 0, define a stack st for i in range 0 to size of string Sif S[i] is opening parentheses, then insert -1 into stackotherwiseif top of stack is -1, then delete from stack and insert 1 into stackotherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x if S[i] is opening parentheses, then insert -1 into stack otherwiseif top of stack is -1, then delete from stack and insert 1 into stackotherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x if top of stack is -1, then delete from stack and insert 1 into stack otherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x x := 0 while top of stack is not -1increase x by st, delete from st increase x by st, delete from st x := x * 2 delete from st, and insert x while stack is not emptyincrease ans by top of st, and delete top element increase ans by top of st, and delete top element return ans. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int scoreOfParentheses(string S) { int ans = 0; stack <int> st; for(int i = 0; i < S.size(); i+=1){ if(S[i] == '('){ st.push(-1); }else{ if(st.top() == -1){ st.pop(); st.push(1); }else{ int x = 0; while(st.top() != -1){ x += st.top(); st.pop(); } x *= 2; st.pop(); st.push(x); } } } while(!st.empty()){ ans += st.top(); st.pop(); } return ans; } }; main(){ Solution ob; cout << (ob.scoreOfParentheses("(()(()))")); } "(()(()))" 6
[ { "code": null, "e": 1184, "s": 1062, "text": "Suppose we have a balanced parentheses string S, we have to compute the score of the string based on the following rule −" }, { "code": null, "e": 1203, "s": 1184, "text": "The () has score 1" }, { "code": null, "e": 1275, "s": 1203, "text": "AB has score A + B, where A and B are two balanced parentheses strings." }, { "code": null, "e": 1338, "s": 1275, "text": "(A) has score 2 * A, where A is a balanced parentheses string." }, { "code": null, "e": 1401, "s": 1338, "text": "So if the input is like “(()(()))”, then the output will be 6." }, { "code": null, "e": 1445, "s": 1401, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1473, "s": 1445, "text": "ans := 0, define a stack st" }, { "code": null, "e": 1758, "s": 1473, "text": "for i in range 0 to size of string Sif S[i] is opening parentheses, then insert -1 into stackotherwiseif top of stack is -1, then delete from stack and insert 1 into stackotherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x" }, { "code": null, "e": 1816, "s": 1758, "text": "if S[i] is opening parentheses, then insert -1 into stack" }, { "code": null, "e": 2008, "s": 1816, "text": "otherwiseif top of stack is -1, then delete from stack and insert 1 into stackotherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x" }, { "code": null, "e": 2078, "s": 2008, "text": "if top of stack is -1, then delete from stack and insert 1 into stack" }, { "code": null, "e": 2192, "s": 2078, "text": "otherwisex := 0while top of stack is not -1increase x by st, delete from stx := x * 2delete from st, and insert x" }, { "code": null, "e": 2199, "s": 2192, "text": "x := 0" }, { "code": null, "e": 2260, "s": 2199, "text": "while top of stack is not -1increase x by st, delete from st" }, { "code": null, "e": 2293, "s": 2260, "text": "increase x by st, delete from st" }, { "code": null, "e": 2304, "s": 2293, "text": "x := x * 2" }, { "code": null, "e": 2333, "s": 2304, "text": "delete from st, and insert x" }, { "code": null, "e": 2407, "s": 2333, "text": "while stack is not emptyincrease ans by top of st, and delete top element" }, { "code": null, "e": 2457, "s": 2407, "text": "increase ans by top of st, and delete top element" }, { "code": null, "e": 2469, "s": 2457, "text": "return ans." }, { "code": null, "e": 2539, "s": 2469, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2550, "s": 2539, "text": " Live Demo" }, { "code": null, "e": 3341, "s": 2550, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int scoreOfParentheses(string S) {\n int ans = 0;\n stack <int> st;\n for(int i = 0; i < S.size(); i+=1){\n if(S[i] == '('){\n st.push(-1);\n }else{\n if(st.top() == -1){\n st.pop();\n st.push(1);\n }else{\n int x = 0;\n while(st.top() != -1){\n x += st.top();\n st.pop();\n }\n x *= 2;\n st.pop();\n st.push(x);\n }\n }\n }\n while(!st.empty()){\n ans += st.top();\n st.pop();\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.scoreOfParentheses(\"(()(()))\"));\n}" }, { "code": null, "e": 3352, "s": 3341, "text": "\"(()(()))\"" }, { "code": null, "e": 3354, "s": 3352, "text": "6" } ]
AJAX - Action
This chapter gives you a clear picture of the exact steps of AJAX operation. A client event occurs. An XMLHttpRequest object is created. The XMLHttpRequest object is configured. The XMLHttpRequest object makes an asynchronous request to the Webserver. The Webserver returns the result containing XML document. The XMLHttpRequest object calls the callback() function and processes the result. The HTML DOM is updated. Let us take these steps one by one. A JavaScript function is called as the result of an event. A JavaScript function is called as the result of an event. Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to "userid" Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to "userid" <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">. <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">. var ajaxRequest; // The variable that makes Ajax possible! function ajaxFunction() { try { // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } } In this step, we will write a function that will be triggered by the client event and a callback function processRequest() will be registered. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); ajaxRequest.open("GET", url, true); ajaxRequest.send(null); } Source code is available in the above piece of code. Code written in bold typeface is responsible to make a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id = " + escape(target.value); ajaxRequest.open("GET", url, true); ajaxRequest.send(null); } Assume you enter Zara in the userid box, then in the above request, the URL is set to "validate?id = Zara". You can implement your server-side script in any language, however its logic should be as follows. Get a request from the client. Parse the input from the client. Do required processing. Send the output to the client. If we assume that you are going to write a servlet, then here is the piece of code. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !accounts.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>true</valid>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>false</valid>"); } } The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will receive the result from the server and will do the required processing. As in the following example, it sets a variable message on true or false based on the returned value from the Webserver. function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; ... } This is the final step and in this step, your HTML page will be updated. It happens in the following way − JavaScript gets a reference to any element in a page using DOM API. The recommended way to gain a reference to an element is to call. document.getElementById("userIdMessage"), // where "userIdMessage" is the ID attribute // of an element appearing in the HTML document JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example − JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example − <script type = "text/javascript"> <!-- function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple // replace it otherwise append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } --> </script> <body> <div id = "userIdMessage"><div> </body> If you have understood the above-mentioned seven steps, then you are almost done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail. 72 Lectures 4.5 hours Frahaan Hussain 20 Lectures 1 hours Laurence Svekis 29 Lectures 2 hours YouAccel 20 Lectures 1.5 hours YouAccel 18 Lectures 2.5 hours Stone River ELearning 47 Lectures 5.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 1813, "s": 1736, "text": "This chapter gives you a clear picture of the exact steps of AJAX operation." }, { "code": null, "e": 1836, "s": 1813, "text": "A client event occurs." }, { "code": null, "e": 1873, "s": 1836, "text": "An XMLHttpRequest object is created." }, { "code": null, "e": 1914, "s": 1873, "text": "The XMLHttpRequest object is configured." }, { "code": null, "e": 1988, "s": 1914, "text": "The XMLHttpRequest object makes an asynchronous request to the Webserver." }, { "code": null, "e": 2046, "s": 1988, "text": "The Webserver returns the result containing XML document." }, { "code": null, "e": 2128, "s": 2046, "text": "The XMLHttpRequest object calls the callback() function and processes the result." }, { "code": null, "e": 2153, "s": 2128, "text": "The HTML DOM is updated." }, { "code": null, "e": 2189, "s": 2153, "text": "Let us take these steps one by one." }, { "code": null, "e": 2248, "s": 2189, "text": "A JavaScript function is called as the result of an event." }, { "code": null, "e": 2307, "s": 2248, "text": "A JavaScript function is called as the result of an event." }, { "code": null, "e": 2452, "s": 2307, "text": "Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to \"userid\"" }, { "code": null, "e": 2597, "s": 2452, "text": "Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to \"userid\"" }, { "code": null, "e": 2688, "s": 2597, "text": "<input type = \"text\" size = \"20\" id = \"userid\" name = \"id\" onkeyup = \"validateUserId();\">." }, { "code": null, "e": 2779, "s": 2688, "text": "<input type = \"text\" size = \"20\" id = \"userid\" name = \"id\" onkeyup = \"validateUserId();\">." }, { "code": null, "e": 3350, "s": 2779, "text": "var ajaxRequest; // The variable that makes Ajax possible!\nfunction ajaxFunction() {\n try {\n // Opera 8.0+, Firefox, Safari\n ajaxRequest = new XMLHttpRequest();\n } catch (e) {\n \n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n \n try {\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n \n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n}" }, { "code": null, "e": 3493, "s": 3350, "text": "In this step, we will write a function that will be triggered by the client event and a callback function processRequest() will be registered." }, { "code": null, "e": 3838, "s": 3493, "text": "function validateUserId() {\n ajaxFunction();\n \n // Here processRequest() is the callback function.\n ajaxRequest.onreadystatechange = processRequest;\n \n if (!target) target = document.getElementById(\"userid\");\n var url = \"validate?id=\" + escape(target.value);\n \n ajaxRequest.open(\"GET\", url, true);\n ajaxRequest.send(null);\n}" }, { "code": null, "e": 4040, "s": 3838, "text": "Source code is available in the above piece of code. Code written in bold typeface is responsible to make a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest." }, { "code": null, "e": 4387, "s": 4040, "text": "function validateUserId() {\n ajaxFunction();\n \n // Here processRequest() is the callback function.\n ajaxRequest.onreadystatechange = processRequest;\n \n if (!target) target = document.getElementById(\"userid\");\n var url = \"validate?id = \" + escape(target.value);\n \n ajaxRequest.open(\"GET\", url, true);\n ajaxRequest.send(null);\n}" }, { "code": null, "e": 4495, "s": 4387, "text": "Assume you enter Zara in the userid box, then in the above request, the URL is set to \"validate?id = Zara\"." }, { "code": null, "e": 4594, "s": 4495, "text": "You can implement your server-side script in any language, however its logic should be as follows." }, { "code": null, "e": 4625, "s": 4594, "text": "Get a request from the client." }, { "code": null, "e": 4658, "s": 4625, "text": "Parse the input from the client." }, { "code": null, "e": 4682, "s": 4658, "text": "Do required processing." }, { "code": null, "e": 4713, "s": 4682, "text": "Send the output to the client." }, { "code": null, "e": 4797, "s": 4713, "text": "If we assume that you are going to write a servlet, then here is the piece of code." }, { "code": null, "e": 5369, "s": 4797, "text": "public void doGet(HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n String targetId = request.getParameter(\"id\");\n \n if ((targetId != null) && !accounts.containsKey(targetId.trim())) {\n response.setContentType(\"text/xml\");\n response.setHeader(\"Cache-Control\", \"no-cache\");\n response.getWriter().write(\"<valid>true</valid>\");\n } else {\n response.setContentType(\"text/xml\");\n response.setHeader(\"Cache-Control\", \"no-cache\");\n response.getWriter().write(\"<valid>false</valid>\");\n }\n}" }, { "code": null, "e": 5741, "s": 5369, "text": "The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will receive the result from the server and will do the required processing. As in the following example, it sets a variable message on true or false based on the returned value from the Webserver." }, { "code": null, "e": 5866, "s": 5741, "text": " \nfunction processRequest() {\n if (req.readyState == 4) {\n if (req.status == 200) {\n var message = ...;\n...\n}" }, { "code": null, "e": 5973, "s": 5866, "text": "This is the final step and in this step, your HTML page will be updated. It happens in the following way −" }, { "code": null, "e": 6041, "s": 5973, "text": "JavaScript gets a reference to any element in a page using DOM API." }, { "code": null, "e": 6107, "s": 6041, "text": "The recommended way to gain a reference to an element is to call." }, { "code": null, "e": 6244, "s": 6107, "text": "document.getElementById(\"userIdMessage\"), \n// where \"userIdMessage\" is the ID attribute \n// of an element appearing in the HTML document" }, { "code": null, "e": 6413, "s": 6244, "text": "JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example −" }, { "code": null, "e": 6582, "s": 6413, "text": "JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example −" }, { "code": null, "e": 7481, "s": 6582, "text": "<script type = \"text/javascript\">\n <!--\n function setMessageUsingDOM(message) {\n var userMessageElement = document.getElementById(\"userIdMessage\");\n var messageText;\n \n if (message == \"false\") {\n userMessageElement.style.color = \"red\";\n messageText = \"Invalid User Id\";\n } else {\n userMessageElement.style.color = \"green\";\n messageText = \"Valid User Id\";\n }\n \n var messageBody = document.createTextNode(messageText);\n \n // if the messageBody element has been created simple \n // replace it otherwise append the new element\n if (userMessageElement.childNodes[0]) {\n userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);\n } else {\n userMessageElement.appendChild(messageBody);\n }\n }\n -->\n</script>\n\n<body>\n <div id = \"userIdMessage\"><div>\n</body>" }, { "code": null, "e": 7644, "s": 7481, "text": "If you have understood the above-mentioned seven steps, then you are almost done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail." }, { "code": null, "e": 7679, "s": 7644, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7696, "s": 7679, "text": " Frahaan Hussain" }, { "code": null, "e": 7729, "s": 7696, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 7746, "s": 7729, "text": " Laurence Svekis" }, { "code": null, "e": 7779, "s": 7746, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 7789, "s": 7779, "text": " YouAccel" }, { "code": null, "e": 7824, "s": 7789, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7834, "s": 7824, "text": " YouAccel" }, { "code": null, "e": 7869, "s": 7834, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7892, "s": 7869, "text": " Stone River ELearning" }, { "code": null, "e": 7927, "s": 7892, "text": "\n 47 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7945, "s": 7927, "text": " Packt Publishing" }, { "code": null, "e": 7952, "s": 7945, "text": " Print" }, { "code": null, "e": 7963, "s": 7952, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML image link
[]
Find the node with maximum value in a Binary Search Tree - GeeksforGeeks
12 Sep, 2021 Given a Binary Search Tree, the task is to find the node with the maximum value in a BST. For the above tree, we start with 20, then we move right to 22. We keep on moving to the right until we see NULL. Since the right of 22 is NULL, 22 is the node with the maximum value. Approach: This is quite simple. Just traverse the node from root to right recursively until the right is NULL. The node whose right is NULL is the node with the maximum value. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // Function to create a new nodestruct node* newNode(int data){ struct node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return (newnode);} // Function to insert a new node in BSTstruct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} // Function to find the node with maximum value// i.e. rightmost leaf nodeint maxValue(struct node* node){ /* loop down to find the rightmost leaf */ struct node* current = node; while (current->right != NULL) current = current->right; return (current->data);} // Driver codeint main(){ struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); cout << "Maximum value in BST is " << maxValue(root); return 0;} // Java implementation to find the sum of last// 'n' nodes of the Linked Listimport java.util.*; class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */static class node{ int data; node left; node right;}; // Function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to insert a new node in BSTstatic node insert(node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to find the node with maximum value// i.e. rightmost leaf nodestatic int maxValue(node node){ /* loop down to find the rightmost leaf */ node current = node; while (current.right != null) current = current.right; return (current.data);} // Driver codepublic static void main(String[] args) { node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); System.out.println("Maximum value in BST is " + maxValue(root));}} /* This code is contributed by PrinciRaj1992 */ import sysimport math # A binary tree node has data, pointer to left child # and a pointer to right child class Node: def __init__(self,data): self.data = data self.left = None self.right = None # Function to insert a new node in BSTdef insert(root, data): # 1. If the tree is empty, return a new, # single node if not root: return Node(data) # 2. Otherwise, recur down the tree if data < root.data: root.left = insert(root.left, data) if data > root.data: root.right = insert(root.right, data) # return the (unchanged) node pointer return root # Function to find the node with maximum value # i.e. rightmost leaf node def maxValue(root): current = root #loop down to find the rightmost leaf while(current.right): current = current.right return current.data # Driver code if __name__=='__main__': root=None root = insert(root,2) root = insert(root,1) root = insert(root,3) root = insert(root,6) root = insert(root,5) print("Maximum value in BST is {}".format(maxValue(root))) # This code is contributed by Vikash Kumar 37 // C# implementation to find the sum of last // 'n' nodes of the Linked List using System; class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */public class node { public int data; public node left; public node right; }; // Function to create a new node static node newNode(int data) { node node = new node(); node.data = data; node.left = null; node.right = null; return (node); } // Function to insert a new node in BST static node insert(node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; } } // Function to find the node with maximum value // i.e. rightmost leaf node static int maxValue(node node) { /* loop down to find the rightmost leaf */ node current = node; while (current.right != null) current = current.right; return (current.data); } // Driver code public static void Main(String[] args) { node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); Console.WriteLine("Maximum value in BST is " + maxValue(root)); } } // This code is contributed by Rajput-Ji <script> // javascript implementation to find the sum of last // 'n' nodes of the Linked List /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } // Function to create a new node function newNode(data) { var node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } // Function to insert a new node in BST function insert( node , data) { /* * 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; } } // Function to find the node with maximum value // i.e. rightmost leaf node function maxValue( node) { /* loop down to find the rightmost leaf */ var current = node; while (current.right != null) current = current.right; return (current.data); } // Driver code var root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); document.write("Maximum value in BST is " + maxValue(root)); // This code contributed by Rajput-Ji </script> Maximum value in BST is 6 Time Complexity: O(N) Auxiliary Space: O(1) Vikash Kumar 37 princiraj1992 Rajput-Ji pankajsharmagfg Technical Scripter 2018 Binary Search Tree Data Structures Technical Scripter Tree Data Structures Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Red Black Tree vs AVL Tree set vs unordered_set in C++ STL Print BST keys in the given range Implementing Forward Iterator in BST Construct BST from given preorder traversal | Set 2 SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class
[ { "code": null, "e": 24833, "s": 24805, "text": "\n12 Sep, 2021" }, { "code": null, "e": 24924, "s": 24833, "text": "Given a Binary Search Tree, the task is to find the node with the maximum value in a BST. " }, { "code": null, "e": 25109, "s": 24924, "text": "For the above tree, we start with 20, then we move right to 22. We keep on moving to the right until we see NULL. Since the right of 22 is NULL, 22 is the node with the maximum value. " }, { "code": null, "e": 25287, "s": 25109, "text": "Approach: This is quite simple. Just traverse the node from root to right recursively until the right is NULL. The node whose right is NULL is the node with the maximum value. " }, { "code": null, "e": 25291, "s": 25287, "text": "C++" }, { "code": null, "e": 25296, "s": 25291, "text": "Java" }, { "code": null, "e": 25304, "s": 25296, "text": "Python3" }, { "code": null, "e": 25307, "s": 25304, "text": "C#" }, { "code": null, "e": 25318, "s": 25307, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // Function to create a new nodestruct node* newNode(int data){ struct node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return (newnode);} // Function to insert a new node in BSTstruct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} // Function to find the node with maximum value// i.e. rightmost leaf nodeint maxValue(struct node* node){ /* loop down to find the rightmost leaf */ struct node* current = node; while (current->right != NULL) current = current->right; return (current->data);} // Driver codeint main(){ struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); cout << \"Maximum value in BST is \" << maxValue(root); return 0;}", "e": 26771, "s": 25318, "text": null }, { "code": "// Java implementation to find the sum of last// 'n' nodes of the Linked Listimport java.util.*; class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */static class node{ int data; node left; node right;}; // Function to create a new nodestatic node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to insert a new node in BSTstatic node insert(node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to find the node with maximum value// i.e. rightmost leaf nodestatic int maxValue(node node){ /* loop down to find the rightmost leaf */ node current = node; while (current.right != null) current = current.right; return (current.data);} // Driver codepublic static void main(String[] args) { node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); System.out.println(\"Maximum value in BST is \" + maxValue(root));}} /* This code is contributed by PrinciRaj1992 */", "e": 28288, "s": 26771, "text": null }, { "code": "import sysimport math # A binary tree node has data, pointer to left child # and a pointer to right child class Node: def __init__(self,data): self.data = data self.left = None self.right = None # Function to insert a new node in BSTdef insert(root, data): # 1. If the tree is empty, return a new, # single node if not root: return Node(data) # 2. Otherwise, recur down the tree if data < root.data: root.left = insert(root.left, data) if data > root.data: root.right = insert(root.right, data) # return the (unchanged) node pointer return root # Function to find the node with maximum value # i.e. rightmost leaf node def maxValue(root): current = root #loop down to find the rightmost leaf while(current.right): current = current.right return current.data # Driver code if __name__=='__main__': root=None root = insert(root,2) root = insert(root,1) root = insert(root,3) root = insert(root,6) root = insert(root,5) print(\"Maximum value in BST is {}\".format(maxValue(root))) # This code is contributed by Vikash Kumar 37", "e": 29445, "s": 28288, "text": null }, { "code": "// C# implementation to find the sum of last // 'n' nodes of the Linked List using System; class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */public class node { public int data; public node left; public node right; }; // Function to create a new node static node newNode(int data) { node node = new node(); node.data = data; node.left = null; node.right = null; return (node); } // Function to insert a new node in BST static node insert(node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; } } // Function to find the node with maximum value // i.e. rightmost leaf node static int maxValue(node node) { /* loop down to find the rightmost leaf */ node current = node; while (current.right != null) current = current.right; return (current.data); } // Driver code public static void Main(String[] args) { node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); Console.WriteLine(\"Maximum value in BST is \" + maxValue(root)); } } // This code is contributed by Rajput-Ji", "e": 31012, "s": 29445, "text": null }, { "code": "<script> // javascript implementation to find the sum of last // 'n' nodes of the Linked List /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } // Function to create a new node function newNode(data) { var node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } // Function to insert a new node in BST function insert( node , data) { /* * 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; } } // Function to find the node with maximum value // i.e. rightmost leaf node function maxValue( node) { /* loop down to find the rightmost leaf */ var current = node; while (current.right != null) current = current.right; return (current.data); } // Driver code var root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); document.write(\"Maximum value in BST is \" + maxValue(root)); // This code contributed by Rajput-Ji </script>", "e": 32722, "s": 31012, "text": null }, { "code": null, "e": 32748, "s": 32722, "text": "Maximum value in BST is 6" }, { "code": null, "e": 32795, "s": 32750, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 32811, "s": 32795, "text": "Vikash Kumar 37" }, { "code": null, "e": 32825, "s": 32811, "text": "princiraj1992" }, { "code": null, "e": 32835, "s": 32825, "text": "Rajput-Ji" }, { "code": null, "e": 32851, "s": 32835, "text": "pankajsharmagfg" }, { "code": null, "e": 32875, "s": 32851, "text": "Technical Scripter 2018" }, { "code": null, "e": 32894, "s": 32875, "text": "Binary Search Tree" }, { "code": null, "e": 32910, "s": 32894, "text": "Data Structures" }, { "code": null, "e": 32929, "s": 32910, "text": "Technical Scripter" }, { "code": null, "e": 32934, "s": 32929, "text": "Tree" }, { "code": null, "e": 32950, "s": 32934, "text": "Data Structures" }, { "code": null, "e": 32969, "s": 32950, "text": "Binary Search Tree" }, { "code": null, "e": 32974, "s": 32969, "text": "Tree" }, { "code": null, "e": 33072, "s": 32974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33081, "s": 33072, "text": "Comments" }, { "code": null, "e": 33094, "s": 33081, "text": "Old Comments" }, { "code": null, "e": 33121, "s": 33094, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 33153, "s": 33121, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 33187, "s": 33153, "text": "Print BST keys in the given range" }, { "code": null, "e": 33224, "s": 33187, "text": "Implementing Forward Iterator in BST" }, { "code": null, "e": 33276, "s": 33224, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 33325, "s": 33276, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33369, "s": 33325, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33394, "s": 33369, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33450, "s": 33394, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles - GeeksforGeeks
21 May, 2021 S(r, n), represents the number of ways that we can arrange r objects around indistinguishable circles of length n, and every circle n must have at least one object around it. Examples: Input: r = 9, n = 2 Output: 109584 Input: r = 6, n = 3 Output: 225 The special cases are: S(r, 0) = 0, trivial. S(r, 1) represents the circular permutation which is equal to (r – 1)! S(r, n) where r = n, equals 1. S(r, r -1) = rC2 An important identity of the Stirling numbers that S(r, n) = S(r – 1, n – 1) + (r – 1) * S(r – 1, n)Approach: For simplicity, denote the r distinct objects by 1, 2, ..., r. Consider the object “1”. In any arrangement of the objects, either “1” is the only object in a circle or“1” is mixed with others in a circle. “1” is the only object in a circle or “1” is mixed with others in a circle. In case 1, there are s(r – 1, n – 1) ways to form such arrangements. In case 2, first of all, the r — 1 objects 2, 3, ..., r are put in n circles in s(r — 1, n) ways; then “1” can be placed in one of the r — 1 distinct space to the “immediate right” of the corresponding r — 1 distinct objects. By multiplication principle, there are (r — 1)s(r — 1, n) ways to form such arrangements in case 2. The identity now follows from the definition of s(r, n) and addition principle. Using the initial values S(0, 0) = 1, s(r, 0) = 0 for r > 1 and s(r, 1) = (r — 1)! for r > 1, and applying the identity we proved, we can easily get the Stirling number by computing it in a recursive way.In the code, we have three functions that are used to generate the Stirling numbers, which are nCr(n, r), which is a function to compute what we call (n – choose – r), the number of ways we can take r objects from n objects without the importance of orderings. factorial (int n) is, unsurprisingly, used to compute the factorial of a number n. The function Stirling number(r, n) works recursively using the four base cases discussed above and then recursing using the identity we proved. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to implement above approach#include <iostream>using namespace std; // Calculating factorial of an integer n.long long factorial(int n){ // Our base cases of factorial 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number of combination// of r objects out of n objects.int nCr(int n, int r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; // nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.long long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver programint main(){ // Calculating the stirling number s(9, 2) int r = 9, n = 2; long long val = stirlingNumber(r, n); if (val == -1) cout << " No stirling number"; else cout << "The Stirling Number s(" << r << ", " << n << ") is : " << val; return 0;} // Java program to implement// above approachimport java.io.*; class GFG{ // Calculating factorial of// an integer n.static long factorial(int n){ // Our base cases of factorial // 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number// of combination of r objects// out of n objects.static int nCr(int n, int r){ // r cant be more than n so // we'd like the program to // crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling// numbers. The base cases which were// discussed above are handled to stop// the recursive calls.static long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver Codepublic static void main (String[] args){ // Calculating the stirling number s(9, 2) int r = 9, n = 2; long val = stirlingNumber(r, n); if (val == -1) System.out.println(" No stirling number"); else System.out.println( "The Stirling Number s(" + r + ", " + n + ") is : " + val);}} // This Code is Contributed by anuj_67 # Python 3 program to implement above approach # Function to compute the number of combination# of r objects out of n objects.# nCr(n, n) = 1, nCr(n, 0) = 1, and these are# the base cases. def nCr(n, r): if(n == r): return 1 if(r == 0): return 1 # nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r) # This function is used to calculate the# factorial of a number n.def factorial(n): res = 1 # 1 ! = 0 ! = 1 if(n <= 1): return res for i in range(1, n + 1): res *= i return res # Main function to calculate the Stirling numbers.# the base cases which were discussed above are# handled to stop the recursive call, n can't be# more than r, s(r, 0) = 0.# s(r, r) = 1. s(r, 1) = (r - 1)!.# s(r, r - 1) = nCr(r, 2)# else as we proved, s(r, n) = s(r - 1, n - 1)# + (r - 1) * s(r - 1, n) def stirlingNumber(r, n): if(r == n): return 1 if(n == 0): return 0 if(n == r -1): return nCr(r, 2) if(r - n == 1): return factorial(r - 1) return (stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n)) r, n = 9, 2 print(stirlingNumber(r, n)) // C# program to implement// above approachusing System; class GFG{ // Calculating factorial of// an integer n.static long factorial(int n){ // Our base cases of factorial // 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number// of combination of r objects// out of n objects.static int nCr(int n, int r){ // r cant be more than n so // we'd like the program to // crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling// numbers. The base cases which were// discussed above are handled to stop// the recursive calls.static long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver Codepublic static void Main (){ // Calculating the stirling // number s(9, 2) int r = 9, n = 2; long val = stirlingNumber(r, n); if (val == -1) Console.WriteLine(" No stirling number"); else Console.WriteLine( "The Stirling Number s(" + r + ", " + n + ") is : " + val);}} // This code is contributed by inder_verma.. <?php// PHP program to implement above approach // Calculating factorial of an integer n.function factorial($n){ // Our base cases of factorial 0! = 1! = 1 if ($n == 0) return 1; // n can't be less than 0. if ($n < 0) return -1; $res = 1; for ($i = 2; $i < $n + 1; ++$i) $res *= $i; return $res;} // Function to compute the number of combination// of r objects out of n objects.function nCr($n, $r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if ($r > $n) return -1; if ($n == $r) return 1; if ($r == 0) return 1; // nCr($n, $r) = nCr($n - 1, $r - 1) + nCr($n - 1, $r) return nCr($n - 1, $r - 1) + nCr($n - 1, $r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.function stirlingNumber($r, $n){ // n can't be more than // r, s(r, 0) = 0. if ($n > $r) return -1; if ($n == 0) return 0; if ($r == $n) return 1; if ($n == 1) return factorial($r - 1); if ($r - $n == 1) return nCr($r, 2); else return stirlingNumber($r - 1, $n - 1) + ($r - 1) * stirlingNumber($r - 1, $n);} // Calculating the stirling number s(9, 2) $r = 9; $n = 2; $val = stirlingNumber($r, $n); if ($val == -1) echo " No stirling number"; else echo "The Stirling Number s(", $r ,", " , $n , ") is : " , $val; // This code is contributed by ANKITRAI1?> <script>// js program to implement above approach // Calculating factorial of an integer n.function factorial( n){ // Our base cases of factorial 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; let res = 1; for (let i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number of combination// of r objects out of n objects.function nCr(n, r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; // nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.function stirlingNumber( r, n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver program// Calculating the stirling number s(9, 2) let r = 9, n = 2; let val = stirlingNumber(r, n); if (val == -1) document.write( " No stirling number"); else document.write( "The Stirling Number s(", r , ", " , n , ") is : " , val); </script> The Stirling Number s(9, 2) is : 109584 Note: The above solution can be optimized by Dynamic Programming. Please refer, Bell Numbers (Number of ways to Partition a Set) for example.Please refer Stirling numbers of the first kind to read more about the Stirling numbers. vt_m inderDuMCA ankthon rohitsingh07052 Combinatorial Dynamic Programming Mathematical Dynamic Programming Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Lexicographic rank of a string Count of subsets with sum equal to X Print all permutations in sorted (lexicographic) order Print all possible strings of length k that can be formed from a set of n characters Python program to get all subsets of given size of a set 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Longest Common Subsequence | DP-4 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 25146, "s": 25118, "text": "\n21 May, 2021" }, { "code": null, "e": 25321, "s": 25146, "text": "S(r, n), represents the number of ways that we can arrange r objects around indistinguishable circles of length n, and every circle n must have at least one object around it." }, { "code": null, "e": 25333, "s": 25321, "text": "Examples: " }, { "code": null, "e": 25401, "s": 25333, "text": "Input: r = 9, n = 2\nOutput: 109584\n\nInput: r = 6, n = 3\nOutput: 225" }, { "code": null, "e": 25426, "s": 25401, "text": "The special cases are: " }, { "code": null, "e": 25448, "s": 25426, "text": "S(r, 0) = 0, trivial." }, { "code": null, "e": 25519, "s": 25448, "text": "S(r, 1) represents the circular permutation which is equal to (r – 1)!" }, { "code": null, "e": 25550, "s": 25519, "text": "S(r, n) where r = n, equals 1." }, { "code": null, "e": 25567, "s": 25550, "text": "S(r, r -1) = rC2" }, { "code": null, "e": 25809, "s": 25567, "text": "An important identity of the Stirling numbers that S(r, n) = S(r – 1, n – 1) + (r – 1) * S(r – 1, n)Approach: For simplicity, denote the r distinct objects by 1, 2, ..., r. Consider the object “1”. In any arrangement of the objects, either " }, { "code": null, "e": 25884, "s": 25809, "text": "“1” is the only object in a circle or“1” is mixed with others in a circle." }, { "code": null, "e": 25922, "s": 25884, "text": "“1” is the only object in a circle or" }, { "code": null, "e": 25960, "s": 25922, "text": "“1” is mixed with others in a circle." }, { "code": null, "e": 27127, "s": 25960, "text": "In case 1, there are s(r – 1, n – 1) ways to form such arrangements. In case 2, first of all, the r — 1 objects 2, 3, ..., r are put in n circles in s(r — 1, n) ways; then “1” can be placed in one of the r — 1 distinct space to the “immediate right” of the corresponding r — 1 distinct objects. By multiplication principle, there are (r — 1)s(r — 1, n) ways to form such arrangements in case 2. The identity now follows from the definition of s(r, n) and addition principle. Using the initial values S(0, 0) = 1, s(r, 0) = 0 for r > 1 and s(r, 1) = (r — 1)! for r > 1, and applying the identity we proved, we can easily get the Stirling number by computing it in a recursive way.In the code, we have three functions that are used to generate the Stirling numbers, which are nCr(n, r), which is a function to compute what we call (n – choose – r), the number of ways we can take r objects from n objects without the importance of orderings. factorial (int n) is, unsurprisingly, used to compute the factorial of a number n. The function Stirling number(r, n) works recursively using the four base cases discussed above and then recursing using the identity we proved." }, { "code": null, "e": 27179, "s": 27127, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27183, "s": 27179, "text": "C++" }, { "code": null, "e": 27188, "s": 27183, "text": "Java" }, { "code": null, "e": 27197, "s": 27188, "text": "Python 3" }, { "code": null, "e": 27200, "s": 27197, "text": "C#" }, { "code": null, "e": 27204, "s": 27200, "text": "PHP" }, { "code": null, "e": 27215, "s": 27204, "text": "Javascript" }, { "code": "// C++ program to implement above approach#include <iostream>using namespace std; // Calculating factorial of an integer n.long long factorial(int n){ // Our base cases of factorial 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number of combination// of r objects out of n objects.int nCr(int n, int r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; // nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.long long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver programint main(){ // Calculating the stirling number s(9, 2) int r = 9, n = 2; long long val = stirlingNumber(r, n); if (val == -1) cout << \" No stirling number\"; else cout << \"The Stirling Number s(\" << r << \", \" << n << \") is : \" << val; return 0;}", "e": 28831, "s": 27215, "text": null }, { "code": "// Java program to implement// above approachimport java.io.*; class GFG{ // Calculating factorial of// an integer n.static long factorial(int n){ // Our base cases of factorial // 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number// of combination of r objects// out of n objects.static int nCr(int n, int r){ // r cant be more than n so // we'd like the program to // crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling// numbers. The base cases which were// discussed above are handled to stop// the recursive calls.static long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver Codepublic static void main (String[] args){ // Calculating the stirling number s(9, 2) int r = 9, n = 2; long val = stirlingNumber(r, n); if (val == -1) System.out.println(\" No stirling number\"); else System.out.println( \"The Stirling Number s(\" + r + \", \" + n + \") is : \" + val);}} // This Code is Contributed by anuj_67", "e": 30536, "s": 28831, "text": null }, { "code": "# Python 3 program to implement above approach # Function to compute the number of combination# of r objects out of n objects.# nCr(n, n) = 1, nCr(n, 0) = 1, and these are# the base cases. def nCr(n, r): if(n == r): return 1 if(r == 0): return 1 # nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r) # This function is used to calculate the# factorial of a number n.def factorial(n): res = 1 # 1 ! = 0 ! = 1 if(n <= 1): return res for i in range(1, n + 1): res *= i return res # Main function to calculate the Stirling numbers.# the base cases which were discussed above are# handled to stop the recursive call, n can't be# more than r, s(r, 0) = 0.# s(r, r) = 1. s(r, 1) = (r - 1)!.# s(r, r - 1) = nCr(r, 2)# else as we proved, s(r, n) = s(r - 1, n - 1)# + (r - 1) * s(r - 1, n) def stirlingNumber(r, n): if(r == n): return 1 if(n == 0): return 0 if(n == r -1): return nCr(r, 2) if(r - n == 1): return factorial(r - 1) return (stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n)) r, n = 9, 2 print(stirlingNumber(r, n))", "e": 31732, "s": 30536, "text": null }, { "code": "// C# program to implement// above approachusing System; class GFG{ // Calculating factorial of// an integer n.static long factorial(int n){ // Our base cases of factorial // 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; long res = 1; for (int i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number// of combination of r objects// out of n objects.static int nCr(int n, int r){ // r cant be more than n so // we'd like the program to // crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling// numbers. The base cases which were// discussed above are handled to stop// the recursive calls.static long stirlingNumber(int r, int n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver Codepublic static void Main (){ // Calculating the stirling // number s(9, 2) int r = 9, n = 2; long val = stirlingNumber(r, n); if (val == -1) Console.WriteLine(\" No stirling number\"); else Console.WriteLine( \"The Stirling Number s(\" + r + \", \" + n + \") is : \" + val);}} // This code is contributed by inder_verma..", "e": 33421, "s": 31732, "text": null }, { "code": "<?php// PHP program to implement above approach // Calculating factorial of an integer n.function factorial($n){ // Our base cases of factorial 0! = 1! = 1 if ($n == 0) return 1; // n can't be less than 0. if ($n < 0) return -1; $res = 1; for ($i = 2; $i < $n + 1; ++$i) $res *= $i; return $res;} // Function to compute the number of combination// of r objects out of n objects.function nCr($n, $r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if ($r > $n) return -1; if ($n == $r) return 1; if ($r == 0) return 1; // nCr($n, $r) = nCr($n - 1, $r - 1) + nCr($n - 1, $r) return nCr($n - 1, $r - 1) + nCr($n - 1, $r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.function stirlingNumber($r, $n){ // n can't be more than // r, s(r, 0) = 0. if ($n > $r) return -1; if ($n == 0) return 0; if ($r == $n) return 1; if ($n == 1) return factorial($r - 1); if ($r - $n == 1) return nCr($r, 2); else return stirlingNumber($r - 1, $n - 1) + ($r - 1) * stirlingNumber($r - 1, $n);} // Calculating the stirling number s(9, 2) $r = 9; $n = 2; $val = stirlingNumber($r, $n); if ($val == -1) echo \" No stirling number\"; else echo \"The Stirling Number s(\", $r ,\", \" , $n , \") is : \" , $val; // This code is contributed by ANKITRAI1?>", "e": 35026, "s": 33421, "text": null }, { "code": "<script>// js program to implement above approach // Calculating factorial of an integer n.function factorial( n){ // Our base cases of factorial 0! = 1! = 1 if (n == 0) return 1; // n can't be less than 0. if (n < 0) return -1; let res = 1; for (let i = 2; i < n + 1; ++i) res *= i; return res;} // Function to compute the number of combination// of r objects out of n objects.function nCr(n, r){ // r cant be more than n so we'd like the // program to crash if the user entered // wrong input. if (r > n) return -1; if (n == r) return 1; if (r == 0) return 1; // nCr(n, r) = nCr(n - 1, r - 1) + nCr(n - 1, r) return nCr(n - 1, r - 1) + nCr(n - 1, r);} // Function to calculate the Stirling numbers.// The base cases which were discussed above are handled// to stop the recursive calls.function stirlingNumber( r, n){ // n can't be more than // r, s(r, 0) = 0. if (n > r) return -1; if (n == 0) return 0; if (r == n) return 1; if (n == 1) return factorial(r - 1); if (r - n == 1) return nCr(r, 2); else return stirlingNumber(r - 1, n - 1) + (r - 1) * stirlingNumber(r - 1, n);} // Driver program// Calculating the stirling number s(9, 2) let r = 9, n = 2; let val = stirlingNumber(r, n); if (val == -1) document.write( \" No stirling number\"); else document.write( \"The Stirling Number s(\", r , \", \" , n , \") is : \" , val); </script>", "e": 36577, "s": 35026, "text": null }, { "code": null, "e": 36617, "s": 36577, "text": "The Stirling Number s(9, 2) is : 109584" }, { "code": null, "e": 36850, "s": 36619, "text": "Note: The above solution can be optimized by Dynamic Programming. Please refer, Bell Numbers (Number of ways to Partition a Set) for example.Please refer Stirling numbers of the first kind to read more about the Stirling numbers. " }, { "code": null, "e": 36855, "s": 36850, "text": "vt_m" }, { "code": null, "e": 36866, "s": 36855, "text": "inderDuMCA" }, { "code": null, "e": 36874, "s": 36866, "text": "ankthon" }, { "code": null, "e": 36890, "s": 36874, "text": "rohitsingh07052" }, { "code": null, "e": 36904, "s": 36890, "text": "Combinatorial" }, { "code": null, "e": 36924, "s": 36904, "text": "Dynamic Programming" }, { "code": null, "e": 36937, "s": 36924, "text": "Mathematical" }, { "code": null, "e": 36957, "s": 36937, "text": "Dynamic Programming" }, { "code": null, "e": 36970, "s": 36957, "text": "Mathematical" }, { "code": null, "e": 36984, "s": 36970, "text": "Combinatorial" }, { "code": null, "e": 37082, "s": 36984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37113, "s": 37082, "text": "Lexicographic rank of a string" }, { "code": null, "e": 37150, "s": 37113, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 37205, "s": 37150, "text": "Print all permutations in sorted (lexicographic) order" }, { "code": null, "e": 37290, "s": 37205, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 37347, "s": 37290, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 37376, "s": 37347, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 37408, "s": 37376, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 37439, "s": 37408, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 37473, "s": 37439, "text": "Longest Common Subsequence | DP-4" } ]
How to save password in android webview?
This example demonstrate about How to save password in android webview. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <WebView android:id = "@+id/web_view" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken web view to show facebook.com. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ProgressDialog; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading Data..."); progressDialog.setCancelable(false); WebView web_view = findViewById(R.id.web_view); web_view.requestFocus(); web_view.getSettings().setJavaScriptEnabled(true); web_view.getSettings().setSavePassword(true); web_view.loadUrl("https://touch.facebook.com/"); web_view.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); web_view.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { if (progress < 100) { progressDialog.show(); } if (progress = = 100) { progressDialog.dismiss(); } } }); } } Step 4 − Add the following code to AndroidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1134, "s": 1062, "text": "This example demonstrate about How to save password in android webview." }, { "code": null, "e": 1263, "s": 1134, "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": 1328, "s": 1263, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1895, "s": 1328, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1959, "s": 1895, "text": "In the above code, we have taken web view to show facebook.com." }, { "code": null, "e": 2016, "s": 1959, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3662, "s": 2016, "text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setSavePassword(true);\n web_view.loadUrl(\"https://touch.facebook.com/\");\n web_view.setWebViewClient(new WebViewClient() {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n });\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}" }, { "code": null, "e": 3717, "s": 3662, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 4494, "s": 3717, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4841, "s": 4494, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4881, "s": 4841, "text": "Click here to download the project code" } ]
Xamarin - Building the App GUI
TextView is a very important component of the Android widgets. It is primarily used for displaying texts on an Android screen. To create a textview, simply open main.axml and add the following code between the linear layout tags. <TextView android:text = "Hello I am a text View" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/textview1" /> A button is a control used to trigger an event when it is clicked. Under your Main.axml file, type the following code to create a button. <Button android:id = "@+id/MyButton" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "@string/Hello" /> Open Resources\Values\Strings.xml and type the following line of code in between <resources> tag. <string name="Hello">Click Me!</string> The above code provides the value of the button we created. Next, we open MainActivity.cs and create the action to be performed when the button is clicked. Type the following code under base.OnCreate (bundle) method. Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { button.Text = "You clicked me"; }; The above code displays “You Clicked Me” when a user clicks on the button. FindViewById<< --> This method finds the ID of a view that was identified. It searches for the id in the .axml layout file. A checkbox is used when one wants to select more than one option from a group of options. In this example, we are going to create a checkbox which on selected, displays a message that it has been checked, else it displays unchecked. To start with, we open Main.axml file in our project and type the following line of code to create a checkbox. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:background = "#d3d3d3" android:layout_width = "fill_parent" android:layout_height = "fill_parent"> <CheckBox android:text = "CheckBox" android:padding = "25dp" android:layout_width = "300dp" android:layout_height = "wrap_content" android:id = "@+id/checkBox1" android:textColor = "@android:color/black" android:background = "@android:color/holo_blue_dark" /> </LinearLayout> Next, go to MainActivity.cs to add the functionality code. CheckBox checkMe = FindViewById<CheckBox>(Resource.Id.checkBox1); checkMe.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { CheckBox check = (CheckBox)sender; if(check.Checked) { check.Text = "Checkbox has been checked"; } else { check.Text = "Checkbox has not been checked"; } }; From the above code, we first find the checkbox using findViewById. Next, we create a handler method for our checkbox and in our handler, we create an if else statement which displays a message depending on the outcome selected. CompoundButton.CheckedChangeEventArgs → This method fires an event when the checkbox state changes. A progress bar is a control that is used to show the progression of an operation. To add a progress bar, add the following line of code in Main.axml file. <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/progressBar1" /> Next, go to MainActivity.cs and set the value of the progress bar. ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1); pb.Progress = 35; In the above code, we have created a progress bar with a value of 35. This is an Android widget which allows a person to choose one from a set of options. In this section, we are going to create a radio group containing a list of cars which will retrieve a checked radio button. First, we add a radio group and a textview as shown in the following code − <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:background = "@android:color/darker_gray" android:layout_width = "fill_parent" android:layout_height = "fill_parent"> <TextView android:text = "What is your favourite Car" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/textView1" android:textColor = "@android:color/black" /> <RadioGroup android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/radioGroup1" android:backgroundTint = "#a52a2aff" android:background = "@android:color/holo_green_dark"> <RadioButton android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Ferrari" android:id = "@+id/radioFerrari" /> <RadioButton android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Mercedes" android:id = "@+id/radioMercedes" /> <RadioButton android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Lamborghini" android:id = "@+id/radioLamborghini" /> <RadioButton android:text = "Audi" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/radioAudi" /> </RadioGroup> </LinearLayout> To perform an action, when a radio button is clicked, we add an activity. Go to MainActivity.cs and create a new event handler as shown below. private void onClickRadioButton(object sender, EventArgs e) { RadioButton cars = (RadioButton)sender; Toast.MakeText(this, cars.Text, ToastLength.Short).Show (); } Toast.MakeText() → This is a view method used to display a message/output in a small pop up. At the bottom of the OnCreate() method just after SetContentView(), add the following piece of code. This will capture each of the radio buttons and add them to the event handler we created. RadioButton radio_Ferrari = FindViewById<RadioButton> (Resource.Id.radioFerrari); RadioButton radio_Mercedes = FindViewById<RadioButton> (Resource.Id.radioMercedes); RadioButton radio_Lambo = FindViewById<RadioButton> (Resource.Id.radioLamborghini); RadioButton radio_Audi = FindViewById<RadioButton> (Resource.Id.radioAudi); radio_Ferrari.Click += onClickRadioButton; radio_Mercedes.Click += onClickRadioButton; radio_Lambo.Click += onClickRadioButton; radio_Audi.Click += onClickRadioButton; Now, run your application. It should display the following screen as the output − Toggle button are used to alternate between two states, e.g., it can toggle between ON and OFF. Open Resources\layout\Main.axml and add the following lines of code to create a toggle button. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:background = "#d3d3d3" android:layout_width = "fill_parent" android:layout_height = "fill_parent"> <ToggleButton android:id = "@+id/togglebutton" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textOn = "Torch ON" android:textOff = "Torch OFF" android:textColor = "@android:color/black" /> </LinearLayout> We can add actions to the toggle bar when it is clicked. Open MainActivity.cs and add the following lines of code after the OnCreate() method class. ToggleButton togglebutton = FindViewById<ToggleButton> (Resource.Id.togglebutton); togglebutton.Click += (o, e) => { if (togglebutton.Checked) Toast.MakeText(this, "Torch is ON", ToastLength.Short).Show (); else Toast.MakeText(this, "Torch is OFF", ToastLength.Short).Show(); }; Now, when you run the App, it should display the following output − A Ratings Bar is a form element that is made up of stars which app users can use to rate things you have provided for them. In your Main.axml file, create a new rating bar with 5 stars. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:background = "#d3d3d3" android:layout_width = "fill_parent" android:layout_height = "fill_parent"> <RatingBar android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/ratingBar1" android:numStars = "5" android:stepSize = "1.0" /> </LinearLayout> On running the app, it should display the following output − This is a textview that shows full suggestions while a user is typing. We are going to create an autocomplete textview containing a list of people’s names and a button which on click will show us the selected name. Open Main.axml and write the following code. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:background = "#d3d3d3" android:layout_height = "fill_parent"> <TextView android:text = "Enter Name" android:textAppearance = "?android:attr/textAppearanceMedium" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:id = "@+id/textView1" android:padding = "5dp" android:textColor = "@android:color/black" /> <AutoCompleteTextView android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:id = "@+id/autoComplete1" android:textColor = "@android:color/black" /> <Button android:text = "Submit" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:id = "@+id/btn_Submit" android:background="@android:color/holo_green_dark" /> </LinearLayout> The above code generates a TextView for typing, AutoCompleteTextView for showing suggestions, and a button to display the names entered from the TextView. Go to MainActivity.cs to add the functionality. Create a new event handler method as shown below. protected void ClickedBtnSubmit(object sender, System.EventArgs e){ if (autoComplete1.Text != ""){ Toast.MakeText(this, "The Name Entered =" + autoComplete1.Text, ToastLength.Short).Show(); } else { Toast.MakeText(this, "Enter a Name!", ToastLength.Short).Show(); } } The created handler checks whether the autocomplete textview is empty. If it is not empty, then it displays the selected autocomplete text. Type the following code inside the OnCreate() class. autoComplete1 = FindViewById<AutoCompleteTextView>(Resource.Id.autoComplete1); btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit); var names = new string[] { "John", "Peter", "Jane", "Britney" }; ArrayAdapter adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, names); autoComplete1.Adapter = adapter; btn_Submit.Click += ClickedBtnSubmit; ArrayAdapter − This is a collection handler that reads data items from a list collection and returns them as a view or displays them on the screen. Now, when you run the application, it should display the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2091, "s": 1964, "text": "TextView is a very important component of the Android widgets. It is primarily used for displaying texts on an Android screen." }, { "code": null, "e": 2194, "s": 2091, "text": "To create a textview, simply open main.axml and add the following code between the linear layout tags." }, { "code": null, "e": 2371, "s": 2194, "text": "<TextView \n android:text = \"Hello I am a text View\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/textview1\" /> " }, { "code": null, "e": 2509, "s": 2371, "text": "A button is a control used to trigger an event when it is clicked. Under your Main.axml file, type the following code to create a button." }, { "code": null, "e": 2672, "s": 2509, "text": "<Button \n android:id = \"@+id/MyButton\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"wrap_content\" \n android:text = \"@string/Hello\" />" }, { "code": null, "e": 2770, "s": 2672, "text": "Open Resources\\Values\\Strings.xml and type the following line of code in between <resources> tag." }, { "code": null, "e": 2810, "s": 2770, "text": "<string name=\"Hello\">Click Me!</string>" }, { "code": null, "e": 3027, "s": 2810, "text": "The above code provides the value of the button we created. Next, we open MainActivity.cs and create the action to be performed when the button is clicked. Type the following code under base.OnCreate (bundle) method." }, { "code": null, "e": 3150, "s": 3027, "text": "Button button = FindViewById<Button>(Resource.Id.MyButton); \nbutton.Click += delegate { button.Text = \"You clicked me\"; };" }, { "code": null, "e": 3225, "s": 3150, "text": "The above code displays “You Clicked Me” when a user clicks on the button." }, { "code": null, "e": 3349, "s": 3225, "text": "FindViewById<< --> This method finds the ID of a view that was identified. It searches for the id in the .axml layout file." }, { "code": null, "e": 3582, "s": 3349, "text": "A checkbox is used when one wants to select more than one option from a group of options. In this example, we are going to create a checkbox which on selected, displays a message that it has been checked, else it displays unchecked." }, { "code": null, "e": 3693, "s": 3582, "text": "To start with, we open Main.axml file in our project and type the following line of code to create a checkbox." }, { "code": null, "e": 4299, "s": 3693, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:background = \"#d3d3d3\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <CheckBox \n android:text = \"CheckBox\" \n android:padding = \"25dp\" \n android:layout_width = \"300dp\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/checkBox1\" \n android:textColor = \"@android:color/black\" \n android:background = \"@android:color/holo_blue_dark\" /> \n</LinearLayout> " }, { "code": null, "e": 4358, "s": 4299, "text": "Next, go to MainActivity.cs to add the functionality code." }, { "code": null, "e": 4700, "s": 4358, "text": "CheckBox checkMe = FindViewById<CheckBox>(Resource.Id.checkBox1); \ncheckMe.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { \n CheckBox check = (CheckBox)sender; \n if(check.Checked) { \n check.Text = \"Checkbox has been checked\"; \n } else { \n check.Text = \"Checkbox has not been checked\"; \n } \n};" }, { "code": null, "e": 4929, "s": 4700, "text": "From the above code, we first find the checkbox using findViewById. Next, we create a handler method for our checkbox and in our handler, we create an if else statement which displays a message depending on the outcome selected." }, { "code": null, "e": 5029, "s": 4929, "text": "CompoundButton.CheckedChangeEventArgs → This method fires an event when the checkbox state changes." }, { "code": null, "e": 5184, "s": 5029, "text": "A progress bar is a control that is used to show the progression of an operation. To add a progress bar, add the following line of code in Main.axml file." }, { "code": null, "e": 5375, "s": 5184, "text": "<ProgressBar \n style=\"?android:attr/progressBarStyleHorizontal\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/progressBar1\" />" }, { "code": null, "e": 5442, "s": 5375, "text": "Next, go to MainActivity.cs and set the value of the progress bar." }, { "code": null, "e": 5531, "s": 5442, "text": "ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1); \npb.Progress = 35;" }, { "code": null, "e": 5601, "s": 5531, "text": "In the above code, we have created a progress bar with a value of 35." }, { "code": null, "e": 5810, "s": 5601, "text": "This is an Android widget which allows a person to choose one from a set of options. In this section, we are going to create a radio group containing a list of cars which will retrieve a checked radio button." }, { "code": null, "e": 5886, "s": 5810, "text": "First, we add a radio group and a textview as shown in the following code −" }, { "code": null, "e": 7461, "s": 5886, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:background = \"@android:color/darker_gray\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <TextView \n android:text = \"What is your favourite Car\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/textView1\" \n android:textColor = \"@android:color/black\" /> \n <RadioGroup \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/radioGroup1\" \n android:backgroundTint = \"#a52a2aff\" \n android:background = \"@android:color/holo_green_dark\"> \n <RadioButton \n android:layout_width = \"wrap_content\" \n android:layout_height = \"wrap_content\" \n android:text = \"Ferrari\" \n android:id = \"@+id/radioFerrari\" /> \n <RadioButton \n android:layout_width = \"wrap_content\" \n android:layout_height = \"wrap_content\" \n android:text = \"Mercedes\" \n android:id = \"@+id/radioMercedes\" /> \n <RadioButton \n android:layout_width = \"wrap_content\" \n android:layout_height = \"wrap_content\" \n android:text = \"Lamborghini\" \n android:id = \"@+id/radioLamborghini\" />\n <RadioButton \n android:text = \"Audi\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/radioAudi\" /> \n </RadioGroup> \n</LinearLayout> " }, { "code": null, "e": 7604, "s": 7461, "text": "To perform an action, when a radio button is clicked, we add an activity. Go to MainActivity.cs and create a new event handler as shown below." }, { "code": null, "e": 7782, "s": 7604, "text": "private void onClickRadioButton(object sender, EventArgs e) { \n RadioButton cars = (RadioButton)sender; \n Toast.MakeText(this, cars.Text, ToastLength.Short).Show \n (); \n} " }, { "code": null, "e": 8066, "s": 7782, "text": "Toast.MakeText() → This is a view method used to display a message/output in a small pop up. At the bottom of the OnCreate() method just after SetContentView(), add the following piece of code. This will capture each of the radio buttons and add them to the event handler we created." }, { "code": null, "e": 8605, "s": 8066, "text": "RadioButton radio_Ferrari = FindViewById<RadioButton> \n (Resource.Id.radioFerrari); \n RadioButton radio_Mercedes = FindViewById<RadioButton> \n (Resource.Id.radioMercedes); \n RadioButton radio_Lambo = FindViewById<RadioButton> \n (Resource.Id.radioLamborghini); \n RadioButton radio_Audi = FindViewById<RadioButton> \n (Resource.Id.radioAudi); \n radio_Ferrari.Click += onClickRadioButton; \n radio_Mercedes.Click += onClickRadioButton; \n radio_Lambo.Click += onClickRadioButton; \n radio_Audi.Click += onClickRadioButton; " }, { "code": null, "e": 8687, "s": 8605, "text": "Now, run your application. It should display the following screen as the output −" }, { "code": null, "e": 8878, "s": 8687, "text": "Toggle button are used to alternate between two states, e.g., it can toggle between ON and OFF. Open Resources\\layout\\Main.axml and add the following lines of code to create a toggle button." }, { "code": null, "e": 9444, "s": 8878, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:background = \"#d3d3d3\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <ToggleButton \n android:id = \"@+id/togglebutton\" \n android:layout_width = \"wrap_content\" \n android:layout_height = \"wrap_content\" \n android:textOn = \"Torch ON\" \n android:textOff = \"Torch OFF\" \n android:textColor = \"@android:color/black\" /> \n</LinearLayout>" }, { "code": null, "e": 9593, "s": 9444, "text": "We can add actions to the toggle bar when it is clicked. Open MainActivity.cs and add the following lines of code after the OnCreate() method class." }, { "code": null, "e": 9904, "s": 9593, "text": "ToggleButton togglebutton = FindViewById<ToggleButton> (Resource.Id.togglebutton); \ntogglebutton.Click += (o, e) => { \n if (togglebutton.Checked) \n Toast.MakeText(this, \"Torch is ON\", ToastLength.Short).Show (); \n else \n Toast.MakeText(this, \"Torch is OFF\", \n ToastLength.Short).Show(); \n}; " }, { "code": null, "e": 9972, "s": 9904, "text": "Now, when you run the App, it should display the following output −" }, { "code": null, "e": 10158, "s": 9972, "text": "A Ratings Bar is a form element that is made up of stars which app users can use to rate things you have provided for them. In your Main.axml file, create a new rating bar with 5 stars." }, { "code": null, "e": 10660, "s": 10158, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:background = \"#d3d3d3\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <RatingBar \n android:layout_width = \"wrap_content\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/ratingBar1\" \n android:numStars = \"5\" \n android:stepSize = \"1.0\" /> \n</LinearLayout> " }, { "code": null, "e": 10721, "s": 10660, "text": "On running the app, it should display the following output −" }, { "code": null, "e": 10936, "s": 10721, "text": "This is a textview that shows full suggestions while a user is typing. We are going to create an autocomplete textview containing a list of people’s names and a button which on click will show us the selected name." }, { "code": null, "e": 10981, "s": 10936, "text": "Open Main.axml and write the following code." }, { "code": null, "e": 12045, "s": 10981, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:layout_width = \"fill_parent\" \n android:background = \"#d3d3d3\" \n android:layout_height = \"fill_parent\"> \n <TextView \n android:text = \"Enter Name\" \n android:textAppearance = \"?android:attr/textAppearanceMedium\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/textView1\" \n android:padding = \"5dp\" \n android:textColor = \"@android:color/black\" /> \n <AutoCompleteTextView \n android:layout_width = \"fill_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/autoComplete1\" \n android:textColor = \"@android:color/black\" /> \n <Button \n android:text = \"Submit\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/btn_Submit\" \n android:background=\"@android:color/holo_green_dark\" /> \n</LinearLayout>" }, { "code": null, "e": 12248, "s": 12045, "text": "The above code generates a TextView for typing, AutoCompleteTextView for showing suggestions, and a button to display the names entered from the TextView. Go to MainActivity.cs to add the functionality." }, { "code": null, "e": 12298, "s": 12248, "text": "Create a new event handler method as shown below." }, { "code": null, "e": 12604, "s": 12298, "text": "protected void ClickedBtnSubmit(object sender, System.EventArgs e){ \n if (autoComplete1.Text != \"\"){ \n Toast.MakeText(this, \"The Name Entered =\" \n + autoComplete1.Text, ToastLength.Short).Show(); \n } else { \n Toast.MakeText(this, \"Enter a Name!\", ToastLength.Short).Show(); \n } \n} " }, { "code": null, "e": 12797, "s": 12604, "text": "The created handler checks whether the autocomplete textview is empty. If it is not empty, then it displays the selected autocomplete text. Type the following code inside the OnCreate() class." }, { "code": null, "e": 13197, "s": 12797, "text": "autoComplete1 = FindViewById<AutoCompleteTextView>(Resource.Id.autoComplete1); \nbtn_Submit = FindViewById<Button>(Resource.Id.btn_Submit); \nvar names = new string[] { \"John\", \"Peter\", \"Jane\", \"Britney\" }; \nArrayAdapter adapter = new ArrayAdapter<string>(this, \n Android.Resource.Layout.SimpleSpinnerItem, names); \nautoComplete1.Adapter = adapter; \nbtn_Submit.Click += ClickedBtnSubmit; " }, { "code": null, "e": 13345, "s": 13197, "text": "ArrayAdapter − This is a collection handler that reads data items from a list collection and returns them as a view or displays them on the screen." }, { "code": null, "e": 13420, "s": 13345, "text": "Now, when you run the application, it should display the following output." }, { "code": null, "e": 13427, "s": 13420, "text": " Print" }, { "code": null, "e": 13438, "s": 13427, "text": " Add Notes" } ]
Foundation - Label Positioning
You can place your labels to the left or right of your inputs. You can place your labels to the left or right of your inputs. To place label on right, use .text-right or .float-right class. To place label on right, use .text-right or .float-right class. To place label on left, use .text-left or .float-left class. To place label on left, use .text-left or .float-left class. You can add .middle class to align the label vertically middle with its input. You can add .middle class to align the label vertically middle with its input. The following example demonstrates the use of label positioning in Foundation. <html> <head> <title>Form Label Positioning</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous"> <!-- Compressed JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script> </head> <body> <form> <div class = "row"> <div class = "small-6 columns"> <label for = "right-label" class = "text-right">Label</label> </div> <div class = "small-6 columns"> <input type = "text" id = "right-label" placeholder = "Right aligned"> </div> </div> <div class = "row"> <div class = "small-6 columns"> <label for = "left-label" class = "text-left">Label</label> </div> <div class = "small-6 columns"> <input type = "text" id = "left-label" placeholder = "Left aligned"> </div> </div> <div class = "row"> <div class = "small-6 columns"> <label for = "middle-label" class = "text-right middle">Label</label> </div> <div class = "small-6 columns"> <input type = "text" id = "middle-label" placeholder = "Right and middle aligned text input"> </div> </div> </form> <script> $(document).ready(function() { $(document).foundation(); }) </script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given html code form_label_positioning.html file. Save the above given html code form_label_positioning.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. 117 Lectures 5.5 hours Shakthi Swaroop 61 Lectures 1.5 hours Hans Weemaes 17 Lectures 4 hours Stephen Kahuria 8 Lectures 50 mins Zenva 28 Lectures 2 hours Sandra L 16 Lectures 2.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2301, "s": 2238, "text": "You can place your labels to the left or right of your inputs." }, { "code": null, "e": 2364, "s": 2301, "text": "You can place your labels to the left or right of your inputs." }, { "code": null, "e": 2428, "s": 2364, "text": "To place label on right, use .text-right or .float-right class." }, { "code": null, "e": 2492, "s": 2428, "text": "To place label on right, use .text-right or .float-right class." }, { "code": null, "e": 2553, "s": 2492, "text": "To place label on left, use .text-left or .float-left class." }, { "code": null, "e": 2614, "s": 2553, "text": "To place label on left, use .text-left or .float-left class." }, { "code": null, "e": 2693, "s": 2614, "text": "You can add .middle class to align the label vertically middle with its input." }, { "code": null, "e": 2772, "s": 2693, "text": "You can add .middle class to align the label vertically middle with its input." }, { "code": null, "e": 2851, "s": 2772, "text": "The following example demonstrates the use of label positioning in Foundation." }, { "code": null, "e": 5029, "s": 2851, "text": "<html>\n <head>\n <title>Form Label Positioning</title>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n\n </head>\n\n <body>\n <form>\n <div class = \"row\">\n <div class = \"small-6 columns\">\n <label for = \"right-label\" class = \"text-right\">Label</label>\n </div>\n\n <div class = \"small-6 columns\">\n <input type = \"text\" id = \"right-label\" placeholder = \"Right aligned\">\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-6 columns\">\n <label for = \"left-label\" class = \"text-left\">Label</label>\n </div>\n\n <div class = \"small-6 columns\">\n <input type = \"text\" id = \"left-label\" placeholder = \"Left aligned\">\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-6 columns\">\n <label for = \"middle-label\" class = \"text-right middle\">Label</label>\n </div>\n\n <div class = \"small-6 columns\">\n <input type = \"text\" id = \"middle-label\" placeholder = \"Right and middle aligned text input\">\n </div>\n </div>\n </form>\n\n \n <script>\n $(document).ready(function() {\n $(document).foundation();\n })\n </script>\n </body>\n</html>" }, { "code": null, "e": 5106, "s": 5029, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 5171, "s": 5106, "text": "Save the above given html code form_label_positioning.html file." }, { "code": null, "e": 5236, "s": 5171, "text": "Save the above given html code form_label_positioning.html file." }, { "code": null, "e": 5309, "s": 5236, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 5382, "s": 5309, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 5418, "s": 5382, "text": "\n 117 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5435, "s": 5418, "text": " Shakthi Swaroop" }, { "code": null, "e": 5470, "s": 5435, "text": "\n 61 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5484, "s": 5470, "text": " Hans Weemaes" }, { "code": null, "e": 5517, "s": 5484, "text": "\n 17 Lectures \n 4 hours \n" }, { "code": null, "e": 5534, "s": 5517, "text": " Stephen Kahuria" }, { "code": null, "e": 5565, "s": 5534, "text": "\n 8 Lectures \n 50 mins\n" }, { "code": null, "e": 5572, "s": 5565, "text": " Zenva" }, { "code": null, "e": 5605, "s": 5572, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 5615, "s": 5605, "text": " Sandra L" }, { "code": null, "e": 5650, "s": 5615, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5667, "s": 5650, "text": " GreyCampus Inc." }, { "code": null, "e": 5674, "s": 5667, "text": " Print" }, { "code": null, "e": 5685, "s": 5674, "text": " Add Notes" } ]
How can we implement different borders using the BorderFactory in Java?
The BorderFactory is a Factory class which provides different types of borders in Java. BevelBorder: This border draws raised or lowered beveled edges. EmptyBorder: It doesn’t do any drawing, but does take up space. EtchedBorder: A Lowered etched border gives an appearance of a rectangle and a Raised etched border looks like a surface of the screen. LineBorder: Draws a simple rectangle around a component. We can specify the color and width of the line in the LineBorder constructor. MatteBorder: We can create a MatteBorder with a certain color and specify the size of the border on the left, top, right, and bottom of the component. A MatteBorder also allows us to pass an Icon that will be used to draw the border. This can be an image (ImageIcon) or any other implementation of the Icon interface. TitledBorder: A regular border with a title. A TitledBorder doesn’t actually draw a border; it just draws a title in conjunction with another border object. This border type is particularly useful for grouping different sets of controls in a complicated interface. Component Border: A border that contains two other borders. This is especially handy if we want to enclose a component in an EmptyBorder and then put something decorative around it, such as an EtchedBorder or a MatteBorder. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class BorderFactoryMain { public static void main(String[] args) { SwingUtilities.invokeLater(run); } static Runnable run = new Runnable() { @Override public void run() { BorderFactoryTest test; test = new BorderFactoryTest(); test.setVisible(true); } }; public static class BorderFactoryTest extends JFrame { public BorderFactoryTest() { setTitle("BorderFactory Test"); setSize(350, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(createBorderedPanel(BorderFactory.createRaisedBevelBorder(), "createRaisedBevelBorder()")); add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.LOWERED), "createBevelBorder(BevelBorder.LOWERED)")); add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.RAISED), "createBevelBorder(BevelBorder.RAISED)")); add(createBorderedPanel(BorderFactory.createCompoundBorder(BorderFactory. createBevelBorder(BevelBorder.RAISED),BorderFactory.createBevelBorder(BevelBorder.LOWERED)), "createCompoundBorder(RAISED, LOWERED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(), "createEtchedBorder()")); add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "createEtchedBorder(EtchedBorder.LOWERED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "createEtchedBorder(EtchedBorder.RAISED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(Color.lightGray, Color.yellow), "createEtchedBorder(Color.lightGray, Color.yellow)")); add(createBorderedPanel(BorderFactory.createLineBorder(Color.red), "createLineBorder(Color.red)")); add(createBorderedPanel(BorderFactory.createLineBorder(Color.blue, 5), "createLineBorder(Color.blue, 5)")); add(createBorderedPanel(BorderFactory.createDashedBorder(null), "createDashedBorder(null)")); setLocationRelativeTo(null); } } private static JPanel createBorderedPanel(Border b, String name) { JLabel label = new JLabel(name); JPanel panel = new JPanel(); panel.setBorder(b); panel.add(label); return panel; } }
[ { "code": null, "e": 1150, "s": 1062, "text": "The BorderFactory is a Factory class which provides different types of borders in Java." }, { "code": null, "e": 1214, "s": 1150, "text": "BevelBorder: This border draws raised or lowered beveled edges." }, { "code": null, "e": 1279, "s": 1214, "text": "EmptyBorder: It doesn’t do any drawing, but does take up space." }, { "code": null, "e": 1415, "s": 1279, "text": "EtchedBorder: A Lowered etched border gives an appearance of a rectangle and a Raised etched border looks like a surface of the screen." }, { "code": null, "e": 1550, "s": 1415, "text": "LineBorder: Draws a simple rectangle around a component. We can specify the color and width of the line in the LineBorder constructor." }, { "code": null, "e": 1868, "s": 1550, "text": "MatteBorder: We can create a MatteBorder with a certain color and specify the size of the border on the left, top, right, and bottom of the component. A MatteBorder also allows us to pass an Icon that will be used to draw the border. This can be an image (ImageIcon) or any other implementation of the Icon interface." }, { "code": null, "e": 2133, "s": 1868, "text": "TitledBorder: A regular border with a title. A TitledBorder doesn’t actually draw a border; it just draws a title in conjunction with another border object. This border type is particularly useful for grouping different sets of controls in a complicated interface." }, { "code": null, "e": 2357, "s": 2133, "text": "Component Border: A border that contains two other borders. This is especially handy if we want to enclose a component in an EmptyBorder and then put something decorative around it, such as an EtchedBorder or a MatteBorder." }, { "code": null, "e": 4765, "s": 2357, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.border.*;\npublic class BorderFactoryMain {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(run);\n }\n static Runnable run = new Runnable() {\n @Override\n public void run() {\n BorderFactoryTest test;\n test = new BorderFactoryTest();\n test.setVisible(true);\n }\n };\n public static class BorderFactoryTest extends JFrame {\n public BorderFactoryTest() {\n setTitle(\"BorderFactory Test\");\n setSize(350, 400);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLayout(new FlowLayout());\n add(createBorderedPanel(BorderFactory.createRaisedBevelBorder(), \"createRaisedBevelBorder()\"));\n add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.LOWERED), \"createBevelBorder(BevelBorder.LOWERED)\"));\n add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.RAISED), \"createBevelBorder(BevelBorder.RAISED)\"));\n add(createBorderedPanel(BorderFactory.createCompoundBorder(BorderFactory.\n createBevelBorder(BevelBorder.RAISED),BorderFactory.createBevelBorder(BevelBorder.LOWERED)),\n \"createCompoundBorder(RAISED, LOWERED)\"));\n add(createBorderedPanel(BorderFactory.createEtchedBorder(), \"createEtchedBorder()\"));\n add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), \"createEtchedBorder(EtchedBorder.LOWERED)\"));\n add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.RAISED), \"createEtchedBorder(EtchedBorder.RAISED)\"));\n add(createBorderedPanel(BorderFactory.createEtchedBorder(Color.lightGray, Color.yellow), \"createEtchedBorder(Color.lightGray, Color.yellow)\"));\n add(createBorderedPanel(BorderFactory.createLineBorder(Color.red), \"createLineBorder(Color.red)\"));\n add(createBorderedPanel(BorderFactory.createLineBorder(Color.blue, 5), \"createLineBorder(Color.blue, 5)\"));\n add(createBorderedPanel(BorderFactory.createDashedBorder(null), \"createDashedBorder(null)\"));\n setLocationRelativeTo(null);\n }\n }\n private static JPanel createBorderedPanel(Border b, String name) {\n JLabel label = new JLabel(name);\n JPanel panel = new JPanel();\n panel.setBorder(b);\n panel.add(label);\n return panel;\n }\n}" } ]
Difference Between Abstract Class and Abstract Method in Java - GeeksforGeeks
17 Jun, 2021 Abstract is the modifier applicable only for methods and classes but not for variables. Even though we don’t have implementation still we can declare a method with an abstract modifier. That is abstract methods have only declaration but not implementation. Hence, abstract method declaration should compulsory ends with semicolons. Illustration: public abstract void methodOne(); ------>valid public abstract void methodOne(){} ------->Invalid Example: Java // Java Program to illustrate Abstract class // Abstract Class// Main classabstract class GFG { // Main driver method public static void main(String args[]) { // Creating object of class inside main() method GFG gfg = new GFG(); }} Output: Output explanation: If a class contains at least one abstract method then compulsory the corresponding class should be declared with an abstract modifier. Because implementation is not complete and hence we can’t create objects of that class. Even though the class doesn’t contain any abstract methods still we can declare the class as abstract which is an abstract class that can contain zero no of abstract methods also. Illustration 1: class Parent { // Method of this class public void methodOne(); } Output: Compile time error. missing method body, or declared abstract public void methodOne(); Illustration 2: class parent { // Method of this class public abstract void methodOne() {} } Output: Compile time error. abstract method cannot have a body. public abstract void methodOne(){} Illustration 3: class parent { // Method of this class public abstract void methodOne(); } Output: Compile time error. Parent is not abstract and does not override abstract method methodOne() in Parent class Parent If a class extends any abstract class then compulsory we should provide implementation for every abstract method of the parent class otherwise we have to declare child class as abstract. Example: Java // Java Program to Illustrate Abstract Method // Main class// Abstract classabstract class Parent { // Methods of abstract parent class public abstract void methodOne(); public abstract void methodTwo();} // Class 2// Child classclass child extends Parent { // Method of abstract child class public void methodOne() {}} Output: Note: If we declare the child as abstract then the code compiles fine, but the child of a child is responsible to provide an implementation for methodTwo(). Now let us finally conclude out the differences between them after having an adequate understanding of both of them. Similar to interfaces, but can Implement methods Fields can have various access modifiers Subclasses can only extend one abstract class Difference Between Java Java 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 Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 26213, "s": 26185, "text": "\n17 Jun, 2021" }, { "code": null, "e": 26546, "s": 26213, "text": "Abstract is the modifier applicable only for methods and classes but not for variables. Even though we don’t have implementation still we can declare a method with an abstract modifier. That is abstract methods have only declaration but not implementation. Hence, abstract method declaration should compulsory ends with semicolons. " }, { "code": null, "e": 26561, "s": 26546, "text": "Illustration: " }, { "code": null, "e": 26659, "s": 26561, "text": "public abstract void methodOne(); ------>valid\npublic abstract void methodOne(){} ------->Invalid" }, { "code": null, "e": 26670, "s": 26659, "text": "Example: " }, { "code": null, "e": 26675, "s": 26670, "text": "Java" }, { "code": "// Java Program to illustrate Abstract class // Abstract Class// Main classabstract class GFG { // Main driver method public static void main(String args[]) { // Creating object of class inside main() method GFG gfg = new GFG(); }}", "e": 26938, "s": 26675, "text": null }, { "code": null, "e": 26946, "s": 26938, "text": "Output:" }, { "code": null, "e": 26966, "s": 26946, "text": "Output explanation:" }, { "code": null, "e": 27190, "s": 26966, "text": "If a class contains at least one abstract method then compulsory the corresponding class should be declared with an abstract modifier. Because implementation is not complete and hence we can’t create objects of that class. " }, { "code": null, "e": 27370, "s": 27190, "text": "Even though the class doesn’t contain any abstract methods still we can declare the class as abstract which is an abstract class that can contain zero no of abstract methods also." }, { "code": null, "e": 27387, "s": 27370, "text": "Illustration 1: " }, { "code": null, "e": 27459, "s": 27387, "text": "class Parent \n{ // Method of this class \n public void methodOne();\n}" }, { "code": null, "e": 27468, "s": 27459, "text": "Output: " }, { "code": null, "e": 27555, "s": 27468, "text": "Compile time error.\nmissing method body, or declared abstract\npublic void methodOne();" }, { "code": null, "e": 27571, "s": 27555, "text": "Illustration 2:" }, { "code": null, "e": 27654, "s": 27571, "text": "class parent {\n // Method of this class\n public abstract void methodOne() {}\n}" }, { "code": null, "e": 27663, "s": 27654, "text": "Output: " }, { "code": null, "e": 27754, "s": 27663, "text": "Compile time error.\nabstract method cannot have a body.\npublic abstract void methodOne(){}" }, { "code": null, "e": 27771, "s": 27754, "text": " Illustration 3:" }, { "code": null, "e": 27853, "s": 27771, "text": "class parent {\n\n // Method of this class\n public abstract void methodOne();\n}" }, { "code": null, "e": 27862, "s": 27853, "text": "Output: " }, { "code": null, "e": 27978, "s": 27862, "text": "Compile time error.\nParent is not abstract and does not override abstract method methodOne() in Parent class\nParent" }, { "code": null, "e": 28166, "s": 27978, "text": "If a class extends any abstract class then compulsory we should provide implementation for every abstract method of the parent class otherwise we have to declare child class as abstract. " }, { "code": null, "e": 28176, "s": 28166, "text": "Example: " }, { "code": null, "e": 28181, "s": 28176, "text": "Java" }, { "code": "// Java Program to Illustrate Abstract Method // Main class// Abstract classabstract class Parent { // Methods of abstract parent class public abstract void methodOne(); public abstract void methodTwo();} // Class 2// Child classclass child extends Parent { // Method of abstract child class public void methodOne() {}}", "e": 28522, "s": 28181, "text": null }, { "code": null, "e": 28531, "s": 28522, "text": "Output: " }, { "code": null, "e": 28689, "s": 28531, "text": "Note: If we declare the child as abstract then the code compiles fine, but the child of a child is responsible to provide an implementation for methodTwo(). " }, { "code": null, "e": 28806, "s": 28689, "text": "Now let us finally conclude out the differences between them after having an adequate understanding of both of them." }, { "code": null, "e": 28838, "s": 28806, "text": "Similar to interfaces, but can " }, { "code": null, "e": 28856, "s": 28838, "text": "Implement methods" }, { "code": null, "e": 28897, "s": 28856, "text": "Fields can have various access modifiers" }, { "code": null, "e": 28943, "s": 28897, "text": "Subclasses can only extend one abstract class" }, { "code": null, "e": 28962, "s": 28943, "text": "Difference Between" }, { "code": null, "e": 28967, "s": 28962, "text": "Java" }, { "code": null, "e": 28972, "s": 28967, "text": "Java" }, { "code": null, "e": 29070, "s": 28972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29131, "s": 29070, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29199, "s": 29131, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 29257, "s": 29199, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29312, "s": 29257, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 29378, "s": 29312, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 29393, "s": 29378, "text": "Arrays in Java" }, { "code": null, "e": 29437, "s": 29393, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29459, "s": 29437, "text": "For-each loop in Java" }, { "code": null, "e": 29510, "s": 29459, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Deep Learning with Tensorflow: Part 3 — Music and text generation | by Matteo Kofler | Towards Data Science
Hi everybody, welcome back to my Tenserflow series, this is part 3. I already described the logic and functionality of neural networks and Tenserflow in the first part as well as I showed you how to perform a image classification in the second part. In this part, I’ll give you a overview on Tensorflow applications as well as I’ll show you how to generate music and text. Tensorflow allows us to build complex applications. While processing multiple input sources, almost everything can be implemented with Tensorflow, even Tesla’s autopilot could be made with it. To obtain a better overview on the possibilities of Tensorflow, i have collected a short summary of examples that people have already made with it: Processing text: spam filters, automated answers on emails, chatbots, sports predictions Processing images: automated cancer detection, street detection Processing audio and speech: sound generation, speech recognition Next up, I’ll explain music generation and text generation in more detail. We’ll start looking at music generation, the possibilities of generating music today and we’ll write our own pop music generator. Later we’ll look at text generation, at a concret example and on building our own poem generator. Let’s do it. Dear songwriters, I am sorry to tell you, but you will be replaced by machine learning algorithms within the next years. Why? Because music can be generated by computers now. Imagine the power such a tool has. Compared to the time, to the hundreds of hours necessary to compose a song, clicking start in a program is like nothing. I guess that might sound a little bit strange for some people, considering the fact that music is often referred to as “emotional” and something “to feel”, not something “factual” or “mathematical”, but machine learning makes it possible. But how would it work? So, let’s say you wanted to make a specific song, a “happy” and “funny” song. The first step would be to get a data set of songs, labeled with emotions. The program would convert the speech of the set to text. For each word, the program would create vectors and train the model. After completing the training, the program would find the associated vectors of your input (“happy” and “funny”) and compare them to the vectors that has been created before. The output would be a set of chords representing the emotions you wanted. Magenta is currently state of the art when it comes to music generation with machine learning, but listen for youself. It’s a project from the Google Brain team that asks: Can we use machine learning to create compelling art and music? Built on top of TensorFlow, Magenta uses a CNN system. Although Magenta is very powerful, we’ll build our own simple music generator using a Restricted Boltzmann Machine (RBM) to generate short sequences of pop music. We’ll receive multiple files, if you link them together it’ll sound like this: Our training data will be around a hundred MIDI files of pop songs (MIDI is a format that directly encodes musical notes). To keep it simple, we won’t label them with emotions as described in the introduction, our output will be another pop melody, just like our training files. RBM is a neural network with two layers, the visible layer and the hidden layer. Each visible node is connected to each hidden node (and vice versa), but there are no visible-visible or hidden-hidden connections (nodes are simply where calculations take place). This is the restriction. Each visible node takes one chord. Each chord is multiplied by a weight and then the node’s output at the hidden layer. Unlike most of the neural networks, RBMs are generative models that directly model the probability distribution of data. To sample from an RBM, we perform an algorithm known as Gibbs sampling. If you want to learn more about RBM’s, go this way. Enough theoretical talk, let’s start building by cloning my repo from GitHub. Open up a terminal and type: git clone https://github.com/koflerm/tensorflow-music-generator.git Next, we’ll have to install a few libraries: pip3 install pandaspip3 install msgpack-pythonpip3 install glob2pip3 install tqdmpip3 install py-midi We’ll use them as follows: Panda as our data analytics library Midi as our helper library for the music files TQDM for printing a progress bar during the process. The songs are stored in the Pop_Music_Midi folder. You could also use your own training data, but the songs have to be in the MIDI format(!). Find some here. Basically, that’s the preparation, you can now execute the program. To run the script, simply write: python rbm_chords.py Training will take 5–10 minutes. The output will be a collection of MIDI files in the out folder, each about ten seconds long. You could also write a script to link them together, if you wanted to hear just “one song”. That’s it, you have successfully created music. If you didn’t understand everything I wrote (i’m sorry...), I would highly recommend you to read respectively listen to this two postings: https://www.youtube.com/watch?v=ZE7qWXX05T0&feature=youtu.be http://danshiebler.com/2016-08-10-musical-tensorflow-part-one-the-rbm/ As explained earlier, songwriters could be replaced by algorithms in near future. Well, this also applies to poets. We’ll write a program that generates a poem based on the plays of William Shakespeare. The training data (the poems) are stored as text-files, the filename is also the label. But to start off, I’ll show you another example of text generation using Tensorflow. Replying to emails on mobiles is a real pain, even for short replies. That’s why Google implemented Smart Replies in its Inbox app. They wanted to build a system that could automatically determine if an email was answerable with a short reply (text recognition), and compose a few suitable responses for it (text generation). They needed to build a machine learning system, because imagine using a system that depends on hand-crafted rules for common reply scenarios for a second. Any engineer’s ability to invent “rules” would be quickly outstripped by the huge diversity of writing styles. A machine learned system, by contrast, captures diverse situations by itself. It generalizes and handles new inputs way better than rule-based systems ever could. Google choose to build the Smart Reply System on a pair of recurrent neural networks (RNN), one used to encode the incoming email and one to predict possible responses. The encoding network takes the words of the incoming email one at a time, and produces a vector. This so called “thought vector” captures the core of what is being said without getting hung up on how it’s said (e.g. the vector for “Are you free tomorrow?” should be the same as the vector for “Does tomorrow work for you?”). The second network starts from this thought vector and makes a grammatically correct reply one word at a time, like it’s typing it out. The detailed operation of each network is entirely learned, just by training the model to predict likely responses. Interested in the Smart Reply System? Read a more detailed explanation here. It’s time to build our text generator on the works of William Shakespeare. We’ll use a Recurrent Neural Network for training our model. After training it, our script will generate a poem itself, which can be viewed in the terminal as well as in a textfile. First off, I know poems aren’t that interesting at all. But don’t worry, you can easily change the data set ;). Let’s dive into it. Start by cloning my repository from GitHub: git clone https://github.com/koflerm/tensorflow-shakespeare-poem-generator.git As you can see, there is a Shakespeare folder containing multiple poems. Simply put your own TXT files in there, if you want to change the topic. Now it’s time to train our language model. > python3 rnn_train.py This takes hours, so be careful! If you don’t have that much time, you can download the checkpoint files (the final model). You don’t have to train the model first! Simply extract the files into the checkpoints folder. Everything set up, time to generate some text. Type the following line: > python3 rnn_play.py The script rnn_play.py uses our trained checkpoint to generate a new “Shakespeare” play. You can see the output in the terminal as well as in the file output_generated.txt There it is, your own personal poem, written the Shakespeare way. Congratulations, you are now able to generate your own music as well as your own version of a Shakespeare play. In the next part, I’ll probably dig in a little bit deeper into image classification and object detection. So stay tuned till the next post! ___ Link to Part 4: https://medium.com/towards-data-science/deep-learning-with-tensorflow-part-4-face-classification-and-video-inputs-fa078f22c1e5
[ { "code": null, "e": 544, "s": 171, "text": "Hi everybody, welcome back to my Tenserflow series, this is part 3. I already described the logic and functionality of neural networks and Tenserflow in the first part as well as I showed you how to perform a image classification in the second part. In this part, I’ll give you a overview on Tensorflow applications as well as I’ll show you how to generate music and text." }, { "code": null, "e": 885, "s": 544, "text": "Tensorflow allows us to build complex applications. While processing multiple input sources, almost everything can be implemented with Tensorflow, even Tesla’s autopilot could be made with it. To obtain a better overview on the possibilities of Tensorflow, i have collected a short summary of examples that people have already made with it:" }, { "code": null, "e": 974, "s": 885, "text": "Processing text: spam filters, automated answers on emails, chatbots, sports predictions" }, { "code": null, "e": 1038, "s": 974, "text": "Processing images: automated cancer detection, street detection" }, { "code": null, "e": 1104, "s": 1038, "text": "Processing audio and speech: sound generation, speech recognition" }, { "code": null, "e": 1420, "s": 1104, "text": "Next up, I’ll explain music generation and text generation in more detail. We’ll start looking at music generation, the possibilities of generating music today and we’ll write our own pop music generator. Later we’ll look at text generation, at a concret example and on building our own poem generator. Let’s do it." }, { "code": null, "e": 1751, "s": 1420, "text": "Dear songwriters, I am sorry to tell you, but you will be replaced by machine learning algorithms within the next years. Why? Because music can be generated by computers now. Imagine the power such a tool has. Compared to the time, to the hundreds of hours necessary to compose a song, clicking start in a program is like nothing." }, { "code": null, "e": 2013, "s": 1751, "text": "I guess that might sound a little bit strange for some people, considering the fact that music is often referred to as “emotional” and something “to feel”, not something “factual” or “mathematical”, but machine learning makes it possible. But how would it work?" }, { "code": null, "e": 2541, "s": 2013, "text": "So, let’s say you wanted to make a specific song, a “happy” and “funny” song. The first step would be to get a data set of songs, labeled with emotions. The program would convert the speech of the set to text. For each word, the program would create vectors and train the model. After completing the training, the program would find the associated vectors of your input (“happy” and “funny”) and compare them to the vectors that has been created before. The output would be a set of chords representing the emotions you wanted." }, { "code": null, "e": 2832, "s": 2541, "text": "Magenta is currently state of the art when it comes to music generation with machine learning, but listen for youself. It’s a project from the Google Brain team that asks: Can we use machine learning to create compelling art and music? Built on top of TensorFlow, Magenta uses a CNN system." }, { "code": null, "e": 2995, "s": 2832, "text": "Although Magenta is very powerful, we’ll build our own simple music generator using a Restricted Boltzmann Machine (RBM) to generate short sequences of pop music." }, { "code": null, "e": 3074, "s": 2995, "text": "We’ll receive multiple files, if you link them together it’ll sound like this:" }, { "code": null, "e": 3353, "s": 3074, "text": "Our training data will be around a hundred MIDI files of pop songs (MIDI is a format that directly encodes musical notes). To keep it simple, we won’t label them with emotions as described in the introduction, our output will be another pop melody, just like our training files." }, { "code": null, "e": 4005, "s": 3353, "text": "RBM is a neural network with two layers, the visible layer and the hidden layer. Each visible node is connected to each hidden node (and vice versa), but there are no visible-visible or hidden-hidden connections (nodes are simply where calculations take place). This is the restriction. Each visible node takes one chord. Each chord is multiplied by a weight and then the node’s output at the hidden layer. Unlike most of the neural networks, RBMs are generative models that directly model the probability distribution of data. To sample from an RBM, we perform an algorithm known as Gibbs sampling. If you want to learn more about RBM’s, go this way." }, { "code": null, "e": 4112, "s": 4005, "text": "Enough theoretical talk, let’s start building by cloning my repo from GitHub. Open up a terminal and type:" }, { "code": null, "e": 4180, "s": 4112, "text": "git clone https://github.com/koflerm/tensorflow-music-generator.git" }, { "code": null, "e": 4225, "s": 4180, "text": "Next, we’ll have to install a few libraries:" }, { "code": null, "e": 4327, "s": 4225, "text": "pip3 install pandaspip3 install msgpack-pythonpip3 install glob2pip3 install tqdmpip3 install py-midi" }, { "code": null, "e": 4354, "s": 4327, "text": "We’ll use them as follows:" }, { "code": null, "e": 4390, "s": 4354, "text": "Panda as our data analytics library" }, { "code": null, "e": 4437, "s": 4390, "text": "Midi as our helper library for the music files" }, { "code": null, "e": 4490, "s": 4437, "text": "TQDM for printing a progress bar during the process." }, { "code": null, "e": 4648, "s": 4490, "text": "The songs are stored in the Pop_Music_Midi folder. You could also use your own training data, but the songs have to be in the MIDI format(!). Find some here." }, { "code": null, "e": 4749, "s": 4648, "text": "Basically, that’s the preparation, you can now execute the program. To run the script, simply write:" }, { "code": null, "e": 4770, "s": 4749, "text": "python rbm_chords.py" }, { "code": null, "e": 4989, "s": 4770, "text": "Training will take 5–10 minutes. The output will be a collection of MIDI files in the out folder, each about ten seconds long. You could also write a script to link them together, if you wanted to hear just “one song”." }, { "code": null, "e": 5176, "s": 4989, "text": "That’s it, you have successfully created music. If you didn’t understand everything I wrote (i’m sorry...), I would highly recommend you to read respectively listen to this two postings:" }, { "code": null, "e": 5237, "s": 5176, "text": "https://www.youtube.com/watch?v=ZE7qWXX05T0&feature=youtu.be" }, { "code": null, "e": 5308, "s": 5237, "text": "http://danshiebler.com/2016-08-10-musical-tensorflow-part-one-the-rbm/" }, { "code": null, "e": 5684, "s": 5308, "text": "As explained earlier, songwriters could be replaced by algorithms in near future. Well, this also applies to poets. We’ll write a program that generates a poem based on the plays of William Shakespeare. The training data (the poems) are stored as text-files, the filename is also the label. But to start off, I’ll show you another example of text generation using Tensorflow." }, { "code": null, "e": 6010, "s": 5684, "text": "Replying to emails on mobiles is a real pain, even for short replies. That’s why Google implemented Smart Replies in its Inbox app. They wanted to build a system that could automatically determine if an email was answerable with a short reply (text recognition), and compose a few suitable responses for it (text generation)." }, { "code": null, "e": 6439, "s": 6010, "text": "They needed to build a machine learning system, because imagine using a system that depends on hand-crafted rules for common reply scenarios for a second. Any engineer’s ability to invent “rules” would be quickly outstripped by the huge diversity of writing styles. A machine learned system, by contrast, captures diverse situations by itself. It generalizes and handles new inputs way better than rule-based systems ever could." }, { "code": null, "e": 7185, "s": 6439, "text": "Google choose to build the Smart Reply System on a pair of recurrent neural networks (RNN), one used to encode the incoming email and one to predict possible responses. The encoding network takes the words of the incoming email one at a time, and produces a vector. This so called “thought vector” captures the core of what is being said without getting hung up on how it’s said (e.g. the vector for “Are you free tomorrow?” should be the same as the vector for “Does tomorrow work for you?”). The second network starts from this thought vector and makes a grammatically correct reply one word at a time, like it’s typing it out. The detailed operation of each network is entirely learned, just by training the model to predict likely responses." }, { "code": null, "e": 7262, "s": 7185, "text": "Interested in the Smart Reply System? Read a more detailed explanation here." }, { "code": null, "e": 7519, "s": 7262, "text": "It’s time to build our text generator on the works of William Shakespeare. We’ll use a Recurrent Neural Network for training our model. After training it, our script will generate a poem itself, which can be viewed in the terminal as well as in a textfile." }, { "code": null, "e": 7651, "s": 7519, "text": "First off, I know poems aren’t that interesting at all. But don’t worry, you can easily change the data set ;). Let’s dive into it." }, { "code": null, "e": 7695, "s": 7651, "text": "Start by cloning my repository from GitHub:" }, { "code": null, "e": 7774, "s": 7695, "text": "git clone https://github.com/koflerm/tensorflow-shakespeare-poem-generator.git" }, { "code": null, "e": 7920, "s": 7774, "text": "As you can see, there is a Shakespeare folder containing multiple poems. Simply put your own TXT files in there, if you want to change the topic." }, { "code": null, "e": 7963, "s": 7920, "text": "Now it’s time to train our language model." }, { "code": null, "e": 7986, "s": 7963, "text": "> python3 rnn_train.py" }, { "code": null, "e": 8205, "s": 7986, "text": "This takes hours, so be careful! If you don’t have that much time, you can download the checkpoint files (the final model). You don’t have to train the model first! Simply extract the files into the checkpoints folder." }, { "code": null, "e": 8277, "s": 8205, "text": "Everything set up, time to generate some text. Type the following line:" }, { "code": null, "e": 8299, "s": 8277, "text": "> python3 rnn_play.py" }, { "code": null, "e": 8471, "s": 8299, "text": "The script rnn_play.py uses our trained checkpoint to generate a new “Shakespeare” play. You can see the output in the terminal as well as in the file output_generated.txt" }, { "code": null, "e": 8537, "s": 8471, "text": "There it is, your own personal poem, written the Shakespeare way." }, { "code": null, "e": 8790, "s": 8537, "text": "Congratulations, you are now able to generate your own music as well as your own version of a Shakespeare play. In the next part, I’ll probably dig in a little bit deeper into image classification and object detection. So stay tuned till the next post!" }, { "code": null, "e": 8794, "s": 8790, "text": "___" } ]
How To Train Keras Models Using the Genetic Algorithm with PyGAD | by Ahmed Gad | Towards Data Science
PyGAD is an open-source Python library for building the genetic algorithm and training machine learning algorithms. It offers a wide range of parameters to customize the genetic algorithm to work with different types of problems. PyGAD has its own modules that support building and training neural networks (NNs) and convolutional neural networks (CNNs). Despite these modules working well, they are implemented in Python without any additional optimization measures. This leads to comparatively high computational times for even simple problems. Starting from PyGAD 2.8.0 (released on 20 September 2020), a new module called kerasga supports training Keras models. Even though Keras is built in Python, it’s fast. The reason is that Keras uses TensorFlow as a backend, and TensorFlow is highly optimized. This tutorial discusses how to train Keras models using PyGAD. The discussion includes building Keras models using either the Sequential Model or the Functional API, building an initial population of Keras model parameters, creating an appropriate fitness function, and more. You can also follow along with the code in this tutorial and run it for free on a Gradient Community Notebook from the ML Showcase. The full tutorial outline is as follows: Getting Started with PyGAD pygad.kerasga Module Steps to Train a Keras Model using PyGAD Decide the Problem Type Create a Keras Model Instantiate the pygad.kerasga.KerasGA Class Prepare the Training Data Loss Function Fitness Function Generation Callback Function (Optional) Create an Instance of the pygad.GA Class Run the Genetic Algorithm Fitness vs. Generation Plot Statistics about the Trained Model Complete Code for Regression Complete Code for Classification using CNN Let’s get started. To start this tutorial, it is essential to install PyGAD. If you already have PyGAD installed, check the __version__ attribute to make sure at least PyGAD 2.8.0 is installed according to the next code. import pygadprint(pygad.__version__) Being available at PyPI (Python Package Index), then it can be installed using the pip installer. Make sure to install PyGAD 2.8.0 or higher. pip install pygad>=2.8.0 Once installed, then you are ready to start. Read the documentation at Read the Docs: pygad.readthedocs.io. The documentation includes some examples. The next code solves a simple problem to optimize the parameters of a linear model. import pygadimport numpyfunction_inputs = [4,-2,3.5,5,-11,-4.7] # Function inputs.desired_output = 44 # Function output.def fitness_func(solution, solution_idx): output = numpy.sum(solution*function_inputs) fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001) return fitnessnum_generations = 100num_parents_mating = 10sol_per_pop = 20num_genes = len(function_inputs)ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_func, sol_per_pop=sol_per_pop, num_genes=num_genes)ga_instance.run()ga_instance.plot_result() Starting from PyGAD 2.8.0, a new module named kerasga is introduced. Its name is short for Keras Genetic Algorithm. The module offers the following functions: Build the initial population of solutions using the KerasGA class. Each solution holds all the parameters in the Keras model. Represent the Keras model’s parameters as a chromosome (i.e. 1D vector) using the model_weights_as_vector() function. Restore the Keras model’s parameters from the chromosome using the model_weights_as_matrix() function. The pygad.kerasga module has a class named KerasGA. The constructor of this class accepts 2 parameters: model: The Keras model.num_solutions: Number of solutions in the population. model: The Keras model. num_solutions: Number of solutions in the population. Based on those 2 parameters, the pygad.kerasga.KerasGA class creates 3 instance attributes: model: A reference to the Keras model.num_solutions: Number of solutions in the population.population_weights: A nested list holding the model parameters. This list is updated after each generation. model: A reference to the Keras model. num_solutions: Number of solutions in the population. population_weights: A nested list holding the model parameters. This list is updated after each generation. Assuming that the Keras model is saved into the model variable, the next code creates an instance of the KerasGA class and saves it into the keras_ga variable. The num_solutions argument is assigned the value 10 which means the population has 10 solutions. The constructor creates a list of length equal to the value of the num_solutions argument. Each element in the list holds different values for the model's parameters after being converted into a 1D vector using the model_weights_as_vector() function. Based on the instance of the KerasGA class, the initial population can be returned from the population_weights attribute. Assuming the model has 60 parameters and there are 10 solutions, then the shape of the initial population is 10x60. import pygad.kerasgakeras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)initial_population = keras_ga.population_weights The next section summarizes the steps to train a Keras model using PyGAD. Each of these steps will be discussed in a separate section. The steps to train a Keras model using PyGAD are summarized as follows: Decide the Problem Type Create a Keras Model Instantiate the pygad.kerasga.KerasGA Class Prepare the Training Data Loss Function Fitness Function Generation Callback Function (Optional) Create an Instance of the pygad.GA Class Run the Genetic Algorithm The next subsections discuss each of these steps. The problem type (either classification or regression) helps to prepare the following: Loss function (which is used to build the fitness function).Output layer in the Keras model.Training data. Loss function (which is used to build the fitness function). Output layer in the Keras model. Training data. For a regression problem, the loss function could be the mean absolute error, mean square error, or another function as listed on this page which summarizes the Keras loss functions for regression: keras.io/api/losses/regression_losses. For a classification problem, the loss function can be binary cross-entropy (for binary classification), categorical cross-entropy (for multi-class problems), or another function as listed in this page which summarizes the Keras classification loss functions: keras.io/api/losses/probabilistic_losses. The activation function in the output layer differs based on whether the problem is classification or regression. For a classification problem, it might be softmax compared to linear for regression. If the problem is regression, then the output of each sample is a continuous number compared to a class label in classification problems. As a summary, it is critical to decide the type of the problem so that the training data and loss function are selected properly. There are 3 ways to build a Keras model: Sequential ModelFunctional APIModel Subclassing Sequential Model Functional API Model Subclassing PyGAD supports building a Keras model using both the Sequential Model and Functional API. For the Sequential Model case, here is an example of building a Keras model. Simply, create each layer using the tensorflow.keras.layers module. Then, create an instance of the tensorflow.keras.Sequential class. Finally, use the add() method to add the layers into the model. import tensorflow.kerasinput_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation="relu")output_layer = tensorflow.keras.layers.Dense(1, activation="linear")model = tensorflow.keras.Sequential()model.add(input_layer)model.add(dense_layer1)model.add(output_layer) Note that the output layer’s activation function is linear which means the problem is regression. For a classification problem, the function can be softmax. In the next line the output layer has 2 neurons (1 for each class) and it uses the softmax activation function. output_layer = tensorflow.keras.layers.Dense(2, activation="linear") For the Functional API case, each layer is created normally as the Sequential Model case. Each layer, otherwise the input layer, is used as a function that accepts the preceding layer as an argument. Finally, an instance of the tensorflow.keras.Model class is created which accepts the input and output layers as arguments. input_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation="relu")(input_layer)output_layer = tensorflow.keras.layers.Dense(1, activation="linear")(dense_layer1)model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer) After the Keras model is created, the next step is to create an initial population of Keras model’s parameters using the KerasGA class. By creating an instance of the pygad.kerasga.KerasGA class, then an initial population of the Keras model's parameters is created. The next code passes the Keras model created in the previous section to the model argument of the KerasGA class constructor. import pygad.kerasgakeras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10) he next section creates the training data used to train the Keras model. Based on the type of problem (classification or regression), the training data is prepared. For a regression problem with 1 output, here is a randomly generated training data where each sample has 3 inputs. import numpy​# Data inputsdata_inputs = numpy.array([[0.02, 0.1, 0.15], [0.7, 0.6, 0.8], [1.5, 1.2, 1.7], [3.2, 2.9, 3.1]])​# Data outputsdata_outputs = numpy.array([[0.1], [0.6], [1.3], [2.5]]) For a binary classification problem like XOR, here is its training data. Each sample has 2 inputs. The outputs are prepared so that the output layer has 2 neurons, 1 for each class. import numpy​# XOR problem inputsdata_inputs = numpy.array([[0, 0], [0, 1], [1, 0], [1, 1]])​# XOR problem outputsdata_outputs = numpy.array([[1, 0], [0, 1], [0, 1], [1, 0]]) The next section discusses the loss function for regression and classification problems. The loss function differs based on the problem type. This section discusses some loss functions in the tensorflow.keras.losses module of Keras for the regression and classification problems. For a regression problem, the loss functions include: tensorflow.keras.losses.MeanAbsoluteError() tensorflow.keras.losses.MeanSquaredError() Check this page for more information. Here is an example that calculates the mean absolute error where y_true and y_pred represent the true and predicted outputs. mae = tensorflow.keras.losses.MeanAbsoluteError()loss = mae(y_true, y_pred).numpy() For a classification problem, the loss functions include: tensorflow.keras.losses.BinaryCrossentropy(): Binary classification. tensorflow.keras.losses.CategoricalCrossentropy(): Multi-class classification. Check this page for more information. Here is an example of calculating the binary class entropy: bce = tensorflow.keras.losses.BinaryCrossentropy()loss = bce(y_true, y_pred).numpy() Based on the loss function, the fitness function is prepared according to the next section. The loss functions for either the classification or regression problems are minimization functions. The fitness functions for the genetic algorithm are maximization ones. So, the fitness value is calculated as the reciprocal of the loss value. fitness_value = 1.0 / loss The steps used to calculate the fitness value of the model are as follows: Restore the model parameters from the 1D vector.Set the model parameters.Make predictions.Calculate the loss value.Calculate the fitness value.Return the fitness value. Restore the model parameters from the 1D vector. Set the model parameters. Make predictions. Calculate the loss value. Calculate the fitness value. Return the fitness value. The next code builds the complete fitness function that works with PyGAD for a regression problem. The fitness function in PyGAD is a regular Python function that must accept 2 arguments. The first one represents the solution to which the fitness value is to be calculated. The other argument is the index of the solution within the population which may be useful in some cases. The solution passed to the fitness function is a 1D vector. To restore the Keras model’s parameters from this vector, the pygad.kerasga.model_weights_as_matrix() is used. model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution) Once the parameters are restored, then they are used as the model’s current parameters by the set_weights() method. model.set_weights(weights=model_weights_matrix) Based on the current parameters, the model predicts the outputs using the predict() method. predictions = model.predict(data_inputs) The predicted outputs are used to calculate the loss value. The mean absolute error is used as a loss function. mae = tensorflow.keras.losses.MeanAbsoluteError() Because the loss value may be 0.0, then it is preferred to add a small value to it like 0.00000001 to avoid diving by zero while calculating the fitness value. solution_fitness = 1.0 / (mae(data_outputs, predictions).numpy() + 0.00000001) Finally, the fitness value is returned. def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs) mae = tensorflow.keras.losses.MeanAbsoluteError() solution_fitness = 1.0 / (mae(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness For a binary classification problem, here is a fitness function that works with PyGAD. It calculates the binary cross-entropy assuming that the classification problem is binary. def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs) bce = tensorflow.keras.losses.BinaryCrossentropy() solution_fitness = 1.0 / (bce(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness The next section builds a callback function executed at the end of each generation. For each generation, the genetic algorithm makes changes over the solutions. A callback function can be called after each generation completes to calculate some statistics about the latest parameters reached. This step is optional and for debugging purposes only. The generation callback function is implemented below. In PyGAD, this callback function must accept a parameter referring to the instance of the genetic algorithm by which the current population can be fetched using the population attribute. In this function, some information is printed like the current generation number and the fitness value of the best solution. Such information keeps the user updated by the progress of the genetic algorithm. def callback_generation(ga_instance): print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1])) The next step towards training a Keras model using PyGAD is to create an instance of the pygad.GA class. The constructor of this class accepts many arguments that can be explored at the documentation. The next code instantiates the pygad.GA class by passing using the minimum arguments in this application which are: num_generations: Number of generations. num_parents_mating: Number of parents to mate. initial_population: The initial population of Keras model's parameters. fitness_func: The fitness function. on_generation: The generation callback function. Note that the number of solutions within the population was previously set to 10 in the constructor of the KerasGA class. Thus, the number of parents to mate must be less than 10. num_generations = 250num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation) The next section runs the genetic algorithm to start training the Keras model. The instance of the pygad.GA class runs by calling the run() method. ga_instance.run() By executing this method, the lifecycle of PyGAD starts according to the next figure. The next section discusses how to draw some conclusions about the trained model. Using the plot_result() method in the pygad.GA class, PyGAD creates a figure that shows how the fitness value changes by generation. ga_instance.plot_result(title="PyGAD & Keras - Iteration vs. Fitness", linewidth=4) The pygad.GA class has a method called best_solution() which returns 3 outputs: Best solution found.Fitness value of the best solution.The index of the best solution within the population. Best solution found. Fitness value of the best solution. The index of the best solution within the population. The next code calls the best_solution() method and prints information about the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution()print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx)) The next code restores the Keras model’s weights from the best solution. Based on the restored weights, the model predicts the outputs of the training samples. You can also predict the outputs of new samples. # Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)print("Predictions : \n", predictions) Given that the loss function used is the mean absolute error, the next code calculates it. mae = tensorflow.keras.losses.MeanAbsoluteError()abs_error = mae(data_outputs, predictions).numpy()print("Absolute Error : ", abs_error) The next sections list the complete code to build and train Keras models using PyGAD. For a regression problem that uses the mean absolute error as a loss function, here is its complete code. import tensorflow.kerasimport pygad.kerasgaimport numpyimport pygad​def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs)​ mae = tensorflow.keras.losses.MeanAbsoluteError() abs_error = mae(data_outputs, predictions).numpy() + 0.00000001 solution_fitness = 1.0 / abs_error​ return solution_fitness​def callback_generation(ga_instance): print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1]))​input_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation="relu")(input_layer)output_layer = tensorflow.keras.layers.Dense(1, activation="linear")(dense_layer1)​model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)​weights_vector = pygad.kerasga.model_weights_as_vector(model=model)​keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)​# Data inputsdata_inputs = numpy.array([[0.02, 0.1, 0.15], [0.7, 0.6, 0.8], [1.5, 1.2, 1.7], [3.2, 2.9, 3.1]])​# Data outputsdata_outputs = numpy.array([[0.1], [0.6], [1.3], [2.5]])​num_generations = 250num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation)ga_instance.run()​# After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations.ga_instance.plot_result(title="PyGAD & Keras - Iteration vs. Fitness", linewidth=4)​# Returning the details of the best solution.solution, solution_fitness, solution_idx = ga_instance.best_solution()print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))​# Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)print("Predictions : \n", predictions)​mae = tensorflow.keras.losses.MeanAbsoluteError()abs_error = mae(data_outputs, predictions).numpy()print("Absolute Error : ", abs_error) After the code completes, the next figure shows that the fitness value is increasing which is a good sign as the Keras model is learning properly. Here are some more details about the trained model. Note that the predicted values are close to the right ones. The MAE is 0.018. Fitness value of the best solution = 54.79189095217631Index of the best solution : 0Predictions : [[0.11471477] [0.6034051 ] [1.3416876 ] [2.486804 ]]Absolute Error : 0.018250866 The next code builds a convolutional neural network using Keras for classifying a dataset of 80 images where the size of each image is 100x100x3. Note that the categorical cross-entropy is used because the dataset has 4 classes. The training data can be downloaded from these links: dataset_inputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_inputs.npydataset_outputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_outputs.npy dataset_inputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_inputs.npy dataset_outputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_outputs.npy import tensorflow.kerasimport pygad.kerasgaimport numpyimport pygad​def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs)​ cce = tensorflow.keras.losses.CategoricalCrossentropy() solution_fitness = 1.0 / (cce(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness​def callback_generation(ga_instance): print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1]))​# Build the keras model using the functional API.input_layer = tensorflow.keras.layers.Input(shape=(100, 100, 3))conv_layer1 = tensorflow.keras.layers.Conv2D(filters=5, kernel_size=7, activation="relu")(input_layer)max_pool1 = tensorflow.keras.layers.MaxPooling2D(pool_size=(5,5), strides=5)(conv_layer1)conv_layer2 = tensorflow.keras.layers.Conv2D(filters=3, kernel_size=3, activation="relu")(max_pool1)flatten_layer = tensorflow.keras.layers.Flatten()(conv_layer2)dense_layer = tensorflow.keras.layers.Dense(15, activation="relu")(flatten_layer)output_layer = tensorflow.keras.layers.Dense(4, activation="softmax")(dense_layer)​model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)​keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)​# Data inputsdata_inputs = numpy.load("dataset_inputs.npy")​# Data outputsdata_outputs = numpy.load("dataset_outputs.npy")data_outputs = tensorflow.keras.utils.to_categorical(data_outputs)​num_generations = 200num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation)​ga_instance.run()​ga_instance.plot_result(title="PyGAD & Keras - Iteration vs. Fitness", linewidth=4)​# Returning the details of the best solution.solution, solution_fitness, solution_idx = ga_instance.best_solution()print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))​# Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)# print("Predictions : \n", predictions)​# Calculate the categorical crossentropy for the trained model.cce = tensorflow.keras.losses.CategoricalCrossentropy()print("Categorical Crossentropy : ", cce(data_outputs, predictions).numpy())​# Calculate the classification accuracy for the trained model.ca = tensorflow.keras.metrics.CategoricalAccuracy()ca.update_state(data_outputs, predictions)accuracy = ca.result().numpy()print("Accuracy : ", accuracy) The next figure shows how the fitness value evolves by generation. As long as the fitness value increases, then increase the number of generations to achieve better accuracy. Here is some information about the trained model. Fitness value of the best solution = 2.7462310258668805Categorical Crossentropy : 0.3641354Accuracy : 0.75 This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient. This tutorial discussed how to train Keras models using the genetic algorithm using a Python 3 library called PyGAD. The Keras models can be created using the Sequential Model or the Functional API. Using the pygad.kerasga module, an initial population of Keras model's weights is created where each solution holds a different set of weights for the model. This population is later evolved according to the lifecycle of PyGAD until all the generations complete. Due to the high-speed nature of TensorFlow, which is the backend of Keras, PyGAD can train complex architectures in a reasonable time.
[ { "code": null, "e": 402, "s": 172, "text": "PyGAD is an open-source Python library for building the genetic algorithm and training machine learning algorithms. It offers a wide range of parameters to customize the genetic algorithm to work with different types of problems." }, { "code": null, "e": 719, "s": 402, "text": "PyGAD has its own modules that support building and training neural networks (NNs) and convolutional neural networks (CNNs). Despite these modules working well, they are implemented in Python without any additional optimization measures. This leads to comparatively high computational times for even simple problems." }, { "code": null, "e": 978, "s": 719, "text": "Starting from PyGAD 2.8.0 (released on 20 September 2020), a new module called kerasga supports training Keras models. Even though Keras is built in Python, it’s fast. The reason is that Keras uses TensorFlow as a backend, and TensorFlow is highly optimized." }, { "code": null, "e": 1254, "s": 978, "text": "This tutorial discusses how to train Keras models using PyGAD. The discussion includes building Keras models using either the Sequential Model or the Functional API, building an initial population of Keras model parameters, creating an appropriate fitness function, and more." }, { "code": null, "e": 1386, "s": 1254, "text": "You can also follow along with the code in this tutorial and run it for free on a Gradient Community Notebook from the ML Showcase." }, { "code": null, "e": 1427, "s": 1386, "text": "The full tutorial outline is as follows:" }, { "code": null, "e": 1454, "s": 1427, "text": "Getting Started with PyGAD" }, { "code": null, "e": 1475, "s": 1454, "text": "pygad.kerasga Module" }, { "code": null, "e": 1516, "s": 1475, "text": "Steps to Train a Keras Model using PyGAD" }, { "code": null, "e": 1540, "s": 1516, "text": "Decide the Problem Type" }, { "code": null, "e": 1561, "s": 1540, "text": "Create a Keras Model" }, { "code": null, "e": 1605, "s": 1561, "text": "Instantiate the pygad.kerasga.KerasGA Class" }, { "code": null, "e": 1631, "s": 1605, "text": "Prepare the Training Data" }, { "code": null, "e": 1645, "s": 1631, "text": "Loss Function" }, { "code": null, "e": 1662, "s": 1645, "text": "Fitness Function" }, { "code": null, "e": 1702, "s": 1662, "text": "Generation Callback Function (Optional)" }, { "code": null, "e": 1743, "s": 1702, "text": "Create an Instance of the pygad.GA Class" }, { "code": null, "e": 1769, "s": 1743, "text": "Run the Genetic Algorithm" }, { "code": null, "e": 1797, "s": 1769, "text": "Fitness vs. Generation Plot" }, { "code": null, "e": 1832, "s": 1797, "text": "Statistics about the Trained Model" }, { "code": null, "e": 1861, "s": 1832, "text": "Complete Code for Regression" }, { "code": null, "e": 1904, "s": 1861, "text": "Complete Code for Classification using CNN" }, { "code": null, "e": 1923, "s": 1904, "text": "Let’s get started." }, { "code": null, "e": 2125, "s": 1923, "text": "To start this tutorial, it is essential to install PyGAD. If you already have PyGAD installed, check the __version__ attribute to make sure at least PyGAD 2.8.0 is installed according to the next code." }, { "code": null, "e": 2162, "s": 2125, "text": "import pygadprint(pygad.__version__)" }, { "code": null, "e": 2304, "s": 2162, "text": "Being available at PyPI (Python Package Index), then it can be installed using the pip installer. Make sure to install PyGAD 2.8.0 or higher." }, { "code": null, "e": 2329, "s": 2304, "text": "pip install pygad>=2.8.0" }, { "code": null, "e": 2479, "s": 2329, "text": "Once installed, then you are ready to start. Read the documentation at Read the Docs: pygad.readthedocs.io. The documentation includes some examples." }, { "code": null, "e": 2563, "s": 2479, "text": "The next code solves a simple problem to optimize the parameters of a linear model." }, { "code": null, "e": 3247, "s": 2563, "text": "import pygadimport numpyfunction_inputs = [4,-2,3.5,5,-11,-4.7] # Function inputs.desired_output = 44 # Function output.def fitness_func(solution, solution_idx): output = numpy.sum(solution*function_inputs) fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001) return fitnessnum_generations = 100num_parents_mating = 10sol_per_pop = 20num_genes = len(function_inputs)ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_func, sol_per_pop=sol_per_pop, num_genes=num_genes)ga_instance.run()ga_instance.plot_result()" }, { "code": null, "e": 3406, "s": 3247, "text": "Starting from PyGAD 2.8.0, a new module named kerasga is introduced. Its name is short for Keras Genetic Algorithm. The module offers the following functions:" }, { "code": null, "e": 3532, "s": 3406, "text": "Build the initial population of solutions using the KerasGA class. Each solution holds all the parameters in the Keras model." }, { "code": null, "e": 3650, "s": 3532, "text": "Represent the Keras model’s parameters as a chromosome (i.e. 1D vector) using the model_weights_as_vector() function." }, { "code": null, "e": 3753, "s": 3650, "text": "Restore the Keras model’s parameters from the chromosome using the model_weights_as_matrix() function." }, { "code": null, "e": 3857, "s": 3753, "text": "The pygad.kerasga module has a class named KerasGA. The constructor of this class accepts 2 parameters:" }, { "code": null, "e": 3934, "s": 3857, "text": "model: The Keras model.num_solutions: Number of solutions in the population." }, { "code": null, "e": 3958, "s": 3934, "text": "model: The Keras model." }, { "code": null, "e": 4012, "s": 3958, "text": "num_solutions: Number of solutions in the population." }, { "code": null, "e": 4104, "s": 4012, "text": "Based on those 2 parameters, the pygad.kerasga.KerasGA class creates 3 instance attributes:" }, { "code": null, "e": 4303, "s": 4104, "text": "model: A reference to the Keras model.num_solutions: Number of solutions in the population.population_weights: A nested list holding the model parameters. This list is updated after each generation." }, { "code": null, "e": 4342, "s": 4303, "text": "model: A reference to the Keras model." }, { "code": null, "e": 4396, "s": 4342, "text": "num_solutions: Number of solutions in the population." }, { "code": null, "e": 4504, "s": 4396, "text": "population_weights: A nested list holding the model parameters. This list is updated after each generation." }, { "code": null, "e": 4761, "s": 4504, "text": "Assuming that the Keras model is saved into the model variable, the next code creates an instance of the KerasGA class and saves it into the keras_ga variable. The num_solutions argument is assigned the value 10 which means the population has 10 solutions." }, { "code": null, "e": 5012, "s": 4761, "text": "The constructor creates a list of length equal to the value of the num_solutions argument. Each element in the list holds different values for the model's parameters after being converted into a 1D vector using the model_weights_as_vector() function." }, { "code": null, "e": 5250, "s": 5012, "text": "Based on the instance of the KerasGA class, the initial population can be returned from the population_weights attribute. Assuming the model has 60 parameters and there are 10 solutions, then the shape of the initial population is 10x60." }, { "code": null, "e": 5414, "s": 5250, "text": "import pygad.kerasgakeras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)initial_population = keras_ga.population_weights" }, { "code": null, "e": 5549, "s": 5414, "text": "The next section summarizes the steps to train a Keras model using PyGAD. Each of these steps will be discussed in a separate section." }, { "code": null, "e": 5621, "s": 5549, "text": "The steps to train a Keras model using PyGAD are summarized as follows:" }, { "code": null, "e": 5645, "s": 5621, "text": "Decide the Problem Type" }, { "code": null, "e": 5666, "s": 5645, "text": "Create a Keras Model" }, { "code": null, "e": 5710, "s": 5666, "text": "Instantiate the pygad.kerasga.KerasGA Class" }, { "code": null, "e": 5736, "s": 5710, "text": "Prepare the Training Data" }, { "code": null, "e": 5750, "s": 5736, "text": "Loss Function" }, { "code": null, "e": 5767, "s": 5750, "text": "Fitness Function" }, { "code": null, "e": 5807, "s": 5767, "text": "Generation Callback Function (Optional)" }, { "code": null, "e": 5848, "s": 5807, "text": "Create an Instance of the pygad.GA Class" }, { "code": null, "e": 5874, "s": 5848, "text": "Run the Genetic Algorithm" }, { "code": null, "e": 5924, "s": 5874, "text": "The next subsections discuss each of these steps." }, { "code": null, "e": 6011, "s": 5924, "text": "The problem type (either classification or regression) helps to prepare the following:" }, { "code": null, "e": 6118, "s": 6011, "text": "Loss function (which is used to build the fitness function).Output layer in the Keras model.Training data." }, { "code": null, "e": 6179, "s": 6118, "text": "Loss function (which is used to build the fitness function)." }, { "code": null, "e": 6212, "s": 6179, "text": "Output layer in the Keras model." }, { "code": null, "e": 6227, "s": 6212, "text": "Training data." }, { "code": null, "e": 6464, "s": 6227, "text": "For a regression problem, the loss function could be the mean absolute error, mean square error, or another function as listed on this page which summarizes the Keras loss functions for regression: keras.io/api/losses/regression_losses." }, { "code": null, "e": 6766, "s": 6464, "text": "For a classification problem, the loss function can be binary cross-entropy (for binary classification), categorical cross-entropy (for multi-class problems), or another function as listed in this page which summarizes the Keras classification loss functions: keras.io/api/losses/probabilistic_losses." }, { "code": null, "e": 6965, "s": 6766, "text": "The activation function in the output layer differs based on whether the problem is classification or regression. For a classification problem, it might be softmax compared to linear for regression." }, { "code": null, "e": 7103, "s": 6965, "text": "If the problem is regression, then the output of each sample is a continuous number compared to a class label in classification problems." }, { "code": null, "e": 7233, "s": 7103, "text": "As a summary, it is critical to decide the type of the problem so that the training data and loss function are selected properly." }, { "code": null, "e": 7274, "s": 7233, "text": "There are 3 ways to build a Keras model:" }, { "code": null, "e": 7322, "s": 7274, "text": "Sequential ModelFunctional APIModel Subclassing" }, { "code": null, "e": 7339, "s": 7322, "text": "Sequential Model" }, { "code": null, "e": 7354, "s": 7339, "text": "Functional API" }, { "code": null, "e": 7372, "s": 7354, "text": "Model Subclassing" }, { "code": null, "e": 7462, "s": 7372, "text": "PyGAD supports building a Keras model using both the Sequential Model and Functional API." }, { "code": null, "e": 7738, "s": 7462, "text": "For the Sequential Model case, here is an example of building a Keras model. Simply, create each layer using the tensorflow.keras.layers module. Then, create an instance of the tensorflow.keras.Sequential class. Finally, use the add() method to add the layers into the model." }, { "code": null, "e": 8048, "s": 7738, "text": "import tensorflow.kerasinput_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation=\"relu\")output_layer = tensorflow.keras.layers.Dense(1, activation=\"linear\")model = tensorflow.keras.Sequential()model.add(input_layer)model.add(dense_layer1)model.add(output_layer)" }, { "code": null, "e": 8317, "s": 8048, "text": "Note that the output layer’s activation function is linear which means the problem is regression. For a classification problem, the function can be softmax. In the next line the output layer has 2 neurons (1 for each class) and it uses the softmax activation function." }, { "code": null, "e": 8386, "s": 8317, "text": "output_layer = tensorflow.keras.layers.Dense(2, activation=\"linear\")" }, { "code": null, "e": 8710, "s": 8386, "text": "For the Functional API case, each layer is created normally as the Sequential Model case. Each layer, otherwise the input layer, is used as a function that accepts the preceding layer as an argument. Finally, an instance of the tensorflow.keras.Model class is created which accepts the input and output layers as arguments." }, { "code": null, "e": 8991, "s": 8710, "text": "input_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation=\"relu\")(input_layer)output_layer = tensorflow.keras.layers.Dense(1, activation=\"linear\")(dense_layer1)model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)" }, { "code": null, "e": 9127, "s": 8991, "text": "After the Keras model is created, the next step is to create an initial population of Keras model’s parameters using the KerasGA class." }, { "code": null, "e": 9383, "s": 9127, "text": "By creating an instance of the pygad.kerasga.KerasGA class, then an initial population of the Keras model's parameters is created. The next code passes the Keras model created in the previous section to the model argument of the KerasGA class constructor." }, { "code": null, "e": 9499, "s": 9383, "text": "import pygad.kerasgakeras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)" }, { "code": null, "e": 9572, "s": 9499, "text": "he next section creates the training data used to train the Keras model." }, { "code": null, "e": 9664, "s": 9572, "text": "Based on the type of problem (classification or regression), the training data is prepared." }, { "code": null, "e": 9779, "s": 9664, "text": "For a regression problem with 1 output, here is a randomly generated training data where each sample has 3 inputs." }, { "code": null, "e": 10133, "s": 9779, "text": "import numpy​# Data inputsdata_inputs = numpy.array([[0.02, 0.1, 0.15], [0.7, 0.6, 0.8], [1.5, 1.2, 1.7], [3.2, 2.9, 3.1]])​# Data outputsdata_outputs = numpy.array([[0.1], [0.6], [1.3], [2.5]])" }, { "code": null, "e": 10315, "s": 10133, "text": "For a binary classification problem like XOR, here is its training data. Each sample has 2 inputs. The outputs are prepared so that the output layer has 2 neurons, 1 for each class." }, { "code": null, "e": 10649, "s": 10315, "text": "import numpy​# XOR problem inputsdata_inputs = numpy.array([[0, 0], [0, 1], [1, 0], [1, 1]])​# XOR problem outputsdata_outputs = numpy.array([[1, 0], [0, 1], [0, 1], [1, 0]])" }, { "code": null, "e": 10738, "s": 10649, "text": "The next section discusses the loss function for regression and classification problems." }, { "code": null, "e": 10929, "s": 10738, "text": "The loss function differs based on the problem type. This section discusses some loss functions in the tensorflow.keras.losses module of Keras for the regression and classification problems." }, { "code": null, "e": 10983, "s": 10929, "text": "For a regression problem, the loss functions include:" }, { "code": null, "e": 11027, "s": 10983, "text": "tensorflow.keras.losses.MeanAbsoluteError()" }, { "code": null, "e": 11070, "s": 11027, "text": "tensorflow.keras.losses.MeanSquaredError()" }, { "code": null, "e": 11108, "s": 11070, "text": "Check this page for more information." }, { "code": null, "e": 11233, "s": 11108, "text": "Here is an example that calculates the mean absolute error where y_true and y_pred represent the true and predicted outputs." }, { "code": null, "e": 11317, "s": 11233, "text": "mae = tensorflow.keras.losses.MeanAbsoluteError()loss = mae(y_true, y_pred).numpy()" }, { "code": null, "e": 11375, "s": 11317, "text": "For a classification problem, the loss functions include:" }, { "code": null, "e": 11444, "s": 11375, "text": "tensorflow.keras.losses.BinaryCrossentropy(): Binary classification." }, { "code": null, "e": 11523, "s": 11444, "text": "tensorflow.keras.losses.CategoricalCrossentropy(): Multi-class classification." }, { "code": null, "e": 11561, "s": 11523, "text": "Check this page for more information." }, { "code": null, "e": 11621, "s": 11561, "text": "Here is an example of calculating the binary class entropy:" }, { "code": null, "e": 11706, "s": 11621, "text": "bce = tensorflow.keras.losses.BinaryCrossentropy()loss = bce(y_true, y_pred).numpy()" }, { "code": null, "e": 11798, "s": 11706, "text": "Based on the loss function, the fitness function is prepared according to the next section." }, { "code": null, "e": 12042, "s": 11798, "text": "The loss functions for either the classification or regression problems are minimization functions. The fitness functions for the genetic algorithm are maximization ones. So, the fitness value is calculated as the reciprocal of the loss value." }, { "code": null, "e": 12069, "s": 12042, "text": "fitness_value = 1.0 / loss" }, { "code": null, "e": 12144, "s": 12069, "text": "The steps used to calculate the fitness value of the model are as follows:" }, { "code": null, "e": 12313, "s": 12144, "text": "Restore the model parameters from the 1D vector.Set the model parameters.Make predictions.Calculate the loss value.Calculate the fitness value.Return the fitness value." }, { "code": null, "e": 12362, "s": 12313, "text": "Restore the model parameters from the 1D vector." }, { "code": null, "e": 12388, "s": 12362, "text": "Set the model parameters." }, { "code": null, "e": 12406, "s": 12388, "text": "Make predictions." }, { "code": null, "e": 12432, "s": 12406, "text": "Calculate the loss value." }, { "code": null, "e": 12461, "s": 12432, "text": "Calculate the fitness value." }, { "code": null, "e": 12487, "s": 12461, "text": "Return the fitness value." }, { "code": null, "e": 12866, "s": 12487, "text": "The next code builds the complete fitness function that works with PyGAD for a regression problem. The fitness function in PyGAD is a regular Python function that must accept 2 arguments. The first one represents the solution to which the fitness value is to be calculated. The other argument is the index of the solution within the population which may be useful in some cases." }, { "code": null, "e": 13037, "s": 12866, "text": "The solution passed to the fitness function is a 1D vector. To restore the Keras model’s parameters from this vector, the pygad.kerasga.model_weights_as_matrix() is used." }, { "code": null, "e": 13136, "s": 13037, "text": "model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)" }, { "code": null, "e": 13252, "s": 13136, "text": "Once the parameters are restored, then they are used as the model’s current parameters by the set_weights() method." }, { "code": null, "e": 13300, "s": 13252, "text": "model.set_weights(weights=model_weights_matrix)" }, { "code": null, "e": 13392, "s": 13300, "text": "Based on the current parameters, the model predicts the outputs using the predict() method." }, { "code": null, "e": 13433, "s": 13392, "text": "predictions = model.predict(data_inputs)" }, { "code": null, "e": 13545, "s": 13433, "text": "The predicted outputs are used to calculate the loss value. The mean absolute error is used as a loss function." }, { "code": null, "e": 13595, "s": 13545, "text": "mae = tensorflow.keras.losses.MeanAbsoluteError()" }, { "code": null, "e": 13755, "s": 13595, "text": "Because the loss value may be 0.0, then it is preferred to add a small value to it like 0.00000001 to avoid diving by zero while calculating the fitness value." }, { "code": null, "e": 13834, "s": 13755, "text": "solution_fitness = 1.0 / (mae(data_outputs, predictions).numpy() + 0.00000001)" }, { "code": null, "e": 13874, "s": 13834, "text": "Finally, the fitness value is returned." }, { "code": null, "e": 14395, "s": 13874, "text": "def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs) mae = tensorflow.keras.losses.MeanAbsoluteError() solution_fitness = 1.0 / (mae(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness" }, { "code": null, "e": 14573, "s": 14395, "text": "For a binary classification problem, here is a fitness function that works with PyGAD. It calculates the binary cross-entropy assuming that the classification problem is binary." }, { "code": null, "e": 15095, "s": 14573, "text": "def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs) bce = tensorflow.keras.losses.BinaryCrossentropy() solution_fitness = 1.0 / (bce(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness" }, { "code": null, "e": 15179, "s": 15095, "text": "The next section builds a callback function executed at the end of each generation." }, { "code": null, "e": 15388, "s": 15179, "text": "For each generation, the genetic algorithm makes changes over the solutions. A callback function can be called after each generation completes to calculate some statistics about the latest parameters reached." }, { "code": null, "e": 15443, "s": 15388, "text": "This step is optional and for debugging purposes only." }, { "code": null, "e": 15685, "s": 15443, "text": "The generation callback function is implemented below. In PyGAD, this callback function must accept a parameter referring to the instance of the genetic algorithm by which the current population can be fetched using the population attribute." }, { "code": null, "e": 15892, "s": 15685, "text": "In this function, some information is printed like the current generation number and the fitness value of the best solution. Such information keeps the user updated by the progress of the genetic algorithm." }, { "code": null, "e": 16103, "s": 15892, "text": "def callback_generation(ga_instance): print(\"Generation = {generation}\".format(generation=ga_instance.generations_completed)) print(\"Fitness = {fitness}\".format(fitness=ga_instance.best_solution()[1]))" }, { "code": null, "e": 16304, "s": 16103, "text": "The next step towards training a Keras model using PyGAD is to create an instance of the pygad.GA class. The constructor of this class accepts many arguments that can be explored at the documentation." }, { "code": null, "e": 16420, "s": 16304, "text": "The next code instantiates the pygad.GA class by passing using the minimum arguments in this application which are:" }, { "code": null, "e": 16460, "s": 16420, "text": "num_generations: Number of generations." }, { "code": null, "e": 16507, "s": 16460, "text": "num_parents_mating: Number of parents to mate." }, { "code": null, "e": 16579, "s": 16507, "text": "initial_population: The initial population of Keras model's parameters." }, { "code": null, "e": 16615, "s": 16579, "text": "fitness_func: The fitness function." }, { "code": null, "e": 16664, "s": 16615, "text": "on_generation: The generation callback function." }, { "code": null, "e": 16844, "s": 16664, "text": "Note that the number of solutions within the population was previously set to 10 in the constructor of the KerasGA class. Thus, the number of parents to mate must be less than 10." }, { "code": null, "e": 17222, "s": 16844, "text": "num_generations = 250num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation)" }, { "code": null, "e": 17301, "s": 17222, "text": "The next section runs the genetic algorithm to start training the Keras model." }, { "code": null, "e": 17370, "s": 17301, "text": "The instance of the pygad.GA class runs by calling the run() method." }, { "code": null, "e": 17388, "s": 17370, "text": "ga_instance.run()" }, { "code": null, "e": 17474, "s": 17388, "text": "By executing this method, the lifecycle of PyGAD starts according to the next figure." }, { "code": null, "e": 17555, "s": 17474, "text": "The next section discusses how to draw some conclusions about the trained model." }, { "code": null, "e": 17688, "s": 17555, "text": "Using the plot_result() method in the pygad.GA class, PyGAD creates a figure that shows how the fitness value changes by generation." }, { "code": null, "e": 17772, "s": 17688, "text": "ga_instance.plot_result(title=\"PyGAD & Keras - Iteration vs. Fitness\", linewidth=4)" }, { "code": null, "e": 17852, "s": 17772, "text": "The pygad.GA class has a method called best_solution() which returns 3 outputs:" }, { "code": null, "e": 17961, "s": 17852, "text": "Best solution found.Fitness value of the best solution.The index of the best solution within the population." }, { "code": null, "e": 17982, "s": 17961, "text": "Best solution found." }, { "code": null, "e": 18018, "s": 17982, "text": "Fitness value of the best solution." }, { "code": null, "e": 18072, "s": 18018, "text": "The index of the best solution within the population." }, { "code": null, "e": 18167, "s": 18072, "text": "The next code calls the best_solution() method and prints information about the best solution." }, { "code": null, "e": 18430, "s": 18167, "text": "solution, solution_fitness, solution_idx = ga_instance.best_solution()print(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))print(\"Index of the best solution : {solution_idx}\".format(solution_idx=solution_idx))" }, { "code": null, "e": 18639, "s": 18430, "text": "The next code restores the Keras model’s weights from the best solution. Based on the restored weights, the model predicts the outputs of the training samples. You can also predict the outputs of new samples." }, { "code": null, "e": 18962, "s": 18639, "text": "# Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)print(\"Predictions : \\n\", predictions)" }, { "code": null, "e": 19053, "s": 18962, "text": "Given that the loss function used is the mean absolute error, the next code calculates it." }, { "code": null, "e": 19190, "s": 19053, "text": "mae = tensorflow.keras.losses.MeanAbsoluteError()abs_error = mae(data_outputs, predictions).numpy()print(\"Absolute Error : \", abs_error)" }, { "code": null, "e": 19276, "s": 19190, "text": "The next sections list the complete code to build and train Keras models using PyGAD." }, { "code": null, "e": 19382, "s": 19276, "text": "For a regression problem that uses the mean absolute error as a loss function, here is its complete code." }, { "code": null, "e": 22362, "s": 19382, "text": "import tensorflow.kerasimport pygad.kerasgaimport numpyimport pygad​def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs)​ mae = tensorflow.keras.losses.MeanAbsoluteError() abs_error = mae(data_outputs, predictions).numpy() + 0.00000001 solution_fitness = 1.0 / abs_error​ return solution_fitness​def callback_generation(ga_instance): print(\"Generation = {generation}\".format(generation=ga_instance.generations_completed)) print(\"Fitness = {fitness}\".format(fitness=ga_instance.best_solution()[1]))​input_layer = tensorflow.keras.layers.Input(3)dense_layer1 = tensorflow.keras.layers.Dense(5, activation=\"relu\")(input_layer)output_layer = tensorflow.keras.layers.Dense(1, activation=\"linear\")(dense_layer1)​model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)​weights_vector = pygad.kerasga.model_weights_as_vector(model=model)​keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)​# Data inputsdata_inputs = numpy.array([[0.02, 0.1, 0.15], [0.7, 0.6, 0.8], [1.5, 1.2, 1.7], [3.2, 2.9, 3.1]])​# Data outputsdata_outputs = numpy.array([[0.1], [0.6], [1.3], [2.5]])​num_generations = 250num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation)ga_instance.run()​# After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations.ga_instance.plot_result(title=\"PyGAD & Keras - Iteration vs. Fitness\", linewidth=4)​# Returning the details of the best solution.solution, solution_fitness, solution_idx = ga_instance.best_solution()print(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))print(\"Index of the best solution : {solution_idx}\".format(solution_idx=solution_idx))​# Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)print(\"Predictions : \\n\", predictions)​mae = tensorflow.keras.losses.MeanAbsoluteError()abs_error = mae(data_outputs, predictions).numpy()print(\"Absolute Error : \", abs_error)" }, { "code": null, "e": 22509, "s": 22362, "text": "After the code completes, the next figure shows that the fitness value is increasing which is a good sign as the Keras model is learning properly." }, { "code": null, "e": 22639, "s": 22509, "text": "Here are some more details about the trained model. Note that the predicted values are close to the right ones. The MAE is 0.018." }, { "code": null, "e": 22820, "s": 22639, "text": "Fitness value of the best solution = 54.79189095217631Index of the best solution : 0Predictions : [[0.11471477] [0.6034051 ] [1.3416876 ] [2.486804 ]]Absolute Error : 0.018250866" }, { "code": null, "e": 23049, "s": 22820, "text": "The next code builds a convolutional neural network using Keras for classifying a dataset of 80 images where the size of each image is 100x100x3. Note that the categorical cross-entropy is used because the dataset has 4 classes." }, { "code": null, "e": 23103, "s": 23049, "text": "The training data can be downloaded from these links:" }, { "code": null, "e": 23282, "s": 23103, "text": "dataset_inputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_inputs.npydataset_outputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_outputs.npy" }, { "code": null, "e": 23371, "s": 23282, "text": "dataset_inputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_inputs.npy" }, { "code": null, "e": 23462, "s": 23371, "text": "dataset_outputs.npy: https://github.com/ahmedfgad/NumPyCNN/blob/master/dataset_outputs.npy" }, { "code": null, "e": 27002, "s": 23462, "text": "import tensorflow.kerasimport pygad.kerasgaimport numpyimport pygad​def fitness_func(solution, sol_idx): global data_inputs, data_outputs, keras_ga, model​ model_weights_matrix = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)​ model.set_weights(weights=model_weights_matrix)​ predictions = model.predict(data_inputs)​ cce = tensorflow.keras.losses.CategoricalCrossentropy() solution_fitness = 1.0 / (cce(data_outputs, predictions).numpy() + 0.00000001)​ return solution_fitness​def callback_generation(ga_instance): print(\"Generation = {generation}\".format(generation=ga_instance.generations_completed)) print(\"Fitness = {fitness}\".format(fitness=ga_instance.best_solution()[1]))​# Build the keras model using the functional API.input_layer = tensorflow.keras.layers.Input(shape=(100, 100, 3))conv_layer1 = tensorflow.keras.layers.Conv2D(filters=5, kernel_size=7, activation=\"relu\")(input_layer)max_pool1 = tensorflow.keras.layers.MaxPooling2D(pool_size=(5,5), strides=5)(conv_layer1)conv_layer2 = tensorflow.keras.layers.Conv2D(filters=3, kernel_size=3, activation=\"relu\")(max_pool1)flatten_layer = tensorflow.keras.layers.Flatten()(conv_layer2)dense_layer = tensorflow.keras.layers.Dense(15, activation=\"relu\")(flatten_layer)output_layer = tensorflow.keras.layers.Dense(4, activation=\"softmax\")(dense_layer)​model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)​keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=10)​# Data inputsdata_inputs = numpy.load(\"dataset_inputs.npy\")​# Data outputsdata_outputs = numpy.load(\"dataset_outputs.npy\")data_outputs = tensorflow.keras.utils.to_categorical(data_outputs)​num_generations = 200num_parents_mating = 5initial_population = keras_ga.population_weights​ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation)​ga_instance.run()​ga_instance.plot_result(title=\"PyGAD & Keras - Iteration vs. Fitness\", linewidth=4)​# Returning the details of the best solution.solution, solution_fitness, solution_idx = ga_instance.best_solution()print(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))print(\"Index of the best solution : {solution_idx}\".format(solution_idx=solution_idx))​# Fetch the parameters of the best solution.best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)model.set_weights(best_solution_weights)predictions = model.predict(data_inputs)# print(\"Predictions : \\n\", predictions)​# Calculate the categorical crossentropy for the trained model.cce = tensorflow.keras.losses.CategoricalCrossentropy()print(\"Categorical Crossentropy : \", cce(data_outputs, predictions).numpy())​# Calculate the classification accuracy for the trained model.ca = tensorflow.keras.metrics.CategoricalAccuracy()ca.update_state(data_outputs, predictions)accuracy = ca.result().numpy()print(\"Accuracy : \", accuracy)" }, { "code": null, "e": 27177, "s": 27002, "text": "The next figure shows how the fitness value evolves by generation. As long as the fitness value increases, then increase the number of generations to achieve better accuracy." }, { "code": null, "e": 27227, "s": 27177, "text": "Here is some information about the trained model." }, { "code": null, "e": 27336, "s": 27227, "text": "Fitness value of the best solution = 2.7462310258668805Categorical Crossentropy : 0.3641354Accuracy : 0.75" }, { "code": null, "e": 27458, "s": 27336, "text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient." }, { "code": null, "e": 27657, "s": 27458, "text": "This tutorial discussed how to train Keras models using the genetic algorithm using a Python 3 library called PyGAD. The Keras models can be created using the Sequential Model or the Functional API." }, { "code": null, "e": 27920, "s": 27657, "text": "Using the pygad.kerasga module, an initial population of Keras model's weights is created where each solution holds a different set of weights for the model. This population is later evolved according to the lifecycle of PyGAD until all the generations complete." } ]
\omega - Tex Command
\omega - Used to create lowercase omega symbol. { \omega} \omega command draws lowercase omega symbol. \omega ω \omega ω \omega 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8034, "s": 7986, "text": "\\omega - Used to create lowercase omega symbol." }, { "code": null, "e": 8044, "s": 8034, "text": "{ \\omega}" }, { "code": null, "e": 8089, "s": 8044, "text": "\\omega command draws lowercase omega symbol." }, { "code": null, "e": 8103, "s": 8089, "text": "\n\\omega\n\nω\n\n\n" }, { "code": null, "e": 8115, "s": 8103, "text": "\\omega\n\nω\n\n" }, { "code": null, "e": 8122, "s": 8115, "text": "\\omega" }, { "code": null, "e": 8154, "s": 8122, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8167, "s": 8154, "text": " Ashraf Said" }, { "code": null, "e": 8200, "s": 8167, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8213, "s": 8200, "text": " Ashraf Said" }, { "code": null, "e": 8245, "s": 8213, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8281, "s": 8245, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8316, "s": 8281, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8333, "s": 8316, "text": " Mohammad Nauman" }, { "code": null, "e": 8366, "s": 8333, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8380, "s": 8366, "text": " Daniel Stern" }, { "code": null, "e": 8412, "s": 8380, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8427, "s": 8412, "text": " Nishant Kumar" }, { "code": null, "e": 8434, "s": 8427, "text": " Print" }, { "code": null, "e": 8445, "s": 8434, "text": " Add Notes" } ]
Engineering - HEX2BIN Function
The HEX2BIN function converts a hexadecimal number to binary. HEX2BIN (number, [places]) The hexadecimal number you want to convert. Number cannot contain more than 10 characters (40 bits). The most significant bit of number is the sign bit (40th bit from the right). The remaining 39 bits are magnitude bits. Negative numbers are represented using two's-complement notation. The number of characters to use. If places is omitted, HEX2BIN uses the minimum number of characters necessary. Places is useful for padding the return value with leading 0s (zeros). The Hexadecimal (Base 16) Numeral System uses the digits 0-9 and the characters A-F The Hexadecimal (Base 16) Numeral System uses the digits 0-9 and the characters A-F The following table shows the first 32 hexadecimal values, along with the equivalent decimal values − The following table shows the first 32 hexadecimal values, along with the equivalent decimal values − As hexadecimals use the numbers 0-9 and the characters A-F, they should be enclosed in quotation marks when they are supplied to an Excel function. For example, the hexadecimal 11A should be input as "11A" As hexadecimals use the numbers 0-9 and the characters A-F, they should be enclosed in quotation marks when they are supplied to an Excel function. For example, the hexadecimal 11A should be input as "11A" The Binary (Base 2) Numeral System uses the digits 0 & 1. The Binary (Base 2) Numeral System uses the digits 0 & 1. The following table shows the first 8 binary values, along with the equivalent decimal values − The following table shows the first 8 binary values, along with the equivalent decimal values − If number is negative, HEX2BIN ignores places and returns a 10-character binary number. If number is negative, HEX2BIN ignores places and returns a 10-character binary number. If number is negative, it cannot be less than FFFFFFFE00 If number is negative, it cannot be less than FFFFFFFE00 If number is positive, it cannot be greater than 1FF. If number is positive, it cannot be greater than 1FF. If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. If HEX2BIN requires more than places characters, it returns the #NUM! error value. If HEX2BIN requires more than places characters, it returns the #NUM! error value. If places is not an integer, it is truncated. If places is not an integer, it is truncated. If places is nonnumeric, HEX2BIN returns the #VALUE! error value. If places is nonnumeric, HEX2BIN returns the #VALUE! error value. If places is negative, HEX2BIN returns the #NUM! error value. If places is negative, HEX2BIN returns the #NUM! error value. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 1916, "s": 1854, "text": "The HEX2BIN function converts a hexadecimal number to binary." }, { "code": null, "e": 1944, "s": 1916, "text": "HEX2BIN (number, [places])\n" }, { "code": null, "e": 1988, "s": 1944, "text": "The hexadecimal number you want to convert." }, { "code": null, "e": 2165, "s": 1988, "text": "Number cannot contain more than 10 characters (40 bits). The most significant bit of number is the sign bit (40th bit from the right). The remaining 39 bits are magnitude bits." }, { "code": null, "e": 2231, "s": 2165, "text": "Negative numbers are represented using two's-complement notation." }, { "code": null, "e": 2264, "s": 2231, "text": "The number of characters to use." }, { "code": null, "e": 2343, "s": 2264, "text": "If places is omitted, HEX2BIN uses the minimum number of characters necessary." }, { "code": null, "e": 2414, "s": 2343, "text": "Places is useful for padding the return value with leading 0s (zeros)." }, { "code": null, "e": 2498, "s": 2414, "text": "The Hexadecimal (Base 16) Numeral System uses the digits 0-9 and the characters A-F" }, { "code": null, "e": 2582, "s": 2498, "text": "The Hexadecimal (Base 16) Numeral System uses the digits 0-9 and the characters A-F" }, { "code": null, "e": 2684, "s": 2582, "text": "The following table shows the first 32 hexadecimal values, along with the equivalent decimal values −" }, { "code": null, "e": 2786, "s": 2684, "text": "The following table shows the first 32 hexadecimal values, along with the equivalent decimal values −" }, { "code": null, "e": 2992, "s": 2786, "text": "As hexadecimals use the numbers 0-9 and the characters A-F, they should be enclosed in quotation marks when they are supplied to an Excel function. For example, the hexadecimal 11A should be input as \"11A\"" }, { "code": null, "e": 3198, "s": 2992, "text": "As hexadecimals use the numbers 0-9 and the characters A-F, they should be enclosed in quotation marks when they are supplied to an Excel function. For example, the hexadecimal 11A should be input as \"11A\"" }, { "code": null, "e": 3256, "s": 3198, "text": "The Binary (Base 2) Numeral System uses the digits 0 & 1." }, { "code": null, "e": 3314, "s": 3256, "text": "The Binary (Base 2) Numeral System uses the digits 0 & 1." }, { "code": null, "e": 3410, "s": 3314, "text": "The following table shows the first 8 binary values, along with the equivalent decimal values −" }, { "code": null, "e": 3506, "s": 3410, "text": "The following table shows the first 8 binary values, along with the equivalent decimal values −" }, { "code": null, "e": 3594, "s": 3506, "text": "If number is negative, HEX2BIN ignores places and returns a 10-character binary number." }, { "code": null, "e": 3682, "s": 3594, "text": "If number is negative, HEX2BIN ignores places and returns a 10-character binary number." }, { "code": null, "e": 3739, "s": 3682, "text": "If number is negative, it cannot be less than FFFFFFFE00" }, { "code": null, "e": 3796, "s": 3739, "text": "If number is negative, it cannot be less than FFFFFFFE00" }, { "code": null, "e": 3850, "s": 3796, "text": "If number is positive, it cannot be greater than 1FF." }, { "code": null, "e": 3904, "s": 3850, "text": "If number is positive, it cannot be greater than 1FF." }, { "code": null, "e": 3988, "s": 3904, "text": "If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value." }, { "code": null, "e": 4072, "s": 3988, "text": "If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value." }, { "code": null, "e": 4155, "s": 4072, "text": "If HEX2BIN requires more than places characters, it returns the #NUM! error value." }, { "code": null, "e": 4238, "s": 4155, "text": "If HEX2BIN requires more than places characters, it returns the #NUM! error value." }, { "code": null, "e": 4284, "s": 4238, "text": "If places is not an integer, it is truncated." }, { "code": null, "e": 4330, "s": 4284, "text": "If places is not an integer, it is truncated." }, { "code": null, "e": 4396, "s": 4330, "text": "If places is nonnumeric, HEX2BIN returns the #VALUE! error value." }, { "code": null, "e": 4462, "s": 4396, "text": "If places is nonnumeric, HEX2BIN returns the #VALUE! error value." }, { "code": null, "e": 4524, "s": 4462, "text": "If places is negative, HEX2BIN returns the #NUM! error value." }, { "code": null, "e": 4586, "s": 4524, "text": "If places is negative, HEX2BIN returns the #NUM! error value." }, { "code": null, "e": 4633, "s": 4586, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 4669, "s": 4633, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 4683, "s": 4669, "text": " Arun Motoori" }, { "code": null, "e": 4718, "s": 4683, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4733, "s": 4718, "text": " Pavan Lalwani" }, { "code": null, "e": 4769, "s": 4733, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4778, "s": 4769, "text": " Inf Sid" }, { "code": null, "e": 4814, "s": 4778, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4829, "s": 4814, "text": " Yoda Learning" }, { "code": null, "e": 4864, "s": 4829, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4879, "s": 4864, "text": " William Fiset" }, { "code": null, "e": 4914, "s": 4879, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4928, "s": 4914, "text": " Sasha Miller" }, { "code": null, "e": 4935, "s": 4928, "text": " Print" }, { "code": null, "e": 4946, "s": 4935, "text": " Add Notes" } ]
HTML - Main Tag
The HTML <main> tag specifies main or important content in the document. It can be used only once per page and can't be used as a descendent of <article>, <aside>, <footer>, <header>, <nav> element. <!DOCTYPE html> <html> <body> <main> <h1>Learning</h1> <p>Learn to gain experience and try to share your knowledge with others.</p> <article> <h3>Web Development Tutorials</h3> <p>Consist of CSS, HTML, and PHP tutorials for 2nd Semester exams.</p> </article> <article> <h3>Academic Tutorials</h3> <p>Consist of Computer Fundamental, Computer Network tutorials for 1st Semester exams.</p> </article> </main> </body> </html> This will produce the following result − Learn to gain experience and try to share your knowledge with others. Consist of CSS, HTML, and PHP tutorials for 2nd Semester exams. Consist of Computer Fundamental, Computer Network tutorials for 1st Semester exams. This tag supports all the global attributes described in − HTML Attribute Reference This tag supports all the event attributes described in − HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2573, "s": 2374, "text": "The HTML <main> tag specifies main or important content in the document. It can be used only once per page and can't be used as a descendent of <article>, <aside>, <footer>, <header>, <nav> element." }, { "code": null, "e": 3153, "s": 2573, "text": "<!DOCTYPE html>\n<html>\n\n <body>\n <main>\n <h1>Learning</h1>\n <p>Learn to gain experience and try to share your knowledge with others.</p>\n \n <article>\n <h3>Web Development Tutorials</h3>\n <p>Consist of CSS, HTML, and PHP tutorials for 2nd Semester exams.</p>\n </article>\n \n <article>\n <h3>Academic Tutorials</h3>\n <p>Consist of Computer Fundamental, Computer Network tutorials for\n 1st Semester exams.</p>\n </article>\n </main>\n </body>\n\n</html>" }, { "code": null, "e": 3194, "s": 3153, "text": "This will produce the following result −" }, { "code": null, "e": 3264, "s": 3194, "text": "Learn to gain experience and try to share your knowledge with others." }, { "code": null, "e": 3328, "s": 3264, "text": "Consist of CSS, HTML, and PHP tutorials for 2nd Semester exams." }, { "code": null, "e": 3412, "s": 3328, "text": "Consist of Computer Fundamental, Computer Network tutorials for 1st Semester exams." }, { "code": null, "e": 3496, "s": 3412, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3576, "s": 3496, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3609, "s": 3576, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3623, "s": 3609, "text": " Anadi Sharma" }, { "code": null, "e": 3658, "s": 3623, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3672, "s": 3658, "text": " Anadi Sharma" }, { "code": null, "e": 3707, "s": 3672, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3724, "s": 3707, "text": " Frahaan Hussain" }, { "code": null, "e": 3759, "s": 3724, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3790, "s": 3759, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3823, "s": 3790, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3854, "s": 3823, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3889, "s": 3854, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3920, "s": 3889, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3927, "s": 3920, "text": " Print" }, { "code": null, "e": 3938, "s": 3927, "text": " Add Notes" } ]
How To Fetch The Exact Values From A Boxplot (Python) | by Elena Kosourova | Towards Data Science
A boxplot is a type of visualization used for displaying the five-number set of descriptive statistics for a dataset: the minimum and maximum (excluding the outliers), the median, the first (Q1) and third (Q3) quartiles. In Python, boxplots can be created in various data visualization libraries including the most basic one — matplotlib. While the main scope of a boxplot is to visualize the statistical information about a dataset, what if we also need to extract and print out the exact numbers of such statistics? In this article, we’ll discuss the easiest way of doing so in the matplotlib library. To start with, let’s create 3 dummy datasets and display the boxplots for them in matplotlib. To be able to further extract the necessary values, though, we have to assign the result of the plt.boxplot() method to a variable (bp): import matplotlib.pyplot as pltimport numpy as npnp.random.seed(1)data_1 = np.random.normal(50, 30, 300)data_2 = np.random.normal(100, 40, 300)data_3 = np.random.normal(70, 10, 300)data = [data_1, data_2, data_3]bp = plt.boxplot(data)plt.show() The resulting variable bp is a Python dictionary: type(bp)Output:dict with the following keys representing the main elements of a boxplot: bp.keys()Output:dict_keys(['whiskers', 'caps', 'boxes', 'medians', 'fliers', 'means']) Here is the dictionary itself: bpOutput:{'whiskers': [<matplotlib.lines.Line2D at 0x1eaf6131b50>, <matplotlib.lines.Line2D at 0x1eaf6131eb0>, <matplotlib.lines.Line2D at 0x1eaf61533a0>, <matplotlib.lines.Line2D at 0x1eaf6153700>, <matplotlib.lines.Line2D at 0x1eaf6162b80>, <matplotlib.lines.Line2D at 0x1eaf6162ee0>], 'caps': [<matplotlib.lines.Line2D at 0x1eaf614a250>, <matplotlib.lines.Line2D at 0x1eaf614a5b0>, <matplotlib.lines.Line2D at 0x1eaf6153a60>, <matplotlib.lines.Line2D at 0x1eaf6153dc0>, <matplotlib.lines.Line2D at 0x1eaf616d280>, <matplotlib.lines.Line2D at 0x1eaf616d5e0>], 'boxes': [<matplotlib.lines.Line2D at 0x1eaf61317f0>, <matplotlib.lines.Line2D at 0x1eaf6153040>, <matplotlib.lines.Line2D at 0x1eaf6162820>], 'medians': [<matplotlib.lines.Line2D at 0x1eaf614a910>, <matplotlib.lines.Line2D at 0x1eaf6162160>, <matplotlib.lines.Line2D at 0x1eaf616d940>], 'fliers': [<matplotlib.lines.Line2D at 0x1eaf614ac70>, <matplotlib.lines.Line2D at 0x1eaf61624c0>, <matplotlib.lines.Line2D at 0x1eaf616dca0>], 'means': []} We see that the values of the dictionary are actually lists of matplotlib objects (in particular, matplotlib.lines.Line2D). All in all, we have 6 whiskers (2 for each boxplot), 6 caps (2 for each boxplot), then 3 boxes, 3 medians, and 3 sets of outliers (fliers), one for each boxplot. A curious thing is that means has an empty list as its value. It's happened because, by default, a boxplot doesn't display the sample mean. To show the mean value on a boxplot, we have to specify it through an optional parameter showmeans: bp = plt.boxplot(data, showmeans=True)bp['means']Output:[<matplotlib.lines.Line2D at 0x1eaf6262790>, <matplotlib.lines.Line2D at 0x1eaf627b340>, <matplotlib.lines.Line2D at 0x1eaf6286e80>][<matplotlib.lines.Line2D at 0x1eaf6262790>, <matplotlib.lines.Line2D at 0x1eaf627b340>, <matplotlib.lines.Line2D at 0x1eaf6286e80>] Now, instead of an empty list, the means key has a list of 3 matplotlib objects as its value. In addition, on each of the 3 boxplots, we see a new marker representing the mean value for each dataset. Before extracting the exact numbers, let’s take a look at the main elements of a boxplot with the mean value (i.e. the keys of our dictionary), as well as the descriptive statistics which we’re going to obtain: Now, let’s extract preliminary statistical values from each item of the dictionary using the get_ydata() method and try to understand their structure keeping in mind the picture above: for key in bp: print(f'{key}: {[item.get_ydata() for item in bp[key]]}\n')Output:whiskers: [array([ 32.27380667, -23.04513292]), array([ 70.59264691, 125.8497712 ]), array([75.68154245, -0.65215444]), array([131.88978143, 185.5131227 ]), array([63.74451462, 46.95092062]), array([76.33158616, 95.05980285])]caps: [array([-23.04513292, -23.04513292]), array([125.8497712, 125.8497712]), array([-0.65215444, -0.65215444]), array([185.5131227, 185.5131227]), array([46.95092062, 46.95092062]), array([95.05980285, 95.05980285])]boxes: [array([32.27380667, 32.27380667, 70.59264691, 70.59264691, 32.27380667]), array([ 75.68154245, 75.68154245, 131.88978143, 131.88978143, 75.68154245]), array([63.74451462, 63.74451462, 76.33158616, 76.33158616, 63.74451462])]medians: [array([52.64528282, 52.64528282]), array([100.43803244, 100.43803244]), array([70.10978367, 70.10978367])]fliers: [array([-33.79255]), array([-11.30137871, 221.23428449, 258.34410816]), array([ 42.09003593, 43.01638258, 39.4623562 , 103.21078756])]means: [array([52.23199524]), array([102.26099759]), array([69.8400676])] We obtained lists of ndarrays for each key of the dictionary. What we actually want to fetch includes the following information for each dataset: the median, the mean, the minimum without outliers, the maximum without outliers, the first quartile Q1, the third quartile Q3, the lower outliers, the upper outliers. Looking at the picture above, it should be noted that we can extract the minimum and maximum values either from caps or whiskers (we'll use the first approach), and analogically for Q1 and Q3: from boxes or whiskers (again, we'll use the first approach). From the extracted raw values above, we see that for medians, we have 3 ndarrays of 2 identical items, while for means — 3 one-item ndarrays. For medians, each ndarray describes the line for the median value in the corresponding box (from left to right), for means — the point for the mean. To obtain the exact values of the median and mean for each boxplot, we have to select the first item of the corresponding ndarray: medians = [item.get_ydata()[0] for item in bp['medians']]means = [item.get_ydata()[0] for item in bp['means']]print(f'Medians: {medians}\n' f'Means: {means}')Output:Medians: [52.64528282246805, 100.43803243566403, 70.10978366813102] Means: [52.23199524458482, 102.26099759095463, 69.84006759933192] Most probably, we may not want such precision of the results. So, here and elsewhere, let’s consider rounding the numbers to the first decimal point: medians = [round(item.get_ydata()[0], 1) for item in bp['medians']]means = [round(item.get_ydata()[0], 1) for item in bp['means']]print(f'Medians: {medians}\n' f'Means: {means}')Output:Medians: [52.6, 100.4, 70.1]Means: [52.2, 102.3, 69.8] For the minimum and maximum values, we can use the ndarrays extracted from caps. Let's take a closer look at them: [item.get_ydata() for item in bp['caps']]Output:[array([-23.04513292, -23.04513292]), array([125.8497712, 125.8497712]), array([-0.65215444, -0.65215444]), array([185.5131227, 185.5131227]), array([46.95092062, 46.95092062]), array([95.05980285, 95.05980285])] The ndarrays of 2 identical items each go in this order: minimum for the 1st (the leftmost) boxplot, maximum for the 1st boxplot, minimum for the 2nd boxplot, etc. Hence, to obtain the minimum values for all the boxplots, we have to use list slicing to get the odd ndarrays (and selecting the first item from each), to obtain the maximum values — the even ones. Also in this case, for convenience, we’ll apply rounding to the first decimal: minimums = [round(item.get_ydata()[0], 1) for item in bp['caps']][::2]maximums = [round(item.get_ydata()[0], 1) for item in bp['caps']][1::2]print(f'Minimums: {minimums}\n' f'Maximums: {maximums}')Output:Minimums: [-23.0, -0.7, 47.0]Maximums: [125.8, 185.5, 95.1] Let’s extract the first and third quartiles from boxes. To remind the raw data of boxes: [item.get_ydata() for item in bp['boxes']]Output:[array([32.27380667, 32.27380667, 70.59264691, 70.59264691, 32.27380667]), array([ 75.68154245, 75.68154245, 131.88978143, 131.88978143, 75.68154245]), array([63.74451462, 63.74451462, 76.33158616, 76.33158616, 63.74451462])] Looking at the pattern of each ndarray (representing each box), we can notice that the boxplot polygons (rectangles) were drawn starting from the minimum on the left going to the right and, in the end, were closed on the minimum again. Practically, what we need here is to extract the minimum value from each box to obtain Q1 and the maximum value to obtain Q3: q1 = [round(min(item.get_ydata()), 1) for item in bp['boxes']]q3 = [round(max(item.get_ydata()), 1) for item in bp['boxes']]print(f'Q1: {q1}\n' f'Q3: {q3}')Output:Q1: [32.3, 75.7, 63.7]Q3: [70.6, 131.9, 76.3] We can find the outlier values in the dictionary key fliers: [item.get_ydata() for item in bp['fliers']]Output:[array([-33.79255]), array([-11.30137871, 221.23428449, 258.34410816]), array([ 42.09003593, 43.01638258, 39.4623562 , 103.21078756])] For now, they are grouped by a boxplot. If we want to have 2 separate lists for lower and upper outliers, we can apply the following code: fliers = [item.get_ydata() for item in bp['fliers']]lower_outliers = []upper_outliers = []for i in range(len(fliers)): lower_outliers_by_box = [] upper_outliers_by_box = [] for outlier in fliers[i]: if outlier < q1[i]: lower_outliers_by_box.append(round(outlier, 1)) else: upper_outliers_by_box.append(round(outlier, 1)) lower_outliers.append(lower_outliers_by_box) upper_outliers.append(upper_outliers_by_box)print(f'Lower outliers: {lower_outliers}\n' f'Upper outliers: {upper_outliers}')Output:Lower outliers: [[-33.8], [-11.3], [42.1, 43.0, 39.5]] Upper outliers: [[], [221.2, 258.3], [103.2]] Since the 1st boxplot doesn’t have any upper outliers, we obtained an empty list for it. Now, let’s summarize in an elegant way all the descriptive statistics that we extracted so from for each dataset. Even though the code below looks a bit scary, the only thing we’ll have to update every time we use a new set of categories (datasets) is the two lines of code marked with a lateral comment # to be updated (and, of course, we'll have to remove the case-specific section for creating datasets). Optionally, we can consider updating rounding the results (the round() method instances) that is currently set to the first decimal point: # Gather all the previous codeimport matplotlib.pyplot as pltimport numpy as np#--------------------------------------# Creating datasetsnp.random.seed(1)data_1 = np.random.normal(50, 30, 300)data_2 = np.random.normal(100, 40, 300)data_3 = np.random.normal(70, 10, 300)#--------------------------------------data = [data_1, data_2, data_3] # to be updatedbp = plt.boxplot(data, showmeans=True)medians = [round(item.get_ydata()[0], 1) for item in bp['medians']]means = [round(item.get_ydata()[0], 1) for item in bp['means']]minimums = [round(item.get_ydata()[0], 1) for item in bp['caps']][::2]maximums = [round(item.get_ydata()[0], 1) for item in bp['caps']][1::2]q1 = [round(min(item.get_ydata()), 1) for item in bp['boxes']]q3 = [round(max(item.get_ydata()), 1) for item in bp['boxes']]fliers = [item.get_ydata() for item in bp['fliers']]lower_outliers = []upper_outliers = []for i in range(len(fliers)): lower_outliers_by_box = [] upper_outliers_by_box = [] for outlier in fliers[i]: if outlier < q1[i]: lower_outliers_by_box.append(round(outlier, 1)) else: upper_outliers_by_box.append(round(outlier, 1)) lower_outliers.append(lower_outliers_by_box) upper_outliers.append(upper_outliers_by_box) # New codestats = [medians, means, minimums, maximums, q1, q3, lower_outliers, upper_outliers]stats_names = ['Median', 'Mean', 'Minimum', 'Maximum', 'Q1', 'Q3', 'Lower outliers', 'Upper outliers']categories = ['DATASET 1', 'DATASET 2', 'DATASET 3'] # to be updatedfor i in range(len(categories)): print(f'\033[1m{categories[i]}\033[0m') for j in range(len(stats)): print(f'{stats_names[j]}: {stats[j][i]}') print('\n')Output:DATASET 1Median: 52.6Mean: 52.2Minimum: -23.0Maximum: 125.8Q1: 32.3Q3: 70.6Lower outliers: [-33.8]Upper outliers: []DATASET 2Median: 100.4Mean: 102.3Minimum: -0.7Maximum: 185.5Q1: 75.7Q3: 131.9Lower outliers: [-11.3]Upper outliers: [221.2, 258.3]DATASET 3Median: 70.1Mean: 69.8Minimum: 47.0Maximum: 95.1Q1: 63.7Q3: 76.3Lower outliers: [42.1, 43.0, 39.5]Upper outliers: [103.2] In this article, we’ve explored how to extract and print out the exact values of the descriptive statistics of a dataset from a boxplot created in the matplotlib library. Such statistical information can include the median, the mean, the minimum and maximum values without outliers, the first and third quartile, the lower and upper outliers. In some cases, this precise data can be a valuable supplement to the visual information from a boxplot itself. Thanks for reading! You can find interesting also these articles:
[ { "code": null, "e": 511, "s": 172, "text": "A boxplot is a type of visualization used for displaying the five-number set of descriptive statistics for a dataset: the minimum and maximum (excluding the outliers), the median, the first (Q1) and third (Q3) quartiles. In Python, boxplots can be created in various data visualization libraries including the most basic one — matplotlib." }, { "code": null, "e": 776, "s": 511, "text": "While the main scope of a boxplot is to visualize the statistical information about a dataset, what if we also need to extract and print out the exact numbers of such statistics? In this article, we’ll discuss the easiest way of doing so in the matplotlib library." }, { "code": null, "e": 1007, "s": 776, "text": "To start with, let’s create 3 dummy datasets and display the boxplots for them in matplotlib. To be able to further extract the necessary values, though, we have to assign the result of the plt.boxplot() method to a variable (bp):" }, { "code": null, "e": 1252, "s": 1007, "text": "import matplotlib.pyplot as pltimport numpy as npnp.random.seed(1)data_1 = np.random.normal(50, 30, 300)data_2 = np.random.normal(100, 40, 300)data_3 = np.random.normal(70, 10, 300)data = [data_1, data_2, data_3]bp = plt.boxplot(data)plt.show()" }, { "code": null, "e": 1302, "s": 1252, "text": "The resulting variable bp is a Python dictionary:" }, { "code": null, "e": 1322, "s": 1302, "text": "type(bp)Output:dict" }, { "code": null, "e": 1391, "s": 1322, "text": "with the following keys representing the main elements of a boxplot:" }, { "code": null, "e": 1478, "s": 1391, "text": "bp.keys()Output:dict_keys(['whiskers', 'caps', 'boxes', 'medians', 'fliers', 'means'])" }, { "code": null, "e": 1509, "s": 1478, "text": "Here is the dictionary itself:" }, { "code": null, "e": 2532, "s": 1509, "text": "bpOutput:{'whiskers': [<matplotlib.lines.Line2D at 0x1eaf6131b50>, <matplotlib.lines.Line2D at 0x1eaf6131eb0>, <matplotlib.lines.Line2D at 0x1eaf61533a0>, <matplotlib.lines.Line2D at 0x1eaf6153700>, <matplotlib.lines.Line2D at 0x1eaf6162b80>, <matplotlib.lines.Line2D at 0x1eaf6162ee0>], 'caps': [<matplotlib.lines.Line2D at 0x1eaf614a250>, <matplotlib.lines.Line2D at 0x1eaf614a5b0>, <matplotlib.lines.Line2D at 0x1eaf6153a60>, <matplotlib.lines.Line2D at 0x1eaf6153dc0>, <matplotlib.lines.Line2D at 0x1eaf616d280>, <matplotlib.lines.Line2D at 0x1eaf616d5e0>], 'boxes': [<matplotlib.lines.Line2D at 0x1eaf61317f0>, <matplotlib.lines.Line2D at 0x1eaf6153040>, <matplotlib.lines.Line2D at 0x1eaf6162820>], 'medians': [<matplotlib.lines.Line2D at 0x1eaf614a910>, <matplotlib.lines.Line2D at 0x1eaf6162160>, <matplotlib.lines.Line2D at 0x1eaf616d940>], 'fliers': [<matplotlib.lines.Line2D at 0x1eaf614ac70>, <matplotlib.lines.Line2D at 0x1eaf61624c0>, <matplotlib.lines.Line2D at 0x1eaf616dca0>], 'means': []}" }, { "code": null, "e": 3058, "s": 2532, "text": "We see that the values of the dictionary are actually lists of matplotlib objects (in particular, matplotlib.lines.Line2D). All in all, we have 6 whiskers (2 for each boxplot), 6 caps (2 for each boxplot), then 3 boxes, 3 medians, and 3 sets of outliers (fliers), one for each boxplot. A curious thing is that means has an empty list as its value. It's happened because, by default, a boxplot doesn't display the sample mean. To show the mean value on a boxplot, we have to specify it through an optional parameter showmeans:" }, { "code": null, "e": 3379, "s": 3058, "text": "bp = plt.boxplot(data, showmeans=True)bp['means']Output:[<matplotlib.lines.Line2D at 0x1eaf6262790>, <matplotlib.lines.Line2D at 0x1eaf627b340>, <matplotlib.lines.Line2D at 0x1eaf6286e80>][<matplotlib.lines.Line2D at 0x1eaf6262790>, <matplotlib.lines.Line2D at 0x1eaf627b340>, <matplotlib.lines.Line2D at 0x1eaf6286e80>]" }, { "code": null, "e": 3579, "s": 3379, "text": "Now, instead of an empty list, the means key has a list of 3 matplotlib objects as its value. In addition, on each of the 3 boxplots, we see a new marker representing the mean value for each dataset." }, { "code": null, "e": 3790, "s": 3579, "text": "Before extracting the exact numbers, let’s take a look at the main elements of a boxplot with the mean value (i.e. the keys of our dictionary), as well as the descriptive statistics which we’re going to obtain:" }, { "code": null, "e": 3975, "s": 3790, "text": "Now, let’s extract preliminary statistical values from each item of the dictionary using the get_ydata() method and try to understand their structure keeping in mind the picture above:" }, { "code": null, "e": 5077, "s": 3975, "text": "for key in bp: print(f'{key}: {[item.get_ydata() for item in bp[key]]}\\n')Output:whiskers: [array([ 32.27380667, -23.04513292]), array([ 70.59264691, 125.8497712 ]), array([75.68154245, -0.65215444]), array([131.88978143, 185.5131227 ]), array([63.74451462, 46.95092062]), array([76.33158616, 95.05980285])]caps: [array([-23.04513292, -23.04513292]), array([125.8497712, 125.8497712]), array([-0.65215444, -0.65215444]), array([185.5131227, 185.5131227]), array([46.95092062, 46.95092062]), array([95.05980285, 95.05980285])]boxes: [array([32.27380667, 32.27380667, 70.59264691, 70.59264691, 32.27380667]), array([ 75.68154245, 75.68154245, 131.88978143, 131.88978143, 75.68154245]), array([63.74451462, 63.74451462, 76.33158616, 76.33158616, 63.74451462])]medians: [array([52.64528282, 52.64528282]), array([100.43803244, 100.43803244]), array([70.10978367, 70.10978367])]fliers: [array([-33.79255]), array([-11.30137871, 221.23428449, 258.34410816]), array([ 42.09003593, 43.01638258, 39.4623562 , 103.21078756])]means: [array([52.23199524]), array([102.26099759]), array([69.8400676])]" }, { "code": null, "e": 5223, "s": 5077, "text": "We obtained lists of ndarrays for each key of the dictionary. What we actually want to fetch includes the following information for each dataset:" }, { "code": null, "e": 5235, "s": 5223, "text": "the median," }, { "code": null, "e": 5245, "s": 5235, "text": "the mean," }, { "code": null, "e": 5275, "s": 5245, "text": "the minimum without outliers," }, { "code": null, "e": 5305, "s": 5275, "text": "the maximum without outliers," }, { "code": null, "e": 5328, "s": 5305, "text": "the first quartile Q1," }, { "code": null, "e": 5351, "s": 5328, "text": "the third quartile Q3," }, { "code": null, "e": 5371, "s": 5351, "text": "the lower outliers," }, { "code": null, "e": 5391, "s": 5371, "text": "the upper outliers." }, { "code": null, "e": 5646, "s": 5391, "text": "Looking at the picture above, it should be noted that we can extract the minimum and maximum values either from caps or whiskers (we'll use the first approach), and analogically for Q1 and Q3: from boxes or whiskers (again, we'll use the first approach)." }, { "code": null, "e": 6068, "s": 5646, "text": "From the extracted raw values above, we see that for medians, we have 3 ndarrays of 2 identical items, while for means — 3 one-item ndarrays. For medians, each ndarray describes the line for the median value in the corresponding box (from left to right), for means — the point for the mean. To obtain the exact values of the median and mean for each boxplot, we have to select the first item of the corresponding ndarray:" }, { "code": null, "e": 6376, "s": 6068, "text": "medians = [item.get_ydata()[0] for item in bp['medians']]means = [item.get_ydata()[0] for item in bp['means']]print(f'Medians: {medians}\\n' f'Means: {means}')Output:Medians: [52.64528282246805, 100.43803243566403, 70.10978366813102] Means: [52.23199524458482, 102.26099759095463, 69.84006759933192]" }, { "code": null, "e": 6526, "s": 6376, "text": "Most probably, we may not want such precision of the results. So, here and elsewhere, let’s consider rounding the numbers to the first decimal point:" }, { "code": null, "e": 6775, "s": 6526, "text": "medians = [round(item.get_ydata()[0], 1) for item in bp['medians']]means = [round(item.get_ydata()[0], 1) for item in bp['means']]print(f'Medians: {medians}\\n' f'Means: {means}')Output:Medians: [52.6, 100.4, 70.1]Means: [52.2, 102.3, 69.8]" }, { "code": null, "e": 6890, "s": 6775, "text": "For the minimum and maximum values, we can use the ndarrays extracted from caps. Let's take a closer look at them:" }, { "code": null, "e": 7151, "s": 6890, "text": "[item.get_ydata() for item in bp['caps']]Output:[array([-23.04513292, -23.04513292]), array([125.8497712, 125.8497712]), array([-0.65215444, -0.65215444]), array([185.5131227, 185.5131227]), array([46.95092062, 46.95092062]), array([95.05980285, 95.05980285])]" }, { "code": null, "e": 7592, "s": 7151, "text": "The ndarrays of 2 identical items each go in this order: minimum for the 1st (the leftmost) boxplot, maximum for the 1st boxplot, minimum for the 2nd boxplot, etc. Hence, to obtain the minimum values for all the boxplots, we have to use list slicing to get the odd ndarrays (and selecting the first item from each), to obtain the maximum values — the even ones. Also in this case, for convenience, we’ll apply rounding to the first decimal:" }, { "code": null, "e": 7861, "s": 7592, "text": "minimums = [round(item.get_ydata()[0], 1) for item in bp['caps']][::2]maximums = [round(item.get_ydata()[0], 1) for item in bp['caps']][1::2]print(f'Minimums: {minimums}\\n' f'Maximums: {maximums}')Output:Minimums: [-23.0, -0.7, 47.0]Maximums: [125.8, 185.5, 95.1]" }, { "code": null, "e": 7950, "s": 7861, "text": "Let’s extract the first and third quartiles from boxes. To remind the raw data of boxes:" }, { "code": null, "e": 8234, "s": 7950, "text": "[item.get_ydata() for item in bp['boxes']]Output:[array([32.27380667, 32.27380667, 70.59264691, 70.59264691, 32.27380667]), array([ 75.68154245, 75.68154245, 131.88978143, 131.88978143, 75.68154245]), array([63.74451462, 63.74451462, 76.33158616, 76.33158616, 63.74451462])]" }, { "code": null, "e": 8596, "s": 8234, "text": "Looking at the pattern of each ndarray (representing each box), we can notice that the boxplot polygons (rectangles) were drawn starting from the minimum on the left going to the right and, in the end, were closed on the minimum again. Practically, what we need here is to extract the minimum value from each box to obtain Q1 and the maximum value to obtain Q3:" }, { "code": null, "e": 8810, "s": 8596, "text": "q1 = [round(min(item.get_ydata()), 1) for item in bp['boxes']]q3 = [round(max(item.get_ydata()), 1) for item in bp['boxes']]print(f'Q1: {q1}\\n' f'Q3: {q3}')Output:Q1: [32.3, 75.7, 63.7]Q3: [70.6, 131.9, 76.3]" }, { "code": null, "e": 8871, "s": 8810, "text": "We can find the outlier values in the dictionary key fliers:" }, { "code": null, "e": 9058, "s": 8871, "text": "[item.get_ydata() for item in bp['fliers']]Output:[array([-33.79255]), array([-11.30137871, 221.23428449, 258.34410816]), array([ 42.09003593, 43.01638258, 39.4623562 , 103.21078756])]" }, { "code": null, "e": 9197, "s": 9058, "text": "For now, they are grouped by a boxplot. If we want to have 2 separate lists for lower and upper outliers, we can apply the following code:" }, { "code": null, "e": 9851, "s": 9197, "text": "fliers = [item.get_ydata() for item in bp['fliers']]lower_outliers = []upper_outliers = []for i in range(len(fliers)): lower_outliers_by_box = [] upper_outliers_by_box = [] for outlier in fliers[i]: if outlier < q1[i]: lower_outliers_by_box.append(round(outlier, 1)) else: upper_outliers_by_box.append(round(outlier, 1)) lower_outliers.append(lower_outliers_by_box) upper_outliers.append(upper_outliers_by_box)print(f'Lower outliers: {lower_outliers}\\n' f'Upper outliers: {upper_outliers}')Output:Lower outliers: [[-33.8], [-11.3], [42.1, 43.0, 39.5]] Upper outliers: [[], [221.2, 258.3], [103.2]]" }, { "code": null, "e": 9940, "s": 9851, "text": "Since the 1st boxplot doesn’t have any upper outliers, we obtained an empty list for it." }, { "code": null, "e": 10487, "s": 9940, "text": "Now, let’s summarize in an elegant way all the descriptive statistics that we extracted so from for each dataset. Even though the code below looks a bit scary, the only thing we’ll have to update every time we use a new set of categories (datasets) is the two lines of code marked with a lateral comment # to be updated (and, of course, we'll have to remove the case-specific section for creating datasets). Optionally, we can consider updating rounding the results (the round() method instances) that is currently set to the first decimal point:" }, { "code": null, "e": 12563, "s": 10487, "text": "# Gather all the previous codeimport matplotlib.pyplot as pltimport numpy as np#--------------------------------------# Creating datasetsnp.random.seed(1)data_1 = np.random.normal(50, 30, 300)data_2 = np.random.normal(100, 40, 300)data_3 = np.random.normal(70, 10, 300)#--------------------------------------data = [data_1, data_2, data_3] # to be updatedbp = plt.boxplot(data, showmeans=True)medians = [round(item.get_ydata()[0], 1) for item in bp['medians']]means = [round(item.get_ydata()[0], 1) for item in bp['means']]minimums = [round(item.get_ydata()[0], 1) for item in bp['caps']][::2]maximums = [round(item.get_ydata()[0], 1) for item in bp['caps']][1::2]q1 = [round(min(item.get_ydata()), 1) for item in bp['boxes']]q3 = [round(max(item.get_ydata()), 1) for item in bp['boxes']]fliers = [item.get_ydata() for item in bp['fliers']]lower_outliers = []upper_outliers = []for i in range(len(fliers)): lower_outliers_by_box = [] upper_outliers_by_box = [] for outlier in fliers[i]: if outlier < q1[i]: lower_outliers_by_box.append(round(outlier, 1)) else: upper_outliers_by_box.append(round(outlier, 1)) lower_outliers.append(lower_outliers_by_box) upper_outliers.append(upper_outliers_by_box) # New codestats = [medians, means, minimums, maximums, q1, q3, lower_outliers, upper_outliers]stats_names = ['Median', 'Mean', 'Minimum', 'Maximum', 'Q1', 'Q3', 'Lower outliers', 'Upper outliers']categories = ['DATASET 1', 'DATASET 2', 'DATASET 3'] # to be updatedfor i in range(len(categories)): print(f'\\033[1m{categories[i]}\\033[0m') for j in range(len(stats)): print(f'{stats_names[j]}: {stats[j][i]}') print('\\n')Output:DATASET 1Median: 52.6Mean: 52.2Minimum: -23.0Maximum: 125.8Q1: 32.3Q3: 70.6Lower outliers: [-33.8]Upper outliers: []DATASET 2Median: 100.4Mean: 102.3Minimum: -0.7Maximum: 185.5Q1: 75.7Q3: 131.9Lower outliers: [-11.3]Upper outliers: [221.2, 258.3]DATASET 3Median: 70.1Mean: 69.8Minimum: 47.0Maximum: 95.1Q1: 63.7Q3: 76.3Lower outliers: [42.1, 43.0, 39.5]Upper outliers: [103.2]" }, { "code": null, "e": 13017, "s": 12563, "text": "In this article, we’ve explored how to extract and print out the exact values of the descriptive statistics of a dataset from a boxplot created in the matplotlib library. Such statistical information can include the median, the mean, the minimum and maximum values without outliers, the first and third quartile, the lower and upper outliers. In some cases, this precise data can be a valuable supplement to the visual information from a boxplot itself." }, { "code": null, "e": 13037, "s": 13017, "text": "Thanks for reading!" } ]
Fine-Tuning “LaBSE” for a Sentiment Classification Task | by Vinura Dhananjaya | Towards Data Science
Some background Multilingual language models (let’s call “MLM”s) have been the trend in the world of NLP in recent times due to their ability to provide multilingual word embeddings (or sentence, document etc.) within a single model. “Pre-trained” is another term comes up along with MLMs, which tells that the models have been trained on large corpora in different domains, so that we do not have to train them again from the scratch, but we can “fine-tune” them for a desired target task while making use of the “knowledge-transfer (transfer learning)” from the pre-trained knowledge. MLMs have been released to the public use mainly by tech-giants such as Google, Facebook, Baidu given that they have resources to train these large models having millions, billions and even trillions of parameters. LaBSE[1] is such a model released by Google, based on the BERT model. LaBSE or “Language-Agnostic BERT Sentence Embedding” was built focusing on Bi-text mining, sentence/embedding similarity tasks. It uses “Wordpiece” tokenization and it can produce sentence embeddings ([CLS] token’s embedding from the model’s final layer represents sentence embeddings) for 109 languages. Although, they have not reported the model’s performance on other downstream tasks such as Classification or Named Entity Recognition (NER) nor used for that kind of downstream tasks much. The architecture of the LaBSE is a ‘dual-encoder’ model (Bidirectional Dual Encoder with Additive Margin Softmax), which means it has two encoder blocks which are based on the ‘BERT-base’ model’s encoders. The two encoders encode source and target sentences separately and fed to a scoring function (cosine similarity) to rank their similarity. The training loss function of LaBSE is based on this scoring, which was mentioned earlier as “Additive Margin Softmax”. Setting things up (I would try to keep things simple while including the important points) The official or the original model of LaBSE was released to the “Tensorflow Hub” (https://www.tensorflow.org/hub/) by the authors, and I will be using it. The module is depended on Tensorflow (2.4.0+ would be great and I am using 2.5.0) There are other libraries that are required, and they can be installed using pip. NOTE: As of now (and as I am aware of) Conda environments do not work with tfhub models + GPU. If you try to use such setup, it would always (automatically) fall back to CPU versions of Tensorflow or throw errors. Hence, if a GPU is used, Conda should be out of the equation. (https://github.com/tensorflow/text/issues/644) First, there are some essential libraries to be installed, (I am using an Ubuntu machine) !pip install tensorflow-hub!pip install tensorflow-text # Needed for loading universal-sentence-encoder-cmlm/multilingual-preprocess!pip install tf-models-official And we can import them, import tensorflow as tfimport tensorflow_hub as hubimport tensorflow_text as text from official.nlp import optimization Obviously, you should import other common libraries as well, if needed (numpy, pandas, sklearn ) which I will not mention here. For the classification task we can use any labelled dataset of the pre-trained 109 languages (or unsupported ones too, it does not matter! but with some performance degradation). What we will be doing is a fine-tuning of the model, which is training the pre-trained model with an additional dataset (a smaller one, compared to the huge pre-trained dataset or corpora) such that the model is fine-tuned to our specific classification (or any other) task. As a starting point, we could use the IMDb movie reviews dataset. (https://ai.stanford.edu/~amaas/data/sentiment/). Hence, our task will become a “binary sentiment classification” task. The dataset consists of 25k training and 25k test data. !wget -c https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz -O — | tar -xzAUTOTUNE = tf.data.AUTOTUNEbatch_size = 32 #8 #16seed = 42raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/train’, batch_size=batch_size, validation_split=0.2, subset=’training’, seed=seed)class_names = raw_train_ds.class_namestrain_ds = raw_train_ds.cache().prefetch(buffer_size=AUTOTUNE)val_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/train’, batch_size=batch_size, validation_split=0.2, subset=’validation’, seed=seed)val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)test_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/test’, batch_size=batch_size)test_ds = test_ds.cache().prefetch(buffer_size=AUTOTUNE) We can use data pipelines for our input data, built with Tensorflow. (If an earlier version of TF is used, this feature might not be entirely or at least directly available.). Next, we need to “Pre-process” this data before feeding into the model we will be building. Afterwards, the pre-processed data can be encoded or embedded in a vector space. For that we can define below variables and we will use the version 2 of LaBSE (https://tfhub.dev/google/LaBSE/2, version 1 was the initial model released to the TFhub) tfhub_handle_preprocess=”https://tfhub.dev/google/universal-sentence-encoder-cmlm/multilingual-preprocess/2"tfhub_handle_encoder=”https://tfhub.dev/google/LaBSE/2" Building the model Next, we can build the model. Below, a function has been defined to build the model with some specific layers. def build_classifier_model(): text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=’text’) preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name=’preprocessing’) encoder_inputs = preprocessing_layer(text_input) encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name=’LaBSE_encoder’) outputs = encoder(encoder_inputs) net = outputs[‘pooled_output’] net = tf.keras.layers.Dropout(0.1)(net) net = tf.keras.layers.Dense(1, name=’classifier’)(net) return tf.keras.Model(text_input, net) You can notice there is the term ‘pooled_outputs’ in the model, which refers to the [CLS] token representation for sentences as mentioned earlier in the post. (The other form of output is ‘sequence_outputs’). The “trainable=True” parameter or flag on the encoder layer implies that, while fine-tuning with out dataset, we can update the weights of the original model’s weights/parameters as well. (which is also called “Global fine-tuning”). encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name=’LaBSE_encoder’)net = outputs[‘pooled_output’] If we want to keep the original model’s weights as they are, then it would be called a “Feature based fine-tuning” or ”Fixed dimensional method” (there are different terms in the literature). Furthermore, some additional layers are added after the encoder (Dropout and Dense) which acts as the classifier layer of the model. This is the combination found frequently in the literature for a classification like this. For the optimizer, Adam or AdamW (more) is preferred which we can set up like below. Based on the dataset or the task, the learning rate may be changed (lowered in most cases). Hyperparameter optimization methods which are already provided in Keras (https://keras.io/guides/keras_tuner/) or a service like “Wandb” (https://wandb.ai/site) can also be used to find the optimum parameters such as learning rate and the batch size. from tensorflow_addons.optimizers import AdamWstep = tf.Variable(0, trainable=False)schedule = tf.optimizers.schedules.PiecewiseConstantDecay( [1000], [5e-5,1e-5])lr = 1 * schedule(step)wd = lambda: 1e-6 * schedule(step)optimizer=AdamW(learning_rate=lr,weight_decay=wd) Next, the model can be compiled and trained with mode.fit() method. classifier_model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=optimizer, metrics=tf.keras.metrics.BinaryAccuracy(threshold=0.0))history = classifier_model.fit(train_ds,validation_data=val_ds, epochs=epochs, batch_size=32) The number of epochs could be set to 3, 4 or 5 which are usually sufficient. We could also include methods such as “Earlystopping” as well. It is not common to use “K-Fold cross validation” with models which are large like these. Instead, we could run this model multiple times with different random seeds for the input data selection. It is fairly easy to build, run and get results from the model. The trained model can be saved and used to predict new data etc. as usually done with Tensorflow models. In my opinion, the LaBSE model could be poor in tasks such as text classification like these, compared to models like XLM-R, perhaps due to the fact that LaBSE was originally built and trained for a bi-text mining or sentence similarity task and also more training-data (fine-tuning data) might be required for better results. LaBSE has not been used much for classification tasks in the literature either (according to my knowledge and the paper itself has 38 citations on Google Scholar). For the task here, I got accuracy, precision, recall and f1 scores slightly higher than 50%. This was done with some randomly chosen hyperparameters as well, hence the results might have been improved if the hyperparameters were changed/tuned as well. (Some similar work has been carried out with LaBSE version 1 (https://medium.com/swlh/language-agnostic-text-classification-with-labse-51a4f55dab77), but a much larger training dataset has been used.) Anyway, I’d like to hear the feedback, comments or other’s experience on this. So. feel free to comment your thoughts and suggestions. Thanks for reading!!! github.com References [1] — Language-agnostic BERT Sentence Embedding, Fangxiaoyu Feng, Yinfei Yang, Daniel Cer, Naveen Arivazhagan, Wei Wang, arXiv:2007.01852v1 [cs.CL]
[ { "code": null, "e": 188, "s": 172, "text": "Some background" }, { "code": null, "e": 1044, "s": 188, "text": "Multilingual language models (let’s call “MLM”s) have been the trend in the world of NLP in recent times due to their ability to provide multilingual word embeddings (or sentence, document etc.) within a single model. “Pre-trained” is another term comes up along with MLMs, which tells that the models have been trained on large corpora in different domains, so that we do not have to train them again from the scratch, but we can “fine-tune” them for a desired target task while making use of the “knowledge-transfer (transfer learning)” from the pre-trained knowledge. MLMs have been released to the public use mainly by tech-giants such as Google, Facebook, Baidu given that they have resources to train these large models having millions, billions and even trillions of parameters. LaBSE[1] is such a model released by Google, based on the BERT model." }, { "code": null, "e": 2003, "s": 1044, "text": "LaBSE or “Language-Agnostic BERT Sentence Embedding” was built focusing on Bi-text mining, sentence/embedding similarity tasks. It uses “Wordpiece” tokenization and it can produce sentence embeddings ([CLS] token’s embedding from the model’s final layer represents sentence embeddings) for 109 languages. Although, they have not reported the model’s performance on other downstream tasks such as Classification or Named Entity Recognition (NER) nor used for that kind of downstream tasks much. The architecture of the LaBSE is a ‘dual-encoder’ model (Bidirectional Dual Encoder with Additive Margin Softmax), which means it has two encoder blocks which are based on the ‘BERT-base’ model’s encoders. The two encoders encode source and target sentences separately and fed to a scoring function (cosine similarity) to rank their similarity. The training loss function of LaBSE is based on this scoring, which was mentioned earlier as “Additive Margin Softmax”." }, { "code": null, "e": 2021, "s": 2003, "text": "Setting things up" }, { "code": null, "e": 2413, "s": 2021, "text": "(I would try to keep things simple while including the important points) The official or the original model of LaBSE was released to the “Tensorflow Hub” (https://www.tensorflow.org/hub/) by the authors, and I will be using it. The module is depended on Tensorflow (2.4.0+ would be great and I am using 2.5.0) There are other libraries that are required, and they can be installed using pip." }, { "code": null, "e": 2737, "s": 2413, "text": "NOTE: As of now (and as I am aware of) Conda environments do not work with tfhub models + GPU. If you try to use such setup, it would always (automatically) fall back to CPU versions of Tensorflow or throw errors. Hence, if a GPU is used, Conda should be out of the equation. (https://github.com/tensorflow/text/issues/644)" }, { "code": null, "e": 2827, "s": 2737, "text": "First, there are some essential libraries to be installed, (I am using an Ubuntu machine)" }, { "code": null, "e": 2991, "s": 2827, "text": "!pip install tensorflow-hub!pip install tensorflow-text # Needed for loading universal-sentence-encoder-cmlm/multilingual-preprocess!pip install tf-models-official" }, { "code": null, "e": 3015, "s": 2991, "text": "And we can import them," }, { "code": null, "e": 3136, "s": 3015, "text": "import tensorflow as tfimport tensorflow_hub as hubimport tensorflow_text as text from official.nlp import optimization " }, { "code": null, "e": 3264, "s": 3136, "text": "Obviously, you should import other common libraries as well, if needed (numpy, pandas, sklearn ) which I will not mention here." }, { "code": null, "e": 3960, "s": 3264, "text": "For the classification task we can use any labelled dataset of the pre-trained 109 languages (or unsupported ones too, it does not matter! but with some performance degradation). What we will be doing is a fine-tuning of the model, which is training the pre-trained model with an additional dataset (a smaller one, compared to the huge pre-trained dataset or corpora) such that the model is fine-tuned to our specific classification (or any other) task. As a starting point, we could use the IMDb movie reviews dataset. (https://ai.stanford.edu/~amaas/data/sentiment/). Hence, our task will become a “binary sentiment classification” task. The dataset consists of 25k training and 25k test data." }, { "code": null, "e": 4728, "s": 3960, "text": "!wget -c https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz -O — | tar -xzAUTOTUNE = tf.data.AUTOTUNEbatch_size = 32 #8 #16seed = 42raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/train’, batch_size=batch_size, validation_split=0.2, subset=’training’, seed=seed)class_names = raw_train_ds.class_namestrain_ds = raw_train_ds.cache().prefetch(buffer_size=AUTOTUNE)val_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/train’, batch_size=batch_size, validation_split=0.2, subset=’validation’, seed=seed)val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)test_ds = tf.keras.preprocessing.text_dataset_from_directory( ‘aclImdb/test’, batch_size=batch_size)test_ds = test_ds.cache().prefetch(buffer_size=AUTOTUNE)" }, { "code": null, "e": 5245, "s": 4728, "text": "We can use data pipelines for our input data, built with Tensorflow. (If an earlier version of TF is used, this feature might not be entirely or at least directly available.). Next, we need to “Pre-process” this data before feeding into the model we will be building. Afterwards, the pre-processed data can be encoded or embedded in a vector space. For that we can define below variables and we will use the version 2 of LaBSE (https://tfhub.dev/google/LaBSE/2, version 1 was the initial model released to the TFhub)" }, { "code": null, "e": 5409, "s": 5245, "text": "tfhub_handle_preprocess=”https://tfhub.dev/google/universal-sentence-encoder-cmlm/multilingual-preprocess/2\"tfhub_handle_encoder=”https://tfhub.dev/google/LaBSE/2\"" }, { "code": null, "e": 5428, "s": 5409, "text": "Building the model" }, { "code": null, "e": 5539, "s": 5428, "text": "Next, we can build the model. Below, a function has been defined to build the model with some specific layers." }, { "code": null, "e": 6061, "s": 5539, "text": "def build_classifier_model(): text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=’text’) preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name=’preprocessing’) encoder_inputs = preprocessing_layer(text_input) encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name=’LaBSE_encoder’) outputs = encoder(encoder_inputs) net = outputs[‘pooled_output’] net = tf.keras.layers.Dropout(0.1)(net) net = tf.keras.layers.Dense(1, name=’classifier’)(net) return tf.keras.Model(text_input, net)" }, { "code": null, "e": 6503, "s": 6061, "text": "You can notice there is the term ‘pooled_outputs’ in the model, which refers to the [CLS] token representation for sentences as mentioned earlier in the post. (The other form of output is ‘sequence_outputs’). The “trainable=True” parameter or flag on the encoder layer implies that, while fine-tuning with out dataset, we can update the weights of the original model’s weights/parameters as well. (which is also called “Global fine-tuning”)." }, { "code": null, "e": 6618, "s": 6503, "text": "encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name=’LaBSE_encoder’)net = outputs[‘pooled_output’]" }, { "code": null, "e": 7034, "s": 6618, "text": "If we want to keep the original model’s weights as they are, then it would be called a “Feature based fine-tuning” or ”Fixed dimensional method” (there are different terms in the literature). Furthermore, some additional layers are added after the encoder (Dropout and Dense) which acts as the classifier layer of the model. This is the combination found frequently in the literature for a classification like this." }, { "code": null, "e": 7462, "s": 7034, "text": "For the optimizer, Adam or AdamW (more) is preferred which we can set up like below. Based on the dataset or the task, the learning rate may be changed (lowered in most cases). Hyperparameter optimization methods which are already provided in Keras (https://keras.io/guides/keras_tuner/) or a service like “Wandb” (https://wandb.ai/site) can also be used to find the optimum parameters such as learning rate and the batch size." }, { "code": null, "e": 7732, "s": 7462, "text": "from tensorflow_addons.optimizers import AdamWstep = tf.Variable(0, trainable=False)schedule = tf.optimizers.schedules.PiecewiseConstantDecay( [1000], [5e-5,1e-5])lr = 1 * schedule(step)wd = lambda: 1e-6 * schedule(step)optimizer=AdamW(learning_rate=lr,weight_decay=wd)" }, { "code": null, "e": 7800, "s": 7732, "text": "Next, the model can be compiled and trained with mode.fit() method." }, { "code": null, "e": 8084, "s": 7800, "text": "classifier_model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=optimizer, metrics=tf.keras.metrics.BinaryAccuracy(threshold=0.0))history = classifier_model.fit(train_ds,validation_data=val_ds, epochs=epochs, batch_size=32)" }, { "code": null, "e": 8589, "s": 8084, "text": "The number of epochs could be set to 3, 4 or 5 which are usually sufficient. We could also include methods such as “Earlystopping” as well. It is not common to use “K-Fold cross validation” with models which are large like these. Instead, we could run this model multiple times with different random seeds for the input data selection. It is fairly easy to build, run and get results from the model. The trained model can be saved and used to predict new data etc. as usually done with Tensorflow models." }, { "code": null, "e": 9533, "s": 8589, "text": "In my opinion, the LaBSE model could be poor in tasks such as text classification like these, compared to models like XLM-R, perhaps due to the fact that LaBSE was originally built and trained for a bi-text mining or sentence similarity task and also more training-data (fine-tuning data) might be required for better results. LaBSE has not been used much for classification tasks in the literature either (according to my knowledge and the paper itself has 38 citations on Google Scholar). For the task here, I got accuracy, precision, recall and f1 scores slightly higher than 50%. This was done with some randomly chosen hyperparameters as well, hence the results might have been improved if the hyperparameters were changed/tuned as well. (Some similar work has been carried out with LaBSE version 1 (https://medium.com/swlh/language-agnostic-text-classification-with-labse-51a4f55dab77), but a much larger training dataset has been used.)" }, { "code": null, "e": 9690, "s": 9533, "text": "Anyway, I’d like to hear the feedback, comments or other’s experience on this. So. feel free to comment your thoughts and suggestions. Thanks for reading!!!" }, { "code": null, "e": 9701, "s": 9690, "text": "github.com" }, { "code": null, "e": 9712, "s": 9701, "text": "References" } ]
Where to use #region directive in C#?
It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. It should be terminated with #endregion. Let us see how to define a region using #region. #region NewClass definition public class NewClass { static void Main() { } } #endregion The following is an example showing the usage of #region directive. Live Demo using System; #region class MyClass { } #endregion class Demo { #region VARIABLE int a; #endregion static void Main() { #region BODY Console.WriteLine("Example showing the usage of region directive!"); #endregion } } Example showing the usage of region directive!
[ { "code": null, "e": 1238, "s": 1062, "text": "It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. It should be terminated with #endregion." }, { "code": null, "e": 1287, "s": 1238, "text": "Let us see how to define a region using #region." }, { "code": null, "e": 1378, "s": 1287, "text": "#region NewClass definition\npublic class NewClass {\n static void Main() { }\n}\n#endregion" }, { "code": null, "e": 1446, "s": 1378, "text": "The following is an example showing the usage of #region directive." }, { "code": null, "e": 1457, "s": 1446, "text": " Live Demo" }, { "code": null, "e": 1708, "s": 1457, "text": "using System;\n#region\nclass MyClass {\n}\n\n#endregion\nclass Demo {\n #region VARIABLE\n int a;\n #endregion\n static void Main() {\n #region BODY\n Console.WriteLine(\"Example showing the usage of region directive!\");\n #endregion\n }\n}" }, { "code": null, "e": 1755, "s": 1708, "text": "Example showing the usage of region directive!" } ]
Java Examples - Display text in a rectangle
How to display string in a rectangle? Following example demonstrates how to display each character in a rectangle by drawing a rectangle around each character using drawRect() method. import java.awt.*; import javax.swing.*; public class Main extends JPanel { public void paint(Graphics g) { g.setFont(new Font("",0,100)); FontMetrics fm = getFontMetrics(new Font("",0,100)); String s = "message"; int x = 5; int y = 5; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int h = fm.getHeight(); int w = fm.charWidth(c); g.drawRect(x, y, w, h); g.drawString(String.valueOf(c), x, y + h); x = x + w; } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new Main()); frame.setSize(500, 700); frame.setVisible(true); } } The above code sample will produce the following result. Each character is displayed in a rectangle. The following is an another sample example to display string in a rectangle. import java.awt.Color; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; class MyCanvas extends JComponent { String s = "message"; int x = 45; int y = 45; public void paint(Graphics g) { g.drawRect (10, 10, 200, 200); g.setColor(Color.red); g.drawString(s, x, y); } } public class Panel { public static void main(String[] a) { JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(30, 30, 300, 300); window.getContentPane().add(new MyCanvas()); window.setVisible(true); } } The above code sample will produce the following result. Each character is displayed in a rectangle. Print Add Notes Bookmark this page
[ { "code": null, "e": 2106, "s": 2068, "text": "How to display string in a rectangle?" }, { "code": null, "e": 2252, "s": 2106, "text": "Following example demonstrates how to display each character in a rectangle by drawing a rectangle around each character using drawRect() method." }, { "code": null, "e": 3047, "s": 2252, "text": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Main extends JPanel {\n public void paint(Graphics g) {\n g.setFont(new Font(\"\",0,100));\n FontMetrics fm = getFontMetrics(new Font(\"\",0,100));\n String s = \"message\";\n int x = 5;\n int y = 5;\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n int h = fm.getHeight();\n int w = fm.charWidth(c);\n \n g.drawRect(x, y, w, h);\n g.drawString(String.valueOf(c), x, y + h);\n x = x + w;\n }\n }\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setContentPane(new Main());\n frame.setSize(500, 700);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 3104, "s": 3047, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3150, "s": 3104, "text": "Each character is displayed in a rectangle. \n" }, { "code": null, "e": 3227, "s": 3150, "text": "The following is an another sample example to display string in a rectangle." }, { "code": null, "e": 3853, "s": 3227, "text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\n\nclass MyCanvas extends JComponent {\n String s = \"message\";\n int x = 45;\n int y = 45;\n public void paint(Graphics g) {\n g.drawRect (10, 10, 200, 200);\n g.setColor(Color.red);\n g.drawString(s, x, y);\n }\n}\npublic class Panel {\n public static void main(String[] a) {\n JFrame window = new JFrame();\n window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n window.setBounds(30, 30, 300, 300);\n window.getContentPane().add(new MyCanvas());\n window.setVisible(true);\n }\n}" }, { "code": null, "e": 3910, "s": 3853, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3956, "s": 3910, "text": "Each character is displayed in a rectangle. \n" }, { "code": null, "e": 3963, "s": 3956, "text": " Print" }, { "code": null, "e": 3974, "s": 3963, "text": " Add Notes" } ]
groupmod - Unix, Linux Command
groupmod modify a group definition on the system groupmod [options] GROUP groupmodThe groupmod command modifies the definition of the specified GROUP by modifying the appropriate entry in the group database. The value of GID must be a non-negative decimal integer. This value must be unique, unless the -o option is used. Users who use the group as primary group will be updated to keep the group as their primary group. Any files that have the old group ID and must continue to belong to GROUP, must have their group ID changed manually. No checks will be performed with regard to the GID_MIN, GID_MAX, SYS_GID_MIN, or SYS_GID_MAX from /etc/login.defs. Example-1: To change the group "newgroup" to "oldgroup". # groupmod -n oldgroup newgroup output: # groupmod -n oldgroup newgroup # grep oldgroup /etc/groupoldgroup:x:9090: Example-2: To change groupid of group: # groupmod -g 777 oldgroup output: # grep oldgroup /etc/groupoldgroup:x:777: Example-3: To use same gid for multiple groups, use -o option #groupmod -g 777 newgroup output: ( both oldgroup and newgroup have same GID's) # grep oldgroup /etc/groupoldgroup:x:777: # grep newgroup /etc/groupoldgroup:x:777: 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10626, "s": 10577, "text": "groupmod modify a group definition on the system" }, { "code": null, "e": 10651, "s": 10626, "text": "groupmod [options] GROUP" }, { "code": null, "e": 10785, "s": 10651, "text": "groupmodThe groupmod command modifies the definition of the specified GROUP by modifying the appropriate entry in the group database." }, { "code": null, "e": 10999, "s": 10785, "text": "The value of GID must be a non-negative decimal integer. This value must be unique, unless the -o option is used.\nUsers who use the group as primary group will be updated to keep the group as their primary group.\n" }, { "code": null, "e": 11232, "s": 10999, "text": "Any files that have the old group ID and must continue to belong to GROUP, must have their group ID changed manually.\nNo checks will be performed with regard to the GID_MIN, GID_MAX, SYS_GID_MIN, or SYS_GID_MAX from /etc/login.defs." }, { "code": null, "e": 11243, "s": 11232, "text": "Example-1:" }, { "code": null, "e": 11289, "s": 11243, "text": "To change the group \"newgroup\" to \"oldgroup\"." }, { "code": null, "e": 11321, "s": 11289, "text": "# groupmod -n oldgroup newgroup" }, { "code": null, "e": 11329, "s": 11321, "text": "output:" }, { "code": null, "e": 11361, "s": 11329, "text": "# groupmod -n oldgroup newgroup" }, { "code": null, "e": 11404, "s": 11361, "text": "# grep oldgroup /etc/groupoldgroup:x:9090:" }, { "code": null, "e": 11415, "s": 11404, "text": "Example-2:" }, { "code": null, "e": 11443, "s": 11415, "text": "To change groupid of group:" }, { "code": null, "e": 11470, "s": 11443, "text": "# groupmod -g 777 oldgroup" }, { "code": null, "e": 11478, "s": 11470, "text": "output:" }, { "code": null, "e": 11520, "s": 11478, "text": "# grep oldgroup /etc/groupoldgroup:x:777:" }, { "code": null, "e": 11531, "s": 11520, "text": "Example-3:" }, { "code": null, "e": 11582, "s": 11531, "text": "To use same gid for multiple groups, use -o option" }, { "code": null, "e": 11608, "s": 11582, "text": "#groupmod -g 777 newgroup" }, { "code": null, "e": 11662, "s": 11608, "text": "output: ( both oldgroup and newgroup have same GID's)" }, { "code": null, "e": 11704, "s": 11662, "text": "# grep oldgroup /etc/groupoldgroup:x:777:" }, { "code": null, "e": 11746, "s": 11704, "text": "# grep newgroup /etc/groupoldgroup:x:777:" }, { "code": null, "e": 11781, "s": 11746, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11809, "s": 11781, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11843, "s": 11809, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11860, "s": 11843, "text": " Frahaan Hussain" }, { "code": null, "e": 11893, "s": 11860, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11904, "s": 11893, "text": " Pradeep D" }, { "code": null, "e": 11939, "s": 11904, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11955, "s": 11939, "text": " Musab Zayadneh" }, { "code": null, "e": 11988, "s": 11955, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 12000, "s": 11988, "text": " GUHARAJANM" }, { "code": null, "e": 12032, "s": 12000, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 12040, "s": 12032, "text": " Uplatz" }, { "code": null, "e": 12047, "s": 12040, "text": " Print" }, { "code": null, "e": 12058, "s": 12047, "text": " Add Notes" } ]
Count numbers having 0 as a digit in C++
We are provided a number N. The goal is to find the numbers that have 0 as digit and are in the range [1,N]. We will do this by traversing numbers from 10 to N ( no need to check from 1 to 9 ) and for each number we will check each digit using a while loop. If any digit is found as zero increment count and move to next number otherwise reduce the number by 10 to check digits until number is >0. Let’s understand with examples. Input N=11 Output Numbers from 1 to N with 0 as digit: 1 Explanation Starting from i=10 to i<=11 Only 10 has 0 as a digit. No need to check the range [1,9]. Input N=100 Output Numbers from 1 to N with 0 as digit: 10 Explanation 10, 20, 30, 40, 50, 60, 70, 80, 90, 100. Ten numbers have 0 as digits. We take an integer N. We take an integer N. Function haveZero(int n) takes n as parameter and returns count of numbers with 0 as digit Function haveZero(int n) takes n as parameter and returns count of numbers with 0 as digit Take the initial variable count as 0 for such numbers. Take the initial variable count as 0 for such numbers. Traverse range of numbers using for loop. i=10 to i=n Traverse range of numbers using for loop. i=10 to i=n Now for each number num=i, using while loop check if num%10==0, if false divide num by 10 and move to next digit until num>0 Now for each number num=i, using while loop check if num%10==0, if false divide num by 10 and move to next digit until num>0 If true stop further checking, increment count and break while loop. If true stop further checking, increment count and break while loop. At the end of all loops count will have a total numbers with 0 as digit between 1 to N. At the end of all loops count will have a total numbers with 0 as digit between 1 to N. Return the count as result. Return the count as result. Live Demo #include <bits/stdc++.h> using namespace std; int haveZero(int n){ int count = 0; for (int i = 1; i <= n; i++) { int num = i; while(num>1){ int digit=num%10; if (digit == 0){ count++; break; } else { num=num/10; } } } return count; } int main(){ int N = 200; cout <<"Numbers from 1 to N with 0 as digit: "<<haveZero(N); return 0; } If we run the above code it will generate the following output − Numbers from 1 to N with 0 as digit: 29
[ { "code": null, "e": 1171, "s": 1062, "text": "We are provided a number N. The goal is to find the numbers that have 0 as digit and are in the range [1,N]." }, { "code": null, "e": 1460, "s": 1171, "text": "We will do this by traversing numbers from 10 to N ( no need to check from 1 to 9 ) and for each number we will check each digit using a while loop. If any digit is found as zero increment count and move to next number otherwise reduce the number by 10 to check digits until number is >0." }, { "code": null, "e": 1492, "s": 1460, "text": "Let’s understand with examples." }, { "code": null, "e": 1499, "s": 1492, "text": "Input " }, { "code": null, "e": 1504, "s": 1499, "text": "N=11" }, { "code": null, "e": 1512, "s": 1504, "text": "Output " }, { "code": null, "e": 1551, "s": 1512, "text": "Numbers from 1 to N with 0 as digit: 1" }, { "code": null, "e": 1564, "s": 1551, "text": "Explanation " }, { "code": null, "e": 1652, "s": 1564, "text": "Starting from i=10 to i<=11\nOnly 10 has 0 as a digit. No need to check the range [1,9]." }, { "code": null, "e": 1659, "s": 1652, "text": "Input " }, { "code": null, "e": 1665, "s": 1659, "text": "N=100" }, { "code": null, "e": 1673, "s": 1665, "text": "Output " }, { "code": null, "e": 1713, "s": 1673, "text": "Numbers from 1 to N with 0 as digit: 10" }, { "code": null, "e": 1726, "s": 1713, "text": "Explanation " }, { "code": null, "e": 1797, "s": 1726, "text": "10, 20, 30, 40, 50, 60, 70, 80, 90, 100. Ten numbers have 0 as digits." }, { "code": null, "e": 1819, "s": 1797, "text": "We take an integer N." }, { "code": null, "e": 1841, "s": 1819, "text": "We take an integer N." }, { "code": null, "e": 1932, "s": 1841, "text": "Function haveZero(int n) takes n as parameter and returns count of numbers with 0 as digit" }, { "code": null, "e": 2023, "s": 1932, "text": "Function haveZero(int n) takes n as parameter and returns count of numbers with 0 as digit" }, { "code": null, "e": 2078, "s": 2023, "text": "Take the initial variable count as 0 for such numbers." }, { "code": null, "e": 2133, "s": 2078, "text": "Take the initial variable count as 0 for such numbers." }, { "code": null, "e": 2187, "s": 2133, "text": "Traverse range of numbers using for loop. i=10 to i=n" }, { "code": null, "e": 2241, "s": 2187, "text": "Traverse range of numbers using for loop. i=10 to i=n" }, { "code": null, "e": 2366, "s": 2241, "text": "Now for each number num=i, using while loop check if num%10==0, if false divide num by 10 and move to next digit until num>0" }, { "code": null, "e": 2491, "s": 2366, "text": "Now for each number num=i, using while loop check if num%10==0, if false divide num by 10 and move to next digit until num>0" }, { "code": null, "e": 2560, "s": 2491, "text": "If true stop further checking, increment count and break while loop." }, { "code": null, "e": 2629, "s": 2560, "text": "If true stop further checking, increment count and break while loop." }, { "code": null, "e": 2717, "s": 2629, "text": "At the end of all loops count will have a total numbers with 0 as digit between 1 to N." }, { "code": null, "e": 2805, "s": 2717, "text": "At the end of all loops count will have a total numbers with 0 as digit between 1 to N." }, { "code": null, "e": 2833, "s": 2805, "text": "Return the count as result." }, { "code": null, "e": 2861, "s": 2833, "text": "Return the count as result." }, { "code": null, "e": 2872, "s": 2861, "text": " Live Demo" }, { "code": null, "e": 3315, "s": 2872, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint haveZero(int n){\n int count = 0;\n for (int i = 1; i <= n; i++) {\n int num = i;\n while(num>1){\n int digit=num%10;\n if (digit == 0){\n count++;\n break;\n }\n else\n { num=num/10; }\n }\n }\n return count;\n}\nint main(){\n int N = 200;\n cout <<\"Numbers from 1 to N with 0 as digit: \"<<haveZero(N);\n return 0;\n}" }, { "code": null, "e": 3380, "s": 3315, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3420, "s": 3380, "text": "Numbers from 1 to N with 0 as digit: 29" } ]
How to set background image in HTML ? - GeeksforGeeks
07 Apr, 2021 Background image which we see on some websites not only makes it look good but also enhances the user experience. The background image has the potential to tell the users about the theme of the website which makes the user stick to the website. Example: If you add a background image related to traveling to your website, it clearly tells the theme about the website and the user will explore it further. It’s like when you give a background image, it invites your users to explore some other site pages too. After reading this article you would be able to set a background image in a webpage by using only HTML and CSS. There are two methods for setting a background image in an HTML file: By using background attribute in the tag in HTML.By using Inline or Internal Style Sheet. By using background attribute in the tag in HTML. By using Inline or Internal Style Sheet. Method 1: By using background attribute in the tag in HTML Syntax: <body background = "image_name.extension"> Property value: It holds the file of an image that you want to use as the background image. Note: HTML 5 does not support the background attribute in the <body> tag, so we have to use CSS to add the background image to the webpage. Example: <!DOCTYPE html><html> <head> <title> HTML body Background Attribute </title></head> <!-- body tag starts here --><body background="https://media.geeksforgeeks.org/wp-content/uploads/rk.png"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> background Attribute</h2> <a href="#"> It is a Computer Science portal For Geeks </a> </center></body><!-- body tag ends here --> </html> Output: Method 2: By using Inline or Internal Style Sheet, here we have to use the style attribute of HTML and background-image property of CSS. Syntax: <div style = "background-image: url('Image_name.extension');"> HTML <!DOCTYPE html><html> <head> <title> By using Inline CSS</title></head> <body style="background-image: url('image.png');"> <h2>Welcome To GFG</h2></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Basics HTML-Questions Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31392, "s": 31364, "text": "\n07 Apr, 2021" }, { "code": null, "e": 31902, "s": 31392, "text": "Background image which we see on some websites not only makes it look good but also enhances the user experience. The background image has the potential to tell the users about the theme of the website which makes the user stick to the website. Example: If you add a background image related to traveling to your website, it clearly tells the theme about the website and the user will explore it further. It’s like when you give a background image, it invites your users to explore some other site pages too. " }, { "code": null, "e": 32014, "s": 31902, "text": "After reading this article you would be able to set a background image in a webpage by using only HTML and CSS." }, { "code": null, "e": 32085, "s": 32014, "text": "There are two methods for setting a background image in an HTML file: " }, { "code": null, "e": 32175, "s": 32085, "text": "By using background attribute in the tag in HTML.By using Inline or Internal Style Sheet." }, { "code": null, "e": 32225, "s": 32175, "text": "By using background attribute in the tag in HTML." }, { "code": null, "e": 32266, "s": 32225, "text": "By using Inline or Internal Style Sheet." }, { "code": null, "e": 32325, "s": 32266, "text": "Method 1: By using background attribute in the tag in HTML" }, { "code": null, "e": 32333, "s": 32325, "text": "Syntax:" }, { "code": null, "e": 32376, "s": 32333, "text": "<body background = \"image_name.extension\">" }, { "code": null, "e": 32468, "s": 32376, "text": "Property value: It holds the file of an image that you want to use as the background image." }, { "code": null, "e": 32608, "s": 32468, "text": "Note: HTML 5 does not support the background attribute in the <body> tag, so we have to use CSS to add the background image to the webpage." }, { "code": null, "e": 32617, "s": 32608, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML body Background Attribute </title></head> <!-- body tag starts here --><body background=\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> background Attribute</h2> <a href=\"#\"> It is a Computer Science portal For Geeks </a> </center></body><!-- body tag ends here --> </html>", "e": 33071, "s": 32617, "text": null }, { "code": null, "e": 33079, "s": 33071, "text": "Output:" }, { "code": null, "e": 33216, "s": 33079, "text": "Method 2: By using Inline or Internal Style Sheet, here we have to use the style attribute of HTML and background-image property of CSS." }, { "code": null, "e": 33224, "s": 33216, "text": "Syntax:" }, { "code": null, "e": 33287, "s": 33224, "text": "<div style = \"background-image: url('Image_name.extension');\">" }, { "code": null, "e": 33292, "s": 33287, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> By using Inline CSS</title></head> <body style=\"background-image: url('image.png');\"> <h2>Welcome To GFG</h2></body> </html>", "e": 33463, "s": 33292, "text": null }, { "code": null, "e": 33471, "s": 33463, "text": "Output:" }, { "code": null, "e": 33608, "s": 33471, "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": 33620, "s": 33608, "text": "HTML-Basics" }, { "code": null, "e": 33635, "s": 33620, "text": "HTML-Questions" }, { "code": null, "e": 33642, "s": 33635, "text": "Picked" }, { "code": null, "e": 33647, "s": 33642, "text": "HTML" }, { "code": null, "e": 33664, "s": 33647, "text": "Web Technologies" }, { "code": null, "e": 33669, "s": 33664, "text": "HTML" }, { "code": null, "e": 33767, "s": 33669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33776, "s": 33767, "text": "Comments" }, { "code": null, "e": 33789, "s": 33776, "text": "Old Comments" }, { "code": null, "e": 33851, "s": 33789, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33901, "s": 33851, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33961, "s": 33901, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34009, "s": 33961, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34070, "s": 34009, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34126, "s": 34070, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 34159, "s": 34126, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34221, "s": 34159, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34264, "s": 34221, "text": "How to fetch data from an API in ReactJS ?" } ]
ChainMap in Python - GeeksforGeeks
28 Jun, 2021 Python contains a container called “ChainMap” which encapsulates many dictionaries into one unit. ChainMap is member of module “collections“. Example: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c) Output: ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}) Let’s see various Operations on ChainMap keys() :- This function is used to display all the keys of all the dictionaries in ChainMap. values() :- This function is used to display values of all the dictionaries in ChainMap. maps() :- This function is used to display keys with corresponding values of all the dictionaries in ChainMap. # Please select Python 3 for running this code in IDE# Python code to demonstrate ChainMap and# keys(), values() and maps # importing collections for ChainMap operationsimport collections # initializing dictionariesdic1 = { 'a' : 1, 'b' : 2 }dic2 = { 'b' : 3, 'c' : 4 } # initializing ChainMapchain = collections.ChainMap(dic1, dic2) # printing chainMap using mapsprint ("All the ChainMap contents are : ")print (chain.maps) # printing keys using keys()print ("All keys of ChainMap are : ")print (list(chain.keys())) # printing keys using keys()print ("All values of ChainMap are : ")print (list(chain.values())) Output : All the ChainMap contents are : [{'b': 2, 'a': 1}, {'c': 4, 'b': 3}] All keys of ChainMap are : ['a', 'c', 'b'] All values of ChainMap are : [1, 4, 2] Note : Notice the key named “b” exists in both dictionaries, but only first dictionary key is taken as key value of “b”. Ordering is done as the dictionaries are passed in function. new_child() :- This function adds a new dictionary in the beginning of the ChainMap. reversed() :- This function reverses the relative ordering of dictionaries in the ChainMap. # Please select Python 3 for running this code in IDE# Python code to demonstrate ChainMap and# reversed() and new_child() # importing collections for ChainMap operationsimport collections # initializing dictionariesdic1 = { 'a' : 1, 'b' : 2 }dic2 = { 'b' : 3, 'c' : 4 }dic3 = { 'f' : 5 } # initializing ChainMapchain = collections.ChainMap(dic1, dic2) # printing chainMap using mapprint ("All the ChainMap contents are : ")print (chain.maps) # using new_child() to add new dictionarychain1 = chain.new_child(dic3) # printing chainMap using mapprint ("Displaying new ChainMap : ")print (chain1.maps) # displaying value associated with b before reversingprint ("Value associated with b before reversing is : ",end="")print (chain1['b']) # reversing the ChainMapchain1.maps = reversed(chain1.maps) # displaying value associated with b after reversingprint ("Value associated with b after reversing is : ",end="")print (chain1['b']) Output : All the ChainMap contents are : [{'b': 2, 'a': 1}, {'b': 3, 'c': 4}] Displaying new ChainMap : [{'f': 5}, {'b': 2, 'a': 1}, {'b': 3, 'c': 4}] Value associated with b before reversing is : 2 Value associated with b after reversing is : 3 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python collections-module Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42677, "s": 42649, "text": "\n28 Jun, 2021" }, { "code": null, "e": 42819, "s": 42677, "text": "Python contains a container called “ChainMap” which encapsulates many dictionaries into one unit. ChainMap is member of module “collections“." }, { "code": null, "e": 42828, "s": 42819, "text": "Example:" }, { "code": "# Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c)", "e": 43072, "s": 42828, "text": null }, { "code": null, "e": 43080, "s": 43072, "text": "Output:" }, { "code": null, "e": 43144, "s": 43080, "text": "ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})\n" }, { "code": null, "e": 43185, "s": 43144, "text": "Let’s see various Operations on ChainMap" }, { "code": null, "e": 43278, "s": 43185, "text": "keys() :- This function is used to display all the keys of all the dictionaries in ChainMap." }, { "code": null, "e": 43367, "s": 43278, "text": "values() :- This function is used to display values of all the dictionaries in ChainMap." }, { "code": null, "e": 43478, "s": 43367, "text": "maps() :- This function is used to display keys with corresponding values of all the dictionaries in ChainMap." }, { "code": "# Please select Python 3 for running this code in IDE# Python code to demonstrate ChainMap and# keys(), values() and maps # importing collections for ChainMap operationsimport collections # initializing dictionariesdic1 = { 'a' : 1, 'b' : 2 }dic2 = { 'b' : 3, 'c' : 4 } # initializing ChainMapchain = collections.ChainMap(dic1, dic2) # printing chainMap using mapsprint (\"All the ChainMap contents are : \")print (chain.maps) # printing keys using keys()print (\"All keys of ChainMap are : \")print (list(chain.keys())) # printing keys using keys()print (\"All values of ChainMap are : \")print (list(chain.values()))", "e": 44097, "s": 43478, "text": null }, { "code": null, "e": 44106, "s": 44097, "text": "Output :" }, { "code": null, "e": 44261, "s": 44106, "text": "All the ChainMap contents are : \n[{'b': 2, 'a': 1}, {'c': 4, 'b': 3}]\nAll keys of ChainMap are : \n['a', 'c', 'b']\nAll values of ChainMap are : \n[1, 4, 2]\n" }, { "code": null, "e": 44445, "s": 44263, "text": "Note : Notice the key named “b” exists in both dictionaries, but only first dictionary key is taken as key value of “b”. Ordering is done as the dictionaries are passed in function." }, { "code": null, "e": 44530, "s": 44445, "text": "new_child() :- This function adds a new dictionary in the beginning of the ChainMap." }, { "code": null, "e": 44622, "s": 44530, "text": "reversed() :- This function reverses the relative ordering of dictionaries in the ChainMap." }, { "code": "# Please select Python 3 for running this code in IDE# Python code to demonstrate ChainMap and# reversed() and new_child() # importing collections for ChainMap operationsimport collections # initializing dictionariesdic1 = { 'a' : 1, 'b' : 2 }dic2 = { 'b' : 3, 'c' : 4 }dic3 = { 'f' : 5 } # initializing ChainMapchain = collections.ChainMap(dic1, dic2) # printing chainMap using mapprint (\"All the ChainMap contents are : \")print (chain.maps) # using new_child() to add new dictionarychain1 = chain.new_child(dic3) # printing chainMap using mapprint (\"Displaying new ChainMap : \")print (chain1.maps) # displaying value associated with b before reversingprint (\"Value associated with b before reversing is : \",end=\"\")print (chain1['b']) # reversing the ChainMapchain1.maps = reversed(chain1.maps) # displaying value associated with b after reversingprint (\"Value associated with b after reversing is : \",end=\"\")print (chain1['b'])", "e": 45561, "s": 44622, "text": null }, { "code": null, "e": 45570, "s": 45561, "text": "Output :" }, { "code": null, "e": 45810, "s": 45570, "text": "All the ChainMap contents are : \n[{'b': 2, 'a': 1}, {'b': 3, 'c': 4}]\nDisplaying new ChainMap : \n[{'f': 5}, {'b': 2, 'a': 1}, {'b': 3, 'c': 4}]\nValue associated with b before reversing is : 2\nValue associated with b after reversing is : 3\n" }, { "code": null, "e": 46109, "s": 45812, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 46234, "s": 46109, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 46260, "s": 46234, "text": "Python collections-module" }, { "code": null, "e": 46267, "s": 46260, "text": "Python" }, { "code": null, "e": 46286, "s": 46267, "text": "Technical Scripter" }, { "code": null, "e": 46384, "s": 46286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46412, "s": 46384, "text": "Read JSON file using Python" }, { "code": null, "e": 46462, "s": 46412, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 46484, "s": 46462, "text": "Python map() function" }, { "code": null, "e": 46528, "s": 46484, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 46563, "s": 46528, "text": "Read a file line by line in Python" }, { "code": null, "e": 46595, "s": 46563, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 46617, "s": 46595, "text": "Enumerate() in Python" }, { "code": null, "e": 46659, "s": 46617, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 46689, "s": 46659, "text": "Iterate over a list in Python" } ]
Java.util.LinkedList.get(), getFirst(), getLast() in Java - GeeksforGeeks
10 Jun, 2020 The conventional method allowing to get the element at particular index is get(). Though in LinkedList its never possible to achieve this without complete traversal, but this method allows the same. Three variants present, all of which are discussed in this article with Exceptions as well.1. get(int index) : This method returns the element at the specified position in this list. Declaration : public E get(int index) Parameters : index : index of the element to return Return Value : This method returns the element at the specified position in this list Exception IndexOutOfBoundsException : if the index is out of range // Java code to demonstrate the working// of get(int index) in linked listimport java.util.*;public class LinkedListget1 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add("Geeks"); list.add("4"); list.add("Geeks"); list.add("8"); // printing the whole list System.out.println("The elements in List are : " + list); // using get() to print element at index 3 // prints 8 System.out.println("Element at index 3 is : " + list.get(3)); }} Output : The elements in List are : [Geeks, 4, Geeks, 8] Element at index 3 is : 8 2. getFirst() : This method returns the first element in this list. Declaration : public E getFirst() Return Value : This method returns the first element in this list Exceptions : NoSuchElementException : if this list is empty // Java code to demonstrate the working// of getFirst() in linked listimport java.util.*;public class LinkedListget2 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add("Geeks"); list.add("4"); list.add("Geeks"); list.add("8"); // printing the whole list System.out.println("The elements in List are : " + list); // using get() to print element at first index // prints "Geeks" System.out.println("Element at 1st index is : " + list.getFirst()); }} Output : The elements in List are : [Geeks, 4, Geeks, 8] Element at 1st index is : Geeks 3. getLast() : This method returns the last element in this list. Declaration : public E getLast() Return Value : This method returns the last element in this list Exceptions : NoSuchElementException : if this list is empty // Java code to demonstrate the working// of getLast() in linked listimport java.util.*;public class LinkedListget3 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add("Geeks"); list.add("4"); list.add("Geeks"); list.add("8"); // printing the whole list System.out.println("The elements in List are : " + list); // using get() to print element at last index // prints "8" System.out.println("Element at last index is : " + list.getLast()); }} Output: The elements in List are : [Geeks, 4, Geeks, 8] Element at last index is : 8 1. IndexOutOfBoundException // Java code to demonstrate the Exceptions// of get()import java.util.*;public class LinkedListExcep1 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add("Geeks"); list.add("4"); list.add("Geeks"); list.add("8"); // Trying to get element at index 7 // throws exception System.out.println("The element at index 7 is : " + list.get(7)); }} Output : No Output Runtime Error : Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 4 at java.util.LinkedList.checkElementIndex(LinkedList.java:555) at java.util.LinkedList.get(LinkedList.java:476) at LinkedListExcep1.main(LinkedListExcep1.java:22) 2. NoSuchElementException // Java code to demonstrate the Exceptions// of getFirst()import java.util.*;public class LinkedListExcep2 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // Trying to get first element at index 7 // throws exception System.out.println("The first element of list is : " + list.getFirst()); }} Output : No Output Runtime Error : Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList.getFirst(LinkedList.java:244) at LinkedListExcep2.main(LinkedListExcep2.java:15) This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet Nitesh9390 Java - util package Java-Collections Java-Functions java-LinkedList Linked Lists Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25771, "s": 25743, "text": "\n10 Jun, 2020" }, { "code": null, "e": 26153, "s": 25771, "text": "The conventional method allowing to get the element at particular index is get(). Though in LinkedList its never possible to achieve this without complete traversal, but this method allows the same. Three variants present, all of which are discussed in this article with Exceptions as well.1. get(int index) : This method returns the element at the specified position in this list." }, { "code": null, "e": 26417, "s": 26153, "text": "Declaration : \n public E get(int index)\nParameters : \n index : index of the element to return\nReturn Value : \n This method returns the element at the specified position in this list\nException\n IndexOutOfBoundsException : if the index is out of range\n" }, { "code": "// Java code to demonstrate the working// of get(int index) in linked listimport java.util.*;public class LinkedListget1 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add(\"Geeks\"); list.add(\"4\"); list.add(\"Geeks\"); list.add(\"8\"); // printing the whole list System.out.println(\"The elements in List are : \" + list); // using get() to print element at index 3 // prints 8 System.out.println(\"Element at index 3 is : \" + list.get(3)); }}", "e": 27058, "s": 26417, "text": null }, { "code": null, "e": 27067, "s": 27058, "text": "Output :" }, { "code": null, "e": 27142, "s": 27067, "text": "The elements in List are : [Geeks, 4, Geeks, 8]\nElement at index 3 is : 8\n" }, { "code": null, "e": 27210, "s": 27142, "text": "2. getFirst() : This method returns the first element in this list." }, { "code": null, "e": 27387, "s": 27210, "text": "Declaration : \n public E getFirst()\nReturn Value : \n This method returns the first element in this list\nExceptions : \n NoSuchElementException : if this list is empty\n" }, { "code": "// Java code to demonstrate the working// of getFirst() in linked listimport java.util.*;public class LinkedListget2 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add(\"Geeks\"); list.add(\"4\"); list.add(\"Geeks\"); list.add(\"8\"); // printing the whole list System.out.println(\"The elements in List are : \" + list); // using get() to print element at first index // prints \"Geeks\" System.out.println(\"Element at 1st index is : \" + list.getFirst()); }}", "e": 28040, "s": 27387, "text": null }, { "code": null, "e": 28049, "s": 28040, "text": "Output :" }, { "code": null, "e": 28130, "s": 28049, "text": "The elements in List are : [Geeks, 4, Geeks, 8]\nElement at 1st index is : Geeks\n" }, { "code": null, "e": 28196, "s": 28130, "text": "3. getLast() : This method returns the last element in this list." }, { "code": null, "e": 28368, "s": 28196, "text": "Declaration : \n public E getLast()\nReturn Value : \n This method returns the last element in this list\nExceptions : \n NoSuchElementException : if this list is empty\n" }, { "code": "// Java code to demonstrate the working// of getLast() in linked listimport java.util.*;public class LinkedListget3 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add(\"Geeks\"); list.add(\"4\"); list.add(\"Geeks\"); list.add(\"8\"); // printing the whole list System.out.println(\"The elements in List are : \" + list); // using get() to print element at last index // prints \"8\" System.out.println(\"Element at last index is : \" + list.getLast()); }}", "e": 29015, "s": 28368, "text": null }, { "code": null, "e": 29023, "s": 29015, "text": "Output:" }, { "code": null, "e": 29101, "s": 29023, "text": "The elements in List are : [Geeks, 4, Geeks, 8]\nElement at last index is : 8\n" }, { "code": null, "e": 29129, "s": 29101, "text": "1. IndexOutOfBoundException" }, { "code": "// Java code to demonstrate the Exceptions// of get()import java.util.*;public class LinkedListExcep1 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // adding elements using add() list.add(\"Geeks\"); list.add(\"4\"); list.add(\"Geeks\"); list.add(\"8\"); // Trying to get element at index 7 // throws exception System.out.println(\"The element at index 7 is : \" + list.get(7)); }}", "e": 29655, "s": 29129, "text": null }, { "code": null, "e": 29664, "s": 29655, "text": "Output :" }, { "code": null, "e": 29675, "s": 29664, "text": "No Output\n" }, { "code": null, "e": 29691, "s": 29675, "text": "Runtime Error :" }, { "code": null, "e": 29949, "s": 29691, "text": "Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 7, Size: 4\n at java.util.LinkedList.checkElementIndex(LinkedList.java:555)\n at java.util.LinkedList.get(LinkedList.java:476)\n at LinkedListExcep1.main(LinkedListExcep1.java:22)\n" }, { "code": null, "e": 29975, "s": 29949, "text": "2. NoSuchElementException" }, { "code": "// Java code to demonstrate the Exceptions// of getFirst()import java.util.*;public class LinkedListExcep2 {public static void main(String[] args) { // declaring a LinkedList LinkedList<String> list = new LinkedList<String>(); // Trying to get first element at index 7 // throws exception System.out.println(\"The first element of list is : \" + list.getFirst()); }}", "e": 30383, "s": 29975, "text": null }, { "code": null, "e": 30392, "s": 30383, "text": "Output :" }, { "code": null, "e": 30403, "s": 30392, "text": "No Output\n" }, { "code": null, "e": 30419, "s": 30403, "text": "Runtime Error :" }, { "code": null, "e": 30593, "s": 30419, "text": "Exception in thread \"main\" java.util.NoSuchElementException\n at java.util.LinkedList.getFirst(LinkedList.java:244)\n at LinkedListExcep2.main(LinkedListExcep2.java:15)\n" }, { "code": null, "e": 31016, "s": 30593, "text": "This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31027, "s": 31016, "text": "nidhi_biet" }, { "code": null, "e": 31038, "s": 31027, "text": "Nitesh9390" }, { "code": null, "e": 31058, "s": 31038, "text": "Java - util package" }, { "code": null, "e": 31075, "s": 31058, "text": "Java-Collections" }, { "code": null, "e": 31090, "s": 31075, "text": "Java-Functions" }, { "code": null, "e": 31106, "s": 31090, "text": "java-LinkedList" }, { "code": null, "e": 31119, "s": 31106, "text": "Linked Lists" }, { "code": null, "e": 31124, "s": 31119, "text": "Java" }, { "code": null, "e": 31129, "s": 31124, "text": "Java" }, { "code": null, "e": 31146, "s": 31129, "text": "Java-Collections" }, { "code": null, "e": 31244, "s": 31146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31295, "s": 31244, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31325, "s": 31295, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31344, "s": 31325, "text": "Interfaces in Java" }, { "code": null, "e": 31359, "s": 31344, "text": "Stream In Java" }, { "code": null, "e": 31390, "s": 31359, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31422, "s": 31390, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31442, "s": 31422, "text": "Stack Class in Java" }, { "code": null, "e": 31474, "s": 31442, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31498, "s": 31474, "text": "Singleton Class in Java" } ]
tmpfile() function in C - GeeksforGeeks
04 Sep, 2017 In C Programming Language, the tmpfile() function is used to produce/create a temporary file. tmpfile() function is defined in the “stdio.h” header file. The created temporary file will automatically be deleted after the termination of program. It opens file in binary update mode i.e., wb+ mode. The syntax of tmpfile() function is:FILE *tmpfile(void) FILE *tmpfile(void) The tmpfile() function always returns a pointer after the creation of file to the temporary file. If by chance temporary file can not be created, then the tmpfile() function returns NULL pointer. // C program to demonstrate working of tmpfile()#include <stdio.h>int main(){ char str[] = "Hello GeeksforGeeks"; int i = 0; FILE* tmp = tmpfile(); if (tmp == NULL) { puts("Unable to create temp file"); return 0; } puts("Temporary file is created\n"); while (str[i] != '\0') { fputc(str[i], tmp); i++; } // rewind() function sets the file pointer // at the beginning of the stream. rewind(tmp); while (!feof(tmp)) putchar(fgetc(tmp));} Output: Temporary file is created Hello GeeksforGeeks This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-File Handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C rand() and srand() in C/C++ std::string class in C++ fork() in C Command line arguments in C/C++ Enumeration (or enum) in C Different methods to reverse a string in C/C++
[ { "code": null, "e": 25689, "s": 25661, "text": "\n04 Sep, 2017" }, { "code": null, "e": 25783, "s": 25689, "text": "In C Programming Language, the tmpfile() function is used to produce/create a temporary file." }, { "code": null, "e": 25843, "s": 25783, "text": "tmpfile() function is defined in the “stdio.h” header file." }, { "code": null, "e": 25934, "s": 25843, "text": "The created temporary file will automatically be deleted after the termination of program." }, { "code": null, "e": 25986, "s": 25934, "text": "It opens file in binary update mode i.e., wb+ mode." }, { "code": null, "e": 26043, "s": 25986, "text": "The syntax of tmpfile() function is:FILE *tmpfile(void) " }, { "code": null, "e": 26064, "s": 26043, "text": "FILE *tmpfile(void) " }, { "code": null, "e": 26260, "s": 26064, "text": "The tmpfile() function always returns a pointer after the creation of file to the temporary file. If by chance temporary file can not be created, then the tmpfile() function returns NULL pointer." }, { "code": "// C program to demonstrate working of tmpfile()#include <stdio.h>int main(){ char str[] = \"Hello GeeksforGeeks\"; int i = 0; FILE* tmp = tmpfile(); if (tmp == NULL) { puts(\"Unable to create temp file\"); return 0; } puts(\"Temporary file is created\\n\"); while (str[i] != '\\0') { fputc(str[i], tmp); i++; } // rewind() function sets the file pointer // at the beginning of the stream. rewind(tmp); while (!feof(tmp)) putchar(fgetc(tmp));}", "e": 26781, "s": 26260, "text": null }, { "code": null, "e": 26789, "s": 26781, "text": "Output:" }, { "code": null, "e": 26836, "s": 26789, "text": "Temporary file is created\nHello GeeksforGeeks\n" }, { "code": null, "e": 27142, "s": 26836, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27267, "s": 27142, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27283, "s": 27267, "text": "C-File Handling" }, { "code": null, "e": 27294, "s": 27283, "text": "C Language" }, { "code": null, "e": 27392, "s": 27294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27409, "s": 27392, "text": "Substring in C++" }, { "code": null, "e": 27444, "s": 27409, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27490, "s": 27444, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27512, "s": 27490, "text": "Function Pointer in C" }, { "code": null, "e": 27540, "s": 27512, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27565, "s": 27540, "text": "std::string class in C++" }, { "code": null, "e": 27577, "s": 27565, "text": "fork() in C" }, { "code": null, "e": 27609, "s": 27577, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27636, "s": 27609, "text": "Enumeration (or enum) in C" } ]
who command in Linux - GeeksforGeeks
18 Feb, 2021 who command is used to find out the following information :1. Time of last system boot2. Current run level of the system3. List of logged in users and more. Description : The who command is used to get information about currently logged in user on to system. Syntax : $who [options] [filename] Examples :1. The who command displays the following information for each user currently logged in to the system if no option is provided : Login name of the usersTerminal line numbersLogin time of the users in to systemRemote host name of the user Login name of the users Terminal line numbers Login time of the users in to system Remote host name of the user hduser@mahesh-Inspiron-3543:~$ who hduser tty7 2018-03-18 19:08 (:0) hduser@mahesh-Inspiron-3543:~$ 2. To display host name and user associated with standard input such as keyboard hduser@mahesh-Inspiron-3543:~$ who -m -H NAME LINE TIME COMMENT 3. To show all active processes which are spawned by INIT process hduser@mahesh-Inspiron-3543:~$ who -p -H NAME LINE TIME PID COMMENT 4. To show status of the users message as +, – or ? hduser@mahesh-Inspiron-3543:~$ who -T -H NAME LINE TIME COMMENT hduser + tty7 2018-03-18 19:08 (:0) 5. To show list of users logged in to system hduser@mahesh-Inspiron-3543:~$ who -u hduser tty7 2018-03-18 19:08 01:16 3357 (:0) 6. To show time of the system when it booted last time hduser@mahesh-Inspiron-3543:~$ who -b -H NAME LINE TIME PID COMMENT system boot 2018-03-18 19:07 7. To show details of all dead processes hduser@mahesh-Inspiron-3543:~$ who -d -H (NO dead process in this case) NAME LINE TIME IDLE PID COMMENT EXIT NAME LINE TIME IDLE PID COMMENT EXIT 8. To show system login process details hduser@mahesh-Inspiron-3543:~$ who -l -H NAME LINE TIME IDLE PID COMMENT LOGIN tty1 2018-03-18 19:07 3073 id=tty1 9. To count number of users logged on to system hduser@mahesh-Inspiron-3543:~$ who -q -H hduser # users=1 10. To display current run level of the system hduser@mahesh-Inspiron-3543:~$ who -r run-level 5 2018-03-18 19:07 11. To display all details of current logged in user hduser@mahesh-Inspiron-3543:~$ who -a system boot 2018-03-18 19:07 LOGIN tty1 2018-03-18 19:07 3073 id=tty1 run-level 5 2018-03-18 19:07 hduser + tty7 2018-03-18 19:08 01:13 3357 (:0) 12. To display system’s username hduser@mahesh-Inspiron-3543:~$ whoami hduser 13. To display list of users and their activities hduser@mahesh-Inspiron-3543:~$ w 20:39:20 up 1:32, 1 user, load average: 0.09, 0.06, 0.07 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT hduser tty7 :0 19:08 1:32m 38.95s 0.19s /sbin/upstart - 14. To display user identification information hduser@mahesh-Inspiron-3543:~$ id uid=1001(hduser) gid=1001(hadoop) groups=1001(hadoop), 27(sudo) Note : For more details, refer linux man page.YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy link11/36InfoShoppingTap 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 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Tail command in Linux with examples UDP Server-Client implementation in C
[ { "code": null, "e": 25881, "s": 25853, "text": "\n18 Feb, 2021" }, { "code": null, "e": 26038, "s": 25881, "text": "who command is used to find out the following information :1. Time of last system boot2. Current run level of the system3. List of logged in users and more." }, { "code": null, "e": 26140, "s": 26038, "text": "Description : The who command is used to get information about currently logged in user on to system." }, { "code": null, "e": 26176, "s": 26140, "text": "Syntax : $who [options] [filename] " }, { "code": null, "e": 26315, "s": 26176, "text": "Examples :1. The who command displays the following information for each user currently logged in to the system if no option is provided :" }, { "code": null, "e": 26424, "s": 26315, "text": "Login name of the usersTerminal line numbersLogin time of the users in to systemRemote host name of the user" }, { "code": null, "e": 26448, "s": 26424, "text": "Login name of the users" }, { "code": null, "e": 26470, "s": 26448, "text": "Terminal line numbers" }, { "code": null, "e": 26507, "s": 26470, "text": "Login time of the users in to system" }, { "code": null, "e": 26536, "s": 26507, "text": "Remote host name of the user" }, { "code": null, "e": 26648, "s": 26536, "text": "hduser@mahesh-Inspiron-3543:~$ who\nhduser tty7 2018-03-18 19:08 (:0)\nhduser@mahesh-Inspiron-3543:~$ \n" }, { "code": null, "e": 26729, "s": 26648, "text": "2. To display host name and user associated with standard input such as keyboard" }, { "code": null, "e": 26818, "s": 26729, "text": "hduser@mahesh-Inspiron-3543:~$ who -m -H\nNAME LINE TIME COMMENT\n" }, { "code": null, "e": 26884, "s": 26818, "text": "3. To show all active processes which are spawned by INIT process" }, { "code": null, "e": 26984, "s": 26884, "text": "hduser@mahesh-Inspiron-3543:~$ who -p -H\nNAME LINE TIME PID COMMENT\n" }, { "code": null, "e": 27036, "s": 26984, "text": "4. To show status of the users message as +, – or ?" }, { "code": null, "e": 27173, "s": 27036, "text": "hduser@mahesh-Inspiron-3543:~$ who -T -H\nNAME LINE TIME COMMENT\nhduser + tty7 2018-03-18 19:08 (:0)\n" }, { "code": null, "e": 27218, "s": 27173, "text": "5. To show list of users logged in to system" }, { "code": null, "e": 27319, "s": 27218, "text": "hduser@mahesh-Inspiron-3543:~$ who -u\nhduser tty7 2018-03-18 19:08 01:16 3357 (:0)\n" }, { "code": null, "e": 27374, "s": 27319, "text": "6. To show time of the system when it booted last time" }, { "code": null, "e": 27513, "s": 27374, "text": "hduser@mahesh-Inspiron-3543:~$ who -b -H\nNAME LINE TIME PID COMMENT\n system boot 2018-03-18 19:07\n" }, { "code": null, "e": 27554, "s": 27513, "text": "7. To show details of all dead processes" }, { "code": null, "e": 27770, "s": 27554, "text": "hduser@mahesh-Inspiron-3543:~$ who -d -H (NO dead process in this case)\nNAME LINE TIME IDLE PID COMMENT EXIT \nNAME LINE TIME IDLE PID COMMENT EXIT\n" }, { "code": null, "e": 27810, "s": 27770, "text": "8. To show system login process details" }, { "code": null, "e": 27982, "s": 27810, "text": "hduser@mahesh-Inspiron-3543:~$ who -l -H\nNAME LINE TIME IDLE PID COMMENT\nLOGIN tty1 2018-03-18 19:07 3073 id=tty1\n" }, { "code": null, "e": 28030, "s": 27982, "text": "9. To count number of users logged on to system" }, { "code": null, "e": 28089, "s": 28030, "text": "hduser@mahesh-Inspiron-3543:~$ who -q -H\nhduser\n# users=1\n" }, { "code": null, "e": 28136, "s": 28089, "text": "10. To display current run level of the system" }, { "code": null, "e": 28214, "s": 28136, "text": "hduser@mahesh-Inspiron-3543:~$ who -r\n run-level 5 2018-03-18 19:07\n" }, { "code": null, "e": 28267, "s": 28214, "text": "11. To display all details of current logged in user" }, { "code": null, "e": 28520, "s": 28267, "text": "hduser@mahesh-Inspiron-3543:~$ who -a\n system boot 2018-03-18 19:07\nLOGIN tty1 2018-03-18 19:07 3073 id=tty1\n run-level 5 2018-03-18 19:07\nhduser + tty7 2018-03-18 19:08 01:13 3357 (:0)\n\n" }, { "code": null, "e": 28553, "s": 28520, "text": "12. To display system’s username" }, { "code": null, "e": 28599, "s": 28553, "text": "hduser@mahesh-Inspiron-3543:~$ whoami\nhduser\n" }, { "code": null, "e": 28649, "s": 28599, "text": "13. To display list of users and their activities" }, { "code": null, "e": 28892, "s": 28649, "text": "hduser@mahesh-Inspiron-3543:~$ w\n 20:39:20 up 1:32, 1 user, load average: 0.09, 0.06, 0.07\nUSER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT\nhduser tty7 :0 19:08 1:32m 38.95s 0.19s /sbin/upstart -\n" }, { "code": null, "e": 28939, "s": 28892, "text": "14. To display user identification information" }, { "code": null, "e": 29038, "s": 28939, "text": "hduser@mahesh-Inspiron-3543:~$ id\nuid=1001(hduser) gid=1001(hadoop) groups=1001(hadoop), 27(sudo)\n" }, { "code": null, "e": 29937, "s": 29038, "text": "Note : For more details, refer linux man page.YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy link11/36InfoShoppingTap 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 / 2:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WnjofnvIIvg\" 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": 29951, "s": 29937, "text": "linux-command" }, { "code": null, "e": 29973, "s": 29951, "text": "Linux-system-commands" }, { "code": null, "e": 29984, "s": 29973, "text": "Linux-Unix" }, { "code": null, "e": 30082, "s": 29984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30117, "s": 30082, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 30155, "s": 30117, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30196, "s": 30155, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 30231, "s": 30196, "text": "tar command in Linux with examples" }, { "code": null, "e": 30267, "s": 30231, "text": "curl command in Linux with Examples" }, { "code": null, "e": 30305, "s": 30267, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 30338, "s": 30305, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 30374, "s": 30338, "text": "diff command in Linux with examples" }, { "code": null, "e": 30410, "s": 30374, "text": "Tail command in Linux with examples" } ]
Laravel | Blade Templates Inheritance - GeeksforGeeks
22 Nov, 2019 A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *.blade.php. In Laravel, most of the times frontend files are stored in resources/views directory. Blade files support PHP and are compiled into plain PHP and cached in the server so that we don’t have to do the extra work of compiling the templates again when a user access a page again, thus using Blade is as efficient as using PHP files itself in the frontend. Template Inheritance: In most of the modern webpages, a fixed theme is followed in all the webpages. Thus it is greatly effective to be able to reuse your code so that you don’t have to write again the repeating parts in your code and Blade greatly helps you in achieving this. Defining a layout: Let’s do that with an example and create a file called layout.blade.php in resources/views directory as shown below:<!DOCTYPE html><html lang="en"><head> <title>@yield('title')</title></head><body> <div> @yield('content') </div></body></html>Now, in the code given above, we use @yield directive to tell the Blade that we are going to further extend this part in the child blade pages. Further, notice that each of yield directive is having a name like title for first one and content for second one. These names are going to be used later in the child page to tell that this section is extended here. <!DOCTYPE html><html lang="en"><head> <title>@yield('title')</title></head><body> <div> @yield('content') </div></body></html> Now, in the code given above, we use @yield directive to tell the Blade that we are going to further extend this part in the child blade pages. Further, notice that each of yield directive is having a name like title for first one and content for second one. These names are going to be used later in the child page to tell that this section is extended here. Extending a layout: Let’s do that too now and create a page at resources/views directory called mypage.blade.php as given below:@extends('layout') @section('title') Child Page@endsection @section('content') <h1>My first page with Blade Inheritance.</h1>@endsectionIn this code, we are first using the @extends directive which tells which blade page we are inheriting this page from. In our case, it is going to be layout as we are going to inherit this page from layout.blade.php, we created earlier. Further, we use the @section directive to extend each of the @yield directive’s of the parent blade file. We have to tell the name of each @yield directive we are extending here in the @section directive as we have done in code above. Make sure after writing the code you end the directive with @endsection. All the @yield sections will be replaced with the respective code in the child blade pages. One last thing left to make this work is adding a route as given below in your routes/web.php.Route::get('/mypage', function() { return view('mypage');});We just created a route to /mypage and in the callback function we are serving mypage.blade.php. Notice that Blade automatically looks for files in resources/views directory. @extends('layout') @section('title') Child Page@endsection @section('content') <h1>My first page with Blade Inheritance.</h1>@endsection In this code, we are first using the @extends directive which tells which blade page we are inheriting this page from. In our case, it is going to be layout as we are going to inherit this page from layout.blade.php, we created earlier. Further, we use the @section directive to extend each of the @yield directive’s of the parent blade file. We have to tell the name of each @yield directive we are extending here in the @section directive as we have done in code above. Make sure after writing the code you end the directive with @endsection. All the @yield sections will be replaced with the respective code in the child blade pages. One last thing left to make this work is adding a route as given below in your routes/web.php. Route::get('/mypage', function() { return view('mypage');}); We just created a route to /mypage and in the callback function we are serving mypage.blade.php. Notice that Blade automatically looks for files in resources/views directory. Output:In the output you can see how @yield(‘title’) is replaced with Child Page and @yield(‘content’) is replaced with My first page with Blade Inheritance. In the output you can see how @yield(‘title’) is replaced with Child Page and @yield(‘content’) is replaced with My first page with Blade Inheritance. Laravel PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26093, "s": 26065, "text": "\n22 Nov, 2019" }, { "code": null, "e": 26584, "s": 26093, "text": "A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *.blade.php. In Laravel, most of the times frontend files are stored in resources/views directory. Blade files support PHP and are compiled into plain PHP and cached in the server so that we don’t have to do the extra work of compiling the templates again when a user access a page again, thus using Blade is as efficient as using PHP files itself in the frontend." }, { "code": null, "e": 26862, "s": 26584, "text": "Template Inheritance: In most of the modern webpages, a fixed theme is followed in all the webpages. Thus it is greatly effective to be able to reuse your code so that you don’t have to write again the repeating parts in your code and Blade greatly helps you in achieving this." }, { "code": null, "e": 27499, "s": 26862, "text": "Defining a layout: Let’s do that with an example and create a file called layout.blade.php in resources/views directory as shown below:<!DOCTYPE html><html lang=\"en\"><head> <title>@yield('title')</title></head><body> <div> @yield('content') </div></body></html>Now, in the code given above, we use @yield directive to tell the Blade that we are going to further extend this part in the child blade pages. Further, notice that each of yield directive is having a name like title for first one and content for second one. These names are going to be used later in the child page to tell that this section is extended here." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>@yield('title')</title></head><body> <div> @yield('content') </div></body></html>", "e": 27642, "s": 27499, "text": null }, { "code": null, "e": 28002, "s": 27642, "text": "Now, in the code given above, we use @yield directive to tell the Blade that we are going to further extend this part in the child blade pages. Further, notice that each of yield directive is having a name like title for first one and content for second one. These names are going to be used later in the child page to tell that this section is extended here." }, { "code": null, "e": 29243, "s": 28002, "text": "Extending a layout: Let’s do that too now and create a page at resources/views directory called mypage.blade.php as given below:@extends('layout') @section('title') Child Page@endsection @section('content') <h1>My first page with Blade Inheritance.</h1>@endsectionIn this code, we are first using the @extends directive which tells which blade page we are inheriting this page from. In our case, it is going to be layout as we are going to inherit this page from layout.blade.php, we created earlier. Further, we use the @section directive to extend each of the @yield directive’s of the parent blade file. We have to tell the name of each @yield directive we are extending here in the @section directive as we have done in code above. Make sure after writing the code you end the directive with @endsection. All the @yield sections will be replaced with the respective code in the child blade pages. One last thing left to make this work is adding a route as given below in your routes/web.php.Route::get('/mypage', function() { return view('mypage');});We just created a route to /mypage and in the callback function we are serving mypage.blade.php. Notice that Blade automatically looks for files in resources/views directory." }, { "code": "@extends('layout') @section('title') Child Page@endsection @section('content') <h1>My first page with Blade Inheritance.</h1>@endsection", "e": 29388, "s": 29243, "text": null }, { "code": null, "e": 30120, "s": 29388, "text": "In this code, we are first using the @extends directive which tells which blade page we are inheriting this page from. In our case, it is going to be layout as we are going to inherit this page from layout.blade.php, we created earlier. Further, we use the @section directive to extend each of the @yield directive’s of the parent blade file. We have to tell the name of each @yield directive we are extending here in the @section directive as we have done in code above. Make sure after writing the code you end the directive with @endsection. All the @yield sections will be replaced with the respective code in the child blade pages. One last thing left to make this work is adding a route as given below in your routes/web.php." }, { "code": "Route::get('/mypage', function() { return view('mypage');});", "e": 30184, "s": 30120, "text": null }, { "code": null, "e": 30359, "s": 30184, "text": "We just created a route to /mypage and in the callback function we are serving mypage.blade.php. Notice that Blade automatically looks for files in resources/views directory." }, { "code": null, "e": 30517, "s": 30359, "text": "Output:In the output you can see how @yield(‘title’) is replaced with Child Page and @yield(‘content’) is replaced with My first page with Blade Inheritance." }, { "code": null, "e": 30668, "s": 30517, "text": "In the output you can see how @yield(‘title’) is replaced with Child Page and @yield(‘content’) is replaced with My first page with Blade Inheritance." }, { "code": null, "e": 30676, "s": 30668, "text": "Laravel" }, { "code": null, "e": 30680, "s": 30676, "text": "PHP" }, { "code": null, "e": 30697, "s": 30680, "text": "Web Technologies" }, { "code": null, "e": 30724, "s": 30697, "text": "Web technologies Questions" }, { "code": null, "e": 30728, "s": 30724, "text": "PHP" }, { "code": null, "e": 30826, "s": 30728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30876, "s": 30826, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30916, "s": 30876, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 30966, "s": 30916, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 31011, "s": 30966, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 31038, "s": 31011, "text": "Comparing two dates in PHP" }, { "code": null, "e": 31078, "s": 31038, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31111, "s": 31078, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31156, "s": 31111, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31199, "s": 31156, "text": "How to fetch data from an API in ReactJS ?" } ]
Flutter - Custom Widgets - GeeksforGeeks
12 Mar, 2021 We create Custom Widgets when we want a custom look and feel to our app, and we know that there will be a repetition of a particular widget. We can create the custom widget in a new dart file with all the codes and defining the parameters that we need in the constructor. For more on how to split widgets, you can visit the article on Flutter – Splitting App into Widgets Here we will be discussing an example of how to build a simple app by applying custom property to the widgets and making them separate from their own properties. We will be making a BMI Calculator App that takes height and weight to calculate the BMI of a person. To show how to use custom widgets we have also defined certain more things on the screen. Let us start by cleaning up the main.dart file as: Dart import 'package:custom_widget_demo/home.dart';import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GFG Custom Widget Demo', theme: ThemeData.dark(), home: Home(), ); }} As you can see that we have defined Home Screen to show all the components on the screen. Now as we have cleaned up the main file we will be creating a widgets directory and add three files namely custom_button.dart, custom_column.dart, and custom_container.dart files to this directory. We will be writing codes for our custom widgets in these files. Starting with the custom_container.dart file we will be writing the following code: Dart import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart'; class CustomContainer extends StatelessWidget { CustomContainer( {@required this.child, this.height, this.width, this.onTap, this.color}); final Function onTap; final Widget child; final double height; final double width; final Color color; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( height: height, width: width, padding: EdgeInsets.all(12), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.all(Radius.circular(8))), child: child, ), ); }} In this custom widget, we have created a Stateless CustomContainer widget which is basically a container with a rounded corner and an onTap property which we have implemented using the GestureDetector widget. We have defined the properties of the widgets as the onTap which accepts a function, a child property that accepts a Widget, a height, width, and finally a color property. We will see the usage of this in the Home Widget that we will be defined later. Moving on to our next Custom widget which we define in the custom_button.dart file that is simply a CustomButton widget which we define as follows – Dart import 'package:flutter/material.dart'; class CustomButton extends StatelessWidget { CustomButton({this.onTap, this.color = Colors.white30, this.icon}); final Function onTap; final Color color; final IconData icon; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( height: 50, width: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: color), child: Icon(icon), ), ); }} We have defined simply a Stateless widget which acts as a simple button that uses a GestureDetector to detect the functions and also accepts an icon as the child to be displayed inside the button. It is a rounded button with a fixed height and width. We can alter the color if we need it, but it already has a custom color of translucent white. Coming to our last widget that is simply a CustomColumn which we define in the custom_column.dart file as: Dart import 'package:flutter/material.dart'; class CustomColumn extends StatelessWidget { CustomColumn({this.text, this.child}); final String text; final Widget child; @override Widget build(BuildContext context) { return Column( children: [ Text( text, style: TextStyle(fontSize: 18), ), child ], ); }} This widget accepts a text and child as its properties displayed in the column. Now that all the components are ready we are going to write the code that is going to display all of our contents on the screen. All of the code from now on is part of the home.dart file that we define in the lib Dart import 'package:custom_widget_demo/widgets/custom_button.dart';import 'package:custom_widget_demo/widgets/custom_column.dart';import 'package:custom_widget_demo/widgets/custom_container.dart';import 'package:flutter/material.dart';import 'dart:math'; enum g { m, f } We import all of our custom widgets along with material and math.dart files. Apart from these we also created an enum for gender g. Dart class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { final activeColor = Colors.white30; final inactiveColor = Colors.white12; g isSelected; int height = 160; int weight = 60; int age = 25; String bmi = ''; The Home widget is a stateful widget, and we have all the properties like the activeColor, inactiveColor, the isSelected for gender selection, the height, weight, and son on for BMI calculation. Dart @overrideWidget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GFG Custom Widget'), ), body: SafeArea( child: Container( padding: EdgeInsets.all(12), child: Column( children: [ Row( children: [ Expanded( child: CustomContainer( color: isSelected == g.m ? activeColor : inactiveColor, onTap: () { setState(() { isSelected = g.m; }); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20.0), child: Text( 'FEMALE', textAlign: TextAlign.center, style: TextStyle(fontSize: 18), ), ), ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( color: isSelected == g.f ? activeColor : inactiveColor, onTap: () { setState(() { isSelected = g.f; }); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20.0), child: Text( 'MALE', textAlign: TextAlign.center, style: TextStyle(fontSize: 18), ), ), ), ), ], ), For the first part, we have defined a Scaffold under which we have defined an AppBar and then as a child, we have defined SafeArea. Now coming to the components we have defined a Column that contains all the components of the screen. The first child of the column is a row widget that contains two CustomContainer widgets with an onTap function to select the gender and change the color of the container as we do so. Dart SizedBox( height: 10, ), CustomContainer( color: inactiveColor, height: 100, child: CustomColumn( text: 'HEIGHT $height cm', child: SliderTheme( data: SliderTheme.of(context).copyWith( activeTrackColor: Colors.white, thumbColor: Colors.green, overlayColor: Color(0x2900ff00), thumbShape: RoundSliderThumbShape(enabledThumbRadius: 15.0), overlayShape: RoundSliderOverlayShape(overlayRadius: 25.0), ), child: Slider( value: height.toDouble(), min: 120.0, max: 220.0, onChanged: (double newValue) { setState(() { height = newValue.floor(); }); }, ), ), ), ), After giving some space we have again defined a CustomContainer with the inactive color with a CustomColumn which accepts the text as Height with dynamically changing heights with the help of the slider that we defined. We have provided custom properties to the slider to look and feel according to our app. Dart SizedBox( height: 10, ), Row( children: [ Expanded( child: CustomContainer( color: inactiveColor, child: CustomColumn( text: 'WEIGHT $weight', child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( onTap: () { setState(() { weight = weight - 1; }); }, icon: Icons.arrow_downward, ), SizedBox( width: 10, ), CustomButton( onTap: () { setState(() { weight = weight + 1; }); }, icon: Icons.arrow_upward, ) ], ), ), ), ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( color: inactiveColor, child: CustomColumn( text: 'AGE $age', child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( onTap: () { setState(() { age = age - 1; }); }, icon: Icons.arrow_downward, ), SizedBox( width: 10, ), CustomButton( onTap: () { setState(() { age = age + 1; }); }, icon: Icons.arrow_upward, ) ], ), ), ), ), ), ], ), Again After giving some space we defined a row with two CustomContainer which both accept a CustomColumn with the text as Weight and Age. Both of these containers has two buttons in a row as the child of the CustomColumn which we define. The functionality of these buttons is to increase or decrease the value of weight and age. Dart SizedBox( height: 10, ), Row( children: [ Expanded( child: CustomContainer( onTap: () { setState(() { bmi = ''; }); }, width: double.infinity, child: Text( 'CLEAR', style: TextStyle( fontSize: 18, ), textAlign: TextAlign.center, ), color: activeColor, ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( onTap: () { double _bmi = weight / pow(height / 100, 2); setState(() { bmi = _bmi.toStringAsFixed(1); }); }, width: double.infinity, child: Text( 'GET BMI', style: TextStyle( fontSize: 18, ), textAlign: TextAlign.center, ), color: Colors.green, ), ), ], ), Here we have defined two buttons with the help of our CustomContainer. The first one is used to clear the output that is displayed and the other one shows the output on the screen. Dart SizedBox( height: 10, ), Expanded( child: CustomContainer( width: double.infinity, child: Column( children: [ SizedBox( height: 20, ), Text( 'YOUR BMI IS', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox( height: 20, ), Text( bmi, style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold), ) ], ), color: inactiveColor, ), ), ], ), ), ), ); }} The last component of the App is also a CustomContainer which is used to display the calculated BMI on the Screen. This completes our app. Now you can run the app on your device. Output: Flutter-widgets Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25533, "s": 25261, "text": "We create Custom Widgets when we want a custom look and feel to our app, and we know that there will be a repetition of a particular widget. We can create the custom widget in a new dart file with all the codes and defining the parameters that we need in the constructor." }, { "code": null, "e": 25633, "s": 25533, "text": "For more on how to split widgets, you can visit the article on Flutter – Splitting App into Widgets" }, { "code": null, "e": 25987, "s": 25633, "text": "Here we will be discussing an example of how to build a simple app by applying custom property to the widgets and making them separate from their own properties. We will be making a BMI Calculator App that takes height and weight to calculate the BMI of a person. To show how to use custom widgets we have also defined certain more things on the screen." }, { "code": null, "e": 26038, "s": 25987, "text": "Let us start by cleaning up the main.dart file as:" }, { "code": null, "e": 26043, "s": 26038, "text": "Dart" }, { "code": "import 'package:custom_widget_demo/home.dart';import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GFG Custom Widget Demo', theme: ThemeData.dark(), home: Home(), ); }}", "e": 26464, "s": 26043, "text": null }, { "code": null, "e": 26816, "s": 26464, "text": "As you can see that we have defined Home Screen to show all the components on the screen. Now as we have cleaned up the main file we will be creating a widgets directory and add three files namely custom_button.dart, custom_column.dart, and custom_container.dart files to this directory. We will be writing codes for our custom widgets in these files." }, { "code": null, "e": 26900, "s": 26816, "text": "Starting with the custom_container.dart file we will be writing the following code:" }, { "code": null, "e": 26905, "s": 26900, "text": "Dart" }, { "code": "import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart'; class CustomContainer extends StatelessWidget { CustomContainer( {@required this.child, this.height, this.width, this.onTap, this.color}); final Function onTap; final Widget child; final double height; final double width; final Color color; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( height: height, width: width, padding: EdgeInsets.all(12), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.all(Radius.circular(8))), child: child, ), ); }}", "e": 27589, "s": 26905, "text": null }, { "code": null, "e": 28050, "s": 27589, "text": "In this custom widget, we have created a Stateless CustomContainer widget which is basically a container with a rounded corner and an onTap property which we have implemented using the GestureDetector widget. We have defined the properties of the widgets as the onTap which accepts a function, a child property that accepts a Widget, a height, width, and finally a color property. We will see the usage of this in the Home Widget that we will be defined later." }, { "code": null, "e": 28199, "s": 28050, "text": "Moving on to our next Custom widget which we define in the custom_button.dart file that is simply a CustomButton widget which we define as follows –" }, { "code": null, "e": 28204, "s": 28199, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class CustomButton extends StatelessWidget { CustomButton({this.onTap, this.color = Colors.white30, this.icon}); final Function onTap; final Color color; final IconData icon; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( height: 50, width: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: color), child: Icon(icon), ), ); }}", "e": 28724, "s": 28204, "text": null }, { "code": null, "e": 29070, "s": 28724, "text": "We have defined simply a Stateless widget which acts as a simple button that uses a GestureDetector to detect the functions and also accepts an icon as the child to be displayed inside the button. It is a rounded button with a fixed height and width. We can alter the color if we need it, but it already has a custom color of translucent white. " }, { "code": null, "e": 29177, "s": 29070, "text": "Coming to our last widget that is simply a CustomColumn which we define in the custom_column.dart file as:" }, { "code": null, "e": 29182, "s": 29177, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class CustomColumn extends StatelessWidget { CustomColumn({this.text, this.child}); final String text; final Widget child; @override Widget build(BuildContext context) { return Column( children: [ Text( text, style: TextStyle(fontSize: 18), ), child ], ); }}", "e": 29543, "s": 29182, "text": null }, { "code": null, "e": 29623, "s": 29543, "text": "This widget accepts a text and child as its properties displayed in the column." }, { "code": null, "e": 29836, "s": 29623, "text": "Now that all the components are ready we are going to write the code that is going to display all of our contents on the screen. All of the code from now on is part of the home.dart file that we define in the lib" }, { "code": null, "e": 29841, "s": 29836, "text": "Dart" }, { "code": "import 'package:custom_widget_demo/widgets/custom_button.dart';import 'package:custom_widget_demo/widgets/custom_column.dart';import 'package:custom_widget_demo/widgets/custom_container.dart';import 'package:flutter/material.dart';import 'dart:math'; enum g { m, f }", "e": 30109, "s": 29841, "text": null }, { "code": null, "e": 30241, "s": 30109, "text": "We import all of our custom widgets along with material and math.dart files. Apart from these we also created an enum for gender g." }, { "code": null, "e": 30246, "s": 30241, "text": "Dart" }, { "code": "class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { final activeColor = Colors.white30; final inactiveColor = Colors.white12; g isSelected; int height = 160; int weight = 60; int age = 25; String bmi = '';", "e": 30538, "s": 30246, "text": null }, { "code": null, "e": 30733, "s": 30538, "text": "The Home widget is a stateful widget, and we have all the properties like the activeColor, inactiveColor, the isSelected for gender selection, the height, weight, and son on for BMI calculation." }, { "code": null, "e": 30738, "s": 30733, "text": "Dart" }, { "code": "@overrideWidget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GFG Custom Widget'), ), body: SafeArea( child: Container( padding: EdgeInsets.all(12), child: Column( children: [ Row( children: [ Expanded( child: CustomContainer( color: isSelected == g.m ? activeColor : inactiveColor, onTap: () { setState(() { isSelected = g.m; }); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20.0), child: Text( 'FEMALE', textAlign: TextAlign.center, style: TextStyle(fontSize: 18), ), ), ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( color: isSelected == g.f ? activeColor : inactiveColor, onTap: () { setState(() { isSelected = g.f; }); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20.0), child: Text( 'MALE', textAlign: TextAlign.center, style: TextStyle(fontSize: 18), ), ), ), ), ], ),", "e": 32451, "s": 30738, "text": null }, { "code": null, "e": 32869, "s": 32451, "text": "For the first part, we have defined a Scaffold under which we have defined an AppBar and then as a child, we have defined SafeArea. Now coming to the components we have defined a Column that contains all the components of the screen. The first child of the column is a row widget that contains two CustomContainer widgets with an onTap function to select the gender and change the color of the container as we do so. " }, { "code": null, "e": 32874, "s": 32869, "text": "Dart" }, { "code": "SizedBox( height: 10, ), CustomContainer( color: inactiveColor, height: 100, child: CustomColumn( text: 'HEIGHT $height cm', child: SliderTheme( data: SliderTheme.of(context).copyWith( activeTrackColor: Colors.white, thumbColor: Colors.green, overlayColor: Color(0x2900ff00), thumbShape: RoundSliderThumbShape(enabledThumbRadius: 15.0), overlayShape: RoundSliderOverlayShape(overlayRadius: 25.0), ), child: Slider( value: height.toDouble(), min: 120.0, max: 220.0, onChanged: (double newValue) { setState(() { height = newValue.floor(); }); }, ), ), ), ),", "e": 33762, "s": 32874, "text": null }, { "code": null, "e": 34070, "s": 33762, "text": "After giving some space we have again defined a CustomContainer with the inactive color with a CustomColumn which accepts the text as Height with dynamically changing heights with the help of the slider that we defined. We have provided custom properties to the slider to look and feel according to our app." }, { "code": null, "e": 34075, "s": 34070, "text": "Dart" }, { "code": "SizedBox( height: 10, ), Row( children: [ Expanded( child: CustomContainer( color: inactiveColor, child: CustomColumn( text: 'WEIGHT $weight', child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( onTap: () { setState(() { weight = weight - 1; }); }, icon: Icons.arrow_downward, ), SizedBox( width: 10, ), CustomButton( onTap: () { setState(() { weight = weight + 1; }); }, icon: Icons.arrow_upward, ) ], ), ), ), ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( color: inactiveColor, child: CustomColumn( text: 'AGE $age', child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( onTap: () { setState(() { age = age - 1; }); }, icon: Icons.arrow_downward, ), SizedBox( width: 10, ), CustomButton( onTap: () { setState(() { age = age + 1; }); }, icon: Icons.arrow_upward, ) ], ), ), ), ), ), ], ),", "e": 36458, "s": 34075, "text": null }, { "code": null, "e": 36787, "s": 36458, "text": "Again After giving some space we defined a row with two CustomContainer which both accept a CustomColumn with the text as Weight and Age. Both of these containers has two buttons in a row as the child of the CustomColumn which we define. The functionality of these buttons is to increase or decrease the value of weight and age." }, { "code": null, "e": 36792, "s": 36787, "text": "Dart" }, { "code": "SizedBox( height: 10, ), Row( children: [ Expanded( child: CustomContainer( onTap: () { setState(() { bmi = ''; }); }, width: double.infinity, child: Text( 'CLEAR', style: TextStyle( fontSize: 18, ), textAlign: TextAlign.center, ), color: activeColor, ), ), SizedBox( width: 10, ), Expanded( child: CustomContainer( onTap: () { double _bmi = weight / pow(height / 100, 2); setState(() { bmi = _bmi.toStringAsFixed(1); }); }, width: double.infinity, child: Text( 'GET BMI', style: TextStyle( fontSize: 18, ), textAlign: TextAlign.center, ), color: Colors.green, ), ), ], ),", "e": 37930, "s": 36792, "text": null }, { "code": null, "e": 38111, "s": 37930, "text": "Here we have defined two buttons with the help of our CustomContainer. The first one is used to clear the output that is displayed and the other one shows the output on the screen." }, { "code": null, "e": 38116, "s": 38111, "text": "Dart" }, { "code": "SizedBox( height: 10, ), Expanded( child: CustomContainer( width: double.infinity, child: Column( children: [ SizedBox( height: 20, ), Text( 'YOUR BMI IS', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox( height: 20, ), Text( bmi, style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold), ) ], ), color: inactiveColor, ), ), ], ), ), ), ); }}", "e": 39076, "s": 38116, "text": null }, { "code": null, "e": 39255, "s": 39076, "text": "The last component of the App is also a CustomContainer which is used to display the calculated BMI on the Screen. This completes our app. Now you can run the app on your device." }, { "code": null, "e": 39263, "s": 39255, "text": "Output:" }, { "code": null, "e": 39279, "s": 39263, "text": "Flutter-widgets" }, { "code": null, "e": 39286, "s": 39279, "text": "Picked" }, { "code": null, "e": 39291, "s": 39286, "text": "Dart" }, { "code": null, "e": 39299, "s": 39291, "text": "Flutter" }, { "code": null, "e": 39397, "s": 39299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39436, "s": 39397, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 39462, "s": 39436, "text": "ListView Class in Flutter" }, { "code": null, "e": 39488, "s": 39462, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 39511, "s": 39488, "text": "Flutter - Stack Widget" }, { "code": null, "e": 39556, "s": 39511, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 39595, "s": 39556, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 39612, "s": 39595, "text": "Flutter Tutorial" }, { "code": null, "e": 39638, "s": 39612, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 39661, "s": 39638, "text": "Flutter - Stack Widget" } ]
How to close current tab in a browser window using JavaScript? - GeeksforGeeks
18 Oct, 2019 We are going to be looking at the method to close the current tab in a browser window using JavaScript. Earlier it used to happen that with a simple JavaScript function, the current tab used to get closed. The following syntax was used for this purpose. Syntax: window.close() But accounting for a security feature, which was introduced a few years ago, ordinary JavaScript lost its privilege to close the current tab, just by using this syntax. Note: A current window/tab will only get closed if and only if it was created & opened by that script.Means the window.close syntax is only allowed for the window/tab that is created & opened using window.open method. Example: This example shows how to open GeekForGeeks window and then close it. <!DOCTYPE html> <html><head> <style> body{ text-align:center; } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h2> <h4 style="color:purple">Close Tab/Window using JavaScript</h4> <button onclick="openWin()">Click to open GeeksforGeeks website</button> <button onclick="closeWin()">Click here to close the window</button> <script> var myGeeksforGeeksWindow; function openWin() { myGeeksforGeeksWindow = window .open("https://www.geeksforgeeks.org", "_blank", "width=786, height=786"); } function closeWin() { myGeeksforGeeksWindow.close(); } </script> </body> </html> Output:When we load the code: New Window/Tab gets opened up: The Window/Tab gets closed: The entire process: nidhi_biet JavaScript-Misc Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Node.js | fs.writeFileSync() Method How to Use the JavaScript Fetch API to Get Data? JavaScript | Promises How to get character array from string in JavaScript? Set the value of an input field in JavaScript
[ { "code": null, "e": 26187, "s": 26159, "text": "\n18 Oct, 2019" }, { "code": null, "e": 26441, "s": 26187, "text": "We are going to be looking at the method to close the current tab in a browser window using JavaScript. Earlier it used to happen that with a simple JavaScript function, the current tab used to get closed. The following syntax was used for this purpose." }, { "code": null, "e": 26449, "s": 26441, "text": "Syntax:" }, { "code": null, "e": 26464, "s": 26449, "text": "window.close()" }, { "code": null, "e": 26633, "s": 26464, "text": "But accounting for a security feature, which was introduced a few years ago, ordinary JavaScript lost its privilege to close the current tab, just by using this syntax." }, { "code": null, "e": 26851, "s": 26633, "text": "Note: A current window/tab will only get closed if and only if it was created & opened by that script.Means the window.close syntax is only allowed for the window/tab that is created & opened using window.open method." }, { "code": null, "e": 26930, "s": 26851, "text": "Example: This example shows how to open GeekForGeeks window and then close it." }, { "code": "<!DOCTYPE html> <html><head> <style> body{ text-align:center; } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <h4 style=\"color:purple\">Close Tab/Window using JavaScript</h4> <button onclick=\"openWin()\">Click to open GeeksforGeeks website</button> <button onclick=\"closeWin()\">Click here to close the window</button> <script> var myGeeksforGeeksWindow; function openWin() { myGeeksforGeeksWindow = window .open(\"https://www.geeksforgeeks.org\", \"_blank\", \"width=786, height=786\"); } function closeWin() { myGeeksforGeeksWindow.close(); } </script> </body> </html>", "e": 27654, "s": 26930, "text": null }, { "code": null, "e": 27684, "s": 27654, "text": "Output:When we load the code:" }, { "code": null, "e": 27715, "s": 27684, "text": "New Window/Tab gets opened up:" }, { "code": null, "e": 27743, "s": 27715, "text": "The Window/Tab gets closed:" }, { "code": null, "e": 27763, "s": 27743, "text": "The entire process:" }, { "code": null, "e": 27774, "s": 27763, "text": "nidhi_biet" }, { "code": null, "e": 27790, "s": 27774, "text": "JavaScript-Misc" }, { "code": null, "e": 27797, "s": 27790, "text": "Picked" }, { "code": null, "e": 27808, "s": 27797, "text": "JavaScript" }, { "code": null, "e": 27906, "s": 27808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27946, "s": 27906, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27991, "s": 27946, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28052, "s": 27991, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28124, "s": 28052, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28165, "s": 28124, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28201, "s": 28165, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 28250, "s": 28201, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 28272, "s": 28250, "text": "JavaScript | Promises" }, { "code": null, "e": 28326, "s": 28272, "text": "How to get character array from string in JavaScript?" } ]
Python | Ways to remove a key from dictionary - GeeksforGeeks
10 Nov, 2018 Dictionary is used in manifold practical applications such as day-day programming, web development and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting a dictionary key-value pair from a dictionary. Method 1 : Using del del keyword can be used to inplace delete the key that is present in the dictionary. One drawback that can be thought of using this is that is raises an exception if the key is not found and hence non-existence of key has to be handled.Code #1 : Demonstrating key-value pair deletion using del # Python code to demonstrate# removal of dict. pair # using del # Initializing dictionarytest_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21} # Printing dictionary before removalprint ("The dictionary before performing remove is : " + str(test_dict)) # Using del to remove a dict# removes Manidel test_dict['Mani'] # Printing dictionary after removalprint ("The dictionary after remove is : " + str(test_dict)) # Using del to remove a dict# raises exceptiondel test_dict['Manjeet'] Output : The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22} Exception : Traceback (most recent call last): File "/home/44db951e7011423359af4861d475458a.py", line 20, in del test_dict['Manjeet'] KeyError: 'Manjeet' Method 2 : Using pop() pop() can be used to delete a key and its value inplace. Advantage over using del is that it provides the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also returns the value of key that is being removed in addition to performing a simple delete operation.Code #2 : Demonstrating key-value pair deletion using pop() # Python code to demonstrate# removal of dict. pair # using pop() # Initializing dictionarytest_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21} # Printing dictionary before removalprint ("The dictionary before performing remove is : " + str(test_dict)) # Using pop() to remove a dict. pair# removes Maniremoved_value = test_dict.pop('Mani') # Printing dictionary after removalprint ("The dictionary after remove is : " + str(test_dict))print ("The removed key's value is : " + str(removed_value)) print ('\r') # Using pop() to remove a dict. pair# doesn't raise exception# assigns 'No Key found' to removed_valueremoved_value = test_dict.pop('Manjeet', 'No Key found') # Printing dictionary after removalprint ("The dictionary after remove is : " + str(test_dict))print ("The removed key's value is : " + str(removed_value)) Output : The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : 21 The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : No Key found Method 3 : Using items() + dict comprehension items() coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict. technique. Actually a new dict if created except for the key we don’t wish to include.Code #3 : Demonstrating key-value pair deletion using items() + dict. comprehension # Python code to demonstrate# removal of dict. pair # using items() + dict comprehension # Initializing dictionarytest_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21} # Printing dictionary before removalprint ("The dictionary before performing remove is : " + str(test_dict)) # Using items() + dict comprehension to remove a dict. pair# removes Maninew_dict = {key:val for key, val in test_dict.items() if key != 'Mani'} # Printing dictionary after removalprint ("The dictionary after remove is : " + str(new_dict)) Output : The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22} Python dictionary-programs python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25661, "s": 25633, "text": "\n10 Nov, 2018" }, { "code": null, "e": 26028, "s": 25661, "text": "Dictionary is used in manifold practical applications such as day-day programming, web development and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting a dictionary key-value pair from a dictionary." }, { "code": null, "e": 26049, "s": 26028, "text": "Method 1 : Using del" }, { "code": null, "e": 26343, "s": 26049, "text": "del keyword can be used to inplace delete the key that is present in the dictionary. One drawback that can be thought of using this is that is raises an exception if the key is not found and hence non-existence of key has to be handled.Code #1 : Demonstrating key-value pair deletion using del" }, { "code": "# Python code to demonstrate# removal of dict. pair # using del # Initializing dictionarytest_dict = {\"Arushi\" : 22, \"Anuradha\" : 21, \"Mani\" : 21, \"Haritha\" : 21} # Printing dictionary before removalprint (\"The dictionary before performing remove is : \" + str(test_dict)) # Using del to remove a dict# removes Manidel test_dict['Mani'] # Printing dictionary after removalprint (\"The dictionary after remove is : \" + str(test_dict)) # Using del to remove a dict# raises exceptiondel test_dict['Manjeet']", "e": 26851, "s": 26343, "text": null }, { "code": null, "e": 26860, "s": 26851, "text": "Output :" }, { "code": null, "e": 27043, "s": 26860, "text": "The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}\nThe dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}\n" }, { "code": null, "e": 27055, "s": 27043, "text": "Exception :" }, { "code": null, "e": 27205, "s": 27055, "text": "Traceback (most recent call last):\n File \"/home/44db951e7011423359af4861d475458a.py\", line 20, in \n del test_dict['Manjeet']\nKeyError: 'Manjeet'\n" }, { "code": null, "e": 27228, "s": 27205, "text": "Method 2 : Using pop()" }, { "code": null, "e": 27588, "s": 27228, "text": "pop() can be used to delete a key and its value inplace. Advantage over using del is that it provides the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also returns the value of key that is being removed in addition to performing a simple delete operation.Code #2 : Demonstrating key-value pair deletion using pop()" }, { "code": "# Python code to demonstrate# removal of dict. pair # using pop() # Initializing dictionarytest_dict = {\"Arushi\" : 22, \"Anuradha\" : 21, \"Mani\" : 21, \"Haritha\" : 21} # Printing dictionary before removalprint (\"The dictionary before performing remove is : \" + str(test_dict)) # Using pop() to remove a dict. pair# removes Maniremoved_value = test_dict.pop('Mani') # Printing dictionary after removalprint (\"The dictionary after remove is : \" + str(test_dict))print (\"The removed key's value is : \" + str(removed_value)) print ('\\r') # Using pop() to remove a dict. pair# doesn't raise exception# assigns 'No Key found' to removed_valueremoved_value = test_dict.pop('Manjeet', 'No Key found') # Printing dictionary after removalprint (\"The dictionary after remove is : \" + str(test_dict))print (\"The removed key's value is : \" + str(removed_value))", "e": 28441, "s": 27588, "text": null }, { "code": null, "e": 28450, "s": 28441, "text": "Output :" }, { "code": null, "e": 28787, "s": 28450, "text": "The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}\nThe dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}\nThe removed key's value is : 21\n\nThe dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}\nThe removed key's value is : No Key found\n" }, { "code": null, "e": 28833, "s": 28787, "text": "Method 3 : Using items() + dict comprehension" }, { "code": null, "e": 29151, "s": 28833, "text": "items() coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict. technique. Actually a new dict if created except for the key we don’t wish to include.Code #3 : Demonstrating key-value pair deletion using items() + dict. comprehension" }, { "code": "# Python code to demonstrate# removal of dict. pair # using items() + dict comprehension # Initializing dictionarytest_dict = {\"Arushi\" : 22, \"Anuradha\" : 21, \"Mani\" : 21, \"Haritha\" : 21} # Printing dictionary before removalprint (\"The dictionary before performing remove is : \" + str(test_dict)) # Using items() + dict comprehension to remove a dict. pair# removes Maninew_dict = {key:val for key, val in test_dict.items() if key != 'Mani'} # Printing dictionary after removalprint (\"The dictionary after remove is : \" + str(new_dict))", "e": 29692, "s": 29151, "text": null }, { "code": null, "e": 29701, "s": 29692, "text": "Output :" }, { "code": null, "e": 29884, "s": 29701, "text": "The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}\nThe dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}\n" }, { "code": null, "e": 29911, "s": 29884, "text": "Python dictionary-programs" }, { "code": null, "e": 29923, "s": 29911, "text": "python-dict" }, { "code": null, "e": 29930, "s": 29923, "text": "Python" }, { "code": null, "e": 29942, "s": 29930, "text": "python-dict" }, { "code": null, "e": 30040, "s": 29942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30075, "s": 30040, "text": "Read a file line by line in Python" }, { "code": null, "e": 30107, "s": 30075, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30129, "s": 30107, "text": "Enumerate() in Python" }, { "code": null, "e": 30171, "s": 30129, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30201, "s": 30171, "text": "Iterate over a list in Python" }, { "code": null, "e": 30227, "s": 30201, "text": "Python String | replace()" }, { "code": null, "e": 30256, "s": 30227, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30300, "s": 30256, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30337, "s": 30300, "text": "Create a Pandas DataFrame from Lists" } ]
Java Program for factorial of a number - GeeksforGeeks
20 Mar, 2018 Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Recursive : // Java program to find factorial of given numberclass Test{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // Driver method public static void main(String[] args) { int num = 5; System.out.println("Factorial of "+ num + " is " + factorial(5)); }} Iterative Solution: // Java program to find factorial of given numberclass Test{ // Method to find factorial of given number static int factorial(int n) { int res = 1, i; for (i=2; i<=n; i++) res *= i; return res; } // Driver method public static void main(String[] args) { int num = 5; System.out.println("Factorial of "+ num + " is " + factorial(5)); }} One line Solution (Using Ternary operator): // Java program to find factorial// of given numberclass Factorial { int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } // Driver Code public static void main(String args[]) { Factorial obj = new Factorial(); int num = 5; System.out.println("Factorial of " + num + " is " + obj.factorial(num)); }}// This code is contributed by Anshika Goyal. The above solutions cause overflow for small numbers. Please refer factorial of large number for a solution that works for large numbers. Please refer complete article on Program for factorial of a number for more details! factorial Java Programs factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Iterate through List in Java Program to print ASCII Value of a character Factory method design pattern in Java Java program to count the occurrence of each character in a string using Hashmap Java Program to Remove Duplicate Elements From the Array Traverse Through a HashMap in Java Min Heap in Java Iterate Over the Characters of a String in Java Remove first and last character of a string in Java
[ { "code": null, "e": 25849, "s": 25821, "text": "\n20 Mar, 2018" }, { "code": null, "e": 26004, "s": 25849, "text": "Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720." }, { "code": null, "e": 26016, "s": 26004, "text": "Recursive :" }, { "code": "// Java program to find factorial of given numberclass Test{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // Driver method public static void main(String[] args) { int num = 5; System.out.println(\"Factorial of \"+ num + \" is \" + factorial(5)); }}", "e": 26418, "s": 26016, "text": null }, { "code": null, "e": 26438, "s": 26418, "text": "Iterative Solution:" }, { "code": "// Java program to find factorial of given numberclass Test{ // Method to find factorial of given number static int factorial(int n) { int res = 1, i; for (i=2; i<=n; i++) res *= i; return res; } // Driver method public static void main(String[] args) { int num = 5; System.out.println(\"Factorial of \"+ num + \" is \" + factorial(5)); }}", "e": 26851, "s": 26438, "text": null }, { "code": null, "e": 26895, "s": 26851, "text": "One line Solution (Using Ternary operator):" }, { "code": "// Java program to find factorial// of given numberclass Factorial { int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } // Driver Code public static void main(String args[]) { Factorial obj = new Factorial(); int num = 5; System.out.println(\"Factorial of \" + num + \" is \" + obj.factorial(num)); }}// This code is contributed by Anshika Goyal.", "e": 27359, "s": 26895, "text": null }, { "code": null, "e": 27497, "s": 27359, "text": "The above solutions cause overflow for small numbers. Please refer factorial of large number for a solution that works for large numbers." }, { "code": null, "e": 27582, "s": 27497, "text": "Please refer complete article on Program for factorial of a number for more details!" }, { "code": null, "e": 27592, "s": 27582, "text": "factorial" }, { "code": null, "e": 27606, "s": 27592, "text": "Java Programs" }, { "code": null, "e": 27616, "s": 27606, "text": "factorial" }, { "code": null, "e": 27714, "s": 27616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27746, "s": 27714, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 27775, "s": 27746, "text": "Iterate through List in Java" }, { "code": null, "e": 27819, "s": 27775, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27857, "s": 27819, "text": "Factory method design pattern in Java" }, { "code": null, "e": 27938, "s": 27857, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 27995, "s": 27938, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 28030, "s": 27995, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 28047, "s": 28030, "text": "Min Heap in Java" }, { "code": null, "e": 28095, "s": 28047, "text": "Iterate Over the Characters of a String in Java" } ]
Get the first letter of each word in a string using regex in Java - GeeksforGeeks
11 Dec, 2018 Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it. \b[a-zA-Z] // Java program to demonstrate extracting first// letter of each word using Regeximport java.util.regex.Matcher;import java.util.regex.Pattern; public class Test{ static void printFirst(String s) { Pattern p = Pattern.compile("\\b[a-zA-Z]"); Matcher m = p.matcher(s); while (m.find()) System.out.print(m.group()); System.out.println(); } public static void main(String[] args) { String s1 = "Geeks for Geeks"; String s2 = "A Computer Science Portal for Geeks"; printFirst(s1); printFirst(s2); }} Output: GfG ACSPfG This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-regular-expression Java-String-Programs Java Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25861, "s": 25833, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26041, "s": 25861, "text": "Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z." }, { "code": null, "e": 26051, "s": 26041, "text": "Examples:" }, { "code": null, "e": 26132, "s": 26051, "text": "Input : Geeks for geeks\nOutput :Gfg\n \nInput : United Kingdom\nOutput : UK\n" }, { "code": null, "e": 26306, "s": 26132, "text": "Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it." }, { "code": null, "e": 26318, "s": 26306, "text": "\\b[a-zA-Z]\n" }, { "code": "// Java program to demonstrate extracting first// letter of each word using Regeximport java.util.regex.Matcher;import java.util.regex.Pattern; public class Test{ static void printFirst(String s) { Pattern p = Pattern.compile(\"\\\\b[a-zA-Z]\"); Matcher m = p.matcher(s); while (m.find()) System.out.print(m.group()); System.out.println(); } public static void main(String[] args) { String s1 = \"Geeks for Geeks\"; String s2 = \"A Computer Science Portal for Geeks\"; printFirst(s1); printFirst(s2); }}", "e": 26906, "s": 26318, "text": null }, { "code": null, "e": 26914, "s": 26906, "text": "Output:" }, { "code": null, "e": 26926, "s": 26914, "text": "GfG\nACSPfG\n" }, { "code": null, "e": 27228, "s": 26926, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27353, "s": 27228, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27377, "s": 27353, "text": "java-regular-expression" }, { "code": null, "e": 27398, "s": 27377, "text": "Java-String-Programs" }, { "code": null, "e": 27403, "s": 27398, "text": "Java" }, { "code": null, "e": 27411, "s": 27403, "text": "Strings" }, { "code": null, "e": 27419, "s": 27411, "text": "Strings" }, { "code": null, "e": 27424, "s": 27419, "text": "Java" }, { "code": null, "e": 27522, "s": 27424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27573, "s": 27522, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27603, "s": 27573, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27618, "s": 27603, "text": "Stream In Java" }, { "code": null, "e": 27637, "s": 27618, "text": "Interfaces in Java" }, { "code": null, "e": 27668, "s": 27637, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27714, "s": 27668, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27774, "s": 27714, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27789, "s": 27774, "text": "C++ Data Types" }, { "code": null, "e": 27823, "s": 27789, "text": "Longest Common Subsequence | DP-4" } ]
Extension Method in C# - GeeksforGeeks
01 May, 2019 In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0. Let us discuss this concept with the help of an example. Suppose you have a class or a structure which contains three methods and you want to add two new methods in this class or structure, you did not have the source code of the class/structure, or do not have permissions from the class/structure, or the class is a sealed class, but you still want to add new methods in it, then you can use the concept extension method to add the new method in the existing class/structure. Now you create a new class which is static and contain the two methods which you want to add in the existing class, now bind this class with the existing class. After binding you will see the existing class can access the two new added methods. As shown in the below program. Example: First we create a class named as Geek in Program1.cs file. It contains three methods that is M1(), M2(), and M3(). // C# program to illustrate the concept // of the extension methodsusing System; namespace ExtensionMethod { // Here Geek class contains three methods// Now we want to add two more new methods in it // Without re-compiling this classclass Geek { // Method 1 public void M1() { Console.WriteLine("Method Name: M1"); } // Method 2 public void M2() { Console.WriteLine("Method Name: M2"); } // Method 3 public void M3() { Console.WriteLine("Method Name: M3"); } } } Now we create a static class named as NewMethodClass in Program2.cs file. It contains two methods that are M4() and M5(). Now we want to add these methods in Geek class, so we use the binding parameter to bind these methods with Geek class. After that, we create another named as GFG in which Geek class access all the five methods. // C# program to illustrate the concept// of the extension methodsusing System; namespace ExtensionMethod { // This class contains M4 and M5 method// Which we want to add in Geek class.// NewMethodClass is a static classstatic class NewMethodClass { // Method 4 public static void M4(this Geek g) { Console.WriteLine("Method Name: M4"); } // Method 5 public static void M5(this Geek g, string str) { Console.WriteLine(str); }} // Now we create a new class in which// Geek class access all the five methodspublic class GFG { // Main Method public static void Main(string[] args) { Geek g = new Geek(); g.M1(); g.M2(); g.M3(); g.M4(); g.M5("Method Name: M5"); }}} Output: Method Name: M1 Method Name: M2 Method Name: M3 Method Name: M4 Method Name: M5 Important Points: Here, Binding parameters are those parameters which are used to bind the new method with the existing class or structure. It does not take any value when you are calling the extension method because they are used only for binding not for any other use. In the parameter list of the extension method binding parameter is always present at the first place if you write binding parameter to second, or third, or any other place rather than first place then the compiler will give an error. The binding parameter is created using this keyword followed by the name of the class in which you want to add a new method and the parameter name. For example:this Geek gHere, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name. this Geek g Here, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name. Extension methods are always defined as a static method, but when they are bound with any class or structure they will convert into non-static methods. When an extension method is defined with the same name and the signature of the existing method, then the compiler will print the existing method, not the extension method. Or in other words, the extension method does not support method overriding. You can also add new methods in the sealed class also using an extension method concept. It cannot apply to fields, properties, or events. It must be defined in top-level static class. Multiple binding parameters are not allowed means an extension method only contains a single binding parameter. But you can define one or more normal parameter in the extension method. Advantages: The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class. CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework C# | Arrays HashSet in C# with Examples C# | Encapsulation
[ { "code": null, "e": 25189, "s": 25161, "text": "\n01 May, 2019" }, { "code": null, "e": 25511, "s": 25189, "text": "In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0." }, { "code": null, "e": 26265, "s": 25511, "text": "Let us discuss this concept with the help of an example. Suppose you have a class or a structure which contains three methods and you want to add two new methods in this class or structure, you did not have the source code of the class/structure, or do not have permissions from the class/structure, or the class is a sealed class, but you still want to add new methods in it, then you can use the concept extension method to add the new method in the existing class/structure. Now you create a new class which is static and contain the two methods which you want to add in the existing class, now bind this class with the existing class. After binding you will see the existing class can access the two new added methods. As shown in the below program." }, { "code": null, "e": 26389, "s": 26265, "text": "Example: First we create a class named as Geek in Program1.cs file. It contains three methods that is M1(), M2(), and M3()." }, { "code": "// C# program to illustrate the concept // of the extension methodsusing System; namespace ExtensionMethod { // Here Geek class contains three methods// Now we want to add two more new methods in it // Without re-compiling this classclass Geek { // Method 1 public void M1() { Console.WriteLine(\"Method Name: M1\"); } // Method 2 public void M2() { Console.WriteLine(\"Method Name: M2\"); } // Method 3 public void M3() { Console.WriteLine(\"Method Name: M3\"); } } }", "e": 26901, "s": 26389, "text": null }, { "code": null, "e": 27234, "s": 26901, "text": "Now we create a static class named as NewMethodClass in Program2.cs file. It contains two methods that are M4() and M5(). Now we want to add these methods in Geek class, so we use the binding parameter to bind these methods with Geek class. After that, we create another named as GFG in which Geek class access all the five methods." }, { "code": "// C# program to illustrate the concept// of the extension methodsusing System; namespace ExtensionMethod { // This class contains M4 and M5 method// Which we want to add in Geek class.// NewMethodClass is a static classstatic class NewMethodClass { // Method 4 public static void M4(this Geek g) { Console.WriteLine(\"Method Name: M4\"); } // Method 5 public static void M5(this Geek g, string str) { Console.WriteLine(str); }} // Now we create a new class in which// Geek class access all the five methodspublic class GFG { // Main Method public static void Main(string[] args) { Geek g = new Geek(); g.M1(); g.M2(); g.M3(); g.M4(); g.M5(\"Method Name: M5\"); }}}", "e": 27997, "s": 27234, "text": null }, { "code": null, "e": 28005, "s": 27997, "text": "Output:" }, { "code": null, "e": 28086, "s": 28005, "text": "Method Name: M1\nMethod Name: M2\nMethod Name: M3\nMethod Name: M4\nMethod Name: M5\n" }, { "code": null, "e": 28104, "s": 28086, "text": "Important Points:" }, { "code": null, "e": 28881, "s": 28104, "text": "Here, Binding parameters are those parameters which are used to bind the new method with the existing class or structure. It does not take any value when you are calling the extension method because they are used only for binding not for any other use. In the parameter list of the extension method binding parameter is always present at the first place if you write binding parameter to second, or third, or any other place rather than first place then the compiler will give an error. The binding parameter is created using this keyword followed by the name of the class in which you want to add a new method and the parameter name. For example:this Geek gHere, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name." }, { "code": null, "e": 28893, "s": 28881, "text": "this Geek g" }, { "code": null, "e": 29012, "s": 28893, "text": "Here, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name." }, { "code": null, "e": 29164, "s": 29012, "text": "Extension methods are always defined as a static method, but when they are bound with any class or structure they will convert into non-static methods." }, { "code": null, "e": 29413, "s": 29164, "text": "When an extension method is defined with the same name and the signature of the existing method, then the compiler will print the existing method, not the extension method. Or in other words, the extension method does not support method overriding." }, { "code": null, "e": 29502, "s": 29413, "text": "You can also add new methods in the sealed class also using an extension method concept." }, { "code": null, "e": 29552, "s": 29502, "text": "It cannot apply to fields, properties, or events." }, { "code": null, "e": 29598, "s": 29552, "text": "It must be defined in top-level static class." }, { "code": null, "e": 29783, "s": 29598, "text": "Multiple binding parameters are not allowed means an extension method only contains a single binding parameter. But you can define one or more normal parameter in the extension method." }, { "code": null, "e": 29795, "s": 29783, "text": "Advantages:" }, { "code": null, "e": 29909, "s": 29795, "text": "The main advantage of the extension method is to add new methods in the existing class without using inheritance." }, { "code": null, "e": 30012, "s": 29909, "text": "You can add new methods in the existing class without modifying the source code of the existing class." }, { "code": null, "e": 30048, "s": 30012, "text": "It can also work with sealed class." }, { "code": null, "e": 30062, "s": 30048, "text": "CSharp-method" }, { "code": null, "e": 30065, "s": 30062, "text": "C#" }, { "code": null, "e": 30163, "s": 30065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30185, "s": 30163, "text": "C# | Abstract Classes" }, { "code": null, "e": 30231, "s": 30185, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30253, "s": 30231, "text": "C# | Class and Object" }, { "code": null, "e": 30271, "s": 30253, "text": "C# | Constructors" }, { "code": null, "e": 30311, "s": 30271, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 30333, "s": 30311, "text": "C# | Replace() Method" }, { "code": null, "e": 30364, "s": 30333, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30376, "s": 30364, "text": "C# | Arrays" }, { "code": null, "e": 30404, "s": 30376, "text": "HashSet in C# with Examples" } ]
PyQt5 QCalendarWidget - Getting Date Text Format - GeeksforGeeks
04 Jul, 2021 In this article, we will see how we can get the date text format to the specific date in the QCalendarWidget. Setting the date text format makes the specified date looks more special such as increasing the size and other features. Below is how a date with date text format looks like. In order to do this we will use dateTextFormat method with the QCalendarWidget object.Syntax : calendar.dateTextFormat()Argument : It takes no argumentReturn : It return dictionary where keys are QDate object and values are QTextCharFormat object Below is the implementation Python3 # 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, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calendar = QCalendarWidget(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # format format = QTextCharFormat() format.setFont(QFont('Times', 15)) # date date = QDate(2020, 6, 10) # setting date text format self.calendar.setDateTextFormat(date, format) # creating a label label = QLabel(self) # setting geometry label.setGeometry(50, 280, 420, 120) # making it multi line label.setWordWrap(True) # checking date text format value = self.calendar.dateTextFormat() # setting text to the label label.setText("Date Text format: " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : clintra Python PyQt-QCalendarWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Enumerate() in Python Python Dictionary Defaultdict in Python sum() function in Python Python String | replace() Read a file line by line in Python How to Install PIP on Windows ? Deque in Python Different ways to create Pandas Dataframe Iterate over a list in Python
[ { "code": null, "e": 26437, "s": 26409, "text": "\n04 Jul, 2021" }, { "code": null, "e": 26723, "s": 26437, "text": "In this article, we will see how we can get the date text format to the specific date in the QCalendarWidget. Setting the date text format makes the specified date looks more special such as increasing the size and other features. Below is how a date with date text format looks like. " }, { "code": null, "e": 26974, "s": 26725, "text": "In order to do this we will use dateTextFormat method with the QCalendarWidget object.Syntax : calendar.dateTextFormat()Argument : It takes no argumentReturn : It return dictionary where keys are QDate object and values are QTextCharFormat object " }, { "code": null, "e": 27004, "s": 26974, "text": "Below is the implementation " }, { "code": null, "e": 27012, "s": 27004, "text": "Python3" }, { "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, 650, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object self.calendar = QCalendarWidget(self) # setting geometry to the calendar self.calendar.setGeometry(50, 10, 400, 250) # setting cursor self.calendar.setCursor(Qt.PointingHandCursor) # format format = QTextCharFormat() format.setFont(QFont('Times', 15)) # date date = QDate(2020, 6, 10) # setting date text format self.calendar.setDateTextFormat(date, format) # creating a label label = QLabel(self) # setting geometry label.setGeometry(50, 280, 420, 120) # making it multi line label.setWordWrap(True) # checking date text format value = self.calendar.dateTextFormat() # setting text to the label label.setText(\"Date Text format: \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28517, "s": 27012, "text": null }, { "code": null, "e": 28528, "s": 28517, "text": "Output : " }, { "code": null, "e": 28538, "s": 28530, "text": "clintra" }, { "code": null, "e": 28566, "s": 28538, "text": "Python PyQt-QCalendarWidget" }, { "code": null, "e": 28577, "s": 28566, "text": "Python-gui" }, { "code": null, "e": 28589, "s": 28577, "text": "Python-PyQt" }, { "code": null, "e": 28596, "s": 28589, "text": "Python" }, { "code": null, "e": 28694, "s": 28596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28716, "s": 28694, "text": "Enumerate() in Python" }, { "code": null, "e": 28734, "s": 28716, "text": "Python Dictionary" }, { "code": null, "e": 28756, "s": 28734, "text": "Defaultdict in Python" }, { "code": null, "e": 28781, "s": 28756, "text": "sum() function in Python" }, { "code": null, "e": 28807, "s": 28781, "text": "Python String | replace()" }, { "code": null, "e": 28842, "s": 28807, "text": "Read a file line by line in Python" }, { "code": null, "e": 28874, "s": 28842, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28890, "s": 28874, "text": "Deque in Python" }, { "code": null, "e": 28932, "s": 28890, "text": "Different ways to create Pandas Dataframe" } ]
ReactJS className Attribute - GeeksforGeeks
25 May, 2021 React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the className attribute is used to set or return the value of an element’s class attribute. Using this property, the user can change the class of an element to the desired class. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'; // Defining our App Componentconst App = () => { // Function to get element by its className function getClassNameAttribute() { var element = document.getElementsByClassName('gfg'); // Printing the element console.log(element) } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div className='gfg'> ReactJS className Attribute </div> <button onClick={getClassNameAttribute}> click </button> </div> </>;} // Exporting your Default App Componentexport default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference:https://reactjs.org/docs/dom-elements.html#classname ReactJS Attributes ReactJS DOM Elements ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n25 May, 2021" }, { "code": null, "e": 26300, "s": 26071, "text": "React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component." }, { "code": null, "e": 26506, "s": 26300, "text": "In class-based components, the className attribute is used to set or return the value of an element’s class attribute. Using this property, the user can change the class of an element to the desired class." }, { "code": null, "e": 26556, "s": 26506, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26651, "s": 26556, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 26715, "s": 26651, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26747, "s": 26715, "text": "npx create-react-app foldername" }, { "code": null, "e": 26860, "s": 26747, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 26960, "s": 26860, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26974, "s": 26960, "text": "cd foldername" }, { "code": null, "e": 27026, "s": 26974, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27156, "s": 27026, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27163, "s": 27156, "text": "App.js" }, { "code": "import React from 'react'; // Defining our App Componentconst App = () => { // Function to get element by its className function getClassNameAttribute() { var element = document.getElementsByClassName('gfg'); // Printing the element console.log(element) } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div className='gfg'> ReactJS className Attribute </div> <button onClick={getClassNameAttribute}> click </button> </div> </>;} // Exporting your Default App Componentexport default App", "e": 27753, "s": 27163, "text": null }, { "code": null, "e": 27866, "s": 27753, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27876, "s": 27866, "text": "npm start" }, { "code": null, "e": 27975, "s": 27876, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28038, "s": 27975, "text": "Reference:https://reactjs.org/docs/dom-elements.html#classname" }, { "code": null, "e": 28057, "s": 28038, "text": "ReactJS Attributes" }, { "code": null, "e": 28078, "s": 28057, "text": "ReactJS DOM Elements" }, { "code": null, "e": 28086, "s": 28078, "text": "ReactJS" }, { "code": null, "e": 28103, "s": 28086, "text": "Web Technologies" }, { "code": null, "e": 28201, "s": 28103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28228, "s": 28201, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28270, "s": 28228, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28308, "s": 28270, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28343, "s": 28308, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28401, "s": 28343, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28441, "s": 28401, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28474, "s": 28441, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28519, "s": 28474, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28569, "s": 28519, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Node.js fs.fstat() Method - GeeksforGeeks
11 Oct, 2021 The fs.fstat() method is used to return information about the given file descriptor. The fs.Stat object returned has several fields and methods to get more details about the file. Syntax: fs.fstat( fd, options, callback ) Parameters: This method accepts three parameters as mentioned above and described below: fd: It is an integer which represents the file descriptor used by the method. options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the methodStats: It is the Stats object that contains the details of the file path. err: It is an error that would be thrown if the method Stats: It is the Stats object that contains the details of the file path. Below examples illustrate the fs.fstat() method in Node.js: Example 1: This example uses fs.fstat() method to get the details of a file and directory. // Node.js program to demonstrate the// fs.fstat() method // Import the filesystem moduleconst fs = require('fs'); // Define the file descriptor for a filelet file_fd = fs.openSync('example_file.txt', 'r'); // Getting information for a filefs.fstat(file_fd, (error, stats) => { if (error) { console.log(error); } else { console.log("Stats object for: example_file.txt"); console.log(stats); // Using methods of the Stats object console.log("Path is file:", stats.isFile()); console.log("Path is directory:", stats.isDirectory()); }}); // Define the file descriptor for a folderlet dir_fd = fs.openSync('example_directory', 'r'); // Getting information for a directoryfs.fstat(dir_fd, (error, stats) => { if (error) { console.log(error); } else { console.log("Stats object for: example_directory.txt"); console.log(stats); // Using methods of the Stats object console.log("Path is file:", stats.isFile()); console.log("Path is directory:", stats.isDirectory()); }}); Output: Stats object for: example_file.txt Stats { dev: 3229478529, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780635, size: 0, blocks: 0, atimeMs: 1584389463707.251, mtimeMs: 1582209885466.6848, ctimeMs: 1582209885466.6848, birthtimeMs: 1584389463707.251, atime: 2020-03-16T20:11:03.707Z, mtime: 2020-02-20T14:44:45.467Z, ctime: 2020-02-20T14:44:45.467Z, birthtime: 2020-03-16T20:11:03.707Z } Path is file: true Path is directory: false Stats object for: example_directory.txt Stats { dev: 3229478529, mode: 16822, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780638, size: 0, blocks: 0, atimeMs: 1584429828080.8872, mtimeMs: 1581074249467.7114, ctimeMs: 1584389463715.2507, birthtimeMs: 1584389463715.2507, atime: 2020-03-17T07:23:48.081Z, mtime: 2020-02-07T11:17:29.468Z, ctime: 2020-03-16T20:11:03.715Z, birthtime: 2020-03-16T20:11:03.715Z } Path is file: false Path is directory: true Example 2: This example uses fs.fstat() method to get the details of a file with and without the bigint option. // Node.js program to demonstrate the// fs.fstat() method // Import the filesystem moduleconst fs = require('fs'); // Define the file descriptor for a filelet file_fd = fs.openSync('example_file.txt', 'r'); fs.fstat(file_fd, (error, stats) => { console.log(stats);}); // Using the bigint option to return// the values in big integer formatfs.fstat(file_fd, { bigint: true }, (error, stats) => { console.log(stats);}); Output: Stats { dev: 3229478529, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780635, size: 0, blocks: 0, atimeMs: 1584389463707.251, mtimeMs: 1582209885466.6848, ctimeMs: 1582209885466.6848, birthtimeMs: 1584389463707.251, atime: 2020-03-16T20:11:03.707Z, mtime: 2020-02-20T14:44:45.467Z, ctime: 2020-02-20T14:44:45.467Z, birthtime: 2020-03-16T20:11:03.707Z } BigIntStats { dev: 3229478529n, mode: 33206n, nlink: 1n, uid: 0n, gid: 0n, rdev: 0n, blksize: 4096n, ino: 281474976780635n, size: 0n, blocks: 0n, atimeMs: 1584389463707n, mtimeMs: 1582209885466n, ctimeMs: 1582209885466n, birthtimeMs: 1584389463707n, atimeNs: 1584389463707251000n, mtimeNs: 1582209885466684900n, ctimeNs: 1582209885466684900n, birthtimeNs: 1584389463707251000n, atime: 2020-03-16T20:11:03.707Z, mtime: 2020-02-20T14:44:45.466Z, ctime: 2020-02-20T14:44:45.466Z, birthtime: 2020-03-16T20:11:03.707Z } Reference: https://nodejs.org/api/fs.html#fs_fs_fstat_fd_options_callback Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js Export Module How to connect Node.js with React.js ? Mongoose find() Function Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26267, "s": 26239, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26447, "s": 26267, "text": "The fs.fstat() method is used to return information about the given file descriptor. The fs.Stat object returned has several fields and methods to get more details about the file." }, { "code": null, "e": 26455, "s": 26447, "text": "Syntax:" }, { "code": null, "e": 26489, "s": 26455, "text": "fs.fstat( fd, options, callback )" }, { "code": null, "e": 26578, "s": 26489, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 26656, "s": 26578, "text": "fd: It is an integer which represents the file descriptor used by the method." }, { "code": null, "e": 26928, "s": 26656, "text": "options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 27068, "s": 26928, "text": "bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 27274, "s": 27068, "text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the methodStats: It is the Stats object that contains the details of the file path." }, { "code": null, "e": 27329, "s": 27274, "text": "err: It is an error that would be thrown if the method" }, { "code": null, "e": 27403, "s": 27329, "text": "Stats: It is the Stats object that contains the details of the file path." }, { "code": null, "e": 27463, "s": 27403, "text": "Below examples illustrate the fs.fstat() method in Node.js:" }, { "code": null, "e": 27554, "s": 27463, "text": "Example 1: This example uses fs.fstat() method to get the details of a file and directory." }, { "code": "// Node.js program to demonstrate the// fs.fstat() method // Import the filesystem moduleconst fs = require('fs'); // Define the file descriptor for a filelet file_fd = fs.openSync('example_file.txt', 'r'); // Getting information for a filefs.fstat(file_fd, (error, stats) => { if (error) { console.log(error); } else { console.log(\"Stats object for: example_file.txt\"); console.log(stats); // Using methods of the Stats object console.log(\"Path is file:\", stats.isFile()); console.log(\"Path is directory:\", stats.isDirectory()); }}); // Define the file descriptor for a folderlet dir_fd = fs.openSync('example_directory', 'r'); // Getting information for a directoryfs.fstat(dir_fd, (error, stats) => { if (error) { console.log(error); } else { console.log(\"Stats object for: example_directory.txt\"); console.log(stats); // Using methods of the Stats object console.log(\"Path is file:\", stats.isFile()); console.log(\"Path is directory:\", stats.isDirectory()); }});", "e": 28573, "s": 27554, "text": null }, { "code": null, "e": 28581, "s": 28573, "text": "Output:" }, { "code": null, "e": 29588, "s": 28581, "text": "Stats object for: example_file.txt\nStats {\n dev: 3229478529,\n mode: 33206,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780635,\n size: 0,\n blocks: 0,\n atimeMs: 1584389463707.251,\n mtimeMs: 1582209885466.6848,\n ctimeMs: 1582209885466.6848,\n birthtimeMs: 1584389463707.251,\n atime: 2020-03-16T20:11:03.707Z,\n mtime: 2020-02-20T14:44:45.467Z,\n ctime: 2020-02-20T14:44:45.467Z,\n birthtime: 2020-03-16T20:11:03.707Z\n}\nPath is file: true\nPath is directory: false\nStats object for: example_directory.txt\nStats {\n dev: 3229478529,\n mode: 16822,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780638,\n size: 0,\n blocks: 0,\n atimeMs: 1584429828080.8872,\n mtimeMs: 1581074249467.7114,\n ctimeMs: 1584389463715.2507,\n birthtimeMs: 1584389463715.2507,\n atime: 2020-03-17T07:23:48.081Z,\n mtime: 2020-02-07T11:17:29.468Z,\n ctime: 2020-03-16T20:11:03.715Z,\n birthtime: 2020-03-16T20:11:03.715Z\n}\nPath is file: false\nPath is directory: true" }, { "code": null, "e": 29700, "s": 29588, "text": "Example 2: This example uses fs.fstat() method to get the details of a file with and without the bigint option." }, { "code": "// Node.js program to demonstrate the// fs.fstat() method // Import the filesystem moduleconst fs = require('fs'); // Define the file descriptor for a filelet file_fd = fs.openSync('example_file.txt', 'r'); fs.fstat(file_fd, (error, stats) => { console.log(stats);}); // Using the bigint option to return// the values in big integer formatfs.fstat(file_fd, { bigint: true }, (error, stats) => { console.log(stats);});", "e": 30124, "s": 29700, "text": null }, { "code": null, "e": 30132, "s": 30124, "text": "Output:" }, { "code": null, "e": 31112, "s": 30132, "text": "Stats {\n dev: 3229478529,\n mode: 33206,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780635,\n size: 0,\n blocks: 0,\n atimeMs: 1584389463707.251,\n mtimeMs: 1582209885466.6848,\n ctimeMs: 1582209885466.6848,\n birthtimeMs: 1584389463707.251,\n atime: 2020-03-16T20:11:03.707Z,\n mtime: 2020-02-20T14:44:45.467Z,\n ctime: 2020-02-20T14:44:45.467Z,\n birthtime: 2020-03-16T20:11:03.707Z\n}\nBigIntStats {\n dev: 3229478529n,\n mode: 33206n,\n nlink: 1n,\n uid: 0n,\n gid: 0n,\n rdev: 0n,\n blksize: 4096n,\n ino: 281474976780635n,\n size: 0n,\n blocks: 0n,\n atimeMs: 1584389463707n,\n mtimeMs: 1582209885466n,\n ctimeMs: 1582209885466n,\n birthtimeMs: 1584389463707n,\n atimeNs: 1584389463707251000n,\n mtimeNs: 1582209885466684900n,\n ctimeNs: 1582209885466684900n,\n birthtimeNs: 1584389463707251000n,\n atime: 2020-03-16T20:11:03.707Z,\n mtime: 2020-02-20T14:44:45.466Z,\n ctime: 2020-02-20T14:44:45.466Z,\n birthtime: 2020-03-16T20:11:03.707Z\n}" }, { "code": null, "e": 31186, "s": 31112, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_fstat_fd_options_callback" }, { "code": null, "e": 31204, "s": 31186, "text": "Node.js-fs-module" }, { "code": null, "e": 31211, "s": 31204, "text": "Picked" }, { "code": null, "e": 31219, "s": 31211, "text": "Node.js" }, { "code": null, "e": 31236, "s": 31219, "text": "Web Technologies" }, { "code": null, "e": 31334, "s": 31236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31356, "s": 31334, "text": "Node.js Export Module" }, { "code": null, "e": 31395, "s": 31356, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 31420, "s": 31395, "text": "Mongoose find() Function" }, { "code": null, "e": 31490, "s": 31420, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 31517, "s": 31490, "text": "Mongoose Populate() Method" }, { "code": null, "e": 31557, "s": 31517, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31602, "s": 31557, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31664, "s": 31602, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31725, "s": 31664, "text": "Difference between var, let and const keywords in JavaScript" } ]
Number of ways of distributing N identical objects in R distinct groups - GeeksforGeeks
07 May, 2021 Given two integers N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups. Examples: Input: N = 4, R = 2 Output: 5 No of objects in 1st group = 0, in second group = 4 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second group = 1 No of objects in 1st group = 4, in second group = 0 Input: N = 4, R = 3 Output: 15 Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in the second group and xR objects are placed in the Rth group. It is given that, x1 + x2 + x3 +...+ xR = N The solution of this equation by multinomial theorem is given by N + R – 1CR – 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// value of ncr effectivelyint ncr(int n, int r){ // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsint NoOfDistributions(int N, int R){ return ncr(N + R - 1, R - 1);} // Driver codeint main(){ int N = 4, R = 3; // Function call cout << NoOfDistributions(N, R); return 0;} // Java implementation of the above approachimport java.util.*; class GFG { // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N + R - 1, R - 1); } // Driver code public static void main(String[] args) { int N = 4, R = 3; // Function call System.out.println(NoOfDistributions(N, R)); }} // This code is contributed by Princi Singh # Python3 implementation of the above approach # Function to return the# value of ncr effectively def ncr(n, r): # Initialize the answer ans = 1 for i in range(1, r+1): # Divide simultaneously by # i to avoid overflow ans *= (n - r + i) ans //= i return ans # Function to return the number of# ways to distribute N identical# objects in R distinct objectsdef NoOfDistributions(N, R): return ncr(N + R-1, R - 1) # Driver codeN = 4R = 3 # Function callprint(NoOfDistributions(N, R)) # This code is contributed by mohit kumar 29 // C# implementation of the above approachusing System; class GFG { // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N + R - 1, R - 1); } // Driver code static public void Main() { int N = 4, R = 3; // Function call Console.WriteLine(NoOfDistributions(N, R)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the above approach // Function to return the// value of ncr effectivelyfunction ncr(n, r){ // Initialize the answer let ans = 1; for(let i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans = parseInt(ans / i); } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsfunction NoOfDistributions(N, R){ return ncr(N + R - 1, R - 1);} // Driver codelet N = 4, R = 3; // Function calldocument.write(NoOfDistributions(N, R)); // This code is contributed by subhammahato348 </script> 15 Time Complexity: O(R) mohit kumar 29 ankthon princi singh anurag__tiwari_ subhammahato348 Numbers Mathematical Mathematical Numbers 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 Sieve of Eratosthenes The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 26487, "s": 26459, "text": "\n07 May, 2021" }, { "code": null, "e": 26617, "s": 26487, "text": "Given two integers N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups." }, { "code": null, "e": 26628, "s": 26617, "text": "Examples: " }, { "code": null, "e": 26918, "s": 26628, "text": "Input: N = 4, R = 2 Output: 5 No of objects in 1st group = 0, in second group = 4 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second group = 1 No of objects in 1st group = 4, in second group = 0" }, { "code": null, "e": 26950, "s": 26918, "text": "Input: N = 4, R = 3 Output: 15 " }, { "code": null, "e": 27270, "s": 26950, "text": "Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in the second group and xR objects are placed in the Rth group. It is given that, x1 + x2 + x3 +...+ xR = N The solution of this equation by multinomial theorem is given by N + R – 1CR – 1." }, { "code": null, "e": 27322, "s": 27270, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27326, "s": 27322, "text": "C++" }, { "code": null, "e": 27331, "s": 27326, "text": "Java" }, { "code": null, "e": 27339, "s": 27331, "text": "Python3" }, { "code": null, "e": 27342, "s": 27339, "text": "C#" }, { "code": null, "e": 27353, "s": 27342, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// value of ncr effectivelyint ncr(int n, int r){ // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsint NoOfDistributions(int N, int R){ return ncr(N + R - 1, R - 1);} // Driver codeint main(){ int N = 4, R = 3; // Function call cout << NoOfDistributions(N, R); return 0;}", "e": 28022, "s": 27353, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG { // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N + R - 1, R - 1); } // Driver code public static void main(String[] args) { int N = 4, R = 3; // Function call System.out.println(NoOfDistributions(N, R)); }} // This code is contributed by Princi Singh", "e": 28886, "s": 28022, "text": null }, { "code": "# Python3 implementation of the above approach # Function to return the# value of ncr effectively def ncr(n, r): # Initialize the answer ans = 1 for i in range(1, r+1): # Divide simultaneously by # i to avoid overflow ans *= (n - r + i) ans //= i return ans # Function to return the number of# ways to distribute N identical# objects in R distinct objectsdef NoOfDistributions(N, R): return ncr(N + R-1, R - 1) # Driver codeN = 4R = 3 # Function callprint(NoOfDistributions(N, R)) # This code is contributed by mohit kumar 29", "e": 29463, "s": 28886, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG { // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N + R - 1, R - 1); } // Driver code static public void Main() { int N = 4, R = 3; // Function call Console.WriteLine(NoOfDistributions(N, R)); }} // This code is contributed by AnkitRai01", "e": 30303, "s": 29463, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to return the// value of ncr effectivelyfunction ncr(n, r){ // Initialize the answer let ans = 1; for(let i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans = parseInt(ans / i); } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsfunction NoOfDistributions(N, R){ return ncr(N + R - 1, R - 1);} // Driver codelet N = 4, R = 3; // Function calldocument.write(NoOfDistributions(N, R)); // This code is contributed by subhammahato348 </script>", "e": 30999, "s": 30303, "text": null }, { "code": null, "e": 31002, "s": 30999, "text": "15" }, { "code": null, "e": 31024, "s": 31002, "text": "Time Complexity: O(R)" }, { "code": null, "e": 31039, "s": 31024, "text": "mohit kumar 29" }, { "code": null, "e": 31047, "s": 31039, "text": "ankthon" }, { "code": null, "e": 31060, "s": 31047, "text": "princi singh" }, { "code": null, "e": 31076, "s": 31060, "text": "anurag__tiwari_" }, { "code": null, "e": 31092, "s": 31076, "text": "subhammahato348" }, { "code": null, "e": 31100, "s": 31092, "text": "Numbers" }, { "code": null, "e": 31113, "s": 31100, "text": "Mathematical" }, { "code": null, "e": 31126, "s": 31113, "text": "Mathematical" }, { "code": null, "e": 31134, "s": 31126, "text": "Numbers" }, { "code": null, "e": 31232, "s": 31134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31256, "s": 31232, "text": "Merge two sorted arrays" }, { "code": null, "e": 31299, "s": 31256, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31313, "s": 31299, "text": "Prime Numbers" }, { "code": null, "e": 31355, "s": 31313, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31428, "s": 31355, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31450, "s": 31428, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 31493, "s": 31450, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31534, "s": 31493, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31555, "s": 31534, "text": "Operators in C / C++" } ]
Generate all possible permutations of words in a Sentence - GeeksforGeeks
08 Jun, 2021 Given a string S, the task is to print permutations of all words in a sentence. Examples: Input: S = “sky is blue”Output: sky is bluesky blue isis sky blueis blue skyblue sky isblue is sky Input: S =” Do what you love”Output:Do what you loveDo what love youDo you what loveDo you love whatDo love what youDo love you whatwhat Do you lovewhat Do love youwhat you Do lovewhat you love Dowhat love Do youwhat love you Doyou Do what loveyou Do love whatyou what Do loveyou what love Doyou love Do whatyou love what Dolove Do what youlove Do you whatlove what Do youlove what you Dolove you Do whatlove you what Do Approach: The given problem can be solved using recursion. Follow the steps below to solve the problem: Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.Permute the list using built-in python functions itertools.permutations().Traverse the permutations and convert each permutation to a list.Print these lists. Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list. Permute the list using built-in python functions itertools.permutations(). Traverse the permutations and convert each permutation to a list. Print these lists. Below is the implementation of the above approach: Python3 # Python implementation of# the above approach from itertools import permutations # Function to generate permutations# of all words in a sentencedef calculatePermutations(sentence): # Stores all words in the sentence lis = list(sentence.split()) # Stores all possible permutations # of words in this list permute = permutations(lis) # Iterate over all permutations for i in permute: # Convert the current # permutation into a list permutelist = list(i) # Print the words in the # list separated by spaces for j in permutelist: print(j, end = " ") # Print a new line print() # Driver Codeif __name__ == '__main__': sentence = "sky is blue" calculatePermutations(sentence) sky is blue sky blue is is sky blue is blue sky blue sky is blue is sky Time Complexity: O(N!), where N denotes the number of words in a sentence.Auxiliary Space: O(N!) ruhelaa48 permutation Python list-programs python-list-functions Combinatorial Python Programs Strings Strings permutation Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Print all possible strings of length k that can be formed from a set of n characters Count of subsets with sum equal to X Python program to get all subsets of given size of a set Heap's Algorithm for generating permutations Distinct permutations of the string | Set 2 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26169, "s": 26141, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26249, "s": 26169, "text": "Given a string S, the task is to print permutations of all words in a sentence." }, { "code": null, "e": 26259, "s": 26249, "text": "Examples:" }, { "code": null, "e": 26359, "s": 26259, "text": "Input: S = “sky is blue”Output: sky is bluesky blue isis sky blueis blue skyblue sky isblue is sky" }, { "code": null, "e": 26780, "s": 26359, "text": "Input: S =” Do what you love”Output:Do what you loveDo what love youDo you what loveDo you love whatDo love what youDo love you whatwhat Do you lovewhat Do love youwhat you Do lovewhat you love Dowhat love Do youwhat love you Doyou Do what loveyou Do love whatyou what Do loveyou what love Doyou love Do whatyou love what Dolove Do what youlove Do you whatlove what Do youlove what you Dolove you Do whatlove you what Do" }, { "code": null, "e": 26884, "s": 26780, "text": "Approach: The given problem can be solved using recursion. Follow the steps below to solve the problem:" }, { "code": null, "e": 27157, "s": 26884, "text": "Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.Permute the list using built-in python functions itertools.permutations().Traverse the permutations and convert each permutation to a list.Print these lists." }, { "code": null, "e": 27273, "s": 27157, "text": "Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list." }, { "code": null, "e": 27348, "s": 27273, "text": "Permute the list using built-in python functions itertools.permutations()." }, { "code": null, "e": 27414, "s": 27348, "text": "Traverse the permutations and convert each permutation to a list." }, { "code": null, "e": 27433, "s": 27414, "text": "Print these lists." }, { "code": null, "e": 27484, "s": 27433, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27492, "s": 27484, "text": "Python3" }, { "code": "# Python implementation of# the above approach from itertools import permutations # Function to generate permutations# of all words in a sentencedef calculatePermutations(sentence): # Stores all words in the sentence lis = list(sentence.split()) # Stores all possible permutations # of words in this list permute = permutations(lis) # Iterate over all permutations for i in permute: # Convert the current # permutation into a list permutelist = list(i) # Print the words in the # list separated by spaces for j in permutelist: print(j, end = \" \") # Print a new line print() # Driver Codeif __name__ == '__main__': sentence = \"sky is blue\" calculatePermutations(sentence)", "e": 28292, "s": 27492, "text": null }, { "code": null, "e": 28369, "s": 28292, "text": "sky is blue \nsky blue is \nis sky blue \nis blue sky \nblue sky is \nblue is sky" }, { "code": null, "e": 28468, "s": 28371, "text": "Time Complexity: O(N!), where N denotes the number of words in a sentence.Auxiliary Space: O(N!)" }, { "code": null, "e": 28478, "s": 28468, "text": "ruhelaa48" }, { "code": null, "e": 28490, "s": 28478, "text": "permutation" }, { "code": null, "e": 28511, "s": 28490, "text": "Python list-programs" }, { "code": null, "e": 28533, "s": 28511, "text": "python-list-functions" }, { "code": null, "e": 28547, "s": 28533, "text": "Combinatorial" }, { "code": null, "e": 28563, "s": 28547, "text": "Python Programs" }, { "code": null, "e": 28571, "s": 28563, "text": "Strings" }, { "code": null, "e": 28579, "s": 28571, "text": "Strings" }, { "code": null, "e": 28591, "s": 28579, "text": "permutation" }, { "code": null, "e": 28605, "s": 28591, "text": "Combinatorial" }, { "code": null, "e": 28703, "s": 28605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28788, "s": 28703, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 28825, "s": 28788, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 28882, "s": 28825, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 28927, "s": 28882, "text": "Heap's Algorithm for generating permutations" }, { "code": null, "e": 28971, "s": 28927, "text": "Distinct permutations of the string | Set 2" }, { "code": null, "e": 29014, "s": 28971, "text": "Python program to convert a list to string" }, { "code": null, "e": 29036, "s": 29014, "text": "Defaultdict in Python" }, { "code": null, "e": 29075, "s": 29036, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29121, "s": 29075, "text": "Python | Split string into list of characters" } ]
Exports & Imports in JavaScript
Note − To run this example you will need to run a localhost server. Following is the code for exports and imports in JavaScript − INDEX.html Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Exports and imports in JavaScript</h1> <button class="Btn">IMPORT</button> <div class="result"></div> <h3>Click on the above button to import module</h3> <script src="script.js" type="module"></script> <script src="sample.js" type="module"></script> </body> </html> script.js import test from './sample.js'; document.querySelector('.Btn').addEventListener('click',()=>{ test(); }) sample.js let resultEle = document.querySelector(".result"); export default function testImport(){ resultEle.innerHTML = 'Module testImport has been imported'; } On clicking the ‘IMPORT’ button −
[ { "code": null, "e": 1130, "s": 1062, "text": "Note − To run this example you will need to run a localhost server." }, { "code": null, "e": 1192, "s": 1130, "text": "Following is the code for exports and imports in JavaScript −" }, { "code": null, "e": 1203, "s": 1192, "text": "INDEX.html" }, { "code": null, "e": 1214, "s": 1203, "text": " Live Demo" }, { "code": null, "e": 1826, "s": 1214, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Exports and imports in JavaScript</h1>\n<button class=\"Btn\">IMPORT</button>\n<div class=\"result\"></div>\n<h3>Click on the above button to import module</h3>\n<script src=\"script.js\" type=\"module\"></script>\n<script src=\"sample.js\" type=\"module\"></script>\n</body>\n</html>" }, { "code": null, "e": 1836, "s": 1826, "text": "script.js" }, { "code": null, "e": 1941, "s": 1836, "text": "import test from './sample.js';\ndocument.querySelector('.Btn').addEventListener('click',()=>{\ntest();\n})" }, { "code": null, "e": 1951, "s": 1941, "text": "sample.js" }, { "code": null, "e": 2103, "s": 1951, "text": "let resultEle = document.querySelector(\".result\");\nexport default function testImport(){\nresultEle.innerHTML = 'Module testImport has been imported';\n}" }, { "code": null, "e": 2137, "s": 2103, "text": "On clicking the ‘IMPORT’ button −" } ]
Arithmetic Number | Practice | GeeksforGeeks
Given three integers 'A' denoting the first term of an arithmetic sequence , 'C' denoting the common difference of an arithmetic sequence and an integer 'B'. you need to tell whether 'B' exists in the arithmetic sequence or not. Example 1: Input: A = 1, B = 3, C = 2 Output: 1 Explaination: 3 is the second term of the sequence starting with 1 and having a common difference 2. Example 2: Input: A = 1, B = 2, C = 3 Output: 0 Explaination: 2 is not present in the sequence. Your Task: You do not need to read input or print anything. Your task is to complete the function inSequence() which takes A, B and C and returns 1 if B is present in the sequence. Otherwise, returns 0. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: -109 ≤ A, B, C ≤ 109 0 wajihafatima81025 days ago int inSequence(int A, int B, int C){ if(C==0){ if(A==B) return 1; return 0; } else if(C>0){ if(B<A) return 0; if((B-A)%C==0) return 1; return 0; } else { if(B>A) return 0; if((B-A)%C==0) return 1; return 0; } return 0; } 0 amarrajsmart1971 week ago Time Taken=0.01 sec. int inSequence(int A, int B, int C){ // code here if(C==0) { if(A==B) { return 1; } else { return 0; } } else if(B==A) { return 1; } else if((B-A)%C==0&&B>A&&C>0) { return 1; } else if((B-A)%C==0&&B<A&&C<0) { return 1; } else { return 0; } } +1 kartikeyashokgautam3 weeks ago Explained in Detail JAVA Solution : - static int inSequence(int A, int B, int C){ if(C==0) // if common diff is 0 , then A and B must be same , therefore return 1; return A==B?1:0; // But if Common diff = 0 , and A , B are not same , then it is not Arithmetic progression in that case will return 0 if(B<A && C>0) return 0; //if common difference is positive , then B should be positive if(B>A && C<0) return 0; //if common difference is negative , then B should be negative int n = ((B-A)/C)+1; // nth number return (A+(n-1)*C==B?1:0);// using Formula an = a + (n-1)d , here a = first term , n = nth number , d = common diff , an = nth term // if B is part of arithmetic then it must be the nth term therefore return 1 else 0 } 0 kumarsurajroy36553 weeks ago //User function Template for Java class Solution{ static int inSequence(int A, int B, int C){ // code here if(C==0){ return (A==B)?1:0; } int n = ((B-A)/C)+1; return (B==(A+((n-1)*C))&&n>0)?1:0; }} +1 manyasmriti4 weeks ago class Solution{ static int inSequence(int a, int b, int c){ // code here if(a == b) return 1; if(c == 0) return 0; if( (b - a) % c == 0 && b > a && c >0) return 1; else if( (b - a) % c == 0 && b < a && c <0) return 1; return 0; } } 0 meetulsingh281084 weeks ago HANDLE EVERY CASE WITH CARE || C++ int inSequence(int A, int B, int C){ if(A==B){ return 1; } if(C==0){ return 0; } if((B-A)%C==0 && (B-A)/C>0){ return 1; } else{ return 0; } } 0 hoodninja4 weeks ago int inSequence(int A, int B, int C){ // code here if(A==B) return 1; if(C == 0) return (A==B); int n; n = ((B-A)/C); if(n <= 0) return 0; if(B == A + (n*C)) { return 1; } return 0; } 0 mashhadihossain1 month ago SIMPLE JAVA SOLUTION (0.1/3.5 SEC) class Solution{ static int inSequence(int A, int B, int C){ if(A==B) { return 1; } if(C==0) { if(A==B) { return 1; } else { return 0; } } if(((B-A)%C)==0 && ((B-A)/C)>0) { return 1; } else { return 0; } }} 0 manish14091 month ago c++ code with use of maths a.p formula int inSequence(int A, int B, int C){ // code here if(C == 0){ return(A==B); } // first corner case:if b smaller and c is graeter than 1 //then no chance of present //eg 4 -12 1 //second corner case: eg -3 6 -2 if((B < A && C > 0)||(B > A && C < 0 )) return 0; double c=C,b=B,a=A; double temp =b-a; float n=temp/c; int check=n; if(n-check==0) return 1; else return 0; } 0 mayank20212 months ago This seems a simple question at first glance, but it gets v tricky when try to consider edge cases.At least, I couldn't submit it correctly in first few attempts , forgetting one case or other in every attempt.. good question.. 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": 456, "s": 226, "text": "Given three integers 'A' denoting the first term of an arithmetic sequence , 'C' denoting the common difference of an arithmetic sequence and an integer 'B'. you need to tell whether 'B' exists in the arithmetic sequence or not." }, { "code": null, "e": 467, "s": 456, "text": "Example 1:" }, { "code": null, "e": 607, "s": 467, "text": "Input: A = 1, B = 3, C = 2\nOutput: 1\nExplaination: 3 is the second term of the \nsequence starting with 1 and having a common \ndifference 2." }, { "code": null, "e": 618, "s": 607, "text": "Example 2:" }, { "code": null, "e": 703, "s": 618, "text": "Input: A = 1, B = 2, C = 3\nOutput: 0\nExplaination: 2 is not present in the sequence." }, { "code": null, "e": 906, "s": 703, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function inSequence() which takes A, B and C and returns 1 if B is present in the sequence. Otherwise, returns 0." }, { "code": null, "e": 968, "s": 906, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1004, "s": 968, "text": "Constraints:\n-109 ≤ A, B, C ≤ 109 " }, { "code": null, "e": 1006, "s": 1004, "text": "0" }, { "code": null, "e": 1033, "s": 1006, "text": "wajihafatima81025 days ago" }, { "code": null, "e": 1413, "s": 1033, "text": "int inSequence(int A, int B, int C){\n if(C==0){\n if(A==B) return 1;\n return 0;\n }\n \n \n else if(C>0){\n \n if(B<A) return 0;\n \n if((B-A)%C==0) return 1;\n return 0;\n }\n \n else {\n \n if(B>A) return 0;\n if((B-A)%C==0) return 1;\n return 0;\n \n }\n return 0;\n}" }, { "code": null, "e": 1415, "s": 1413, "text": "0" }, { "code": null, "e": 1441, "s": 1415, "text": "amarrajsmart1971 week ago" }, { "code": null, "e": 1462, "s": 1441, "text": "Time Taken=0.01 sec." }, { "code": null, "e": 1931, "s": 1462, "text": "int inSequence(int A, int B, int C){ // code here if(C==0) { if(A==B) { return 1; } else { return 0; } } else if(B==A) { return 1; } else if((B-A)%C==0&&B>A&&C>0) { return 1; } else if((B-A)%C==0&&B<A&&C<0) { return 1; } else { return 0; } }" }, { "code": null, "e": 1934, "s": 1931, "text": "+1" }, { "code": null, "e": 1965, "s": 1934, "text": "kartikeyashokgautam3 weeks ago" }, { "code": null, "e": 2004, "s": 1965, "text": "Explained in Detail JAVA Solution : - " }, { "code": null, "e": 2822, "s": 2006, "text": "static int inSequence(int A, int B, int C){ if(C==0) // if common diff is 0 , then A and B must be same , therefore return 1; return A==B?1:0; // But if Common diff = 0 , and A , B are not same , then it is not Arithmetic progression in that case will return 0 if(B<A && C>0) return 0; //if common difference is positive , then B should be positive if(B>A && C<0) return 0; //if common difference is negative , then B should be negative int n = ((B-A)/C)+1; // nth number return (A+(n-1)*C==B?1:0);// using Formula an = a + (n-1)d , here a = first term , n = nth number , d = common diff , an = nth term // if B is part of arithmetic then it must be the nth term therefore return 1 else 0 " }, { "code": null, "e": 2828, "s": 2822, "text": " }" }, { "code": null, "e": 2830, "s": 2828, "text": "0" }, { "code": null, "e": 2859, "s": 2830, "text": "kumarsurajroy36553 weeks ago" }, { "code": null, "e": 2893, "s": 2859, "text": "//User function Template for Java" }, { "code": null, "e": 3143, "s": 2893, "text": "class Solution{ static int inSequence(int A, int B, int C){ // code here if(C==0){ return (A==B)?1:0; } int n = ((B-A)/C)+1; return (B==(A+((n-1)*C))&&n>0)?1:0; }}" }, { "code": null, "e": 3146, "s": 3143, "text": "+1" }, { "code": null, "e": 3169, "s": 3146, "text": "manyasmriti4 weeks ago" }, { "code": null, "e": 3473, "s": 3169, "text": "class Solution{\n static int inSequence(int a, int b, int c){\n // code here\n if(a == b) return 1;\n if(c == 0) return 0;\n if( (b - a) % c == 0 && b > a && c >0)\n return 1;\n else if( (b - a) % c == 0 && b < a && c <0)\n return 1;\n return 0;\n }\n}" }, { "code": null, "e": 3475, "s": 3473, "text": "0" }, { "code": null, "e": 3503, "s": 3475, "text": "meetulsingh281084 weeks ago" }, { "code": null, "e": 3538, "s": 3503, "text": "HANDLE EVERY CASE WITH CARE || C++" }, { "code": null, "e": 3774, "s": 3538, "text": " int inSequence(int A, int B, int C){ if(A==B){ return 1; } if(C==0){ return 0; } if((B-A)%C==0 && (B-A)/C>0){ return 1; } else{ return 0; } }" }, { "code": null, "e": 3776, "s": 3774, "text": "0" }, { "code": null, "e": 3797, "s": 3776, "text": "hoodninja4 weeks ago" }, { "code": null, "e": 4136, "s": 3797, "text": " int inSequence(int A, int B, int C){\n // code here\n if(A==B)\n return 1;\n if(C == 0)\n return (A==B);\n\n\n int n;\n n = ((B-A)/C);\n \n if(n <= 0)\n return 0;\n \n if(B == A + (n*C))\n {\n return 1;\n }\n return 0;\n }" }, { "code": null, "e": 4138, "s": 4136, "text": "0" }, { "code": null, "e": 4165, "s": 4138, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 4200, "s": 4165, "text": "SIMPLE JAVA SOLUTION (0.1/3.5 SEC)" }, { "code": null, "e": 4600, "s": 4200, "text": "class Solution{ static int inSequence(int A, int B, int C){ if(A==B) { return 1; } if(C==0) { if(A==B) { return 1; } else { return 0; } } if(((B-A)%C)==0 && ((B-A)/C)>0) { return 1; } else { return 0; } }}" }, { "code": null, "e": 4602, "s": 4600, "text": "0" }, { "code": null, "e": 4624, "s": 4602, "text": "manish14091 month ago" }, { "code": null, "e": 4663, "s": 4624, "text": "c++ code with use of maths a.p formula" }, { "code": null, "e": 5138, "s": 4663, "text": "int inSequence(int A, int B, int C){ // code here if(C == 0){ return(A==B); } // first corner case:if b smaller and c is graeter than 1 //then no chance of present //eg 4 -12 1 //second corner case: eg -3 6 -2 if((B < A && C > 0)||(B > A && C < 0 )) return 0; double c=C,b=B,a=A; double temp =b-a; float n=temp/c; int check=n; if(n-check==0) return 1; else return 0; }" }, { "code": null, "e": 5140, "s": 5138, "text": "0" }, { "code": null, "e": 5163, "s": 5140, "text": "mayank20212 months ago" }, { "code": null, "e": 5391, "s": 5163, "text": "This seems a simple question at first glance, but it gets v tricky when try to consider edge cases.At least, I couldn't submit it correctly in first few attempts , forgetting one case or other in every attempt.. good question.." }, { "code": null, "e": 5537, "s": 5391, "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": 5573, "s": 5537, "text": " Login to access your submissions. " }, { "code": null, "e": 5583, "s": 5573, "text": "\nProblem\n" }, { "code": null, "e": 5593, "s": 5583, "text": "\nContest\n" }, { "code": null, "e": 5656, "s": 5593, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5804, "s": 5656, "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": 6012, "s": 5804, "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": 6118, "s": 6012, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to resize an image in Android using Picasso?
This example demonstrates how to do I in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Open build.gradle (Module: app) and add the following dependency − implementation 'com.squareup.picasso:picasso:2.5.2' Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); String url = "https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg"; Picasso.with(this).load(url).resize(200, 500).into(imageView); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1112, "s": 1062, "text": "This example demonstrates how to do I in android." }, { "code": null, "e": 1241, "s": 1112, "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": 1317, "s": 1241, "text": "Step 2 − Open build.gradle (Module: app) and add the following dependency −" }, { "code": null, "e": 1369, "s": 1317, "text": "implementation 'com.squareup.picasso:picasso:2.5.2'" }, { "code": null, "e": 1434, "s": 1369, "text": "Step 3 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1920, "s": 1434, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1977, "s": 1920, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2568, "s": 1977, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport com.squareup.picasso.Picasso;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n String url = \"https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg\";\n Picasso.with(this).load(url).resize(200, 500).into(imageView);\n }\n}" }, { "code": null, "e": 2623, "s": 2568, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3361, "s": 2623, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3715, "s": 3361, "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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Metasploit - Brute-Force Attacks
In a brute-force attack, the hacker uses all possible combinations of letters, numbers, special characters, and small and capital letters in an automated way to gain access over a host or a service. This type of attack has a high probability of success, but it requires an enormous amount of time to process all the combinations. A brute-force attack is slow and the hacker might require a system with high processing power to perform all those permutations and combinations faster. In this chapter, we will discuss how to perform a brute-force attack using Metasploit. After scanning the Metasploitable machine with NMAP, we know what services are running on it. The services are FTP, SSH, mysql, http, and Telnet. To perform a brute-force attack on these services, we will use auxiliaries of each service. Auxiliaries are small scripts used in Metasploit which don’t create a shell in the victim machine; they just provide access to the machine if the brute-force attack is successful. Let’s see how to use auxiliaries. Here, we have created a dictionary list at the root of Kali distribution machine. Open Metasploit. The first service that we will try to attack is FTP and the auxiliary that helps us for this purpose is auxiliary/scanner/ftp/ftp_login. Type the following command to use this auxiliary − msf > use auxiliary/scanner/ftp/ftp_login Set the path of the file that contains our dictionary. Set the victim IP and run. It will produce the following output − As you can see, it is completed, but no session has been created. It means we were unsuccessful in retrieving any useful username and password. To attack the SSH service, we can use the auxiliary: auxiliary/scanner/ssh/ssh_login As you can see in the following screenshot, we have set the RHOSTS to 192.168.1.101 (that is the victim IP) and the username list and password (that is userpass.txt). Then we apply the run command. As can be seen in the above screenshot, three sessions were created. It means three combinations were successful. We have underlined the usernames. To interact with one of the three sessions, we use the command msf > sessions –i 3 which means we will connect with session number 3. The apply a brute-force attack on a Telnet service, we will take a provided set of credentials and a range of IP addresses and attempt to login to any Telnet servers. For this, we will use the auxiliary: auxiliary/scanner/telnet/telnet_login. The process of using the auxiliary is same as in the case of attacking an FTP service or an SSH service. We have to use the auxiliary, set RHOST, then set the list of passwords and run it. Take a look at the following screenshot. Highlighted in blue arrow are the incorrect attempts that the auxiliary did. The red arrows show the successful logins that created sessions. Some other auxiliaries that you can apply in brute-force attack are − SMB service − auxiliary/scanner/smb/smb_login SMB service − auxiliary/scanner/smb/smb_login SNMP service − auxiliary/scanner/snmp/snmp_login SNMP service − auxiliary/scanner/snmp/snmp_login Print Add Notes Bookmark this page
[ { "code": null, "e": 2501, "s": 2171, "text": "In a brute-force attack, the hacker uses all possible combinations of letters, numbers, special characters, and small and capital letters in an automated way to gain access over a host or a service. This type of attack has a high probability of success, but it requires an enormous amount of time to process all the combinations." }, { "code": null, "e": 2741, "s": 2501, "text": "A brute-force attack is slow and the hacker might require a system with high processing power to perform all those permutations and combinations faster. In this chapter, we will discuss how to perform a brute-force attack using Metasploit." }, { "code": null, "e": 2887, "s": 2741, "text": "After scanning the Metasploitable machine with NMAP, we know what services are running on it. The services are FTP, SSH, mysql, http, and Telnet." }, { "code": null, "e": 3193, "s": 2887, "text": "To perform a brute-force attack on these services, we will use auxiliaries of each service. Auxiliaries are small scripts used in Metasploit which don’t create a shell in the victim machine; they just provide access to the machine if the brute-force attack is successful. Let’s see how to use auxiliaries." }, { "code": null, "e": 3275, "s": 3193, "text": "Here, we have created a dictionary list at the root of Kali distribution machine." }, { "code": null, "e": 3429, "s": 3275, "text": "Open Metasploit. The first service that we will try to attack is FTP and the auxiliary that helps us for this purpose is auxiliary/scanner/ftp/ftp_login." }, { "code": null, "e": 3480, "s": 3429, "text": "Type the following command to use this auxiliary −" }, { "code": null, "e": 3523, "s": 3480, "text": "msf > use auxiliary/scanner/ftp/ftp_login\n" }, { "code": null, "e": 3578, "s": 3523, "text": "Set the path of the file that contains our dictionary." }, { "code": null, "e": 3605, "s": 3578, "text": "Set the victim IP and run." }, { "code": null, "e": 3644, "s": 3605, "text": "It will produce the following output −" }, { "code": null, "e": 3788, "s": 3644, "text": "As you can see, it is completed, but no session has been created. It means we were unsuccessful in retrieving any useful username and password." }, { "code": null, "e": 3873, "s": 3788, "text": "To attack the SSH service, we can use the auxiliary: auxiliary/scanner/ssh/ssh_login" }, { "code": null, "e": 4071, "s": 3873, "text": "As you can see in the following screenshot, we have set the RHOSTS to 192.168.1.101 (that is the victim IP) and the username list and password (that is userpass.txt). Then we apply the run command." }, { "code": null, "e": 4219, "s": 4071, "text": "As can be seen in the above screenshot, three sessions were created. It means three combinations were successful. We have underlined the usernames." }, { "code": null, "e": 4353, "s": 4219, "text": "To interact with one of the three sessions, we use the command msf > sessions –i 3 which means we will connect with session number 3." }, { "code": null, "e": 4596, "s": 4353, "text": "The apply a brute-force attack on a Telnet service, we will take a provided set of credentials and a range of IP addresses and attempt to login to any Telnet servers. For this, we will use the auxiliary: auxiliary/scanner/telnet/telnet_login." }, { "code": null, "e": 4785, "s": 4596, "text": "The process of using the auxiliary is same as in the case of attacking an FTP service or an SSH service. We have to use the auxiliary, set RHOST, then set the list of passwords and run it." }, { "code": null, "e": 4968, "s": 4785, "text": "Take a look at the following screenshot. Highlighted in blue arrow are the incorrect attempts that the auxiliary did. The red arrows show the successful logins that created sessions." }, { "code": null, "e": 5038, "s": 4968, "text": "Some other auxiliaries that you can apply in brute-force attack are −" }, { "code": null, "e": 5084, "s": 5038, "text": "SMB service − auxiliary/scanner/smb/smb_login" }, { "code": null, "e": 5130, "s": 5084, "text": "SMB service − auxiliary/scanner/smb/smb_login" }, { "code": null, "e": 5179, "s": 5130, "text": "SNMP service − auxiliary/scanner/snmp/snmp_login" }, { "code": null, "e": 5228, "s": 5179, "text": "SNMP service − auxiliary/scanner/snmp/snmp_login" }, { "code": null, "e": 5235, "s": 5228, "text": " Print" }, { "code": null, "e": 5246, "s": 5235, "text": " Add Notes" } ]
3 Python Modules You Should Know to Extract Text Data | by Pranjal Saxena | Towards Data Science
Extracting text data is the initial step to do further analysis of the data. We have a considerable amount of data present over social media. However, we need a system that can help us extract useful information from the bundle of text data. Some famous applications that use text extraction are Resume Parsing and Invoice Reading. In this article, We will see some latest free to use python libraries to extract text data and how to use them. PDF Plumber library is written in python. This library can solve different purposes while extracting text. If we want to extract text or tabular data from any document, this library can be much handy. To install this library, open the command prompt and type the below command. Make sure that the python is available in the machine. pip install pdfplumber To use this library, first, we need to import it and then use pdfplumber.open to read any pdf files. import requestsimport pdfplumberwith pdfplumber.open("Pranjal Saxena Resume.pdf") as pdf: page=pdf.pages[0] text=page.extract_text() I have used my resume to extract the data and get a fantastic result to do my further text processing on the text. PyPDF2 by Matthew Stamy is another good library that can help us extract data from the documents. It can perform the following actions. Extracting document information. Splitting documents page by page Merging documents page by page Cropping pages Merging multiple pages into a single page Encrypting and decrypting PDF files It performs all the actions in pdf documents. Let us see how it performs in extracting text data from the document. To install this PyPDF2 library, open the command prompt and type the below command. Make sure that the python is available in the machine. pip install PyPDF2 To use this PyPDF2 library, first, we need to import it and then use PdfFileReader to read any pdf files. And, then finally use extractText() to get the text data. from PyPDF2 import PdfFileReaderpdfFile_pypdf = open('Pranjal Saxena Resume.pdf', 'rb')pdfReader = PdfFileReader(pdfFile_pypdf)print(pdfReader.getPage(0).extractText()) The output here is not that much favourable if we compare it to PDF Plumber library because this library focuses on other pdf document manipulations tasks also. Apache Tika is a content detection and analysis framework that was written in Java and stewarded at the Apache Software Foundation. I was surprised by looking at the kind of output it can provide (you will too). Because the was user friendly and easy to transform into valuable data. To install & work with Apache Tika python library, you should have the latest version of Java installed. After installing Java, open the command prompt and type the below command. Make sure that the python is available in the machine. pip install tika==1.23 And, if you are using Jupyter Notebook to run the code, then Jupyter Notebook will itself install the required java environment. To use Apache Tika library, first, we need to import parser from tika and then use parser.from_file to read any pdf files. And, then finally use [“content”] to get the text data. from tika import parserparsed_tika=parser.from_file("Pranjal Saxena Resume.pdf")print(parsed_tika["content"]) The output seems very interesting. We can have appropriately organized text extracted from the document. We have discussed some latest free to use python libraries to extract text or tabular data from the document. These libraries are much helpful in gathering informative data from the documents. We can try these three libraries and can use them accordingly based on the format of the document. Now that we have the data, the next step is to find the pattern in data using regular expression and store the extracted data for further actions. That is all for this article. I will see you somewhere around. 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": 616, "s": 172, "text": "Extracting text data is the initial step to do further analysis of the data. We have a considerable amount of data present over social media. However, we need a system that can help us extract useful information from the bundle of text data. Some famous applications that use text extraction are Resume Parsing and Invoice Reading. In this article, We will see some latest free to use python libraries to extract text data and how to use them." }, { "code": null, "e": 817, "s": 616, "text": "PDF Plumber library is written in python. This library can solve different purposes while extracting text. If we want to extract text or tabular data from any document, this library can be much handy." }, { "code": null, "e": 949, "s": 817, "text": "To install this library, open the command prompt and type the below command. Make sure that the python is available in the machine." }, { "code": null, "e": 972, "s": 949, "text": "pip install pdfplumber" }, { "code": null, "e": 1073, "s": 972, "text": "To use this library, first, we need to import it and then use pdfplumber.open to read any pdf files." }, { "code": null, "e": 1212, "s": 1073, "text": "import requestsimport pdfplumberwith pdfplumber.open(\"Pranjal Saxena Resume.pdf\") as pdf: page=pdf.pages[0] text=page.extract_text()" }, { "code": null, "e": 1327, "s": 1212, "text": "I have used my resume to extract the data and get a fantastic result to do my further text processing on the text." }, { "code": null, "e": 1463, "s": 1327, "text": "PyPDF2 by Matthew Stamy is another good library that can help us extract data from the documents. It can perform the following actions." }, { "code": null, "e": 1496, "s": 1463, "text": "Extracting document information." }, { "code": null, "e": 1529, "s": 1496, "text": "Splitting documents page by page" }, { "code": null, "e": 1560, "s": 1529, "text": "Merging documents page by page" }, { "code": null, "e": 1575, "s": 1560, "text": "Cropping pages" }, { "code": null, "e": 1617, "s": 1575, "text": "Merging multiple pages into a single page" }, { "code": null, "e": 1653, "s": 1617, "text": "Encrypting and decrypting PDF files" }, { "code": null, "e": 1769, "s": 1653, "text": "It performs all the actions in pdf documents. Let us see how it performs in extracting text data from the document." }, { "code": null, "e": 1908, "s": 1769, "text": "To install this PyPDF2 library, open the command prompt and type the below command. Make sure that the python is available in the machine." }, { "code": null, "e": 1927, "s": 1908, "text": "pip install PyPDF2" }, { "code": null, "e": 2091, "s": 1927, "text": "To use this PyPDF2 library, first, we need to import it and then use PdfFileReader to read any pdf files. And, then finally use extractText() to get the text data." }, { "code": null, "e": 2260, "s": 2091, "text": "from PyPDF2 import PdfFileReaderpdfFile_pypdf = open('Pranjal Saxena Resume.pdf', 'rb')pdfReader = PdfFileReader(pdfFile_pypdf)print(pdfReader.getPage(0).extractText())" }, { "code": null, "e": 2421, "s": 2260, "text": "The output here is not that much favourable if we compare it to PDF Plumber library because this library focuses on other pdf document manipulations tasks also." }, { "code": null, "e": 2705, "s": 2421, "text": "Apache Tika is a content detection and analysis framework that was written in Java and stewarded at the Apache Software Foundation. I was surprised by looking at the kind of output it can provide (you will too). Because the was user friendly and easy to transform into valuable data." }, { "code": null, "e": 2940, "s": 2705, "text": "To install & work with Apache Tika python library, you should have the latest version of Java installed. After installing Java, open the command prompt and type the below command. Make sure that the python is available in the machine." }, { "code": null, "e": 2963, "s": 2940, "text": "pip install tika==1.23" }, { "code": null, "e": 3092, "s": 2963, "text": "And, if you are using Jupyter Notebook to run the code, then Jupyter Notebook will itself install the required java environment." }, { "code": null, "e": 3271, "s": 3092, "text": "To use Apache Tika library, first, we need to import parser from tika and then use parser.from_file to read any pdf files. And, then finally use [“content”] to get the text data." }, { "code": null, "e": 3381, "s": 3271, "text": "from tika import parserparsed_tika=parser.from_file(\"Pranjal Saxena Resume.pdf\")print(parsed_tika[\"content\"])" }, { "code": null, "e": 3486, "s": 3381, "text": "The output seems very interesting. We can have appropriately organized text extracted from the document." }, { "code": null, "e": 3925, "s": 3486, "text": "We have discussed some latest free to use python libraries to extract text or tabular data from the document. These libraries are much helpful in gathering informative data from the documents. We can try these three libraries and can use them accordingly based on the format of the document. Now that we have the data, the next step is to find the pattern in data using regular expression and store the extracted data for further actions." }, { "code": null, "e": 3988, "s": 3925, "text": "That is all for this article. I will see you somewhere around." }, { "code": null, "e": 4005, "s": 3988, "text": "Before you go..." }, { "code": null, "e": 4204, "s": 4005, "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": 4393, "s": 4204, "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." } ]
4 Pandas Plotting Function You Should Know | by Cornellius Yudha Wijaya | Towards Data Science
Pandas is a powerful package for data scientists. There are many reasons we use Pandas, e.g. Data wrangling, Data cleaning, and Data manipulation. Although, there is a method that rarely talks about regarding Pandas package and that is the Data plotting. Data plotting, just like the name implies, is a process to plot the data into some graph or chart to visualise the data. While we have much fancier visualisation package out there, some method is just available in the pandas plotting API. Let’s see a few selected method I choose. RadViz is a method to visualise N-dimensional data set into a 2D plot. The problem where we have more than 3-dimensional (features) data or more is that we could not visualise it, but RadViz allows it to happen. According to Pandas, radviz allows us to project an N-dimensional data set into a 2D space where the influence of each dimension can be interpreted as a balance between the importance of all dimensions. In a simpler term, it means we could project a multi-dimensional data into a 2D space in a primitive way. Let’s try to use the function in a sample dataset. #RadViz exampleimport pandas as pdimport seaborn as sns#To use the pd.plotting.radviz, you need a multidimensional data set with all numerical columns but one as the class column (should be categorical).mpg = sns.load_dataset('mpg')pd.plotting.radviz(mpg.drop(['name'], axis =1), 'origin') Above is the result of RadViz function, but how you would interpret the plot? So, each Series in the DataFrame is represented as an evenly distributed slice on a circle. Just look at the example above, there is a circle with the series name. Each data point then is plotted in the circle according to the value on each Series. Highly correlated Series in the DataFrame are placed closer on the unit circle. In the example, we could see the japan and europe car data are closer to the model_year while the usa car is closer to the displacement. It means japan and europe car are most likely correlated to the model_year while usa car is with the displacement. If you want to know more about RadViz, you could check the paper here. According to Pandas, the bootstrap plot is used to estimate the uncertainty of a statistic by relying on random sampling with replacement. In simpler words, it is used to trying to determine the uncertainty in fundamental statistic such as mean and median by resampling the data with replacement (you could sample the same data multiple times). You could read more about bootstrap here. The boostrap_plot function will generate bootstrapping plots for mean, median and mid-range statistics for the given number of samples of the given size. Let’s try using the function with an example dataset. For example, I have the mpg dataset and already have the information regarding the mpg feature data. mpg['mpg'].describe() We could see that the mpg mean is 23.51 and the median is 23. Although this is just a snapshot of the real-world data. How are the values actually is in the population is unknown, that is why we could measure the uncertainty with the bootstrap methods. #bootstrap_plot examplepd.plotting.bootstrap_plot(mpg['mpg'],size = 50 , samples = 500) Above is the result example of bootstap_plot function. Mind that the result could be different than the example because it relies on random resampling. We could see in the first set of the plots (first row) is the sampling result, where the x-axis is the repetition, and the y-axis is the statistic. In the second set is the statistic distribution plot (Mean, Median and Midrange). Take an example of the mean, most of the result is around 23, but it could be between 22.5 and 25 (more or less). This set the uncertainty in the real world that the mean in the population could be between 22.5 and 25. Note that there is a way to estimate the uncertainty by taking the values in the position 2.5% and 97.5% quantile (95% confident) although it is still up to your judgement. A lag plot is a scatter plot for a time series and the same data lagged. Lag itself is a fixed amount of passing time; for example, lag 1 is a day 1 (Y1) with a 1-day time lag (Y1+1 or Y2). A lag plot is used to checks whether the time series data is random or not, and if the data is correlated with themselves. Random data should not have any identifiable patterns, such as linear. Although, why we bother with randomness or correlation? This is because many Time Series models are based on the linear regression, and one assumption is no correlation (Specifically is no Autocorrelation). Let’s try with an example data. In this case, I would use a specific package to scrap stock data from Yahoo Finance called yahoo_historical. pip install yahoo_historical With this package, we could scrap a specific stock data history. Let’s try it. from yahoo_historical import Fetcher#We would scrap the Apple stock data. I would take the data between 1 January 2007 to 1 January 2017 data = Fetcher("AAPL", [2007,1,1], [2017,1,1])apple_df = data.getHistorical()#Set the date as the indexapple_df['Date'] = pd.to_datetime(apple_df['Date'])apple_df = apple_df.set_index('Date') Above is our Apple stock dataset with the date as the index. We could try to plot the data to see the pattern over time with a simple method. apple_df['Adj Close'].plot() We can see the Adj Close is increasing over time but is the data itself shown any pattern in with their lag? In this case, we would use the lag_plot. #Try lag 1 daypd.plotting.lag_plot(apple_df['Adj Close'], lag = 1) As we can see in the plot above, it is almost near linear. It means there is a correlation between daily Adj Close. It is expected as the daily price of the stock would not be varied much in each day. How about a weekly basis? Let’s try to plot it #The data only consist of work days, so one week is 5 dayspd.plotting.lag_plot(apple_df['Adj Close'], lag = 5) We can see the pattern is similar to the lag 1 plot. How about 365 days? would it have any differences? pd.plotting.lag_plot(apple_df['Adj Close'], lag = 365) We can see right now the pattern becomes more random, although the non-linear pattern still exists. The scatter_matrix is just like the name implies; it creates a matrix of scatter plot. Let’s try it with an example at once. import matplotlib.pyplot as plttips = sns.load_dataset('tips')pd.plotting.scatter_matrix(tips, figsize = (8,8))plt.show() We can see the scatter_matrix function automatically detects the numerical features within the Data Frame we passed to the function and create a matrix of the scatter plot. In the example above, between two numerical features are plotted together to create a scatter plot (total_bill and size, total_bill and tip, and tip and size). Whereas, the diagonal part is the histogram of the numerical features. This is a simple function but powerful enough as we could get much information with a single line of code. Here I have shown you 4 different pandas plotting functions that you should know, that includes: radvizbootstrap_plotlag_plotscatter_matrix radviz bootstrap_plot lag_plot scatter_matrix I hope it helps! If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 426, "s": 171, "text": "Pandas is a powerful package for data scientists. There are many reasons we use Pandas, e.g. Data wrangling, Data cleaning, and Data manipulation. Although, there is a method that rarely talks about regarding Pandas package and that is the Data plotting." }, { "code": null, "e": 665, "s": 426, "text": "Data plotting, just like the name implies, is a process to plot the data into some graph or chart to visualise the data. While we have much fancier visualisation package out there, some method is just available in the pandas plotting API." }, { "code": null, "e": 707, "s": 665, "text": "Let’s see a few selected method I choose." }, { "code": null, "e": 919, "s": 707, "text": "RadViz is a method to visualise N-dimensional data set into a 2D plot. The problem where we have more than 3-dimensional (features) data or more is that we could not visualise it, but RadViz allows it to happen." }, { "code": null, "e": 1228, "s": 919, "text": "According to Pandas, radviz allows us to project an N-dimensional data set into a 2D space where the influence of each dimension can be interpreted as a balance between the importance of all dimensions. In a simpler term, it means we could project a multi-dimensional data into a 2D space in a primitive way." }, { "code": null, "e": 1279, "s": 1228, "text": "Let’s try to use the function in a sample dataset." }, { "code": null, "e": 1569, "s": 1279, "text": "#RadViz exampleimport pandas as pdimport seaborn as sns#To use the pd.plotting.radviz, you need a multidimensional data set with all numerical columns but one as the class column (should be categorical).mpg = sns.load_dataset('mpg')pd.plotting.radviz(mpg.drop(['name'], axis =1), 'origin')" }, { "code": null, "e": 1647, "s": 1569, "text": "Above is the result of RadViz function, but how you would interpret the plot?" }, { "code": null, "e": 1811, "s": 1647, "text": "So, each Series in the DataFrame is represented as an evenly distributed slice on a circle. Just look at the example above, there is a circle with the series name." }, { "code": null, "e": 2228, "s": 1811, "text": "Each data point then is plotted in the circle according to the value on each Series. Highly correlated Series in the DataFrame are placed closer on the unit circle. In the example, we could see the japan and europe car data are closer to the model_year while the usa car is closer to the displacement. It means japan and europe car are most likely correlated to the model_year while usa car is with the displacement." }, { "code": null, "e": 2299, "s": 2228, "text": "If you want to know more about RadViz, you could check the paper here." }, { "code": null, "e": 2686, "s": 2299, "text": "According to Pandas, the bootstrap plot is used to estimate the uncertainty of a statistic by relying on random sampling with replacement. In simpler words, it is used to trying to determine the uncertainty in fundamental statistic such as mean and median by resampling the data with replacement (you could sample the same data multiple times). You could read more about bootstrap here." }, { "code": null, "e": 2894, "s": 2686, "text": "The boostrap_plot function will generate bootstrapping plots for mean, median and mid-range statistics for the given number of samples of the given size. Let’s try using the function with an example dataset." }, { "code": null, "e": 2995, "s": 2894, "text": "For example, I have the mpg dataset and already have the information regarding the mpg feature data." }, { "code": null, "e": 3017, "s": 2995, "text": "mpg['mpg'].describe()" }, { "code": null, "e": 3270, "s": 3017, "text": "We could see that the mpg mean is 23.51 and the median is 23. Although this is just a snapshot of the real-world data. How are the values actually is in the population is unknown, that is why we could measure the uncertainty with the bootstrap methods." }, { "code": null, "e": 3358, "s": 3270, "text": "#bootstrap_plot examplepd.plotting.bootstrap_plot(mpg['mpg'],size = 50 , samples = 500)" }, { "code": null, "e": 3510, "s": 3358, "text": "Above is the result example of bootstap_plot function. Mind that the result could be different than the example because it relies on random resampling." }, { "code": null, "e": 3740, "s": 3510, "text": "We could see in the first set of the plots (first row) is the sampling result, where the x-axis is the repetition, and the y-axis is the statistic. In the second set is the statistic distribution plot (Mean, Median and Midrange)." }, { "code": null, "e": 4132, "s": 3740, "text": "Take an example of the mean, most of the result is around 23, but it could be between 22.5 and 25 (more or less). This set the uncertainty in the real world that the mean in the population could be between 22.5 and 25. Note that there is a way to estimate the uncertainty by taking the values in the position 2.5% and 97.5% quantile (95% confident) although it is still up to your judgement." }, { "code": null, "e": 4322, "s": 4132, "text": "A lag plot is a scatter plot for a time series and the same data lagged. Lag itself is a fixed amount of passing time; for example, lag 1 is a day 1 (Y1) with a 1-day time lag (Y1+1 or Y2)." }, { "code": null, "e": 4723, "s": 4322, "text": "A lag plot is used to checks whether the time series data is random or not, and if the data is correlated with themselves. Random data should not have any identifiable patterns, such as linear. Although, why we bother with randomness or correlation? This is because many Time Series models are based on the linear regression, and one assumption is no correlation (Specifically is no Autocorrelation)." }, { "code": null, "e": 4864, "s": 4723, "text": "Let’s try with an example data. In this case, I would use a specific package to scrap stock data from Yahoo Finance called yahoo_historical." }, { "code": null, "e": 4893, "s": 4864, "text": "pip install yahoo_historical" }, { "code": null, "e": 4972, "s": 4893, "text": "With this package, we could scrap a specific stock data history. Let’s try it." }, { "code": null, "e": 5301, "s": 4972, "text": "from yahoo_historical import Fetcher#We would scrap the Apple stock data. I would take the data between 1 January 2007 to 1 January 2017 data = Fetcher(\"AAPL\", [2007,1,1], [2017,1,1])apple_df = data.getHistorical()#Set the date as the indexapple_df['Date'] = pd.to_datetime(apple_df['Date'])apple_df = apple_df.set_index('Date')" }, { "code": null, "e": 5443, "s": 5301, "text": "Above is our Apple stock dataset with the date as the index. We could try to plot the data to see the pattern over time with a simple method." }, { "code": null, "e": 5472, "s": 5443, "text": "apple_df['Adj Close'].plot()" }, { "code": null, "e": 5622, "s": 5472, "text": "We can see the Adj Close is increasing over time but is the data itself shown any pattern in with their lag? In this case, we would use the lag_plot." }, { "code": null, "e": 5689, "s": 5622, "text": "#Try lag 1 daypd.plotting.lag_plot(apple_df['Adj Close'], lag = 1)" }, { "code": null, "e": 5890, "s": 5689, "text": "As we can see in the plot above, it is almost near linear. It means there is a correlation between daily Adj Close. It is expected as the daily price of the stock would not be varied much in each day." }, { "code": null, "e": 5937, "s": 5890, "text": "How about a weekly basis? Let’s try to plot it" }, { "code": null, "e": 6048, "s": 5937, "text": "#The data only consist of work days, so one week is 5 dayspd.plotting.lag_plot(apple_df['Adj Close'], lag = 5)" }, { "code": null, "e": 6152, "s": 6048, "text": "We can see the pattern is similar to the lag 1 plot. How about 365 days? would it have any differences?" }, { "code": null, "e": 6207, "s": 6152, "text": "pd.plotting.lag_plot(apple_df['Adj Close'], lag = 365)" }, { "code": null, "e": 6307, "s": 6207, "text": "We can see right now the pattern becomes more random, although the non-linear pattern still exists." }, { "code": null, "e": 6432, "s": 6307, "text": "The scatter_matrix is just like the name implies; it creates a matrix of scatter plot. Let’s try it with an example at once." }, { "code": null, "e": 6554, "s": 6432, "text": "import matplotlib.pyplot as plttips = sns.load_dataset('tips')pd.plotting.scatter_matrix(tips, figsize = (8,8))plt.show()" }, { "code": null, "e": 6727, "s": 6554, "text": "We can see the scatter_matrix function automatically detects the numerical features within the Data Frame we passed to the function and create a matrix of the scatter plot." }, { "code": null, "e": 6958, "s": 6727, "text": "In the example above, between two numerical features are plotted together to create a scatter plot (total_bill and size, total_bill and tip, and tip and size). Whereas, the diagonal part is the histogram of the numerical features." }, { "code": null, "e": 7065, "s": 6958, "text": "This is a simple function but powerful enough as we could get much information with a single line of code." }, { "code": null, "e": 7162, "s": 7065, "text": "Here I have shown you 4 different pandas plotting functions that you should know, that includes:" }, { "code": null, "e": 7205, "s": 7162, "text": "radvizbootstrap_plotlag_plotscatter_matrix" }, { "code": null, "e": 7212, "s": 7205, "text": "radviz" }, { "code": null, "e": 7227, "s": 7212, "text": "bootstrap_plot" }, { "code": null, "e": 7236, "s": 7227, "text": "lag_plot" }, { "code": null, "e": 7251, "s": 7236, "text": "scatter_matrix" }, { "code": null, "e": 7268, "s": 7251, "text": "I hope it helps!" } ]
How to pass a jQuery event as a parameter in a method?
To pass a jQuery event as a parameter in a method, use the bind() method. You can try to run the following code to learn how to apss a jQuery event as a parameter: 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(){ $("#btn1").bind("click", { key1: "value1", key2: "value2" }, myFunction); function myFunction (event) { $("#myid").text(event.data.key1); } }); </script> </head> <body> <input id= "btn1" type="button" value="click me" /> <div id = "myid" style="border:2px solid blue; width:400px; height:300px"> </body> </html>
[ { "code": null, "e": 1136, "s": 1062, "text": "To pass a jQuery event as a parameter in a method, use the bind() method." }, { "code": null, "e": 1226, "s": 1136, "text": "You can try to run the following code to learn how to apss a jQuery event as a parameter:" }, { "code": null, "e": 1236, "s": 1226, "text": "Live Demo" }, { "code": null, "e": 1725, "s": 1236, "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 $(\"#btn1\").bind(\"click\", { key1: \"value1\", key2: \"value2\" }, myFunction);\n function myFunction (event)\n {\n $(\"#myid\").text(event.data.key1);\n }\n});\n</script>\n</head>\n<body>\n\n<input id= \"btn1\" type=\"button\" value=\"click me\" />\n<div id = \"myid\" style=\"border:2px solid blue; width:400px; height:300px\">\n\n</body>\n</html>" } ]
Execute VBScript Online
HTML File with VBScript
[]
MySQL query to select rows except first row in descending order?
Let us first create a table − mysql> create table DemoTable -> ( -> Amount int -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select *from DemoTable; +--------+ | Amount | +--------+ | 10 | | 20 | | 30 | | 40 | +--------+ 4 rows in set (0.00 sec) Following is the query to select rows except first row in descending order − mysql> select *from DemoTable WHERE Amount NOT IN (SELECT MAX(Amount) from DemoTable) ORDER BY Amount DESC; +--------+ | Amount | +--------+ | 30 | | 20 | | 10 | +--------+ 3 rows in set (0.05 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1193, "s": 1092, "text": "mysql> create table DemoTable\n -> (\n -> Amount int\n -> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1249, "s": 1193, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1560, "s": 1249, "text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable values(40);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1620, "s": 1560, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1651, "s": 1620, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1764, "s": 1651, "text": "+--------+\n| Amount |\n+--------+\n| 10 |\n| 20 |\n| 30 |\n| 40 |\n+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1841, "s": 1764, "text": "Following is the query to select rows except first row in descending order −" }, { "code": null, "e": 1949, "s": 1841, "text": "mysql> select *from DemoTable WHERE Amount NOT IN (SELECT MAX(Amount) from DemoTable) ORDER BY Amount DESC;" }, { "code": null, "e": 2051, "s": 1949, "text": "+--------+\n| Amount |\n+--------+\n| 30 |\n| 20 |\n| 10 |\n+--------+\n3 rows in set (0.05 sec)" } ]
MySQL SELECT products WHERE 'average price per product' < value?
Let us first create a table − mysql> create table DemoTable848( ProductId int, ProductPrice int ); Query OK, 0 rows affected (1.20 sec) Insert some records in the table using insert command − mysql> insert into DemoTable848 values(100,30); Query OK, 1 row affected (0.57 sec) mysql> insert into DemoTable848 values(101,50); Query OK, 1 row affected (1.06 sec) mysql> insert into DemoTable848 values(100,40); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable848 values(101,25); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable848 values(100,20); Query OK, 1 row affected (0.31 sec) Display all records from the table using select statement − mysql> select *from DemoTable848; This will produce the following output − +-----------+--------------+ | ProductId | ProductPrice | +-----------+--------------+ | 100 | 30 | | 101 | 50 | | 100 | 40 | | 101 | 25 | | 100 | 20 | +-----------+--------------+ 5 rows in set (0.00 sec) Following is the query to select products WHERE 'average price per product' < value. Here, we wanted the average to be less than 35. The same is only valid for corresponding column values with ProductId 100 − mysql> select ProductId,avg(ProductPrice) from DemoTable848 group by ProductId having AVG(ProductPrice) < 35; This will produce the following output − +-----------+-------------------+ | ProductId | avg(ProductPrice) | +-----------+-------------------+ | 100 | 30.0000 | +-----------+-------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1204, "s": 1092, "text": "mysql> create table DemoTable848(\n ProductId int,\n ProductPrice int\n);\nQuery OK, 0 rows affected (1.20 sec)" }, { "code": null, "e": 1260, "s": 1204, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1680, "s": 1260, "text": "mysql> insert into DemoTable848 values(100,30);\nQuery OK, 1 row affected (0.57 sec)\nmysql> insert into DemoTable848 values(101,50);\nQuery OK, 1 row affected (1.06 sec)\nmysql> insert into DemoTable848 values(100,40);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable848 values(101,25);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable848 values(100,20);\nQuery OK, 1 row affected (0.31 sec)" }, { "code": null, "e": 1740, "s": 1680, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1774, "s": 1740, "text": "mysql> select *from DemoTable848;" }, { "code": null, "e": 1815, "s": 1774, "text": "This will produce the following output −" }, { "code": null, "e": 2101, "s": 1815, "text": "+-----------+--------------+\n| ProductId | ProductPrice |\n+-----------+--------------+\n| 100 | 30 |\n| 101 | 50 |\n| 100 | 40 |\n| 101 | 25 |\n| 100 | 20 |\n+-----------+--------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2310, "s": 2101, "text": "Following is the query to select products WHERE 'average price per product' < value. Here, we wanted the average to be less than 35. The same is only valid for corresponding column values with ProductId 100 −" }, { "code": null, "e": 2420, "s": 2310, "text": "mysql> select ProductId,avg(ProductPrice) from DemoTable848 group by ProductId having AVG(ProductPrice) < 35;" }, { "code": null, "e": 2461, "s": 2420, "text": "This will produce the following output −" }, { "code": null, "e": 2655, "s": 2461, "text": "+-----------+-------------------+\n| ProductId | avg(ProductPrice) |\n+-----------+-------------------+\n| 100 | 30.0000 |\n+-----------+-------------------+\n1 row in set (0.00 sec)" } ]
Difference between DataClass vs NamedTuple vs Object in Python - GeeksforGeeks
01 Aug, 2020 Data Class: Data Class is a type of class that is used to store data without any functionality. These data classes are just regular classes having the main purpose to store state and data without knowing the constraints and logic behind it. Whenever you create a class that mostly contains attributes and certain properties to deal with the data and its representation. Example: Python3 # Importing dataclass module from dataclasses import dataclass # Annotation@dataclass # Class with attributesclass GeeksArticle(): """A class for holding an article content""" # Attributes Declaration # using Type Hints topic: str contributor: str language: str upvotes: int # A DataClass object article = GeeksArticle("DataClasses", "nightfury1", "Python", 1) print(article) Output: GfgArticle(topic=’DataClasses’, contributor=’nightfury1’, language=’Python’, upvotes=1) NamedTuple: The NamedTuple is a class that contains the data like a dictionary format stored under the ‘collections‘ module. It stored the data in a key-value format where each key having mapped to more values. So, we access those data using a specific key or can use the indexes. Example: Python3 # Python script to demonstrate namedtuple() # importing nametuple() from collections module from collections import namedtuple # Declaring namedtuple() Contributor = namedtuple('Contributor', ['topic', 'author', 'post']) # Adding values C = Contributor('Difference between DataClass vs NamedTuple vs Object in Python', 'night_fury1', 'Technical Content Writer Intern') # Access using index print ("The Article Topic : ", end ="") print (C[0]) # Access using name print ("The Article Contributor Name : ", end ="") print (C.author) # Access using getattr() print ("The Article Contributor Post : ", end ="") print (getattr(C, 'post')) Output: The Article Topic : Difference between DataClass vs NamedTuple vs Object in PythonThe Article Contributor Name : night_fury1The Article Contributor Post : Technical Content Writer Intern Object: An object is simply a collection of data (variables) and methods (functions) that act on those data. In other words, we say that Object is an instance of the class. Example: Python3 # Python script for demostraation of objectclass Gfg: def __init__(self, topic, contributor): self.topic = topic self.contributor = contributor def myfunc(self): print("Article: ", self.topic) print("Contributor: ", self.contributor) # objects creation g = Gfg("Difference between DataClass vs NamedTuple vs Object in Python", "nightfury1") # function callg.myfunc() Output: Article: Difference between DataClass vs NamedTuple vs Object in PythonContributor: nightfury1 Table of difference between DataClass, NamedTuple and Object DataClass NamedTuple Object Python collections-module python-oop-concepts 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n01 Aug, 2020" }, { "code": null, "e": 24582, "s": 24212, "text": "Data Class: Data Class is a type of class that is used to store data without any functionality. These data classes are just regular classes having the main purpose to store state and data without knowing the constraints and logic behind it. Whenever you create a class that mostly contains attributes and certain properties to deal with the data and its representation." }, { "code": null, "e": 24591, "s": 24582, "text": "Example:" }, { "code": null, "e": 24599, "s": 24591, "text": "Python3" }, { "code": "# Importing dataclass module from dataclasses import dataclass # Annotation@dataclass # Class with attributesclass GeeksArticle(): \"\"\"A class for holding an article content\"\"\" # Attributes Declaration # using Type Hints topic: str contributor: str language: str upvotes: int # A DataClass object article = GeeksArticle(\"DataClasses\", \"nightfury1\", \"Python\", 1) print(article)", "e": 25010, "s": 24599, "text": null }, { "code": null, "e": 25018, "s": 25010, "text": "Output:" }, { "code": null, "e": 25106, "s": 25018, "text": "GfgArticle(topic=’DataClasses’, contributor=’nightfury1’, language=’Python’, upvotes=1)" }, { "code": null, "e": 25387, "s": 25106, "text": "NamedTuple: The NamedTuple is a class that contains the data like a dictionary format stored under the ‘collections‘ module. It stored the data in a key-value format where each key having mapped to more values. So, we access those data using a specific key or can use the indexes." }, { "code": null, "e": 25396, "s": 25387, "text": "Example:" }, { "code": null, "e": 25404, "s": 25396, "text": "Python3" }, { "code": "# Python script to demonstrate namedtuple() # importing nametuple() from collections module from collections import namedtuple # Declaring namedtuple() Contributor = namedtuple('Contributor', ['topic', 'author', 'post']) # Adding values C = Contributor('Difference between DataClass vs NamedTuple vs Object in Python', 'night_fury1', 'Technical Content Writer Intern') # Access using index print (\"The Article Topic : \", end =\"\") print (C[0]) # Access using name print (\"The Article Contributor Name : \", end =\"\") print (C.author) # Access using getattr() print (\"The Article Contributor Post : \", end =\"\") print (getattr(C, 'post'))", "e": 26091, "s": 25404, "text": null }, { "code": null, "e": 26099, "s": 26091, "text": "Output:" }, { "code": null, "e": 26286, "s": 26099, "text": "The Article Topic : Difference between DataClass vs NamedTuple vs Object in PythonThe Article Contributor Name : night_fury1The Article Contributor Post : Technical Content Writer Intern" }, { "code": null, "e": 26459, "s": 26286, "text": "Object: An object is simply a collection of data (variables) and methods (functions) that act on those data. In other words, we say that Object is an instance of the class." }, { "code": null, "e": 26468, "s": 26459, "text": "Example:" }, { "code": null, "e": 26476, "s": 26468, "text": "Python3" }, { "code": "# Python script for demostraation of objectclass Gfg: def __init__(self, topic, contributor): self.topic = topic self.contributor = contributor def myfunc(self): print(\"Article: \", self.topic) print(\"Contributor: \", self.contributor) # objects creation g = Gfg(\"Difference between DataClass vs NamedTuple vs Object in Python\", \"nightfury1\") # function callg.myfunc()", "e": 26872, "s": 26476, "text": null }, { "code": null, "e": 26880, "s": 26872, "text": "Output:" }, { "code": null, "e": 26977, "s": 26880, "text": "Article: Difference between DataClass vs NamedTuple vs Object in PythonContributor: nightfury1" }, { "code": null, "e": 27038, "s": 26977, "text": "Table of difference between DataClass, NamedTuple and Object" }, { "code": null, "e": 27048, "s": 27038, "text": "DataClass" }, { "code": null, "e": 27059, "s": 27048, "text": "NamedTuple" }, { "code": null, "e": 27066, "s": 27059, "text": "Object" }, { "code": null, "e": 27092, "s": 27066, "text": "Python collections-module" }, { "code": null, "e": 27112, "s": 27092, "text": "python-oop-concepts" }, { "code": null, "e": 27119, "s": 27112, "text": "Python" }, { "code": null, "e": 27217, "s": 27119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27226, "s": 27217, "text": "Comments" }, { "code": null, "e": 27239, "s": 27226, "text": "Old Comments" }, { "code": null, "e": 27271, "s": 27239, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27326, "s": 27271, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27382, "s": 27326, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27421, "s": 27382, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27463, "s": 27421, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27505, "s": 27463, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27536, "s": 27505, "text": "Python | os.path.join() method" }, { "code": null, "e": 27558, "s": 27536, "text": "Defaultdict in Python" }, { "code": null, "e": 27587, "s": 27558, "text": "Create a directory in Python" } ]
How to use finally on promise with then and catch in Javascript?
When a promise is settled, i.e either fulfilled or rejected, the specified callback function in finally method is invoked. The finally() method also returns a Promise. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. Let us look at an example, new Promise( (resolve) => setTimeout(resolve("success"), 1000) ).then(val => console.log(val)).finally(() => console.log("Promise complete!")) success Promise complete! Now let us look what happens if a promise fails − // No method get on undefined. This will throw an error new Promise(() => undefined.get()) .then(val => console.log(val)) .catch(err => console.log("Failed!")) .finally(() => console.log("Promise complete!")) Failed! Promise complete! Note in both the cases whether failed or succeeded, the promise executed the finally statement.
[ { "code": null, "e": 1230, "s": 1062, "text": "When a promise is settled, i.e either fulfilled or rejected, the specified callback function in finally method is invoked. The finally() method also returns a Promise." }, { "code": null, "e": 1393, "s": 1230, "text": "This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. Let us look at an example," }, { "code": null, "e": 1539, "s": 1393, "text": "new Promise(\n (resolve) => setTimeout(resolve(\"success\"), 1000)\n).then(val => console.log(val)).finally(() => console.log(\"Promise complete!\"))" }, { "code": null, "e": 1565, "s": 1539, "text": "success\nPromise complete!" }, { "code": null, "e": 1615, "s": 1565, "text": "Now let us look what happens if a promise fails −" }, { "code": null, "e": 1833, "s": 1615, "text": "// No method get on undefined. This will throw an error\nnew Promise(() => undefined.get())\n .then(val => console.log(val))\n .catch(err => console.log(\"Failed!\"))\n .finally(() => console.log(\"Promise complete!\"))" }, { "code": null, "e": 1860, "s": 1833, "text": "Failed! \nPromise complete!" }, { "code": null, "e": 1956, "s": 1860, "text": "Note in both the cases whether failed or succeeded, the promise executed the finally statement." } ]
How can MySQL IF ELSEIF ELSE statement be used in a stored procedure?
MySQL IF ELSEIF ELSE execute the statements based on multiple expressions Its syntax is as follows − IF expression THEN statements; ELSEIF elseif-expression THEN elseif-statements; ... ... ... ... ELSE else-statements; END IF; The statements must end with a semicolon. To demonstrate the use of IF ELSEIF ELSE statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘student_info’ − mysql> Select * from student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 125 | Raman | Shimla | Computers | +------+---------+------------+------------+ 3 rows in set (0.00 sec) The following query will create a procedure named ‘coursedetails_IF_ELSEIF’ which have IF ELSEIF ELSE statements in it − mysql> DELIMITER // ; mysql> CREATE PROCEDURE coursedetails_IF_ELSEIF(IN S_Subject Varchar(20), OUT S_Course varchar(20)) -> BEGIN -> DECLARE Sub Varchar(20); -> SELECT Subject INTO SUB -> FROM Student_info WHERE S_Subject = Subject; -> IF Sub = 'Computers' THEN -> SET S_Course = 'B.Tech(CSE)'; -> ELSEIF Sub = 'History' THEN -> SET S_Course = 'Masters in History'; -> ELSEIF Sub = 'Literature' THEN -> SET S_Course = 'Masters in English'; -> END IF; -> END // Query OK, 0 rows affected (0.00 sec) Now, we can see the result below when we invoke this procedure − mysql> Delimiter ; // mysql> CALL coursedetails_IF_ELSEIF('Computers', @S_Course); Query OK, 1 row affected (0.00 sec) mysql> Select @S_Course; +-------------+ | @S_Course | +-------------+ | B.Tech(CSE) | +-------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_IF_ELSEIF ('Literature', @S_Course); Query OK, 1 row affected (0.00 sec) mysql> Select @S_Course; +--------------------+ | @S_Course | +--------------------+ | Masters in English | +--------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1163, "s": 1062, "text": "MySQL IF ELSEIF ELSE execute the statements based on multiple expressions Its syntax is as follows −" }, { "code": null, "e": 1297, "s": 1163, "text": "IF expression THEN\n statements;\nELSEIF elseif-expression THEN\n elseif-statements;\n... ... ... ...\nELSE\n else-statements;\nEND IF;" }, { "code": null, "e": 1339, "s": 1297, "text": "The statements must end with a semicolon." }, { "code": null, "e": 1550, "s": 1339, "text": "To demonstrate the use of IF ELSEIF ELSE statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘student_info’ −" }, { "code": null, "e": 1925, "s": 1550, "text": "mysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 125 | Raman | Shimla | Computers |\n+------+---------+------------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2046, "s": 1925, "text": "The following query will create a procedure named ‘coursedetails_IF_ELSEIF’ which have IF ELSEIF ELSE statements in it −" }, { "code": null, "e": 2593, "s": 2046, "text": "mysql> DELIMITER // ;\nmysql> CREATE PROCEDURE coursedetails_IF_ELSEIF(IN S_Subject Varchar(20), OUT S_Course varchar(20))\n -> BEGIN\n -> DECLARE Sub Varchar(20);\n -> SELECT Subject INTO SUB\n -> FROM Student_info WHERE S_Subject = Subject;\n -> IF Sub = 'Computers' THEN\n -> SET S_Course = 'B.Tech(CSE)';\n -> ELSEIF Sub = 'History' THEN\n -> SET S_Course = 'Masters in History';\n -> ELSEIF Sub = 'Literature' THEN\n -> SET S_Course = 'Masters in English';\n -> END IF;\n -> END //\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2658, "s": 2593, "text": "Now, we can see the result below when we invoke this procedure −" }, { "code": null, "e": 3173, "s": 2658, "text": "mysql> Delimiter ; //\n\nmysql> CALL coursedetails_IF_ELSEIF('Computers', @S_Course);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> Select @S_Course;\n+-------------+\n| @S_Course |\n+-------------+\n| B.Tech(CSE) |\n+-------------+\n1 row in set (0.00 sec)\n\nmysql> CALL coursedetails_IF_ELSEIF ('Literature', @S_Course);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> Select @S_Course;\n+--------------------+\n| @S_Course |\n+--------------------+\n| Masters in English |\n+--------------------+\n1 row in set (0.00 sec)" } ]
Angular Google Charts - Basic Bar Chart
Following is an example of a basic Bar Chart. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a basic Bar Chart. We've used BarChart class to show bar based chart. type = 'BarChart'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Population (in millions)'; type = 'BarChart'; data = [ ["2012", 900], ["2013", 1000], ["2014", 1170], ["2015", 1250], ["2016", 1530] ]; columnNames = ['Year', 'Asia']; options = { }; width = 550; height = 400; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 1842, "s": 1796, "text": "Following is an example of a basic Bar Chart." }, { "code": null, "e": 1999, "s": 1842, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a basic Bar Chart." }, { "code": null, "e": 2050, "s": 1999, "text": "We've used BarChart class to show bar based chart." }, { "code": null, "e": 2070, "s": 2050, "text": "type = 'BarChart';\n" }, { "code": null, "e": 2087, "s": 2070, "text": "app.component.ts" }, { "code": null, "e": 2552, "s": 2087, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Population (in millions)';\n type = 'BarChart';\n data = [\n [\"2012\", 900],\n [\"2013\", 1000],\n [\"2014\", 1170],\n [\"2015\", 1250],\n [\"2016\", 1530]\n ];\n columnNames = ['Year', 'Asia'];\n options = { };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 2571, "s": 2552, "text": "Verify the result." }, { "code": null, "e": 2606, "s": 2571, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2620, "s": 2606, "text": " Anadi Sharma" }, { "code": null, "e": 2655, "s": 2620, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2669, "s": 2655, "text": " Anadi Sharma" }, { "code": null, "e": 2704, "s": 2669, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 2724, "s": 2704, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 2759, "s": 2724, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2776, "s": 2759, "text": " Frahaan Hussain" }, { "code": null, "e": 2809, "s": 2776, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 2821, "s": 2809, "text": " Senol Atac" }, { "code": null, "e": 2856, "s": 2821, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2868, "s": 2856, "text": " Senol Atac" }, { "code": null, "e": 2875, "s": 2868, "text": " Print" }, { "code": null, "e": 2886, "s": 2875, "text": " Add Notes" } ]
C# | Getting an enumerator that iterates through LinkedList<T> - GeeksforGeeks
01 Feb, 2019 LinkedList<T>.GetEnumerator Method is used to get an enumerator that iterates through the LinkedList<T>. Syntax: public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator (); Return Value: It returns an LinkedList<T>.Enumerator for the LinkedList<T>. Below programs illustrate the use of above-discussed method: Example 1: // C# code to get an enumerator that// iterates through the LinkedList<T>using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get an Enumerator // for the List. LinkedList<int>.Enumerator em = myList.GetEnumerator(); display(em); } // display method static void display(IEnumerator<int> em) { while (em.MoveNext()) { int val = em.Current; Console.WriteLine(val); } }} 2 4 6 8 Example 2: // C# code to get an enumerator that// iterates through the LinkedList<T>using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("GeeksforGeeks"); myList.AddLast("GFG"); myList.AddLast("Data Structures"); myList.AddLast("Noida"); // To get an Enumerator // for the LinkedList<T>. LinkedList<string>.Enumerator em = myList.GetEnumerator(); display(em); } // display method static void display(IEnumerator<string> em) { while (em.MoveNext()) { string val = em.Current; Console.WriteLine(val); } }} GeeksforGeeks GFG Data Structures Noida Note: The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.getenumerator?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-LinkedList CSharp-LinkedList-Methods C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to calculate Electricity Bill Linked List Implementation in C# C# | How to insert an element in an Array? HashSet in C# with Examples Lambda Expressions in C# Main Method in C# Difference between Hashtable and Dictionary in C# C# | Dictionary.Add() Method Collections in C# Different Ways to Convert Char Array to String in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24016, "s": 23911, "text": "LinkedList<T>.GetEnumerator Method is used to get an enumerator that iterates through the LinkedList<T>." }, { "code": null, "e": 24024, "s": 24016, "text": "Syntax:" }, { "code": null, "e": 24101, "s": 24024, "text": "public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator ();" }, { "code": null, "e": 24177, "s": 24101, "text": "Return Value: It returns an LinkedList<T>.Enumerator for the LinkedList<T>." }, { "code": null, "e": 24238, "s": 24177, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 24249, "s": 24238, "text": "Example 1:" }, { "code": "// C# code to get an enumerator that// iterates through the LinkedList<T>using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get an Enumerator // for the List. LinkedList<int>.Enumerator em = myList.GetEnumerator(); display(em); } // display method static void display(IEnumerator<int> em) { while (em.MoveNext()) { int val = em.Current; Console.WriteLine(val); } }}", "e": 25011, "s": 24249, "text": null }, { "code": null, "e": 25020, "s": 25011, "text": "2\n4\n6\n8\n" }, { "code": null, "e": 25031, "s": 25020, "text": "Example 2:" }, { "code": "// C# code to get an enumerator that// iterates through the LinkedList<T>using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"GeeksforGeeks\"); myList.AddLast(\"GFG\"); myList.AddLast(\"Data Structures\"); myList.AddLast(\"Noida\"); // To get an Enumerator // for the LinkedList<T>. LinkedList<string>.Enumerator em = myList.GetEnumerator(); display(em); } // display method static void display(IEnumerator<string> em) { while (em.MoveNext()) { string val = em.Current; Console.WriteLine(val); } }}", "e": 25856, "s": 25031, "text": null }, { "code": null, "e": 25897, "s": 25856, "text": "GeeksforGeeks\nGFG\nData Structures\nNoida\n" }, { "code": null, "e": 25903, "s": 25897, "text": "Note:" }, { "code": null, "e": 26075, "s": 25903, "text": "The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator." }, { "code": null, "e": 26196, "s": 26075, "text": "Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection." }, { "code": null, "e": 26313, "s": 26196, "text": "Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element." }, { "code": null, "e": 26549, "s": 26313, "text": "An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined." }, { "code": null, "e": 26583, "s": 26549, "text": "This method is an O(1) operation." }, { "code": null, "e": 26594, "s": 26583, "text": "Reference:" }, { "code": null, "e": 26716, "s": 26594, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.getenumerator?view=netframework-4.7.2" }, { "code": null, "e": 26741, "s": 26716, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 26759, "s": 26741, "text": "CSharp-LinkedList" }, { "code": null, "e": 26785, "s": 26759, "text": "CSharp-LinkedList-Methods" }, { "code": null, "e": 26788, "s": 26785, "text": "C#" }, { "code": null, "e": 26886, "s": 26788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26895, "s": 26886, "text": "Comments" }, { "code": null, "e": 26908, "s": 26895, "text": "Old Comments" }, { "code": null, "e": 26946, "s": 26908, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 26979, "s": 26946, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27022, "s": 26979, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27050, "s": 27022, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27075, "s": 27050, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27093, "s": 27075, "text": "Main Method in C#" }, { "code": null, "e": 27143, "s": 27093, "text": "Difference between Hashtable and Dictionary in C#" }, { "code": null, "e": 27172, "s": 27143, "text": "C# | Dictionary.Add() Method" }, { "code": null, "e": 27190, "s": 27172, "text": "Collections in C#" } ]
Difference between “INNER JOIN” and “OUTER JOIN” - GeeksforGeeks
10 Jun, 2021 JOINS :Joins in SQL are used to combine rows from multiple tables on a specific condition, which is a relation between the columns of two tables. And there are different types of joins and in this article let us cover INNER JOIN and OUTER JOIN and their differences. Let us consider the two tables student and location and see how the differences would look like by combing tables using different joins.Table1 – student Table2 – location Firstly, creating tables and inserting data into tables using MSSQL as a server: Creating the student tables and location using the following queries – Created two tables Inserting rows into student tables and location using the following queries – Inserted data into tables Viewing the tables using the following query – Viewing data from tables Types of JOINS : 1. INNER JOIN EQUI JOIN SELF JOIN 2. OUTER JOIN LEFT JOIN RIGHT JOIN FULL JOIN 1. Inner Join : When the inner join is used, it considers only those attributes that we want to match both the table and, if anything that doesn’t, wouldn’t be included in our result table.Two types of Inner Join – Equi Join – It is the subcategory of Inner Join where it is restricted to only equality condition in the table. The join is said to be Equi join if and only if there is an equality condition in the query.The query for Equi Join on the above two tables: SELECT * FROM student INNER JOIN location ON student.student_id = location.student_id; OUTPUT TABLE – Self Join – Self Join considers the same table as another table and outputs the resultant table after the required condition satisfies. The query for Self Join is in the above two tables: SELECT s1.student_id ,s1.student_name FROM student s1 INNER JOIN student s2 ON s1.student_name= s2.student_name AND s1.student_id<> s2.student_id; OUTPUT TABLE – Venn diagram representation of the Inner Join – 2. Outer Join :In the outer join, we consider any of the tables completely or both such that the remaining fields that were unmatched in both the tables were kept NULL. Three types of Outer Join –1. Left Join or (left outer join) – In left join, we consider the left table completely and the matched attributes (based on condition) in the right table along with, the unmatched attributes of the left table with the right table are placed NULL with respect to the column in the left table.The query for Left Join is in the above two tables: SELECT * FROM student LEFT JOIN location ON student.student_id = location.student_id; OUTPUT TABLE: Venn diagram representation of the Left Join: Right, Join – In the right join, we consider the right table completely and the matched attributes (based on condition) in the left table along with, the unmatched attributes of the right table with the left table are placed NULL with respect to a column in the right table.The query for Right Join is in the above two tables: SELECT * FROM student RIGHT JOIN location ON student.student_id = location.student_id; OUTPUT TABLE – Venn diagram representation of the Right Join – Full Join –It is the union of both left join and right join where all the columns of the left table and the right table are considered where the unmatched or unfound attributes of the left table or right table will be placed with NULL in the resultant table.The query for Full Join is in the above two tables: SELECT * FROM student FULL JOIN location ON student.student_id = location.student_id; OUTPUT TABLE – Venn diagram representation of the full Join – DBMS-SQL Picked DBMS Difference Between GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS KDD Process in Data Mining Relational Model in DBMS What is Temporary Table in SQL? 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": 24250, "s": 24222, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24518, "s": 24250, "text": "JOINS :Joins in SQL are used to combine rows from multiple tables on a specific condition, which is a relation between the columns of two tables. And there are different types of joins and in this article let us cover INNER JOIN and OUTER JOIN and their differences." }, { "code": null, "e": 24664, "s": 24518, "text": "Let us consider the two tables student and location and see how the differences would look like by combing tables using different joins.Table1 – " }, { "code": null, "e": 24750, "s": 24664, "text": " student" }, { "code": null, "e": 24759, "s": 24750, "text": "Table2 –" }, { "code": null, "e": 24840, "s": 24759, "text": " location" }, { "code": null, "e": 24922, "s": 24840, "text": " Firstly, creating tables and inserting data into tables using MSSQL as a server:" }, { "code": null, "e": 24993, "s": 24922, "text": "Creating the student tables and location using the following queries –" }, { "code": null, "e": 25012, "s": 24993, "text": "Created two tables" }, { "code": null, "e": 25090, "s": 25012, "text": "Inserting rows into student tables and location using the following queries –" }, { "code": null, "e": 25116, "s": 25090, "text": "Inserted data into tables" }, { "code": null, "e": 25163, "s": 25116, "text": "Viewing the tables using the following query –" }, { "code": null, "e": 25188, "s": 25163, "text": "Viewing data from tables" }, { "code": null, "e": 25205, "s": 25188, "text": "Types of JOINS :" }, { "code": null, "e": 25219, "s": 25205, "text": "1. INNER JOIN" }, { "code": null, "e": 25229, "s": 25219, "text": "EQUI JOIN" }, { "code": null, "e": 25239, "s": 25229, "text": "SELF JOIN" }, { "code": null, "e": 25254, "s": 25239, "text": "2. OUTER JOIN " }, { "code": null, "e": 25264, "s": 25254, "text": "LEFT JOIN" }, { "code": null, "e": 25275, "s": 25264, "text": "RIGHT JOIN" }, { "code": null, "e": 25285, "s": 25275, "text": "FULL JOIN" }, { "code": null, "e": 25500, "s": 25285, "text": "1. Inner Join : When the inner join is used, it considers only those attributes that we want to match both the table and, if anything that doesn’t, wouldn’t be included in our result table.Two types of Inner Join –" }, { "code": null, "e": 25753, "s": 25500, "text": "Equi Join – It is the subcategory of Inner Join where it is restricted to only equality condition in the table. The join is said to be Equi join if and only if there is an equality condition in the query.The query for Equi Join on the above two tables:" }, { "code": null, "e": 25844, "s": 25753, "text": "SELECT * FROM \nstudent \nINNER JOIN \nlocation\nON \nstudent.student_id = location.student_id;" }, { "code": null, "e": 25864, "s": 25844, "text": " OUTPUT TABLE –" }, { "code": null, "e": 26000, "s": 25864, "text": "Self Join – Self Join considers the same table as another table and outputs the resultant table after the required condition satisfies." }, { "code": null, "e": 26052, "s": 26000, "text": "The query for Self Join is in the above two tables:" }, { "code": null, "e": 26203, "s": 26052, "text": "SELECT s1.student_id ,s1.student_name FROM \nstudent s1\nINNER JOIN \nstudent s2 \nON \ns1.student_name= s2.student_name AND s1.student_id<> s2.student_id;" }, { "code": null, "e": 26218, "s": 26203, "text": "OUTPUT TABLE –" }, { "code": null, "e": 26267, "s": 26218, "text": " Venn diagram representation of the Inner Join –" }, { "code": null, "e": 26436, "s": 26267, "text": "2. Outer Join :In the outer join, we consider any of the tables completely or both such that the remaining fields that were unmatched in both the tables were kept NULL." }, { "code": null, "e": 26807, "s": 26436, "text": "Three types of Outer Join –1. Left Join or (left outer join) – In left join, we consider the left table completely and the matched attributes (based on condition) in the right table along with, the unmatched attributes of the left table with the right table are placed NULL with respect to the column in the left table.The query for Left Join is in the above two tables:" }, { "code": null, "e": 26897, "s": 26807, "text": "SELECT * FROM \nstudent \nLEFT JOIN \nlocation\nON \nstudent.student_id = location.student_id;" }, { "code": null, "e": 26912, "s": 26897, "text": "OUTPUT TABLE: " }, { "code": null, "e": 26958, "s": 26912, "text": "Venn diagram representation of the Left Join:" }, { "code": null, "e": 27285, "s": 26958, "text": "Right, Join – In the right join, we consider the right table completely and the matched attributes (based on condition) in the left table along with, the unmatched attributes of the right table with the left table are placed NULL with respect to a column in the right table.The query for Right Join is in the above two tables:" }, { "code": null, "e": 27376, "s": 27285, "text": "SELECT * FROM \nstudent \nRIGHT JOIN \nlocation\nON \nstudent.student_id = location.student_id;" }, { "code": null, "e": 27391, "s": 27376, "text": "OUTPUT TABLE –" }, { "code": null, "e": 27440, "s": 27391, "text": " Venn diagram representation of the Right Join –" }, { "code": null, "e": 27750, "s": 27440, "text": "Full Join –It is the union of both left join and right join where all the columns of the left table and the right table are considered where the unmatched or unfound attributes of the left table or right table will be placed with NULL in the resultant table.The query for Full Join is in the above two tables:" }, { "code": null, "e": 27840, "s": 27750, "text": "SELECT * FROM \nstudent \nFULL JOIN \nlocation\nON \nstudent.student_id = location.student_id;" }, { "code": null, "e": 27855, "s": 27840, "text": "OUTPUT TABLE –" }, { "code": null, "e": 27903, "s": 27855, "text": "Venn diagram representation of the full Join – " }, { "code": null, "e": 27912, "s": 27903, "text": "DBMS-SQL" }, { "code": null, "e": 27919, "s": 27912, "text": "Picked" }, { "code": null, "e": 27924, "s": 27919, "text": "DBMS" }, { "code": null, "e": 27943, "s": 27924, "text": "Difference Between" }, { "code": null, "e": 27951, "s": 27943, "text": "GATE CS" }, { "code": null, "e": 27955, "s": 27951, "text": "SQL" }, { "code": null, "e": 27960, "s": 27955, "text": "DBMS" }, { "code": null, "e": 27964, "s": 27960, "text": "SQL" }, { "code": null, "e": 28062, "s": 27964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28071, "s": 28062, "text": "Comments" }, { "code": null, "e": 28084, "s": 28071, "text": "Old Comments" }, { "code": null, "e": 28109, "s": 28084, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 28152, "s": 28109, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 28179, "s": 28152, "text": "KDD Process in Data Mining" }, { "code": null, "e": 28204, "s": 28179, "text": "Relational Model in DBMS" }, { "code": null, "e": 28236, "s": 28204, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28267, "s": 28236, "text": "Difference between BFS and DFS" }, { "code": null, "e": 28307, "s": 28267, "text": "Class method vs Static method in Python" }, { "code": null, "e": 28339, "s": 28307, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28377, "s": 28339, "text": "Difference between Process and Thread" } ]
HTML 5 video or audio playlist
Use HTML with JavaScript to add playlist. The onended event fires when the audio/video has reached the end. You can add messages like “Thank you for watching”, “Stay tuned!”, etc You can try to run the following code to implement the onended attribute − <!DOCTYPE HTML> <html> <body> <video width = "300" height = "200" controls onended = "display()"> <source src = "/html5/foo.ogg" type = "video/ogg" /> Your browser does not support the video element. </video> <script> function display() { alert ("Thank you for watching! Stay tuned!"); } </script> </body> </html> You could load the next clip in the onended event like in the below-given code <script > var next = "path/of/next/video.mp4"; var video = document.getElementById('video'); video.onended = function(){ video.src = next; } </script> <video id = "video" src = "path/of/current/video.mp4" autoplayautobuffer controls />
[ { "code": null, "e": 1241, "s": 1062, "text": "Use HTML with JavaScript to add playlist. The onended event fires when the audio/video has reached the end. You can add messages like “Thank you for watching”, “Stay tuned!”, etc" }, { "code": null, "e": 1316, "s": 1241, "text": "You can try to run the following code to implement the onended attribute −" }, { "code": null, "e": 1708, "s": 1316, "text": "<!DOCTYPE HTML>\n<html>\n <body>\n <video width = \"300\" height = \"200\" controls onended = \"display()\">\n <source src = \"/html5/foo.ogg\" type = \"video/ogg\" />\n Your browser does not support the video element.\n </video>\n <script>\n function display() {\n alert (\"Thank you for watching! Stay tuned!\");\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 1787, "s": 1708, "text": "You could load the next clip in the onended event like in the below-given code" }, { "code": null, "e": 2035, "s": 1787, "text": "<script >\n var next = \"path/of/next/video.mp4\";\n var video = document.getElementById('video');\n video.onended = function(){\n video.src = next;\n}\n</script>\n<video id = \"video\" src = \"path/of/current/video.mp4\" autoplayautobuffer controls />" } ]
How to use Dataset in TensorFlow. The built-in Input Pipeline. Never use... | by Francesco Zuppichini | Towards Data Science
The built-in Input Pipeline. Never use ‘feed-dict’ anymore 16/02/2020: I have switched to PyTorch 😍 29/05/2019: I will update the tutorial to tf 2.0 😎 (I am finishing my Master Thesis) Update 2/06/2018: Added second full example to read csv directly into the dataset Update 25/05/2018: Added second full example with a Reinitializable iterator Updated to TensorFlow 1.8 As you should know, feed-dict is the slowest possible way to pass information to TensorFlow and it must be avoided. The correct way to feed data into your models is to use an input pipeline to ensure that the GPU has never to wait for new stuff to come in. Fortunately, TensorFlow has a built-in API, called Dataset to make it easier to accomplish this task. In this tutorial, we are going to see how we can create an input pipeline and how to feed the data into the model efficiently. This article will explain the basic mechanics of the Dataset, covering the most common use cases. You can found all the code as a jupyter notebook here : https://github.com/FrancescoSaverioZuppichini/Tensorflow-Dataset-Tutorial/blob/master/dataset_tutorial.ipynb In order to use a Dataset we need three steps: Importing Data. Create a Dataset instance from some data Create an Iterator. By using the created dataset to make an Iterator instance to iterate through the dataset Consuming Data. By using the created iterator we can get the elements from the dataset to feed the model We first need some data to put inside our dataset This is the common case, we have a numpy array and we want to pass it to tensorflow. # create a random vector of shape (100,2)x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x) We can also pass more than one numpy array, one classic example is when we have a couple of data divided into features and labels features, labels = (np.random.sample((100,2)), np.random.sample((100,1)))dataset = tf.data.Dataset.from_tensor_slices((features,labels)) We can, of course, initialise our dataset with some tensor # using a tensordataset = tf.data.Dataset.from_tensor_slices(tf.random_uniform([100, 2])) This is useful when we want to dynamically change the data inside the Dataset, we will see later how. x = tf.placeholder(tf.float32, shape=[None,2])dataset = tf.data.Dataset.from_tensor_slices(x) We can also initialise a Dataset from a generator, this is useful when we have an array of different elements length (e.g a sequence): # from generatorsequence = np.array([[[1]],[[2],[3]],[[3],[4],[5]]])def generator(): for el in sequence: yield eldataset = tf.data.Dataset().batch(1).from_generator(generator, output_types= tf.int64, output_shapes=(tf.TensorShape([None, 1])))iter = dataset.make_initializable_iterator()el = iter.get_next()with tf.Session() as sess: sess.run(iter.initializer) print(sess.run(el)) print(sess.run(el)) print(sess.run(el)) Ouputs: [[1]][[2] [3]][[3] [4] [5]] In this case, you also need to specify the types and the shapes of your data that will be used to create the correct tensors. You can directly read a csv file into a dataset. For example, I have a csv file with tweets and their sentiment. I can now easily create a Dataset from it by calling tf.contrib.data.make_csv_dataset . Be aware that the iterator will create a dictionary with key as the column names and values as Tensor with the correct row value. # load a csvCSV_PATH = './tweets.csv'dataset = tf.contrib.data.make_csv_dataset(CSV_PATH, batch_size=32)iter = dataset.make_one_shot_iterator()next = iter.get_next()print(next) # next is a dict with key=columns names and value=column datainputs, labels = next['text'], next['sentiment']with tf.Session() as sess: sess.run([inputs, labels]) Where next is {'sentiment': <tf.Tensor 'IteratorGetNext_15:0' shape=(?,) dtype=int32>, 'text': <tf.Tensor 'IteratorGetNext_15:1' shape=(?,) dtype=string>} We have seen how to create a dataset, but how to get our data back? We have to use an Iterator, that will give us the ability to iterate through the dataset and retrieve the real values of the data. There exist four types of iterators. One shot. It can iterate once through a dataset, you cannot feed any value to it. Initializable: You can dynamically change calling its initializer operation and passing the new data with feed_dict . It’s basically a bucket that you can fill with stuff. Reinitializable: It can be initialised from different Dataset. Very useful when you have a training dataset that needs some additional transformation, eg. shuffle, and a testing dataset. It’s like using a tower crane to select a different container. Feedable: It can be used to select with iterator to use. Following the previous example, it’s like a tower crane that selects which tower crane to use to select which container to take. In my opinion is useless. This is the easiest iterator. Using the first example x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)# create the iteratoriter = dataset.make_one_shot_iterator() Then you need to call get_next() to get the tensor that will contain your data ...# create the iteratoriter = dataset.make_one_shot_iterator()el = iter.get_next() We can run el in order to see its value with tf.Session() as sess: print(sess.run(el)) # output: [ 0.42116176 0.40666069] In case we want to build a dynamic dataset in which we can change the data source at runtime, we can create a dataset with a placeholder. Then we can initialize the placeholder using the common feed-dict mechanism. This is done with an initializable iterator. Using example three from last section # using a placeholderx = tf.placeholder(tf.float32, shape=[None,2])dataset = tf.data.Dataset.from_tensor_slices(x)data = np.random.sample((100,2))iter = dataset.make_initializable_iterator() # create the iteratorel = iter.get_next()with tf.Session() as sess: # feed the placeholder with data sess.run(iter.initializer, feed_dict={ x: data }) print(sess.run(el)) # output [ 0.52374458 0.71968478] This time we call make_initializable_iterator . Then, inside thesess scope, we run the initializer operation in order to pass our data, in this case a random numpy array. . Imagine that now we have a train set and a test set, a real common scenario: train_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.array([[1,2]]), np.array([[0]])) Then we would like to train the model and then evaluate it on the test dataset, this can be done by initialising the iterator again after training # initializable iterator to switch between datasetEPOCHS = 10x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])dataset = tf.data.Dataset.from_tensor_slices((x, y))train_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.array([[1,2]]), np.array([[0]]))iter = dataset.make_initializable_iterator()features, labels = iter.get_next()with tf.Session() as sess:# initialise iterator with train data sess.run(iter.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) for _ in range(EPOCHS): sess.run([features, labels])# switch to test data sess.run(iter.initializer, feed_dict={ x: test_data[0], y: test_data[1]}) print(sess.run([features, labels])) The concept is similar to before, we want to dynamic switch between data. But instead of feed new data to the same dataset, we switch dataset. As before, we want to have a train dataset and a test dataset # making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1))) We can create two Datasets # create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices(train_data)test_dataset = tf.data.Dataset.from_tensor_slices(test_data) Now, this is the trick, we create a generic Iterator # create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes) and then two initialization operations: # create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset) We get the next element as before features, labels = iter.get_next() Now, we can directly run the two initialisation operation using our session. Putting all together we get: # Reinitializable iterator to switch between DatasetsEPOCHS = 10# making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1)))# create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices(train_data)test_dataset = tf.data.Dataset.from_tensor_slices(test_data)# create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)features, labels = iter.get_next()# create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset)with tf.Session() as sess: sess.run(train_init_op) # switch to train dataset for _ in range(EPOCHS): sess.run([features, labels]) sess.run(test_init_op) # switch to val dataset print(sess.run([features, labels])) This is very similar to the reinitializable iterator, but instead of switch between datasets, it switch between iterators. After we created two datasets train_dataset = tf.data.Dataset.from_tensor_slices((x,y))test_dataset = tf.data.Dataset.from_tensor_slices((x,y)) One for training and one for testing. Then, we can create our iterator, in this case we use the initializable iterator, but you can also use a one shot iterator train_iterator = train_dataset.make_initializable_iterator()test_iterator = test_dataset.make_initializable_iterator() Now, we need to defined and handle , that will be out placeholder that can be dynamically changed. handle = tf.placeholder(tf.string, shape=[]) Then, similar to before, we define a generic iterator using the shape of the dataset iter = tf.data.Iterator.from_string_handle( handle, train_dataset.output_types, train_dataset.output_shapes) Then, we get the next elements next_elements = iter.get_next() In order to switch between the iterators we just have to call the next_elemenents operation passing the correct handle in the feed_dict. For example, to get one element from the train set: sess.run(next_elements, feed_dict = {handle: train_handle}) If you are using initializable iterators, as we are doing, just remember to initialize them before starting sess.run(train_iterator.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) sess.run(test_iterator.initializer, feed_dict={ x: test_data[0], y: test_data[1]}) Putting all together we get: # feedable iterator to switch between iteratorsEPOCHS = 10# making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1)))# create placeholderx, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])# create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices((x,y))test_dataset = tf.data.Dataset.from_tensor_slices((x,y))# create the iterators from the datasettrain_iterator = train_dataset.make_initializable_iterator()test_iterator = test_dataset.make_initializable_iterator()# same as in the doc https://www.tensorflow.org/programmers_guide/datasets#creating_an_iteratorhandle = tf.placeholder(tf.string, shape=[])iter = tf.data.Iterator.from_string_handle( handle, train_dataset.output_types, train_dataset.output_shapes)next_elements = iter.get_next()with tf.Session() as sess: train_handle = sess.run(train_iterator.string_handle()) test_handle = sess.run(test_iterator.string_handle()) # initialise iterators. sess.run(train_iterator.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) sess.run(test_iterator.initializer, feed_dict={ x: test_data[0], y: test_data[1]}) for _ in range(EPOCHS): x,y = sess.run(next_elements, feed_dict = {handle: train_handle}) print(x, y) x,y = sess.run(next_elements, feed_dict = {handle: test_handle}) print(x,y) In the previous example we have used the session to print the value of the next element in the Dataset. ...next_el = iter.get_next()...print(sess.run(next_el)) # will output the current element In order to pass the data to a model we have to just pass the tensors generated from get_next() In the following snippet we have a Dataset that contains two numpy arrays, using the same example from the first section. Notice that we need to wrap the .random.sample in another numpy array to add a dimension that we is needed to batch the data # using two numpy arraysfeatures, labels = (np.array([np.random.sample((100,2))]), np.array([np.random.sample((100,1))]))dataset = tf.data.Dataset.from_tensor_slices((features,labels)).repeat().batch(BATCH_SIZE) Then as always, we create an iterator iter = dataset.make_one_shot_iterator()x, y = iter.get_next() We make a model, a simple neural network # make a simple modelnet = tf.layers.dense(x, 8) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8)prediction = tf.layers.dense(net, 1)loss = tf.losses.mean_squared_error(prediction, y) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss) We directly use the Tensors from iter.get_next() as input to the first layer and as labels for the loss function. Wrapping all together: EPOCHS = 10BATCH_SIZE = 16# using two numpy arraysfeatures, labels = (np.array([np.random.sample((100,2))]), np.array([np.random.sample((100,1))]))dataset = tf.data.Dataset.from_tensor_slices((features,labels)).repeat().batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()x, y = iter.get_next()# make a simple modelnet = tf.layers.dense(x, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, y) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(EPOCHS): _, loss_value = sess.run([train_op, loss]) print("Iter: {}, Loss: {:.4f}".format(i, loss_value)) Output: Iter: 0, Loss: 0.1328 Iter: 1, Loss: 0.1312 Iter: 2, Loss: 0.1296 Iter: 3, Loss: 0.1281 Iter: 4, Loss: 0.1267 Iter: 5, Loss: 0.1254 Iter: 6, Loss: 0.1242 Iter: 7, Loss: 0.1231 Iter: 8, Loss: 0.1220 Iter: 9, Loss: 0.1210 Usually batching data is a pain in the ass, with the Dataset API we can use the method batch(BATCH_SIZE) that automatically batches the dataset with the provided size. The default value is one. In the following example, we use a batch size of 4 # BATCHINGBATCH_SIZE = 4x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x).batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess: print(sess.run(el)) Output: [[ 0.65686128 0.99373963] [ 0.69690451 0.32446826] [ 0.57148422 0.68688242] [ 0.20335116 0.82473219]] Using .repeat() we can specify the number of times we want the dataset to be iterated. If no parameter is passed it will loop forever, usually is good to just loop forever and directly control the number of epochs with a standard loop. We can shuffle the Dataset by using the method shuffle() that shuffles the dataset by default every epoch. Remember: shuffle the dataset is very important to avoid overfitting. We can also set the parameter buffer_size , a fixed size buffer from which the next element will be uniformly chosen from. Example: # BATCHINGBATCH_SIZE = 4x = np.array([[1],[2],[3],[4]])# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)dataset = dataset.shuffle(buffer_size=100)dataset = dataset.batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess: print(sess.run(el)) First run output: [[4] [2] [3] [1]] Second run output: [[3] [1] [2] [4]] Yep. It was shuffled. If you want, you can also set the seed parameter. You can apply a custom function to each member of a dataset using the map method. In the following example we multiply each element by two: # MAPx = np.array([[1],[2],[3],[4]])# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)dataset = dataset.map(lambda x: x*2)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess:# this will run forever for _ in range(len(x)): print(sess.run(el)) Output: [2][4][6][8] In the example below we train a simple model using batching and we switch between train and test dataset using a Initializable iterator # Wrapping all together -> Switch between train and test set using Initializable iteratorEPOCHS = 10# create a placeholder to dynamically switch between batch sizesbatch_size = tf.placeholder(tf.int64)x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(batch_size).repeat()# using two numpy arraystrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((20,2)), np.random.sample((20,1)))iter = dataset.make_initializable_iterator()features, labels = iter.get_next()# make a simple modelnet = tf.layers.dense(features, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, labels) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # initialise iterator with train data sess.run(iter.initializer, feed_dict={ x: train_data[0], y: train_data[1], batch_size: BATCH_SIZE}) print('Training...') for i in range(EPOCHS): tot_loss = 0 for _ in range(n_batches): _, loss_value = sess.run([train_op, loss]) tot_loss += loss_value print("Iter: {}, Loss: {:.4f}".format(i, tot_loss / n_batches)) # initialise iterator with test data sess.run(iter.initializer, feed_dict={ x: test_data[0], y: test_data[1], batch_size: test_data[0].shape[0]}) print('Test Loss: {:4f}'.format(sess.run(loss))) Notice that we use a placeholder for the batch size in order to dynamically switch it after training Output Training...Iter: 0, Loss: 0.2977Iter: 1, Loss: 0.2152Iter: 2, Loss: 0.1787Iter: 3, Loss: 0.1597Iter: 4, Loss: 0.1277Iter: 5, Loss: 0.1334Iter: 6, Loss: 0.1000Iter: 7, Loss: 0.1154Iter: 8, Loss: 0.0989Iter: 9, Loss: 0.0948Test Loss: 0.082150 In the example below we train a simple model using batching and we switch between train and test dataset using a Reinitializable Iterator # Wrapping all together -> Switch between train and test set using Reinitializable iteratorEPOCHS = 10# create a placeholder to dynamically switch between batch sizesbatch_size = tf.placeholder(tf.int64)x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])train_dataset = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size).repeat()test_dataset = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size) # always batch even if you want to one shot it# using two numpy arraystrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((20,2)), np.random.sample((20,1)))# create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)features, labels = iter.get_next()# create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset)# make a simple modelnet = tf.layers.dense(features, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, labels) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # initialise iterator with train data sess.run(train_init_op, feed_dict = {x : train_data[0], y: train_data[1], batch_size: 16}) print('Training...') for i in range(EPOCHS): tot_loss = 0 for _ in range(n_batches): _, loss_value = sess.run([train_op, loss]) tot_loss += loss_value print("Iter: {}, Loss: {:.4f}".format(i, tot_loss / n_batches)) # initialise iterator with test data sess.run(test_init_op, feed_dict = {x : test_data[0], y: test_data[1], batch_size:len(test_data[0])}) print('Test Loss: {:4f}'.format(sess.run(loss))) TensorFlow dataset tutorial: https://www.tensorflow.org/programmers_guide/datasets Dataset docs: https://www.tensorflow.org/api_docs/python/tf/data/Dataset The Dataset API gives us a fast and robust way to create optimized input pipeline to train, evaluate and test our models. In this article, we have seen most of the common operation we can do with them. You can use the jupyter-notebook that I’ve made for this article as a reference. Thank you for reading,
[ { "code": null, "e": 230, "s": 171, "text": "The built-in Input Pipeline. Never use ‘feed-dict’ anymore" }, { "code": null, "e": 271, "s": 230, "text": "16/02/2020: I have switched to PyTorch 😍" }, { "code": null, "e": 356, "s": 271, "text": "29/05/2019: I will update the tutorial to tf 2.0 😎 (I am finishing my Master Thesis)" }, { "code": null, "e": 438, "s": 356, "text": "Update 2/06/2018: Added second full example to read csv directly into the dataset" }, { "code": null, "e": 515, "s": 438, "text": "Update 25/05/2018: Added second full example with a Reinitializable iterator" }, { "code": null, "e": 541, "s": 515, "text": "Updated to TensorFlow 1.8" }, { "code": null, "e": 798, "s": 541, "text": "As you should know, feed-dict is the slowest possible way to pass information to TensorFlow and it must be avoided. The correct way to feed data into your models is to use an input pipeline to ensure that the GPU has never to wait for new stuff to come in." }, { "code": null, "e": 1027, "s": 798, "text": "Fortunately, TensorFlow has a built-in API, called Dataset to make it easier to accomplish this task. In this tutorial, we are going to see how we can create an input pipeline and how to feed the data into the model efficiently." }, { "code": null, "e": 1125, "s": 1027, "text": "This article will explain the basic mechanics of the Dataset, covering the most common use cases." }, { "code": null, "e": 1181, "s": 1125, "text": "You can found all the code as a jupyter notebook here :" }, { "code": null, "e": 1290, "s": 1181, "text": "https://github.com/FrancescoSaverioZuppichini/Tensorflow-Dataset-Tutorial/blob/master/dataset_tutorial.ipynb" }, { "code": null, "e": 1337, "s": 1290, "text": "In order to use a Dataset we need three steps:" }, { "code": null, "e": 1394, "s": 1337, "text": "Importing Data. Create a Dataset instance from some data" }, { "code": null, "e": 1503, "s": 1394, "text": "Create an Iterator. By using the created dataset to make an Iterator instance to iterate through the dataset" }, { "code": null, "e": 1608, "s": 1503, "text": "Consuming Data. By using the created iterator we can get the elements from the dataset to feed the model" }, { "code": null, "e": 1658, "s": 1608, "text": "We first need some data to put inside our dataset" }, { "code": null, "e": 1743, "s": 1658, "text": "This is the common case, we have a numpy array and we want to pass it to tensorflow." }, { "code": null, "e": 1896, "s": 1743, "text": "# create a random vector of shape (100,2)x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)" }, { "code": null, "e": 2026, "s": 1896, "text": "We can also pass more than one numpy array, one classic example is when we have a couple of data divided into features and labels" }, { "code": null, "e": 2163, "s": 2026, "text": "features, labels = (np.random.sample((100,2)), np.random.sample((100,1)))dataset = tf.data.Dataset.from_tensor_slices((features,labels))" }, { "code": null, "e": 2222, "s": 2163, "text": "We can, of course, initialise our dataset with some tensor" }, { "code": null, "e": 2312, "s": 2222, "text": "# using a tensordataset = tf.data.Dataset.from_tensor_slices(tf.random_uniform([100, 2]))" }, { "code": null, "e": 2414, "s": 2312, "text": "This is useful when we want to dynamically change the data inside the Dataset, we will see later how." }, { "code": null, "e": 2508, "s": 2414, "text": "x = tf.placeholder(tf.float32, shape=[None,2])dataset = tf.data.Dataset.from_tensor_slices(x)" }, { "code": null, "e": 2643, "s": 2508, "text": "We can also initialise a Dataset from a generator, this is useful when we have an array of different elements length (e.g a sequence):" }, { "code": null, "e": 3170, "s": 2643, "text": "# from generatorsequence = np.array([[[1]],[[2],[3]],[[3],[4],[5]]])def generator(): for el in sequence: yield eldataset = tf.data.Dataset().batch(1).from_generator(generator, output_types= tf.int64, output_shapes=(tf.TensorShape([None, 1])))iter = dataset.make_initializable_iterator()el = iter.get_next()with tf.Session() as sess: sess.run(iter.initializer) print(sess.run(el)) print(sess.run(el)) print(sess.run(el))" }, { "code": null, "e": 3178, "s": 3170, "text": "Ouputs:" }, { "code": null, "e": 3206, "s": 3178, "text": "[[1]][[2] [3]][[3] [4] [5]]" }, { "code": null, "e": 3332, "s": 3206, "text": "In this case, you also need to specify the types and the shapes of your data that will be used to create the correct tensors." }, { "code": null, "e": 3445, "s": 3332, "text": "You can directly read a csv file into a dataset. For example, I have a csv file with tweets and their sentiment." }, { "code": null, "e": 3663, "s": 3445, "text": "I can now easily create a Dataset from it by calling tf.contrib.data.make_csv_dataset . Be aware that the iterator will create a dictionary with key as the column names and values as Tensor with the correct row value." }, { "code": null, "e": 4007, "s": 3663, "text": "# load a csvCSV_PATH = './tweets.csv'dataset = tf.contrib.data.make_csv_dataset(CSV_PATH, batch_size=32)iter = dataset.make_one_shot_iterator()next = iter.get_next()print(next) # next is a dict with key=columns names and value=column datainputs, labels = next['text'], next['sentiment']with tf.Session() as sess: sess.run([inputs, labels])" }, { "code": null, "e": 4021, "s": 4007, "text": "Where next is" }, { "code": null, "e": 4162, "s": 4021, "text": "{'sentiment': <tf.Tensor 'IteratorGetNext_15:0' shape=(?,) dtype=int32>, 'text': <tf.Tensor 'IteratorGetNext_15:1' shape=(?,) dtype=string>}" }, { "code": null, "e": 4398, "s": 4162, "text": "We have seen how to create a dataset, but how to get our data back? We have to use an Iterator, that will give us the ability to iterate through the dataset and retrieve the real values of the data. There exist four types of iterators." }, { "code": null, "e": 4480, "s": 4398, "text": "One shot. It can iterate once through a dataset, you cannot feed any value to it." }, { "code": null, "e": 4652, "s": 4480, "text": "Initializable: You can dynamically change calling its initializer operation and passing the new data with feed_dict . It’s basically a bucket that you can fill with stuff." }, { "code": null, "e": 4902, "s": 4652, "text": "Reinitializable: It can be initialised from different Dataset. Very useful when you have a training dataset that needs some additional transformation, eg. shuffle, and a testing dataset. It’s like using a tower crane to select a different container." }, { "code": null, "e": 5114, "s": 4902, "text": "Feedable: It can be used to select with iterator to use. Following the previous example, it’s like a tower crane that selects which tower crane to use to select which container to take. In my opinion is useless." }, { "code": null, "e": 5168, "s": 5114, "text": "This is the easiest iterator. Using the first example" }, { "code": null, "e": 5340, "s": 5168, "text": "x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)# create the iteratoriter = dataset.make_one_shot_iterator()" }, { "code": null, "e": 5419, "s": 5340, "text": "Then you need to call get_next() to get the tensor that will contain your data" }, { "code": null, "e": 5503, "s": 5419, "text": "...# create the iteratoriter = dataset.make_one_shot_iterator()el = iter.get_next()" }, { "code": null, "e": 5543, "s": 5503, "text": "We can run el in order to see its value" }, { "code": null, "e": 5629, "s": 5543, "text": "with tf.Session() as sess: print(sess.run(el)) # output: [ 0.42116176 0.40666069]" }, { "code": null, "e": 5927, "s": 5629, "text": "In case we want to build a dynamic dataset in which we can change the data source at runtime, we can create a dataset with a placeholder. Then we can initialize the placeholder using the common feed-dict mechanism. This is done with an initializable iterator. Using example three from last section" }, { "code": null, "e": 6334, "s": 5927, "text": "# using a placeholderx = tf.placeholder(tf.float32, shape=[None,2])dataset = tf.data.Dataset.from_tensor_slices(x)data = np.random.sample((100,2))iter = dataset.make_initializable_iterator() # create the iteratorel = iter.get_next()with tf.Session() as sess: # feed the placeholder with data sess.run(iter.initializer, feed_dict={ x: data }) print(sess.run(el)) # output [ 0.52374458 0.71968478]" }, { "code": null, "e": 6507, "s": 6334, "text": "This time we call make_initializable_iterator . Then, inside thesess scope, we run the initializer operation in order to pass our data, in this case a random numpy array. ." }, { "code": null, "e": 6584, "s": 6507, "text": "Imagine that now we have a train set and a test set, a real common scenario:" }, { "code": null, "e": 6700, "s": 6584, "text": "train_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.array([[1,2]]), np.array([[0]]))" }, { "code": null, "e": 6847, "s": 6700, "text": "Then we would like to train the model and then evaluate it on the test dataset, this can be done by initialising the iterator again after training" }, { "code": null, "e": 7597, "s": 6847, "text": "# initializable iterator to switch between datasetEPOCHS = 10x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])dataset = tf.data.Dataset.from_tensor_slices((x, y))train_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.array([[1,2]]), np.array([[0]]))iter = dataset.make_initializable_iterator()features, labels = iter.get_next()with tf.Session() as sess:# initialise iterator with train data sess.run(iter.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) for _ in range(EPOCHS): sess.run([features, labels])# switch to test data sess.run(iter.initializer, feed_dict={ x: test_data[0], y: test_data[1]}) print(sess.run([features, labels]))" }, { "code": null, "e": 7802, "s": 7597, "text": "The concept is similar to before, we want to dynamic switch between data. But instead of feed new data to the same dataset, we switch dataset. As before, we want to have a train dataset and a test dataset" }, { "code": null, "e": 7964, "s": 7802, "text": "# making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1)))" }, { "code": null, "e": 7991, "s": 7964, "text": "We can create two Datasets" }, { "code": null, "e": 8170, "s": 7991, "text": "# create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices(train_data)test_dataset = tf.data.Dataset.from_tensor_slices(test_data)" }, { "code": null, "e": 8223, "s": 8170, "text": "Now, this is the trick, we create a generic Iterator" }, { "code": null, "e": 8410, "s": 8223, "text": "# create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)" }, { "code": null, "e": 8450, "s": 8410, "text": "and then two initialization operations:" }, { "code": null, "e": 8591, "s": 8450, "text": "# create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset)" }, { "code": null, "e": 8625, "s": 8591, "text": "We get the next element as before" }, { "code": null, "e": 8660, "s": 8625, "text": "features, labels = iter.get_next()" }, { "code": null, "e": 8766, "s": 8660, "text": "Now, we can directly run the two initialisation operation using our session. Putting all together we get:" }, { "code": null, "e": 9761, "s": 8766, "text": "# Reinitializable iterator to switch between DatasetsEPOCHS = 10# making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1)))# create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices(train_data)test_dataset = tf.data.Dataset.from_tensor_slices(test_data)# create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)features, labels = iter.get_next()# create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset)with tf.Session() as sess: sess.run(train_init_op) # switch to train dataset for _ in range(EPOCHS): sess.run([features, labels]) sess.run(test_init_op) # switch to val dataset print(sess.run([features, labels]))" }, { "code": null, "e": 9914, "s": 9761, "text": "This is very similar to the reinitializable iterator, but instead of switch between datasets, it switch between iterators. After we created two datasets" }, { "code": null, "e": 10028, "s": 9914, "text": "train_dataset = tf.data.Dataset.from_tensor_slices((x,y))test_dataset = tf.data.Dataset.from_tensor_slices((x,y))" }, { "code": null, "e": 10189, "s": 10028, "text": "One for training and one for testing. Then, we can create our iterator, in this case we use the initializable iterator, but you can also use a one shot iterator" }, { "code": null, "e": 10308, "s": 10189, "text": "train_iterator = train_dataset.make_initializable_iterator()test_iterator = test_dataset.make_initializable_iterator()" }, { "code": null, "e": 10407, "s": 10308, "text": "Now, we need to defined and handle , that will be out placeholder that can be dynamically changed." }, { "code": null, "e": 10452, "s": 10407, "text": "handle = tf.placeholder(tf.string, shape=[])" }, { "code": null, "e": 10537, "s": 10452, "text": "Then, similar to before, we define a generic iterator using the shape of the dataset" }, { "code": null, "e": 10649, "s": 10537, "text": "iter = tf.data.Iterator.from_string_handle( handle, train_dataset.output_types, train_dataset.output_shapes)" }, { "code": null, "e": 10680, "s": 10649, "text": "Then, we get the next elements" }, { "code": null, "e": 10712, "s": 10680, "text": "next_elements = iter.get_next()" }, { "code": null, "e": 10901, "s": 10712, "text": "In order to switch between the iterators we just have to call the next_elemenents operation passing the correct handle in the feed_dict. For example, to get one element from the train set:" }, { "code": null, "e": 10961, "s": 10901, "text": "sess.run(next_elements, feed_dict = {handle: train_handle})" }, { "code": null, "e": 11069, "s": 10961, "text": "If you are using initializable iterators, as we are doing, just remember to initialize them before starting" }, { "code": null, "e": 11241, "s": 11069, "text": "sess.run(train_iterator.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) sess.run(test_iterator.initializer, feed_dict={ x: test_data[0], y: test_data[1]})" }, { "code": null, "e": 11270, "s": 11241, "text": "Putting all together we get:" }, { "code": null, "e": 12772, "s": 11270, "text": "# feedable iterator to switch between iteratorsEPOCHS = 10# making fake data using numpytrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((10,2)), np.random.sample((10,1)))# create placeholderx, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])# create two datasets, one for training and one for testtrain_dataset = tf.data.Dataset.from_tensor_slices((x,y))test_dataset = tf.data.Dataset.from_tensor_slices((x,y))# create the iterators from the datasettrain_iterator = train_dataset.make_initializable_iterator()test_iterator = test_dataset.make_initializable_iterator()# same as in the doc https://www.tensorflow.org/programmers_guide/datasets#creating_an_iteratorhandle = tf.placeholder(tf.string, shape=[])iter = tf.data.Iterator.from_string_handle( handle, train_dataset.output_types, train_dataset.output_shapes)next_elements = iter.get_next()with tf.Session() as sess: train_handle = sess.run(train_iterator.string_handle()) test_handle = sess.run(test_iterator.string_handle()) # initialise iterators. sess.run(train_iterator.initializer, feed_dict={ x: train_data[0], y: train_data[1]}) sess.run(test_iterator.initializer, feed_dict={ x: test_data[0], y: test_data[1]}) for _ in range(EPOCHS): x,y = sess.run(next_elements, feed_dict = {handle: train_handle}) print(x, y) x,y = sess.run(next_elements, feed_dict = {handle: test_handle}) print(x,y)" }, { "code": null, "e": 12876, "s": 12772, "text": "In the previous example we have used the session to print the value of the next element in the Dataset." }, { "code": null, "e": 12966, "s": 12876, "text": "...next_el = iter.get_next()...print(sess.run(next_el)) # will output the current element" }, { "code": null, "e": 13062, "s": 12966, "text": "In order to pass the data to a model we have to just pass the tensors generated from get_next()" }, { "code": null, "e": 13309, "s": 13062, "text": "In the following snippet we have a Dataset that contains two numpy arrays, using the same example from the first section. Notice that we need to wrap the .random.sample in another numpy array to add a dimension that we is needed to batch the data" }, { "code": null, "e": 13541, "s": 13309, "text": "# using two numpy arraysfeatures, labels = (np.array([np.random.sample((100,2))]), np.array([np.random.sample((100,1))]))dataset = tf.data.Dataset.from_tensor_slices((features,labels)).repeat().batch(BATCH_SIZE)" }, { "code": null, "e": 13579, "s": 13541, "text": "Then as always, we create an iterator" }, { "code": null, "e": 13641, "s": 13579, "text": "iter = dataset.make_one_shot_iterator()x, y = iter.get_next()" }, { "code": null, "e": 13682, "s": 13641, "text": "We make a model, a simple neural network" }, { "code": null, "e": 14002, "s": 13682, "text": "# make a simple modelnet = tf.layers.dense(x, 8) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8)prediction = tf.layers.dense(net, 1)loss = tf.losses.mean_squared_error(prediction, y) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)" }, { "code": null, "e": 14139, "s": 14002, "text": "We directly use the Tensors from iter.get_next() as input to the first layer and as labels for the loss function. Wrapping all together:" }, { "code": null, "e": 15048, "s": 14139, "text": "EPOCHS = 10BATCH_SIZE = 16# using two numpy arraysfeatures, labels = (np.array([np.random.sample((100,2))]), np.array([np.random.sample((100,1))]))dataset = tf.data.Dataset.from_tensor_slices((features,labels)).repeat().batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()x, y = iter.get_next()# make a simple modelnet = tf.layers.dense(x, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, y) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(EPOCHS): _, loss_value = sess.run([train_op, loss]) print(\"Iter: {}, Loss: {:.4f}\".format(i, loss_value))" }, { "code": null, "e": 15056, "s": 15048, "text": "Output:" }, { "code": null, "e": 15276, "s": 15056, "text": "Iter: 0, Loss: 0.1328 Iter: 1, Loss: 0.1312 Iter: 2, Loss: 0.1296 Iter: 3, Loss: 0.1281 Iter: 4, Loss: 0.1267 Iter: 5, Loss: 0.1254 Iter: 6, Loss: 0.1242 Iter: 7, Loss: 0.1231 Iter: 8, Loss: 0.1220 Iter: 9, Loss: 0.1210" }, { "code": null, "e": 15521, "s": 15276, "text": "Usually batching data is a pain in the ass, with the Dataset API we can use the method batch(BATCH_SIZE) that automatically batches the dataset with the provided size. The default value is one. In the following example, we use a batch size of 4" }, { "code": null, "e": 15784, "s": 15521, "text": "# BATCHINGBATCH_SIZE = 4x = np.random.sample((100,2))# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x).batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess: print(sess.run(el)) " }, { "code": null, "e": 15792, "s": 15784, "text": "Output:" }, { "code": null, "e": 15898, "s": 15792, "text": "[[ 0.65686128 0.99373963] [ 0.69690451 0.32446826] [ 0.57148422 0.68688242] [ 0.20335116 0.82473219]]" }, { "code": null, "e": 16134, "s": 15898, "text": "Using .repeat() we can specify the number of times we want the dataset to be iterated. If no parameter is passed it will loop forever, usually is good to just loop forever and directly control the number of epochs with a standard loop." }, { "code": null, "e": 16241, "s": 16134, "text": "We can shuffle the Dataset by using the method shuffle() that shuffles the dataset by default every epoch." }, { "code": null, "e": 16311, "s": 16241, "text": "Remember: shuffle the dataset is very important to avoid overfitting." }, { "code": null, "e": 16443, "s": 16311, "text": "We can also set the parameter buffer_size , a fixed size buffer from which the next element will be uniformly chosen from. Example:" }, { "code": null, "e": 16766, "s": 16443, "text": "# BATCHINGBATCH_SIZE = 4x = np.array([[1],[2],[3],[4]])# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)dataset = dataset.shuffle(buffer_size=100)dataset = dataset.batch(BATCH_SIZE)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess: print(sess.run(el))" }, { "code": null, "e": 16784, "s": 16766, "text": "First run output:" }, { "code": null, "e": 16802, "s": 16784, "text": "[[4] [2] [3] [1]]" }, { "code": null, "e": 16821, "s": 16802, "text": "Second run output:" }, { "code": null, "e": 16839, "s": 16821, "text": "[[3] [1] [2] [4]]" }, { "code": null, "e": 16911, "s": 16839, "text": "Yep. It was shuffled. If you want, you can also set the seed parameter." }, { "code": null, "e": 17051, "s": 16911, "text": "You can apply a custom function to each member of a dataset using the map method. In the following example we multiply each element by two:" }, { "code": null, "e": 17380, "s": 17051, "text": "# MAPx = np.array([[1],[2],[3],[4]])# make a dataset from a numpy arraydataset = tf.data.Dataset.from_tensor_slices(x)dataset = dataset.map(lambda x: x*2)iter = dataset.make_one_shot_iterator()el = iter.get_next()with tf.Session() as sess:# this will run forever for _ in range(len(x)): print(sess.run(el))" }, { "code": null, "e": 17388, "s": 17380, "text": "Output:" }, { "code": null, "e": 17401, "s": 17388, "text": "[2][4][6][8]" }, { "code": null, "e": 17537, "s": 17401, "text": "In the example below we train a simple model using batching and we switch between train and test dataset using a Initializable iterator" }, { "code": null, "e": 19220, "s": 17537, "text": "# Wrapping all together -> Switch between train and test set using Initializable iteratorEPOCHS = 10# create a placeholder to dynamically switch between batch sizesbatch_size = tf.placeholder(tf.int64)x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(batch_size).repeat()# using two numpy arraystrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((20,2)), np.random.sample((20,1)))iter = dataset.make_initializable_iterator()features, labels = iter.get_next()# make a simple modelnet = tf.layers.dense(features, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, labels) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # initialise iterator with train data sess.run(iter.initializer, feed_dict={ x: train_data[0], y: train_data[1], batch_size: BATCH_SIZE}) print('Training...') for i in range(EPOCHS): tot_loss = 0 for _ in range(n_batches): _, loss_value = sess.run([train_op, loss]) tot_loss += loss_value print(\"Iter: {}, Loss: {:.4f}\".format(i, tot_loss / n_batches)) # initialise iterator with test data sess.run(iter.initializer, feed_dict={ x: test_data[0], y: test_data[1], batch_size: test_data[0].shape[0]}) print('Test Loss: {:4f}'.format(sess.run(loss)))" }, { "code": null, "e": 19321, "s": 19220, "text": "Notice that we use a placeholder for the batch size in order to dynamically switch it after training" }, { "code": null, "e": 19328, "s": 19321, "text": "Output" }, { "code": null, "e": 19569, "s": 19328, "text": "Training...Iter: 0, Loss: 0.2977Iter: 1, Loss: 0.2152Iter: 2, Loss: 0.1787Iter: 3, Loss: 0.1597Iter: 4, Loss: 0.1277Iter: 5, Loss: 0.1334Iter: 6, Loss: 0.1000Iter: 7, Loss: 0.1154Iter: 8, Loss: 0.0989Iter: 9, Loss: 0.0948Test Loss: 0.082150" }, { "code": null, "e": 19707, "s": 19569, "text": "In the example below we train a simple model using batching and we switch between train and test dataset using a Reinitializable Iterator" }, { "code": null, "e": 21784, "s": 19707, "text": "# Wrapping all together -> Switch between train and test set using Reinitializable iteratorEPOCHS = 10# create a placeholder to dynamically switch between batch sizesbatch_size = tf.placeholder(tf.int64)x, y = tf.placeholder(tf.float32, shape=[None,2]), tf.placeholder(tf.float32, shape=[None,1])train_dataset = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size).repeat()test_dataset = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size) # always batch even if you want to one shot it# using two numpy arraystrain_data = (np.random.sample((100,2)), np.random.sample((100,1)))test_data = (np.random.sample((20,2)), np.random.sample((20,1)))# create a iterator of the correct shape and typeiter = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)features, labels = iter.get_next()# create the initialisation operationstrain_init_op = iter.make_initializer(train_dataset)test_init_op = iter.make_initializer(test_dataset)# make a simple modelnet = tf.layers.dense(features, 8, activation=tf.tanh) # pass the first value from iter.get_next() as inputnet = tf.layers.dense(net, 8, activation=tf.tanh)prediction = tf.layers.dense(net, 1, activation=tf.tanh)loss = tf.losses.mean_squared_error(prediction, labels) # pass the second value from iter.get_net() as labeltrain_op = tf.train.AdamOptimizer().minimize(loss)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # initialise iterator with train data sess.run(train_init_op, feed_dict = {x : train_data[0], y: train_data[1], batch_size: 16}) print('Training...') for i in range(EPOCHS): tot_loss = 0 for _ in range(n_batches): _, loss_value = sess.run([train_op, loss]) tot_loss += loss_value print(\"Iter: {}, Loss: {:.4f}\".format(i, tot_loss / n_batches)) # initialise iterator with test data sess.run(test_init_op, feed_dict = {x : test_data[0], y: test_data[1], batch_size:len(test_data[0])}) print('Test Loss: {:4f}'.format(sess.run(loss)))" }, { "code": null, "e": 21867, "s": 21784, "text": "TensorFlow dataset tutorial: https://www.tensorflow.org/programmers_guide/datasets" }, { "code": null, "e": 21881, "s": 21867, "text": "Dataset docs:" }, { "code": null, "e": 21940, "s": 21881, "text": "https://www.tensorflow.org/api_docs/python/tf/data/Dataset" }, { "code": null, "e": 22142, "s": 21940, "text": "The Dataset API gives us a fast and robust way to create optimized input pipeline to train, evaluate and test our models. In this article, we have seen most of the common operation we can do with them." }, { "code": null, "e": 22223, "s": 22142, "text": "You can use the jupyter-notebook that I’ve made for this article as a reference." } ]
Java - The SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in an ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in the following table − Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set. Comparator comparator( ) Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned. Object first( ) Returns the first element in the invoking sorted set. SortedSet headSet(Object end) Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set. Object last( ) Returns the last element in the invoking sorted set. SortedSet subSet(Object start, Object end) Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object. SortedSet tailSet(Object start) Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object. SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class − import java.util.*; public class SortedSetTest { public static void main(String[] args) { // Create the sorted set SortedSet set = new TreeSet(); // Add elements to the set set.add("b"); set.add("c"); set.add("a"); // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } } } This will produce the following result − a b c 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2604, "s": 2377, "text": "The SortedSet interface extends Set and declares the behavior of a set sorted in an ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in the following table −" }, { "code": null, "e": 2790, "s": 2604, "text": "Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set." }, { "code": null, "e": 2902, "s": 2790, "text": "A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set." }, { "code": null, "e": 2927, "s": 2902, "text": "Comparator comparator( )" }, { "code": null, "e": 3037, "s": 2927, "text": "Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned." }, { "code": null, "e": 3053, "s": 3037, "text": "Object first( )" }, { "code": null, "e": 3107, "s": 3053, "text": "Returns the first element in the invoking sorted set." }, { "code": null, "e": 3137, "s": 3107, "text": "SortedSet headSet(Object end)" }, { "code": null, "e": 3328, "s": 3137, "text": "Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set." }, { "code": null, "e": 3343, "s": 3328, "text": "Object last( )" }, { "code": null, "e": 3396, "s": 3343, "text": "Returns the last element in the invoking sorted set." }, { "code": null, "e": 3439, "s": 3396, "text": "SortedSet subSet(Object start, Object end)" }, { "code": null, "e": 3593, "s": 3439, "text": "Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object." }, { "code": null, "e": 3625, "s": 3593, "text": "SortedSet tailSet(Object start)" }, { "code": null, "e": 3816, "s": 3625, "text": "Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object." }, { "code": null, "e": 3928, "s": 3816, "text": "SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class −" }, { "code": null, "e": 4425, "s": 3928, "text": "import java.util.*;\npublic class SortedSetTest {\n\n public static void main(String[] args) {\n // Create the sorted set\n SortedSet set = new TreeSet(); \n\n // Add elements to the set\n set.add(\"b\");\n set.add(\"c\");\n set.add(\"a\");\n\n // Iterating over the elements in the set\n Iterator it = set.iterator();\n\n while (it.hasNext()) {\n // Get element\n Object element = it.next();\n System.out.println(element.toString());\n }\n }\n}" }, { "code": null, "e": 4466, "s": 4425, "text": "This will produce the following result −" }, { "code": null, "e": 4473, "s": 4466, "text": "a\nb\nc\n" }, { "code": null, "e": 4506, "s": 4473, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4522, "s": 4506, "text": " Malhar Lathkar" }, { "code": null, "e": 4555, "s": 4522, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4571, "s": 4555, "text": " Malhar Lathkar" }, { "code": null, "e": 4606, "s": 4571, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4620, "s": 4606, "text": " Anadi Sharma" }, { "code": null, "e": 4654, "s": 4620, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4668, "s": 4654, "text": " Tushar Kale" }, { "code": null, "e": 4705, "s": 4668, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4720, "s": 4705, "text": " Monica Mittal" }, { "code": null, "e": 4753, "s": 4720, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4772, "s": 4753, "text": " Arnab Chakraborty" }, { "code": null, "e": 4779, "s": 4772, "text": " Print" }, { "code": null, "e": 4790, "s": 4779, "text": " Add Notes" } ]
Gotcha! global variable with recursion | by Han Qi | Towards Data Science
I was working on this leetcode question https://leetcode.com/contest/weekly-contest-212/problems/path-with-minimum-effort/ using backtracking and spent some time debugging strange output. This article discusses some pitfalls when using recursion with global variables, how to handle them, and how to change the code from global to local. Disclaimer: Backtracking only passing 15/75 test cases and Time Limit Exceeded for the rest, the purpose of this article is to highlight possible issues with global variables rather than give the best solutions. For more beautiful solutions using Binary Search, Dijkstra and Kruskal, watch Alex’s walkthrough (beginning 7:26) at https://www.youtube.com/watch?v=AM__3Zx1XNw&t=2325s&ab_channel=AlexWice The problem is to find the path with minimum effort after walking from top left to bottom right with each step allowing 4 directions of up, down, left, right. effort is defined as the maximum absolute difference in values between any 2 consecutive squares. import numpy as np import math min_effort = math.inf def valid(r,c,visited): return 0 <= r < visited.shape[0] and 0 <= c < visited.shape[1] and visited[r,c] == 0 def find_path(heights_arr,visited,r,c,effort,max_row, max_col): global min_effort if r == max_row and c == max_col: print(f'-------------------Found end: effort is {effort}') return effort for row,col in ((r+1,c),(r,c+1),(r-1,c),(r,c-1)): if valid(row,col,visited): print(f'going from {r},{c} to {row},{col}') print(f'effort before recurse: {effort}') visited[row,col] = 1 updated_effort = max(effort, abs(heights_arr[row,col]-heights_arr[r,c])) # possibly update current max effort along path #recursion_res = find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col) #print(f'min_effort:{min_effort} recursion_res:{recursion_res}') #min_effort = min(min_effort,recursion_res) min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col)) # problem #min_effort = min(find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col),min_effort) visited[row,col] = 0 print(f'global min_effort after recurse: {min_effort}') return math.inf #return min_effort def minimumEffortPath(heights): heights_arr = np.array(heights) rows, cols = heights_arr.shape max_row, max_col = rows-1, cols-1 r,c = 0,0 visited = np.zeros((rows, cols)) visited[r,c]=1 effort = 0 find_path(heights_arr,visited,r,c,effort,max_row, max_col) heights = [[1,2,3],[3,8,4],[5,3,5]] minimumEffortPath(heights) print(min_effort) going from 0,0 to 1,0 effort before recurse: 0 going from 1,0 to 2,0 effort before recurse: 2 going from 2,0 to 2,1 effort before recurse: 2 going from 2,1 to 2,2 effort before recurse: 2 -------------------Found end: effort is 2 global min_effort after recurse: 2 going from 2,1 to 1,1 effort before recurse: 2 going from 1,1 to 1,2 effort before recurse: 5 going from 1,2 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 2 going from 1,2 to 0,2 effort before recurse: 5 going from 0,2 to 0,1 effort before recurse: 5 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 0,1 effort before recurse: 5 going from 0,1 to 0,2 effort before recurse: 6 going from 0,2 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: inf global min_effort after recurse: inf going from 1,0 to 1,1 effort before recurse: 2 going from 1,1 to 2,1 effort before recurse: 5 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 5 going from 2,1 to 2,0 effort before recurse: 5 global min_effort after recurse: 5 global min_effort after recurse: inf going from 1,1 to 1,2 effort before recurse: 5 going from 1,2 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 5 going from 1,2 to 0,2 effort before recurse: 5 going from 0,2 to 0,1 effort before recurse: 5 global min_effort after recurse: 5 global min_effort after recurse: 5 global min_effort after recurse: inf going from 1,1 to 0,1 effort before recurse: 5 going from 0,1 to 0,2 effort before recurse: 6 going from 0,2 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 6 global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf going from 0,0 to 0,1 effort before recurse: 0 going from 0,1 to 1,1 effort before recurse: 1 going from 1,1 to 2,1 effort before recurse: 6 going from 2,1 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 6 going from 2,1 to 2,0 effort before recurse: 6 going from 2,0 to 1,0 effort before recurse: 6 global min_effort after recurse: 6 global min_effort after recurse: 6 global min_effort after recurse: inf going from 1,1 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 6 going from 1,2 to 0,2 effort before recurse: 6 global min_effort after recurse: 6 global min_effort after recurse: inf going from 1,1 to 1,0 effort before recurse: 6 going from 1,0 to 2,0 effort before recurse: 6 going from 2,0 to 2,1 effort before recurse: 6 going from 2,1 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 6 global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf going from 0,1 to 0,2 effort before recurse: 1 going from 0,2 to 1,2 effort before recurse: 1 going from 1,2 to 2,2 effort before recurse: 1 -------------------Found end: effort is 1 global min_effort after recurse: 1 going from 1,2 to 1,1 effort before recurse: 1 going from 1,1 to 2,1 effort before recurse: 4 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 1 going from 2,1 to 2,0 effort before recurse: 5 going from 2,0 to 1,0 effort before recurse: 5 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 going from 1,1 to 1,0 effort before recurse: 4 going from 1,0 to 2,0 effort before recurse: 5 going from 2,0 to 2,1 effort before recurse: 5 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: inf global min_effort after recurse: inf global min_effort after recurse: inf inf import numpy as np import math def valid(r,c,visited): return 0 <= r < visited.shape[0] and 0 <= c < visited.shape[1] and visited[r,c] == 0 def find_path(heights_arr,visited,r,c,effort,max_row, max_col,min_effort): if r == max_row and c == max_col: print(f'-------------------Found end: effort is {effort}') return effort for row,col in ((r+1,c),(r,c+1),(r-1,c),(r,c-1)): if valid(row,col,visited): print(f'going from {r},{c} to {row},{col}') print(f'effort before recurse: {effort}') updated_effort = max(effort, abs(heights_arr[row,col]-heights_arr[r,c])) # possibly update current max effort along path visited[row,col] = 1 #recursion_res = find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort) #print(f'min_effort:{min_effort} recursion_res:{recursion_res}') #min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort)) min_effort = min(find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort),min_effort) visited[row,col] = 0 print(f'global min_effort after recurse: {min_effort}') return min_effort #return math.inf def minimumEffortPath(heights): min_effort = math.inf heights_arr = np.array(heights) rows, cols = heights_arr.shape max_row, max_col = rows-1, cols-1 r,c = 0,0 visited = np.zeros((rows, cols)) visited[r,c]=1 effort = 0 return find_path(heights_arr,visited,r,c,effort,max_row, max_col,min_effort) #heights = [[1,2,2],[3,8,2],[5,3,5]] heights = [[1,2,3],[3,8,4],[5,3,5]] #heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] #heights = [[1,10,6,7,9,10,4,9]] #heights = [[4,3,4,10,5,5,9,2],[10,8,2,10,9,7,5,6],[5,8,10,10,10,7,4,2],[5,1,3,1,1,3,1,9],[6,4,10,6,10,9,4,6]] print(minimumEffortPath(heights)) #print(min_effort) going from 0,0 to 1,0 effort before recurse: 0 going from 1,0 to 2,0 effort before recurse: 2 going from 2,0 to 2,1 effort before recurse: 2 going from 2,1 to 2,2 effort before recurse: 2 -------------------Found end: effort is 2 global min_effort after recurse: 2 going from 2,1 to 1,1 effort before recurse: 2 going from 1,1 to 1,2 effort before recurse: 5 going from 1,2 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 2 going from 1,2 to 0,2 effort before recurse: 5 going from 0,2 to 0,1 effort before recurse: 5 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 0,1 effort before recurse: 5 going from 0,1 to 0,2 effort before recurse: 6 going from 0,2 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,0 to 1,1 effort before recurse: 2 going from 1,1 to 2,1 effort before recurse: 5 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 2 going from 2,1 to 2,0 effort before recurse: 5 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 1,2 effort before recurse: 5 going from 1,2 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 2 going from 1,2 to 0,2 effort before recurse: 5 going from 0,2 to 0,1 effort before recurse: 5 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 0,1 effort before recurse: 5 going from 0,1 to 0,2 effort before recurse: 6 going from 0,2 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 0,0 to 0,1 effort before recurse: 0 going from 0,1 to 1,1 effort before recurse: 1 going from 1,1 to 2,1 effort before recurse: 6 going from 2,1 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 going from 2,1 to 2,0 effort before recurse: 6 going from 2,0 to 1,0 effort before recurse: 6 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 1,2 effort before recurse: 6 going from 1,2 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 going from 1,2 to 0,2 effort before recurse: 6 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 1,1 to 1,0 effort before recurse: 6 going from 1,0 to 2,0 effort before recurse: 6 going from 2,0 to 2,1 effort before recurse: 6 going from 2,1 to 2,2 effort before recurse: 6 -------------------Found end: effort is 6 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 global min_effort after recurse: 2 going from 0,1 to 0,2 effort before recurse: 1 going from 0,2 to 1,2 effort before recurse: 1 going from 1,2 to 2,2 effort before recurse: 1 -------------------Found end: effort is 1 global min_effort after recurse: 1 going from 1,2 to 1,1 effort before recurse: 1 going from 1,1 to 2,1 effort before recurse: 4 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 1 going from 2,1 to 2,0 effort before recurse: 5 going from 2,0 to 1,0 effort before recurse: 5 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 going from 1,1 to 1,0 effort before recurse: 4 going from 1,0 to 2,0 effort before recurse: 5 going from 2,0 to 2,1 effort before recurse: 5 going from 2,1 to 2,2 effort before recurse: 5 -------------------Found end: effort is 5 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 global min_effort after recurse: 1 1 Notebook containing implementation with global vs no global variable: https://gist.github.com/gitgithan/a818d336c2309852a21d99efd619238d My backtracking solution was to use a visited 2D array to track visits.Starting from the top-left cell, we try to move in the order of down, right, up, left (this order reaches the destination faster than some other orders, so the global min can be updated earlier, and used to bound/speed up the exploration of future paths) if within rectangle bounds and not visited before. Before moving (recursing), the visit is marked so future attempts to visit will return False for if valid(). Along the way, the effort (intialized to 0) of the path is updated using abs difference between the cell we are going to visit and current cell. If we reach base case (bottom-right cell), return the effort. Once a single direction of recursion is complete, we update the global minimum min_effort (initialized to math.inf) and unmark the cell in that direction. Once all 4 directions from the current cell is done, we return math.inf back up the call stack so it does not wrongly influence the min() of the caller. This output of five 2, followed by two inf was mindboggling. It looked like the global variable min_effort which was updated from inf to 2 after the first solution (1, down to 3, down to 5, right to 3, right to 5) went back to inf! The final answer(path of 1, 2, 3, 4, 5) was also wrongly inf instead of 1. Those five 2 correspond to the algorithm backtracking from destination 5 to 4,3,2,8,3,5 because all these have all 4 directions either visited or out of bounds, so the next path to try is to go right from 1,0 to 1,1 (3 to 8). The problem is with the line min_effort = min(min_effort,find_path(...)) Because python evaluates arguments from left to right, the global variable min_effort was already evaluated before entering the recursion, so whatever happens in the recursion (including updates to global variable) has no effect on min_effort. At the scope of the 3 in bottom middle of the grid, the algorithm has not yet found a successful path (the 1st path being 1,3,5,3,5), so min_effort was still math.inf at that moment, and min(math.inf,math.inf) became inf. Swap arguments Swap arguments A fix is to simply swap the order of arguments to min_effort = min(find_path(...), min_effort). This gives the recursion a chance to update the global variable first before comparison. 2. Save into variable first If you still wanted to maintain the old order as a matter of preference, the recursion can be calculated and saved into a variable first. recursion_res = find_path(...)min_effort = min(min_effort, recursion_res) 3. Remove global variables completely This was prompted by Leetcode giving wrong test results running all test cases, but running the failing case individually as custom input gives the correct result. If you insist on using globals on leetcode, copy the result, clear the global, and return the copied result so the cleared global is ready for the next test case. Two changes: 1. Add the previously global variable to recursive function signature find_path(...,min_effort) 2. Return min_effort rather than math.inf This will ensure the minimum effort path is always propagated through the recursive calls. If you ask why not return min_effort while using global variable, that is workable too, but unnecessary, since if you avoid the gotcha mentioned above, min_effort would have been updated to a non-inf value before the min(min_effort,find_path(...))comparison, so even if the 2nd argument returns math.inf, the 1st argument will always be updated to the correct value once any path first reaches the destination. Also, math.inf felt more representative of a “no solution/bad value”. However, the argument in support of return min_effort rather than return math.inf is that it more accurately represents the most updated program state. Also, we can totally avoid the gotcha handling (the 1st two fixes described) and use min(min_effort,find_path(...)) directly because with return min_effort the 2nd argument will always be updated, so a “pre-recursion evaluated” min_effort that could contain its initialized math.inf in the 1st argument causes no harm. (exactly opposite situation of the previous paragraph). Since we are looking for the global minimum, any path can be influenced by the results of any other path. This offers a chance for the current best result to short-circuit future paths once they are found to have longer effort than the current min_effort . This can be achieved by wrapping the backtracking section (visit,recurse,unvisit) with an extra check if updated_effort < min_effort: to largely reduce exploration steps, using “less than” because there is no point trying something that won’t reduce the current best. if updated_effort < min_effort: visited[row,col] = 1 min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col)) visited[row,col] = 0 Global pros: Lax return values allowed ( math.inf or min_effort )Convenient coding (less parameter passing and simpler recursive functions) Lax return values allowed ( math.inf or min_effort ) Convenient coding (less parameter passing and simpler recursive functions) Global cons: Don’t gel with online coding platforms (risky for job interview automated coding assessments)Constantly have to be aware of side effects and variables not within current stackSensitive to function argument ordering (the root of all these troubles) Don’t gel with online coding platforms (risky for job interview automated coding assessments) Constantly have to be aware of side effects and variables not within current stack Sensitive to function argument ordering (the root of all these troubles) Local pros: Easier debugging/tracing focusing on local problem spaceLess side effects Easier debugging/tracing focusing on local problem space Less side effects Local cons: More verbose function signature (more items to track means longer signature)Lose ability to return math.inf , have to return min_effort to propagate updated results back to rest of program More verbose function signature (more items to track means longer signature) Lose ability to return math.inf , have to return min_effort to propagate updated results back to rest of program When using globals, if I had returned min_effort or coded properly using fix 2 above initially, I would not have seen this gotcha at all. It’s a blessing in disguise that returning the most intuitively correct value and being lazy with (possibly) extraneous variable assignments allowed me to strengthen my understanding of python evaluation order and debugging skills.
[ { "code": null, "e": 510, "s": 172, "text": "I was working on this leetcode question https://leetcode.com/contest/weekly-contest-212/problems/path-with-minimum-effort/ using backtracking and spent some time debugging strange output. This article discusses some pitfalls when using recursion with global variables, how to handle them, and how to change the code from global to local." }, { "code": null, "e": 911, "s": 510, "text": "Disclaimer: Backtracking only passing 15/75 test cases and Time Limit Exceeded for the rest, the purpose of this article is to highlight possible issues with global variables rather than give the best solutions. For more beautiful solutions using Binary Search, Dijkstra and Kruskal, watch Alex’s walkthrough (beginning 7:26) at https://www.youtube.com/watch?v=AM__3Zx1XNw&t=2325s&ab_channel=AlexWice" }, { "code": null, "e": 1168, "s": 911, "text": "The problem is to find the path with minimum effort after walking from top left to bottom right with each step allowing 4 directions of up, down, left, right. effort is defined as the maximum absolute difference in values between any 2 consecutive squares." }, { "code": null, "e": 2993, "s": 1168, "text": "import numpy as np\nimport math\n\nmin_effort = math.inf\n\ndef valid(r,c,visited):\n return 0 <= r < visited.shape[0] and 0 <= c < visited.shape[1] and visited[r,c] == 0\n\ndef find_path(heights_arr,visited,r,c,effort,max_row, max_col):\n global min_effort\n \n if r == max_row and c == max_col: \n print(f'-------------------Found end: effort is {effort}')\n return effort\n \n for row,col in ((r+1,c),(r,c+1),(r-1,c),(r,c-1)):\n if valid(row,col,visited):\n print(f'going from {r},{c} to {row},{col}')\n print(f'effort before recurse: {effort}')\n visited[row,col] = 1 \n updated_effort = max(effort, abs(heights_arr[row,col]-heights_arr[r,c])) # possibly update current max effort along path\n \n #recursion_res = find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col)\n #print(f'min_effort:{min_effort} recursion_res:{recursion_res}')\n #min_effort = min(min_effort,recursion_res)\n \n min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col)) # problem\n #min_effort = min(find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col),min_effort)\n \n visited[row,col] = 0\n \n print(f'global min_effort after recurse: {min_effort}')\n \n return math.inf\n #return min_effort\n \ndef minimumEffortPath(heights):\n heights_arr = np.array(heights) \n rows, cols = heights_arr.shape\n max_row, max_col = rows-1, cols-1\n \n r,c = 0,0\n visited = np.zeros((rows, cols))\n visited[r,c]=1\n \n effort = 0\n find_path(heights_arr,visited,r,c,effort,max_row, max_col)\n\n\nheights = [[1,2,3],[3,8,4],[5,3,5]]\nminimumEffortPath(heights)\nprint(min_effort)\n" }, { "code": null, "e": 7638, "s": 2993, "text": "going from 0,0 to 1,0\neffort before recurse: 0\ngoing from 1,0 to 2,0\neffort before recurse: 2\ngoing from 2,0 to 2,1\neffort before recurse: 2\ngoing from 2,1 to 2,2\neffort before recurse: 2\n-------------------Found end: effort is 2\nglobal min_effort after recurse: 2\ngoing from 2,1 to 1,1\neffort before recurse: 2\ngoing from 1,1 to 1,2\neffort before recurse: 5\ngoing from 1,2 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 2\ngoing from 1,2 to 0,2\neffort before recurse: 5\ngoing from 0,2 to 0,1\neffort before recurse: 5\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 0,1\neffort before recurse: 5\ngoing from 0,1 to 0,2\neffort before recurse: 6\ngoing from 0,2 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\ngoing from 1,0 to 1,1\neffort before recurse: 2\ngoing from 1,1 to 2,1\neffort before recurse: 5\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 5\ngoing from 2,1 to 2,0\neffort before recurse: 5\nglobal min_effort after recurse: 5\nglobal min_effort after recurse: inf\ngoing from 1,1 to 1,2\neffort before recurse: 5\ngoing from 1,2 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 5\ngoing from 1,2 to 0,2\neffort before recurse: 5\ngoing from 0,2 to 0,1\neffort before recurse: 5\nglobal min_effort after recurse: 5\nglobal min_effort after recurse: 5\nglobal min_effort after recurse: inf\ngoing from 1,1 to 0,1\neffort before recurse: 5\ngoing from 0,1 to 0,2\neffort before recurse: 6\ngoing from 0,2 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 6\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\ngoing from 0,0 to 0,1\neffort before recurse: 0\ngoing from 0,1 to 1,1\neffort before recurse: 1\ngoing from 1,1 to 2,1\neffort before recurse: 6\ngoing from 2,1 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 6\ngoing from 2,1 to 2,0\neffort before recurse: 6\ngoing from 2,0 to 1,0\neffort before recurse: 6\nglobal min_effort after recurse: 6\nglobal min_effort after recurse: 6\nglobal min_effort after recurse: inf\ngoing from 1,1 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 6\ngoing from 1,2 to 0,2\neffort before recurse: 6\nglobal min_effort after recurse: 6\nglobal min_effort after recurse: inf\ngoing from 1,1 to 1,0\neffort before recurse: 6\ngoing from 1,0 to 2,0\neffort before recurse: 6\ngoing from 2,0 to 2,1\neffort before recurse: 6\ngoing from 2,1 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 6\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\ngoing from 0,1 to 0,2\neffort before recurse: 1\ngoing from 0,2 to 1,2\neffort before recurse: 1\ngoing from 1,2 to 2,2\neffort before recurse: 1\n-------------------Found end: effort is 1\nglobal min_effort after recurse: 1\ngoing from 1,2 to 1,1\neffort before recurse: 1\ngoing from 1,1 to 2,1\neffort before recurse: 4\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 1\ngoing from 2,1 to 2,0\neffort before recurse: 5\ngoing from 2,0 to 1,0\neffort before recurse: 5\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\ngoing from 1,1 to 1,0\neffort before recurse: 4\ngoing from 1,0 to 2,0\neffort before recurse: 5\ngoing from 2,0 to 2,1\neffort before recurse: 5\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\nglobal min_effort after recurse: inf\ninf\n" }, { "code": null, "e": 9693, "s": 7638, "text": "import numpy as np\nimport math\n\ndef valid(r,c,visited):\n return 0 <= r < visited.shape[0] and 0 <= c < visited.shape[1] and visited[r,c] == 0\n\ndef find_path(heights_arr,visited,r,c,effort,max_row, max_col,min_effort):\n \n if r == max_row and c == max_col: \n print(f'-------------------Found end: effort is {effort}')\n return effort\n \n for row,col in ((r+1,c),(r,c+1),(r-1,c),(r,c-1)):\n if valid(row,col,visited):\n print(f'going from {r},{c} to {row},{col}')\n print(f'effort before recurse: {effort}')\n \n updated_effort = max(effort, abs(heights_arr[row,col]-heights_arr[r,c])) # possibly update current max effort along path\n \n visited[row,col] = 1\n\n #recursion_res = find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort)\n #print(f'min_effort:{min_effort} recursion_res:{recursion_res}')\n \n #min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort))\n min_effort = min(find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col,min_effort),min_effort)\n\n visited[row,col] = 0\n print(f'global min_effort after recurse: {min_effort}')\n \n return min_effort\n #return math.inf\n \ndef minimumEffortPath(heights):\n min_effort = math.inf\n \n heights_arr = np.array(heights) \n rows, cols = heights_arr.shape\n max_row, max_col = rows-1, cols-1\n \n r,c = 0,0\n visited = np.zeros((rows, cols))\n visited[r,c]=1\n \n effort = 0\n return find_path(heights_arr,visited,r,c,effort,max_row, max_col,min_effort)\n\n#heights = [[1,2,2],[3,8,2],[5,3,5]]\nheights = [[1,2,3],[3,8,4],[5,3,5]]\n#heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\n#heights = [[1,10,6,7,9,10,4,9]]\n#heights = [[4,3,4,10,5,5,9,2],[10,8,2,10,9,7,5,6],[5,8,10,10,10,7,4,2],[5,1,3,1,1,3,1,9],[6,4,10,6,10,9,4,6]]\nprint(minimumEffortPath(heights))\n#print(min_effort)\n" }, { "code": null, "e": 14300, "s": 9693, "text": "going from 0,0 to 1,0\neffort before recurse: 0\ngoing from 1,0 to 2,0\neffort before recurse: 2\ngoing from 2,0 to 2,1\neffort before recurse: 2\ngoing from 2,1 to 2,2\neffort before recurse: 2\n-------------------Found end: effort is 2\nglobal min_effort after recurse: 2\ngoing from 2,1 to 1,1\neffort before recurse: 2\ngoing from 1,1 to 1,2\neffort before recurse: 5\ngoing from 1,2 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 2\ngoing from 1,2 to 0,2\neffort before recurse: 5\ngoing from 0,2 to 0,1\neffort before recurse: 5\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 0,1\neffort before recurse: 5\ngoing from 0,1 to 0,2\neffort before recurse: 6\ngoing from 0,2 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,0 to 1,1\neffort before recurse: 2\ngoing from 1,1 to 2,1\neffort before recurse: 5\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 2\ngoing from 2,1 to 2,0\neffort before recurse: 5\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 1,2\neffort before recurse: 5\ngoing from 1,2 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 2\ngoing from 1,2 to 0,2\neffort before recurse: 5\ngoing from 0,2 to 0,1\neffort before recurse: 5\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 0,1\neffort before recurse: 5\ngoing from 0,1 to 0,2\neffort before recurse: 6\ngoing from 0,2 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 0,0 to 0,1\neffort before recurse: 0\ngoing from 0,1 to 1,1\neffort before recurse: 1\ngoing from 1,1 to 2,1\neffort before recurse: 6\ngoing from 2,1 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\ngoing from 2,1 to 2,0\neffort before recurse: 6\ngoing from 2,0 to 1,0\neffort before recurse: 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 1,2\neffort before recurse: 6\ngoing from 1,2 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\ngoing from 1,2 to 0,2\neffort before recurse: 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 1,1 to 1,0\neffort before recurse: 6\ngoing from 1,0 to 2,0\neffort before recurse: 6\ngoing from 2,0 to 2,1\neffort before recurse: 6\ngoing from 2,1 to 2,2\neffort before recurse: 6\n-------------------Found end: effort is 6\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\nglobal min_effort after recurse: 2\ngoing from 0,1 to 0,2\neffort before recurse: 1\ngoing from 0,2 to 1,2\neffort before recurse: 1\ngoing from 1,2 to 2,2\neffort before recurse: 1\n-------------------Found end: effort is 1\nglobal min_effort after recurse: 1\ngoing from 1,2 to 1,1\neffort before recurse: 1\ngoing from 1,1 to 2,1\neffort before recurse: 4\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 1\ngoing from 2,1 to 2,0\neffort before recurse: 5\ngoing from 2,0 to 1,0\neffort before recurse: 5\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\ngoing from 1,1 to 1,0\neffort before recurse: 4\ngoing from 1,0 to 2,0\neffort before recurse: 5\ngoing from 2,0 to 2,1\neffort before recurse: 5\ngoing from 2,1 to 2,2\neffort before recurse: 5\n-------------------Found end: effort is 5\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\nglobal min_effort after recurse: 1\n1\n" }, { "code": null, "e": 14440, "s": 14303, "text": "Notebook containing implementation with global vs no global variable: https://gist.github.com/gitgithan/a818d336c2309852a21d99efd619238d" }, { "code": null, "e": 14926, "s": 14440, "text": "My backtracking solution was to use a visited 2D array to track visits.Starting from the top-left cell, we try to move in the order of down, right, up, left (this order reaches the destination faster than some other orders, so the global min can be updated earlier, and used to bound/speed up the exploration of future paths) if within rectangle bounds and not visited before. Before moving (recursing), the visit is marked so future attempts to visit will return False for if valid()." }, { "code": null, "e": 15133, "s": 14926, "text": "Along the way, the effort (intialized to 0) of the path is updated using abs difference between the cell we are going to visit and current cell. If we reach base case (bottom-right cell), return the effort." }, { "code": null, "e": 15288, "s": 15133, "text": "Once a single direction of recursion is complete, we update the global minimum min_effort (initialized to math.inf) and unmark the cell in that direction." }, { "code": null, "e": 15441, "s": 15288, "text": "Once all 4 directions from the current cell is done, we return math.inf back up the call stack so it does not wrongly influence the min() of the caller." }, { "code": null, "e": 15748, "s": 15441, "text": "This output of five 2, followed by two inf was mindboggling. It looked like the global variable min_effort which was updated from inf to 2 after the first solution (1, down to 3, down to 5, right to 3, right to 5) went back to inf! The final answer(path of 1, 2, 3, 4, 5) was also wrongly inf instead of 1." }, { "code": null, "e": 15974, "s": 15748, "text": "Those five 2 correspond to the algorithm backtracking from destination 5 to 4,3,2,8,3,5 because all these have all 4 directions either visited or out of bounds, so the next path to try is to go right from 1,0 to 1,1 (3 to 8)." }, { "code": null, "e": 16291, "s": 15974, "text": "The problem is with the line min_effort = min(min_effort,find_path(...)) Because python evaluates arguments from left to right, the global variable min_effort was already evaluated before entering the recursion, so whatever happens in the recursion (including updates to global variable) has no effect on min_effort." }, { "code": null, "e": 16513, "s": 16291, "text": "At the scope of the 3 in bottom middle of the grid, the algorithm has not yet found a successful path (the 1st path being 1,3,5,3,5), so min_effort was still math.inf at that moment, and min(math.inf,math.inf) became inf." }, { "code": null, "e": 16528, "s": 16513, "text": "Swap arguments" }, { "code": null, "e": 16543, "s": 16528, "text": "Swap arguments" }, { "code": null, "e": 16728, "s": 16543, "text": "A fix is to simply swap the order of arguments to min_effort = min(find_path(...), min_effort). This gives the recursion a chance to update the global variable first before comparison." }, { "code": null, "e": 16756, "s": 16728, "text": "2. Save into variable first" }, { "code": null, "e": 16894, "s": 16756, "text": "If you still wanted to maintain the old order as a matter of preference, the recursion can be calculated and saved into a variable first." }, { "code": null, "e": 16968, "s": 16894, "text": "recursion_res = find_path(...)min_effort = min(min_effort, recursion_res)" }, { "code": null, "e": 17006, "s": 16968, "text": "3. Remove global variables completely" }, { "code": null, "e": 17333, "s": 17006, "text": "This was prompted by Leetcode giving wrong test results running all test cases, but running the failing case individually as custom input gives the correct result. If you insist on using globals on leetcode, copy the result, clear the global, and return the copied result so the cleared global is ready for the next test case." }, { "code": null, "e": 17442, "s": 17333, "text": "Two changes: 1. Add the previously global variable to recursive function signature find_path(...,min_effort)" }, { "code": null, "e": 17484, "s": 17442, "text": "2. Return min_effort rather than math.inf" }, { "code": null, "e": 18056, "s": 17484, "text": "This will ensure the minimum effort path is always propagated through the recursive calls. If you ask why not return min_effort while using global variable, that is workable too, but unnecessary, since if you avoid the gotcha mentioned above, min_effort would have been updated to a non-inf value before the min(min_effort,find_path(...))comparison, so even if the 2nd argument returns math.inf, the 1st argument will always be updated to the correct value once any path first reaches the destination. Also, math.inf felt more representative of a “no solution/bad value”." }, { "code": null, "e": 18583, "s": 18056, "text": "However, the argument in support of return min_effort rather than return math.inf is that it more accurately represents the most updated program state. Also, we can totally avoid the gotcha handling (the 1st two fixes described) and use min(min_effort,find_path(...)) directly because with return min_effort the 2nd argument will always be updated, so a “pre-recursion evaluated” min_effort that could contain its initialized math.inf in the 1st argument causes no harm. (exactly opposite situation of the previous paragraph)." }, { "code": null, "e": 19108, "s": 18583, "text": "Since we are looking for the global minimum, any path can be influenced by the results of any other path. This offers a chance for the current best result to short-circuit future paths once they are found to have longer effort than the current min_effort . This can be achieved by wrapping the backtracking section (visit,recurse,unvisit) with an extra check if updated_effort < min_effort: to largely reduce exploration steps, using “less than” because there is no point trying something that won’t reduce the current best." }, { "code": null, "e": 19326, "s": 19108, "text": "if updated_effort < min_effort: visited[row,col] = 1 min_effort = min(min_effort,find_path(heights_arr,visited,row,col,updated_effort,max_row,max_col)) visited[row,col] = 0" }, { "code": null, "e": 19339, "s": 19326, "text": "Global pros:" }, { "code": null, "e": 19466, "s": 19339, "text": "Lax return values allowed ( math.inf or min_effort )Convenient coding (less parameter passing and simpler recursive functions)" }, { "code": null, "e": 19519, "s": 19466, "text": "Lax return values allowed ( math.inf or min_effort )" }, { "code": null, "e": 19594, "s": 19519, "text": "Convenient coding (less parameter passing and simpler recursive functions)" }, { "code": null, "e": 19607, "s": 19594, "text": "Global cons:" }, { "code": null, "e": 19855, "s": 19607, "text": "Don’t gel with online coding platforms (risky for job interview automated coding assessments)Constantly have to be aware of side effects and variables not within current stackSensitive to function argument ordering (the root of all these troubles)" }, { "code": null, "e": 19949, "s": 19855, "text": "Don’t gel with online coding platforms (risky for job interview automated coding assessments)" }, { "code": null, "e": 20032, "s": 19949, "text": "Constantly have to be aware of side effects and variables not within current stack" }, { "code": null, "e": 20105, "s": 20032, "text": "Sensitive to function argument ordering (the root of all these troubles)" }, { "code": null, "e": 20117, "s": 20105, "text": "Local pros:" }, { "code": null, "e": 20191, "s": 20117, "text": "Easier debugging/tracing focusing on local problem spaceLess side effects" }, { "code": null, "e": 20248, "s": 20191, "text": "Easier debugging/tracing focusing on local problem space" }, { "code": null, "e": 20266, "s": 20248, "text": "Less side effects" }, { "code": null, "e": 20278, "s": 20266, "text": "Local cons:" }, { "code": null, "e": 20467, "s": 20278, "text": "More verbose function signature (more items to track means longer signature)Lose ability to return math.inf , have to return min_effort to propagate updated results back to rest of program" }, { "code": null, "e": 20544, "s": 20467, "text": "More verbose function signature (more items to track means longer signature)" }, { "code": null, "e": 20657, "s": 20544, "text": "Lose ability to return math.inf , have to return min_effort to propagate updated results back to rest of program" } ]
How to Install Multiple R Packages? - GeeksforGeeks
25 Mar, 2022 In this article, we will see how to install multiple packages in R Programming Language. Installation can be done in two ways. Step 1: Open R Studio Step 2: Navigate to Tools and select the Install packages option Step 3: In the Text box packages, enter the package names. Step 4: Click on install button Step 5: Find the console after clicking on the install button. If all packages installed successfully the below output will be generated. Otherwise, follow the steps again. In this method simply specify the packages to be installed as a vector to install.packages() function. Syntax: install.packages(c(“package1′′,....,”package n”)) Example R install.packages(c("ggplot2","dpylr")) To load multiple packages at once specify the names of the packages to be loaded to lapply() function. Syntax: lapply(c(“package 1′′,...”package n”), require, character.only = TRUE) Example: R lapply(c("dpylr", "ggplot2"), require, character.only = TRUE) surinderdawra388 how-to-install Picked R-Packages How To Installation Guide R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Check the OS Version in Linux? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 25024, "s": 24993, "text": " \n25 Mar, 2022\n" }, { "code": null, "e": 25151, "s": 25024, "text": "In this article, we will see how to install multiple packages in R Programming Language. Installation can be done in two ways." }, { "code": null, "e": 25173, "s": 25151, "text": "Step 1: Open R Studio" }, { "code": null, "e": 25239, "s": 25173, "text": "Step 2: Navigate to Tools and select the Install packages option " }, { "code": null, "e": 25298, "s": 25239, "text": "Step 3: In the Text box packages, enter the package names." }, { "code": null, "e": 25350, "s": 25318, "text": "Step 4: Click on install button" }, { "code": null, "e": 25523, "s": 25350, "text": "Step 5: Find the console after clicking on the install button. If all packages installed successfully the below output will be generated. Otherwise, follow the steps again." }, { "code": null, "e": 25626, "s": 25523, "text": "In this method simply specify the packages to be installed as a vector to install.packages() function." }, { "code": null, "e": 25634, "s": 25626, "text": "Syntax:" }, { "code": null, "e": 25684, "s": 25634, "text": "install.packages(c(“package1′′,....,”package n”))" }, { "code": null, "e": 25692, "s": 25684, "text": "Example" }, { "code": null, "e": 25694, "s": 25692, "text": "R" }, { "code": "\n\n\n\n\n\n\ninstall.packages(c(\"ggplot2\",\"dpylr\")) \n\n\n\n\n\n", "e": 25757, "s": 25704, "text": null }, { "code": null, "e": 25860, "s": 25757, "text": "To load multiple packages at once specify the names of the packages to be loaded to lapply() function." }, { "code": null, "e": 25868, "s": 25860, "text": "Syntax:" }, { "code": null, "e": 25939, "s": 25868, "text": "lapply(c(“package 1′′,...”package n”), require, character.only = TRUE)" }, { "code": null, "e": 25948, "s": 25939, "text": "Example:" }, { "code": null, "e": 25950, "s": 25948, "text": "R" }, { "code": "\n\n\n\n\n\n\nlapply(c(\"dpylr\", \"ggplot2\"), require, character.only = TRUE)\n\n\n\n\n\n", "e": 26035, "s": 25960, "text": null }, { "code": null, "e": 26052, "s": 26035, "text": "surinderdawra388" }, { "code": null, "e": 26069, "s": 26052, "text": "\nhow-to-install\n" }, { "code": null, "e": 26078, "s": 26069, "text": "\nPicked\n" }, { "code": null, "e": 26091, "s": 26078, "text": "\nR-Packages\n" }, { "code": null, "e": 26100, "s": 26091, "text": "\nHow To\n" }, { "code": null, "e": 26121, "s": 26100, "text": "\nInstallation Guide\n" }, { "code": null, "e": 26134, "s": 26121, "text": "\nR Language\n" }, { "code": null, "e": 26339, "s": 26134, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26373, "s": 26339, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26422, "s": 26373, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26480, "s": 26422, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26522, "s": 26480, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26560, "s": 26522, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 26593, "s": 26560, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26627, "s": 26593, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26662, "s": 26627, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 26720, "s": 26662, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
How to draw a line in OpenCV using C++?
To draw a line we need two points-the starting point and ending point. We also require a canvas to draw the line. Using OpenCV, the matrix in our canvas, we need to define the line's starting and ending points. We require to assign a color to the line as well. The thickness of the line has to be explained too. If we want to draw a line using OpenCV, we need to declare a matrix, two points, and color and line thickness. Using OpenCV we have to include <imgproc.hpp> header because line() function is defined in this header. The basic syntax of this method is as follows − line(whiteMatrix, starting, ending, line_Color, thickness); The following program shows how to draws a line on an image in OpenCV − #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; int main() { Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix// Point starting(50, 50);//Starting Point of the line Point ending(150, 150);//Ending Point of the line Scalar line_Color(0, 0, 0);//Color of the line int thickness = 2;//thickens of the line namedWindow("GrayImage");//Declaring a window to show the line line(whiteMatrix, starting, ending, line_Color, thickness);//using line() function to draw the line// imshow("GrayImage", whiteMatrix);//showing the line// waitKey(0);//Waiting for KeyStroke return 0; }
[ { "code": null, "e": 1176, "s": 1062, "text": "To draw a line we need two points-the starting point and ending point. We also require a canvas to draw the line." }, { "code": null, "e": 1485, "s": 1176, "text": "Using OpenCV, the matrix in our canvas, we need to define the line's starting and ending points. We require to assign a color to the line as well. The thickness of the line has to be explained too. If we want to draw a line using OpenCV, we need to declare a matrix, two points, and color and line thickness." }, { "code": null, "e": 1589, "s": 1485, "text": "Using OpenCV we have to include <imgproc.hpp> header because line() function is defined in this header." }, { "code": null, "e": 1637, "s": 1589, "text": "The basic syntax of this method is as follows −" }, { "code": null, "e": 1697, "s": 1637, "text": "line(whiteMatrix, starting, ending, line_Color, thickness);" }, { "code": null, "e": 1769, "s": 1697, "text": "The following program shows how to draws a line on an image in OpenCV −" }, { "code": null, "e": 2491, "s": 1769, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace cv;\nusing namespace std;\nint main() {\n Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix//\n Point starting(50, 50);//Starting Point of the line\n Point ending(150, 150);//Ending Point of the line\n Scalar line_Color(0, 0, 0);//Color of the line\n int thickness = 2;//thickens of the line\n namedWindow(\"GrayImage\");//Declaring a window to show the line\n line(whiteMatrix, starting, ending, line_Color, thickness);//using line() function to draw the line//\n imshow(\"GrayImage\", whiteMatrix);//showing the line//\n waitKey(0);//Waiting for KeyStroke\n return 0;\n}" } ]
Algorithms From Scratch: K-Nearest Neighbors | by Kurtis Pykes | Towards Data Science
A non-parametric algorithm capable of performing Classification and Regression; Thomas Cover, a professor at Stanford University, first proposed the idea of K-Nearest Neighbors algorithm in 1967. Many often refer to the K-NN as a lazy learner or a type of instance based learner since all computation is deferred until function evaluation. Personally, I believe this puts K-Nearest Neighbors towards the less complex end of Machine Learning Algorithms when we begin to conceptualize it. No matter whether we are doing Classification or Regression style problems the input will consist of the k nearest training examples in the original feature space. However, the output for the algorithm will of-course depend on the type of question — See Terminology section for more on the different outputs. Link to code generated in the Article... github.com K-Nearest Neighbors Classification → The output would determine class membership and the prediction is made by a plurality vote of its neighbors. Therefore, the new instance would be assigned to the class most common amongst the k nearest neighbors. K-Nearest Neighbors Regression → The output would determine property value for the object. Therefore, the new instance would be classified as the average of the values of the k Nearest Neighbors Instance-Based Learning → A family of Machine Learning Learning Algorithms that, instead of performing explicit generalization, compares new problem instances with instances seen in training which has been stored in memory. (Source: Wikipedia) Lazy Learning → A Machine Learning method in which generalization of the training data is, in theory, delayed until a query is made to the system, as opposed to eager learning where the system tries to generalize the training data before receiving queries. (Source: Wikipedia) Creating the K-NN algorithm is quite simple. The training phase is literally storing feature vectors and labels of the training samples, however we need to determine a positive integer for k. Generally, when we select a large value of k we reduce the effect of noise on the classification, thence making the boundaries between classes less distinctive. Ultimately, the selection of k is largely influenced by the data which means we have no way of knowing until we have tried with the data, yet there are many different heuristics we can use to select k for our data. Note: To read more about tuning the k hyperparameter see the Hyperparameter Optimization Wikipedia page. Great, we have selected k. In order to make a prediction on new instances for a classification task, the k closest records (from the training data) to the new observation are identified. Upon evaluation of the of the k neighbors an prediction is made — see K-Nearest Neighbors Classification in the terminology section to see how this is done. For us to identify the k closest records to a new instance we must take a measure of all the instances. This can be done in various ways, although as a guide many practitioners often use Euclidean distance when we have continuous variables and Hamming distance for discrete variables. IMAGE HAMMING AND EUCLIDEAN DISTANCE Chunking the Algorithm Calculate the Euclidean DistanceLocate NeighborsPredict Calculate the Euclidean Distance Locate Neighbors Predict Implementation To implement our K-Nearest Neighbors Classification algorithm, we will use the Iris dataset from Scikit-Learn. In this task we are challenged to predict whether a flower is setosa, versicolor, or virginica given the measurements of the flowers — making it a multiclass classification task. Note: In this implementation I did not perform any heuristics to select the optimal k — I simply randomly selected a value for k. import numpy as npimport pandas as pdfrom collections import Counterimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.metrics import accuracy_scorefrom sklearn.datasets import load_irisfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitiris = load_iris()X, y = iris.data, iris.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state=1810)X_train.shape, y_train.shape, X_test.shape, y_test.shape((120, 4), (120,), (30, 4), (30,)) We now have the data and have used a holdout based cross validation scheme to split the data — If you are unfamiliar with this terminology see the link below. towardsdatascience.com The first step is calculating the Euclidean distance between two rows. def euclidean(x1, x2): return np.sqrt(np.sum((x1 - x2)**2)) To test this function, I have taken some code from Jason Brownlee that he used to test his distance function. If we have the correct implementation then our outputs should be the same. # dataset from https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/dataset = [[2.7810836,2.550537003,0],[1.465489372,2.362125076,0],[3.396561688,4.400293529,0],[1.38807019,1.850220317,0],[3.06407232,3.005305973,0],[7.627531214,2.759262235,1],[5.332441248,2.088626775,1],[6.922596716,1.77106367,1],[8.675418651,-0.242068655,1],[7.673756466,3.508563011,1]]row0 = dataset[0]for row in dataset: print(euclidean(np.array(row0), np.array(row)))0.01.32901739152757871.94946466556532471.55914393855405490.53562807219384924.9529406111642152.77899026747829854.33124803802076.598623496953045.084885603993178 And we get the exact same output — feel free to check on the link provided. As previously mentioned, the k — neighbors to a new observation are the k nearest instances from the training data. Using our distance function, euclidean, we can now calculate the distance between each observation in the training data and the new we’ve been passed and select the k instances from are training data that are closest to our new observation. def find_neighbors(X_train, X_test, y_train, n_neighbors): distances = [euclidean(X_test, x) for x in X_train] k_nearest = np.argsort(distances)[:n_neighbors] k_nearest_label = [y_train[i] for i in k_nearest] most_common = Counter(k_nearest_label).most_common(1)[0][0] return most_common This function calculates the distances of the new observation to all the rows in the training data and stores it in a list. Next, we find the indexes of the k lowest distances using the NumPy module np.argsort() — see documentation. We then use the indexes to identify the class of the k instances. After that, we count the number of instances in k_nearest_labels list using the Counter function from Pythons in-built modules and return the most common (the label with highest counts). However, we won’t get to see this in action until we make a prediction so lets build our predict function. def predict(X_test, X_train, y_train, n_neighbors=3): predictions = [find_neighbors(X_train, x, y_train, n_neighbors) for x in X_test] return np.array(predictions)predict(X_test, X_train, y_train, n_neighbors=3)array([0, 0, 2, 2, 0, 1, 0, 0, 1, 1, 2, 1, 2, 0, 1, 2, 0, 0, 0, 2, 1, 2, 0, 0, 0, 0, 1, 1, 0, 2]) In the predict function we use a list comprehension to find the nearest neighbor for each new instance in the test set and return an array. Using 3 neighbors we get 100% accuracy on our task and we can compared it to scikit-learns implementation to see if we get the same results — which it did. Note: The Documentation for K-Nearest Neighbors Classifier can be found here knn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train, y_train)sklearn_preds = knn.predict(X_test)preds = predict(X_test, X_train, y_train, n_neighbors=3)print(f"My Implementation: {accuracy_score(y_test, preds)}\nScikit-Learn Implementation: {accuracy_score(y_test, sklearn_preds)}")My Implementation: 1.0Scikit-Learn Implementation: 1.0 Pros Intuitive and Simple No training step Can be used both for Classification and Regression (and unsupervised learning) Easy to implement for multiclass problems Cons As the data grows the algorithm becomes slow quite quickly Sensitive to Outliers Imbalanced Data causes problems — Can use weighted distances to overcome this. In this story you’ve learned about the K-Nearest Neighbors algorithm, how to implement the K-Nearest Neighbors classification algorithm from scratch in Python, and the pros and cons of using K-Nearest Neighbors. Let’s continue the conversation on LinkedIn...
[ { "code": null, "e": 368, "s": 172, "text": "A non-parametric algorithm capable of performing Classification and Regression; Thomas Cover, a professor at Stanford University, first proposed the idea of K-Nearest Neighbors algorithm in 1967." }, { "code": null, "e": 659, "s": 368, "text": "Many often refer to the K-NN as a lazy learner or a type of instance based learner since all computation is deferred until function evaluation. Personally, I believe this puts K-Nearest Neighbors towards the less complex end of Machine Learning Algorithms when we begin to conceptualize it." }, { "code": null, "e": 968, "s": 659, "text": "No matter whether we are doing Classification or Regression style problems the input will consist of the k nearest training examples in the original feature space. However, the output for the algorithm will of-course depend on the type of question — See Terminology section for more on the different outputs." }, { "code": null, "e": 1009, "s": 968, "text": "Link to code generated in the Article..." }, { "code": null, "e": 1020, "s": 1009, "text": "github.com" }, { "code": null, "e": 1270, "s": 1020, "text": "K-Nearest Neighbors Classification → The output would determine class membership and the prediction is made by a plurality vote of its neighbors. Therefore, the new instance would be assigned to the class most common amongst the k nearest neighbors." }, { "code": null, "e": 1465, "s": 1270, "text": "K-Nearest Neighbors Regression → The output would determine property value for the object. Therefore, the new instance would be classified as the average of the values of the k Nearest Neighbors" }, { "code": null, "e": 1709, "s": 1465, "text": "Instance-Based Learning → A family of Machine Learning Learning Algorithms that, instead of performing explicit generalization, compares new problem instances with instances seen in training which has been stored in memory. (Source: Wikipedia)" }, { "code": null, "e": 1986, "s": 1709, "text": "Lazy Learning → A Machine Learning method in which generalization of the training data is, in theory, delayed until a query is made to the system, as opposed to eager learning where the system tries to generalize the training data before receiving queries. (Source: Wikipedia)" }, { "code": null, "e": 2554, "s": 1986, "text": "Creating the K-NN algorithm is quite simple. The training phase is literally storing feature vectors and labels of the training samples, however we need to determine a positive integer for k. Generally, when we select a large value of k we reduce the effect of noise on the classification, thence making the boundaries between classes less distinctive. Ultimately, the selection of k is largely influenced by the data which means we have no way of knowing until we have tried with the data, yet there are many different heuristics we can use to select k for our data." }, { "code": null, "e": 2659, "s": 2554, "text": "Note: To read more about tuning the k hyperparameter see the Hyperparameter Optimization Wikipedia page." }, { "code": null, "e": 3003, "s": 2659, "text": "Great, we have selected k. In order to make a prediction on new instances for a classification task, the k closest records (from the training data) to the new observation are identified. Upon evaluation of the of the k neighbors an prediction is made — see K-Nearest Neighbors Classification in the terminology section to see how this is done." }, { "code": null, "e": 3288, "s": 3003, "text": "For us to identify the k closest records to a new instance we must take a measure of all the instances. This can be done in various ways, although as a guide many practitioners often use Euclidean distance when we have continuous variables and Hamming distance for discrete variables." }, { "code": null, "e": 3325, "s": 3288, "text": "IMAGE HAMMING AND EUCLIDEAN DISTANCE" }, { "code": null, "e": 3348, "s": 3325, "text": "Chunking the Algorithm" }, { "code": null, "e": 3404, "s": 3348, "text": "Calculate the Euclidean DistanceLocate NeighborsPredict" }, { "code": null, "e": 3437, "s": 3404, "text": "Calculate the Euclidean Distance" }, { "code": null, "e": 3454, "s": 3437, "text": "Locate Neighbors" }, { "code": null, "e": 3462, "s": 3454, "text": "Predict" }, { "code": null, "e": 3477, "s": 3462, "text": "Implementation" }, { "code": null, "e": 3767, "s": 3477, "text": "To implement our K-Nearest Neighbors Classification algorithm, we will use the Iris dataset from Scikit-Learn. In this task we are challenged to predict whether a flower is setosa, versicolor, or virginica given the measurements of the flowers — making it a multiclass classification task." }, { "code": null, "e": 3897, "s": 3767, "text": "Note: In this implementation I did not perform any heuristics to select the optimal k — I simply randomly selected a value for k." }, { "code": null, "e": 4426, "s": 3897, "text": "import numpy as npimport pandas as pdfrom collections import Counterimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.metrics import accuracy_scorefrom sklearn.datasets import load_irisfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitiris = load_iris()X, y = iris.data, iris.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state=1810)X_train.shape, y_train.shape, X_test.shape, y_test.shape((120, 4), (120,), (30, 4), (30,))" }, { "code": null, "e": 4585, "s": 4426, "text": "We now have the data and have used a holdout based cross validation scheme to split the data — If you are unfamiliar with this terminology see the link below." }, { "code": null, "e": 4608, "s": 4585, "text": "towardsdatascience.com" }, { "code": null, "e": 4679, "s": 4608, "text": "The first step is calculating the Euclidean distance between two rows." }, { "code": null, "e": 4742, "s": 4679, "text": "def euclidean(x1, x2): return np.sqrt(np.sum((x1 - x2)**2))" }, { "code": null, "e": 4927, "s": 4742, "text": "To test this function, I have taken some code from Jason Brownlee that he used to test his distance function. If we have the correct implementation then our outputs should be the same." }, { "code": null, "e": 5576, "s": 4927, "text": "# dataset from https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/dataset = [[2.7810836,2.550537003,0],[1.465489372,2.362125076,0],[3.396561688,4.400293529,0],[1.38807019,1.850220317,0],[3.06407232,3.005305973,0],[7.627531214,2.759262235,1],[5.332441248,2.088626775,1],[6.922596716,1.77106367,1],[8.675418651,-0.242068655,1],[7.673756466,3.508563011,1]]row0 = dataset[0]for row in dataset: print(euclidean(np.array(row0), np.array(row)))0.01.32901739152757871.94946466556532471.55914393855405490.53562807219384924.9529406111642152.77899026747829854.33124803802076.598623496953045.084885603993178" }, { "code": null, "e": 5652, "s": 5576, "text": "And we get the exact same output — feel free to check on the link provided." }, { "code": null, "e": 6009, "s": 5652, "text": "As previously mentioned, the k — neighbors to a new observation are the k nearest instances from the training data. Using our distance function, euclidean, we can now calculate the distance between each observation in the training data and the new we’ve been passed and select the k instances from are training data that are closest to our new observation." }, { "code": null, "e": 6325, "s": 6009, "text": "def find_neighbors(X_train, X_test, y_train, n_neighbors): distances = [euclidean(X_test, x) for x in X_train] k_nearest = np.argsort(distances)[:n_neighbors] k_nearest_label = [y_train[i] for i in k_nearest] most_common = Counter(k_nearest_label).most_common(1)[0][0] return most_common" }, { "code": null, "e": 6918, "s": 6325, "text": "This function calculates the distances of the new observation to all the rows in the training data and stores it in a list. Next, we find the indexes of the k lowest distances using the NumPy module np.argsort() — see documentation. We then use the indexes to identify the class of the k instances. After that, we count the number of instances in k_nearest_labels list using the Counter function from Pythons in-built modules and return the most common (the label with highest counts). However, we won’t get to see this in action until we make a prediction so lets build our predict function." }, { "code": null, "e": 7261, "s": 6918, "text": "def predict(X_test, X_train, y_train, n_neighbors=3): predictions = [find_neighbors(X_train, x, y_train, n_neighbors) for x in X_test] return np.array(predictions)predict(X_test, X_train, y_train, n_neighbors=3)array([0, 0, 2, 2, 0, 1, 0, 0, 1, 1, 2, 1, 2, 0, 1, 2, 0, 0, 0, 2, 1, 2, 0, 0, 0, 0, 1, 1, 0, 2])" }, { "code": null, "e": 7557, "s": 7261, "text": "In the predict function we use a list comprehension to find the nearest neighbor for each new instance in the test set and return an array. Using 3 neighbors we get 100% accuracy on our task and we can compared it to scikit-learns implementation to see if we get the same results — which it did." }, { "code": null, "e": 7634, "s": 7557, "text": "Note: The Documentation for K-Nearest Neighbors Classifier can be found here" }, { "code": null, "e": 7976, "s": 7634, "text": "knn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train, y_train)sklearn_preds = knn.predict(X_test)preds = predict(X_test, X_train, y_train, n_neighbors=3)print(f\"My Implementation: {accuracy_score(y_test, preds)}\\nScikit-Learn Implementation: {accuracy_score(y_test, sklearn_preds)}\")My Implementation: 1.0Scikit-Learn Implementation: 1.0" }, { "code": null, "e": 7981, "s": 7976, "text": "Pros" }, { "code": null, "e": 8002, "s": 7981, "text": "Intuitive and Simple" }, { "code": null, "e": 8019, "s": 8002, "text": "No training step" }, { "code": null, "e": 8098, "s": 8019, "text": "Can be used both for Classification and Regression (and unsupervised learning)" }, { "code": null, "e": 8140, "s": 8098, "text": "Easy to implement for multiclass problems" }, { "code": null, "e": 8145, "s": 8140, "text": "Cons" }, { "code": null, "e": 8204, "s": 8145, "text": "As the data grows the algorithm becomes slow quite quickly" }, { "code": null, "e": 8226, "s": 8204, "text": "Sensitive to Outliers" }, { "code": null, "e": 8305, "s": 8226, "text": "Imbalanced Data causes problems — Can use weighted distances to overcome this." }, { "code": null, "e": 8517, "s": 8305, "text": "In this story you’ve learned about the K-Nearest Neighbors algorithm, how to implement the K-Nearest Neighbors classification algorithm from scratch in Python, and the pros and cons of using K-Nearest Neighbors." } ]
Data Integration with Pandas. How to easily import Data | by Christianlauer | Towards Data Science
For adhoc data analysis via Jupyter Notebook you often need external data via CSV, Excel or database to process them with Python. Reading the data is relatively easy thanks to the handy Pandas library. I have summarized the standard procedures for you in this article. Of course, you can also use the same errors for later standardized and integrated data integration processes, such as an ETL for your Data Warehouse. Here is my selection of commands and sources that I use most often. If you want to try it out as well, you can simply use Jupyter Notebook Online — Click here [1]. Read from a CSV File A very typical first use case is of course the famous CSV file, which was either provided to you as a dump of a source system, and can be retrieved online or was automatically stored on a file folder. import pandas as pdpd.read_csv(‘yourfilename.csv’, header=None, nrows=5) After importing Pandas and importing the file via read_csv you will already see success: Read Data from Google Sheet Same like above but with a Google Sheets Link — be aware that you published the Sheet to the web before. (Go to file →publish to web [2]) import pandas as pdnew_google_sheet_url = ‘https://docs.google.com/spreadsheets/d/e/2PACX-1vQ8lv36OQPiqgfFjdgJF9clvwhhh2Ao2xDzkIzYp2g1CqBbpLsnW5nefPsPVOKKBX2PdFVX6Mweyyut/pub?gid=1696994381&single=true&output=csv'df=pd.read_csv(new_google_sheet_url) Et voilà: Read Data from a Database Beside CSV and other similar files you will often connect data to a database — here we need beside Pandas also the sqlite3 module[3]. import pandas as pdimport sqlite3 After the successful import of the data, we now can easily query tables via SQL String: # Read via SQLite databasescon = sqlite3.connect(“your.database.link”)#Read table via Select Statementplayer = pd.read_sql_query(“SELECT * from Table”, con)#close the connectioncon.close() Other possible Data Sources In addition to the standard data sources mentioned above, there are of course many other possible data sources, such as data warehouse technologies like Google Big Query and Amazon’s Redshift or even NoSQL databases. Here, you will often find downloadable Pythons libraries [4]. Whether for an adhoc data analysis via e.g. Jupyter Notebook or later for standardized and automated data integration processes, external data sources like files or databases are often needed. These can be easily connected and queried with the toolset Python, Pandas and possibly other libraries. In this article, the most commonly used data sources were mentioned as an overview, further data sources can usually be accessed with other third-party libraries. [1] Jupyter.org, Mainpage (2021) [2] zhukovgreen, Stackoverflow (2016) [3] pythoncentral.io, Introduction to SQLite in Python (2013) [4] Google, Downloading BigQuery data to pandas using the BigQuery Storage API (2021)
[ { "code": null, "e": 591, "s": 172, "text": "For adhoc data analysis via Jupyter Notebook you often need external data via CSV, Excel or database to process them with Python. Reading the data is relatively easy thanks to the handy Pandas library. I have summarized the standard procedures for you in this article. Of course, you can also use the same errors for later standardized and integrated data integration processes, such as an ETL for your Data Warehouse." }, { "code": null, "e": 755, "s": 591, "text": "Here is my selection of commands and sources that I use most often. If you want to try it out as well, you can simply use Jupyter Notebook Online — Click here [1]." }, { "code": null, "e": 776, "s": 755, "text": "Read from a CSV File" }, { "code": null, "e": 977, "s": 776, "text": "A very typical first use case is of course the famous CSV file, which was either provided to you as a dump of a source system, and can be retrieved online or was automatically stored on a file folder." }, { "code": null, "e": 1050, "s": 977, "text": "import pandas as pdpd.read_csv(‘yourfilename.csv’, header=None, nrows=5)" }, { "code": null, "e": 1139, "s": 1050, "text": "After importing Pandas and importing the file via read_csv you will already see success:" }, { "code": null, "e": 1167, "s": 1139, "text": "Read Data from Google Sheet" }, { "code": null, "e": 1305, "s": 1167, "text": "Same like above but with a Google Sheets Link — be aware that you published the Sheet to the web before. (Go to file →publish to web [2])" }, { "code": null, "e": 1555, "s": 1305, "text": "import pandas as pdnew_google_sheet_url = ‘https://docs.google.com/spreadsheets/d/e/2PACX-1vQ8lv36OQPiqgfFjdgJF9clvwhhh2Ao2xDzkIzYp2g1CqBbpLsnW5nefPsPVOKKBX2PdFVX6Mweyyut/pub?gid=1696994381&single=true&output=csv'df=pd.read_csv(new_google_sheet_url)" }, { "code": null, "e": 1566, "s": 1555, "text": "Et voilà:" }, { "code": null, "e": 1592, "s": 1566, "text": "Read Data from a Database" }, { "code": null, "e": 1726, "s": 1592, "text": "Beside CSV and other similar files you will often connect data to a database — here we need beside Pandas also the sqlite3 module[3]." }, { "code": null, "e": 1760, "s": 1726, "text": "import pandas as pdimport sqlite3" }, { "code": null, "e": 1848, "s": 1760, "text": "After the successful import of the data, we now can easily query tables via SQL String:" }, { "code": null, "e": 2037, "s": 1848, "text": "# Read via SQLite databasescon = sqlite3.connect(“your.database.link”)#Read table via Select Statementplayer = pd.read_sql_query(“SELECT * from Table”, con)#close the connectioncon.close()" }, { "code": null, "e": 2065, "s": 2037, "text": "Other possible Data Sources" }, { "code": null, "e": 2344, "s": 2065, "text": "In addition to the standard data sources mentioned above, there are of course many other possible data sources, such as data warehouse technologies like Google Big Query and Amazon’s Redshift or even NoSQL databases. Here, you will often find downloadable Pythons libraries [4]." }, { "code": null, "e": 2804, "s": 2344, "text": "Whether for an adhoc data analysis via e.g. Jupyter Notebook or later for standardized and automated data integration processes, external data sources like files or databases are often needed. These can be easily connected and queried with the toolset Python, Pandas and possibly other libraries. In this article, the most commonly used data sources were mentioned as an overview, further data sources can usually be accessed with other third-party libraries." }, { "code": null, "e": 2837, "s": 2804, "text": "[1] Jupyter.org, Mainpage (2021)" }, { "code": null, "e": 2875, "s": 2837, "text": "[2] zhukovgreen, Stackoverflow (2016)" }, { "code": null, "e": 2937, "s": 2875, "text": "[3] pythoncentral.io, Introduction to SQLite in Python (2013)" } ]
jQuery - Widget Spinner
The Widget Spinner function can be used with widgets in JqueryUI.Spinner provide a quick way to select one value from a set. Here is the simple syntax to use Spinner − $( "#menu" ).selectmenu(); Following is a simple example showing the usage of Spinner − <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Spinner - Default functionality</title> <link rel = "stylesheet" href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src = "//code.jquery.com/jquery-1.10.2.js"> </script> <script src = "/resources/demos/external/jquery-mousewheel/jquery.mousewheel.js"> </script> <script src = "//code.jquery.com/ui/1.11.4/jquery-ui.js"> </script> <script> $(function() { var spinner = $( "#spinner" ).spinner(); $( "#disable" ).click(function() { if ( spinner.spinner( "option", "disabled" ) ) { spinner.spinner( "enable" ); } else { spinner.spinner( "disable" ); } }); $( "#destroy" ).click(function() { if ( spinner.spinner( "instance" ) ) { spinner.spinner( "destroy" ); } else { spinner.spinner(); } }); $( "#getvalue" ).click(function() { alert( spinner.spinner( "value" ) ); }); $( "#setvalue" ).click(function() { spinner.spinner( "value", 5 ); }); $( "button" ).button(); }); </script> </head> <body> <p> <label for = "spinner">Select a value:</label> <input id = "spinner" name = "value"> </p> </body> </html> This will produce following result − Select a value: ▲▼ 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2322, "text": "The Widget Spinner function can be used with widgets in JqueryUI.Spinner provide a quick way to select one value from a set." }, { "code": null, "e": 2490, "s": 2447, "text": "Here is the simple syntax to use Spinner −" }, { "code": null, "e": 2518, "s": 2490, "text": "$( \"#menu\" ).selectmenu();\n" }, { "code": null, "e": 2579, "s": 2518, "text": "Following is a simple example showing the usage of Spinner −" }, { "code": null, "e": 4187, "s": 2579, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner - Default functionality</title>\n\t\t\n <link rel = \"stylesheet\" \n href = \"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\t\t\t\n <script src = \"//code.jquery.com/jquery-1.10.2.js\">\n </script>\n <script \n src = \"/resources/demos/external/jquery-mousewheel/jquery.mousewheel.js\">\n </script>\n <script src = \"//code.jquery.com/ui/1.11.4/jquery-ui.js\">\n </script>\n\n <script>\n $(function() {\n\t\t\t\n var spinner = $( \"#spinner\" ).spinner();\n \n $( \"#disable\" ).click(function() {\n if ( spinner.spinner( \"option\", \"disabled\" ) ) {\n spinner.spinner( \"enable\" );\n } else {\n spinner.spinner( \"disable\" );\n }\n });\n\t\t\t\t\n $( \"#destroy\" ).click(function() {\n if ( spinner.spinner( \"instance\" ) ) {\n spinner.spinner( \"destroy\" );\n } else {\n spinner.spinner();\n }\n });\n\t\t\t\t\n $( \"#getvalue\" ).click(function() {\n alert( spinner.spinner( \"value\" ) );\n });\n\t\t\t\t\n $( \"#setvalue\" ).click(function() {\n spinner.spinner( \"value\", 5 );\n });\n \n $( \"button\" ).button();\n\t\t\t\t\n });\n </script>\n </head>\n\n <body>\n <p>\n <label for = \"spinner\">Select a value:</label>\n <input id = \"spinner\" name = \"value\">\n </p>\n </body>\n</html>" }, { "code": null, "e": 4224, "s": 4187, "text": "This will produce following result −" }, { "code": null, "e": 4245, "s": 4224, "text": "\nSelect a value:\n▲▼\n" }, { "code": null, "e": 4278, "s": 4245, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4292, "s": 4278, "text": " Mahesh Kumar" }, { "code": null, "e": 4327, "s": 4292, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4341, "s": 4327, "text": " Pratik Singh" }, { "code": null, "e": 4376, "s": 4341, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4393, "s": 4376, "text": " Frahaan Hussain" }, { "code": null, "e": 4426, "s": 4393, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4454, "s": 4426, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4487, "s": 4454, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4508, "s": 4487, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4540, "s": 4508, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4557, "s": 4540, "text": " Laurence Svekis" }, { "code": null, "e": 4564, "s": 4557, "text": " Print" }, { "code": null, "e": 4575, "s": 4564, "text": " Add Notes" } ]
Scala - Recursion Functions
Recursion plays a big role in pure functional programming and Scala supports recursion functions very well. Recursion means a function can call itself repeatedly. Try the following program, it is a good example of recursion where factorials of the passed number are calculated. object Demo { def main(args: Array[String]) { for (i <- 1 to 10) println( "Factorial of " + i + ": = " + factorial(i) ) } def factorial(n: BigInt): BigInt = { if (n <= 1) 1 else n * factorial(n - 1) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Factorial of 1: = 1 Factorial of 2: = 2 Factorial of 3: = 6 Factorial of 4: = 24 Factorial of 5: = 120 Factorial of 6: = 720 Factorial of 7: = 5040 Factorial of 8: = 40320 Factorial of 9: = 362880 Factorial of 10: = 3628800 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2161, "s": 1998, "text": "Recursion plays a big role in pure functional programming and Scala supports recursion functions very well. Recursion means a function can call itself repeatedly." }, { "code": null, "e": 2276, "s": 2161, "text": "Try the following program, it is a good example of recursion where factorials of the passed number are calculated." }, { "code": null, "e": 2545, "s": 2276, "text": "object Demo {\n def main(args: Array[String]) {\n for (i <- 1 to 10)\n println( \"Factorial of \" + i + \": = \" + factorial(i) )\n }\n \n def factorial(n: BigInt): BigInt = { \n if (n <= 1)\n 1 \n else \n n * factorial(n - 1)\n }\n}" }, { "code": null, "e": 2652, "s": 2545, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 2686, "s": 2652, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 2911, "s": 2686, "text": "Factorial of 1: = 1\nFactorial of 2: = 2\nFactorial of 3: = 6\nFactorial of 4: = 24\nFactorial of 5: = 120\nFactorial of 6: = 720\nFactorial of 7: = 5040\nFactorial of 8: = 40320\nFactorial of 9: = 362880\nFactorial of 10: = 3628800\n" }, { "code": null, "e": 2944, "s": 2911, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 2963, "s": 2944, "text": " Arnab Chakraborty" }, { "code": null, "e": 2998, "s": 2963, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3019, "s": 2998, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3054, "s": 3019, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3072, "s": 3054, "text": " Bigdata Engineer" }, { "code": null, "e": 3107, "s": 3072, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3125, "s": 3107, "text": " Bigdata Engineer" }, { "code": null, "e": 3160, "s": 3125, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3178, "s": 3160, "text": " Bigdata Engineer" }, { "code": null, "e": 3213, "s": 3178, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3236, "s": 3213, "text": " Stone River ELearning" }, { "code": null, "e": 3243, "s": 3236, "text": " Print" }, { "code": null, "e": 3254, "s": 3243, "text": " Add Notes" } ]
Difference between Parcelable and Serializable in android
This example demonstrates about Difference between Parcel able and Serializable in android Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable. A simple example of serializable as shown below – import java.io.Serializable; class serializableObject implements Serializable { String name; public serializableObject(String name) { this.name = name; } public String getName() { return name; } } Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities. A simple example of Parcel able as shown below – import android.os.Parcel; import android.os.Parcelable; class parcleObject implements Parcelable { private String name; protected parcleObject(Parcel in) { this.name = in.readString(); } public parcleObject(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static final Creator<parcleObject> CREATOR = new Creator<parcleObject>() { @Override public parcleObject createFromParcel(Parcel in) { return new parcleObject(in); } @Override public parcleObject[] newArray(int size) { return new parcleObject[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); } }
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates about Difference between Parcel able and Serializable in android" }, { "code": null, "e": 1533, "s": 1153, "text": "Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable." }, { "code": null, "e": 1583, "s": 1533, "text": "A simple example of serializable as shown below –" }, { "code": null, "e": 1807, "s": 1583, "text": "import java.io.Serializable;\nclass serializableObject implements Serializable {\n String name;\n public serializableObject(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n}" }, { "code": null, "e": 2100, "s": 1807, "text": "Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities." }, { "code": null, "e": 2149, "s": 2100, "text": "A simple example of Parcel able as shown below –" }, { "code": null, "e": 3039, "s": 2149, "text": "import android.os.Parcel;\nimport android.os.Parcelable;\nclass parcleObject implements Parcelable {\n private String name;\n protected parcleObject(Parcel in) {\n this.name = in.readString();\n }\n public parcleObject(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public static final Creator<parcleObject> CREATOR = new Creator<parcleObject>() {\n @Override\n public parcleObject createFromParcel(Parcel in) {\n return new parcleObject(in);\n }\n @Override\n public parcleObject[] newArray(int size) {\n return new parcleObject[size];\n }\n };\n @Override\n public int describeContents() {\n return 0;\n }\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.name);\n }\n}" } ]
LocalDate getYear() method in Java
The year for a particular LocalDate can be obtained using the getYear() method in the LocalDate class in Java. This method requires no parameters and it returns the year which can range from MIN_YEAR to MAX_YEAR. A program that demonstrates this is given as follows Live Demo import java.time.*; public class Demo { public static void main(String[] args) { LocalDate ld = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate is: " + ld); System.out.println("The year is: " + ld.getYear()); } } The LocalDate is: 2019-02-14 The year is: 2019 Now let us understand the above program. First the LocalDate is displayed. Then the year for the LocalDate is displayed using the getYear() method. A code snippet that demonstrates this is as follows: LocalDate ld = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate is: " + ld); System.out.println("The year is: " + ld.getYear());
[ { "code": null, "e": 1275, "s": 1062, "text": "The year for a particular LocalDate can be obtained using the getYear() method in the LocalDate class in Java. This method requires no parameters and it returns the year which can range from MIN_YEAR to MAX_YEAR." }, { "code": null, "e": 1328, "s": 1275, "text": "A program that demonstrates this is given as follows" }, { "code": null, "e": 1339, "s": 1328, "text": " Live Demo" }, { "code": null, "e": 1593, "s": 1339, "text": "import java.time.*;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate ld = LocalDate.parse(\"2019-02-14\");\n System.out.println(\"The LocalDate is: \" + ld);\n System.out.println(\"The year is: \" + ld.getYear());\n }\n}" }, { "code": null, "e": 1640, "s": 1593, "text": "The LocalDate is: 2019-02-14\nThe year is: 2019" }, { "code": null, "e": 1681, "s": 1640, "text": "Now let us understand the above program." }, { "code": null, "e": 1841, "s": 1681, "text": "First the LocalDate is displayed. Then the year for the LocalDate is displayed using the getYear() method. A code snippet that demonstrates this is as follows:" }, { "code": null, "e": 1986, "s": 1841, "text": "LocalDate ld = LocalDate.parse(\"2019-02-14\");\nSystem.out.println(\"The LocalDate is: \" + ld);\nSystem.out.println(\"The year is: \" + ld.getYear());" } ]
Hive - Data Types
This chapter takes you through the different data types in Hive, which are involved in the table creation. All the data types in Hive are classified into four types, given as follows: Column Types Literals Null Values Complex Types Column type are used as column data types of Hive. They are as follows: Integer type data can be specified using integral data types, INT. When the data range exceeds the range of INT, you need to use BIGINT and if the data range is smaller than the INT, you use SMALLINT. TINYINT is smaller than SMALLINT. The following table depicts various INT data types: String type data types can be specified using single quotes (' ') or double quotes (" "). It contains two data types: VARCHAR and CHAR. Hive follows C-types escape characters. The following table depicts various CHAR data types: It supports traditional UNIX timestamp with optional nanosecond precision. It supports java.sql.Timestamp format “YYYY-MM-DD HH:MM:SS.fffffffff” and format “yyyy-mm-dd hh:mm:ss.ffffffffff”. DATE values are described in year/month/day format in the form {{YYYY-MM-DD}}. The DECIMAL type in Hive is as same as Big Decimal format of Java. It is used for representing immutable arbitrary precision. The syntax and example is as follows: DECIMAL(precision, scale) decimal(10,0) Union is a collection of heterogeneous data types. You can create an instance using create union. The syntax and example is as follows: UNIONTYPE<int, double, array<string>, struct<a:int,b:string>> {0:1} {1:2.0} {2:["three","four"]} {3:{"a":5,"b":"five"}} {2:["six","seven"]} {3:{"a":8,"b":"eight"}} {0:9} {1:10.0} The following literals are used in Hive: Floating point types are nothing but numbers with decimal points. Generally, this type of data is composed of DOUBLE data type. Missing values are represented by the special value NULL. The Hive complex data types are as follows: Arrays in Hive are used the same way they are used in Java. Syntax: ARRAY<data_type> Maps in Hive are similar to Java Maps. Syntax: MAP<primitive_type, data_type> Structs in Hive is similar to using complex data with comment. Syntax: STRUCT<col_name : data_type [COMMENT col_comment], ...> 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2134, "s": 1950, "text": "This chapter takes you through the different data types in Hive, which are involved in the table creation. All the data types in Hive are classified into four types, given as follows:" }, { "code": null, "e": 2147, "s": 2134, "text": "Column Types" }, { "code": null, "e": 2156, "s": 2147, "text": "Literals" }, { "code": null, "e": 2168, "s": 2156, "text": "Null Values" }, { "code": null, "e": 2182, "s": 2168, "text": "Complex Types" }, { "code": null, "e": 2254, "s": 2182, "text": "Column type are used as column data types of Hive. They are as follows:" }, { "code": null, "e": 2489, "s": 2254, "text": "Integer type data can be specified using integral data types, INT. When the data range exceeds the range of INT, you need to use BIGINT and if the data range is smaller than the INT, you use SMALLINT. TINYINT is smaller than SMALLINT." }, { "code": null, "e": 2541, "s": 2489, "text": "The following table depicts various INT data types:" }, { "code": null, "e": 2717, "s": 2541, "text": "String type data types can be specified using single quotes (' ') or double quotes (\" \"). It contains two data types: VARCHAR and CHAR. Hive follows C-types escape characters." }, { "code": null, "e": 2770, "s": 2717, "text": "The following table depicts various CHAR data types:" }, { "code": null, "e": 2960, "s": 2770, "text": "It supports traditional UNIX timestamp with optional nanosecond precision. It supports java.sql.Timestamp format “YYYY-MM-DD HH:MM:SS.fffffffff” and format “yyyy-mm-dd hh:mm:ss.ffffffffff”." }, { "code": null, "e": 3039, "s": 2960, "text": "DATE values are described in year/month/day format in the form {{YYYY-MM-DD}}." }, { "code": null, "e": 3203, "s": 3039, "text": "The DECIMAL type in Hive is as same as Big Decimal format of Java. It is used for representing immutable arbitrary precision. The syntax and example is as follows:" }, { "code": null, "e": 3243, "s": 3203, "text": "DECIMAL(precision, scale)\ndecimal(10,0)" }, { "code": null, "e": 3379, "s": 3243, "text": "Union is a collection of heterogeneous data types. You can create an instance using create union. The syntax and example is as follows:" }, { "code": null, "e": 3566, "s": 3379, "text": "UNIONTYPE<int, double, array<string>, struct<a:int,b:string>>\n\n{0:1} \n{1:2.0} \n{2:[\"three\",\"four\"]} \n{3:{\"a\":5,\"b\":\"five\"}} \n{2:[\"six\",\"seven\"]} \n{3:{\"a\":8,\"b\":\"eight\"}} \n{0:9} \n{1:10.0}" }, { "code": null, "e": 3607, "s": 3566, "text": "The following literals are used in Hive:" }, { "code": null, "e": 3735, "s": 3607, "text": "Floating point types are nothing but numbers with decimal points. Generally, this type of data is composed of DOUBLE data type." }, { "code": null, "e": 3793, "s": 3735, "text": "Missing values are represented by the special value NULL." }, { "code": null, "e": 3837, "s": 3793, "text": "The Hive complex data types are as follows:" }, { "code": null, "e": 3897, "s": 3837, "text": "Arrays in Hive are used the same way they are used in Java." }, { "code": null, "e": 3922, "s": 3897, "text": "Syntax: ARRAY<data_type>" }, { "code": null, "e": 3961, "s": 3922, "text": "Maps in Hive are similar to Java Maps." }, { "code": null, "e": 4000, "s": 3961, "text": "Syntax: MAP<primitive_type, data_type>" }, { "code": null, "e": 4063, "s": 4000, "text": "Structs in Hive is similar to using complex data with comment." }, { "code": null, "e": 4127, "s": 4063, "text": "Syntax: STRUCT<col_name : data_type [COMMENT col_comment], ...>" }, { "code": null, "e": 4160, "s": 4127, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 4174, "s": 4160, "text": " Navdeep Kaur" }, { "code": null, "e": 4207, "s": 4174, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 4225, "s": 4207, "text": " Bigdata Engineer" }, { "code": null, "e": 4259, "s": 4225, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 4277, "s": 4259, "text": " Bigdata Engineer" }, { "code": null, "e": 4284, "s": 4277, "text": " Print" }, { "code": null, "e": 4295, "s": 4284, "text": " Add Notes" } ]
A Guide to Everything String Formatting in Python | by Sara A. Metwalli | Towards Data Science
Strings are one of the most essential and used datatypes in programming. It allows the computer to interact and communicate with the world, such as printing instructions or reading input from the user. The ability to manipulate and formate strings give the programmer the power to process and handle text, for example, extract user input from websites forms, data from processed text, and use this data to perform activities such as sentimental analysis. Sentimental analysis is a subfield of natural language processing that allows the computer to classify emotions — negative, positive, or neutral — based on a piece of text. “All sentiment is right; because sentiment has a reference to nothing beyond itself, and is always real, wherever a man is conscious of it.” — David Hume Python is one of the main programming languages used to analyze and manipulate data next to R. Python is used in data analytics to help access databases and communicate with them. It is also useful in importing and exporting data using different web scraping techniques. Once this data is obtained, Python is used to clean and prepare data sets before they are fed to a machine-learning algorithm. There are five ways you can use Python to format strings: formatting strings using the modulo operator, formatting using Python’s built-in format function, formatting using Python 3.7 f-strings, formatting manually, and finally using template strings. We will cover each one of these methods as well as when to use each of them. Let’s get right to it... If you wrote code using C or C++ before, this would look very familiar to you. In Python, we can use the modulo operator (%) to perform simple positional formatting. What I call placeHolder here, represents the control specs for formatting and converting the string. The % tells the interpreter that the following characters are the rules for converting the string. The conversion rules include information about the desired width of the result formatted string, the type of the result, and the precision of it — in case of floats. This type of string formatting is sometimes referred to as the “old style” formatting. The placeHolder can refer to values directly or can be specified using keywords arguments. formatted_str = 'Yesterday I bought %d %s for only %.2f$!' % (10, 2'bananas',2.6743) If we try to print this string, we will get Yesterday I bought 10 bananas for only 2.67$! . As you can see here, I had three placeHolders for three values, the first integer, the string — bananas — and the price of the bananas, which is a float. When referring to the float, I decided that a precision of two is all I needed; that’s why only 67 is displayed after the decimal point. In the previous example, we replaced the placeHolders with the values directly. There is another way we can achieve this mapping, which is through using keyword arguments or by passing a dictionary. name = 'John'balance = 235765formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {"name":name, "balance":balance} Using this method, we need to use the {} instead of the (). Because of that, we can also use a dictionary directly to fill in the placeHolders. dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = 'I got %(quantity)d %(name)s for $%(price).2f$' % dictionary The complete code for this section: In Python 3, a new method to regulate the % operator syntax was introduced to the language. This is done using the built-in format method, also known as the “new style” formatting. Using the format method has many commonalities with using the % operator. Let’s consider rewriting some of the examples from before: name = 'John'balance = 235765formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {"name":name, "balance":balance} Will become: name = 'John'balance = 235765formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format("name":name, "balance":balance) We can summarize the differences between the % operator syntax and the format method as: Using the % operator, we use the () inside the string, while with format method we use {} .To define the type of the conversion in the % operator, we set it right after the %, while in the format function we set the conversion after : inside the {}. Using the % operator, we use the () inside the string, while with format method we use {} . To define the type of the conversion in the % operator, we set it right after the %, while in the format function we set the conversion after : inside the {}. However, if we want to pass a dictionary to the format string, we will need to modify the reforestation slightly. Instead of passing the name of the dictionary, we need to pass a pointer to the dictionary, for example: dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = 'I got {quantity:d} {name:s} for {price:.2f}$'.format(**dictionary) Moreover, we can use the same conversion rules of the % operator that can be used in the format method as well. In Python 3 and up to 3.6, the format method is preferred to the % operator approach. The format method presented a powerful approach to format strings; it didn’t complicate the simple case — such as the examples above — but, at the same time providing new levels to how we format strings. The complete code for this section: This, in my opinion, the fanciest and most elegant method to format strings. The f-string was presented in Python 3.8 as a more straightforward approach to string formating. Before we get into f-strings, let’s quickly cover the three types of strings in Python 3.8 and up. Normal/ standard strings: contained between “” or ‘’, example “Hello, world!”. These are the most commonly used string type.Raw strings: lead by r”, for example r’hello\nworld’. In this type of strings, no processing is done on the string. Which means, escape characters don't work in these strings. Instead, they will be printed without any processing. This type of strings is mostly used in regular expressions.f-strings: lead by f”, for example, f’hello John!’. F-strings as used as an alternative way to format strings. Normal/ standard strings: contained between “” or ‘’, example “Hello, world!”. These are the most commonly used string type. Raw strings: lead by r”, for example r’hello\nworld’. In this type of strings, no processing is done on the string. Which means, escape characters don't work in these strings. Instead, they will be printed without any processing. This type of strings is mostly used in regular expressions. f-strings: lead by f”, for example, f’hello John!’. F-strings as used as an alternative way to format strings. towardsdatascience.com f-strings present a simple way to format strings by directly embedding expression into the string. Let’s revisit the examples from before, one more time. name = 'John'balance = 235765formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format("name":name, "balance":balance) If we want to rewrite this formatting using f-strings, it will look like: name = 'John'balance = 235765formatted_str = f'Hello {name}, your current balance is {balance} dollars.' One way f-string simplifies string formatting is, we can directly pass iterables — dictionaries, lists, etc. — to the string, as follows: dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = f'I got dictionary[quantity] dictionary[name] for dictionary[price]$'#f-string with listsmyList = [1,2,3,4]formatted_str = f'The last item of the list is myList[-1]' You can also perform simple arithmetic or logic operations within an f-string directly. #ArithmeticmyList = [1,2,3,4]formatted_str = f'The sum of the last and first items of the list is myList[0] + myList[-1]'#Logicformatted_str = f'myList[0] == myList[-1]' f-strings provide much more freedom to the options we can use inside the string we want to format, such as list indexing, calling list or dictionary methods, or general iterables functions — e.g., len, sum, min, and max. We can also use conditional statements in an f-string: age = 21formatted_str = f'You {"can't" if age < 21 else "can"} drink!' The complete code for this section: Manual formatting refers to using standard string methods to format strings. Mostly, we use the rjust, ljust, and center to justify the strings. The rjust method right-justifies a string given a specific width by padding it with spaces on the left. The ljust adds padding to the right and the center method adds padding on both sides of the string. These methods do not modify the original string; they instead return a new modified string. There is another string method that can be used to format strings, which is the zfill method. This method pads a string with a numeric value with zeros on the left. Template strings are an alternative to the % operator, but instead of the %, template strings use the $ sign. Both methods provide what we refer to as substitution formatting. Template strings are not built-in in Python, hence to use them, we need to first import the string module. Template strings have three rules: $$ is an escape character.Whatever follows the $ sign directly is the placeHolder for the template. By default, these placeHolders are restricted to any case-insensitive alphanumeric string. The first non-placeHolder character after the $ sign terminates this placeHolder specs, for example, a whitespace character. $$ is an escape character. Whatever follows the $ sign directly is the placeHolder for the template. By default, these placeHolders are restricted to any case-insensitive alphanumeric string. The first non-placeHolder character after the $ sign terminates this placeHolder specs, for example, a whitespace character. These rules ad more are already defined in the string module, so once imported, you can go ahead and use them without the need to define them. The template string has two main methods: the substitute method and the safe_substitute method. Both methods take the same argument, which is the substitute mapping. Moreover, both methods return a new formatted string, you can think of the template object as the blueprint for how future strings will be formatted. For example: from string import Templateformatted_str = Template('Hello $who, your current balance is $how dollars.')formatted_str.substitute(who='John', how=235765) To see the difference between the substitute and the safe_substitute methods, let’s try using a dictionary as our substitution mapping. from string import Templatemapping = dict(who='John', how=235765)formatted_str = Template('Hello $who, your current balance is $how dollars.')Returned_str = formatted_str.substitute(mapping) Assume our dictionary doesn’t have all the keys we need for the mapping, using the substitute method will give a keyError. Here's where safe_substitute comes to the help, if this method didn't find the correct key, it will return a string with the placeHolder for the wrong key. For example, this code: from string import Templatemapping = dict(who='John')formatted_str = Template('Hello $who, your current balance is $how dollars.')Returned_str = formatted_str.safe_substitute(mapping) Will return Hello John, your current balance is $how dollars. where if I had used the substitute method, I would've gotten an error. The complete code for this section: In this article, we covered five different ways you can use to format a string in Python: The modulo operator.The format function.f-strings.Manual formatting.Template strings. The modulo operator. The format function. f-strings. Manual formatting. Template strings. Each method has its usage advantages and disadvantages. A general rule of thumb, as put by Dan Badar, if the string you’re formatting is user-obtained, template strings are the way to go. If not, use f-strings if you’re on Python 3.7 or the format function elsewhere.
[ { "code": null, "e": 799, "s": 171, "text": "Strings are one of the most essential and used datatypes in programming. It allows the computer to interact and communicate with the world, such as printing instructions or reading input from the user. The ability to manipulate and formate strings give the programmer the power to process and handle text, for example, extract user input from websites forms, data from processed text, and use this data to perform activities such as sentimental analysis. Sentimental analysis is a subfield of natural language processing that allows the computer to classify emotions — negative, positive, or neutral — based on a piece of text." }, { "code": null, "e": 953, "s": 799, "text": "“All sentiment is right; because sentiment has a reference to nothing beyond itself, and is always real, wherever a man is conscious of it.” — David Hume" }, { "code": null, "e": 1351, "s": 953, "text": "Python is one of the main programming languages used to analyze and manipulate data next to R. Python is used in data analytics to help access databases and communicate with them. It is also useful in importing and exporting data using different web scraping techniques. Once this data is obtained, Python is used to clean and prepare data sets before they are fed to a machine-learning algorithm." }, { "code": null, "e": 1680, "s": 1351, "text": "There are five ways you can use Python to format strings: formatting strings using the modulo operator, formatting using Python’s built-in format function, formatting using Python 3.7 f-strings, formatting manually, and finally using template strings. We will cover each one of these methods as well as when to use each of them." }, { "code": null, "e": 1705, "s": 1680, "text": "Let’s get right to it..." }, { "code": null, "e": 2237, "s": 1705, "text": "If you wrote code using C or C++ before, this would look very familiar to you. In Python, we can use the modulo operator (%) to perform simple positional formatting. What I call placeHolder here, represents the control specs for formatting and converting the string. The % tells the interpreter that the following characters are the rules for converting the string. The conversion rules include information about the desired width of the result formatted string, the type of the result, and the precision of it — in case of floats." }, { "code": null, "e": 2415, "s": 2237, "text": "This type of string formatting is sometimes referred to as the “old style” formatting. The placeHolder can refer to values directly or can be specified using keywords arguments." }, { "code": null, "e": 2500, "s": 2415, "text": "formatted_str = 'Yesterday I bought %d %s for only %.2f$!' % (10, 2'bananas',2.6743)" }, { "code": null, "e": 2592, "s": 2500, "text": "If we try to print this string, we will get Yesterday I bought 10 bananas for only 2.67$! ." }, { "code": null, "e": 2883, "s": 2592, "text": "As you can see here, I had three placeHolders for three values, the first integer, the string — bananas — and the price of the bananas, which is a float. When referring to the float, I decided that a precision of two is all I needed; that’s why only 67 is displayed after the decimal point." }, { "code": null, "e": 3082, "s": 2883, "text": "In the previous example, we replaced the placeHolders with the values directly. There is another way we can achieve this mapping, which is through using keyword arguments or by passing a dictionary." }, { "code": null, "e": 3228, "s": 3082, "text": "name = 'John'balance = 235765formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {\"name\":name, \"balance\":balance}" }, { "code": null, "e": 3372, "s": 3228, "text": "Using this method, we need to use the {} instead of the (). Because of that, we can also use a dictionary directly to fill in the placeHolders." }, { "code": null, "e": 3514, "s": 3372, "text": "dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = 'I got %(quantity)d %(name)s for $%(price).2f$' % dictionary" }, { "code": null, "e": 3550, "s": 3514, "text": "The complete code for this section:" }, { "code": null, "e": 3864, "s": 3550, "text": "In Python 3, a new method to regulate the % operator syntax was introduced to the language. This is done using the built-in format method, also known as the “new style” formatting. Using the format method has many commonalities with using the % operator. Let’s consider rewriting some of the examples from before:" }, { "code": null, "e": 4010, "s": 3864, "text": "name = 'John'balance = 235765formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {\"name\":name, \"balance\":balance}" }, { "code": null, "e": 4023, "s": 4010, "text": "Will become:" }, { "code": null, "e": 4173, "s": 4023, "text": "name = 'John'balance = 235765formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format(\"name\":name, \"balance\":balance)" }, { "code": null, "e": 4262, "s": 4173, "text": "We can summarize the differences between the % operator syntax and the format method as:" }, { "code": null, "e": 4512, "s": 4262, "text": "Using the % operator, we use the () inside the string, while with format method we use {} .To define the type of the conversion in the % operator, we set it right after the %, while in the format function we set the conversion after : inside the {}." }, { "code": null, "e": 4604, "s": 4512, "text": "Using the % operator, we use the () inside the string, while with format method we use {} ." }, { "code": null, "e": 4763, "s": 4604, "text": "To define the type of the conversion in the % operator, we set it right after the %, while in the format function we set the conversion after : inside the {}." }, { "code": null, "e": 4982, "s": 4763, "text": "However, if we want to pass a dictionary to the format string, we will need to modify the reforestation slightly. Instead of passing the name of the dictionary, we need to pass a pointer to the dictionary, for example:" }, { "code": null, "e": 5131, "s": 4982, "text": "dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = 'I got {quantity:d} {name:s} for {price:.2f}$'.format(**dictionary)" }, { "code": null, "e": 5533, "s": 5131, "text": "Moreover, we can use the same conversion rules of the % operator that can be used in the format method as well. In Python 3 and up to 3.6, the format method is preferred to the % operator approach. The format method presented a powerful approach to format strings; it didn’t complicate the simple case — such as the examples above — but, at the same time providing new levels to how we format strings." }, { "code": null, "e": 5569, "s": 5533, "text": "The complete code for this section:" }, { "code": null, "e": 5842, "s": 5569, "text": "This, in my opinion, the fanciest and most elegant method to format strings. The f-string was presented in Python 3.8 as a more straightforward approach to string formating. Before we get into f-strings, let’s quickly cover the three types of strings in Python 3.8 and up." }, { "code": null, "e": 6366, "s": 5842, "text": "Normal/ standard strings: contained between “” or ‘’, example “Hello, world!”. These are the most commonly used string type.Raw strings: lead by r”, for example r’hello\\nworld’. In this type of strings, no processing is done on the string. Which means, escape characters don't work in these strings. Instead, they will be printed without any processing. This type of strings is mostly used in regular expressions.f-strings: lead by f”, for example, f’hello John!’. F-strings as used as an alternative way to format strings." }, { "code": null, "e": 6491, "s": 6366, "text": "Normal/ standard strings: contained between “” or ‘’, example “Hello, world!”. These are the most commonly used string type." }, { "code": null, "e": 6781, "s": 6491, "text": "Raw strings: lead by r”, for example r’hello\\nworld’. In this type of strings, no processing is done on the string. Which means, escape characters don't work in these strings. Instead, they will be printed without any processing. This type of strings is mostly used in regular expressions." }, { "code": null, "e": 6892, "s": 6781, "text": "f-strings: lead by f”, for example, f’hello John!’. F-strings as used as an alternative way to format strings." }, { "code": null, "e": 6915, "s": 6892, "text": "towardsdatascience.com" }, { "code": null, "e": 7069, "s": 6915, "text": "f-strings present a simple way to format strings by directly embedding expression into the string. Let’s revisit the examples from before, one more time." }, { "code": null, "e": 7219, "s": 7069, "text": "name = 'John'balance = 235765formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format(\"name\":name, \"balance\":balance)" }, { "code": null, "e": 7293, "s": 7219, "text": "If we want to rewrite this formatting using f-strings, it will look like:" }, { "code": null, "e": 7398, "s": 7293, "text": "name = 'John'balance = 235765formatted_str = f'Hello {name}, your current balance is {balance} dollars.'" }, { "code": null, "e": 7536, "s": 7398, "text": "One way f-string simplifies string formatting is, we can directly pass iterables — dictionaries, lists, etc. — to the string, as follows:" }, { "code": null, "e": 7783, "s": 7536, "text": "dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}formatted_str = f'I got dictionary[quantity] dictionary[name] for dictionary[price]$'#f-string with listsmyList = [1,2,3,4]formatted_str = f'The last item of the list is myList[-1]'" }, { "code": null, "e": 7871, "s": 7783, "text": "You can also perform simple arithmetic or logic operations within an f-string directly." }, { "code": null, "e": 8041, "s": 7871, "text": "#ArithmeticmyList = [1,2,3,4]formatted_str = f'The sum of the last and first items of the list is myList[0] + myList[-1]'#Logicformatted_str = f'myList[0] == myList[-1]'" }, { "code": null, "e": 8317, "s": 8041, "text": "f-strings provide much more freedom to the options we can use inside the string we want to format, such as list indexing, calling list or dictionary methods, or general iterables functions — e.g., len, sum, min, and max. We can also use conditional statements in an f-string:" }, { "code": null, "e": 8388, "s": 8317, "text": "age = 21formatted_str = f'You {\"can't\" if age < 21 else \"can\"} drink!'" }, { "code": null, "e": 8424, "s": 8388, "text": "The complete code for this section:" }, { "code": null, "e": 9030, "s": 8424, "text": "Manual formatting refers to using standard string methods to format strings. Mostly, we use the rjust, ljust, and center to justify the strings. The rjust method right-justifies a string given a specific width by padding it with spaces on the left. The ljust adds padding to the right and the center method adds padding on both sides of the string. These methods do not modify the original string; they instead return a new modified string. There is another string method that can be used to format strings, which is the zfill method. This method pads a string with a numeric value with zeros on the left." }, { "code": null, "e": 9348, "s": 9030, "text": "Template strings are an alternative to the % operator, but instead of the %, template strings use the $ sign. Both methods provide what we refer to as substitution formatting. Template strings are not built-in in Python, hence to use them, we need to first import the string module. Template strings have three rules:" }, { "code": null, "e": 9664, "s": 9348, "text": "$$ is an escape character.Whatever follows the $ sign directly is the placeHolder for the template. By default, these placeHolders are restricted to any case-insensitive alphanumeric string. The first non-placeHolder character after the $ sign terminates this placeHolder specs, for example, a whitespace character." }, { "code": null, "e": 9691, "s": 9664, "text": "$$ is an escape character." }, { "code": null, "e": 9981, "s": 9691, "text": "Whatever follows the $ sign directly is the placeHolder for the template. By default, these placeHolders are restricted to any case-insensitive alphanumeric string. The first non-placeHolder character after the $ sign terminates this placeHolder specs, for example, a whitespace character." }, { "code": null, "e": 10124, "s": 9981, "text": "These rules ad more are already defined in the string module, so once imported, you can go ahead and use them without the need to define them." }, { "code": null, "e": 10453, "s": 10124, "text": "The template string has two main methods: the substitute method and the safe_substitute method. Both methods take the same argument, which is the substitute mapping. Moreover, both methods return a new formatted string, you can think of the template object as the blueprint for how future strings will be formatted. For example:" }, { "code": null, "e": 10606, "s": 10453, "text": "from string import Templateformatted_str = Template('Hello $who, your current balance is $how dollars.')formatted_str.substitute(who='John', how=235765)" }, { "code": null, "e": 10742, "s": 10606, "text": "To see the difference between the substitute and the safe_substitute methods, let’s try using a dictionary as our substitution mapping." }, { "code": null, "e": 10933, "s": 10742, "text": "from string import Templatemapping = dict(who='John', how=235765)formatted_str = Template('Hello $who, your current balance is $how dollars.')Returned_str = formatted_str.substitute(mapping)" }, { "code": null, "e": 11236, "s": 10933, "text": "Assume our dictionary doesn’t have all the keys we need for the mapping, using the substitute method will give a keyError. Here's where safe_substitute comes to the help, if this method didn't find the correct key, it will return a string with the placeHolder for the wrong key. For example, this code:" }, { "code": null, "e": 11420, "s": 11236, "text": "from string import Templatemapping = dict(who='John')formatted_str = Template('Hello $who, your current balance is $how dollars.')Returned_str = formatted_str.safe_substitute(mapping)" }, { "code": null, "e": 11553, "s": 11420, "text": "Will return Hello John, your current balance is $how dollars. where if I had used the substitute method, I would've gotten an error." }, { "code": null, "e": 11589, "s": 11553, "text": "The complete code for this section:" }, { "code": null, "e": 11679, "s": 11589, "text": "In this article, we covered five different ways you can use to format a string in Python:" }, { "code": null, "e": 11765, "s": 11679, "text": "The modulo operator.The format function.f-strings.Manual formatting.Template strings." }, { "code": null, "e": 11786, "s": 11765, "text": "The modulo operator." }, { "code": null, "e": 11807, "s": 11786, "text": "The format function." }, { "code": null, "e": 11818, "s": 11807, "text": "f-strings." }, { "code": null, "e": 11837, "s": 11818, "text": "Manual formatting." }, { "code": null, "e": 11855, "s": 11837, "text": "Template strings." } ]
How to create directory programmatically in Android?
This example demonstrates how to create directory programmatically in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import java.io.File; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.view.Menu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); File file = new File(Environment.getExternalStorageDirectory()+"/Sample Directory"); boolean success = true; if(!file.exists()) { Toast.makeText(getApplicationContext(),"Directory does not exist, create it", Toast.LENGTH_LONG).show(); } if(success) { Toast.makeText(getApplication(),"Directory created", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this,"Failed to create Directory", Toast.LENGTH_LONG).show(); } } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1140, "s": 1062, "text": "This example demonstrates how to create directory programmatically in Android" }, { "code": null, "e": 1269, "s": 1140, "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": 1334, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2072, "s": 1334, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n 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=\"match_parent\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2129, "s": 2072, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3129, "s": 2129, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport java.io.File;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.app.Activity;\nimport android.view.Menu;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n File file = new File(Environment.getExternalStorageDirectory()+\"/Sample Directory\");\n boolean success = true;\n if(!file.exists()) {\n Toast.makeText(getApplicationContext(),\"Directory does not exist, create it\",\n Toast.LENGTH_LONG).show();\n }\n if(success) {\n Toast.makeText(getApplication(),\"Directory created\",\n Toast.LENGTH_LONG).show();\n }\n else {\n Toast.makeText(this,\"Failed to create Directory\",\n Toast.LENGTH_LONG).show();\n }\n }\n}" }, { "code": null, "e": 3194, "s": 3129, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3947, "s": 3194, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.app.sample\">\n <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4301, "s": 3947, "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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Bubble Sort algorithm using JavaScript - GeeksforGeeks
22 Jan, 2021 Bubble sort algorithm is an algorithm that sorts the array by comparing two adjacent elements and swaps them if they are not in the intended order. Here order can be anything like increasing order or decreasing order. We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ] the task is to sort the array using bubble sort. Bubble sort compares the element from index 0 and if the 0th index is less than 1st index then the values get swapped and if the 0th index is less than the 1st index then nothing happens. then, the 1st index compares to the 2nd index then the 2nd index compares to the 3rd, and so on... let’s see it with an example, each step is briefly illustrated here Comparisons happen till the last element of the array After each iteration, the greatest value of the array becomes the last index of the array. in each iteration, the comparison happens till the last unsorted element. Now comparison reduced one step because the biggest element is at its right place After all the iteration and comparisons of elements, we get a sorted array. BubbleSort(array){ for i -> 0 to arrayLength for j -> 0 to (arrayLength - i - 1) if arr[j] > arr[j + 1] swap(arr[j], arr[j + 1]) } Javascript // Bubble sort Implementation using Javascript // Creating the bblSort function function bblSort(arr){ for(var i = 0; i < arr.length; i++){ // Last i elements are already in place for(var j = 0; j < ( arr.length - i -1 ); j++){ // Checking if the item at present iteration // is greater than the next iteration if(arr[j] > arr[j+1]){ // If the condition is true then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j+1] = temp } } } // Print the sorted array console.log(arr);} // This is our unsorted arrayvar arr = [234, 43, 55, 63, 5, 6, 235, 547]; // Now pass this array to the bblSort() functionbblSort(arr); Output Sorted array : [5, 6, 43, 55, 63, 234, 235, 547] Note: This implementation is not optimized. We will see the optimized solution next. As we discussed the implementation of bubble sort earlier that is not optimized. Even If the array is sorted, the code will run with O(n^2) complexity. Let’s see how to implement an optimized bubble sort algorithm in javascript. BubbleSort(array){ for i -> 0 to arrayLength isSwapped <- false for j -> 0 to (arrayLength - i - 1) if arr[j] > arr[j + 1] swap(arr[j], arr[j + 1]) isSwapped -> true } Javascript // Optimized implementation of bubble sort Algorithm function bubbleSort(arr){ var i, j; var len = arr.length; var isSwapped = false; for(i =0; i < len; i++){ isSwapped = false; for(j = 0; j < len; j++){ if(arr[j] > arr[j + 1]){ var temp = arr[j] arr[j] = arr[j+1]; arr[j+1] = temp; isSwapped = true; } } // IF no two elements were swapped by inner loop, then break if(!isSwapped){ break; } } // Print the array console.log(arr)} var arr = [243, 45, 23, 356, 3, 5346, 35, 5]; // calling the bubbleSort FunctionbubbleSort(arr) Output Sorted Array : [3, 5, 23, 35, 45, 243, 356, 5346] If the array is in reverse order then this condition is the worst case and Its time complexity is O(n2). If the array is already sorted then it is the best-case scenario and its time complexity is O(n) Auxiliary Space: O(1) BubbleSort JavaScript-Misc Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advantages and Disadvantages of OOP Consensus Algorithms in Blockchain Challenges in Internet of things (IoT) Lex Program to count number of words Spatial Filtering and its Types Characteristics of Internet of Things Election algorithm and distributed processing Transmission Impairment in Data Communication Communication Models in IoT (Internet of Things ) Introduction to Internet of Things (IoT) | Set 1
[ { "code": null, "e": 24673, "s": 24645, "text": "\n22 Jan, 2021" }, { "code": null, "e": 24891, "s": 24673, "text": "Bubble sort algorithm is an algorithm that sorts the array by comparing two adjacent elements and swaps them if they are not in the intended order. Here order can be anything like increasing order or decreasing order." }, { "code": null, "e": 24995, "s": 24891, "text": "We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ] the task is to sort the array using bubble sort. " }, { "code": null, "e": 25183, "s": 24995, "text": "Bubble sort compares the element from index 0 and if the 0th index is less than 1st index then the values get swapped and if the 0th index is less than the 1st index then nothing happens." }, { "code": null, "e": 25282, "s": 25183, "text": "then, the 1st index compares to the 2nd index then the 2nd index compares to the 3rd, and so on..." }, { "code": null, "e": 25350, "s": 25282, "text": "let’s see it with an example, each step is briefly illustrated here" }, { "code": null, "e": 25404, "s": 25350, "text": "Comparisons happen till the last element of the array" }, { "code": null, "e": 25569, "s": 25404, "text": "After each iteration, the greatest value of the array becomes the last index of the array. in each iteration, the comparison happens till the last unsorted element." }, { "code": null, "e": 25651, "s": 25569, "text": "Now comparison reduced one step because the biggest element is at its right place" }, { "code": null, "e": 25727, "s": 25651, "text": "After all the iteration and comparisons of elements, we get a sorted array." }, { "code": null, "e": 25880, "s": 25727, "text": "BubbleSort(array){\n for i -> 0 to arrayLength \n for j -> 0 to (arrayLength - i - 1)\n if arr[j] > arr[j + 1]\n swap(arr[j], arr[j + 1])\n}" }, { "code": null, "e": 25891, "s": 25880, "text": "Javascript" }, { "code": "// Bubble sort Implementation using Javascript // Creating the bblSort function function bblSort(arr){ for(var i = 0; i < arr.length; i++){ // Last i elements are already in place for(var j = 0; j < ( arr.length - i -1 ); j++){ // Checking if the item at present iteration // is greater than the next iteration if(arr[j] > arr[j+1]){ // If the condition is true then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j+1] = temp } } } // Print the sorted array console.log(arr);} // This is our unsorted arrayvar arr = [234, 43, 55, 63, 5, 6, 235, 547]; // Now pass this array to the bblSort() functionbblSort(arr);", "e": 26594, "s": 25891, "text": null }, { "code": null, "e": 26651, "s": 26594, "text": "Output \nSorted array :\n[5, 6, 43, 55, 63, 234, 235, 547]" }, { "code": null, "e": 26736, "s": 26651, "text": "Note: This implementation is not optimized. We will see the optimized solution next." }, { "code": null, "e": 26965, "s": 26736, "text": "As we discussed the implementation of bubble sort earlier that is not optimized. Even If the array is sorted, the code will run with O(n^2) complexity. Let’s see how to implement an optimized bubble sort algorithm in javascript." }, { "code": null, "e": 27168, "s": 26965, "text": "BubbleSort(array){\n for i -> 0 to arrayLength \n isSwapped <- false\n for j -> 0 to (arrayLength - i - 1)\n if arr[j] > arr[j + 1]\n swap(arr[j], arr[j + 1])\n isSwapped -> true\n}" }, { "code": null, "e": 27179, "s": 27168, "text": "Javascript" }, { "code": "// Optimized implementation of bubble sort Algorithm function bubbleSort(arr){ var i, j; var len = arr.length; var isSwapped = false; for(i =0; i < len; i++){ isSwapped = false; for(j = 0; j < len; j++){ if(arr[j] > arr[j + 1]){ var temp = arr[j] arr[j] = arr[j+1]; arr[j+1] = temp; isSwapped = true; } } // IF no two elements were swapped by inner loop, then break if(!isSwapped){ break; } } // Print the array console.log(arr)} var arr = [243, 45, 23, 356, 3, 5346, 35, 5]; // calling the bubbleSort FunctionbubbleSort(arr)", "e": 27831, "s": 27179, "text": null }, { "code": null, "e": 27888, "s": 27831, "text": "Output\nSorted Array :\n[3, 5, 23, 35, 45, 243, 356, 5346]" }, { "code": null, "e": 27993, "s": 27888, "text": "If the array is in reverse order then this condition is the worst case and Its time complexity is O(n2)." }, { "code": null, "e": 28090, "s": 27993, "text": "If the array is already sorted then it is the best-case scenario and its time complexity is O(n)" }, { "code": null, "e": 28112, "s": 28090, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 28123, "s": 28112, "text": "BubbleSort" }, { "code": null, "e": 28139, "s": 28123, "text": "JavaScript-Misc" }, { "code": null, "e": 28144, "s": 28139, "text": "Misc" }, { "code": null, "e": 28149, "s": 28144, "text": "Misc" }, { "code": null, "e": 28154, "s": 28149, "text": "Misc" }, { "code": null, "e": 28252, "s": 28154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28288, "s": 28252, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 28323, "s": 28288, "text": "Consensus Algorithms in Blockchain" }, { "code": null, "e": 28362, "s": 28323, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 28399, "s": 28362, "text": "Lex Program to count number of words" }, { "code": null, "e": 28431, "s": 28399, "text": "Spatial Filtering and its Types" }, { "code": null, "e": 28469, "s": 28431, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 28515, "s": 28469, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 28561, "s": 28515, "text": "Transmission Impairment in Data Communication" }, { "code": null, "e": 28611, "s": 28561, "text": "Communication Models in IoT (Internet of Things )" } ]
What is unsafe/unmanaged code in C#?
Applications that are not under the control of the CLR are unmanaged. The unsafe code or the unmanaged code is a code block that uses a pointer variable and allows pointer usage in unmanaged code. The following is the code − static unsafe void Main(string[] args) { int x = 100; int* a = &x; Console.WriteLine("Data : {0} ", x); Console.WriteLine("Address : {0}", (int)a); Console.ReadKey(); }
[ { "code": null, "e": 1259, "s": 1062, "text": "Applications that are not under the control of the CLR are unmanaged. The unsafe code or the unmanaged code is a code block that uses a pointer variable and allows pointer usage in unmanaged code." }, { "code": null, "e": 1287, "s": 1259, "text": "The following is the code −" }, { "code": null, "e": 1472, "s": 1287, "text": "static unsafe void Main(string[] args) {\n int x = 100;\n int* a = &x;\n\n Console.WriteLine(\"Data : {0} \", x);\n Console.WriteLine(\"Address : {0}\", (int)a);\n Console.ReadKey();\n}" } ]
Tryit Editor v3.7
Tryit: The class selector only for specific element
[]
How to save figures to pdf as raster images in Matplotlib?
To save figures to pdf as raster images in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create a new figure or activate an existing figure. Add an axes to the figure as part of a subplot arrangement. Create random data using numpy. Display the data as an image, i.e., on a 2D regular raster. Save the plot as pdf format. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111, rasterized=True) data = np.random.rand(5, 5) ax.imshow(data, cmap="copper", aspect=True, interpolation="nearest") plt.savefig("rasterized.pdf") When we execute the code, it will save the following plot in the project directory with the name "rasterized.pdf".
[ { "code": null, "e": 1151, "s": 1062, "text": "To save figures to pdf as raster images in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1227, "s": 1151, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1279, "s": 1227, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1339, "s": 1279, "text": "Add an axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1371, "s": 1339, "text": "Create random data using numpy." }, { "code": null, "e": 1431, "s": 1371, "text": "Display the data as an image, i.e., on a 2D regular raster." }, { "code": null, "e": 1460, "s": 1431, "text": "Save the plot as pdf format." }, { "code": null, "e": 1791, "s": 1460, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\nax = fig.add_subplot(111, rasterized=True)\ndata = np.random.rand(5, 5)\n\nax.imshow(data, cmap=\"copper\", aspect=True, interpolation=\"nearest\")\n\nplt.savefig(\"rasterized.pdf\")" }, { "code": null, "e": 1906, "s": 1791, "text": "When we execute the code, it will save the following plot in the project directory with the name \"rasterized.pdf\"." } ]
How to resize an image using Tkinter?
To process images with Tkinter and other Python packages, we generally use the Pillow Package (or PIL) in Python. It provides a way to load, process, manipulate, convert, and helps to resize the images. The package can be installed by using the command pip install Pillow. Once the package is installed, we can import it using the ‘from PIL import Image, ImageTk’ command. To resize an image using the PIL package, we have to follow these steps − Install Pillow Package or PIL in the local machine. Install Pillow Package or PIL in the local machine. Open the Image using Open(image_location) method. Open the Image using Open(image_location) method. Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it. Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it. Display the Image using Canvas create_image(x,y, image) method. Display the Image using Canvas create_image(x,y, image) method. #Import the required Libraries from tkinter import * from PIL import Image,ImageTk #Create an instance of tkinter frame win = Tk() #Set the geometry of tkinter frame win.geometry("750x270") #Create a canvas canvas= Canvas(win, width= 600, height= 400) canvas.pack() #Load an image in the script img= (Image.open("download.png")) #Resize the Image using resize method resized_image= img.resize((300,205), Image.ANTIALIAS) new_image= ImageTk.PhotoImage(resized_image) #Add image to the Canvas Items canvas.create_image(10,10, anchor=NW, image=new_image) win.mainloop() Running the above code will display a window that will display a resized image in the Canvas.
[ { "code": null, "e": 1435, "s": 1062, "text": "To process images with Tkinter and other Python packages, we generally use the Pillow Package (or PIL) in Python. It provides a way to load, process, manipulate, convert, and helps to resize the images. The package can be installed by using the command pip install Pillow. Once the package is installed, we can import it using the ‘from PIL import Image, ImageTk’ command." }, { "code": null, "e": 1509, "s": 1435, "text": "To resize an image using the PIL package, we have to follow these steps −" }, { "code": null, "e": 1561, "s": 1509, "text": "Install Pillow Package or PIL in the local machine." }, { "code": null, "e": 1613, "s": 1561, "text": "Install Pillow Package or PIL in the local machine." }, { "code": null, "e": 1663, "s": 1613, "text": "Open the Image using Open(image_location) method." }, { "code": null, "e": 1713, "s": 1663, "text": "Open the Image using Open(image_location) method." }, { "code": null, "e": 1854, "s": 1713, "text": "Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it." }, { "code": null, "e": 1995, "s": 1854, "text": "Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it." }, { "code": null, "e": 2059, "s": 1995, "text": "Display the Image using Canvas create_image(x,y, image) method." }, { "code": null, "e": 2123, "s": 2059, "text": "Display the Image using Canvas create_image(x,y, image) method." }, { "code": null, "e": 2697, "s": 2123, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom PIL import Image,ImageTk\n\n#Create an instance of tkinter frame\nwin = Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x270\")\n\n#Create a canvas\ncanvas= Canvas(win, width= 600, height= 400)\ncanvas.pack()\n\n#Load an image in the script\nimg= (Image.open(\"download.png\"))\n\n#Resize the Image using resize method\nresized_image= img.resize((300,205), Image.ANTIALIAS)\nnew_image= ImageTk.PhotoImage(resized_image)\n\n#Add image to the Canvas Items\ncanvas.create_image(10,10, anchor=NW, image=new_image)\n\nwin.mainloop()" }, { "code": null, "e": 2791, "s": 2697, "text": "Running the above code will display a window that will display a resized image in the Canvas." } ]
Searching in an array where adjacent differ by at most k | Practice | GeeksforGeeks
A step array is an array of integer where each element has a difference of at most k with its neighbor. Given a key x, we need to find the index value of x if multiple elements exist, return the first occurrence of the key. Example 1: ​Input : arr[ ] = {4, 5, 6, 7, 6}, K = 1 and X = 6 Output : 2 Explanation: In an array arr 6 is present at index 2. So, return 2. ​Example 2: Input : arr[ ] = {20 40 50}, K = 20 and X = 70 Output : -1 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function search() that takes an array (arr), sizeOfArray (n), an integer value X, another integer value K, and return an integer displaying the index of the element X in the array arr. If the element is not present in the array return -1. The driver code takes care of the printing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 105 1 ≤ K ≤ 102 1 ≤ arr[i], X ≤ 105 0 amritkumar79791 week ago int search(int arr[], int n, int x, int k){ for(int i=0; i<n; i++) { if(arr[i]==x) { return i; } } return -1;} 0 vishalsavade2 weeks ago //IDK what this question wanted to convey but it is working //for simple search int search(int arr[], int n, int x, int k) { // Complete the function for(int i = 0; i < n; i++){ if(arr[i] == x) return i; } return -1; } 0 itsmemritu This comment was deleted. -3 ravisharmaaaa4 weeks ago //code for(int i=0;i<n;i++) { if(arr[i]==x) { return i; break; } } return -1; -1 omuksa0072 months ago What is the meaning of K here 😒 0 chiragagrawal7652 months ago why is binary search not working over here? please answer some1 -4 2019sushilkumarkori2 months ago int search(int arr[], int n, int x, int k) { // Complete the function for(int i=0;i<n;i++){ if(arr[i] == x){ return i; } } return -1; } +1 sagar9760dharvan2 months ago #Java int search(int a[], int n, int x, int k){ int nextse=0; while(nextse<n) { if(a[nextse]==x) { return nextse; } int low=a[nextse]-k; int high=a[nextse]+k; if(x>=low && x<=high) nextse++; else nextse+=2; } return -1;} 0 anushkay00921 This comment was deleted. 0 allenvrghs20073 months ago c++ solution vector <int> v (arr, arr +n); auto it = find(v.begin(), v.end(), x); // If element was found if (it != v.end()) { // calculating the index // of K int index = it - v.begin(); // cout << index << endl; return index; } else { // If the element is not // present in the vector // cout << "-1" << endl; return -1; 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": 463, "s": 238, "text": "A step array is an array of integer where each element has a difference of at most k with its neighbor. Given a key x, we need to find the index value of x if multiple elements exist, return the first occurrence of the key. " }, { "code": null, "e": 475, "s": 463, "text": "\nExample 1:" }, { "code": null, "e": 618, "s": 475, "text": "​Input : arr[ ] = {4, 5, 6, 7, 6}, K = 1 \n and X = 6\nOutput : 2\nExplanation:\nIn an array arr 6 is present at index 2.\nSo, return 2.\n" }, { "code": null, "e": 634, "s": 618, "text": "\n​Example 2:" }, { "code": null, "e": 704, "s": 634, "text": "Input : arr[ ] = {20 40 50}, K = 20 \n and X = 70\nOutput : -1 " }, { "code": null, "e": 1113, "s": 706, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function search() that takes an array (arr), sizeOfArray (n), an integer value X, another integer value K, and return an integer displaying the index of the element X in the array arr. If the element is not present in the array return -1. The driver code takes care of the printing." }, { "code": null, "e": 1177, "s": 1113, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1236, "s": 1179, "text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ K ≤ 102\n1 ≤ arr[i], X ≤ 105" }, { "code": null, "e": 1238, "s": 1236, "text": "0" }, { "code": null, "e": 1263, "s": 1238, "text": "amritkumar79791 week ago" }, { "code": null, "e": 1414, "s": 1263, "text": "int search(int arr[], int n, int x, int k){ for(int i=0; i<n; i++) { if(arr[i]==x) { return i; } } return -1;} " }, { "code": null, "e": 1416, "s": 1414, "text": "0" }, { "code": null, "e": 1440, "s": 1416, "text": "vishalsavade2 weeks ago" }, { "code": null, "e": 1701, "s": 1440, "text": "//IDK what this question wanted to convey but it is working\n//for simple search \nint search(int arr[], int n, int x, int k)\n{\n // Complete the function\n for(int i = 0; i < n; i++){\n if(arr[i] == x)\n return i;\n }\n \n return -1;\n}" }, { "code": null, "e": 1703, "s": 1701, "text": "0" }, { "code": null, "e": 1714, "s": 1703, "text": "itsmemritu" }, { "code": null, "e": 1740, "s": 1714, "text": "This comment was deleted." }, { "code": null, "e": 1743, "s": 1740, "text": "-3" }, { "code": null, "e": 1768, "s": 1743, "text": "ravisharmaaaa4 weeks ago" }, { "code": null, "e": 1776, "s": 1768, "text": "//code " }, { "code": null, "e": 1891, "s": 1776, "text": "for(int i=0;i<n;i++) { if(arr[i]==x) { return i; break; } } return -1;" }, { "code": null, "e": 1894, "s": 1891, "text": "-1" }, { "code": null, "e": 1916, "s": 1894, "text": "omuksa0072 months ago" }, { "code": null, "e": 1948, "s": 1916, "text": "What is the meaning of K here 😒" }, { "code": null, "e": 1950, "s": 1948, "text": "0" }, { "code": null, "e": 1979, "s": 1950, "text": "chiragagrawal7652 months ago" }, { "code": null, "e": 2023, "s": 1979, "text": "why is binary search not working over here?" }, { "code": null, "e": 2043, "s": 2023, "text": "please answer some1" }, { "code": null, "e": 2046, "s": 2043, "text": "-4" }, { "code": null, "e": 2078, "s": 2046, "text": "2019sushilkumarkori2 months ago" }, { "code": null, "e": 2263, "s": 2078, "text": "int search(int arr[], int n, int x, int k)\n{\n // Complete the function\n for(int i=0;i<n;i++){\n if(arr[i] == x){\n return i;\n }\n }\n return -1;\n} \t" }, { "code": null, "e": 2266, "s": 2263, "text": "+1" }, { "code": null, "e": 2295, "s": 2266, "text": "sagar9760dharvan2 months ago" }, { "code": null, "e": 2301, "s": 2295, "text": "#Java" }, { "code": null, "e": 2607, "s": 2303, "text": "int search(int a[], int n, int x, int k){ int nextse=0; while(nextse<n) { if(a[nextse]==x) { return nextse; } int low=a[nextse]-k; int high=a[nextse]+k; if(x>=low && x<=high) nextse++; else nextse+=2; } return -1;} " }, { "code": null, "e": 2609, "s": 2607, "text": "0" }, { "code": null, "e": 2623, "s": 2609, "text": "anushkay00921" }, { "code": null, "e": 2649, "s": 2623, "text": "This comment was deleted." }, { "code": null, "e": 2651, "s": 2649, "text": "0" }, { "code": null, "e": 2678, "s": 2651, "text": "allenvrghs20073 months ago" }, { "code": null, "e": 2691, "s": 2678, "text": "c++ solution" }, { "code": null, "e": 3078, "s": 2693, "text": " vector <int> v (arr, arr +n); auto it = find(v.begin(), v.end(), x); // If element was found if (it != v.end()) { // calculating the index // of K int index = it - v.begin(); // cout << index << endl; return index; } else { // If the element is not // present in the vector // cout << \"-1\" << endl; return -1;" }, { "code": null, "e": 3224, "s": 3078, "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": 3260, "s": 3224, "text": " Login to access your submissions. " }, { "code": null, "e": 3270, "s": 3260, "text": "\nProblem\n" }, { "code": null, "e": 3280, "s": 3270, "text": "\nContest\n" }, { "code": null, "e": 3343, "s": 3280, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3491, "s": 3343, "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": 3699, "s": 3491, "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": 3805, "s": 3699, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python Lambda
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. The expression is executed and the result is returned: Add 10 to argument a, and return the result: Lambda functions can take any number of arguments: Multiply argument a with argument b and return the result: Summarize argument a, b, and c and return the result: The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number: Use that function definition to make a function that always doubles the number you send in: Or, use the same function definition to make a function that always triples the number you send in: Or, use the same function definition to make both functions, in the same program: Use lambda functions when an anonymous function is required for a short period of time. Create a lambda function that takes one parameter (a) and returns it. x = Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 49, "s": 0, "text": "A lambda function is a small anonymous function." }, { "code": null, "e": 135, "s": 49, "text": "A lambda function can take any number of arguments, but can only have one expression." }, { "code": null, "e": 190, "s": 135, "text": "The expression is executed and the result is returned:" }, { "code": null, "e": 238, "s": 190, "text": "Add 10 to argument a, and \n return the result:" }, { "code": null, "e": 289, "s": 238, "text": "Lambda functions can take any number of arguments:" }, { "code": null, "e": 354, "s": 289, "text": "Multiply argument a with argument \n b and return the \n result:" }, { "code": null, "e": 417, "s": 354, "text": "Summarize argument a, \n b, and c and \n return the \n result:" }, { "code": null, "e": 522, "s": 417, "text": "The power of lambda is better shown when you use them as an anonymous \nfunction inside another function." }, { "code": null, "e": 644, "s": 522, "text": "Say you have a function definition that takes one argument, and that argument \nwill be multiplied with an unknown number:" }, { "code": null, "e": 737, "s": 644, "text": "Use that function definition to make a function that always doubles the \nnumber you send in:" }, { "code": null, "e": 838, "s": 737, "text": "Or, use the same function definition to make a function that always triples the \nnumber you send in:" }, { "code": null, "e": 921, "s": 838, "text": "Or, use the same function definition to make both functions, in the same \nprogram:" }, { "code": null, "e": 1009, "s": 921, "text": "Use lambda functions when an anonymous function is required for a short period of time." }, { "code": null, "e": 1079, "s": 1009, "text": "Create a lambda function that takes one parameter (a) and returns it." }, { "code": null, "e": 1088, "s": 1079, "text": "x = \n" }, { "code": null, "e": 1107, "s": 1088, "text": "Start the Exercise" }, { "code": null, "e": 1140, "s": 1107, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1182, "s": 1140, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1289, "s": 1182, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1308, "s": 1289, "text": "help@w3schools.com" } ]
Running Timeseries Anomaly Detection at Scale on SQL Data | by Sachin Bansal | Towards Data Science
Time is probably the most important dimension for metrics. In the business world, business executives, analysts, and product managers track metrics over time. In the startup world, VCs want metrics to grow 5% week-on-week. In public stock markets, long-term investors evaluate metrics on a quarter-on-quarter basis to make buy/sell decisions. Short-term traders monitor stock prices at a much smaller time granularity — minutes or hours — to make the same decisions. In the system monitoring world, teams track metrics on a second or a minute basis. In the data science world, time series analysis is an important component of work. Even though time may be the most important dimension in the data, data does have many other dimensions. These dimensions have varying cardinality. Some high cardinality dimensions can have thousands of unique dimension values. It’s almost impossible to manually monitor metrics across thousands of these dimension values and their combinations. This is where timeseries analysis, particularly timeseries anomaly detection comes in handy. Most business data is in SQL databases Most business data is in SQL databases Timeseries analysis needs timeseries data as an input. But most business data is tabular and sits in relational data warehouses and databases. Analysts typically use SQL to query these databases. How can we use SQL to generate timeseries data? 2. How to split metrics by dimensions? Some dimensions can have thousands of unique dimension values. Running anomaly detection for all dimensions values will be expensive and noisy. How can we select significant dimension values only for our analysis? 3. Anomaly Detection at Scale is Expensive Say you work for an online retailer. Your store sells 1000 products. You want to run anomaly detection on daily orders for each of these 1000 products. This means the following: Number of Metrics = 1 (Orders)Number of Dimension Values = 1000 (1000 products)Number of Metric Combinations = 1000 (1 metric * 1000 dimension values) This means the anomaly detection process must run 1000 times every day, once for each metric combination. Let’s say you want to monitor Orders by another dimension — State (50 unique values). You also want to monitor the metric by the combinations of these two dimensions. This means the anomaly detection process must now run 51,050 times every day. 51,050 = (1 metric * 1000 products) + (1 metric * 50 states) + (1 metric * 1000 products * 50 states) To get a sense of infrastructure pricing, let’s look at the pricing of the AWS anomaly detection service. AWS will charge you $638 per month to track 51K metric combinations on a daily basis. This is what you will pay for just running the anomaly detection process. Before each run of the process, you need to run a query to pull data from your datawarehouse. 51K metric combinations mean 51K queries on your datawarehouse daily, which is an additional cost. And this is just the cloud infrastructure cost. 4. Anomaly Detection at Scale is Noisy Each of these 51K metric combinations has the potential to be an anomaly. Even if 0.1% of these combinations turn out to be anomalies, you are looking at 51 anomalies on a daily basis, for a single metric. Will you or your team have the bandwidth to take action on so many anomalies every single day? Probably no. If you don’t act on these anomalies, these anomalies don’t add any business value. Instead, they just add to your cost. 5. When an anomaly is detected, how to dig deeper and do root cause analysis? Say you have the following anomaly: Orders for State = CA decreased by 15% yesterday This might raise questions like: Did the Orders decrease for all cities in the state? If not, which cities? Did the Orders decrease for all products or a specific few? How can we answer these questions quickly? Faced with these challenges, we started building CueObserve. Below is how we are solving these. Datasets are similar to aggregated SQL VIEWS of data. We write a SQL GROUP BY query with aggregate functions to roll-up data, map its columns as dimensions and metrics, and save it as a virtual Dataset. Below is a sample GROUP BY query for BigQuery: We can now define one or more anomaly detection jobs on the dataset. The anomaly detection job can monitor a metric at an aggregate level or split the metric by a dimension. When we split a metric by a dimension, we limit the number of unique dimension values. We use one of 3 ways to limit: Top N: limit based on the dimension value’s contribution to the metric.Min % Contribution: limit based on the dimension value’s contribution to the metric.Minimum Average Value: limit based on the metric’s average value. Top N: limit based on the dimension value’s contribution to the metric. Min % Contribution: limit based on the dimension value’s contribution to the metric. Minimum Average Value: limit based on the metric’s average value. As the first step in the anomaly detection process, we execute the dataset’s SQL query and fetch the result as a Pandas dataframe. This dataframe acts as the source data for identifying dimension values and the anomaly detection process. Next, we create new dataframes on which the actual anomaly detection process will run. During this process, we find dimension values and create sub-dataframes by filtering on the dimension. The dimension values for which sub dataframes need to be created are determined by one of the 3 dimension split rules mentioned above. For example, if the dimension split rule is Top N, an internal method determines the Top N dimension values and returns a list of dicts, each containing the dimension value string, its percentage contribution, and the sub dataframe. The sub dataframes mentioned are just dataframes after filtering for specific dimension values and removing all other columns except the timestamp column and metric column. datasetDf[datasetDf[dimensionCol] == dimVal][[timestampCol, metricCol]] One important step in the preparation of sub dataframes is the aggregation on timestamp which you can see in the previous code snippet. "df": aggregateDf(tempDf, timestampCol) This aggregation involves grouping the filtered sub dataframe over the timestamp column and summing it over the metric column. We also rename the timestamp column as “ds” and the metric column as “y”, as Prophet requires the dataframe columns to be named as such. We now feed the timeseries dataframe into Prophet. Each dataframe is separately trained on Prophet and a forecast is generated. Each dataframe must have at least 20 data points after aggregation as anything less than that would be too little training data for reasonably good results. There are some other considerations that are taken with respect to the granularity of the dataframe, like the number of predictions Prophet makes and also the training data interval. For hourly granularity, we only train Prophet on the last 7 days of data. We initialize Prophet with predetermined parameters and interval width for reasonably broad confidence intervals. Later, we plan on making these settings configurable as well. After getting the confidence intervals and predicted values for the future, we clip all predicted values to be greater than zero and remove all extra columns from Prophet’s output. Next, we combine the actual data with the forecasted data from Prophet, along with the uncertainty interval bands. These bands estimate the trend of the data and will be used as the threshold for determining a data point as an anomaly. For each data point in the original dataframe, we check if it lies within the predicted bands or not and classify it as an anomaly accordingly. Finally, we store all the individual results of the process along with the metadata in a format for easy visual representation. Below is a sample anomaly visualization. To run anomaly detection on multi-dimensional business data, we write a SQL GROUP BY query, map its columns as dimensions and measures, and save it as a virtual dataset. We then define one or more anomaly detection jobs on the dataset. We limit the number of dimension values to minimize noise and reduce infrastructure costs. When an anomaly detection job runs, we execute the dataset SQL and store the result as a Pandas dataframe. We generate one or more timeseries from the dataframe. We then generate a forecast for each timeseries using Prophet. Finally, we create a visual card for each timeseries.
[ { "code": null, "e": 231, "s": 172, "text": "Time is probably the most important dimension for metrics." }, { "code": null, "e": 331, "s": 231, "text": "In the business world, business executives, analysts, and product managers track metrics over time." }, { "code": null, "e": 395, "s": 331, "text": "In the startup world, VCs want metrics to grow 5% week-on-week." }, { "code": null, "e": 639, "s": 395, "text": "In public stock markets, long-term investors evaluate metrics on a quarter-on-quarter basis to make buy/sell decisions. Short-term traders monitor stock prices at a much smaller time granularity — minutes or hours — to make the same decisions." }, { "code": null, "e": 722, "s": 639, "text": "In the system monitoring world, teams track metrics on a second or a minute basis." }, { "code": null, "e": 805, "s": 722, "text": "In the data science world, time series analysis is an important component of work." }, { "code": null, "e": 1032, "s": 805, "text": "Even though time may be the most important dimension in the data, data does have many other dimensions. These dimensions have varying cardinality. Some high cardinality dimensions can have thousands of unique dimension values." }, { "code": null, "e": 1243, "s": 1032, "text": "It’s almost impossible to manually monitor metrics across thousands of these dimension values and their combinations. This is where timeseries analysis, particularly timeseries anomaly detection comes in handy." }, { "code": null, "e": 1282, "s": 1243, "text": "Most business data is in SQL databases" }, { "code": null, "e": 1321, "s": 1282, "text": "Most business data is in SQL databases" }, { "code": null, "e": 1565, "s": 1321, "text": "Timeseries analysis needs timeseries data as an input. But most business data is tabular and sits in relational data warehouses and databases. Analysts typically use SQL to query these databases. How can we use SQL to generate timeseries data?" }, { "code": null, "e": 1604, "s": 1565, "text": "2. How to split metrics by dimensions?" }, { "code": null, "e": 1818, "s": 1604, "text": "Some dimensions can have thousands of unique dimension values. Running anomaly detection for all dimensions values will be expensive and noisy. How can we select significant dimension values only for our analysis?" }, { "code": null, "e": 1861, "s": 1818, "text": "3. Anomaly Detection at Scale is Expensive" }, { "code": null, "e": 2039, "s": 1861, "text": "Say you work for an online retailer. Your store sells 1000 products. You want to run anomaly detection on daily orders for each of these 1000 products. This means the following:" }, { "code": null, "e": 2190, "s": 2039, "text": "Number of Metrics = 1 (Orders)Number of Dimension Values = 1000 (1000 products)Number of Metric Combinations = 1000 (1 metric * 1000 dimension values)" }, { "code": null, "e": 2296, "s": 2190, "text": "This means the anomaly detection process must run 1000 times every day, once for each metric combination." }, { "code": null, "e": 2541, "s": 2296, "text": "Let’s say you want to monitor Orders by another dimension — State (50 unique values). You also want to monitor the metric by the combinations of these two dimensions. This means the anomaly detection process must now run 51,050 times every day." }, { "code": null, "e": 2643, "s": 2541, "text": "51,050 = (1 metric * 1000 products) + (1 metric * 50 states) + (1 metric * 1000 products * 50 states)" }, { "code": null, "e": 2835, "s": 2643, "text": "To get a sense of infrastructure pricing, let’s look at the pricing of the AWS anomaly detection service. AWS will charge you $638 per month to track 51K metric combinations on a daily basis." }, { "code": null, "e": 3102, "s": 2835, "text": "This is what you will pay for just running the anomaly detection process. Before each run of the process, you need to run a query to pull data from your datawarehouse. 51K metric combinations mean 51K queries on your datawarehouse daily, which is an additional cost." }, { "code": null, "e": 3150, "s": 3102, "text": "And this is just the cloud infrastructure cost." }, { "code": null, "e": 3189, "s": 3150, "text": "4. Anomaly Detection at Scale is Noisy" }, { "code": null, "e": 3395, "s": 3189, "text": "Each of these 51K metric combinations has the potential to be an anomaly. Even if 0.1% of these combinations turn out to be anomalies, you are looking at 51 anomalies on a daily basis, for a single metric." }, { "code": null, "e": 3503, "s": 3395, "text": "Will you or your team have the bandwidth to take action on so many anomalies every single day? Probably no." }, { "code": null, "e": 3623, "s": 3503, "text": "If you don’t act on these anomalies, these anomalies don’t add any business value. Instead, they just add to your cost." }, { "code": null, "e": 3701, "s": 3623, "text": "5. When an anomaly is detected, how to dig deeper and do root cause analysis?" }, { "code": null, "e": 3737, "s": 3701, "text": "Say you have the following anomaly:" }, { "code": null, "e": 3786, "s": 3737, "text": "Orders for State = CA decreased by 15% yesterday" }, { "code": null, "e": 3819, "s": 3786, "text": "This might raise questions like:" }, { "code": null, "e": 3894, "s": 3819, "text": "Did the Orders decrease for all cities in the state? If not, which cities?" }, { "code": null, "e": 3954, "s": 3894, "text": "Did the Orders decrease for all products or a specific few?" }, { "code": null, "e": 3997, "s": 3954, "text": "How can we answer these questions quickly?" }, { "code": null, "e": 4093, "s": 3997, "text": "Faced with these challenges, we started building CueObserve. Below is how we are solving these." }, { "code": null, "e": 4296, "s": 4093, "text": "Datasets are similar to aggregated SQL VIEWS of data. We write a SQL GROUP BY query with aggregate functions to roll-up data, map its columns as dimensions and metrics, and save it as a virtual Dataset." }, { "code": null, "e": 4343, "s": 4296, "text": "Below is a sample GROUP BY query for BigQuery:" }, { "code": null, "e": 4517, "s": 4343, "text": "We can now define one or more anomaly detection jobs on the dataset. The anomaly detection job can monitor a metric at an aggregate level or split the metric by a dimension." }, { "code": null, "e": 4635, "s": 4517, "text": "When we split a metric by a dimension, we limit the number of unique dimension values. We use one of 3 ways to limit:" }, { "code": null, "e": 4856, "s": 4635, "text": "Top N: limit based on the dimension value’s contribution to the metric.Min % Contribution: limit based on the dimension value’s contribution to the metric.Minimum Average Value: limit based on the metric’s average value." }, { "code": null, "e": 4928, "s": 4856, "text": "Top N: limit based on the dimension value’s contribution to the metric." }, { "code": null, "e": 5013, "s": 4928, "text": "Min % Contribution: limit based on the dimension value’s contribution to the metric." }, { "code": null, "e": 5079, "s": 5013, "text": "Minimum Average Value: limit based on the metric’s average value." }, { "code": null, "e": 5317, "s": 5079, "text": "As the first step in the anomaly detection process, we execute the dataset’s SQL query and fetch the result as a Pandas dataframe. This dataframe acts as the source data for identifying dimension values and the anomaly detection process." }, { "code": null, "e": 5875, "s": 5317, "text": "Next, we create new dataframes on which the actual anomaly detection process will run. During this process, we find dimension values and create sub-dataframes by filtering on the dimension. The dimension values for which sub dataframes need to be created are determined by one of the 3 dimension split rules mentioned above. For example, if the dimension split rule is Top N, an internal method determines the Top N dimension values and returns a list of dicts, each containing the dimension value string, its percentage contribution, and the sub dataframe." }, { "code": null, "e": 6048, "s": 5875, "text": "The sub dataframes mentioned are just dataframes after filtering for specific dimension values and removing all other columns except the timestamp column and metric column." }, { "code": null, "e": 6120, "s": 6048, "text": "datasetDf[datasetDf[dimensionCol] == dimVal][[timestampCol, metricCol]]" }, { "code": null, "e": 6256, "s": 6120, "text": "One important step in the preparation of sub dataframes is the aggregation on timestamp which you can see in the previous code snippet." }, { "code": null, "e": 6296, "s": 6256, "text": "\"df\": aggregateDf(tempDf, timestampCol)" }, { "code": null, "e": 6560, "s": 6296, "text": "This aggregation involves grouping the filtered sub dataframe over the timestamp column and summing it over the metric column. We also rename the timestamp column as “ds” and the metric column as “y”, as Prophet requires the dataframe columns to be named as such." }, { "code": null, "e": 7102, "s": 6560, "text": "We now feed the timeseries dataframe into Prophet. Each dataframe is separately trained on Prophet and a forecast is generated. Each dataframe must have at least 20 data points after aggregation as anything less than that would be too little training data for reasonably good results. There are some other considerations that are taken with respect to the granularity of the dataframe, like the number of predictions Prophet makes and also the training data interval. For hourly granularity, we only train Prophet on the last 7 days of data." }, { "code": null, "e": 7459, "s": 7102, "text": "We initialize Prophet with predetermined parameters and interval width for reasonably broad confidence intervals. Later, we plan on making these settings configurable as well. After getting the confidence intervals and predicted values for the future, we clip all predicted values to be greater than zero and remove all extra columns from Prophet’s output." }, { "code": null, "e": 7839, "s": 7459, "text": "Next, we combine the actual data with the forecasted data from Prophet, along with the uncertainty interval bands. These bands estimate the trend of the data and will be used as the threshold for determining a data point as an anomaly. For each data point in the original dataframe, we check if it lies within the predicted bands or not and classify it as an anomaly accordingly." }, { "code": null, "e": 8008, "s": 7839, "text": "Finally, we store all the individual results of the process along with the metadata in a format for easy visual representation. Below is a sample anomaly visualization." }, { "code": null, "e": 8335, "s": 8008, "text": "To run anomaly detection on multi-dimensional business data, we write a SQL GROUP BY query, map its columns as dimensions and measures, and save it as a virtual dataset. We then define one or more anomaly detection jobs on the dataset. We limit the number of dimension values to minimize noise and reduce infrastructure costs." } ]
Ruby | Array class insert() function - GeeksforGeeks
07 Jan, 2020 insert() is a Array class method which returns the array by inserting a given element at the specified index value. Syntax: Array.insert() Parameter: Arrayindexelement Return: insert elements the specific index value Example #1 : # Ruby code for insert() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # insertputs "insert : #{a.insert(2, 5)}\n\n" # insertputs "insert : #{b.insert(2, 4, 1, 1)}\n\n" # insertputs "insert : #{c.insert(4, 4)}\n\n" Output : insert : [18, 22, 5, 33, nil, 5, 6] insert : [1, 4, 4, 1, 1, 1, 1, 88, 9] insert : [18, 22, nil, nil, 4, 50, 6] Example #2 : # Ruby code for insert() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # insertputs "insert : #{a.insert(2, 5)}\n\n" # insertputs "insert : #{b.insert(2, 4, 1, 1)}\n\n" # insertputs "insert : #{c.insert(4, 4)}\n\n" Output : insert : ["abc", "nil", 5, "dog"] insert : ["cow", nil, 4, 1, 1, "dog"] insert : ["cat", nil, nil, nil, 4] Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Include v/s Extend in Ruby Ruby | Enumerator each_with_index function Ruby | Array select() function Global Variable in Ruby Ruby | Hash delete() function Ruby | String gsub! Method Ruby | String capitalize() Method How to Make a Custom Array of Hashes in Ruby? Ruby | Case Statement Ruby | Numeric round() function
[ { "code": null, "e": 23273, "s": 23245, "text": "\n07 Jan, 2020" }, { "code": null, "e": 23389, "s": 23273, "text": "insert() is a Array class method which returns the array by inserting a given element at the specified index value." }, { "code": null, "e": 23412, "s": 23389, "text": "Syntax: Array.insert()" }, { "code": null, "e": 23441, "s": 23412, "text": "Parameter: Arrayindexelement" }, { "code": null, "e": 23490, "s": 23441, "text": "Return: insert elements the specific index value" }, { "code": null, "e": 23503, "s": 23490, "text": "Example #1 :" }, { "code": "# Ruby code for insert() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # insertputs \"insert : #{a.insert(2, 5)}\\n\\n\" # insertputs \"insert : #{b.insert(2, 4, 1, 1)}\\n\\n\" # insertputs \"insert : #{c.insert(4, 4)}\\n\\n\"", "e": 23818, "s": 23503, "text": null }, { "code": null, "e": 23827, "s": 23818, "text": "Output :" }, { "code": null, "e": 23943, "s": 23827, "text": "insert : [18, 22, 5, 33, nil, 5, 6]\n\ninsert : [1, 4, 4, 1, 1, 1, 1, 88, 9]\n\ninsert : [18, 22, nil, nil, 4, 50, 6]\n\n" }, { "code": null, "e": 23956, "s": 23943, "text": "Example #2 :" }, { "code": "# Ruby code for insert() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayb = [\"cow\", nil, \"dog\"] # declaring arrayc = [\"cat\", nil, nil] # insertputs \"insert : #{a.insert(2, 5)}\\n\\n\" # insertputs \"insert : #{b.insert(2, 4, 1, 1)}\\n\\n\" # insertputs \"insert : #{c.insert(4, 4)}\\n\\n\"", "e": 24261, "s": 23956, "text": null }, { "code": null, "e": 24270, "s": 24261, "text": "Output :" }, { "code": null, "e": 24381, "s": 24270, "text": "insert : [\"abc\", \"nil\", 5, \"dog\"]\n\ninsert : [\"cow\", nil, 4, 1, 1, \"dog\"]\n\ninsert : [\"cat\", nil, nil, nil, 4]\n\n" }, { "code": null, "e": 24398, "s": 24381, "text": "Ruby Array-class" }, { "code": null, "e": 24411, "s": 24398, "text": "Ruby-Methods" }, { "code": null, "e": 24416, "s": 24411, "text": "Ruby" }, { "code": null, "e": 24514, "s": 24416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24523, "s": 24514, "text": "Comments" }, { "code": null, "e": 24536, "s": 24523, "text": "Old Comments" }, { "code": null, "e": 24563, "s": 24536, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 24606, "s": 24563, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 24637, "s": 24606, "text": "Ruby | Array select() function" }, { "code": null, "e": 24661, "s": 24637, "text": "Global Variable in Ruby" }, { "code": null, "e": 24691, "s": 24661, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 24718, "s": 24691, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 24752, "s": 24718, "text": "Ruby | String capitalize() Method" }, { "code": null, "e": 24798, "s": 24752, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 24820, "s": 24798, "text": "Ruby | Case Statement" } ]
Espresso Testing Framework - AdapterView
AdapterView is a special kind of view specifically designed to render a collection of similar information like product list and user contacts fetched from an underlying data source using Adapter. The data source may be simple list to complex database entries. Some of the view derived from AdapterView are ListView, GridView and Spinner. AdapterView renders the user interface dynamically depending on the amount of data available in the underlying data source. In addition, AdapterView renders only the minimum necessary data, which can be rendered in the available visible area of the screen. AdapterView does this to conserve memory and to make the user interface look smooth even if the underlying data is large. Upon analysis, the nature of the AdapterView architecture makes the onView option and its view matchers irrelevant because the particular view to be tested may not be rendered at all in the first place. Luckily, espresso provides a method, onData(), which accepts hamcrest matchers (relevant to the data type of the underlying data) to match the underlying data and returns object of type DataInteraction corresponding to the view o the matched data. A sample code is as follows, onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click()) Here, onData() matches entry “Apple”, if it is available in the underlying data (array list) and returns DataInteraction object to interact with the matched view (TextView corresponding to “Apple” entry). DataInteraction provides the below methods to interact with the view, This accepts view actions and fires the passed in view actions. onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click()) This accepts view assertions and checks the passed in view assertions. onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))) .check(matches(withText("Apple"))) This accepts view matchers. It selects the particular AdapterView based on the passed in view matchers and returns DataInteraction object to interact with the matched AdapterView onData(allOf()) .inAdapterView(withId(R.id.adapter_view)) .atPosition(5) .perform(click()) This accepts an argument of type integer and refers the position of the item in the underlying data. It selects the view corresponding to the passed in positional value of the data and returns DataInteraction object to interact with the matched view. It will be useful, if we know the correct order of the underlying data. onData(allOf()) .inAdapterView(withId(R.id.adapter_view)) .atPosition(5) .perform(click()) This accepts view matchers and matches the view inside the specific child view. For example, we can interact with specific items like Buy button in a product list based AdapterView. onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))) .onChildView(withId(R.id.buy_button)) .perform(click()) Follow the steps shown below to write a simple application based on AdapterView and write a test case using the onData() method. Start Android studio. Start Android studio. Create new project as discussed earlier and name it, MyFruitApp. Create new project as discussed earlier and name it, MyFruitApp. Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu. Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu. Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows, Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows, <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <ListView android:id = "@+id/listView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </RelativeLayout> Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows, Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows, <?xml version = "1.0" encoding = "utf-8"?> <TextView xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/name" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:padding = "8dp" /> Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below, Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below, @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find fruit list view final ListView listView = (ListView) findViewById(R.id.listView); // Initialize fruit data String[] fruits = new String[]{ "Apple", "Banana", "Cherry", "Dates", "Elderberry", "Fig", "Grapes", "Grapefruit", "Guava", "Jack fruit", "Lemon", "Mango", "Orange", "Papaya", "Pears", "Peaches", "Pineapple", "Plums", "Raspberry", "Strawberry", "Watermelon" }; // Create array list of fruits final ArrayList<String> fruitList = new ArrayList<String>(); for (int i = 0; i < fruits.length; ++i) { fruitList.add(fruits[i]); } // Create Array adapter final ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item, fruitList); // Set adapter in list view listView.setAdapter(adapter); } Now, compile the code and run the application. The screenshot of the My Fruit App is as follows, Now, compile the code and run the application. The screenshot of the My Fruit App is as follows, Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below, Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below, @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<MainActivity>(MainActivity.class); Also, make sure the test configuration is done in app/build.gradle − dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test:rules:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } Add a new test case to test the list view as below, Add a new test case to test the list view as below, @Test public void listView_isCorrect() { // check list view is visible onView(withId(R.id.listView)).check(matches(isDisplayed())); onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click()); onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))) .check(matches(withText("Apple"))); // click a child item onData(allOf()) .inAdapterView(withId(R.id.listView)) .atPosition(10) .perform(click()); } Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding. Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding. 17 Lectures 1.5 hours Anuja Jain Print Add Notes Bookmark this page
[ { "code": null, "e": 2314, "s": 1976, "text": "AdapterView is a special kind of view specifically designed to render a collection of similar information like product list and user contacts fetched from an underlying data source using Adapter. The data source may be simple list to complex database entries. Some of the view derived from AdapterView are ListView, GridView and Spinner." }, { "code": null, "e": 2693, "s": 2314, "text": "AdapterView renders the user interface dynamically depending on the amount of data available in the underlying data source. In addition, AdapterView renders only the minimum necessary data, which can be rendered in the available visible area of the screen. AdapterView does this to conserve memory and to make the user interface look smooth even if the underlying data is large." }, { "code": null, "e": 3173, "s": 2693, "text": "Upon analysis, the nature of the AdapterView architecture makes the onView option and its view matchers irrelevant because the particular view to be tested may not be rendered at all in the first place. Luckily, espresso provides a method, onData(), which accepts hamcrest matchers (relevant to the data type of the underlying data) to match the underlying data and returns object of type DataInteraction corresponding to the view o the matched data. A sample code is as follows," }, { "code": null, "e": 3256, "s": 3173, "text": "onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\"))).perform(click())\n" }, { "code": null, "e": 3461, "s": 3256, "text": "Here, onData() matches entry “Apple”, if it is available in the underlying data (array list) and returns DataInteraction object to interact with the matched view (TextView corresponding to “Apple” entry)." }, { "code": null, "e": 3531, "s": 3461, "text": "DataInteraction provides the below methods to interact with the view," }, { "code": null, "e": 3595, "s": 3531, "text": "This accepts view actions and fires the passed in view actions." }, { "code": null, "e": 3678, "s": 3595, "text": "onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\"))).perform(click())\n" }, { "code": null, "e": 3749, "s": 3678, "text": "This accepts view assertions and checks the passed in view assertions." }, { "code": null, "e": 3853, "s": 3749, "text": "onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\")))\n .check(matches(withText(\"Apple\")))\n" }, { "code": null, "e": 4032, "s": 3853, "text": "This accepts view matchers. It selects the particular AdapterView based on the passed in view matchers and returns DataInteraction object to interact with the matched AdapterView" }, { "code": null, "e": 4133, "s": 4032, "text": "onData(allOf())\n .inAdapterView(withId(R.id.adapter_view))\n .atPosition(5)\n .perform(click())\n" }, { "code": null, "e": 4456, "s": 4133, "text": "This accepts an argument of type integer and refers the position of the item in the underlying data. It selects the view corresponding to the passed in positional value of the data and returns DataInteraction object to interact with the matched view. It will be useful, if we know the correct order of the underlying data." }, { "code": null, "e": 4557, "s": 4456, "text": "onData(allOf())\n .inAdapterView(withId(R.id.adapter_view))\n .atPosition(5)\n .perform(click())\n" }, { "code": null, "e": 4739, "s": 4557, "text": "This accepts view matchers and matches the view inside the specific child view. For example, we can interact with specific items like Buy button in a product list based AdapterView." }, { "code": null, "e": 4867, "s": 4739, "text": "onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\")))\n .onChildView(withId(R.id.buy_button))\n .perform(click())\n" }, { "code": null, "e": 4996, "s": 4867, "text": "Follow the steps shown below to write a simple application based on AdapterView and write a test case using the onData() method." }, { "code": null, "e": 5018, "s": 4996, "text": "Start Android studio." }, { "code": null, "e": 5040, "s": 5018, "text": "Start Android studio." }, { "code": null, "e": 5105, "s": 5040, "text": "Create new project as discussed earlier and name it, MyFruitApp." }, { "code": null, "e": 5170, "s": 5105, "text": "Create new project as discussed earlier and name it, MyFruitApp." }, { "code": null, "e": 5266, "s": 5170, "text": "Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu." }, { "code": null, "e": 5362, "s": 5266, "text": "Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu." }, { "code": null, "e": 5475, "s": 5362, "text": "Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows," }, { "code": null, "e": 5588, "s": 5475, "text": "Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows," }, { "code": null, "e": 6094, "s": 5588, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout 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 = \"match_parent\"\n tools:context = \".MainActivity\">\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 6218, "s": 6094, "text": "Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows," }, { "code": null, "e": 6342, "s": 6218, "text": "Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows," }, { "code": null, "e": 6595, "s": 6342, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<TextView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/name\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\"\n android:padding = \"8dp\"\n/>" }, { "code": null, "e": 6761, "s": 6595, "text": "Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below," }, { "code": null, "e": 6927, "s": 6761, "text": "Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below," }, { "code": null, "e": 7980, "s": 6927, "text": "@Override\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // Find fruit list view\n final ListView listView = (ListView) findViewById(R.id.listView);\n \n // Initialize fruit data\n String[] fruits = new String[]{\n \"Apple\", \n \"Banana\", \n \"Cherry\", \n \"Dates\", \n \"Elderberry\", \n \"Fig\", \n \"Grapes\", \n \"Grapefruit\", \n \"Guava\",\n \"Jack fruit\", \n \"Lemon\",\n \"Mango\", \n \"Orange\", \n \"Papaya\", \n \"Pears\", \n \"Peaches\", \n \"Pineapple\",\n \"Plums\", \n \"Raspberry\",\n \"Strawberry\", \n \"Watermelon\"\n };\n \n // Create array list of fruits\n final ArrayList<String> fruitList = new ArrayList<String>();\n for (int i = 0; i < fruits.length; ++i) {\n fruitList.add(fruits[i]);\n }\n \n // Create Array adapter\n final ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item, fruitList);\n \n // Set adapter in list view\n listView.setAdapter(adapter);\n}" }, { "code": null, "e": 8077, "s": 7980, "text": "Now, compile the code and run the application. The screenshot of the My Fruit App is as follows," }, { "code": null, "e": 8174, "s": 8077, "text": "Now, compile the code and run the application. The screenshot of the My Fruit App is as follows," }, { "code": null, "e": 8263, "s": 8174, "text": "Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below," }, { "code": null, "e": 8352, "s": 8263, "text": "Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below," }, { "code": null, "e": 8472, "s": 8352, "text": "@Rule\npublic ActivityTestRule<MainActivity> mActivityRule =\n new ActivityTestRule<MainActivity>(MainActivity.class);\n" }, { "code": null, "e": 8541, "s": 8472, "text": "Also, make sure the test configuration is done in app/build.gradle −" }, { "code": null, "e": 8788, "s": 8541, "text": "dependencies {\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'androidx.test:runner:1.1.1'\n androidTestImplementation 'androidx.test:rules:1.1.1'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'\n}" }, { "code": null, "e": 8840, "s": 8788, "text": "Add a new test case to test the list view as below," }, { "code": null, "e": 8892, "s": 8840, "text": "Add a new test case to test the list view as below," }, { "code": null, "e": 9364, "s": 8892, "text": "@Test\npublic void listView_isCorrect() {\n // check list view is visible\n onView(withId(R.id.listView)).check(matches(isDisplayed()));\n onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\"))).perform(click());\n onData(allOf(is(instanceOf(String.class)), startsWith(\"Apple\")))\n .check(matches(withText(\"Apple\")));\n // click a child item\n onData(allOf())\n .inAdapterView(withId(R.id.listView))\n .atPosition(10)\n .perform(click());\n}\n" }, { "code": null, "e": 9476, "s": 9364, "text": "Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding." }, { "code": null, "e": 9588, "s": 9476, "text": "Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding." }, { "code": null, "e": 9623, "s": 9588, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9635, "s": 9623, "text": " Anuja Jain" }, { "code": null, "e": 9642, "s": 9635, "text": " Print" }, { "code": null, "e": 9653, "s": 9642, "text": " Add Notes" } ]
Fantastic Pandas Data Frame Report with Pandas Profiling | by Cornellius Yudha Wijaya | Towards Data Science
As a Data Scientist, we would explore data for our everyday work. For Pythonist, using the Pandas module is a must. While compelling, sometimes we find the report is just too basic. Let me show it by an example below. import pandas as pdimport seaborn as sns#Loading dataset mpg = sns.load_dataset('mpg')mpg.describe() We could produce the fundamental statistic using .describe() attribute, but instead of a basic report like the sample above, we could have our report way more attractive like below. Just look at how different the report becomes. It makes our daily exploration way easier. Furthermore, you could save the report into HTML and share it with anybody you want. Let’s just get into it. We could create a fantastic report like above with the help of Pandas Profiling module. This module is the best to work in the Jupyter environment so that this article would cover the report generated in the Jupyter Notebook. Now, to use this module, we need to install the module. #Installing via pippip install -U pandas-profiling[notebook]#Enable the widget extension in Jupyterjupyter nbextension enable --py widgetsnbextension#or if you prefer via Condaconda env create -n pandas-profilingconda activate pandas-profilingconda install -c conda-forge pandas-profiling#or if you prefer installing directly from the sourcepip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip#in any case, if the code raise an error, it probably need permission from user. To do that, add --user in the end of the line. With that, we are ready to generate the report. We would use the Pandas Profiling function, just like the code below. #Importing the functionfrom pandas_profiling import ProfileReport#Generate the report. We would use the mpg dataset as sample, title parameter for naming our report, and explorative parameter set to True for Deeper exploration.profile = ProfileReport(mpg, title='MPG Pandas Profiling Report', explorative = True)profile After waiting a while, we would end up with an HTML report like below. In the first part, we would get the overview information of our Data Frame. It is similar if we use the.info() attribute from the Pandas Data Frame object, but the Pandas Profiling offer more information. For example, the Warnings section. What is excellent about the Warnings section is that the information given are not just basic info such as missing data, but more complex one such as high correlation, high cardinality, etc. We could modify how high it is to consider what is ‘High Cardinal’ or ‘High Correlation’, but I would not discuss it in this article. If we scroll down, we would see the Variables Section, which shown all the Numerical and Categorical columns with more detail. Below is the example of the numerical variable. We could see that for each variable, we are served with complete statistic information. Furthermore, there are sections where we could get information for the most common values and extreme values. How about Categorical variable? Let me show you in the image below. Just like the numerical variable, we acquired complete information about the variable. Scroll down even further; we would arrive in the Interactions section. This is the section where we could get a Scatter Plot between two numerical variables. And just below it is the Correlations section. This section is showing the correlation values between numerical variables in the form of a heatmap. Only four correlation calculation available here and if you need the correlation descriptions, you could click the “Toggle correlation descriptions button”. There is also a section dedicated to the Missing values, just like the example below. And the last section would only show the data samples — nothing interesting there. If you need a more simple way to show the report, we could use the following code to transform the report. profile.to_widgets() With one line of code, we get the same information from what I showed you above. The only differences are just the UI becomes more straightforward. The information, although, would still the same. Lastly, if you want to export the report into an external HTML file, we could use the following code. profile.to_file('your_report_name.html') You could find the HTML file in the same folder with your Jupyter Notebook. If you open the file, it would automatically open on your default browser with beautiful UI similar to the one in our Jupyter Notebook. I have shown you how to transform our basic report in the Pandas Data Frame to a more interactive form by using the Pandas Profiling Module. I hope it helps. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 389, "s": 171, "text": "As a Data Scientist, we would explore data for our everyday work. For Pythonist, using the Pandas module is a must. While compelling, sometimes we find the report is just too basic. Let me show it by an example below." }, { "code": null, "e": 490, "s": 389, "text": "import pandas as pdimport seaborn as sns#Loading dataset mpg = sns.load_dataset('mpg')mpg.describe()" }, { "code": null, "e": 672, "s": 490, "text": "We could produce the fundamental statistic using .describe() attribute, but instead of a basic report like the sample above, we could have our report way more attractive like below." }, { "code": null, "e": 871, "s": 672, "text": "Just look at how different the report becomes. It makes our daily exploration way easier. Furthermore, you could save the report into HTML and share it with anybody you want. Let’s just get into it." }, { "code": null, "e": 1153, "s": 871, "text": "We could create a fantastic report like above with the help of Pandas Profiling module. This module is the best to work in the Jupyter environment so that this article would cover the report generated in the Jupyter Notebook. Now, to use this module, we need to install the module." }, { "code": null, "e": 1705, "s": 1153, "text": "#Installing via pippip install -U pandas-profiling[notebook]#Enable the widget extension in Jupyterjupyter nbextension enable --py widgetsnbextension#or if you prefer via Condaconda env create -n pandas-profilingconda activate pandas-profilingconda install -c conda-forge pandas-profiling#or if you prefer installing directly from the sourcepip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip#in any case, if the code raise an error, it probably need permission from user. To do that, add --user in the end of the line." }, { "code": null, "e": 1823, "s": 1705, "text": "With that, we are ready to generate the report. We would use the Pandas Profiling function, just like the code below." }, { "code": null, "e": 2143, "s": 1823, "text": "#Importing the functionfrom pandas_profiling import ProfileReport#Generate the report. We would use the mpg dataset as sample, title parameter for naming our report, and explorative parameter set to True for Deeper exploration.profile = ProfileReport(mpg, title='MPG Pandas Profiling Report', explorative = True)profile" }, { "code": null, "e": 2214, "s": 2143, "text": "After waiting a while, we would end up with an HTML report like below." }, { "code": null, "e": 2454, "s": 2214, "text": "In the first part, we would get the overview information of our Data Frame. It is similar if we use the.info() attribute from the Pandas Data Frame object, but the Pandas Profiling offer more information. For example, the Warnings section." }, { "code": null, "e": 2779, "s": 2454, "text": "What is excellent about the Warnings section is that the information given are not just basic info such as missing data, but more complex one such as high correlation, high cardinality, etc. We could modify how high it is to consider what is ‘High Cardinal’ or ‘High Correlation’, but I would not discuss it in this article." }, { "code": null, "e": 2954, "s": 2779, "text": "If we scroll down, we would see the Variables Section, which shown all the Numerical and Categorical columns with more detail. Below is the example of the numerical variable." }, { "code": null, "e": 3152, "s": 2954, "text": "We could see that for each variable, we are served with complete statistic information. Furthermore, there are sections where we could get information for the most common values and extreme values." }, { "code": null, "e": 3220, "s": 3152, "text": "How about Categorical variable? Let me show you in the image below." }, { "code": null, "e": 3465, "s": 3220, "text": "Just like the numerical variable, we acquired complete information about the variable. Scroll down even further; we would arrive in the Interactions section. This is the section where we could get a Scatter Plot between two numerical variables." }, { "code": null, "e": 3512, "s": 3465, "text": "And just below it is the Correlations section." }, { "code": null, "e": 3770, "s": 3512, "text": "This section is showing the correlation values between numerical variables in the form of a heatmap. Only four correlation calculation available here and if you need the correlation descriptions, you could click the “Toggle correlation descriptions button”." }, { "code": null, "e": 3856, "s": 3770, "text": "There is also a section dedicated to the Missing values, just like the example below." }, { "code": null, "e": 3939, "s": 3856, "text": "And the last section would only show the data samples — nothing interesting there." }, { "code": null, "e": 4046, "s": 3939, "text": "If you need a more simple way to show the report, we could use the following code to transform the report." }, { "code": null, "e": 4067, "s": 4046, "text": "profile.to_widgets()" }, { "code": null, "e": 4264, "s": 4067, "text": "With one line of code, we get the same information from what I showed you above. The only differences are just the UI becomes more straightforward. The information, although, would still the same." }, { "code": null, "e": 4366, "s": 4264, "text": "Lastly, if you want to export the report into an external HTML file, we could use the following code." }, { "code": null, "e": 4407, "s": 4366, "text": "profile.to_file('your_report_name.html')" }, { "code": null, "e": 4619, "s": 4407, "text": "You could find the HTML file in the same folder with your Jupyter Notebook. If you open the file, it would automatically open on your default browser with beautiful UI similar to the one in our Jupyter Notebook." }, { "code": null, "e": 4777, "s": 4619, "text": "I have shown you how to transform our basic report in the Pandas Data Frame to a more interactive form by using the Pandas Profiling Module. I hope it helps." } ]
AWT TextArea Class
The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left. Following is the declaration for java.awt.TextArea class: public class TextArea extends TextComponent Following are the fields for java.awt.TextArea class: static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars. static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars. static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only. static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only. static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area. static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area. static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only. static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only. TextArea() Constructs a new text area with the empty string as text. TextArea(int rows, int columns) Constructs a new text area with the specified number of rows and columns and the empty string as text. TextArea(String text) Constructs a new text area with the specified text. TextArea(String text, int rows, int columns) Constructs a new text area with the specified text, and with the specified number of rows and columns. TextArea(String text, int rows, int columns, int scrollbars) Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified. void addNotify() Creates the TextArea's peer. void append(String str) Appends the given text to the text area's current text. void appendText(String str) Deprecated. As of JDK version 1.1, replaced by append(String). AccessibleContext getAccessibleContext() Returns the AccessibleContext associated with this TextArea. int getColumns() Returns the number of columns in this text area. Dimension getMinimumSize() Determines the minimum size of this text area. Dimension getMinimumSize(int rows, int columns) Determines the minimum size of a text area with the specified number of rows and columns. Dimension getPreferredSize() Determines the preferred size of this text area. Dimension getPreferredSize(int rows, int columns) Determines the preferred size of a text area with the specified number of rows and columns. int getRows() Returns the number of rows in the text area. int getScrollbarVisibility() Returns an enumerated value that indicates which scroll bars the text area uses. void insert(String str, int pos) Inserts the specified text at the specified position in this text area. void insertText(String str, int pos) Deprecated. As of JDK version 1.1, replaced by insert(String, int). Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). Dimension minimumSize(int rows, int columns) Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int). protected String paramString() Returns a string representing the state of this TextArea. Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). Dimension preferredSize(int rows, int columns) Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int). void replaceRange(String str, int start, int end) Replaces text between the indicated start and end positions with the specified replacement text. void replaceText(String str, int start, int end) Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int). void setColumns(int columns) Sets the number of columns for this text area. void setRows(int rows) Sets the number of rows for this text area. This class inherits methods from the following classes: java.awt.TextComponent java.awt.TextComponent java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showTextAreaDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showTextAreaDemo(){ headerLabel.setText("Control in action: TextArea"); Label commentlabel= new Label("Comments: ", Label.RIGHT); final TextArea commentTextArea = new TextArea("This is a AWT tutorial " +"to make GUI application in Java.",5,30); Button showButton = new Button("Show"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText( commentTextArea.getText()); } }); controlPanel.add(commentlabel); controlPanel.add(commentTextArea); controlPanel.add(showButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2022, "s": 1747, "text": "The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left." }, { "code": null, "e": 2080, "s": 2022, "text": "Following is the declaration for java.awt.TextArea class:" }, { "code": null, "e": 2127, "s": 2080, "text": "public class TextArea\n extends TextComponent" }, { "code": null, "e": 2181, "s": 2127, "text": "Following are the fields for java.awt.TextArea class:" }, { "code": null, "e": 2274, "s": 2181, "text": "static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars. \t" }, { "code": null, "e": 2367, "s": 2274, "text": "static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars. \t" }, { "code": null, "e": 2455, "s": 2367, "text": "static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only." }, { "code": null, "e": 2543, "s": 2455, "text": "static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only." }, { "code": null, "e": 2634, "s": 2543, "text": "static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area. " }, { "code": null, "e": 2725, "s": 2634, "text": "static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area. " }, { "code": null, "e": 2808, "s": 2725, "text": "static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only." }, { "code": null, "e": 2891, "s": 2808, "text": "static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only." }, { "code": null, "e": 2903, "s": 2891, "text": "TextArea() " }, { "code": null, "e": 2961, "s": 2903, "text": "Constructs a new text area with the empty string as text." }, { "code": null, "e": 2994, "s": 2961, "text": "TextArea(int rows, int columns) " }, { "code": null, "e": 3097, "s": 2994, "text": "Constructs a new text area with the specified number of rows and columns and the empty string as text." }, { "code": null, "e": 3120, "s": 3097, "text": "TextArea(String text) " }, { "code": null, "e": 3172, "s": 3120, "text": "Constructs a new text area with the specified text." }, { "code": null, "e": 3218, "s": 3172, "text": "TextArea(String text, int rows, int columns) " }, { "code": null, "e": 3321, "s": 3218, "text": "Constructs a new text area with the specified text, and with the specified number of rows and columns." }, { "code": null, "e": 3383, "s": 3321, "text": "TextArea(String text, int rows, int columns, int scrollbars) " }, { "code": null, "e": 3503, "s": 3383, "text": "Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified." }, { "code": null, "e": 3521, "s": 3503, "text": "void addNotify() " }, { "code": null, "e": 3550, "s": 3521, "text": "Creates the TextArea's peer." }, { "code": null, "e": 3575, "s": 3550, "text": "void append(String str) " }, { "code": null, "e": 3631, "s": 3575, "text": "Appends the given text to the text area's current text." }, { "code": null, "e": 3660, "s": 3631, "text": "void appendText(String str) " }, { "code": null, "e": 3723, "s": 3660, "text": "Deprecated. As of JDK version 1.1, replaced by append(String)." }, { "code": null, "e": 3765, "s": 3723, "text": "AccessibleContext getAccessibleContext() " }, { "code": null, "e": 3826, "s": 3765, "text": "Returns the AccessibleContext associated with this TextArea." }, { "code": null, "e": 3844, "s": 3826, "text": "int getColumns() " }, { "code": null, "e": 3893, "s": 3844, "text": "Returns the number of columns in this text area." }, { "code": null, "e": 3921, "s": 3893, "text": "Dimension getMinimumSize() " }, { "code": null, "e": 3968, "s": 3921, "text": "Determines the minimum size of this text area." }, { "code": null, "e": 4017, "s": 3968, "text": "Dimension getMinimumSize(int rows, int columns) " }, { "code": null, "e": 4107, "s": 4017, "text": "Determines the minimum size of a text area with the specified number of rows and columns." }, { "code": null, "e": 4137, "s": 4107, "text": "Dimension getPreferredSize() " }, { "code": null, "e": 4186, "s": 4137, "text": "Determines the preferred size of this text area." }, { "code": null, "e": 4237, "s": 4186, "text": "Dimension getPreferredSize(int rows, int columns) " }, { "code": null, "e": 4329, "s": 4237, "text": "Determines the preferred size of a text area with the specified number of rows and columns." }, { "code": null, "e": 4344, "s": 4329, "text": "int getRows() " }, { "code": null, "e": 4389, "s": 4344, "text": "Returns the number of rows in the text area." }, { "code": null, "e": 4419, "s": 4389, "text": "int getScrollbarVisibility() " }, { "code": null, "e": 4500, "s": 4419, "text": "Returns an enumerated value that indicates which scroll bars the text area uses." }, { "code": null, "e": 4534, "s": 4500, "text": "void insert(String str, int pos) " }, { "code": null, "e": 4606, "s": 4534, "text": "Inserts the specified text at the specified position in this text area." }, { "code": null, "e": 4644, "s": 4606, "text": "void insertText(String str, int pos) " }, { "code": null, "e": 4712, "s": 4644, "text": "Deprecated. As of JDK version 1.1, replaced by insert(String, int)." }, { "code": null, "e": 4737, "s": 4712, "text": "Dimension minimumSize() " }, { "code": null, "e": 4802, "s": 4737, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize()." }, { "code": null, "e": 4848, "s": 4802, "text": "Dimension minimumSize(int rows, int columns) " }, { "code": null, "e": 4921, "s": 4848, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int)." }, { "code": null, "e": 4953, "s": 4921, "text": "protected String paramString() " }, { "code": null, "e": 5011, "s": 4953, "text": "Returns a string representing the state of this TextArea." }, { "code": null, "e": 5038, "s": 5011, "text": "Dimension preferredSize() " }, { "code": null, "e": 5105, "s": 5038, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()." }, { "code": null, "e": 5153, "s": 5105, "text": "Dimension preferredSize(int rows, int columns) " }, { "code": null, "e": 5228, "s": 5153, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int)." }, { "code": null, "e": 5279, "s": 5228, "text": "void replaceRange(String str, int start, int end) " }, { "code": null, "e": 5376, "s": 5279, "text": "Replaces text between the indicated start and end positions with the specified replacement text." }, { "code": null, "e": 5426, "s": 5376, "text": "void replaceText(String str, int start, int end) " }, { "code": null, "e": 5505, "s": 5426, "text": "Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int)." }, { "code": null, "e": 5535, "s": 5505, "text": "void setColumns(int columns) " }, { "code": null, "e": 5582, "s": 5535, "text": "Sets the number of columns for this text area." }, { "code": null, "e": 5606, "s": 5582, "text": "void setRows(int rows) " }, { "code": null, "e": 5650, "s": 5606, "text": "Sets the number of rows for this text area." }, { "code": null, "e": 5706, "s": 5650, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 5729, "s": 5706, "text": "java.awt.TextComponent" }, { "code": null, "e": 5752, "s": 5729, "text": "java.awt.TextComponent" }, { "code": null, "e": 5771, "s": 5752, "text": "java.awt.Component" }, { "code": null, "e": 5790, "s": 5771, "text": "java.awt.Component" }, { "code": null, "e": 5807, "s": 5790, "text": "java.lang.Object" }, { "code": null, "e": 5824, "s": 5807, "text": "java.lang.Object" }, { "code": null, "e": 5938, "s": 5824, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 7856, "s": 5938, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showTextAreaDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showTextAreaDemo(){\n headerLabel.setText(\"Control in action: TextArea\"); \n\n Label commentlabel= new Label(\"Comments: \", Label.RIGHT);\n\n final TextArea commentTextArea = new TextArea(\"This is a AWT tutorial \"\n +\"to make GUI application in Java.\",5,30);\n\n Button showButton = new Button(\"Show\");\n\n showButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText( commentTextArea.getText()); \n }\n }); \n\n controlPanel.add(commentlabel);\n controlPanel.add(commentTextArea); \n controlPanel.add(showButton);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 7947, "s": 7856, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 8003, "s": 7947, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 8100, "s": 8003, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 8150, "s": 8100, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 8178, "s": 8150, "text": "Verify the following output" }, { "code": null, "e": 8211, "s": 8178, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8219, "s": 8211, "text": " EduOLC" }, { "code": null, "e": 8226, "s": 8219, "text": " Print" }, { "code": null, "e": 8237, "s": 8226, "text": " Add Notes" } ]
How to predict your best footballers’ FIFA 20 ratings. | by Mubarak Ganiyu | Towards Data Science
I passed the ball from Milner to Salah. Salah did a quick dribble, gave the ball to Firmino. Firmino stylishly did a 360 pass to Mane. Mane hits the ball with his left foot into the top right corner of the post. It’s a goal. Another powerful effort by a highly rated Liverpool FC team. This feeling of being able to control your favorite players and make them do different skills in a virtual world is unfathomable. I have had some of my best experience playing FIFA. I get to see footballers do what I want them to do and have the chance to control the pace and outcome of the game which is why I was so excited to play FIFA 20. Every year, EA sports releases a new FIFA game. This year, my favorite player, Virgil van Dijk is on the front cover. I could not just wait to install the game and use a 91 rated van Dijk to play against opponents. I was also eager to experience new in-game activities such as volta football, house rules and FIFA ultimate team. Looking at the players’ ratings, I remembered an article (which can be found here) I wrote a while ago in which I predicted FIFA 19 players’ ratings using a machine learning algorithm. Thus, I decided to write a new article on predicting FIFA 20 players’ ratings. This was done in two ways. Firstly, by using FIFA 20 players’ attributes. Then, by using the machine learning algorithm developed to predict the FIFA 19 players’ ratings. The datasets that had the right attributes were found. Two datasets consisting of the 2019 FIFA ratings and the 2020 FIFA ratings were gotten from this link. After they were obtained, they were loaded and cleaned into Jupyter Notebooks. The main features that were retained for data analysis are: name, overall, age, value, wage and potential. A scatterplot was created to find out how FIFA 20 players’ overall ratings correlated with their potential. A regression line was also built into the scatterplot. The correlation coefficient for this scatterplot was about 0.647 which suggests that there is a moderate positive relationship between both of variables. Below is a table showing the correlation coefficient between all the variables. Upon reviewing other variables’ relationships with overall ratings, it has been concluded that age, wage and value also have a moderate positive relationship with overall. The dataset was split into two groups: training and testing datasets. The training dataset retained 87.5 % of the entire dataset while the testing dataset retained 12.5 % of the entire dataset. The purpose of splitting the dataset into two groups was to use the training dataset to learn how the independent variables (age, potential, value and wage) interacted with the dependent variable (overall). Then, the algorithm developed from this interaction was used to predict the overall ratings of the testing dataset. Here is the code for splitting, training and testing the dataset. import numpy as npsplit = np.random.rand(len(df_fifa1)) < 0.875train = df_fifa1[split]test = df_fifa1[~split] regr = linear_model.LinearRegression() ## Trainig & fitting the modelfifa_x_train = train[['age','value_eur','potential','wage_eur']]fifa_y_train = train[['overall']]poly = PolynomialFeatures(degree=4)fifa_x_train_poly = poly.fit_transform(fifa_x_train)regr.fit(fifa_x_train_poly, fifa_y_train) ## Testing the modelfifa_x_test = test[['age','value_eur','potential', 'wage_eur']]fifa_y_test = test[['overall']]fifa_x_test_poly = poly.fit_transform(fifa_x_test) Using a multiple polynomial regression with a with a degree of four, the predictions were made and its accuracy was tested by using r2-score, pearson correlation coefficient and p value. The machine learning algorithm was significantly accurate. Its r2-score was about 97.6 %, pearson correlation coefficient of 98.8 % and a p-value of 0. After making predictions, two tables were created to display both the training datasets’ predicted ratings and the testing datasets’ predicted ratings. In both datasets, the player’s predicted ratings can be viewed on the first column from the right. This makes Lionel Messi’s predicted rating, 93.59, Ronaldo’s predicted rating, 93.27 and Neymar’s predicted rating, 91.00. Therefore, showing how accurate their ratings are compared to their actual ratings of 94, 93 and 92 respectively and justifying the 97.6 % accuracy of the model. The same process that was done for generating a predictive model for FIFA 20 players’ ratings based on attributes was repeated for FIFA 19 players’ datasets. Then, the predictive model from the FIFA 19 dataset was used to generate predicted ratings for the FIFA 20 ratings using FIFA 20 players’ attributes. The model also turned out to be accurate. It had an r-2 score of 97.4 %, pearson correlation coefficient of 98.8 % and a p-value of 0. According to the table, most of the predicted ratings are quite close to the overall ratings. However, Marc Ter Stegen seems to be an outlier. His rating was predicted to be 104 whereas the maximum one can get is 100. UEFA player of the year, Virgil van Dijk, got a predicted rating of 92.9. His overall rating is 91. FIFA best player of the year, Lionel Messi, got a predicted rating of 92.14. His overall rating is 94. Looking at the results of the two methods used to predict the ratings, it can be concluded that FIFA uses the same metric every year to determine players’ ratings. The full version of the code that was used to build these predictive models can be seen here.
[ { "code": null, "e": 333, "s": 47, "text": "I passed the ball from Milner to Salah. Salah did a quick dribble, gave the ball to Firmino. Firmino stylishly did a 360 pass to Mane. Mane hits the ball with his left foot into the top right corner of the post. It’s a goal. Another powerful effort by a highly rated Liverpool FC team." }, { "code": null, "e": 677, "s": 333, "text": "This feeling of being able to control your favorite players and make them do different skills in a virtual world is unfathomable. I have had some of my best experience playing FIFA. I get to see footballers do what I want them to do and have the chance to control the pace and outcome of the game which is why I was so excited to play FIFA 20." }, { "code": null, "e": 1006, "s": 677, "text": "Every year, EA sports releases a new FIFA game. This year, my favorite player, Virgil van Dijk is on the front cover. I could not just wait to install the game and use a 91 rated van Dijk to play against opponents. I was also eager to experience new in-game activities such as volta football, house rules and FIFA ultimate team." }, { "code": null, "e": 1270, "s": 1006, "text": "Looking at the players’ ratings, I remembered an article (which can be found here) I wrote a while ago in which I predicted FIFA 19 players’ ratings using a machine learning algorithm. Thus, I decided to write a new article on predicting FIFA 20 players’ ratings." }, { "code": null, "e": 1441, "s": 1270, "text": "This was done in two ways. Firstly, by using FIFA 20 players’ attributes. Then, by using the machine learning algorithm developed to predict the FIFA 19 players’ ratings." }, { "code": null, "e": 1785, "s": 1441, "text": "The datasets that had the right attributes were found. Two datasets consisting of the 2019 FIFA ratings and the 2020 FIFA ratings were gotten from this link. After they were obtained, they were loaded and cleaned into Jupyter Notebooks. The main features that were retained for data analysis are: name, overall, age, value, wage and potential." }, { "code": null, "e": 1948, "s": 1785, "text": "A scatterplot was created to find out how FIFA 20 players’ overall ratings correlated with their potential. A regression line was also built into the scatterplot." }, { "code": null, "e": 2102, "s": 1948, "text": "The correlation coefficient for this scatterplot was about 0.647 which suggests that there is a moderate positive relationship between both of variables." }, { "code": null, "e": 2182, "s": 2102, "text": "Below is a table showing the correlation coefficient between all the variables." }, { "code": null, "e": 2354, "s": 2182, "text": "Upon reviewing other variables’ relationships with overall ratings, it has been concluded that age, wage and value also have a moderate positive relationship with overall." }, { "code": null, "e": 2548, "s": 2354, "text": "The dataset was split into two groups: training and testing datasets. The training dataset retained 87.5 % of the entire dataset while the testing dataset retained 12.5 % of the entire dataset." }, { "code": null, "e": 2871, "s": 2548, "text": "The purpose of splitting the dataset into two groups was to use the training dataset to learn how the independent variables (age, potential, value and wage) interacted with the dependent variable (overall). Then, the algorithm developed from this interaction was used to predict the overall ratings of the testing dataset." }, { "code": null, "e": 2937, "s": 2871, "text": "Here is the code for splitting, training and testing the dataset." }, { "code": null, "e": 3087, "s": 2937, "text": "import numpy as npsplit = np.random.rand(len(df_fifa1)) < 0.875train = df_fifa1[split]test = df_fifa1[~split] regr = linear_model.LinearRegression()" }, { "code": null, "e": 3343, "s": 3087, "text": "## Trainig & fitting the modelfifa_x_train = train[['age','value_eur','potential','wage_eur']]fifa_y_train = train[['overall']]poly = PolynomialFeatures(degree=4)fifa_x_train_poly = poly.fit_transform(fifa_x_train)regr.fit(fifa_x_train_poly, fifa_y_train)" }, { "code": null, "e": 3508, "s": 3343, "text": "## Testing the modelfifa_x_test = test[['age','value_eur','potential', 'wage_eur']]fifa_y_test = test[['overall']]fifa_x_test_poly = poly.fit_transform(fifa_x_test)" }, { "code": null, "e": 3695, "s": 3508, "text": "Using a multiple polynomial regression with a with a degree of four, the predictions were made and its accuracy was tested by using r2-score, pearson correlation coefficient and p value." }, { "code": null, "e": 3847, "s": 3695, "text": "The machine learning algorithm was significantly accurate. Its r2-score was about 97.6 %, pearson correlation coefficient of 98.8 % and a p-value of 0." }, { "code": null, "e": 3999, "s": 3847, "text": "After making predictions, two tables were created to display both the training datasets’ predicted ratings and the testing datasets’ predicted ratings." }, { "code": null, "e": 4383, "s": 3999, "text": "In both datasets, the player’s predicted ratings can be viewed on the first column from the right. This makes Lionel Messi’s predicted rating, 93.59, Ronaldo’s predicted rating, 93.27 and Neymar’s predicted rating, 91.00. Therefore, showing how accurate their ratings are compared to their actual ratings of 94, 93 and 92 respectively and justifying the 97.6 % accuracy of the model." }, { "code": null, "e": 4691, "s": 4383, "text": "The same process that was done for generating a predictive model for FIFA 20 players’ ratings based on attributes was repeated for FIFA 19 players’ datasets. Then, the predictive model from the FIFA 19 dataset was used to generate predicted ratings for the FIFA 20 ratings using FIFA 20 players’ attributes." }, { "code": null, "e": 4826, "s": 4691, "text": "The model also turned out to be accurate. It had an r-2 score of 97.4 %, pearson correlation coefficient of 98.8 % and a p-value of 0." }, { "code": null, "e": 5247, "s": 4826, "text": "According to the table, most of the predicted ratings are quite close to the overall ratings. However, Marc Ter Stegen seems to be an outlier. His rating was predicted to be 104 whereas the maximum one can get is 100. UEFA player of the year, Virgil van Dijk, got a predicted rating of 92.9. His overall rating is 91. FIFA best player of the year, Lionel Messi, got a predicted rating of 92.14. His overall rating is 94." }, { "code": null, "e": 5411, "s": 5247, "text": "Looking at the results of the two methods used to predict the ratings, it can be concluded that FIFA uses the same metric every year to determine players’ ratings." } ]
C++ | References | Question 4 - GeeksforGeeks
28 Jun, 2021 Predict the output of following C++ program. #include<iostream>using namespace std; int &fun(){ static int x = 10; return x;}int main(){ fun() = 30; cout << fun(); return 0;} (A) Compiler Error: Function cannot be used as lvalue(B) 10(C) 30Answer: (C)Explanation: When a function returns by reference, it can be used as lvalue. Since x is a static variable, it is shared among function calls and the initialization line “static int x = 10;” is executed only once.The function call fun() = 30, modifies x to 30. The next call “cout << fun()" returns the modified value.Quiz of this Question C++-References References C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Core Dump (Segmentation fault) in C/C++ fork() in C C++ | Exception Handling | Question 3 C++ | Inheritance | Question 7 C++ | new and delete | Question 4 C++ | Inheritance | Question 1 C++ | Inheritance | Question 11
[ { "code": null, "e": 24326, "s": 24298, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24371, "s": 24326, "text": "Predict the output of following C++ program." }, { "code": "#include<iostream>using namespace std; int &fun(){ static int x = 10; return x;}int main(){ fun() = 30; cout << fun(); return 0;}", "e": 24517, "s": 24371, "text": null }, { "code": null, "e": 24932, "s": 24517, "text": "(A) Compiler Error: Function cannot be used as lvalue(B) 10(C) 30Answer: (C)Explanation: When a function returns by reference, it can be used as lvalue. Since x is a static variable, it is shared among function calls and the initialization line “static int x = 10;” is executed only once.The function call fun() = 30, modifies x to 30. The next call “cout << fun()\" returns the modified value.Quiz of this Question" }, { "code": null, "e": 24947, "s": 24932, "text": "C++-References" }, { "code": null, "e": 24958, "s": 24947, "text": "References" }, { "code": null, "e": 24969, "s": 24958, "text": "C Language" }, { "code": null, "e": 24978, "s": 24969, "text": "C++ Quiz" }, { "code": null, "e": 25076, "s": 24978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25111, "s": 25076, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25139, "s": 25111, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25185, "s": 25139, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25225, "s": 25185, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 25237, "s": 25225, "text": "fork() in C" }, { "code": null, "e": 25275, "s": 25237, "text": "C++ | Exception Handling | Question 3" }, { "code": null, "e": 25306, "s": 25275, "text": "C++ | Inheritance | Question 7" }, { "code": null, "e": 25340, "s": 25306, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 25371, "s": 25340, "text": "C++ | Inheritance | Question 1" } ]
Converting a Simple Deep Learning Model from PyTorch to TensorFlow | by Yu Xuan Lee | Towards Data Science
Introduction TensorFlow and PyTorch are two of the more popular frameworks out there for deep learning. There are people who prefer TensorFlow for support in terms of deployment, and there are those who prefer PyTorch because of the flexibility in model building and training without the difficulties faced in using TensorFlow. The downside of using PyTorch is that the model built and trained using this framework cannot be deployed into production. (Update in Dec 2019: It is claimed that later versions of PyTorch have better support for deployment, but I believe that is something else to be explored.) To address the issue of deploying models built using PyTorch, one solution is to use ONNX (Open Neural Network Exchange). As explained in ONNX’s About page, ONNX is like a bridge that links the various deep learning frameworks together. To this end, the ONNX tool enables the conversion of models from one framework to another. Up to the time of this writing, ONNX is limited to simpler model structures, but there may be further additions later on. This article will illustrate how a simple deep learning model can be converted from PyTorch to TensorFlow. Installing the necessary packages To start off, we would need to install PyTorch, TensorFlow, ONNX, and ONNX-TF (the package to convert ONNX models to TensorFlow). If using virtualenv in Linux, you could run the command below (replace tensorflow with tensorflow-gpu if you have NVidia CUDA installed). Do note that as of Dec 2019, ONNX does not work with TensorFlow 2.0 yet, so please take note of the version of the TensorFlow that you install. source <your virtual environment>/bin/activatepip install tensorflow==1.15.0# For PyTorch, choose one of the following (refer to https://pytorch.org/get-started/locally/ for further details)pip install torch torchvision # if using CUDA 10.1pip install torch==1.3.1+cu92 torchvision==0.4.2+cu92 -f https://download.pytorch.org/whl/torch_stable.html # if using CUDA 9.2pip install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html # if using CPU onlypip install onnx# For onnx-tensorflow, you may want to refer to the installation guide here: https://github.com/onnx/onnx-tensorflowgit clone https://github.com/onnx/onnx-tensorflow.gitcd onnx-tensorflowpip install -e .. If using Conda, you may want to run the following commands instead: conda activte <your virtual environment>conda install -c pytorch pytorchpip install tensorflow==1.15.0pip install onnx# For onnx-tensorflow, you may want to refer to the installation guide here: https://github.com/onnx/onnx-tensorflowgit clone https://github.com/onnx/onnx-tensorflow.gitcd onnx-tensorflowpip install -e .. I find that installing TensorFlow, ONNX, and ONNX-TF using pip will ensure that the packages are compatible with one another. It is OK, however, to use other ways of installing the packages, as long as they work properly in your machine. To test that the packages have been installed correctly, you can run the following commands: pythonimport tensorflow as tfimport torchimport onnxfrom onnx_tf.backend import prepare If you do not see any error messages, it means that the packages are installed correctly, and we are good to go. In this example, I used Jupyter Notebook, but the conversion can also be done in a .py file. To install Jupyter Notebook, you can run one of the following commands: # Installing Jupyter Notebook via pippip install notebook# Installing Jupyter Notebook via Condaconda install notebook Building, training, and evaluating the example model The next thing to do is to obtain a model in PyTorch that can be used for the conversion. In this example, I generated some simulated data, and use this data for training and evaluating a simple Multilayer Perceptron (MLP) model. The following snippet shows how the installed packages are imported, and how I generated and prepared the data. I then created a class for the simple MLP model and defined the layers such that we can specify any number and size of hidden layers. I also defined a binary cross-entropy loss and Adam optimizer to be used for the computation of loss and weight updates during training. The following snippet shows this process. After building the model and defining the loss and optimizer, I trained the model for 20 epochs using the generated training set, then used the test set for evaluation. The test loss and accuracy of the model was not good, but that does not really matter here, as the main purpose here is to show how to convert a PyTorch model to TensorFlow. The snippet below shows the training and evaluation process. After training and evaluating the model, we would need to save the model, as below: Converting the model to TensorFlow Now, we need to convert the .pt file to a .onnx file using the torch.onnx.export function. There are two things we need to take note here: 1) we need to define a dummy input as one of the inputs for the export function, and 2) the dummy input needs to have the shape (1, dimension(s) of single input). For example, if the single input is an image array with the shape (number of channels, height, width), then the dummy input needs to have the shape (1, number of channels, height, width). The dummy input is needed as an input placeholder for the resulting TensorFlow model). The following snippet shows the process of exporting the PyTorch model in the ONNX format. I included the input and output names as arguments as well to make it easier for inference in TensorFlow. After getting the .onnx file, we would need to use the prepare() function in ONNX-TF’s backend module to convert the model from ONNX to TensorFlow. Doing inference in TensorFlow Here comes the fun part, which is to see if the resultant TensorFlow model can do inference as intended. Loading a TensorFlow model from a .pb file can be done by defining the following function. With the function to load the model defined, we need to start a TensorFlow graph session, specify the placeholders for the input and output, and feed an input into the session. The output of the snippet above would look like below. The names of the placeholders correspond to those specified in the torch.onnx.export function (indicated in bold). (<tf.Tensor 'Const:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'Const_1:0' shape=(50, 20) dtype=float32>,)(<tf.Tensor 'Const_2:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'Const_3:0' shape=(50, 50) dtype=float32>,)(<tf.Tensor 'Const_4:0' shape=(1,) dtype=float32>,)(<tf.Tensor 'Const_5:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'input:0' shape=(1, 20) dtype=float32>,)(<tf.Tensor 'flatten/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten/Reshape:0' shape=(1, 20) dtype=float32>,)(<tf.Tensor 'transpose/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose:0' shape=(20, 50) dtype=float32>,)(<tf.Tensor 'MatMul:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_1/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_1:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'add:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'Relu:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'flatten_1/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten_1/Reshape:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'transpose_1/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose_1:0' shape=(50, 50) dtype=float32>,)(<tf.Tensor 'MatMul_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_2/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_2:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_3/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_3:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'add_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'Relu_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'flatten_2/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten_2/Reshape:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'transpose_2/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose_2:0' shape=(50, 1) dtype=float32>,)(<tf.Tensor 'MatMul_2:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'mul_4/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_4:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'mul_5/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_5:0' shape=(1,) dtype=float32>,)(<tf.Tensor 'add_2:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'output:0' shape=(1, 1) dtype=float32>,) If all goes well, the result of print(output) should match that of print(dummy_output) in the earlier step. Conclusion ONNX can be pretty straightforward, provided that your model is not too complicated. The steps in this example would work for deep learning models with single input and output. For models with multiple inputs and/or outputs, it would be more challenging to convert them via ONNX. As such, an example to convert multiple input/output models would have to be done in another article, unless there are new versions of ONNX later on that can handle such models. The Jupyter notebook containing all the codes can be found here.
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 901, "s": 185, "text": "TensorFlow and PyTorch are two of the more popular frameworks out there for deep learning. There are people who prefer TensorFlow for support in terms of deployment, and there are those who prefer PyTorch because of the flexibility in model building and training without the difficulties faced in using TensorFlow. The downside of using PyTorch is that the model built and trained using this framework cannot be deployed into production. (Update in Dec 2019: It is claimed that later versions of PyTorch have better support for deployment, but I believe that is something else to be explored.) To address the issue of deploying models built using PyTorch, one solution is to use ONNX (Open Neural Network Exchange)." }, { "code": null, "e": 1336, "s": 901, "text": "As explained in ONNX’s About page, ONNX is like a bridge that links the various deep learning frameworks together. To this end, the ONNX tool enables the conversion of models from one framework to another. Up to the time of this writing, ONNX is limited to simpler model structures, but there may be further additions later on. This article will illustrate how a simple deep learning model can be converted from PyTorch to TensorFlow." }, { "code": null, "e": 1370, "s": 1336, "text": "Installing the necessary packages" }, { "code": null, "e": 1782, "s": 1370, "text": "To start off, we would need to install PyTorch, TensorFlow, ONNX, and ONNX-TF (the package to convert ONNX models to TensorFlow). If using virtualenv in Linux, you could run the command below (replace tensorflow with tensorflow-gpu if you have NVidia CUDA installed). Do note that as of Dec 2019, ONNX does not work with TensorFlow 2.0 yet, so please take note of the version of the TensorFlow that you install." }, { "code": null, "e": 2495, "s": 1782, "text": "source <your virtual environment>/bin/activatepip install tensorflow==1.15.0# For PyTorch, choose one of the following (refer to https://pytorch.org/get-started/locally/ for further details)pip install torch torchvision # if using CUDA 10.1pip install torch==1.3.1+cu92 torchvision==0.4.2+cu92 -f https://download.pytorch.org/whl/torch_stable.html # if using CUDA 9.2pip install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html # if using CPU onlypip install onnx# For onnx-tensorflow, you may want to refer to the installation guide here: https://github.com/onnx/onnx-tensorflowgit clone https://github.com/onnx/onnx-tensorflow.gitcd onnx-tensorflowpip install -e .." }, { "code": null, "e": 2563, "s": 2495, "text": "If using Conda, you may want to run the following commands instead:" }, { "code": null, "e": 2886, "s": 2563, "text": "conda activte <your virtual environment>conda install -c pytorch pytorchpip install tensorflow==1.15.0pip install onnx# For onnx-tensorflow, you may want to refer to the installation guide here: https://github.com/onnx/onnx-tensorflowgit clone https://github.com/onnx/onnx-tensorflow.gitcd onnx-tensorflowpip install -e .." }, { "code": null, "e": 3124, "s": 2886, "text": "I find that installing TensorFlow, ONNX, and ONNX-TF using pip will ensure that the packages are compatible with one another. It is OK, however, to use other ways of installing the packages, as long as they work properly in your machine." }, { "code": null, "e": 3217, "s": 3124, "text": "To test that the packages have been installed correctly, you can run the following commands:" }, { "code": null, "e": 3305, "s": 3217, "text": "pythonimport tensorflow as tfimport torchimport onnxfrom onnx_tf.backend import prepare" }, { "code": null, "e": 3418, "s": 3305, "text": "If you do not see any error messages, it means that the packages are installed correctly, and we are good to go." }, { "code": null, "e": 3583, "s": 3418, "text": "In this example, I used Jupyter Notebook, but the conversion can also be done in a .py file. To install Jupyter Notebook, you can run one of the following commands:" }, { "code": null, "e": 3702, "s": 3583, "text": "# Installing Jupyter Notebook via pippip install notebook# Installing Jupyter Notebook via Condaconda install notebook" }, { "code": null, "e": 3755, "s": 3702, "text": "Building, training, and evaluating the example model" }, { "code": null, "e": 4097, "s": 3755, "text": "The next thing to do is to obtain a model in PyTorch that can be used for the conversion. In this example, I generated some simulated data, and use this data for training and evaluating a simple Multilayer Perceptron (MLP) model. The following snippet shows how the installed packages are imported, and how I generated and prepared the data." }, { "code": null, "e": 4410, "s": 4097, "text": "I then created a class for the simple MLP model and defined the layers such that we can specify any number and size of hidden layers. I also defined a binary cross-entropy loss and Adam optimizer to be used for the computation of loss and weight updates during training. The following snippet shows this process." }, { "code": null, "e": 4814, "s": 4410, "text": "After building the model and defining the loss and optimizer, I trained the model for 20 epochs using the generated training set, then used the test set for evaluation. The test loss and accuracy of the model was not good, but that does not really matter here, as the main purpose here is to show how to convert a PyTorch model to TensorFlow. The snippet below shows the training and evaluation process." }, { "code": null, "e": 4898, "s": 4814, "text": "After training and evaluating the model, we would need to save the model, as below:" }, { "code": null, "e": 4933, "s": 4898, "text": "Converting the model to TensorFlow" }, { "code": null, "e": 5707, "s": 4933, "text": "Now, we need to convert the .pt file to a .onnx file using the torch.onnx.export function. There are two things we need to take note here: 1) we need to define a dummy input as one of the inputs for the export function, and 2) the dummy input needs to have the shape (1, dimension(s) of single input). For example, if the single input is an image array with the shape (number of channels, height, width), then the dummy input needs to have the shape (1, number of channels, height, width). The dummy input is needed as an input placeholder for the resulting TensorFlow model). The following snippet shows the process of exporting the PyTorch model in the ONNX format. I included the input and output names as arguments as well to make it easier for inference in TensorFlow." }, { "code": null, "e": 5855, "s": 5707, "text": "After getting the .onnx file, we would need to use the prepare() function in ONNX-TF’s backend module to convert the model from ONNX to TensorFlow." }, { "code": null, "e": 5885, "s": 5855, "text": "Doing inference in TensorFlow" }, { "code": null, "e": 6081, "s": 5885, "text": "Here comes the fun part, which is to see if the resultant TensorFlow model can do inference as intended. Loading a TensorFlow model from a .pb file can be done by defining the following function." }, { "code": null, "e": 6258, "s": 6081, "text": "With the function to load the model defined, we need to start a TensorFlow graph session, specify the placeholders for the input and output, and feed an input into the session." }, { "code": null, "e": 6428, "s": 6258, "text": "The output of the snippet above would look like below. The names of the placeholders correspond to those specified in the torch.onnx.export function (indicated in bold)." }, { "code": null, "e": 8592, "s": 6428, "text": "(<tf.Tensor 'Const:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'Const_1:0' shape=(50, 20) dtype=float32>,)(<tf.Tensor 'Const_2:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'Const_3:0' shape=(50, 50) dtype=float32>,)(<tf.Tensor 'Const_4:0' shape=(1,) dtype=float32>,)(<tf.Tensor 'Const_5:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'input:0' shape=(1, 20) dtype=float32>,)(<tf.Tensor 'flatten/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten/Reshape:0' shape=(1, 20) dtype=float32>,)(<tf.Tensor 'transpose/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose:0' shape=(20, 50) dtype=float32>,)(<tf.Tensor 'MatMul:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_1/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_1:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'add:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'Relu:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'flatten_1/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten_1/Reshape:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'transpose_1/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose_1:0' shape=(50, 50) dtype=float32>,)(<tf.Tensor 'MatMul_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_2/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_2:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'mul_3/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_3:0' shape=(50,) dtype=float32>,)(<tf.Tensor 'add_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'Relu_1:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'flatten_2/Reshape/shape:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'flatten_2/Reshape:0' shape=(1, 50) dtype=float32>,)(<tf.Tensor 'transpose_2/perm:0' shape=(2,) dtype=int32>,)(<tf.Tensor 'transpose_2:0' shape=(50, 1) dtype=float32>,)(<tf.Tensor 'MatMul_2:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'mul_4/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_4:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'mul_5/x:0' shape=() dtype=float32>,)(<tf.Tensor 'mul_5:0' shape=(1,) dtype=float32>,)(<tf.Tensor 'add_2:0' shape=(1, 1) dtype=float32>,)(<tf.Tensor 'output:0' shape=(1, 1) dtype=float32>,)" }, { "code": null, "e": 8700, "s": 8592, "text": "If all goes well, the result of print(output) should match that of print(dummy_output) in the earlier step." }, { "code": null, "e": 8711, "s": 8700, "text": "Conclusion" }, { "code": null, "e": 9169, "s": 8711, "text": "ONNX can be pretty straightforward, provided that your model is not too complicated. The steps in this example would work for deep learning models with single input and output. For models with multiple inputs and/or outputs, it would be more challenging to convert them via ONNX. As such, an example to convert multiple input/output models would have to be done in another article, unless there are new versions of ONNX later on that can handle such models." } ]
T-SQL - SELECT Statement
SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets. Following is the basic syntax of SELECT statement − SELECT column1, column2, columnN FROM table_name; Where, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax − SELECT * FROM table_name; Consider the CUSTOMERS table having the following records − ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table − SELECT ID, NAME, SALARY FROM CUSTOMERS; The above command will produce the following output. ID NAME SALARY 1 Ramesh 2000.00 2 Khilan 1500.00 3 kaushik 2000.00 4 Chaitali 6500.00 5 Hardik 8500.00 6 Komal 4500.00 7 Muffy 10000.00 If you want to fetch all the fields of CUSTOMERS table, then use the following query − SELECT * FROM CUSTOMERS; The above will produce the following output. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2228, "s": 2060, "text": "SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets." }, { "code": null, "e": 2280, "s": 2228, "text": "Following is the basic syntax of SELECT statement −" }, { "code": null, "e": 2331, "s": 2280, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 2515, "s": 2331, "text": "Where, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −" }, { "code": null, "e": 2542, "s": 2515, "text": "SELECT * FROM table_name;\n" }, { "code": null, "e": 2602, "s": 2542, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 3035, "s": 2602, "text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n" }, { "code": null, "e": 3161, "s": 3035, "text": "Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table −" }, { "code": null, "e": 3202, "s": 3161, "text": "SELECT ID, NAME, SALARY FROM CUSTOMERS; " }, { "code": null, "e": 3255, "s": 3202, "text": "The above command will produce the following output." }, { "code": null, "e": 3472, "s": 3255, "text": "ID NAME SALARY \n1 Ramesh 2000.00 \n2 Khilan 1500.00 \n3 kaushik 2000.00 \n4 Chaitali 6500.00 \n5 Hardik 8500.00 \n6 Komal 4500.00 \n7 Muffy 10000.00 \n" }, { "code": null, "e": 3559, "s": 3472, "text": "If you want to fetch all the fields of CUSTOMERS table, then use the following query −" }, { "code": null, "e": 3584, "s": 3559, "text": "SELECT * FROM CUSTOMERS;" }, { "code": null, "e": 3629, "s": 3584, "text": "The above will produce the following output." }, { "code": null, "e": 4070, "s": 3629, "text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n" }, { "code": null, "e": 4103, "s": 4070, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4118, "s": 4103, "text": " Nishant Malik" }, { "code": null, "e": 4153, "s": 4118, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4168, "s": 4153, "text": " Nishant Malik" }, { "code": null, "e": 4203, "s": 4168, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4218, "s": 4203, "text": " Nishant Malik" }, { "code": null, "e": 4251, "s": 4218, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 4265, "s": 4251, "text": " Asif Hussain" }, { "code": null, "e": 4300, "s": 4265, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4315, "s": 4300, "text": " Nishant Malik" }, { "code": null, "e": 4350, "s": 4315, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4364, "s": 4350, "text": " Asif Hussain" }, { "code": null, "e": 4371, "s": 4364, "text": " Print" }, { "code": null, "e": 4382, "s": 4371, "text": " Add Notes" } ]
Powershell - Check Folder Existence
Test-Path cmdlet is used to check existence of a folder. In this example, we're having a folder test in D:\temp directory Type the following command in PowerShell ISE Console Test-Path D:\temp\test You can see following output in PowerShell console. Test-Path D:\temp\test True In this example, we're not having a folder named test2 in D:\temp directory Type the following command in PowerShell ISE Console Test-Path D:\temp\test2 You can see following output in PowerShell console. Test-Path D:\temp\test2 False 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2091, "s": 2034, "text": "Test-Path cmdlet is used to check existence of a folder." }, { "code": null, "e": 2156, "s": 2091, "text": "In this example, we're having a folder test in D:\\temp directory" }, { "code": null, "e": 2209, "s": 2156, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2232, "s": 2209, "text": "Test-Path D:\\temp\\test" }, { "code": null, "e": 2284, "s": 2232, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2313, "s": 2284, "text": "Test-Path D:\\temp\\test\nTrue\n" }, { "code": null, "e": 2389, "s": 2313, "text": "In this example, we're not having a folder named test2 in D:\\temp directory" }, { "code": null, "e": 2442, "s": 2389, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2466, "s": 2442, "text": "Test-Path D:\\temp\\test2" }, { "code": null, "e": 2518, "s": 2466, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2549, "s": 2518, "text": "Test-Path D:\\temp\\test2\nFalse\n" }, { "code": null, "e": 2584, "s": 2549, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2605, "s": 2584, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2640, "s": 2605, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2653, "s": 2640, "text": " Vijay Saini" }, { "code": null, "e": 2690, "s": 2653, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2702, "s": 2690, "text": " Fettah Ben" }, { "code": null, "e": 2709, "s": 2702, "text": " Print" }, { "code": null, "e": 2720, "s": 2709, "text": " Add Notes" } ]
Java Inner Class (Nested Class)
In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable. To access the inner class, create an object of the outer class, and then create an object of the inner class: class OuterClass { int x = 10; class InnerClass { int y = 5; } } public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.y + myOuter.x); } } // Outputs 15 (5 + 10) Try it Yourself » Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to access the inner class, declare the class as private: class OuterClass { int x = 10; private class InnerClass { int y = 5; } } public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.y + myOuter.x); } } If you try to access a private inner class from an outside class, an error occurs: Try it Yourself » An inner class can also be static, which means that you can access it without creating an object of the outer class: class OuterClass { int x = 10; static class InnerClass { int y = 5; } } public class Main { public static void main(String[] args) { OuterClass.InnerClass myInner = new OuterClass.InnerClass(); System.out.println(myInner.y); } } // Outputs 5 Try it Yourself » Note: just like static attributes and methods, a static inner class does not have access to members of the outer class. One advantage of inner classes, is that they can access attributes and methods of the outer class: class OuterClass { int x = 10; class InnerClass { public int myInnerMethod() { return x; } } } public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.myInnerMethod()); } } // Outputs 10 Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 198, "s": 0, "text": "In Java, it is also possible to nest classes (a class within a class). The purpose \nof nested classes is to group classes that belong together, which makes your code more readable and maintainable." }, { "code": null, "e": 308, "s": 198, "text": "To access the inner class, create an object of the outer class, and then create an object of the inner class:" }, { "code": null, "e": 633, "s": 308, "text": "class OuterClass {\n int x = 10;\n\n class InnerClass {\n int y = 5;\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n OuterClass myOuter = new OuterClass();\n OuterClass.InnerClass myInner = myOuter.new InnerClass();\n System.out.println(myInner.y + myOuter.x);\n }\n}\n\n// Outputs 15 (5 + 10)\n \n" }, { "code": null, "e": 653, "s": 633, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 816, "s": 653, "text": "Unlike a \"regular\" class, an inner class can be private or protected. \nIf you don't want outside objects to access the inner class, declare \nthe class as private:" }, { "code": null, "e": 1125, "s": 816, "text": "class OuterClass {\n int x = 10;\n\n private class InnerClass {\n int y = 5;\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n OuterClass myOuter = new OuterClass();\n OuterClass.InnerClass myInner = myOuter.new InnerClass();\n System.out.println(myInner.y + myOuter.x);\n }\n}\n \n" }, { "code": null, "e": 1208, "s": 1125, "text": "If you try to access a private inner class from an outside class, an error occurs:" }, { "code": null, "e": 1228, "s": 1208, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1346, "s": 1228, "text": "An inner class can also be static, which means that you can access it without \ncreating an object of the outer class:" }, { "code": null, "e": 1616, "s": 1346, "text": "class OuterClass {\n int x = 10;\n\n static class InnerClass {\n int y = 5;\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n OuterClass.InnerClass myInner = new OuterClass.InnerClass();\n System.out.println(myInner.y);\n }\n}\n\n// Outputs 5\n \n" }, { "code": null, "e": 1636, "s": 1616, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1756, "s": 1636, "text": "Note: just like static attributes and methods, a static inner class does not have access to members of the outer class." }, { "code": null, "e": 1855, "s": 1756, "text": "One advantage of inner classes, is that they can access attributes and methods of the outer class:" }, { "code": null, "e": 2211, "s": 1855, "text": "class OuterClass {\n int x = 10;\n\n class InnerClass {\n public int myInnerMethod() {\n return x;\n }\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n OuterClass myOuter = new OuterClass();\n OuterClass.InnerClass myInner = myOuter.new InnerClass();\n System.out.println(myInner.myInnerMethod());\n }\n}\n\n// Outputs 10\n" }, { "code": null, "e": 2231, "s": 2211, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2264, "s": 2231, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2306, "s": 2264, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2413, "s": 2306, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2432, "s": 2413, "text": "help@w3schools.com" } ]
How to Create the most Awesome Development Setup for Data Science using Atom? | by Rahul Agarwal | Towards Data Science
Before I even begin this article, let me just say that I love iPython Notebooks, and Atom is not an alternative to Jupyter in any way. Notebooks provide me an interface where I have to think of “Coding one code block at a time,” as I like to call it, and it helps me to think more clearly while helping me make my code more modular. Yet, Jupyter is not suitable for some tasks in its present form. And the most prominent is when I have to work with .py files. And one will need to work with .py files whenever they want to push your code to production or change other people’s code. So, until now, I used sublime text to edit Python files, and I found it excellent. But recently, when I looked at the Atom editor, my loyalties seemed to shift when I saw the multiple out of the box options provided by it. Now, the real power to Atom comes from the various packages you can install. In this post, I will talk about the packages that help make Atom just the most hackable and wholesome development environment ever. Before we even begin, we need to install Atom. You can do it from the main website here. The installation process is pretty simple, whatever your platform is. For Linux, I just downloaded the .deb file and double-clicked it. Once you have installed Atom, You can look at doing some tweaks: Open Core settings in Atom using Ctrl+Shift+P and typing settings therein. This Ctrl+Shift+P command is going to be one of the most important commands in Atom as it lets you navigate and run a lot of commands. Now go to the Editor menu and Uncheck “Soft Tabs”. This is done so that TAB key registers as a TAB and not two spaces. If you want you can also activate “Soft Wrap” which wraps the text if the text exceeds the window width. Now, as we have Atom installed, we can look at some of the most awesome packages it provides. And the most important of them is GitHub. Are you fed up with leaving your text editor to use terminal every time you push a commit to Github? If your answer is yes, Atom solves this very problem by letting you push commits without you ever leaving the text editor window. This is one of the main features that pushed me towards Atom from Sublime Text. I like how this functionality comes preloaded with Atom and it doesn’t take much time to set it up. To start using it, click on the GitHub link in the right bottom of the Atom screen, and the Atom screen will prompt you to log in to your Github to provide access. It is a one-time setup, and once you log in and give the token generated to Atom, you will be able to push your commits from the Atom screen itself without navigating to the terminal window. The process to push a commit is: Change any file or multiple files. Click on Git on the bottom right corner. Stage the Changes Write a commit message. Click on Push in the bottom right corner. And we are done:) Below, I am pushing a very simple commit to Github, where I add a title to my Markdown file. Its a GIF file, so it might take some time to load. I am always torn between the medium editor vs. Markdown whenever I write blog posts for my site. For one, I prefer using Markdown when I have to use Math symbols for my post or have to use custom HTML. But, I also like the Medium editor as it is WYSIWYG(What You See Is What You Get). And with Atom, I have finally found the perfect markdown editor for me, which provides me with Markdown as well as WYSIWYG. And it has now become a default option for me to create any README.md files for GitHub. Using Markdown in Atom is again a piece of cake and is activated by default. To see a live preview with Markdown in Atom: Use Ctrl+Shift+M to open Markdown Preview Pane. Whatever changes you do in the document will reflect near real-time in the preview window. Till now, we haven’t installed any new package to Atom, so let’s install an elementary package as our first package. This package is called minimap, and it is something that I like to have from my Sublime Text days. It lets you have a side panel where you can click and reach any part of the code. Pretty useful for large files. To install a package, you can go to settings and click on Install Packages. Ctrl_Shift+P > Settings > + Install > Minimap> Install Once you install the package, you can see the minimap on the side of your screen. An editor is never really complete until it provides you with some autocomplete options for your favorite language. Atom integrates well with Kite, which tries to integrate AI and autocomplete. So, to enable autocomplete with Kite, we can use the package named autocomplete-python in Atom. The install steps remain the same as before. i.e. Ctrl+Shift+P > Settings > + Install > autocomplete-python> Install. You will also see the option of using Kite along with it. I usually end up using Kite instead of Jedi(Another autocomplete option). This is how it looks when you work on a Python document with Kite autocompletion. Want to run Python also in your Atom Editor with any Jupyter Kernel? There is a way for that too. We just need to install “Hydrogen” using the same method as before. Once Hydrogen is installed you can use it by: Run the command on which your cursor is on using Ctrl+Enter. Select any Kernel from the Kernel Selection Screen. I select pyt kernel from the list. Now I can continue working in pyt kernel. Sometimes it might happen that you don’t see an environment/kernel in Atom. In such cases, you can install ipykernel to make that kernel visible to Jupyter as well as Atom. Here is how to make a new kernel and make it visible in Jupyter/Atom: conda create -n exampleenv python=3.7conda activate exampleenvconda install -c anaconda ipykernelpython -m ipykernel install --user --name=exampleenv Once you run these commands, your kernel will be installed. You can now update the Atom’s kernel list by using: Ctrl+Shift+P >Hydrogen: Update Kernels And your kernel should now be available in your Atom editor. Stack Overflow is an integral part of any developer’s life. But you know what the hassle is? To leave the coding environment and go to Chrome to search for every simple thing you need to do. And we end up doing it back and forth throughout the day. So, what if we can access Stack Overflow from Atom? You can do precisely that through the “ask-stack” package, which lets one search for questions on SO. We can access it using Ctrl+Alt+A Some other honorable mentions of packages you could use are: Teletype: Do Pair Coding. Linter: Checks code for Stylistic and Programmatic errors. To enable linting in Python, You can use “linter” and “python-linters”. Highlight Selected: Highlight all occurrences of a text by double-clicking or selecting the text with a cursor. Atom-File-Icons: Provides you with file icons in the left side tree view. Looks much better than before, right? In this post, I talked about how I use Atom in my Python Development flow. There are a plethora of other packages in Atom which you may like, and you can look at them to make your environment even more customizable. Or one can even write their own packages as well as Atom is called as the “Most Hackable Editor”. If you want to learn about Python and not exactly a Python editor, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out. Also, here are my course recommendations to become a Data Scientist in 2020. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 380, "s": 47, "text": "Before I even begin this article, let me just say that I love iPython Notebooks, and Atom is not an alternative to Jupyter in any way. Notebooks provide me an interface where I have to think of “Coding one code block at a time,” as I like to call it, and it helps me to think more clearly while helping me make my code more modular." }, { "code": null, "e": 853, "s": 380, "text": "Yet, Jupyter is not suitable for some tasks in its present form. And the most prominent is when I have to work with .py files. And one will need to work with .py files whenever they want to push your code to production or change other people’s code. So, until now, I used sublime text to edit Python files, and I found it excellent. But recently, when I looked at the Atom editor, my loyalties seemed to shift when I saw the multiple out of the box options provided by it." }, { "code": null, "e": 1062, "s": 853, "text": "Now, the real power to Atom comes from the various packages you can install. In this post, I will talk about the packages that help make Atom just the most hackable and wholesome development environment ever." }, { "code": null, "e": 1352, "s": 1062, "text": "Before we even begin, we need to install Atom. You can do it from the main website here. The installation process is pretty simple, whatever your platform is. For Linux, I just downloaded the .deb file and double-clicked it. Once you have installed Atom, You can look at doing some tweaks:" }, { "code": null, "e": 1562, "s": 1352, "text": "Open Core settings in Atom using Ctrl+Shift+P and typing settings therein. This Ctrl+Shift+P command is going to be one of the most important commands in Atom as it lets you navigate and run a lot of commands." }, { "code": null, "e": 1786, "s": 1562, "text": "Now go to the Editor menu and Uncheck “Soft Tabs”. This is done so that TAB key registers as a TAB and not two spaces. If you want you can also activate “Soft Wrap” which wraps the text if the text exceeds the window width." }, { "code": null, "e": 1922, "s": 1786, "text": "Now, as we have Atom installed, we can look at some of the most awesome packages it provides. And the most important of them is GitHub." }, { "code": null, "e": 2153, "s": 1922, "text": "Are you fed up with leaving your text editor to use terminal every time you push a commit to Github? If your answer is yes, Atom solves this very problem by letting you push commits without you ever leaving the text editor window." }, { "code": null, "e": 2333, "s": 2153, "text": "This is one of the main features that pushed me towards Atom from Sublime Text. I like how this functionality comes preloaded with Atom and it doesn’t take much time to set it up." }, { "code": null, "e": 2688, "s": 2333, "text": "To start using it, click on the GitHub link in the right bottom of the Atom screen, and the Atom screen will prompt you to log in to your Github to provide access. It is a one-time setup, and once you log in and give the token generated to Atom, you will be able to push your commits from the Atom screen itself without navigating to the terminal window." }, { "code": null, "e": 2721, "s": 2688, "text": "The process to push a commit is:" }, { "code": null, "e": 2756, "s": 2721, "text": "Change any file or multiple files." }, { "code": null, "e": 2797, "s": 2756, "text": "Click on Git on the bottom right corner." }, { "code": null, "e": 2815, "s": 2797, "text": "Stage the Changes" }, { "code": null, "e": 2839, "s": 2815, "text": "Write a commit message." }, { "code": null, "e": 2881, "s": 2839, "text": "Click on Push in the bottom right corner." }, { "code": null, "e": 2899, "s": 2881, "text": "And we are done:)" }, { "code": null, "e": 3044, "s": 2899, "text": "Below, I am pushing a very simple commit to Github, where I add a title to my Markdown file. Its a GIF file, so it might take some time to load." }, { "code": null, "e": 3541, "s": 3044, "text": "I am always torn between the medium editor vs. Markdown whenever I write blog posts for my site. For one, I prefer using Markdown when I have to use Math symbols for my post or have to use custom HTML. But, I also like the Medium editor as it is WYSIWYG(What You See Is What You Get). And with Atom, I have finally found the perfect markdown editor for me, which provides me with Markdown as well as WYSIWYG. And it has now become a default option for me to create any README.md files for GitHub." }, { "code": null, "e": 3663, "s": 3541, "text": "Using Markdown in Atom is again a piece of cake and is activated by default. To see a live preview with Markdown in Atom:" }, { "code": null, "e": 3711, "s": 3663, "text": "Use Ctrl+Shift+M to open Markdown Preview Pane." }, { "code": null, "e": 3802, "s": 3711, "text": "Whatever changes you do in the document will reflect near real-time in the preview window." }, { "code": null, "e": 4131, "s": 3802, "text": "Till now, we haven’t installed any new package to Atom, so let’s install an elementary package as our first package. This package is called minimap, and it is something that I like to have from my Sublime Text days. It lets you have a side panel where you can click and reach any part of the code. Pretty useful for large files." }, { "code": null, "e": 4262, "s": 4131, "text": "To install a package, you can go to settings and click on Install Packages. Ctrl_Shift+P > Settings > + Install > Minimap> Install" }, { "code": null, "e": 4344, "s": 4262, "text": "Once you install the package, you can see the minimap on the side of your screen." }, { "code": null, "e": 4538, "s": 4344, "text": "An editor is never really complete until it provides you with some autocomplete options for your favorite language. Atom integrates well with Kite, which tries to integrate AI and autocomplete." }, { "code": null, "e": 4966, "s": 4538, "text": "So, to enable autocomplete with Kite, we can use the package named autocomplete-python in Atom. The install steps remain the same as before. i.e. Ctrl+Shift+P > Settings > + Install > autocomplete-python> Install. You will also see the option of using Kite along with it. I usually end up using Kite instead of Jedi(Another autocomplete option). This is how it looks when you work on a Python document with Kite autocompletion." }, { "code": null, "e": 5178, "s": 4966, "text": "Want to run Python also in your Atom Editor with any Jupyter Kernel? There is a way for that too. We just need to install “Hydrogen” using the same method as before. Once Hydrogen is installed you can use it by:" }, { "code": null, "e": 5239, "s": 5178, "text": "Run the command on which your cursor is on using Ctrl+Enter." }, { "code": null, "e": 5326, "s": 5239, "text": "Select any Kernel from the Kernel Selection Screen. I select pyt kernel from the list." }, { "code": null, "e": 5368, "s": 5326, "text": "Now I can continue working in pyt kernel." }, { "code": null, "e": 5541, "s": 5368, "text": "Sometimes it might happen that you don’t see an environment/kernel in Atom. In such cases, you can install ipykernel to make that kernel visible to Jupyter as well as Atom." }, { "code": null, "e": 5611, "s": 5541, "text": "Here is how to make a new kernel and make it visible in Jupyter/Atom:" }, { "code": null, "e": 5761, "s": 5611, "text": "conda create -n exampleenv python=3.7conda activate exampleenvconda install -c anaconda ipykernelpython -m ipykernel install --user --name=exampleenv" }, { "code": null, "e": 5873, "s": 5761, "text": "Once you run these commands, your kernel will be installed. You can now update the Atom’s kernel list by using:" }, { "code": null, "e": 5912, "s": 5873, "text": "Ctrl+Shift+P >Hydrogen: Update Kernels" }, { "code": null, "e": 5973, "s": 5912, "text": "And your kernel should now be available in your Atom editor." }, { "code": null, "e": 6410, "s": 5973, "text": "Stack Overflow is an integral part of any developer’s life. But you know what the hassle is? To leave the coding environment and go to Chrome to search for every simple thing you need to do. And we end up doing it back and forth throughout the day. So, what if we can access Stack Overflow from Atom? You can do precisely that through the “ask-stack” package, which lets one search for questions on SO. We can access it using Ctrl+Alt+A" }, { "code": null, "e": 6471, "s": 6410, "text": "Some other honorable mentions of packages you could use are:" }, { "code": null, "e": 6497, "s": 6471, "text": "Teletype: Do Pair Coding." }, { "code": null, "e": 6628, "s": 6497, "text": "Linter: Checks code for Stylistic and Programmatic errors. To enable linting in Python, You can use “linter” and “python-linters”." }, { "code": null, "e": 6740, "s": 6628, "text": "Highlight Selected: Highlight all occurrences of a text by double-clicking or selecting the text with a cursor." }, { "code": null, "e": 6852, "s": 6740, "text": "Atom-File-Icons: Provides you with file icons in the left side tree view. Looks much better than before, right?" }, { "code": null, "e": 6927, "s": 6852, "text": "In this post, I talked about how I use Atom in my Python Development flow." }, { "code": null, "e": 7166, "s": 6927, "text": "There are a plethora of other packages in Atom which you may like, and you can look at them to make your environment even more customizable. Or one can even write their own packages as well as Atom is called as the “Most Hackable Editor”." }, { "code": null, "e": 7440, "s": 7166, "text": "If you want to learn about Python and not exactly a Python editor, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out. Also, here are my course recommendations to become a Data Scientist in 2020." }, { "code": null, "e": 7683, "s": 7440, "text": "I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
Comprehending the ‘Comprehensions’ in Python | by Parul Pandey | Towards Data Science
“Good code is its own best documentation” — Steve McConnell In my last article, I explained the concept of Lambda, Map, Filter, and Reduce functions in Python, which are based on the Functional Programming Paradigm. I also touched upon the idea of List Comprehensions, which are considered as a substitute for the lambda function. This entire article covers the essentials of comprehensions and their various forms, in detail. Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced us to the concept of list comprehensions, and Python 3.0 took it further by including the dictionary and set comprehensions. Why are the comprehensions so powerful? We shall try and understand this with an example. We all know Python offers various ways to express a list. For instance: One can either explicitly write the whole things as: squares = [0, 1, 4, 9,16,25] Or, write a for loop to create a list: squares = []for num in range(6): squares.append(num*num) Another way to create a list is by using a single line of code. squares = [num*num for num in range(6)] This one-liner above is called a List Comprehension and is a convenient way to create a list. It removes the dependence on loops and makes the code compact. The next section further goes deeper into the concept of the list and other types comprehensions provided in Python 3. List comprehension is a way to define and create lists in Python in a concise way. In most cases, list comprehensions let us create lists in a single line of code without worrying about initializing lists or setting up loops. A list comprehension consists of the following parts: Say, we need to find the squares of the first five even numbers. As seen in the previous section, there are two ways to do this: with an explicit for-loop or with a list comprehension. Let’s try with both. Using For Loop even_squares = []>>> for num in range(11):... if num%2 == 0:... even_squares.append(num * num)>>> even_squares[0, 4, 16, 36, 64, 100] Using List Comprehensions even_squares = [num * num for num in range(11) if num%2 == 0]even_squares[0, 4, 16, 36, 64, 100] If we look closely, it can be seen that a list comprehension can be created by merely rearranging a For loop. List comprehensions are Python’s way of implementing the notation for sets as used in mathematics. Let’s try and see some more examples of creating lists with the help of List Comprehensions. A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. We usually write such a triplet as (a,b,c), for instance (3,4,5). [(a,b,c) for a in range(1,30) for b in range(1,30) for c in range(1,30)if a**2 + b**2 == c**2][(3, 4, 5), (4, 3, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 6, 10), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 5, 13), (12, 9, 15), (12, 16, 20), (15, 8, 17), (15, 20, 25),(16, 12, 20), (20, 15, 25),(20, 21, 29), (21, 20, 29), (24, 7, 25), (24, 10, 26)] Converting lowercase letters in a string to uppercase. colors = ["pink", "white", "blue", "black", purple"][color.upper() for color in colors]['RED', 'GREEN', 'BLUE', 'PURPLE'] Swapping the first and the last name in a given list. presidents_usa = ["George Washington", "John Adams","Thomas Jefferson","James Madison","James Monroe","John Adams","Andrew Jackson"]split_names = [name.split(" ") for name in presidents_usa]swapped_list = [split_name[1] + " " + split_name[0] for split_name in split_names]swapped_list['Washington George', 'Adams John', 'Jefferson Thomas', 'Madison James', 'Monroe James', 'Adams John', 'Jackson Andrew'] If the expression contains a tuple (e.g. the (x, y) , it must be parenthesized. # Convert height from cms to feet using List Comprehension : 1 cm = 0.0328 feetheight_in_cms = [('Tom',183),('Daisy',171),('Margaret',179),('Michael',190),('Nick',165)]height_in_feet = [(height[0],round(height[1]*0.0328,1)) for height in height_in_cms]height_in_feet[('Tom', 6.0), ('Daisy', 5.6), ('Margaret', 5.9), ('Michael', 6.2), ('Nick', 5.4)] List comprehensions can also be nested to create complicated lists. For instance, we can create a matrix using only list comprehensions. Creating a 3X3 Matrix matrix = [[j * j+i for j in range(3)] for i in range(3)]matrix[[0, 1, 4], [1, 2, 5], [2, 3, 6]] A set comprehension is similar to a list comprehension but returns a set instead of a list. The syntax is slightly different in the sense that we use curly brackets instead of square brackets to create a set. Consider the following list that consists of names of people: names = [ 'Arnold', 'BILL', 'alice', 'arnold', 'MARY', 'J', 'BIll' ,'maRy'] The list includes a lot of duplicates, and there are names with only a single letter. What we want is a list that consists of names that are longer than one letter and have only the first letter capitalized. To accomplish such a task, we turn to set comprehensions. {name.capitalize() for name in names if len(name) > 1}{'Alice', 'Arnold', 'Bill', 'Mary'} Dictionary comprehensions are used when the input is in the form of a dictionary or a key: value pair. For instance, consider a dictionary where the keys represent characters, and the values denote the number of times these characters appear in a corpus. char_dict = {'A' : 4,'z': 2, 'D' : 8, 'a': 5, 'Z' : 10 } The dictionary char_dict consists of a mix of upper and lowercase letters. We want to count the total number of occurrence of the letters irrespective of their case. Let’s use a dictionary comprehension to achieve this: { k.lower() : char_dict.get(k.lower(), 0) + char_dict.get(k.upper(), 0) for k in char_dict.keys()}{'a': 9, 'z': 12, 'd': 8} List comprehensions are to lists, as generator expressions are to generators. Generator functions output values one-at-a-time from a given sequence instead of giving them all at once. Here is a nice article which explains the nitty-gritty of Generators in Python. www.dataquest.io The syntax and the way of working of generator expressions are precisely like a list comprehension except that they use round brackets instead of square ones. Let’s say we want to calculate the sum of squares of the first ten natural numbers. # Sum of first ten natural numbers using List Comprehensionssum([num**2 for num in range(11)])385 The result would have been the same had we used any other iterable and not necessarily a list. sum({num**2 for num in range(11)})385 Now, if we use a generator expression to calculate the squares of the first ten natural numbers, it would be something like this: squares = (num**2 for num in range(11))squaressquares<generator object <genexpr> at 0x1159536d8> Unlike list comprehensions, a generator expression doesn’t return a list but a generator object. To get the result, we can use the above expression with the sum function. sum(n ** 2 for n in numbers)385 See how we got rid of the redundant parenthesis in the expression above, making the code more efficient. List comprehensions are an effective way to reduce the length of the code. They also make the code more readable. But there are instances when we can comfortably do without them. It is not advisable to use comprehensions when the logic of your program is too long. The main idea of using comprehensions is to shorten the code. However, when we start packing too much of code into a single statement, we tend to compromise with the code’s readability. A for loop is a better idea in such situations. List Comprehensions Overview
[ { "code": null, "e": 232, "s": 172, "text": "“Good code is its own best documentation” — Steve McConnell" }, { "code": null, "e": 599, "s": 232, "text": "In my last article, I explained the concept of Lambda, Map, Filter, and Reduce functions in Python, which are based on the Functional Programming Paradigm. I also touched upon the idea of List Comprehensions, which are considered as a substitute for the lambda function. This entire article covers the essentials of comprehensions and their various forms, in detail." }, { "code": null, "e": 831, "s": 599, "text": "Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced us to the concept of list comprehensions, and Python 3.0 took it further by including the dictionary and set comprehensions." }, { "code": null, "e": 993, "s": 831, "text": "Why are the comprehensions so powerful? We shall try and understand this with an example. We all know Python offers various ways to express a list. For instance:" }, { "code": null, "e": 1046, "s": 993, "text": "One can either explicitly write the whole things as:" }, { "code": null, "e": 1075, "s": 1046, "text": "squares = [0, 1, 4, 9,16,25]" }, { "code": null, "e": 1114, "s": 1075, "text": "Or, write a for loop to create a list:" }, { "code": null, "e": 1174, "s": 1114, "text": "squares = []for num in range(6): squares.append(num*num)" }, { "code": null, "e": 1238, "s": 1174, "text": "Another way to create a list is by using a single line of code." }, { "code": null, "e": 1278, "s": 1238, "text": "squares = [num*num for num in range(6)]" }, { "code": null, "e": 1554, "s": 1278, "text": "This one-liner above is called a List Comprehension and is a convenient way to create a list. It removes the dependence on loops and makes the code compact. The next section further goes deeper into the concept of the list and other types comprehensions provided in Python 3." }, { "code": null, "e": 1780, "s": 1554, "text": "List comprehension is a way to define and create lists in Python in a concise way. In most cases, list comprehensions let us create lists in a single line of code without worrying about initializing lists or setting up loops." }, { "code": null, "e": 1834, "s": 1780, "text": "A list comprehension consists of the following parts:" }, { "code": null, "e": 2040, "s": 1834, "text": "Say, we need to find the squares of the first five even numbers. As seen in the previous section, there are two ways to do this: with an explicit for-loop or with a list comprehension. Let’s try with both." }, { "code": null, "e": 2055, "s": 2040, "text": "Using For Loop" }, { "code": null, "e": 2199, "s": 2055, "text": "even_squares = []>>> for num in range(11):... if num%2 == 0:... even_squares.append(num * num)>>> even_squares[0, 4, 16, 36, 64, 100]" }, { "code": null, "e": 2225, "s": 2199, "text": "Using List Comprehensions" }, { "code": null, "e": 2322, "s": 2225, "text": "even_squares = [num * num for num in range(11) if num%2 == 0]even_squares[0, 4, 16, 36, 64, 100]" }, { "code": null, "e": 2432, "s": 2322, "text": "If we look closely, it can be seen that a list comprehension can be created by merely rearranging a For loop." }, { "code": null, "e": 2531, "s": 2432, "text": "List comprehensions are Python’s way of implementing the notation for sets as used in mathematics." }, { "code": null, "e": 2624, "s": 2531, "text": "Let’s try and see some more examples of creating lists with the help of List Comprehensions." }, { "code": null, "e": 2784, "s": 2624, "text": "A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. We usually write such a triplet as (a,b,c), for instance (3,4,5)." }, { "code": null, "e": 3139, "s": 2784, "text": "[(a,b,c) for a in range(1,30) for b in range(1,30) for c in range(1,30)if a**2 + b**2 == c**2][(3, 4, 5), (4, 3, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 6, 10), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 5, 13), (12, 9, 15), (12, 16, 20), (15, 8, 17), (15, 20, 25),(16, 12, 20), (20, 15, 25),(20, 21, 29), (21, 20, 29), (24, 7, 25), (24, 10, 26)]" }, { "code": null, "e": 3194, "s": 3139, "text": "Converting lowercase letters in a string to uppercase." }, { "code": null, "e": 3316, "s": 3194, "text": "colors = [\"pink\", \"white\", \"blue\", \"black\", purple\"][color.upper() for color in colors]['RED', 'GREEN', 'BLUE', 'PURPLE']" }, { "code": null, "e": 3370, "s": 3316, "text": "Swapping the first and the last name in a given list." }, { "code": null, "e": 3775, "s": 3370, "text": "presidents_usa = [\"George Washington\", \"John Adams\",\"Thomas Jefferson\",\"James Madison\",\"James Monroe\",\"John Adams\",\"Andrew Jackson\"]split_names = [name.split(\" \") for name in presidents_usa]swapped_list = [split_name[1] + \" \" + split_name[0] for split_name in split_names]swapped_list['Washington George', 'Adams John', 'Jefferson Thomas', 'Madison James', 'Monroe James', 'Adams John', 'Jackson Andrew']" }, { "code": null, "e": 3855, "s": 3775, "text": "If the expression contains a tuple (e.g. the (x, y) , it must be parenthesized." }, { "code": null, "e": 4204, "s": 3855, "text": "# Convert height from cms to feet using List Comprehension : 1 cm = 0.0328 feetheight_in_cms = [('Tom',183),('Daisy',171),('Margaret',179),('Michael',190),('Nick',165)]height_in_feet = [(height[0],round(height[1]*0.0328,1)) for height in height_in_cms]height_in_feet[('Tom', 6.0), ('Daisy', 5.6), ('Margaret', 5.9), ('Michael', 6.2), ('Nick', 5.4)]" }, { "code": null, "e": 4341, "s": 4204, "text": "List comprehensions can also be nested to create complicated lists. For instance, we can create a matrix using only list comprehensions." }, { "code": null, "e": 4363, "s": 4341, "text": "Creating a 3X3 Matrix" }, { "code": null, "e": 4459, "s": 4363, "text": "matrix = [[j * j+i for j in range(3)] for i in range(3)]matrix[[0, 1, 4], [1, 2, 5], [2, 3, 6]]" }, { "code": null, "e": 4668, "s": 4459, "text": "A set comprehension is similar to a list comprehension but returns a set instead of a list. The syntax is slightly different in the sense that we use curly brackets instead of square brackets to create a set." }, { "code": null, "e": 4730, "s": 4668, "text": "Consider the following list that consists of names of people:" }, { "code": null, "e": 4806, "s": 4730, "text": "names = [ 'Arnold', 'BILL', 'alice', 'arnold', 'MARY', 'J', 'BIll' ,'maRy']" }, { "code": null, "e": 5072, "s": 4806, "text": "The list includes a lot of duplicates, and there are names with only a single letter. What we want is a list that consists of names that are longer than one letter and have only the first letter capitalized. To accomplish such a task, we turn to set comprehensions." }, { "code": null, "e": 5162, "s": 5072, "text": "{name.capitalize() for name in names if len(name) > 1}{'Alice', 'Arnold', 'Bill', 'Mary'}" }, { "code": null, "e": 5417, "s": 5162, "text": "Dictionary comprehensions are used when the input is in the form of a dictionary or a key: value pair. For instance, consider a dictionary where the keys represent characters, and the values denote the number of times these characters appear in a corpus." }, { "code": null, "e": 5474, "s": 5417, "text": "char_dict = {'A' : 4,'z': 2, 'D' : 8, 'a': 5, 'Z' : 10 }" }, { "code": null, "e": 5694, "s": 5474, "text": "The dictionary char_dict consists of a mix of upper and lowercase letters. We want to count the total number of occurrence of the letters irrespective of their case. Let’s use a dictionary comprehension to achieve this:" }, { "code": null, "e": 5818, "s": 5694, "text": "{ k.lower() : char_dict.get(k.lower(), 0) + char_dict.get(k.upper(), 0) for k in char_dict.keys()}{'a': 9, 'z': 12, 'd': 8}" }, { "code": null, "e": 6082, "s": 5818, "text": "List comprehensions are to lists, as generator expressions are to generators. Generator functions output values one-at-a-time from a given sequence instead of giving them all at once. Here is a nice article which explains the nitty-gritty of Generators in Python." }, { "code": null, "e": 6099, "s": 6082, "text": "www.dataquest.io" }, { "code": null, "e": 6342, "s": 6099, "text": "The syntax and the way of working of generator expressions are precisely like a list comprehension except that they use round brackets instead of square ones. Let’s say we want to calculate the sum of squares of the first ten natural numbers." }, { "code": null, "e": 6440, "s": 6342, "text": "# Sum of first ten natural numbers using List Comprehensionssum([num**2 for num in range(11)])385" }, { "code": null, "e": 6535, "s": 6440, "text": "The result would have been the same had we used any other iterable and not necessarily a list." }, { "code": null, "e": 6573, "s": 6535, "text": "sum({num**2 for num in range(11)})385" }, { "code": null, "e": 6703, "s": 6573, "text": "Now, if we use a generator expression to calculate the squares of the first ten natural numbers, it would be something like this:" }, { "code": null, "e": 6800, "s": 6703, "text": "squares = (num**2 for num in range(11))squaressquares<generator object <genexpr> at 0x1159536d8>" }, { "code": null, "e": 6971, "s": 6800, "text": "Unlike list comprehensions, a generator expression doesn’t return a list but a generator object. To get the result, we can use the above expression with the sum function." }, { "code": null, "e": 7003, "s": 6971, "text": "sum(n ** 2 for n in numbers)385" }, { "code": null, "e": 7108, "s": 7003, "text": "See how we got rid of the redundant parenthesis in the expression above, making the code more efficient." }, { "code": null, "e": 7287, "s": 7108, "text": "List comprehensions are an effective way to reduce the length of the code. They also make the code more readable. But there are instances when we can comfortably do without them." }, { "code": null, "e": 7607, "s": 7287, "text": "It is not advisable to use comprehensions when the logic of your program is too long. The main idea of using comprehensions is to shorten the code. However, when we start packing too much of code into a single statement, we tend to compromise with the code’s readability. A for loop is a better idea in such situations." } ]
Articulation Points (or Cut Vertices) in a Graph - GeeksforGeeks
19 Jan, 2022 A vertex in an undirected connected graph is an articulation point (or cut vertex) if removing it (and edges through it) disconnects the graph. Articulation points represent vulnerabilities in a connected network – single points whose failure would split the network into 2 or more components. They are useful for designing reliable networks. For a disconnected undirected graph, an articulation point is a vertex removing which increases number of connected components. Following are some example graphs with articulation points encircled with red color. How to find all articulation points in a given graph? A simple approach is to one by one remove all vertices and see if removal of a vertex causes disconnected graph. Following are steps of simple approach for connected graph.1) For every vertex v, do following .....a) Remove v from graph .....b) See if the graph remains connected (We can either use BFS or DFS) .....c) Add v back to the graphTime complexity of above method is O(V*(V+E)) for a graph represented using adjacency list. Can we do better? A O(V+E) algorithm to find all Articulation Points (APs) The idea is to use DFS (Depth First Search). In DFS, we follow vertices in tree form called DFS tree. In DFS tree, a vertex u is parent of another vertex v, if v is discovered by u (obviously v is an adjacent of u in graph). In DFS tree, a vertex u is articulation point if one of the following two conditions is true. 1) u is root of DFS tree and it has at least two children. 2) u is not root of DFS tree and it has a child v such that no vertex in subtree rooted with v has a back edge to one of the ancestors (in DFS tree) of u. Following figure shows same points as above with one additional point that a leaf in DFS Tree can never be an articulation point. We do DFS traversal of given graph with additional code to find out Articulation Points (APs). In DFS traversal, we maintain a parent[] array where parent[u] stores parent of vertex u. Among the above mentioned two cases, the first case is simple to detect. For every vertex, count children. If currently visited vertex u is root (parent[u] is NIL) and has more than two children, print it. How to handle second case? The second case is trickier. We maintain an array disc[] to store discovery time of vertices. For every node u, we need to find out the earliest visited vertex (the vertex with minimum discovery time) that can be reached from subtree rooted with u. So we maintain an additional array low[] which is defined as follows. low[u] = min(disc[u], disc[w]) where w is an ancestor of u and there is a back edge from some descendant of u to w. Following is the implementation of Tarjan’s algorithm for finding articulation points. C++ Java Python3 C# Javascript // C++ program to find articulation points in an undirected graph#include <bits/stdc++.h>using namespace std; // A recursive function that find articulation// points using DFS traversal// adj[] --> Adjacency List representation of the graph// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// low[] -- >> earliest visited vertex (the vertex with minimum// discovery time) that can be reached from subtree// rooted with current vertex// parent --> Stores the parent vertex in DFS tree// isAP[] --> Stores articulation pointsvoid APUtil(vector<int> adj[], int u, bool visited[], int disc[], int low[], int& time, int parent, bool isAP[]){ // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this for (auto v : adj[u]) { // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, time, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true;} void AP(vector<int> adj[], int V){ int disc[V] = { 0 }; int low[V]; bool visited[V] = { false }; bool isAP[V] = { false }; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (!visited[u]) APUtil(adj, u, visited, disc, low, time, par, isAP); // Printing the APs for (int u = 0; u < V; u++) if (isAP[u] == true) cout << u << " ";} // Utility function to add an edgevoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} int main(){ // Create graphs given in above diagrams cout << "Articulation points in first graph \n"; int V = 5; vector<int> adj1[V]; addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); AP(adj1, V); cout << "\nArticulation points in second graph \n"; V = 4; vector<int> adj2[V]; addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); AP(adj2, V); cout << "\nArticulation points in third graph \n"; V = 7; vector<int> adj3[V]; addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); AP(adj3, V); return 0;} // A Java program to find articulation// points in an undirected graphimport java.util.*; class Graph { static int time; static void addEdge(ArrayList<ArrayList<Integer> > adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } static void APUtil(ArrayList<ArrayList<Integer> > adj, int u, boolean visited[], int disc[], int low[], int parent, boolean isAP[]) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this for (Integer v : adj.get(u)) { // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = Math.min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = Math.min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true; } static void AP(ArrayList<ArrayList<Integer> > adj, int V) { boolean[] visited = new boolean[V]; int[] disc = new int[V]; int[] low = new int[V]; boolean[] isAP = new boolean[V]; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (visited[u] == false) APUtil(adj, u, visited, disc, low, par, isAP); for (int u = 0; u < V; u++) if (isAP[u] == true) System.out.print(u + " "); System.out.println(); } public static void main(String[] args) { // Creating first example graph int V = 5; ArrayList<ArrayList<Integer> > adj1 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj1.add(new ArrayList<Integer>()); addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); System.out.println("Articulation points in first graph"); AP(adj1, V); // Creating second example graph V = 4; ArrayList<ArrayList<Integer> > adj2 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj2.add(new ArrayList<Integer>()); addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); System.out.println("Articulation points in second graph"); AP(adj2, V); // Creating third example graph V = 7; ArrayList<ArrayList<Integer> > adj3 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj3.add(new ArrayList<Integer>()); addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); System.out.println("Articulation points in third graph"); AP(adj3, V); }} # Python program to find articulation points in an undirected graph from collections import defaultdict # This class represents an undirected graph# using adjacency list representationclass Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that find articulation points using DFS traversal u --> The vertex to be visited next visited[] --> keeps track of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree ap[] --> Store articulation points''' def APUtil(self, u, visited, ap, parent, low, disc): # Count of children in current node children = 0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False : parent[v] = u children += 1 self.APUtil(v, visited, ap, parent, low, disc) # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more children. if parent[u] == -1 and children > 1: ap[u] = True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True # Update low value of u for parent function calls elif v != parent[u]: low[u] = min(low[u], disc[v]) # The function to do DFS traversal. It uses recursive APUtil() def AP(self): # Mark all the vertices as not visited # and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float("Inf")] * (self.V) low = [float("Inf")] * (self.V) parent = [-1] * (self.V) ap = [False] * (self.V) # To store articulation points # Call the recursive helper function # to find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if visited[i] == False: self.APUtil(i, visited, ap, parent, low, disc) for index, value in enumerate (ap): if value == True: print (index,end=" ") # Create a graph given in the above diagramg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(2, 1)g1.addEdge(0, 3)g1.addEdge(3, 4) print ("\nArticulation points in first graph ")g1.AP() g2 = Graph(4)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 3)print ("\nArticulation points in second graph ")g2.AP() g3 = Graph (7)g3.addEdge(0, 1)g3.addEdge(1, 2)g3.addEdge(2, 0)g3.addEdge(1, 3)g3.addEdge(1, 4)g3.addEdge(1, 6)g3.addEdge(3, 5)g3.addEdge(4, 5)print ("\nArticulation points in third graph ")g3.AP() # This code is contributed by Neelam Yadav // A C# program to find articulation// points in an undirected graphusing System;using System.Collections.Generic; // This class represents an undirected graph// using adjacency list representationpublic class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private List<int>[] adj; int time = 0; static readonly int NIL = -1; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. adj[w].Add(v); // Add v to w's list } // A recursive function that find articulation points using DFS // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree // ap[] --> Store articulation points void APUtil(int u, bool[] visited, int[] disc, int[] low, int[] parent, bool[] ap) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this foreach(int i in adj[u]) { int v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; APUtil(v, visited, disc, low, parent, ap); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = Math.Min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) ap[u] = true; // (2) If u is not root and low value of one of its child // is more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) ap[u] = true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.Min(low[u], disc[v]); } } // The function to do DFS traversal. // It uses recursive function APUtil() void AP() { // Mark all the vertices as not visited bool[] visited = new bool[V]; int[] disc = new int[V]; int[] low = new int[V]; int[] parent = new int[V]; bool[] ap = new bool[V]; // To store articulation points // Initialize parent and visited, and // ap(articulation point) arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; ap[i] = false; } // Call the recursive helper function to find articulation // points in DFS tree rooted with vertex 'i' for (int i = 0; i < V; i++) if (visited[i] == false) APUtil(i, visited, disc, low, parent, ap); // Now ap[] contains articulation points, print them for (int i = 0; i < V; i++) if (ap[i] == true) Console.Write(i + " "); } // Driver method public static void Main(String[] args) { // Create graphs given in above diagrams Console.WriteLine("Articulation points in first graph "); Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.AP(); Console.WriteLine(); Console.WriteLine("Articulation points in Second graph"); Graph g2 = new Graph(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.AP(); Console.WriteLine(); Console.WriteLine("Articulation points in Third graph "); Graph g3 = new Graph(7); g3.addEdge(0, 1); g3.addEdge(1, 2); g3.addEdge(2, 0); g3.addEdge(1, 3); g3.addEdge(1, 4); g3.addEdge(1, 6); g3.addEdge(3, 5); g3.addEdge(4, 5); g3.AP(); }} // This code is contributed by PrinciRaj1992 <script>// A Javascript program to find articulation points in an undirected graph // This class represents an undirected graph using adjacency list// representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.NIL = -1; this.time = 0; for (let i=0; i<v; ++i) this.adj[i] = []; } //Function to add an edge into the graph addEdge(v, w) { this.adj[v].push(w); // Add w to v's list. this.adj[w].push(v); //Add v to w's list } // A recursive function that find articulation points using DFS // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree // ap[] --> Store articulation points APUtil(u, visited, disc, low, parent, ap) { // Count of children in DFS Tree let children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++this.time; // Go through all vertices adjacent to this for(let i of this.adj[u]) { let v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; this.APUtil(v, visited, disc, low, parent, ap); // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == this.NIL && children > 1) ap[u] = true; // (2) If u is not root and low value of one of its child // is more than discovery value of u. if (parent[u] != this.NIL && low[v] >= disc[u]) ap[u] = true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } } // The function to do DFS traversal. It uses recursive function APUtil() AP() { // Mark all the vertices as not visited let visited = new Array(this.V); let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); let ap = new Array(this.V); // To store articulation points // Initialize parent and visited, and ap(articulation point) // arrays for (let i = 0; i < this.V; i++) { parent[i] = this.NIL; visited[i] = false; ap[i] = false; } // Call the recursive helper function to find articulation // points in DFS tree rooted with vertex 'i' for (let i = 0; i < this.V; i++) if (visited[i] == false) this.APUtil(i, visited, disc, low, parent, ap); // Now ap[] contains articulation points, print them for (let i = 0; i < this.V; i++) if (ap[i] == true) document.write(i+" "); }} // Driver method// Create graphs given in above diagramsdocument.write("Articulation points in first graph <br>");let g1 = new Graph(5);g1.addEdge(1, 0);g1.addEdge(0, 2);g1.addEdge(2, 1);g1.addEdge(0, 3);g1.addEdge(3, 4);g1.AP();document.write("<br>"); document.write("Articulation points in Second graph <br>");let g2 = new Graph(4);g2.addEdge(0, 1);g2.addEdge(1, 2);g2.addEdge(2, 3);g2.AP();document.write("<br>"); document.write("Articulation points in Third graph <br>");let g3 = new Graph(7);g3.addEdge(0, 1);g3.addEdge(1, 2);g3.addEdge(2, 0);g3.addEdge(1, 3);g3.addEdge(1, 4);g3.addEdge(1, 6);g3.addEdge(3, 5);g3.addEdge(4, 5);g3.AP(); // This code is contributed by avanitrachhadiya2155</script> Output: Articulation points in first graph 0 3 Articulation points in second graph 1 2 Articulation points in third graph 1 Time Complexity: The above function is simple DFS with additional arrays. So time complexity is same as DFS which is O(V+E) for adjacency list representation of graph. References: https://www.cs.washington.edu/education/courses/421/04su/slides/artic.pdf http://www.slideshare.net/TraianRebedea/algorithm-design-and-complexity-course-8 http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L25-Connectivity.htmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 vthukral94 winter_soldier udaigupta19311 avanitrachhadiya2155 surindertarika1234 varshagumber28 ruhelaa48 amartyaghoshgfg germanshephered48 BFS DFS graph-connectivity Graph DFS Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26581, "s": 26553, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26925, "s": 26581, "text": "A vertex in an undirected connected graph is an articulation point (or cut vertex) if removing it (and edges through it) disconnects the graph. Articulation points represent vulnerabilities in a connected network – single points whose failure would split the network into 2 or more components. They are useful for designing reliable networks. " }, { "code": null, "e": 27053, "s": 26925, "text": "For a disconnected undirected graph, an articulation point is a vertex removing which increases number of connected components." }, { "code": null, "e": 27140, "s": 27053, "text": "Following are some example graphs with articulation points encircled with red color. " }, { "code": null, "e": 27647, "s": 27142, "text": "How to find all articulation points in a given graph? A simple approach is to one by one remove all vertices and see if removal of a vertex causes disconnected graph. Following are steps of simple approach for connected graph.1) For every vertex v, do following .....a) Remove v from graph .....b) See if the graph remains connected (We can either use BFS or DFS) .....c) Add v back to the graphTime complexity of above method is O(V*(V+E)) for a graph represented using adjacency list. Can we do better?" }, { "code": null, "e": 28237, "s": 27647, "text": "A O(V+E) algorithm to find all Articulation Points (APs) The idea is to use DFS (Depth First Search). In DFS, we follow vertices in tree form called DFS tree. In DFS tree, a vertex u is parent of another vertex v, if v is discovered by u (obviously v is an adjacent of u in graph). In DFS tree, a vertex u is articulation point if one of the following two conditions is true. 1) u is root of DFS tree and it has at least two children. 2) u is not root of DFS tree and it has a child v such that no vertex in subtree rooted with v has a back edge to one of the ancestors (in DFS tree) of u." }, { "code": null, "e": 28367, "s": 28237, "text": "Following figure shows same points as above with one additional point that a leaf in DFS Tree can never be an articulation point." }, { "code": null, "e": 28759, "s": 28367, "text": "We do DFS traversal of given graph with additional code to find out Articulation Points (APs). In DFS traversal, we maintain a parent[] array where parent[u] stores parent of vertex u. Among the above mentioned two cases, the first case is simple to detect. For every vertex, count children. If currently visited vertex u is root (parent[u] is NIL) and has more than two children, print it. " }, { "code": null, "e": 29107, "s": 28759, "text": "How to handle second case? The second case is trickier. We maintain an array disc[] to store discovery time of vertices. For every node u, we need to find out the earliest visited vertex (the vertex with minimum discovery time) that can be reached from subtree rooted with u. So we maintain an additional array low[] which is defined as follows. " }, { "code": null, "e": 29225, "s": 29107, "text": "low[u] = min(disc[u], disc[w]) \nwhere w is an ancestor of u and there is a back edge from \nsome descendant of u to w." }, { "code": null, "e": 29313, "s": 29225, "text": "Following is the implementation of Tarjan’s algorithm for finding articulation points. " }, { "code": null, "e": 29317, "s": 29313, "text": "C++" }, { "code": null, "e": 29322, "s": 29317, "text": "Java" }, { "code": null, "e": 29330, "s": 29322, "text": "Python3" }, { "code": null, "e": 29333, "s": 29330, "text": "C#" }, { "code": null, "e": 29344, "s": 29333, "text": "Javascript" }, { "code": "// C++ program to find articulation points in an undirected graph#include <bits/stdc++.h>using namespace std; // A recursive function that find articulation// points using DFS traversal// adj[] --> Adjacency List representation of the graph// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// low[] -- >> earliest visited vertex (the vertex with minimum// discovery time) that can be reached from subtree// rooted with current vertex// parent --> Stores the parent vertex in DFS tree// isAP[] --> Stores articulation pointsvoid APUtil(vector<int> adj[], int u, bool visited[], int disc[], int low[], int& time, int parent, bool isAP[]){ // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this for (auto v : adj[u]) { // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, time, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true;} void AP(vector<int> adj[], int V){ int disc[V] = { 0 }; int low[V]; bool visited[V] = { false }; bool isAP[V] = { false }; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (!visited[u]) APUtil(adj, u, visited, disc, low, time, par, isAP); // Printing the APs for (int u = 0; u < V; u++) if (isAP[u] == true) cout << u << \" \";} // Utility function to add an edgevoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} int main(){ // Create graphs given in above diagrams cout << \"Articulation points in first graph \\n\"; int V = 5; vector<int> adj1[V]; addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); AP(adj1, V); cout << \"\\nArticulation points in second graph \\n\"; V = 4; vector<int> adj2[V]; addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); AP(adj2, V); cout << \"\\nArticulation points in third graph \\n\"; V = 7; vector<int> adj3[V]; addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); AP(adj3, V); return 0;}", "e": 32605, "s": 29344, "text": null }, { "code": "// A Java program to find articulation// points in an undirected graphimport java.util.*; class Graph { static int time; static void addEdge(ArrayList<ArrayList<Integer> > adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } static void APUtil(ArrayList<ArrayList<Integer> > adj, int u, boolean visited[], int disc[], int low[], int parent, boolean isAP[]) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this for (Integer v : adj.get(u)) { // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = Math.min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = Math.min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true; } static void AP(ArrayList<ArrayList<Integer> > adj, int V) { boolean[] visited = new boolean[V]; int[] disc = new int[V]; int[] low = new int[V]; boolean[] isAP = new boolean[V]; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (visited[u] == false) APUtil(adj, u, visited, disc, low, par, isAP); for (int u = 0; u < V; u++) if (isAP[u] == true) System.out.print(u + \" \"); System.out.println(); } public static void main(String[] args) { // Creating first example graph int V = 5; ArrayList<ArrayList<Integer> > adj1 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj1.add(new ArrayList<Integer>()); addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); System.out.println(\"Articulation points in first graph\"); AP(adj1, V); // Creating second example graph V = 4; ArrayList<ArrayList<Integer> > adj2 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj2.add(new ArrayList<Integer>()); addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); System.out.println(\"Articulation points in second graph\"); AP(adj2, V); // Creating third example graph V = 7; ArrayList<ArrayList<Integer> > adj3 = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj3.add(new ArrayList<Integer>()); addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); System.out.println(\"Articulation points in third graph\"); AP(adj3, V); }}", "e": 36410, "s": 32605, "text": null }, { "code": "# Python program to find articulation points in an undirected graph from collections import defaultdict # This class represents an undirected graph# using adjacency list representationclass Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that find articulation points using DFS traversal u --> The vertex to be visited next visited[] --> keeps track of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree ap[] --> Store articulation points''' def APUtil(self, u, visited, ap, parent, low, disc): # Count of children in current node children = 0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False : parent[v] = u children += 1 self.APUtil(v, visited, ap, parent, low, disc) # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more children. if parent[u] == -1 and children > 1: ap[u] = True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True # Update low value of u for parent function calls elif v != parent[u]: low[u] = min(low[u], disc[v]) # The function to do DFS traversal. It uses recursive APUtil() def AP(self): # Mark all the vertices as not visited # and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float(\"Inf\")] * (self.V) low = [float(\"Inf\")] * (self.V) parent = [-1] * (self.V) ap = [False] * (self.V) # To store articulation points # Call the recursive helper function # to find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if visited[i] == False: self.APUtil(i, visited, ap, parent, low, disc) for index, value in enumerate (ap): if value == True: print (index,end=\" \") # Create a graph given in the above diagramg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(2, 1)g1.addEdge(0, 3)g1.addEdge(3, 4) print (\"\\nArticulation points in first graph \")g1.AP() g2 = Graph(4)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 3)print (\"\\nArticulation points in second graph \")g2.AP() g3 = Graph (7)g3.addEdge(0, 1)g3.addEdge(1, 2)g3.addEdge(2, 0)g3.addEdge(1, 3)g3.addEdge(1, 4)g3.addEdge(1, 6)g3.addEdge(3, 5)g3.addEdge(4, 5)print (\"\\nArticulation points in third graph \")g3.AP() # This code is contributed by Neelam Yadav", "e": 40004, "s": 36410, "text": null }, { "code": "// A C# program to find articulation// points in an undirected graphusing System;using System.Collections.Generic; // This class represents an undirected graph// using adjacency list representationpublic class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private List<int>[] adj; int time = 0; static readonly int NIL = -1; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. adj[w].Add(v); // Add v to w's list } // A recursive function that find articulation points using DFS // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree // ap[] --> Store articulation points void APUtil(int u, bool[] visited, int[] disc, int[] low, int[] parent, bool[] ap) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this foreach(int i in adj[u]) { int v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; APUtil(v, visited, disc, low, parent, ap); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = Math.Min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) ap[u] = true; // (2) If u is not root and low value of one of its child // is more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) ap[u] = true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.Min(low[u], disc[v]); } } // The function to do DFS traversal. // It uses recursive function APUtil() void AP() { // Mark all the vertices as not visited bool[] visited = new bool[V]; int[] disc = new int[V]; int[] low = new int[V]; int[] parent = new int[V]; bool[] ap = new bool[V]; // To store articulation points // Initialize parent and visited, and // ap(articulation point) arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; ap[i] = false; } // Call the recursive helper function to find articulation // points in DFS tree rooted with vertex 'i' for (int i = 0; i < V; i++) if (visited[i] == false) APUtil(i, visited, disc, low, parent, ap); // Now ap[] contains articulation points, print them for (int i = 0; i < V; i++) if (ap[i] == true) Console.Write(i + \" \"); } // Driver method public static void Main(String[] args) { // Create graphs given in above diagrams Console.WriteLine(\"Articulation points in first graph \"); Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.AP(); Console.WriteLine(); Console.WriteLine(\"Articulation points in Second graph\"); Graph g2 = new Graph(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.AP(); Console.WriteLine(); Console.WriteLine(\"Articulation points in Third graph \"); Graph g3 = new Graph(7); g3.addEdge(0, 1); g3.addEdge(1, 2); g3.addEdge(2, 0); g3.addEdge(1, 3); g3.addEdge(1, 4); g3.addEdge(1, 6); g3.addEdge(3, 5); g3.addEdge(4, 5); g3.AP(); }} // This code is contributed by PrinciRaj1992", "e": 44506, "s": 40004, "text": null }, { "code": "<script>// A Javascript program to find articulation points in an undirected graph // This class represents an undirected graph using adjacency list// representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.NIL = -1; this.time = 0; for (let i=0; i<v; ++i) this.adj[i] = []; } //Function to add an edge into the graph addEdge(v, w) { this.adj[v].push(w); // Add w to v's list. this.adj[w].push(v); //Add v to w's list } // A recursive function that find articulation points using DFS // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree // ap[] --> Store articulation points APUtil(u, visited, disc, low, parent, ap) { // Count of children in DFS Tree let children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++this.time; // Go through all vertices adjacent to this for(let i of this.adj[u]) { let v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; this.APUtil(v, visited, disc, low, parent, ap); // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == this.NIL && children > 1) ap[u] = true; // (2) If u is not root and low value of one of its child // is more than discovery value of u. if (parent[u] != this.NIL && low[v] >= disc[u]) ap[u] = true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } } // The function to do DFS traversal. It uses recursive function APUtil() AP() { // Mark all the vertices as not visited let visited = new Array(this.V); let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); let ap = new Array(this.V); // To store articulation points // Initialize parent and visited, and ap(articulation point) // arrays for (let i = 0; i < this.V; i++) { parent[i] = this.NIL; visited[i] = false; ap[i] = false; } // Call the recursive helper function to find articulation // points in DFS tree rooted with vertex 'i' for (let i = 0; i < this.V; i++) if (visited[i] == false) this.APUtil(i, visited, disc, low, parent, ap); // Now ap[] contains articulation points, print them for (let i = 0; i < this.V; i++) if (ap[i] == true) document.write(i+\" \"); }} // Driver method// Create graphs given in above diagramsdocument.write(\"Articulation points in first graph <br>\");let g1 = new Graph(5);g1.addEdge(1, 0);g1.addEdge(0, 2);g1.addEdge(2, 1);g1.addEdge(0, 3);g1.addEdge(3, 4);g1.AP();document.write(\"<br>\"); document.write(\"Articulation points in Second graph <br>\");let g2 = new Graph(4);g2.addEdge(0, 1);g2.addEdge(1, 2);g2.addEdge(2, 3);g2.AP();document.write(\"<br>\"); document.write(\"Articulation points in Third graph <br>\");let g3 = new Graph(7);g3.addEdge(0, 1);g3.addEdge(1, 2);g3.addEdge(2, 0);g3.addEdge(1, 3);g3.addEdge(1, 4);g3.addEdge(1, 6);g3.addEdge(3, 5);g3.addEdge(4, 5);g3.AP(); // This code is contributed by avanitrachhadiya2155</script>", "e": 48632, "s": 44506, "text": null }, { "code": null, "e": 48641, "s": 48632, "text": "Output: " }, { "code": null, "e": 48757, "s": 48641, "text": "Articulation points in first graph\n0 3\nArticulation points in second graph\n1 2\nArticulation points in third graph\n1" }, { "code": null, "e": 48925, "s": 48757, "text": "Time Complexity: The above function is simple DFS with additional arrays. So time complexity is same as DFS which is O(V+E) for adjacency list representation of graph." }, { "code": null, "e": 49304, "s": 48925, "text": "References: https://www.cs.washington.edu/education/courses/421/04su/slides/artic.pdf http://www.slideshare.net/TraianRebedea/algorithm-design-and-complexity-course-8 http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L25-Connectivity.htmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 49318, "s": 49304, "text": "princiraj1992" }, { "code": null, "e": 49329, "s": 49318, "text": "vthukral94" }, { "code": null, "e": 49344, "s": 49329, "text": "winter_soldier" }, { "code": null, "e": 49359, "s": 49344, "text": "udaigupta19311" }, { "code": null, "e": 49380, "s": 49359, "text": "avanitrachhadiya2155" }, { "code": null, "e": 49399, "s": 49380, "text": "surindertarika1234" }, { "code": null, "e": 49414, "s": 49399, "text": "varshagumber28" }, { "code": null, "e": 49424, "s": 49414, "text": "ruhelaa48" }, { "code": null, "e": 49440, "s": 49424, "text": "amartyaghoshgfg" }, { "code": null, "e": 49458, "s": 49440, "text": "germanshephered48" }, { "code": null, "e": 49462, "s": 49458, "text": "BFS" }, { "code": null, "e": 49466, "s": 49462, "text": "DFS" }, { "code": null, "e": 49485, "s": 49466, "text": "graph-connectivity" }, { "code": null, "e": 49491, "s": 49485, "text": "Graph" }, { "code": null, "e": 49495, "s": 49491, "text": "DFS" }, { "code": null, "e": 49501, "s": 49495, "text": "Graph" }, { "code": null, "e": 49505, "s": 49501, "text": "BFS" }, { "code": null, "e": 49603, "s": 49505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49623, "s": 49603, "text": "Topological Sorting" }, { "code": null, "e": 49656, "s": 49623, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 49724, "s": 49656, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 49774, "s": 49724, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 49849, "s": 49774, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 49897, "s": 49849, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 49933, "s": 49897, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 49968, "s": 49933, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 50004, "s": 49968, "text": "m Coloring Problem | Backtracking-5" } ]
Count of sub-strings that contain character X at least once - GeeksforGeeks
07 Jun, 2021 Given a string str and a character X. The task is to find the total number of sub-strings that contain the character X at least once.Examples: Input: str = “abcd”, X = ‘b’ Output: 6 “ab”, “abc”, “abcd”, “b”, “bc” and “bcd” are the required sub-strings.Input: str = “geeksforgeeks”, X = ‘e’ Output: 66 Approach: Total number of sub-strings are n * (n + 1) / 2, among them only those sub-strings need to be counted which contain character X. Character X is present in those sub-strings from position of X to the length of the string. For each character before X this sub-string must be counted.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// required sub-stringsint countSubStr(string str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codeint main(){ string str = "abcabc"; int n = str.length(); char x = 'c'; cout << countSubStr(str, n, x); return 0;} // Java implementation of the approachclass GFG{ // Function to return the count of// required sub-stringsstatic int countSubStr(String str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str.charAt(i) == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codepublic static void main(String[] args){ String str = "abcabc"; int n = str.length(); char x = 'c'; System.out.println(countSubStr(str, n, x));}} // This code has been contributed by 29AjayKumar # Python implementation of the approach # Function to return the count of# required sub-stringsdef countSubStr(str, n, x): res = 0; count = 0; for i in range(n): if (str[i] == x): # Number of sub-strings from position # of current x to the end of str res += ((count + 1) * (n - i)); # To store the number of characters # before x count = 0; else: count+=1; return res; # Driver codestr = "abcabc";n = len(str);x = 'c'; print(countSubStr(str, n, x)); # This code contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Function to return the count of// required sub-stringsstatic int countSubStr(String str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codepublic static void Main(String[] args){ String str = "abcabc"; int n = str.Length; char x = 'c'; Console.WriteLine(countSubStr(str, n, x));}} /* This code contributed by PrinciRaj1992 */ <?php// PHP implementation of the approach // Function to return the count of// required sub-stringsfunction countSubStr($str, $n, $x){ $res = 0; $count = 0; for ($i = 0; $i < $n; $i++) { if ($str[$i] == $x) { // Number of sub-strings from position // of current x to the end of str $res += (($count + 1) * ($n - $i)); // To store the number of characters // before x $count = 0; } else $count++; } return $res;} // Driver code$str = "abcabc";$n = strlen($str);$x = 'c'; echo countSubStr($str, $n, $x); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to return the count of // required sub-strings function countSubStr(str, n, x) { let res = 0, count = 0; for (let i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res; } let str = "abcabc"; let n = str.length; let x = 'c'; document.write(countSubStr(str, n, x)); // This code is contributed by divyeshrabadiya07.</script> 15 ankthon 29AjayKumar princiraj1992 divyeshrabadiya07 substring Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Array of Strings in C++ (5 Different Ways to Create) Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26561, "s": 26533, "text": "\n07 Jun, 2021" }, { "code": null, "e": 26706, "s": 26561, "text": "Given a string str and a character X. The task is to find the total number of sub-strings that contain the character X at least once.Examples: " }, { "code": null, "e": 26866, "s": 26706, "text": "Input: str = “abcd”, X = ‘b’ Output: 6 “ab”, “abc”, “abcd”, “b”, “bc” and “bcd” are the required sub-strings.Input: str = “geeksforgeeks”, X = ‘e’ Output: 66 " }, { "code": null, "e": 27212, "s": 26868, "text": "Approach: Total number of sub-strings are n * (n + 1) / 2, among them only those sub-strings need to be counted which contain character X. Character X is present in those sub-strings from position of X to the length of the string. For each character before X this sub-string must be counted.Below is the implementation of the above approach: " }, { "code": null, "e": 27216, "s": 27212, "text": "C++" }, { "code": null, "e": 27221, "s": 27216, "text": "Java" }, { "code": null, "e": 27229, "s": 27221, "text": "Python3" }, { "code": null, "e": 27232, "s": 27229, "text": "C#" }, { "code": null, "e": 27236, "s": 27232, "text": "PHP" }, { "code": null, "e": 27247, "s": 27236, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// required sub-stringsint countSubStr(string str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codeint main(){ string str = \"abcabc\"; int n = str.length(); char x = 'c'; cout << countSubStr(str, n, x); return 0;}", "e": 27957, "s": 27247, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the count of// required sub-stringsstatic int countSubStr(String str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str.charAt(i) == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codepublic static void main(String[] args){ String str = \"abcabc\"; int n = str.length(); char x = 'c'; System.out.println(countSubStr(str, n, x));}} // This code has been contributed by 29AjayKumar", "e": 28734, "s": 27957, "text": null }, { "code": "# Python implementation of the approach # Function to return the count of# required sub-stringsdef countSubStr(str, n, x): res = 0; count = 0; for i in range(n): if (str[i] == x): # Number of sub-strings from position # of current x to the end of str res += ((count + 1) * (n - i)); # To store the number of characters # before x count = 0; else: count+=1; return res; # Driver codestr = \"abcabc\";n = len(str);x = 'c'; print(countSubStr(str, n, x)); # This code contributed by PrinciRaj1992", "e": 29333, "s": 28734, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of// required sub-stringsstatic int countSubStr(String str, int n, char x){ int res = 0, count = 0; for (int i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res;} // Driver codepublic static void Main(String[] args){ String str = \"abcabc\"; int n = str.Length; char x = 'c'; Console.WriteLine(countSubStr(str, n, x));}} /* This code contributed by PrinciRaj1992 */", "e": 30108, "s": 29333, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of// required sub-stringsfunction countSubStr($str, $n, $x){ $res = 0; $count = 0; for ($i = 0; $i < $n; $i++) { if ($str[$i] == $x) { // Number of sub-strings from position // of current x to the end of str $res += (($count + 1) * ($n - $i)); // To store the number of characters // before x $count = 0; } else $count++; } return $res;} // Driver code$str = \"abcabc\";$n = strlen($str);$x = 'c'; echo countSubStr($str, $n, $x); // This code is contributed by Ryuga?>", "e": 30773, "s": 30108, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of // required sub-strings function countSubStr(str, n, x) { let res = 0, count = 0; for (let i = 0; i < n; i++) { if (str[i] == x) { // Number of sub-strings from position // of current x to the end of str res += ((count + 1) * (n - i)); // To store the number of characters // before x count = 0; } else count++; } return res; } let str = \"abcabc\"; let n = str.length; let x = 'c'; document.write(countSubStr(str, n, x)); // This code is contributed by divyeshrabadiya07.</script>", "e": 31572, "s": 30773, "text": null }, { "code": null, "e": 31575, "s": 31572, "text": "15" }, { "code": null, "e": 31585, "s": 31577, "text": "ankthon" }, { "code": null, "e": 31597, "s": 31585, "text": "29AjayKumar" }, { "code": null, "e": 31611, "s": 31597, "text": "princiraj1992" }, { "code": null, "e": 31629, "s": 31611, "text": "divyeshrabadiya07" }, { "code": null, "e": 31639, "s": 31629, "text": "substring" }, { "code": null, "e": 31647, "s": 31639, "text": "Strings" }, { "code": null, "e": 31655, "s": 31647, "text": "Strings" }, { "code": null, "e": 31753, "s": 31655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31828, "s": 31753, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 31885, "s": 31828, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31921, "s": 31885, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31974, "s": 31921, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 32021, "s": 31974, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32057, "s": 32021, "text": "Convert string to char array in C++" }, { "code": null, "e": 32095, "s": 32057, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32125, "s": 32095, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32177, "s": 32125, "text": "Check whether two strings are anagram of each other" } ]
How to Create a Virus that Deletes the Registry File of Windows OS? - GeeksforGeeks
13 Apr, 2021 The virus that we are going to create in this article can be used to wipe out the Windows registry or simply registry from the database of the Windows system. The registry or Windows registry is a database that holds information regarding the settings, options, and critical values that software and hardware in the Windows OS use. For this, we don’t have to download any specific software we can start coding in Notepad and save the file as .bat Extension. Now to create the virus follow the below steps: Step 1: Press the Window + R Button from the Keyboard. This will open the Run Dialog book will Open in front of us. Step 2: Type Notepad in the Dialog Box and press Enter. This will open the notepad for us. Step 3: Type in the below-mentioned code in the Notepad: @ECHO OFF START reg delete HKCR/.exe START reg delete HKCR/.dll START reg delete HKCR/* Step 4: After typing in all the code save the file with the name of your choice. But remember to save the file with .bat extension. The Virus has been Successfully Created by you but this will only work when it is opened by the user once. To resolve this issue the user must Reinstall the Operating System. No other Option will work in this situation because this will also delete the Backup kept in the Computer. Disclaimer: GeeksforGeeks does not support the spread of ransomware/viruses and if you intend to use this information for malicious purposes, we are in no way responsible. This information is intended to be used for educational purposes only. If the virus file is clicked or opened by the user, resultantly all the registry data in the system will be wiped clean. How To TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Check the OS Version in Linux? How to Run a Python Script using Docker? Docker - COPY Instruction Running Python script on GPU. Setting up the environment in Java How to setup cron jobs in Ubuntu
[ { "code": null, "e": 24872, "s": 24844, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25031, "s": 24872, "text": "The virus that we are going to create in this article can be used to wipe out the Windows registry or simply registry from the database of the Windows system." }, { "code": null, "e": 25331, "s": 25031, "text": "The registry or Windows registry is a database that holds information regarding the settings, options, and critical values that software and hardware in the Windows OS use. For this, we don’t have to download any specific software we can start coding in Notepad and save the file as .bat Extension. " }, { "code": null, "e": 25379, "s": 25331, "text": "Now to create the virus follow the below steps:" }, { "code": null, "e": 25496, "s": 25379, "text": "Step 1: Press the Window + R Button from the Keyboard. This will open the Run Dialog book will Open in front of us. " }, { "code": null, "e": 25587, "s": 25496, "text": "Step 2: Type Notepad in the Dialog Box and press Enter. This will open the notepad for us." }, { "code": null, "e": 25644, "s": 25587, "text": "Step 3: Type in the below-mentioned code in the Notepad:" }, { "code": null, "e": 25732, "s": 25644, "text": "@ECHO OFF\nSTART reg delete HKCR/.exe\nSTART reg delete HKCR/.dll\nSTART reg delete HKCR/*" }, { "code": null, "e": 25864, "s": 25732, "text": "Step 4: After typing in all the code save the file with the name of your choice. But remember to save the file with .bat extension." }, { "code": null, "e": 25971, "s": 25864, "text": "The Virus has been Successfully Created by you but this will only work when it is opened by the user once." }, { "code": null, "e": 26146, "s": 25971, "text": "To resolve this issue the user must Reinstall the Operating System. No other Option will work in this situation because this will also delete the Backup kept in the Computer." }, { "code": null, "e": 26510, "s": 26146, "text": "Disclaimer: GeeksforGeeks does not support the spread of ransomware/viruses and if you intend to use this information for malicious purposes, we are in no way responsible. This information is intended to be used for educational purposes only. If the virus file is clicked or opened by the user, resultantly all the registry data in the system will be wiped clean." }, { "code": null, "e": 26517, "s": 26510, "text": "How To" }, { "code": null, "e": 26526, "s": 26517, "text": "TechTips" }, { "code": null, "e": 26624, "s": 26526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26633, "s": 26624, "text": "Comments" }, { "code": null, "e": 26646, "s": 26633, "text": "Old Comments" }, { "code": null, "e": 26680, "s": 26646, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26729, "s": 26680, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26787, "s": 26729, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26829, "s": 26787, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26867, "s": 26829, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 26908, "s": 26867, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 26934, "s": 26908, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26964, "s": 26934, "text": "Running Python script on GPU." }, { "code": null, "e": 26999, "s": 26964, "text": "Setting up the environment in Java" } ]
Longest subsequence whose average is less than K - GeeksforGeeks
31 Jan, 2022 Given an array of N positive integers and Q queries consisting of an integer K, the task is to print the length of the longest subsequence whose average is less than K. Examples: Input: a[] = {1, 3, 2, 5, 4} Query1: K = 3 Query2: K = 5Output: 4 5 Query1: The subsequence is: {1, 3, 2, 4} or {1, 3, 2, 5} Query2: The subsequence is: {1, 3, 2, 5, 4} A Naive Approach is to generate all subsequences using power-set and check for the longest subsequence whose average is less than K. Time Complexity: O(2N * N ) An efficient approach is to sort the array elements and find the average of elements starting from the left. Insert the average of elements computed from the left into the container(vector or arrays). Sort the container’s element and then use binary search to search for the number K in the container. The length of the longest subsequence will thus be the index number which upper_bound() returns for every query.Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to perform Q queries// to find longest subsequence whose// average is less than K#include <bits/stdc++.h>using namespace std; // Function to print the length for every queryint longestSubsequence(int a[], int n, int q[], int m){ // sort array of N elements sort(a, a + n); int sum = 0; // Array to store average from left int b[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average sort(b, b + n); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upper_bound(b, b + n, k) - b; cout << "Answer to Query" << i + 1 << ": " << longest << endl; }} // Driver Codeint main(){ int a[] = { 1, 3, 2, 5, 4 }; int n = sizeof(a) / sizeof(a[0]); // 4 queries int q[] = { 4, 2, 1, 5 }; int m = sizeof(q) / sizeof(q[0]); longestSubsequence(a, n, q, m); return 0;} // Java program to perform Q queries// to find longest subsequence whose// average is less than Kimport java.util.Arrays; class GFG{ // Function to print the length for every query static void longestSubsequence(int a[], int n, int q[], int m) { // sort array of N elements Arrays.sort(a); int sum = 0; // Array to store average from left int []b = new int[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average Arrays.sort(b); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upperBound(b,0, n, k); System.out.println("Answer to Query" + (i + 1) +": " + longest); } } private static int upperBound(int[] a, int low, int high, int element) { while(low < high) { int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } // Driver Code public static void main(String[] args) { int a[] = { 1, 3, 2, 5, 4 }; int n = a.length; // 4 queries int q[] = { 4, 2, 1, 5 }; int m = q.length; longestSubsequence(a, n, q, m); }} /* This code contributed by PrinciRaj1992 */ # Python3 program to perform Q queries to find# longest subsequence whose average is less than Kimport bisect # Function to print the length for every querydef longestSubsequence(a, n, q, m): # sort array of N elements a.sort() Sum = 0 # Array to store average from left b = [None] * n for i in range(0, n): Sum += a[i] av = Sum // (i + 1) b[i] = av + 1 # Sort array of average b.sort() # number of queries for i in range(0, m): k = q[i] # print answer to every query # using binary search longest = bisect.bisect_right(b, k) print("Answer to Query", i + 1, ":", longest) # Driver Codeif __name__ == "__main__": a = [1, 3, 2, 5, 4] n = len(a) # 4 queries q = [4, 2, 1, 5] m = len(q) longestSubsequence(a, n, q, m) # This code is contributed by Rituraj Jain // C# program to perform Q queries// to find longest subsequence whose// average is less than Kusing System; class GFG{ // Function to print the length for every query static void longestSubsequence(int []a, int n, int []q, int m) { // sort array of N elements Array.Sort(a); int sum = 0; // Array to store average from left int []b = new int[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average Array.Sort(b); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upperBound(b,0, n, k); Console.WriteLine("Answer to Query" + (i + 1) +": " + longest); } } private static int upperBound(int[] a, int low, int high, int element) { while(low < high) { int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } // Driver Code static public void Main () { int []a = { 1, 3, 2, 5, 4 }; int n = a.Length; // 4 queries int []q = { 4, 2, 1, 5 }; int m = q.Length; longestSubsequence(a, n, q, m); }} /* This code contributed by ajit */ <script> // Javascript program to perform Q queries // to find longest subsequence whose // average is less than K // Function to print the length for every query function longestSubsequence(a, n, q, m) { // sort array of N elements a.sort(function(a, b){return a - b}); let sum = 0; // Array to store average from left let b = new Array(n); for (let i = 0; i < n; i++) { sum += a[i]; let av = parseInt((sum) / (i + 1), 10); b[i] = (av + 1); } // Sort array of average b.sort(function(a, b){return a - b}); // number of queries for (let i = 0; i < m; i++) { let k = q[i]; // print answer to every query // using binary search let longest = upperBound(b,0, n, k); document.write("Answer to Query" + (i + 1) +": " + longest + "</br>"); } } function upperBound(a, low, high, element) { while(low < high) { let middle = low + parseInt((high - low)/2, 10); if(a[middle] > element) high = middle; else low = middle + 1; } return low; } let a = [ 1, 3, 2, 5, 4 ]; let n = a.length; // 4 queries let q = [ 4, 2, 1, 5 ]; let m = q.length; longestSubsequence(a, n, q, m); </script> Output: Answer to Query1: 5 Answer to Query2: 2 Answer to Query3: 0 Answer to Query4: 5 Time Complexity: O(N*log N + M*log N) Auxiliary Space: O(N) rituraj_jain Code_r princiraj1992 jit_t divyeshrabadiya07 avtarkumar719 Sorting Quiz subsequence Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Move all negative numbers to beginning and positive to end with constant extra space Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24820, "s": 24792, "text": "\n31 Jan, 2022" }, { "code": null, "e": 25001, "s": 24820, "text": "Given an array of N positive integers and Q queries consisting of an integer K, the task is to print the length of the longest subsequence whose average is less than K. Examples: " }, { "code": null, "e": 25172, "s": 25001, "text": "Input: a[] = {1, 3, 2, 5, 4} Query1: K = 3 Query2: K = 5Output: 4 5 Query1: The subsequence is: {1, 3, 2, 4} or {1, 3, 2, 5} Query2: The subsequence is: {1, 3, 2, 5, 4} " }, { "code": null, "e": 25802, "s": 25174, "text": "A Naive Approach is to generate all subsequences using power-set and check for the longest subsequence whose average is less than K. Time Complexity: O(2N * N ) An efficient approach is to sort the array elements and find the average of elements starting from the left. Insert the average of elements computed from the left into the container(vector or arrays). Sort the container’s element and then use binary search to search for the number K in the container. The length of the longest subsequence will thus be the index number which upper_bound() returns for every query.Below is the implementation of the above approach. " }, { "code": null, "e": 25806, "s": 25802, "text": "C++" }, { "code": null, "e": 25811, "s": 25806, "text": "Java" }, { "code": null, "e": 25819, "s": 25811, "text": "Python3" }, { "code": null, "e": 25822, "s": 25819, "text": "C#" }, { "code": null, "e": 25833, "s": 25822, "text": "Javascript" }, { "code": "// C++ program to perform Q queries// to find longest subsequence whose// average is less than K#include <bits/stdc++.h>using namespace std; // Function to print the length for every queryint longestSubsequence(int a[], int n, int q[], int m){ // sort array of N elements sort(a, a + n); int sum = 0; // Array to store average from left int b[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average sort(b, b + n); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upper_bound(b, b + n, k) - b; cout << \"Answer to Query\" << i + 1 << \": \" << longest << endl; }} // Driver Codeint main(){ int a[] = { 1, 3, 2, 5, 4 }; int n = sizeof(a) / sizeof(a[0]); // 4 queries int q[] = { 4, 2, 1, 5 }; int m = sizeof(q) / sizeof(q[0]); longestSubsequence(a, n, q, m); return 0;}", "e": 26904, "s": 25833, "text": null }, { "code": "// Java program to perform Q queries// to find longest subsequence whose// average is less than Kimport java.util.Arrays; class GFG{ // Function to print the length for every query static void longestSubsequence(int a[], int n, int q[], int m) { // sort array of N elements Arrays.sort(a); int sum = 0; // Array to store average from left int []b = new int[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average Arrays.sort(b); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upperBound(b,0, n, k); System.out.println(\"Answer to Query\" + (i + 1) +\": \" + longest); } } private static int upperBound(int[] a, int low, int high, int element) { while(low < high) { int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } // Driver Code public static void main(String[] args) { int a[] = { 1, 3, 2, 5, 4 }; int n = a.length; // 4 queries int q[] = { 4, 2, 1, 5 }; int m = q.length; longestSubsequence(a, n, q, m); }} /* This code contributed by PrinciRaj1992 */", "e": 28509, "s": 26904, "text": null }, { "code": "# Python3 program to perform Q queries to find# longest subsequence whose average is less than Kimport bisect # Function to print the length for every querydef longestSubsequence(a, n, q, m): # sort array of N elements a.sort() Sum = 0 # Array to store average from left b = [None] * n for i in range(0, n): Sum += a[i] av = Sum // (i + 1) b[i] = av + 1 # Sort array of average b.sort() # number of queries for i in range(0, m): k = q[i] # print answer to every query # using binary search longest = bisect.bisect_right(b, k) print(\"Answer to Query\", i + 1, \":\", longest) # Driver Codeif __name__ == \"__main__\": a = [1, 3, 2, 5, 4] n = len(a) # 4 queries q = [4, 2, 1, 5] m = len(q) longestSubsequence(a, n, q, m) # This code is contributed by Rituraj Jain", "e": 29391, "s": 28509, "text": null }, { "code": "// C# program to perform Q queries// to find longest subsequence whose// average is less than Kusing System; class GFG{ // Function to print the length for every query static void longestSubsequence(int []a, int n, int []q, int m) { // sort array of N elements Array.Sort(a); int sum = 0; // Array to store average from left int []b = new int[n]; for (int i = 0; i < n; i++) { sum += a[i]; double av = (double)(sum) / (double)(i + 1); b[i] = ((int)(av + 1)); } // Sort array of average Array.Sort(b); // number of queries for (int i = 0; i < m; i++) { int k = q[i]; // print answer to every query // using binary search int longest = upperBound(b,0, n, k); Console.WriteLine(\"Answer to Query\" + (i + 1) +\": \" + longest); } } private static int upperBound(int[] a, int low, int high, int element) { while(low < high) { int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } // Driver Code static public void Main () { int []a = { 1, 3, 2, 5, 4 }; int n = a.Length; // 4 queries int []q = { 4, 2, 1, 5 }; int m = q.Length; longestSubsequence(a, n, q, m); }} /* This code contributed by ajit */", "e": 31007, "s": 29391, "text": null }, { "code": "<script> // Javascript program to perform Q queries // to find longest subsequence whose // average is less than K // Function to print the length for every query function longestSubsequence(a, n, q, m) { // sort array of N elements a.sort(function(a, b){return a - b}); let sum = 0; // Array to store average from left let b = new Array(n); for (let i = 0; i < n; i++) { sum += a[i]; let av = parseInt((sum) / (i + 1), 10); b[i] = (av + 1); } // Sort array of average b.sort(function(a, b){return a - b}); // number of queries for (let i = 0; i < m; i++) { let k = q[i]; // print answer to every query // using binary search let longest = upperBound(b,0, n, k); document.write(\"Answer to Query\" + (i + 1) +\": \" + longest + \"</br>\"); } } function upperBound(a, low, high, element) { while(low < high) { let middle = low + parseInt((high - low)/2, 10); if(a[middle] > element) high = middle; else low = middle + 1; } return low; } let a = [ 1, 3, 2, 5, 4 ]; let n = a.length; // 4 queries let q = [ 4, 2, 1, 5 ]; let m = q.length; longestSubsequence(a, n, q, m); </script>", "e": 32489, "s": 31007, "text": null }, { "code": null, "e": 32499, "s": 32489, "text": "Output: " }, { "code": null, "e": 32579, "s": 32499, "text": "Answer to Query1: 5\nAnswer to Query2: 2\nAnswer to Query3: 0\nAnswer to Query4: 5" }, { "code": null, "e": 32640, "s": 32579, "text": "Time Complexity: O(N*log N + M*log N) Auxiliary Space: O(N) " }, { "code": null, "e": 32653, "s": 32640, "text": "rituraj_jain" }, { "code": null, "e": 32660, "s": 32653, "text": "Code_r" }, { "code": null, "e": 32674, "s": 32660, "text": "princiraj1992" }, { "code": null, "e": 32680, "s": 32674, "text": "jit_t" }, { "code": null, "e": 32698, "s": 32680, "text": "divyeshrabadiya07" }, { "code": null, "e": 32712, "s": 32698, "text": "avtarkumar719" }, { "code": null, "e": 32725, "s": 32712, "text": "Sorting Quiz" }, { "code": null, "e": 32737, "s": 32725, "text": "subsequence" }, { "code": null, "e": 32744, "s": 32737, "text": "Arrays" }, { "code": null, "e": 32751, "s": 32744, "text": "Greedy" }, { "code": null, "e": 32758, "s": 32751, "text": "Arrays" }, { "code": null, "e": 32765, "s": 32758, "text": "Greedy" }, { "code": null, "e": 32863, "s": 32765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32872, "s": 32863, "text": "Comments" }, { "code": null, "e": 32885, "s": 32872, "text": "Old Comments" }, { "code": null, "e": 32910, "s": 32885, "text": "Window Sliding Technique" }, { "code": null, "e": 32959, "s": 32910, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33044, "s": 32959, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 33082, "s": 33044, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33140, "s": 33082, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33191, "s": 33140, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 33249, "s": 33191, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 33300, "s": 33249, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 33331, "s": 33300, "text": "Huffman Coding | Greedy Algo-3" } ]
How to count the number of lines in a text file using Java?
To count the number of lines in a file Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor. Read the contents of the file to a bytearray using the read() method of FileInputStream class. Instantiate a String class by passing the byte array obtained, as a parameter its constructor. Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method. Now, find the length of the obtained array. import java.io.File; import java.io.FileInputStream; public class NumberOfCharacters { public static void main(String args[]) throws Exception{ File file = new File("data"); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fis.read(byteArray); String data = new String(byteArray); String[] stringArray = data.split("\r\n"); System.out.println("Number of lines in the file are ::"+stringArray.length); } } Number of lines in the file are ::3
[ { "code": null, "e": 1101, "s": 1062, "text": "To count the number of lines in a file" }, { "code": null, "e": 1214, "s": 1101, "text": "Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor." }, { "code": null, "e": 1309, "s": 1214, "text": "Read the contents of the file to a bytearray using the read() method of FileInputStream class." }, { "code": null, "e": 1404, "s": 1309, "text": "Instantiate a String class by passing the byte array obtained, as a parameter its constructor." }, { "code": null, "e": 1563, "s": 1404, "text": "Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method." }, { "code": null, "e": 1607, "s": 1563, "text": "Now, find the length of the obtained array." }, { "code": null, "e": 2113, "s": 1607, "text": "import java.io.File;\nimport java.io.FileInputStream;\npublic class NumberOfCharacters {\n public static void main(String args[]) throws Exception{\n \n File file = new File(\"data\");\n FileInputStream fis = new FileInputStream(file);\n byte[] byteArray = new byte[(int)file.length()];\n fis.read(byteArray);\n String data = new String(byteArray);\n String[] stringArray = data.split(\"\\r\\n\");\n System.out.println(\"Number of lines in the file are ::\"+stringArray.length);\n }\n}" }, { "code": null, "e": 2149, "s": 2113, "text": "Number of lines in the file are ::3" } ]
Check whether triangle is valid or not if sides are given in Python
Suppose we have three sides. We have to check whether these three sides are forming a triangle or not. So, if the input is like sides = [14,20,10], then the output will be True as 20 < (10+14). To solve this, we will follow these steps − sort the list sides if sum of first two sides <= third side, thenreturn False return False return True Let us see the following implementation to get better understanding − Live Demo def solve(sides): sides.sort() if sides[0] + sides[1] <= sides[2]: return False return True sides = [14,20,10] print(solve(sides)) [14,20,10] True
[ { "code": null, "e": 1165, "s": 1062, "text": "Suppose we have three sides. We have to check whether these three sides are forming a triangle or not." }, { "code": null, "e": 1256, "s": 1165, "text": "So, if the input is like sides = [14,20,10], then the output will be True as 20 < (10+14)." }, { "code": null, "e": 1300, "s": 1256, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1320, "s": 1300, "text": "sort the list sides" }, { "code": null, "e": 1378, "s": 1320, "text": "if sum of first two sides <= third side, thenreturn False" }, { "code": null, "e": 1391, "s": 1378, "text": "return False" }, { "code": null, "e": 1403, "s": 1391, "text": "return True" }, { "code": null, "e": 1473, "s": 1403, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1483, "s": 1473, "text": "Live Demo" }, { "code": null, "e": 1630, "s": 1483, "text": "def solve(sides):\n sides.sort()\n if sides[0] + sides[1] <= sides[2]:\n return False\n return True\n\nsides = [14,20,10]\nprint(solve(sides))" }, { "code": null, "e": 1642, "s": 1630, "text": "[14,20,10]\n" }, { "code": null, "e": 1647, "s": 1642, "text": "True" } ]
What is HTTP ETag? - GeeksforGeeks
29 Jun, 2020 An entity tag (ETag) is an HTTP header used for Web cache validation and conditional request from browsers to resources. The value of an ETag is an identifier that represents a specific version of the resource. Additionally, ETags help prevents simultaneous updates of a resource from overwriting each other. Example of ETag header is ETag: "version1" Note :The value of the ETag header must be in double-quotes. The server receives an HTTP request for a particular resource. The server generates a response and attached an ETag header. For Eg: ETag: “response_version1”. The server sends the response with the above header with the status code 200. Then the application represents the resource and at the same time caches the resource copy along with header information. Later the same application makes another request for the same resource with following conditional request header: If-None-Match: “response_version1” On receiving the request for the resource along with the ‘If-None-Match’ header, the server-side logic compare the current value of the ETag identifier on the server-side and the one which is received in the request header. If the request’s If-None-Match is the same as the currently generated value of ETag on the server, then status code 304 (Not Modified) with the empty body is sent back and the application uses the cached copy of the resource. If the request’s If-None-Match value doesn’t match the currently generated/assigned value of ETag (say “response_version2”) for the same resource then the server sends back the new content in the body along with status code 200. The ‘ETag’ header with the new value is also included in the response. The application uses the new resource and updates its cache with the new data. That’s entirely up to the application to generate it as it wants. It can be created and updated manually or can be auto-generated. Common methods of its auto-generation include using a hash of the resource’s content or just a hash of the last modification timestamp. The generated hash should be collision-free. It is just comparison of two values. It is divided into 2 parts Strong ValidationWeak Validation Strong Validation Weak Validation 1.Strong Validation: The different resource representations are byte-for-byte identical. This is the default validation of ETag and no special directive is used for it. 2.Weak Validation: The two resource representations are semantically equivalent. For e.g. the current date displayed on the page might not be important for updating the entire resource for it. References: https://en.wikipedia.org/wiki/HTTP_ETaghttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag https://en.wikipedia.org/wiki/HTTP_ETag https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag jyash97 Advanced Computer Subject Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Copying Files to and from Docker Containers Decision Tree System Design Tutorial Python | Decision tree implementation SDE SHEET - A Complete Guide for SDE Preparation Introduction to Algorithms Software Engineering | Coupling and Cohesion Software Engineering | Prototyping Model Difference between NP hard and NP complete problem
[ { "code": null, "e": 24306, "s": 24278, "text": "\n29 Jun, 2020" }, { "code": null, "e": 24641, "s": 24306, "text": "An entity tag (ETag) is an HTTP header used for Web cache validation and conditional request from browsers to resources. The value of an ETag is an identifier that represents a specific version of the resource. Additionally, ETags help prevents simultaneous updates of a resource from overwriting each other. Example of ETag header is" }, { "code": null, "e": 24658, "s": 24641, "text": "ETag: \"version1\"" }, { "code": null, "e": 24719, "s": 24658, "text": "Note :The value of the ETag header must be in double-quotes." }, { "code": null, "e": 24782, "s": 24719, "text": "The server receives an HTTP request for a particular resource." }, { "code": null, "e": 24878, "s": 24782, "text": "The server generates a response and attached an ETag header. For Eg: ETag: “response_version1”." }, { "code": null, "e": 25078, "s": 24878, "text": "The server sends the response with the above header with the status code 200. Then the application represents the resource and at the same time caches the resource copy along with header information." }, { "code": null, "e": 25227, "s": 25078, "text": "Later the same application makes another request for the same resource with following conditional request header: If-None-Match: “response_version1”" }, { "code": null, "e": 25451, "s": 25227, "text": "On receiving the request for the resource along with the ‘If-None-Match’ header, the server-side logic compare the current value of the ETag identifier on the server-side and the one which is received in the request header." }, { "code": null, "e": 25677, "s": 25451, "text": "If the request’s If-None-Match is the same as the currently generated value of ETag on the server, then status code 304 (Not Modified) with the empty body is sent back and the application uses the cached copy of the resource." }, { "code": null, "e": 26056, "s": 25677, "text": "If the request’s If-None-Match value doesn’t match the currently generated/assigned value of ETag (say “response_version2”) for the same resource then the server sends back the new content in the body along with status code 200. The ‘ETag’ header with the new value is also included in the response. The application uses the new resource and updates its cache with the new data." }, { "code": null, "e": 26368, "s": 26056, "text": "That’s entirely up to the application to generate it as it wants. It can be created and updated manually or can be auto-generated. Common methods of its auto-generation include using a hash of the resource’s content or just a hash of the last modification timestamp. The generated hash should be collision-free." }, { "code": null, "e": 26432, "s": 26368, "text": "It is just comparison of two values. It is divided into 2 parts" }, { "code": null, "e": 26465, "s": 26432, "text": "Strong ValidationWeak Validation" }, { "code": null, "e": 26483, "s": 26465, "text": "Strong Validation" }, { "code": null, "e": 26499, "s": 26483, "text": "Weak Validation" }, { "code": null, "e": 26520, "s": 26499, "text": "1.Strong Validation:" }, { "code": null, "e": 26668, "s": 26520, "text": "The different resource representations are byte-for-byte identical. This is the default validation of ETag and no special directive is used for it." }, { "code": null, "e": 26687, "s": 26668, "text": "2.Weak Validation:" }, { "code": null, "e": 26861, "s": 26687, "text": "The two resource representations are semantically equivalent. For e.g. the current date displayed on the page might not be important for updating the entire resource for it." }, { "code": null, "e": 26873, "s": 26861, "text": "References:" }, { "code": null, "e": 26975, "s": 26873, "text": "https://en.wikipedia.org/wiki/HTTP_ETaghttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag" }, { "code": null, "e": 27015, "s": 26975, "text": "https://en.wikipedia.org/wiki/HTTP_ETag" }, { "code": null, "e": 27078, "s": 27015, "text": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag" }, { "code": null, "e": 27086, "s": 27078, "text": "jyash97" }, { "code": null, "e": 27112, "s": 27086, "text": "Advanced Computer Subject" }, { "code": null, "e": 27129, "s": 27112, "text": "Computer Subject" }, { "code": null, "e": 27227, "s": 27129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27236, "s": 27227, "text": "Comments" }, { "code": null, "e": 27249, "s": 27236, "text": "Old Comments" }, { "code": null, "e": 27272, "s": 27249, "text": "ML | Linear Regression" }, { "code": null, "e": 27316, "s": 27272, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27330, "s": 27316, "text": "Decision Tree" }, { "code": null, "e": 27353, "s": 27330, "text": "System Design Tutorial" }, { "code": null, "e": 27391, "s": 27353, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27440, "s": 27391, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 27467, "s": 27440, "text": "Introduction to Algorithms" }, { "code": null, "e": 27512, "s": 27467, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 27553, "s": 27512, "text": "Software Engineering | Prototyping Model" } ]
CodeIgniter - Security
XSS means cross-site scripting. CodeIgniter comes with XSS filtering security. This filter will prevent any malicious JavaScript code or any other code that attempts to hijack cookie and do malicious activities. To filter data through the XSS filter, use the xss_clean() method as shown below. $data = $this->security->xss_clean($data); You should use this function only when you are submitting data. The optional second Boolean parameter can also be used to check image file for XSS attack. This is useful for file upload facility. If its value is true, means image is safe and not otherwise. SQL injection is an attack made on database query. In PHP, we are use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this. We can prevent SQL Injection in CodeIgniter in the following three ways − Escaping Queries Query Biding Active Record Class <?php $username = $this->input->post('username'); $query = 'SELECT * FROM subscribers_tbl WHERE user_name = '. $this->db->escape($email); $this->db->query($query); ?> $this->db->escape() function automatically adds single quotes around the data and determines the data type so that it can escape only string data. <?php $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; $this->db->query($sql, array(3, 'live', 'Rick')); ?> In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically, so you do not have to remember it. <?php $this->db->get_where('subscribers_tbl',array ('status'=> active','email' => 'info@arjun.net.in')); ?> Using active records, query syntax is generated by each database adapter. It also allows safer queries, since the values escape automatically. In production environment, we often do not want to display any error message to the users. It is good if it is enabled in the development environment for debugging purposes. These error messages may contain some information, which we should not show to the site users for security reasons. There are three CodeIgniter files related with errors. Different environment requires different levels of error reporting. By default, development will show errors but testing and live will hide them. There is a file called index.php in root directory of CodeIgniter, which is used for this purpose. If we pass zero as argument to error_reporting() function then that will hide all the errors. Even if you have turned off the PHP errors, MySQL errors are still open. You can turn this off in application/config/database.php. Set the db_debug option in $db array to FALSE as shown below. $db['default']['db_debug'] = FALSE; Another way is to transfer the errors to log files. So, it will not be displayed to users on the site. Simply, set the log_threshold value in $config array to 1 in application/cofig/config.php file as shown below. $config['log_threshold'] = 1; CSRF stands for cross-site request forgery. You can prevent this attack by enabling it in the application/config/config.php file as shown below. $config['csrf_protection'] = TRUE; When you are creating form using form_open() function, it will automatically insert a CSRF as hidden field. You can also manually add the CSRF using the get_csrf_token_name() and get_csrf_hash() function. The get_csrf_token_name() function will return the name of the CSRF and get_csrf_hash() will return the hash value of CSRF. The CSRF token can be regenerated every time for submission or you can also keep it same throughout the life of CSRF cookie. By setting the value TRUE, in config array with key ‘csrf_regenerate’ will regenerate token as shown below. $config['csrf_regenerate'] = TRUE; You can also whitelist URLs from CSRF protection by setting it in the config array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expression. $config['csrf_exclude_uris'] = array('api/person/add'); Many developers do not know how to handle password in web applications, which is probably why numerous hackers find it so easy to break into the systems. One should keep in mind the following points while handling passwords − DO NOT store passwords in plain-text format. DO NOT store passwords in plain-text format. Always hash your passwords. Always hash your passwords. DO NOT use Base64 or similar encoding for storing passwords. DO NOT use Base64 or similar encoding for storing passwords. DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions. DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions. DO NOT ever display or send a password in plain-text format. DO NOT ever display or send a password in plain-text format. DO NOT put unnecessary limits on your users’ passwords. DO NOT put unnecessary limits on your users’ passwords. Print Add Notes Bookmark this page
[ { "code": null, "e": 2613, "s": 2319, "text": "XSS means cross-site scripting. CodeIgniter comes with XSS filtering security. This filter will prevent any malicious JavaScript code or any other code that attempts to hijack cookie and do malicious activities. To filter data through the XSS filter, use the xss_clean() method as shown below." }, { "code": null, "e": 2657, "s": 2613, "text": "$data = $this->security->xss_clean($data);\n" }, { "code": null, "e": 2914, "s": 2657, "text": "You should use this function only when you are submitting data. The optional second Boolean parameter can also be used to check image file for XSS attack. This is useful for file upload facility. If its value is true, means image is safe and not otherwise." }, { "code": null, "e": 3138, "s": 2914, "text": "SQL injection is an attack made on database query. In PHP, we are use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this." }, { "code": null, "e": 3212, "s": 3138, "text": "We can prevent SQL Injection in CodeIgniter in the following three ways −" }, { "code": null, "e": 3229, "s": 3212, "text": "Escaping Queries" }, { "code": null, "e": 3242, "s": 3229, "text": "Query Biding" }, { "code": null, "e": 3262, "s": 3242, "text": "Active Record Class" }, { "code": null, "e": 3444, "s": 3262, "text": "<?php\n $username = $this->input->post('username');\n $query = 'SELECT * FROM subscribers_tbl WHERE user_name = '.\n $this->db->escape($email);\n $this->db->query($query);\n?>" }, { "code": null, "e": 3591, "s": 3444, "text": "$this->db->escape() function automatically adds single quotes around the data and determines the data type so that it can escape only string data." }, { "code": null, "e": 3734, "s": 3591, "text": "<?php\n $sql = \"SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?\";\n $this->db->query($sql, array(3, 'live', 'Rick'));\n?>" }, { "code": null, "e": 4056, "s": 3734, "text": "In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically, so you do not have to remember it." }, { "code": null, "e": 4173, "s": 4056, "text": "<?php\n $this->db->get_where('subscribers_tbl',array\n ('status'=> active','email' => 'info@arjun.net.in'));\n?>" }, { "code": null, "e": 4316, "s": 4173, "text": "Using active records, query syntax is generated by each database adapter. It also allows safer queries, since the values escape automatically." }, { "code": null, "e": 4606, "s": 4316, "text": "In production environment, we often do not want to display any error message to the users. It is good if it is enabled in the development environment for debugging purposes. These error messages may contain some information, which we should not show to the site users for security reasons." }, { "code": null, "e": 4661, "s": 4606, "text": "There are three CodeIgniter files related with errors." }, { "code": null, "e": 5000, "s": 4661, "text": "Different environment requires different levels of error reporting. By default, development will show errors but testing and live will hide them. There is a file called index.php in root directory of CodeIgniter, which is used for this purpose. If we pass zero as argument to error_reporting() function then that will hide all the errors." }, { "code": null, "e": 5193, "s": 5000, "text": "Even if you have turned off the PHP errors, MySQL errors are still open. You can turn this off in application/config/database.php. Set the db_debug option in $db array to FALSE as shown below." }, { "code": null, "e": 5230, "s": 5193, "text": "$db['default']['db_debug'] = FALSE;\n" }, { "code": null, "e": 5444, "s": 5230, "text": "Another way is to transfer the errors to log files. So, it will not be displayed to users on the site. Simply, set the log_threshold value in $config array to 1 in application/cofig/config.php file as shown below." }, { "code": null, "e": 5475, "s": 5444, "text": "$config['log_threshold'] = 1;\n" }, { "code": null, "e": 5620, "s": 5475, "text": "CSRF stands for cross-site request forgery. You can prevent this attack by enabling it in the application/config/config.php file as shown below." }, { "code": null, "e": 5656, "s": 5620, "text": "$config['csrf_protection'] = TRUE;\n" }, { "code": null, "e": 5985, "s": 5656, "text": "When you are creating form using form_open() function, it will automatically insert a CSRF as hidden field. You can also manually add the CSRF using the get_csrf_token_name() and get_csrf_hash() function. The get_csrf_token_name() function will return the name of the CSRF and get_csrf_hash() will return the hash value of CSRF." }, { "code": null, "e": 6218, "s": 5985, "text": "The CSRF token can be regenerated every time for submission or you can also keep it same throughout the life of CSRF cookie. By setting the value TRUE, in config array with key ‘csrf_regenerate’ will regenerate token as shown below." }, { "code": null, "e": 6254, "s": 6218, "text": "$config['csrf_regenerate'] = TRUE;\n" }, { "code": null, "e": 6424, "s": 6254, "text": "You can also whitelist URLs from CSRF protection by setting it in the config array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expression." }, { "code": null, "e": 6481, "s": 6424, "text": "$config['csrf_exclude_uris'] = array('api/person/add');\n" }, { "code": null, "e": 6707, "s": 6481, "text": "Many developers do not know how to handle password in web applications, which is probably why numerous hackers find it so easy to break into the systems. One should keep in mind the following points while handling passwords −" }, { "code": null, "e": 6752, "s": 6707, "text": "DO NOT store passwords in plain-text format." }, { "code": null, "e": 6797, "s": 6752, "text": "DO NOT store passwords in plain-text format." }, { "code": null, "e": 6825, "s": 6797, "text": "Always hash your passwords." }, { "code": null, "e": 6853, "s": 6825, "text": "Always hash your passwords." }, { "code": null, "e": 6914, "s": 6853, "text": "DO NOT use Base64 or similar encoding for storing passwords." }, { "code": null, "e": 6975, "s": 6914, "text": "DO NOT use Base64 or similar encoding for storing passwords." }, { "code": null, "e": 7150, "s": 6975, "text": "DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions." }, { "code": null, "e": 7325, "s": 7150, "text": "DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions." }, { "code": null, "e": 7386, "s": 7325, "text": "DO NOT ever display or send a password in plain-text format." }, { "code": null, "e": 7447, "s": 7386, "text": "DO NOT ever display or send a password in plain-text format." }, { "code": null, "e": 7503, "s": 7447, "text": "DO NOT put unnecessary limits on your users’ passwords." }, { "code": null, "e": 7559, "s": 7503, "text": "DO NOT put unnecessary limits on your users’ passwords." }, { "code": null, "e": 7566, "s": 7559, "text": " Print" }, { "code": null, "e": 7577, "s": 7566, "text": " Add Notes" } ]