title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Uri.GetLeftPart() Method in C# with Examples - GeeksforGeeks
|
28 May, 2020
Uri.GetLeftPart() Method is an instance method that is used to get a specified part from the given URI based on passed UriPartial enum.
Syntax: string Uri.GetLeftPart (UriPartial Part);
Parameters:
Part: It represents UriPartial to get specified part from Uri.
Return Value: This method returns string value to represent specified part of Uri.
Exception: There are two type of exception are:
System.ArgumentException: If the specified part is not valid.
System.InvalidOperationException: If the current Uri instance is not an absolute instance.
Below programs illustrate the use of Uri.GetLeftPart() Method:
Example 1:
C#
// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing Uri Uri val; val = new Uri("https://www.geeksforgeeks.org/data-structure"); // Use of Uri.GetLeftPart() Method // Getting the Authority string str = val.GetLeftPart(UriPartial.Authority); Console.WriteLine(str); } }
Output:
https://www.geeksforgeeks.org
Example 2:
C#
// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing Uri Uri val; val = new Uri("https://www.geeksforgeeks.org/"); // Use of Uri.GetLeftPart() Method // Getting the Path string str1 = val.GetLeftPart(UriPartial.Path); Console.WriteLine(str1); // Getting the Query string str2 = val.GetLeftPart(UriPartial.Query); Console.WriteLine(str2); // Getting the Scheme string str3 = val.GetLeftPart(UriPartial.Scheme); Console.WriteLine(str3); } }
Output:
https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/
https://
CSharp-Uri-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 25683,
"s": 25547,
"text": "Uri.GetLeftPart() Method is an instance method that is used to get a specified part from the given URI based on passed UriPartial enum."
},
{
"code": null,
"e": 25733,
"s": 25683,
"text": "Syntax: string Uri.GetLeftPart (UriPartial Part);"
},
{
"code": null,
"e": 25745,
"s": 25733,
"text": "Parameters:"
},
{
"code": null,
"e": 25808,
"s": 25745,
"text": "Part: It represents UriPartial to get specified part from Uri."
},
{
"code": null,
"e": 25891,
"s": 25808,
"text": "Return Value: This method returns string value to represent specified part of Uri."
},
{
"code": null,
"e": 25939,
"s": 25891,
"text": "Exception: There are two type of exception are:"
},
{
"code": null,
"e": 26001,
"s": 25939,
"text": "System.ArgumentException: If the specified part is not valid."
},
{
"code": null,
"e": 26092,
"s": 26001,
"text": "System.InvalidOperationException: If the current Uri instance is not an absolute instance."
},
{
"code": null,
"e": 26155,
"s": 26092,
"text": "Below programs illustrate the use of Uri.GetLeftPart() Method:"
},
{
"code": null,
"e": 26166,
"s": 26155,
"text": "Example 1:"
},
{
"code": null,
"e": 26169,
"s": 26166,
"text": "C#"
},
{
"code": "// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing Uri Uri val; val = new Uri(\"https://www.geeksforgeeks.org/data-structure\"); // Use of Uri.GetLeftPart() Method // Getting the Authority string str = val.GetLeftPart(UriPartial.Authority); Console.WriteLine(str); } }",
"e": 26680,
"s": 26169,
"text": null
},
{
"code": null,
"e": 26688,
"s": 26680,
"text": "Output:"
},
{
"code": null,
"e": 26719,
"s": 26688,
"text": "https://www.geeksforgeeks.org\n"
},
{
"code": null,
"e": 26730,
"s": 26719,
"text": "Example 2:"
},
{
"code": null,
"e": 26733,
"s": 26730,
"text": "C#"
},
{
"code": "// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing Uri Uri val; val = new Uri(\"https://www.geeksforgeeks.org/\"); // Use of Uri.GetLeftPart() Method // Getting the Path string str1 = val.GetLeftPart(UriPartial.Path); Console.WriteLine(str1); // Getting the Query string str2 = val.GetLeftPart(UriPartial.Query); Console.WriteLine(str2); // Getting the Scheme string str3 = val.GetLeftPart(UriPartial.Scheme); Console.WriteLine(str3); } }",
"e": 27466,
"s": 26733,
"text": null
},
{
"code": null,
"e": 27474,
"s": 27466,
"text": "Output:"
},
{
"code": null,
"e": 27546,
"s": 27474,
"text": "https://www.geeksforgeeks.org/\nhttps://www.geeksforgeeks.org/\nhttps://\n"
},
{
"code": null,
"e": 27563,
"s": 27546,
"text": "CSharp-Uri-Class"
},
{
"code": null,
"e": 27566,
"s": 27563,
"text": "C#"
},
{
"code": null,
"e": 27664,
"s": 27566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27687,
"s": 27664,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27715,
"s": 27687,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27732,
"s": 27715,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27754,
"s": 27732,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27783,
"s": 27754,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27823,
"s": 27783,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27846,
"s": 27823,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 27889,
"s": 27846,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27929,
"s": 27889,
"text": "Convert String to Character Array in C#"
}
] |
Creating a Simple Application in Flutter - GeeksforGeeks
|
14 Aug, 2020
Flutter is an open-source cross-platform mobile application development SDK created by Google. It is highly user-friendly and builds high-quality mobile applications. The intention behind this article is to guide readers about the process of building an application through flutter by creating a simple Flutter App on Android Studio. To start creating a Flutter application we have to first create a flutter project and many other things, for that follow the steps mentioned below:
Step 1: Open the Android Studio IDE and select Start a new Flutter project.
Step 2: Select the Flutter Application as the project type. Then click Next.
Step 3: Verify the Flutter SDK path specifies the SDK’s location (select Install SDK... if the text field is blank).
Step 4: Enter a project name (for example, myapp). Then click Next.
Note:
1. Project name: flutter_app
2. Flutter SDK Path: <path-to-flutter-sdk>
3. Project Location: <path-to-project-folder>
4. Description: Flutter based simple application
Step 5: Click Finish and wait till Android Studio creates the project.
After successfully creating a file, we can edit the code of the application to show the output we want. Android Studio creates a fully working flutter application with minimal functionality. Let us check the structure of the application and then, change the code to do our task.
The structure of the application and its purpose are as follows?
We have to edit code in main.dart as mentioned in the above image. We can see that Android Studio has automatically generated most of the files for our flutter app.
Replace the dart code in the lib/main.dart file with the below code:
Dart
// Importing important packages require to connect // Flutter and Dartimport 'package:flutter/material.dart'; // Main Functionvoid main(){ // Giving command to runApp() to run the app. /* The purpose of the runApp() function is to attach the given widget to the screen. */ runApp(MyApp());} // Widget is used to create UI in flutter framework. /* StatelessWidget is a widget, which does not maintain any state of the widget. */ /* MyApp extends StatelessWidget and overrides its build method. */class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // title of the application title: 'Hello World Demo Application', // theme of the widget theme: ThemeData( primarySwatch: Colors.lightGreen, ), // Inner UI of the application home: MyHomePage(title: 'Home page'), ); }} /* This class is similar to MyApp instead it returns Scaffold Widget */class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), // Sets the content to the // center of the application page body: Center( // Sets the content of the Application child: Text( 'Welcome to GeeksForGeeks!', ) ), ); }}
Output:
android
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Flutter - Stack Widget
Operators in Dart
Android Studio Setup for Flutter Development
|
[
{
"code": null,
"e": 25235,
"s": 25207,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 25717,
"s": 25235,
"text": "Flutter is an open-source cross-platform mobile application development SDK created by Google. It is highly user-friendly and builds high-quality mobile applications. The intention behind this article is to guide readers about the process of building an application through flutter by creating a simple Flutter App on Android Studio. To start creating a Flutter application we have to first create a flutter project and many other things, for that follow the steps mentioned below:"
},
{
"code": null,
"e": 25793,
"s": 25717,
"text": "Step 1: Open the Android Studio IDE and select Start a new Flutter project."
},
{
"code": null,
"e": 25870,
"s": 25793,
"text": "Step 2: Select the Flutter Application as the project type. Then click Next."
},
{
"code": null,
"e": 25987,
"s": 25870,
"text": "Step 3: Verify the Flutter SDK path specifies the SDK’s location (select Install SDK... if the text field is blank)."
},
{
"code": null,
"e": 26055,
"s": 25987,
"text": "Step 4: Enter a project name (for example, myapp). Then click Next."
},
{
"code": null,
"e": 26231,
"s": 26055,
"text": "Note:\n1. Project name: flutter_app\n2. Flutter SDK Path: <path-to-flutter-sdk>\n3. Project Location: <path-to-project-folder>\n4. Description: Flutter based simple application\n\n\n"
},
{
"code": null,
"e": 26302,
"s": 26231,
"text": "Step 5: Click Finish and wait till Android Studio creates the project."
},
{
"code": null,
"e": 26581,
"s": 26302,
"text": "After successfully creating a file, we can edit the code of the application to show the output we want. Android Studio creates a fully working flutter application with minimal functionality. Let us check the structure of the application and then, change the code to do our task."
},
{
"code": null,
"e": 26646,
"s": 26581,
"text": "The structure of the application and its purpose are as follows?"
},
{
"code": null,
"e": 26811,
"s": 26646,
"text": "We have to edit code in main.dart as mentioned in the above image. We can see that Android Studio has automatically generated most of the files for our flutter app."
},
{
"code": null,
"e": 26880,
"s": 26811,
"text": "Replace the dart code in the lib/main.dart file with the below code:"
},
{
"code": null,
"e": 26885,
"s": 26880,
"text": "Dart"
},
{
"code": "// Importing important packages require to connect // Flutter and Dartimport 'package:flutter/material.dart'; // Main Functionvoid main(){ // Giving command to runApp() to run the app. /* The purpose of the runApp() function is to attach the given widget to the screen. */ runApp(MyApp());} // Widget is used to create UI in flutter framework. /* StatelessWidget is a widget, which does not maintain any state of the widget. */ /* MyApp extends StatelessWidget and overrides its build method. */class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // title of the application title: 'Hello World Demo Application', // theme of the widget theme: ThemeData( primarySwatch: Colors.lightGreen, ), // Inner UI of the application home: MyHomePage(title: 'Home page'), ); }} /* This class is similar to MyApp instead it returns Scaffold Widget */class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), // Sets the content to the // center of the application page body: Center( // Sets the content of the Application child: Text( 'Welcome to GeeksForGeeks!', ) ), ); }}",
"e": 28454,
"s": 26885,
"text": null
},
{
"code": null,
"e": 28462,
"s": 28454,
"text": "Output:"
},
{
"code": null,
"e": 28470,
"s": 28462,
"text": "android"
},
{
"code": null,
"e": 28478,
"s": 28470,
"text": "Flutter"
},
{
"code": null,
"e": 28483,
"s": 28478,
"text": "Dart"
},
{
"code": null,
"e": 28581,
"s": 28483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28613,
"s": 28581,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 28652,
"s": 28613,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28678,
"s": 28652,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 28704,
"s": 28678,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 28730,
"s": 28704,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 28757,
"s": 28730,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 28771,
"s": 28757,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 28794,
"s": 28771,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 28812,
"s": 28794,
"text": "Operators in Dart"
}
] |
Python String | zfill() - GeeksforGeeks
|
08 Jan, 2018
zfill() method returns a copy of the string with ‘0’ characters padded to the leftside of the given string.
Syntax :
str.zfill(length)
Parameters :
length : length is the length of the returned string from zfill() with ‘0’ digits filled to the leftside.
Return :
Returns a copy of the string with '0' characters
padded to the leftside of the given string.
CODE 1
text = "geeks for geeks" print(text.zfill(25)) print(text.zfill(20)) # Given length is less than# the length od original stringprint(text.zfill(10))
Output :
0000000000geeks for geeks
00000geeks for geeks
geeks for geeks
CODE 2
number = "6041"print(number.zfill(8)) number = "+6041"print(number.zfill(8)) text = "--anything%(&%(%)*^"print(text.zfill(20))
Output :
00006041
+0006041
-0-anything%(&%(%)*^
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 24293,
"s": 24265,
"text": "\n08 Jan, 2018"
},
{
"code": null,
"e": 24401,
"s": 24293,
"text": "zfill() method returns a copy of the string with ‘0’ characters padded to the leftside of the given string."
},
{
"code": null,
"e": 24410,
"s": 24401,
"text": "Syntax :"
},
{
"code": null,
"e": 24429,
"s": 24410,
"text": "str.zfill(length)\n"
},
{
"code": null,
"e": 24442,
"s": 24429,
"text": "Parameters :"
},
{
"code": null,
"e": 24548,
"s": 24442,
"text": "length : length is the length of the returned string from zfill() with ‘0’ digits filled to the leftside."
},
{
"code": null,
"e": 24557,
"s": 24548,
"text": "Return :"
},
{
"code": null,
"e": 24654,
"s": 24557,
"text": "Returns a copy of the string with '0' characters \npadded to the leftside of the given string.\n"
},
{
"code": null,
"e": 24661,
"s": 24654,
"text": "CODE 1"
},
{
"code": "text = \"geeks for geeks\" print(text.zfill(25)) print(text.zfill(20)) # Given length is less than# the length od original stringprint(text.zfill(10))",
"e": 24813,
"s": 24661,
"text": null
},
{
"code": null,
"e": 24822,
"s": 24813,
"text": "Output :"
},
{
"code": null,
"e": 24886,
"s": 24822,
"text": "0000000000geeks for geeks\n00000geeks for geeks\ngeeks for geeks\n"
},
{
"code": null,
"e": 24893,
"s": 24886,
"text": "CODE 2"
},
{
"code": "number = \"6041\"print(number.zfill(8)) number = \"+6041\"print(number.zfill(8)) text = \"--anything%(&%(%)*^\"print(text.zfill(20))",
"e": 25022,
"s": 24893,
"text": null
},
{
"code": null,
"e": 25031,
"s": 25022,
"text": "Output :"
},
{
"code": null,
"e": 25071,
"s": 25031,
"text": "00006041\n+0006041\n-0-anything%(&%(%)*^\n"
},
{
"code": null,
"e": 25085,
"s": 25071,
"text": "python-string"
},
{
"code": null,
"e": 25092,
"s": 25085,
"text": "Python"
},
{
"code": null,
"e": 25190,
"s": 25092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25218,
"s": 25190,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 25268,
"s": 25218,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 25290,
"s": 25268,
"text": "Python map() function"
},
{
"code": null,
"e": 25334,
"s": 25290,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 25352,
"s": 25334,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25375,
"s": 25352,
"text": "Taking input in Python"
},
{
"code": null,
"e": 25407,
"s": 25375,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25442,
"s": 25407,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25464,
"s": 25442,
"text": "Enumerate() in Python"
}
] |
How to check the user is using Internet Explorer in JavaScript? - GeeksforGeeks
|
14 May, 2019
There may arise cases when we need to check the browser being used. Some features of your website may not be supported in older browsers like Internet Explorer(IE). There are different ways to check the version of Internet Explorer being used.
Syntax-1: For Internet Explorer 10 or older
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
Syntax-2: For Internet Explorer 11
var ua = window.navigator.userAgent;
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
Syntax-3: For Internet Explorer 12+ (Edge)
var ua = window.navigator.userAgent;
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
Example:
<!DOCTYPE html><html> <head> <title> Detects user uses Internet Explorer </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <script> //detects if user uses Internet Explorer //returns version of IE or false, if browser is not IE //Function to detect IE or not function IEdetection() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older, return version number return ('IE ' + parseInt(ua.substring( msie + 5, ua.indexOf('.', msie)), 10)); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11, return version number var rv = ua.indexOf('rv:'); return ('IE ' + parseInt(ua.substring( rv + 3, ua.indexOf('.', rv)), 10)); } var edge = ua.indexOf('Edge/'); if (edge > 0) { //Edge (IE 12+), return version number return ('IE ' + parseInt(ua.substring( edge + 5, ua.indexOf('.', edge)), 10)); } // User uses other browser return ('Not IE'); } var result = IEdetection(); document.write(result); </script> </center></body> </html>
Output (Opening with Firefox):
Not IE
Output (Opening with IE 11):
IE 11
Output (Opening with Edge):
IE 18
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26165,
"s": 26137,
"text": "\n14 May, 2019"
},
{
"code": null,
"e": 26409,
"s": 26165,
"text": "There may arise cases when we need to check the browser being used. Some features of your website may not be supported in older browsers like Internet Explorer(IE). There are different ways to check the version of Internet Explorer being used."
},
{
"code": null,
"e": 26453,
"s": 26409,
"text": "Syntax-1: For Internet Explorer 10 or older"
},
{
"code": null,
"e": 26667,
"s": 26453,
"text": "var ua = window.navigator.userAgent;\nvar msie = ua.indexOf('MSIE ');\nif (msie > 0) {\n // IE 10 or older => return version number\n return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);\n }\n"
},
{
"code": null,
"e": 26702,
"s": 26667,
"text": "Syntax-2: For Internet Explorer 11"
},
{
"code": null,
"e": 26953,
"s": 26702,
"text": "var ua = window.navigator.userAgent;\nvar trident = ua.indexOf('Trident/');\nif (trident > 0) {\n // IE 11 => return version number\n var rv = ua.indexOf('rv:');\n return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);\n }\n"
},
{
"code": null,
"e": 26996,
"s": 26953,
"text": "Syntax-3: For Internet Explorer 12+ (Edge)"
},
{
"code": null,
"e": 27212,
"s": 26996,
"text": "var ua = window.navigator.userAgent;\nvar edge = ua.indexOf('Edge/');\nif (edge > 0) {\n // Edge (IE 12+) => return version number\n return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);\n }\n"
},
{
"code": null,
"e": 27221,
"s": 27212,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Detects user uses Internet Explorer </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <script> //detects if user uses Internet Explorer //returns version of IE or false, if browser is not IE //Function to detect IE or not function IEdetection() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older, return version number return ('IE ' + parseInt(ua.substring( msie + 5, ua.indexOf('.', msie)), 10)); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11, return version number var rv = ua.indexOf('rv:'); return ('IE ' + parseInt(ua.substring( rv + 3, ua.indexOf('.', rv)), 10)); } var edge = ua.indexOf('Edge/'); if (edge > 0) { //Edge (IE 12+), return version number return ('IE ' + parseInt(ua.substring( edge + 5, ua.indexOf('.', edge)), 10)); } // User uses other browser return ('Not IE'); } var result = IEdetection(); document.write(result); </script> </center></body> </html>",
"e": 28726,
"s": 27221,
"text": null
},
{
"code": null,
"e": 28757,
"s": 28726,
"text": "Output (Opening with Firefox):"
},
{
"code": null,
"e": 28764,
"s": 28757,
"text": "Not IE"
},
{
"code": null,
"e": 28793,
"s": 28764,
"text": "Output (Opening with IE 11):"
},
{
"code": null,
"e": 28799,
"s": 28793,
"text": "IE 11"
},
{
"code": null,
"e": 28827,
"s": 28799,
"text": "Output (Opening with Edge):"
},
{
"code": null,
"e": 28833,
"s": 28827,
"text": "IE 18"
},
{
"code": null,
"e": 28849,
"s": 28833,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28856,
"s": 28849,
"text": "Picked"
},
{
"code": null,
"e": 28867,
"s": 28856,
"text": "JavaScript"
},
{
"code": null,
"e": 28884,
"s": 28867,
"text": "Web Technologies"
},
{
"code": null,
"e": 28982,
"s": 28884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29022,
"s": 28982,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29067,
"s": 29022,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29128,
"s": 29067,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29200,
"s": 29128,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29241,
"s": 29200,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29281,
"s": 29241,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29314,
"s": 29281,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29359,
"s": 29314,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29402,
"s": 29359,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Lex program to copy the content of one file to another file - GeeksforGeeks
|
07 Apr, 2021
Problem: Given a text file as input, the task is to copy the content of the given file to another file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the text matched by the current token. Append the value of yytext to a temporary string. If a newline character (‘\n’) is encountered, write the content of temporary string to destination file. Input File: input.txt
GeeksForGeeks: A Computer Science portal for geeks.
Below is the implementation of above approach:
C
/* LEX code to replace a word with another taking input from file */ /* Definition section *//* character array line can be accessed inside rule section and main() */ %{#include<stdio.h>#include<string.h>char line[100]; %} /* Rule Section *//* Rule 1 writes the string stored in line character array to file output.txt *//* Rule 2 copies the matched token i.e every character except newline character to line character array */ %%['\n'] { fprintf(yyout,"%s\n",line);}(.*) { strcpy(line,yytext); line[0] = '\0'; }<<EOF>> { fprintf(yyout,"%s",line); return 0;}%% int yywrap(){ return 1;} /* code section */int main(){ extern FILE *yyin, *yyout; /* open the source file in read mode */ yyin=fopen("input.txt","r"); /* open the output file in write mode */ yyout=fopen("output.txt","w"); yylex();}
Output:
Output file: output.txt
GeeksForGeeks: A Computer Science portal for geeks.
y_27
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Issues in the design of a code generator
Error Handling in Compiler Design
Error detection and Recovery in Compiler
Difference between Top down parsing and Bottom up parsing
Runtime Environments in Compiler Design
Loop Optimization in Compiler Design
Why FIRST and FOLLOW in Compiler Design?
Bottom Up or Shift Reduce Parsers | Set 2
|
[
{
"code": null,
"e": 25691,
"s": 25663,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26302,
"s": 25691,
"text": "Problem: Given a text file as input, the task is to copy the content of the given file to another file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the text matched by the current token. Append the value of yytext to a temporary string. If a newline character (‘\\n’) is encountered, write the content of temporary string to destination file. Input File: input.txt "
},
{
"code": null,
"e": 26354,
"s": 26302,
"text": "GeeksForGeeks: A Computer Science portal for geeks."
},
{
"code": null,
"e": 26402,
"s": 26354,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26404,
"s": 26402,
"text": "C"
},
{
"code": "/* LEX code to replace a word with another taking input from file */ /* Definition section *//* character array line can be accessed inside rule section and main() */ %{#include<stdio.h>#include<string.h>char line[100]; %} /* Rule Section *//* Rule 1 writes the string stored in line character array to file output.txt *//* Rule 2 copies the matched token i.e every character except newline character to line character array */ %%['\\n'] { fprintf(yyout,\"%s\\n\",line);}(.*) { strcpy(line,yytext); line[0] = '\\0'; }<<EOF>> { fprintf(yyout,\"%s\",line); return 0;}%% int yywrap(){ return 1;} /* code section */int main(){ extern FILE *yyin, *yyout; /* open the source file in read mode */ yyin=fopen(\"input.txt\",\"r\"); /* open the output file in write mode */ yyout=fopen(\"output.txt\",\"w\"); yylex();}",
"e": 27285,
"s": 26404,
"text": null
},
{
"code": null,
"e": 27294,
"s": 27285,
"text": "Output: "
},
{
"code": null,
"e": 27320,
"s": 27294,
"text": "Output file: output.txt "
},
{
"code": null,
"e": 27372,
"s": 27320,
"text": "GeeksForGeeks: A Computer Science portal for geeks."
},
{
"code": null,
"e": 27379,
"s": 27374,
"text": "y_27"
},
{
"code": null,
"e": 27391,
"s": 27379,
"text": "Lex program"
},
{
"code": null,
"e": 27407,
"s": 27391,
"text": "Compiler Design"
},
{
"code": null,
"e": 27505,
"s": 27407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27563,
"s": 27505,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 27633,
"s": 27563,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 27674,
"s": 27633,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 27708,
"s": 27674,
"text": "Error Handling in Compiler Design"
},
{
"code": null,
"e": 27749,
"s": 27708,
"text": "Error detection and Recovery in Compiler"
},
{
"code": null,
"e": 27807,
"s": 27749,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 27847,
"s": 27807,
"text": "Runtime Environments in Compiler Design"
},
{
"code": null,
"e": 27884,
"s": 27847,
"text": "Loop Optimization in Compiler Design"
},
{
"code": null,
"e": 27925,
"s": 27884,
"text": "Why FIRST and FOLLOW in Compiler Design?"
}
] |
Working with csv files in Python - GeeksforGeeks
|
19 Feb, 2022
This article explains how to load and parse a CSV file in Python.First of all, what is a CSV ? CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.For working CSV files in python, there is an inbuilt module called csv.
Reading a CSV file
Python
# importing csv moduleimport csv # csv file namefilename = "aapl.csv" # initializing the titles and rows listfields = []rows = [] # reading csv filewith open(filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names through first row fields = next(csvreader) # extracting each data row one by one for row in csvreader: rows.append(row) # get total number of rows print("Total no. of rows: %d"%(csvreader.line_num)) # printing the field namesprint('Field names are:' + ', '.join(field for field in fields)) # printing first 5 rowsprint('\nFirst 5 rows are:\n')for row in rows[:5]: # parsing each column of a row for col in row: print("%10s"%col,end=" "), print('\n')
The output of the above program looks like this:
The above example uses a CSV file aapl.csv which can be downloaded from here. Run this program with the aapl.csv file in the same directory.Let us try to understand this piece of code.
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
Here, we first open the CSV file in READ mode. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object as csvreader.
fields = csvreader.next()
csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), we save them in a list called fields.
for row in csvreader:
rows.append(row)
Now, we iterate through the remaining rows using a for loop. Each row is appended to a list called rows. If you try to print each row, one can find that a row is nothing but a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
csvreader.line_num is nothing but a counter which returns the number of rows that have been iterated.
Writing to a CSV file
Python
# importing the csv moduleimport csv # field namesfields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv filerows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv filefilename = "university_records.csv" # writing to csv filewith open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows)
Let us try to understand the above code in pieces.
fields and rows have been already defined. fields is a list containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row.
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
Here, we first open the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. We save the csv.writer object as csvwriter.
csvwriter.writerow(fields)
Now we use writerow method to write the first row which is nothing but the field names.
csvwriter.writerows(rows)
We use writerows method to write multiple rows at once.
Writing a dictionary to a CSV file
Python
# importing the csv moduleimport csv # my data rows as dictionary objectsmydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] # field namesfields = ['name', 'branch', 'year', 'cgpa'] # name of csv filefilename = "university_records.csv" # writing to csv filewith open(filename, 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile, fieldnames = fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(mydict)
In this example, we write a dictionary mydict to a CSV file.
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
Here, the file object (csvfile) is converted to a DictWriter object. Here, we specify the fieldnames as an argument.
writer.writeheader()
writeheader method simply writes the first row of your csv file using the pre-specified fieldnames.
writer.writerows(mydict)
writerows method simply writes all the rows but in each row, it writes only the values(not keys).
So, in the end, our CSV file looks like this:
Important Points:
In csv modules, an optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. You can define your own dialect using register_dialect method. Here is an example:
Now, while defining a csv.reader or csv.writer object, we can specify the dialect like this:
Now, consider that a CSV file looks like this in plain-text:
We notice that the delimiter is not a comma but a semi-colon. Also, the rows are separated by two newlines instead of one. In such cases, we can specify the delimiter and line terminator as follows:
So, this was a brief, yet concise discussion on how to load and parse CSV files in a python program.
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Working with CSV files in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9DzfTARXJE0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This blog is contributed by Nikhil Kumar. 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.
NishaAfrin
27montegu
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
GET and POST requests using Python
Must Do Coding Questions for Product Based Companies
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
|
[
{
"code": null,
"e": 42677,
"s": 42649,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 43221,
"s": 42677,
"text": "This article explains how to load and parse a CSV file in Python.First of all, what is a CSV ? CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.For working CSV files in python, there is an inbuilt module called csv. "
},
{
"code": null,
"e": 43240,
"s": 43221,
"text": "Reading a CSV file"
},
{
"code": null,
"e": 43249,
"s": 43242,
"text": "Python"
},
{
"code": "# importing csv moduleimport csv # csv file namefilename = \"aapl.csv\" # initializing the titles and rows listfields = []rows = [] # reading csv filewith open(filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names through first row fields = next(csvreader) # extracting each data row one by one for row in csvreader: rows.append(row) # get total number of rows print(\"Total no. of rows: %d\"%(csvreader.line_num)) # printing the field namesprint('Field names are:' + ', '.join(field for field in fields)) # printing first 5 rowsprint('\\nFirst 5 rows are:\\n')for row in rows[:5]: # parsing each column of a row for col in row: print(\"%10s\"%col,end=\" \"), print('\\n')",
"e": 44027,
"s": 43249,
"text": null
},
{
"code": null,
"e": 44077,
"s": 44027,
"text": "The output of the above program looks like this: "
},
{
"code": null,
"e": 44264,
"s": 44077,
"text": "The above example uses a CSV file aapl.csv which can be downloaded from here. Run this program with the aapl.csv file in the same directory.Let us try to understand this piece of code. "
},
{
"code": null,
"e": 44339,
"s": 44266,
"text": "with open(filename, 'r') as csvfile:\n csvreader = csv.reader(csvfile)"
},
{
"code": null,
"e": 44518,
"s": 44339,
"text": "Here, we first open the CSV file in READ mode. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object as csvreader."
},
{
"code": null,
"e": 44546,
"s": 44520,
"text": "fields = csvreader.next()"
},
{
"code": null,
"e": 44781,
"s": 44546,
"text": "csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), we save them in a list called fields."
},
{
"code": null,
"e": 44830,
"s": 44783,
"text": "for row in csvreader:\n rows.append(row)"
},
{
"code": null,
"e": 45044,
"s": 44830,
"text": "Now, we iterate through the remaining rows using a for loop. Each row is appended to a list called rows. If you try to print each row, one can find that a row is nothing but a list containing all the field values."
},
{
"code": null,
"e": 45098,
"s": 45046,
"text": "print(\"Total no. of rows: %d\"%(csvreader.line_num))"
},
{
"code": null,
"e": 45200,
"s": 45098,
"text": "csvreader.line_num is nothing but a counter which returns the number of rows that have been iterated."
},
{
"code": null,
"e": 45224,
"s": 45202,
"text": "Writing to a CSV file"
},
{
"code": null,
"e": 45233,
"s": 45226,
"text": "Python"
},
{
"code": "# importing the csv moduleimport csv # field namesfields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv filerows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv filefilename = \"university_records.csv\" # writing to csv filewith open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows)",
"e": 45883,
"s": 45233,
"text": null
},
{
"code": null,
"e": 45936,
"s": 45883,
"text": "Let us try to understand the above code in pieces. "
},
{
"code": null,
"e": 46113,
"s": 45936,
"text": "fields and rows have been already defined. fields is a list containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row."
},
{
"code": null,
"e": 46188,
"s": 46115,
"text": "with open(filename, 'w') as csvfile:\n csvwriter = csv.writer(csvfile)"
},
{
"code": null,
"e": 46368,
"s": 46188,
"text": "Here, we first open the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. We save the csv.writer object as csvwriter."
},
{
"code": null,
"e": 46397,
"s": 46370,
"text": "csvwriter.writerow(fields)"
},
{
"code": null,
"e": 46485,
"s": 46397,
"text": "Now we use writerow method to write the first row which is nothing but the field names."
},
{
"code": null,
"e": 46514,
"s": 46487,
"text": " csvwriter.writerows(rows)"
},
{
"code": null,
"e": 46570,
"s": 46514,
"text": "We use writerows method to write multiple rows at once."
},
{
"code": null,
"e": 46607,
"s": 46572,
"text": "Writing a dictionary to a CSV file"
},
{
"code": null,
"e": 46616,
"s": 46609,
"text": "Python"
},
{
"code": "# importing the csv moduleimport csv # my data rows as dictionary objectsmydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] # field namesfields = ['name', 'branch', 'year', 'cgpa'] # name of csv filefilename = \"university_records.csv\" # writing to csv filewith open(filename, 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile, fieldnames = fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(mydict)",
"e": 47510,
"s": 46616,
"text": null
},
{
"code": null,
"e": 47573,
"s": 47510,
"text": "In this example, we write a dictionary mydict to a CSV file. "
},
{
"code": null,
"e": 47670,
"s": 47575,
"text": "with open(filename, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames = fields)"
},
{
"code": null,
"e": 47787,
"s": 47670,
"text": "Here, the file object (csvfile) is converted to a DictWriter object. Here, we specify the fieldnames as an argument."
},
{
"code": null,
"e": 47811,
"s": 47789,
"text": " writer.writeheader()"
},
{
"code": null,
"e": 47911,
"s": 47811,
"text": "writeheader method simply writes the first row of your csv file using the pre-specified fieldnames."
},
{
"code": null,
"e": 47938,
"s": 47913,
"text": "writer.writerows(mydict)"
},
{
"code": null,
"e": 48036,
"s": 47938,
"text": "writerows method simply writes all the rows but in each row, it writes only the values(not keys)."
},
{
"code": null,
"e": 48083,
"s": 48036,
"text": "So, in the end, our CSV file looks like this: "
},
{
"code": null,
"e": 48103,
"s": 48083,
"text": "Important Points: "
},
{
"code": null,
"e": 48423,
"s": 48103,
"text": "In csv modules, an optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. You can define your own dialect using register_dialect method. Here is an example: "
},
{
"code": null,
"e": 48522,
"s": 48427,
"text": "Now, while defining a csv.reader or csv.writer object, we can specify the dialect like this: "
},
{
"code": null,
"e": 48589,
"s": 48526,
"text": "Now, consider that a CSV file looks like this in plain-text: "
},
{
"code": null,
"e": 48790,
"s": 48589,
"text": "We notice that the delimiter is not a comma but a semi-colon. Also, the rows are separated by two newlines instead of one. In such cases, we can specify the delimiter and line terminator as follows: "
},
{
"code": null,
"e": 48897,
"s": 48794,
"text": "So, this was a brief, yet concise discussion on how to load and parse CSV files in a python program. "
},
{
"code": null,
"e": 49758,
"s": 48897,
"text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Working with CSV files in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9DzfTARXJE0\" 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": 50176,
"s": 49758,
"text": "This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 50187,
"s": 50176,
"text": "NishaAfrin"
},
{
"code": null,
"e": 50197,
"s": 50187,
"text": "27montegu"
},
{
"code": null,
"e": 50203,
"s": 50197,
"text": "GBlog"
},
{
"code": null,
"e": 50210,
"s": 50203,
"text": "Python"
},
{
"code": null,
"e": 50308,
"s": 50210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50382,
"s": 50308,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 50407,
"s": 50382,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 50435,
"s": 50407,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 50470,
"s": 50435,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 50523,
"s": 50470,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 50551,
"s": 50523,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 50601,
"s": 50551,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 50623,
"s": 50601,
"text": "Python map() function"
},
{
"code": null,
"e": 50667,
"s": 50623,
"text": "How to get column names in Pandas dataframe"
}
] |
Program to Convert List to Map in Java - GeeksforGeeks
|
19 Jun, 2019
The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.
The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.
Example:
Input: List : [1="1", 2="2", 3="3"]
Output: Map : {1=1, 2=2, 3=3}
Input: List : [1="Geeks", 2="for", 3="Geeks"]
Output: Map : {1=Geeks, 2=for, 3=Geeks}
Below are various ways to convert List to Map in Java. For this, it is assumed that each element of the List has an identifier which will be used as a key in the resulting Map.
Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println("Map : " + map); }}Output:Map : {1=Geeks, 2=For, 3=Geeks}
Using Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + ", " + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + "=" + y)); }}Output:1=Geeks
2=For
3=Geeks
Creating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(1, "For")); lt.add(new Student(2, "Geeks")); lt.add(new Student(2, "GeeksForGeeks")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println("MultiMap = " + multimap); }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}
Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println("Map : " + map); }}Output:Map : {1=Geeks, 2=For, 3=Geeks}
Approach:
Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map
Get the List to be converted into Map
Create an empty Map
Iterate through the items in the list and add each of them into the Map.
Return the formed Map
// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println("Map : " + map); }}
Map : {1=Geeks, 2=For, 3=Geeks}
Using Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + ", " + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + "=" + y)); }}Output:1=Geeks
2=For
3=Geeks
Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map
Get the List to be converted into Map
Convert the List into stream using List.stream() method
Create map with the help of Collectors.toMap() method
Collect the formed Map using stream.collect() method
Return the formed Map
// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + ", " + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + "=" + y)); }}
1=Geeks
2=For
3=Geeks
Creating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(1, "For")); lt.add(new Student(2, "Geeks")); lt.add(new Student(2, "GeeksForGeeks")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println("MultiMap = " + multimap); }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}
Approach:
Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map
Get the List to be converted into Map
Convert the List into stream using List.stream() method
Create map with the help of Collectors.groupingBy() method
Collect the formed Map using stream.collect() method
Return the formed Map
// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(1, "For")); lt.add(new Student(2, "Geeks")); lt.add(new Student(2, "GeeksForGeeks")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println("MultiMap = " + multimap); }}
MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}
nidhi_biet
Java-Collections
java-list
Java-List-Programs
java-map
Java-Map-Programs
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 25469,
"s": 25441,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 25773,
"s": 25469,
"text": "The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes."
},
{
"code": null,
"e": 25989,
"s": 25773,
"text": "The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types."
},
{
"code": null,
"e": 25998,
"s": 25989,
"text": "Example:"
},
{
"code": null,
"e": 26152,
"s": 25998,
"text": "Input: List : [1=\"1\", 2=\"2\", 3=\"3\"]\nOutput: Map : {1=1, 2=2, 3=3}\n\nInput: List : [1=\"Geeks\", 2=\"for\", 3=\"Geeks\"]\nOutput: Map : {1=Geeks, 2=for, 3=Geeks}\n"
},
{
"code": null,
"e": 26329,
"s": 26152,
"text": "Below are various ways to convert List to Map in Java. For this, it is assumed that each element of the List has an identifier which will be used as a key in the resulting Map."
},
{
"code": null,
"e": 32186,
"s": 26329,
"text": "Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println(\"Map : \" + map); }}Output:Map : {1=Geeks, 2=For, 3=Geeks}\nUsing Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + \", \" + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + \"=\" + y)); }}Output:1=Geeks\n2=For\n3=Geeks\nCreating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(1, \"For\")); lt.add(new Student(2, \"Geeks\")); lt.add(new Student(2, \"GeeksForGeeks\")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println(\"MultiMap = \" + multimap); }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}\n"
},
{
"code": null,
"e": 33795,
"s": 32186,
"text": "Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println(\"Map : \" + map); }}Output:Map : {1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 33805,
"s": 33795,
"text": "Approach:"
},
{
"code": null,
"e": 33955,
"s": 33805,
"text": "Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map"
},
{
"code": null,
"e": 33993,
"s": 33955,
"text": "Get the List to be converted into Map"
},
{
"code": null,
"e": 34013,
"s": 33993,
"text": "Create an empty Map"
},
{
"code": null,
"e": 34086,
"s": 34013,
"text": "Iterate through the items in the list and add each of them into the Map."
},
{
"code": null,
"e": 34108,
"s": 34086,
"text": "Return the formed Map"
},
{
"code": "// Java program for list convert in map// with the help of Object method import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println(\"Map : \" + map); }}",
"e": 35495,
"s": 34108,
"text": null
},
{
"code": null,
"e": 35529,
"s": 35495,
"text": "Map : {1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 37577,
"s": 35529,
"text": "Using Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + \", \" + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + \"=\" + y)); }}Output:1=Geeks\n2=For\n3=Geeks\n"
},
{
"code": null,
"e": 37796,
"s": 37577,
"text": "Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map"
},
{
"code": null,
"e": 37834,
"s": 37796,
"text": "Get the List to be converted into Map"
},
{
"code": null,
"e": 37890,
"s": 37834,
"text": "Convert the List into stream using List.stream() method"
},
{
"code": null,
"e": 37944,
"s": 37890,
"text": "Create map with the help of Collectors.toMap() method"
},
{
"code": null,
"e": 37997,
"s": 37944,
"text": "Collect the formed Map using stream.collect() method"
},
{
"code": null,
"e": 38019,
"s": 37997,
"text": "Return the formed Map"
},
{
"code": "// Java program for list convert in map// with the help of Collectors.toMap() method import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(2, \"For\")); lt.add(new Student(3, \"Geeks\")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + \", \" + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + \"=\" + y)); }}",
"e": 39661,
"s": 38019,
"text": null
},
{
"code": null,
"e": 39684,
"s": 39661,
"text": "1=Geeks\n2=For\n3=Geeks\n"
},
{
"code": null,
"e": 41886,
"s": 39684,
"text": "Creating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(1, \"For\")); lt.add(new Student(2, \"Geeks\")); lt.add(new Student(2, \"GeeksForGeeks\")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println(\"MultiMap = \" + multimap); }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}\n"
},
{
"code": null,
"e": 41896,
"s": 41886,
"text": "Approach:"
},
{
"code": null,
"e": 42120,
"s": 41896,
"text": "Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map"
},
{
"code": null,
"e": 42158,
"s": 42120,
"text": "Get the List to be converted into Map"
},
{
"code": null,
"e": 42214,
"s": 42158,
"text": "Convert the List into stream using List.stream() method"
},
{
"code": null,
"e": 42273,
"s": 42214,
"text": "Create map with the help of Collectors.groupingBy() method"
},
{
"code": null,
"e": 42326,
"s": 42273,
"text": "Collect the formed Map using stream.collect() method"
},
{
"code": null,
"e": 42348,
"s": 42326,
"text": "Return the formed Map"
},
{
"code": "// Java program for list convert in map// with the help of Collectors.groupingBy() method import java.util.*;import java.util.stream.Collectors; // create a listclass Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; }} // main class and methodpublic class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, \"Geeks\")); lt.add(new Student(1, \"For\")); lt.add(new Student(2, \"Geeks\")); lt.add(new Student(2, \"GeeksForGeeks\")); // create map with the help of // Object (stu) method // create object of Multi Map class // create multimap and store the value of list Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); // print the multiMap System.out.println(\"MultiMap = \" + multimap); }}",
"e": 44209,
"s": 42348,
"text": null
},
{
"code": null,
"e": 44264,
"s": 44209,
"text": "MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}\n"
},
{
"code": null,
"e": 44275,
"s": 44264,
"text": "nidhi_biet"
},
{
"code": null,
"e": 44292,
"s": 44275,
"text": "Java-Collections"
},
{
"code": null,
"e": 44302,
"s": 44292,
"text": "java-list"
},
{
"code": null,
"e": 44321,
"s": 44302,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 44330,
"s": 44321,
"text": "java-map"
},
{
"code": null,
"e": 44348,
"s": 44330,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 44372,
"s": 44348,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 44377,
"s": 44372,
"text": "Java"
},
{
"code": null,
"e": 44396,
"s": 44377,
"text": "Technical Scripter"
},
{
"code": null,
"e": 44401,
"s": 44396,
"text": "Java"
},
{
"code": null,
"e": 44418,
"s": 44401,
"text": "Java-Collections"
},
{
"code": null,
"e": 44516,
"s": 44418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44531,
"s": 44516,
"text": "Stream In Java"
},
{
"code": null,
"e": 44550,
"s": 44531,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 44568,
"s": 44550,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 44600,
"s": 44568,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 44620,
"s": 44600,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 44652,
"s": 44620,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 44676,
"s": 44652,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 44699,
"s": 44676,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 44719,
"s": 44699,
"text": "Collections in Java"
}
] |
RFM Analysis Analysis Using Python - GeeksforGeeks
|
08 Nov, 2021
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly.
RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium value customers or low-value customers, and similarly many others.
Let’s assume we are a company, our company name is geek, let’s perform the RFM analysis on our customers
Recency: How recently has the customer made a transaction with usFrequency: How frequent is the customer in ordering/buying some product from usMonetary: How much does the customer spend on purchasing products from us.
Recency: How recently has the customer made a transaction with us
Frequency: How frequent is the customer in ordering/buying some product from us
Monetary: How much does the customer spend on purchasing products from us.
Here we will import the required module( pandas, DateTime, and NumPy) and then read the data in the dataframe.
Dataset Used: rfm
Python3
# importing necessary librariesimport pandas as pdimport datetime as dtimport numpy as np # importing the datadf = pd.read_excel( < my excel file location > )df.head()
Here we are calculating recency for customers who had made a purchase with a company.
Python3
df_recency = df.groupby(by='Customer Name', as_index=False)['Order Date'].max()df_recency.columns = ['CustomerName', 'LastPurchaseDate']recent_date = df_recency['LastPurchaseDate'].max()df_recency['Recency'] = df_recency['LastPurchaseDate'].apply( lambda x: (recent_date - x).days)df_recency.head()
We are here calculating the frequency of frequent transactions of the customer in ordering/buying some product from the company.
Python3
frequency_df = df.drop_duplicates().groupby( by=['Customer Name'], as_index=False)['Order Date'].count()frequency_df.columns = ['CustomerName', 'Frequency']frequency_df.head()
Here we are calculating the monetary value of customer spend on purchasing products from the company.
Python3
df['Total'] = df['Sales']*df['Quantity']monetary_df = df.groupby(by='Customer Name', as_index=False)['Total'].sum()monetary_df.columns = ['CustomerName', 'Monetary']monetary_df.head()
Here we are mering all the dataframe columns in a single entity using the merge function to display the recency, frequency, monetary value.
Python3
rf_df = df_recency.merge(frequency_df, on='CustomerName')rfm_df = rf_df.merge(monetary_df, on='CustomerName').drop( columns='LastPurchaseDate')rfm_df.head()
Here we are normalizing the rank of the customers within a company to analyze the ranking.
Python3
rfm_df['R_rank'] = rfm_df['Recency'].rank(ascending=False)rfm_df['F_rank'] = rfm_df['Frequency'].rank(ascending=True)rfm_df['M_rank'] = rfm_df['Monetary'].rank(ascending=True) # normalizing the rank of the customersrfm_df['R_rank_norm'] = (rfm_df['R_rank']/rfm_df['R_rank'].max())*100rfm_df['F_rank_norm'] = (rfm_df['F_rank']/rfm_df['F_rank'].max())*100rfm_df['M_rank_norm'] = (rfm_df['F_rank']/rfm_df['M_rank'].max())*100 rfm_df.drop(columns=['R_rank', 'F_rank', 'M_rank'], inplace=True) rfm_df.head()
RFM score is calculated based upon recency, frequency, monetary value normalize ranks. Based upon this score we divide our customers. Here we rate them on a scale of 5. Formula used for calculating rfm score is : 0.15*Recency score + 0.28*Frequency score + 0.57 *Monetary score
Python3
rfm_df['RFM_Score'] = 0.15*rfm_df['R_rank_norm']+0.28 * \ rfm_df['F_rank_norm']+0.57*rfm_df['M_rank_norm']rfm_df['RFM_Score'] *= 0.05rfm_df = rfm_df.round(2)rfm_df[['CustomerName', 'RFM_Score']].head(7)
rfm score >4.5 : Top Customer
4.5 > rfm score > 4 : High Value Customer
4>rfm score >3 : Medium value customer
3>rfm score>1.6 : Low-value customer
rfm score<1.6 :Lost Customer
Python3
rfm_df["Customer_segment"] = np.where(rfm_df['RFM_Score'] > 4.5, "Top Customers", (np.where( rfm_df['RFM_Score'] > 4, "High value Customer", (np.where( rfm_df['RFM_Score'] > 3, "Medium Value Customer", np.where(rfm_df['RFM_Score'] > 1.6, 'Low Value Customers', 'Lost Customers'))))))rfm_df[['CustomerName', 'RFM_Score', 'Customer_segment']].head(20)
Here we will use a pie plot to display all segments of customers.
Python3
plt.pie(rfm_df.Customer_segment.value_counts(), labels=rfm_df.Customer_segment.value_counts().index, autopct='%.0f%%')plt.show()
clintra
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 25713,
"s": 25563,
"text": "In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly."
},
{
"code": null,
"e": 25959,
"s": 25713,
"text": "RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium value customers or low-value customers, and similarly many others."
},
{
"code": null,
"e": 26064,
"s": 25959,
"text": "Let’s assume we are a company, our company name is geek, let’s perform the RFM analysis on our customers"
},
{
"code": null,
"e": 26283,
"s": 26064,
"text": "Recency: How recently has the customer made a transaction with usFrequency: How frequent is the customer in ordering/buying some product from usMonetary: How much does the customer spend on purchasing products from us."
},
{
"code": null,
"e": 26349,
"s": 26283,
"text": "Recency: How recently has the customer made a transaction with us"
},
{
"code": null,
"e": 26429,
"s": 26349,
"text": "Frequency: How frequent is the customer in ordering/buying some product from us"
},
{
"code": null,
"e": 26504,
"s": 26429,
"text": "Monetary: How much does the customer spend on purchasing products from us."
},
{
"code": null,
"e": 26615,
"s": 26504,
"text": "Here we will import the required module( pandas, DateTime, and NumPy) and then read the data in the dataframe."
},
{
"code": null,
"e": 26633,
"s": 26615,
"text": "Dataset Used: rfm"
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Python3"
},
{
"code": "# importing necessary librariesimport pandas as pdimport datetime as dtimport numpy as np # importing the datadf = pd.read_excel( < my excel file location > )df.head()",
"e": 26809,
"s": 26641,
"text": null
},
{
"code": null,
"e": 26895,
"s": 26809,
"text": "Here we are calculating recency for customers who had made a purchase with a company."
},
{
"code": null,
"e": 26903,
"s": 26895,
"text": "Python3"
},
{
"code": "df_recency = df.groupby(by='Customer Name', as_index=False)['Order Date'].max()df_recency.columns = ['CustomerName', 'LastPurchaseDate']recent_date = df_recency['LastPurchaseDate'].max()df_recency['Recency'] = df_recency['LastPurchaseDate'].apply( lambda x: (recent_date - x).days)df_recency.head()",
"e": 27228,
"s": 26903,
"text": null
},
{
"code": null,
"e": 27357,
"s": 27228,
"text": "We are here calculating the frequency of frequent transactions of the customer in ordering/buying some product from the company."
},
{
"code": null,
"e": 27365,
"s": 27357,
"text": "Python3"
},
{
"code": "frequency_df = df.drop_duplicates().groupby( by=['Customer Name'], as_index=False)['Order Date'].count()frequency_df.columns = ['CustomerName', 'Frequency']frequency_df.head()",
"e": 27544,
"s": 27365,
"text": null
},
{
"code": null,
"e": 27646,
"s": 27544,
"text": "Here we are calculating the monetary value of customer spend on purchasing products from the company."
},
{
"code": null,
"e": 27654,
"s": 27646,
"text": "Python3"
},
{
"code": "df['Total'] = df['Sales']*df['Quantity']monetary_df = df.groupby(by='Customer Name', as_index=False)['Total'].sum()monetary_df.columns = ['CustomerName', 'Monetary']monetary_df.head()",
"e": 27838,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27978,
"s": 27838,
"text": "Here we are mering all the dataframe columns in a single entity using the merge function to display the recency, frequency, monetary value."
},
{
"code": null,
"e": 27986,
"s": 27978,
"text": "Python3"
},
{
"code": "rf_df = df_recency.merge(frequency_df, on='CustomerName')rfm_df = rf_df.merge(monetary_df, on='CustomerName').drop( columns='LastPurchaseDate')rfm_df.head()",
"e": 28146,
"s": 27986,
"text": null
},
{
"code": null,
"e": 28237,
"s": 28146,
"text": "Here we are normalizing the rank of the customers within a company to analyze the ranking."
},
{
"code": null,
"e": 28245,
"s": 28237,
"text": "Python3"
},
{
"code": "rfm_df['R_rank'] = rfm_df['Recency'].rank(ascending=False)rfm_df['F_rank'] = rfm_df['Frequency'].rank(ascending=True)rfm_df['M_rank'] = rfm_df['Monetary'].rank(ascending=True) # normalizing the rank of the customersrfm_df['R_rank_norm'] = (rfm_df['R_rank']/rfm_df['R_rank'].max())*100rfm_df['F_rank_norm'] = (rfm_df['F_rank']/rfm_df['F_rank'].max())*100rfm_df['M_rank_norm'] = (rfm_df['F_rank']/rfm_df['M_rank'].max())*100 rfm_df.drop(columns=['R_rank', 'F_rank', 'M_rank'], inplace=True) rfm_df.head()",
"e": 28748,
"s": 28245,
"text": null
},
{
"code": null,
"e": 29026,
"s": 28748,
"text": "RFM score is calculated based upon recency, frequency, monetary value normalize ranks. Based upon this score we divide our customers. Here we rate them on a scale of 5. Formula used for calculating rfm score is : 0.15*Recency score + 0.28*Frequency score + 0.57 *Monetary score"
},
{
"code": null,
"e": 29034,
"s": 29026,
"text": "Python3"
},
{
"code": "rfm_df['RFM_Score'] = 0.15*rfm_df['R_rank_norm']+0.28 * \\ rfm_df['F_rank_norm']+0.57*rfm_df['M_rank_norm']rfm_df['RFM_Score'] *= 0.05rfm_df = rfm_df.round(2)rfm_df[['CustomerName', 'RFM_Score']].head(7)",
"e": 29240,
"s": 29034,
"text": null
},
{
"code": null,
"e": 29270,
"s": 29240,
"text": "rfm score >4.5 : Top Customer"
},
{
"code": null,
"e": 29312,
"s": 29270,
"text": "4.5 > rfm score > 4 : High Value Customer"
},
{
"code": null,
"e": 29351,
"s": 29312,
"text": "4>rfm score >3 : Medium value customer"
},
{
"code": null,
"e": 29388,
"s": 29351,
"text": "3>rfm score>1.6 : Low-value customer"
},
{
"code": null,
"e": 29417,
"s": 29388,
"text": "rfm score<1.6 :Lost Customer"
},
{
"code": null,
"e": 29425,
"s": 29417,
"text": "Python3"
},
{
"code": "rfm_df[\"Customer_segment\"] = np.where(rfm_df['RFM_Score'] > 4.5, \"Top Customers\", (np.where( rfm_df['RFM_Score'] > 4, \"High value Customer\", (np.where( rfm_df['RFM_Score'] > 3, \"Medium Value Customer\", np.where(rfm_df['RFM_Score'] > 1.6, 'Low Value Customers', 'Lost Customers'))))))rfm_df[['CustomerName', 'RFM_Score', 'Customer_segment']].head(20)",
"e": 30052,
"s": 29425,
"text": null
},
{
"code": null,
"e": 30118,
"s": 30052,
"text": "Here we will use a pie plot to display all segments of customers."
},
{
"code": null,
"e": 30126,
"s": 30118,
"text": "Python3"
},
{
"code": "plt.pie(rfm_df.Customer_segment.value_counts(), labels=rfm_df.Customer_segment.value_counts().index, autopct='%.0f%%')plt.show()",
"e": 30269,
"s": 30126,
"text": null
},
{
"code": null,
"e": 30277,
"s": 30269,
"text": "clintra"
},
{
"code": null,
"e": 30291,
"s": 30277,
"text": "Python-pandas"
},
{
"code": null,
"e": 30298,
"s": 30291,
"text": "Python"
},
{
"code": null,
"e": 30396,
"s": 30298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30428,
"s": 30396,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30470,
"s": 30428,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30512,
"s": 30470,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30568,
"s": 30512,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30595,
"s": 30568,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30634,
"s": 30595,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30665,
"s": 30634,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30694,
"s": 30665,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30716,
"s": 30694,
"text": "Defaultdict in Python"
}
] |
Check if a large number is divisible by 6 or not - GeeksforGeeks
|
13 May, 2021
Given a number, the task is to check if a number is divisible by 6 or not. The input number may be large and it may not be possible to store even if we use long long int.
Examples:
Input : n = 2112
Output : Yes
Input : n = 1124
Output : No
Input : n = 363588395960667043875487
Output : No
Since input number may be very large, we cannot use n % 6 to check if a number is divisible by 6 or not, especially in languages like C/C++. The idea is based on following fact.
A number is divisible by 6 it's divisible by 2 and 3.
a) A number is divisible by 2 if its last digit is divisible by 2.
b) A number is divisible by 3 if sum of digits is divisible by 3.
Below is the implementation based on above steps.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if a number is divisible by// 6 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 6 or notbool check(string str){ int n = str.length(); // Return false if number is not divisible by 2. if ((str[n-1]-'0')%2 != 0) return false; // If we reach here, number is divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 3 return (digitSum % 3 == 0);} // Driver codeint main(){ string str = "1332"; check(str)? cout << "Yes" : cout << "No "; return 0;}
// Java program to find if a number is// divisible by 6 or notclass IsDivisible{ // Function to find that number divisible by 6 or not static boolean check(String str) { int n = str.length(); // Return false if number is not divisible by 2. if ((str.charAt(n-1) -'0')%2 != 0) return false; // If we reach here, number is divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is divisible by 3 return (digitSum % 3 == 0); } // main function public static void main (String[] args) { String str = "1332"; if(check(str)) System.out.println("Yes"); else System.out.println("No"); }}
# Python 3 program to find# if a number is divisible# by 6 or not # Function to find that number# is divisible by 6 or notdef check(st) : n = len(st) # Return false if number # is not divisible by 2. if (((int)(st[n-1])%2) != 0) : return False # If we reach here, number # is divisible by 2. Now # check for 3. # Compute sum of digits digitSum = 0 for i in range(0, n) : digitSum = digitSum + (int)(st[i]) # Check if sum of digits # is divisible by 3 return (digitSum % 3 == 0) # Driver codest = "1332"if(check(st)) : print("Yes")else : print("No ") # This article is contributed by Nikita Tiwari.
// C# program to find if a number is// divisible by 6 or notusing System; class GFG { // Function to find that number // divisible by 6 or not static bool check(String str) { int n = str.Length; // Return false if number is // not divisible by 2. if ((str[n-1] -'0') % 2 != 0) return false; // If we reach here, number is // divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3 return (digitSum % 3 == 0); } // main function public static void Main () { String str = "1332"; if(check(str)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by parashar.
<?php// PHP program to find if a// number is divisible by// 6 or not // Function to find that number// divisible by 6 or notfunction check($str){ $n = strlen($str); // Return false if number is // not divisible by 2. if (($str[$n - 1] - '0') % 2 != 0) return false; // If we reach here, number // is divisible by 2. // Now check for 3. // Compute sum of digits $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 3 return ($digitSum % 3 == 0);} // Driver code $str = "1332"; if(check($str)) echo "Yes" ; else echo " No "; return 0; // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach // Function to find that number // divisible by 6 or not function check(str) { let n = str.length; // Return false if number is // not divisible by 2. if ((str[n-1] -'0') % 2 != 0) return false; // If we reach here, number is // divisible by 2. // Now check for 3. // Compute sum of digits let digitSum = 0; for (let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3 return (digitSum % 3 == 0); } // Driver Code let str = "1332"; if(check(str)) document.write("Yes"); else document.write("No"); // This code is contributed by splevel62.</script>
Output:
Yes
This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
parashar
nitin mittal
ManasChhabra2
splevel62
CoderSaty
divisibility
large-numbers
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Count all possible paths from top left to bottom right of a mXn matrix
Modular multiplicative inverse
Program to multiply two matrices
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Min Cost Path | DP-6
|
[
{
"code": null,
"e": 25962,
"s": 25934,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 26133,
"s": 25962,
"text": "Given a number, the task is to check if a number is divisible by 6 or not. The input number may be large and it may not be possible to store even if we use long long int."
},
{
"code": null,
"e": 26144,
"s": 26133,
"text": "Examples: "
},
{
"code": null,
"e": 26256,
"s": 26144,
"text": "Input : n = 2112\nOutput : Yes\n\nInput : n = 1124\nOutput : No\n\nInput : n = 363588395960667043875487\nOutput : No"
},
{
"code": null,
"e": 26435,
"s": 26256,
"text": "Since input number may be very large, we cannot use n % 6 to check if a number is divisible by 6 or not, especially in languages like C/C++. The idea is based on following fact. "
},
{
"code": null,
"e": 26625,
"s": 26435,
"text": "A number is divisible by 6 it's divisible by 2 and 3. \na) A number is divisible by 2 if its last digit is divisible by 2.\nb) A number is divisible by 3 if sum of digits is divisible by 3."
},
{
"code": null,
"e": 26676,
"s": 26625,
"text": "Below is the implementation based on above steps. "
},
{
"code": null,
"e": 26680,
"s": 26676,
"text": "C++"
},
{
"code": null,
"e": 26685,
"s": 26680,
"text": "Java"
},
{
"code": null,
"e": 26693,
"s": 26685,
"text": "Python3"
},
{
"code": null,
"e": 26696,
"s": 26693,
"text": "C#"
},
{
"code": null,
"e": 26700,
"s": 26696,
"text": "PHP"
},
{
"code": null,
"e": 26711,
"s": 26700,
"text": "Javascript"
},
{
"code": "// C++ program to find if a number is divisible by// 6 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 6 or notbool check(string str){ int n = str.length(); // Return false if number is not divisible by 2. if ((str[n-1]-'0')%2 != 0) return false; // If we reach here, number is divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 3 return (digitSum % 3 == 0);} // Driver codeint main(){ string str = \"1332\"; check(str)? cout << \"Yes\" : cout << \"No \"; return 0;}",
"e": 27396,
"s": 26711,
"text": null
},
{
"code": "// Java program to find if a number is// divisible by 6 or notclass IsDivisible{ // Function to find that number divisible by 6 or not static boolean check(String str) { int n = str.length(); // Return false if number is not divisible by 2. if ((str.charAt(n-1) -'0')%2 != 0) return false; // If we reach here, number is divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is divisible by 3 return (digitSum % 3 == 0); } // main function public static void main (String[] args) { String str = \"1332\"; if(check(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 28270,
"s": 27396,
"text": null
},
{
"code": "# Python 3 program to find# if a number is divisible# by 6 or not # Function to find that number# is divisible by 6 or notdef check(st) : n = len(st) # Return false if number # is not divisible by 2. if (((int)(st[n-1])%2) != 0) : return False # If we reach here, number # is divisible by 2. Now # check for 3. # Compute sum of digits digitSum = 0 for i in range(0, n) : digitSum = digitSum + (int)(st[i]) # Check if sum of digits # is divisible by 3 return (digitSum % 3 == 0) # Driver codest = \"1332\"if(check(st)) : print(\"Yes\")else : print(\"No \") # This article is contributed by Nikita Tiwari.",
"e": 28948,
"s": 28270,
"text": null
},
{
"code": "// C# program to find if a number is// divisible by 6 or notusing System; class GFG { // Function to find that number // divisible by 6 or not static bool check(String str) { int n = str.Length; // Return false if number is // not divisible by 2. if ((str[n-1] -'0') % 2 != 0) return false; // If we reach here, number is // divisible by 2. // Now check for 3. // Compute sum of digits int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3 return (digitSum % 3 == 0); } // main function public static void Main () { String str = \"1332\"; if(check(str)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by parashar.",
"e": 29881,
"s": 28948,
"text": null
},
{
"code": "<?php// PHP program to find if a// number is divisible by// 6 or not // Function to find that number// divisible by 6 or notfunction check($str){ $n = strlen($str); // Return false if number is // not divisible by 2. if (($str[$n - 1] - '0') % 2 != 0) return false; // If we reach here, number // is divisible by 2. // Now check for 3. // Compute sum of digits $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 3 return ($digitSum % 3 == 0);} // Driver code $str = \"1332\"; if(check($str)) echo \"Yes\" ; else echo \" No \"; return 0; // This code is contributed by nitin mittal.?>",
"e": 30609,
"s": 29881,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find that number // divisible by 6 or not function check(str) { let n = str.length; // Return false if number is // not divisible by 2. if ((str[n-1] -'0') % 2 != 0) return false; // If we reach here, number is // divisible by 2. // Now check for 3. // Compute sum of digits let digitSum = 0; for (let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3 return (digitSum % 3 == 0); } // Driver Code let str = \"1332\"; if(check(str)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by splevel62.</script>",
"e": 31436,
"s": 30609,
"text": null
},
{
"code": null,
"e": 31445,
"s": 31436,
"text": "Output: "
},
{
"code": null,
"e": 31449,
"s": 31445,
"text": "Yes"
},
{
"code": null,
"e": 31869,
"s": 31449,
"text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31878,
"s": 31869,
"text": "parashar"
},
{
"code": null,
"e": 31891,
"s": 31878,
"text": "nitin mittal"
},
{
"code": null,
"e": 31905,
"s": 31891,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 31915,
"s": 31905,
"text": "splevel62"
},
{
"code": null,
"e": 31925,
"s": 31915,
"text": "CoderSaty"
},
{
"code": null,
"e": 31938,
"s": 31925,
"text": "divisibility"
},
{
"code": null,
"e": 31952,
"s": 31938,
"text": "large-numbers"
},
{
"code": null,
"e": 31966,
"s": 31952,
"text": "number-digits"
},
{
"code": null,
"e": 31979,
"s": 31966,
"text": "Mathematical"
},
{
"code": null,
"e": 31992,
"s": 31979,
"text": "Mathematical"
},
{
"code": null,
"e": 32090,
"s": 31992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32134,
"s": 32090,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32176,
"s": 32134,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 32247,
"s": 32176,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 32278,
"s": 32247,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32311,
"s": 32278,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32336,
"s": 32311,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32368,
"s": 32336,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 32403,
"s": 32368,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 32449,
"s": 32403,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Check if a Binary Tree is BST : Simple and Efficient Approach - GeeksforGeeks
|
22 Jun, 2021
Given a Binary Tree, the task is to check whether the given binary tree is Binary Search Tree or not.A binary search tree (BST) is a node-based binary tree data structure which has the following properties.
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
From the above properties it naturally follows that:
Each node (item in the tree) has a distinct key.
We have already discussed different approaches to solve this problem in the previous article.In this article, we will discuss a simple yet efficient approach to solve the above problem.The idea is to use Inorder traversal and keep track of the previously visited node’s value. Since the inorder traversal of a BST generates a sorted array as output, So, the previous element should always be less than or equals to the current element.While doing In-Order traversal, we can keep track of previously visited Node’s value and if the value of the currently visited node is less than the previous value, then the tree is not BST.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if a given tree is BST.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Utility function to check if Binary Tree is BSTbool isBSTUtil(struct Node* root, int& prev){ // traverse the tree in inorder fashion and // keep track of prev node if (root) { if (!isBSTUtil(root->left, prev)) return false; // Allows only distinct valued nodes if (root->data <= prev) return false; // Initialize prev to current prev = root->data; return isBSTUtil(root->right, prev); } return true;} // Function to check if Binary Tree is BSTbool isBST(Node* root){ int prev = INT_MIN; return isBSTUtil(root, prev);} /* Driver code*/int main(){ struct Node* root = new Node(5); root->left = new Node(2); root->right = new Node(15); root->left->left = new Node(1); root->left->right = new Node(4); if (isBST(root)) cout << "Is BST"; else cout << "Not a BST"; return 0;}
// Java program to check if a given tree is BST.class GFG { static int prev = Integer.MIN_VALUE; /* A binary tree node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; } }; // Utility function to check if Binary Tree is BST static boolean isBSTUtil(Node root) { // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right); } return true; } // Function to check if Binary Tree is BST static boolean isBST(Node root) { return isBSTUtil(root); } /* Driver code*/ public static void main(String[] args) { Node root = new Node(5); root.left = new Node(2); root.right = new Node(15); root.left.left = new Node(1); root.left.right = new Node(4); if (isBST(root)) System.out.print("Is BST"); else System.out.print("Not a BST"); }} // This code is contributed by PrinciRaj1992
# Python3 program to check if a given tree is BST. import mathprev = -math.inf class Node: """ Creates a Binary tree node that has data, a pointer to it's left and right child """ def __init__(self, data): self.left = None self.right = None self.data = data def checkBST(root): """ Function to check if Binary Tree is a Binary Search Tree :param root: current root node :return: Boolean value """ # traverse the tree in inorder # fashion and update the prev node global prev if root: if not checkBST(root.left): return False # Handles same valued nodes if root.data < prev: return False # Set value of prev to current node prev = root.data return checkBST(root.right) return True # Driver Codedef main(): root = Node(1) root.left = Node(2) root.right = Node(15) root.left.left = Node(1) root.left.right = Node(4) if checkBST(root): print("Is BST") else: print("Not a BST") if __name__ == '__main__': main() # This code is contributed by priyankapunjabi94
// C# program to check if a given tree is BST.using System; class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } }; // Utility function to check if Binary Tree is BST static bool isBSTUtil(Node root, int prev) { // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left, prev)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right, prev); } return true; } // Function to check if Binary Tree is BST static bool isBST(Node root) { int prev = int.MinValue; return isBSTUtil(root, prev); } /* Driver code*/ public static void Main(String[] args) { Node root = new Node(5); root.left = new Node(2); root.right = new Node(15); root.left.left = new Node(1); root.left.right = new Node(4); if (isBST(root)) Console.Write("Is BST"); else Console.Write("Not a BST"); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to check if a given tree is BST./* A binary tree node has data, pointer toleft child and a pointer to right child */class Node { constructor(data) { this.data = data; this.left = null; this.right = null; }};// Utility function to check if Binary Tree is BSTfunction isBSTUtil(root, prev){ // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left, prev)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right, prev); } return true;}// Function to check if Binary Tree is BSTfunction isBST(root){ var prev = -1000000000; return isBSTUtil(root, prev);}/* Driver code*/var root = new Node(5);root.left = new Node(2);root.right = new Node(15);root.left.left = new Node(1);root.left.right = new Node(4);if (isBST(root)) document.write("Is BST");else document.write("Not a BST"); </script>
Is BST
Time Complexity: O(N) Auxiliary Space: O(1)
princiraj1992
SHUBHAMSINGH10
priyankapunjabi94
dhanishtha96
importantly
Binary Tree
Inorder Traversal
Binary Search Tree
Tree
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Construct BST from given preorder traversal | Set 2
Red Black Tree vs AVL Tree
Find median of BST in O(n) time and O(1) space
Print BST keys in the given range
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 26469,
"s": 26441,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 26677,
"s": 26469,
"text": "Given a Binary Tree, the task is to check whether the given binary tree is Binary Search Tree or not.A binary search tree (BST) is a node-based binary tree data structure which has the following properties. "
},
{
"code": null,
"e": 26760,
"s": 26677,
"text": "The left subtree of a node contains only nodes with keys less than the node’s key."
},
{
"code": null,
"e": 26847,
"s": 26760,
"text": "The right subtree of a node contains only nodes with keys greater than the node’s key."
},
{
"code": null,
"e": 26914,
"s": 26847,
"text": "Both the left and right subtrees must also be binary search trees."
},
{
"code": null,
"e": 26968,
"s": 26914,
"text": "From the above properties it naturally follows that: "
},
{
"code": null,
"e": 27018,
"s": 26968,
"text": "Each node (item in the tree) has a distinct key. "
},
{
"code": null,
"e": 27647,
"s": 27020,
"text": "We have already discussed different approaches to solve this problem in the previous article.In this article, we will discuss a simple yet efficient approach to solve the above problem.The idea is to use Inorder traversal and keep track of the previously visited node’s value. Since the inorder traversal of a BST generates a sorted array as output, So, the previous element should always be less than or equals to the current element.While doing In-Order traversal, we can keep track of previously visited Node’s value and if the value of the currently visited node is less than the previous value, then the tree is not BST. "
},
{
"code": null,
"e": 27698,
"s": 27647,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27702,
"s": 27698,
"text": "C++"
},
{
"code": null,
"e": 27707,
"s": 27702,
"text": "Java"
},
{
"code": null,
"e": 27715,
"s": 27707,
"text": "Python3"
},
{
"code": null,
"e": 27718,
"s": 27715,
"text": "C#"
},
{
"code": null,
"e": 27729,
"s": 27718,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given tree is BST.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Utility function to check if Binary Tree is BSTbool isBSTUtil(struct Node* root, int& prev){ // traverse the tree in inorder fashion and // keep track of prev node if (root) { if (!isBSTUtil(root->left, prev)) return false; // Allows only distinct valued nodes if (root->data <= prev) return false; // Initialize prev to current prev = root->data; return isBSTUtil(root->right, prev); } return true;} // Function to check if Binary Tree is BSTbool isBST(Node* root){ int prev = INT_MIN; return isBSTUtil(root, prev);} /* Driver code*/int main(){ struct Node* root = new Node(5); root->left = new Node(2); root->right = new Node(15); root->left->left = new Node(1); root->left->right = new Node(4); if (isBST(root)) cout << \"Is BST\"; else cout << \"Not a BST\"; return 0;}",
"e": 28949,
"s": 27729,
"text": null
},
{
"code": "// Java program to check if a given tree is BST.class GFG { static int prev = Integer.MIN_VALUE; /* A binary tree node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; } }; // Utility function to check if Binary Tree is BST static boolean isBSTUtil(Node root) { // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right); } return true; } // Function to check if Binary Tree is BST static boolean isBST(Node root) { return isBSTUtil(root); } /* Driver code*/ public static void main(String[] args) { Node root = new Node(5); root.left = new Node(2); root.right = new Node(15); root.left.left = new Node(1); root.left.right = new Node(4); if (isBST(root)) System.out.print(\"Is BST\"); else System.out.print(\"Not a BST\"); }} // This code is contributed by PrinciRaj1992",
"e": 30386,
"s": 28949,
"text": null
},
{
"code": "# Python3 program to check if a given tree is BST. import mathprev = -math.inf class Node: \"\"\" Creates a Binary tree node that has data, a pointer to it's left and right child \"\"\" def __init__(self, data): self.left = None self.right = None self.data = data def checkBST(root): \"\"\" Function to check if Binary Tree is a Binary Search Tree :param root: current root node :return: Boolean value \"\"\" # traverse the tree in inorder # fashion and update the prev node global prev if root: if not checkBST(root.left): return False # Handles same valued nodes if root.data < prev: return False # Set value of prev to current node prev = root.data return checkBST(root.right) return True # Driver Codedef main(): root = Node(1) root.left = Node(2) root.right = Node(15) root.left.left = Node(1) root.left.right = Node(4) if checkBST(root): print(\"Is BST\") else: print(\"Not a BST\") if __name__ == '__main__': main() # This code is contributed by priyankapunjabi94",
"e": 31521,
"s": 30386,
"text": null
},
{
"code": "// C# program to check if a given tree is BST.using System; class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } }; // Utility function to check if Binary Tree is BST static bool isBSTUtil(Node root, int prev) { // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left, prev)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right, prev); } return true; } // Function to check if Binary Tree is BST static bool isBST(Node root) { int prev = int.MinValue; return isBSTUtil(root, prev); } /* Driver code*/ public static void Main(String[] args) { Node root = new Node(5); root.left = new Node(2); root.right = new Node(15); root.left.left = new Node(1); root.left.right = new Node(4); if (isBST(root)) Console.Write(\"Is BST\"); else Console.Write(\"Not a BST\"); }} // This code is contributed by PrinciRaj1992",
"e": 32992,
"s": 31521,
"text": null
},
{
"code": "<script> // JavaScript program to check if a given tree is BST./* A binary tree node has data, pointer toleft child and a pointer to right child */class Node { constructor(data) { this.data = data; this.left = null; this.right = null; }};// Utility function to check if Binary Tree is BSTfunction isBSTUtil(root, prev){ // traverse the tree in inorder fashion and // keep track of prev node if (root != null) { if (!isBSTUtil(root.left, prev)) return false; // Allows only distinct valued nodes if (root.data <= prev) return false; // Initialize prev to current prev = root.data; return isBSTUtil(root.right, prev); } return true;}// Function to check if Binary Tree is BSTfunction isBST(root){ var prev = -1000000000; return isBSTUtil(root, prev);}/* Driver code*/var root = new Node(5);root.left = new Node(2);root.right = new Node(15);root.left.left = new Node(1);root.left.right = new Node(4);if (isBST(root)) document.write(\"Is BST\");else document.write(\"Not a BST\"); </script>",
"e": 34098,
"s": 32992,
"text": null
},
{
"code": null,
"e": 34105,
"s": 34098,
"text": "Is BST"
},
{
"code": null,
"e": 34150,
"s": 34105,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 34164,
"s": 34150,
"text": "princiraj1992"
},
{
"code": null,
"e": 34179,
"s": 34164,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 34197,
"s": 34179,
"text": "priyankapunjabi94"
},
{
"code": null,
"e": 34210,
"s": 34197,
"text": "dhanishtha96"
},
{
"code": null,
"e": 34222,
"s": 34210,
"text": "importantly"
},
{
"code": null,
"e": 34234,
"s": 34222,
"text": "Binary Tree"
},
{
"code": null,
"e": 34252,
"s": 34234,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 34271,
"s": 34252,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34276,
"s": 34271,
"text": "Tree"
},
{
"code": null,
"e": 34295,
"s": 34276,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34300,
"s": 34295,
"text": "Tree"
},
{
"code": null,
"e": 34398,
"s": 34300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34430,
"s": 34398,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 34482,
"s": 34430,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 34509,
"s": 34482,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 34556,
"s": 34509,
"text": "Find median of BST in O(n) time and O(1) space"
},
{
"code": null,
"e": 34590,
"s": 34556,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 34640,
"s": 34590,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 34675,
"s": 34640,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 34709,
"s": 34675,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 34752,
"s": 34709,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
Cognizant Placement Paper | Aptitude Set 1 - GeeksforGeeks
|
02 Feb, 2022
This is a model placement paper for aptitude preparation of Cognizant Technology Solutions Interview. This placement paper will cover aptitude questions that are asked in CTS recruitment drives and also strictly follows the pattern of questions asked in CTS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the CTS interview.
1. There are forty students in a class out of which there are 14 who are taking Maths and 29 who are taking Computer. What is the probability that a randomly chosen student from this group is taking only the Computer class? a) 40% b) 55% c) 65% d) 70%
Answer: 65%
Solution: There are in total of 40 students. 14 are taking Maths and 29 are taking computer. Therefore there have to be 3 students who are taking both the classes. So, 29 – 3 = 26 students are taking only Computer. So probability = 26/40 = 13/20 = 65%
2. Find the number, the second digit of which is smaller than its first digit by 4, and if the number was divided by the digit’s sum, the quotient would be 7. a) 51 b) 62 c) 73 d) None of these
Answer: d) None of these
Solution: If we consider the number 84, then we get 8 – 4 = 4 and when the sum of digits that is 12 divides the number 84, we get 7.
3. If all 6s get inverted and become 9s, between 1 and 100 then by how much will the sum of all numbers change including both? a) 300 b) 330 c) 333 d) None of these
Answer: b) 330
Solution: For the 6 at the unit place: When the digits are changed to 9, each value will increase by 3. Since there are 10 such numbers, so total increase = 10 * 3 = 30 For the 6 at 10’s place: When the digits are changed to 9, each value will increase by 30. Since there are 10 such numbers, so total increase = 10 * 30 = 300 So the total increase will be 30 + 300 = 330
4. Rajesh and Prabhu went to a bookshop. Rajesh purchased 5 pens, 3 notebooks, and 9 pencils and used up all her money. Prabhu purchased 6 pens, 6 notebooks, and 18 pencils and paid 50% more than what Rajesh paid. What % of the Rajesh money was spent on pens? a) 12.5 b) 62.5 c) 75 d) Cannot be determined
Answer: a) 62.5
Solution: Let the amount spent by Rajesh be ‘x’
According to the question, 5 pen + 3 notebooks + 9 pecils = x and 6 pens + 6 notebooks + 18 pencils = 1.5x
By solving both the equations we get, 1 pen = 0.125x
=> 5 pens = 5*(0.125x) = 0.625x = 62.5% of x.
5. In a group of persons travelling in a bus, 6 persons can speak Tamil, 15 can speak Hindi, and 6 can speak Gujarati. In that group, none can speak any other language. If 2 persons in the group can speak two languages and one person can speak all three languages, then how many persons are there in the group? a) 21 b) 22 c) 24 d) 23
Answer: d) 23
Solution: Assuming the two persons who can speak two languages be Hindi and Tamil and the third person speaks all the three languages. Therefore, the number of people who can speak Tamil is 6. Only Tamil = 6 – 2 – 1 = 3 Therefore, the number of people who can speak Hindi is 15. Only Hindi = 15 – 2 – 1 = 12 Therefore, the number of people who can speak Gujarati is 6. Only Gujarati = 6 – 1 = 5 Thus the number of persons who can speak only one language is 3 + 12 + 5 = 20 Given, The number of persons who can speak two languages is 2 The number of people who speak all three languages is 1 Therefore the answer is 23.
6. There are 2 trucks facing each other at a distance of 500 cm from each other. Each truck moves forward by 100 cm at a speed of 50 cm/s and then moves backwards by 50 cm at a speed of 25 cm/s. How long will they take to collide? a) 12 sec b) 16 sec c) 13 sec d) 14 sec
Answer: d) 14 sec
Solution: If we observe the series carefully running from time = 2 sec and hence,
Moving forward: At 2 secs each truck will move to a distance of 100cms
Moving backwards: At 4 secs each truck will move to a distance of 50cms
Moving forward: At 6 secs each truck will move to a distance of 150cms
Moving backwards: At 8 secs each truck will move to a distance of 100cms
Moving forward: At 10 secs each truck will move to a distance of 200cms
Moving backwards: At 12 secs each truck will move to a distance of 150cms
Moving forward: At 14 secs each truck will move to a distance of 250cms and in all 500 cms that are the point they must collide.
7. What is the greatest number that will divide 964, 1238, and 1400 and leave a remainder of 41, 31, and 51 respectively? a) 71 b) 58 c) 64 d) 79
Answer: a) 71
Solution: To reach to the solution we just need to find the HCF of (964 – 41), (1238 – 31), (1400 – 51) = 923, 1207, 1349 The HCF of 923, 1207 and 1349 = 71
8. The average temperature of Monday, Tuesday and Wednesday were 37°C and on Tuesday, Wednesday and Thursday was 34°C. If the temperature on Thursday was 4/5 th of that of Monday, then what was the temperature on Thursday? a) 36 °C b) 36.5 °C c) 34 °C d) 35.5 °C
Answer: a) 36 °C
Solution: According to the question, Monday + Tuesday + Wednesday = 37 °C Tuesday + Wednesday + Thursday = 34 °C Thursday = 4/5 of Monday On solving the first two equations and substituting the values from the third condition we get the temperature of Thursday = 36 °C
9. There are 6 cities, and every city is connected to each other. How many different routes can one trace from A to B, such that no city is touched more than once in any one route? a) 72 b) 65 c) 60 d) 48
Answer: b) 65
Solution: There must be 1 direct route. There are 4 ways to cover 1 city There are 4 * 3 = 12 ways to cover 2 cities There are 4 * 3 * 2 ways to cover 3 cities There are 4 * 3 * 2 * 1 ways to cover 4 cities Total ways = 65 ways
10. A secret can be said by only 2 persons in 5 minutes. The same person tells the secret to 2 more persons and so on. How long will take to tell it to tell 768 persons? a) 500 min b) 50 min c) 47.5 min d) 49 min
Answer: c) 47.5 min
Solution: One person telling to 2 means he takes 2.5 min to tell the secret to 1 person, So 1 person telling the truth to another 2 people and the next two telling the truth to the next two who in turn are telling another 2 people and so on... Therefore a series is formed of 1 to 2, 2 to 4, 4 to 8, 8 to 16 and so on... Therefore a series of 1, 2, 4, 8, 16, 32,..., 512 Till 512 it would take Till this will take 45 minutes and now these people i.e., 256 will be telling the truth to only 1 of the total person will be 768, Therefore, 45 + 2.5 = 47.5 min
rahulkumar96
vrinda18amu
Cognizant
interview-preparation
placement preparation
Placements
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 20 Puzzles Commonly Asked During SDE Interviews
Codenation Recruitment Process
Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
Minimum changes required to make all Array elements Prime
Work and Wages
Progressions (AP, GP, HP)
Permutation and Combination
How to Prepare for HR Interviews
Interview Preparation
Puzzle | 50 red marbles and 50 blue marbles
|
[
{
"code": null,
"e": 26215,
"s": 26187,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 26605,
"s": 26215,
"text": "This is a model placement paper for aptitude preparation of Cognizant Technology Solutions Interview. This placement paper will cover aptitude questions that are asked in CTS recruitment drives and also strictly follows the pattern of questions asked in CTS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the CTS interview. "
},
{
"code": null,
"e": 26858,
"s": 26605,
"text": "1. There are forty students in a class out of which there are 14 who are taking Maths and 29 who are taking Computer. What is the probability that a randomly chosen student from this group is taking only the Computer class? a) 40% b) 55% c) 65% d) 70% "
},
{
"code": null,
"e": 26870,
"s": 26858,
"text": "Answer: 65%"
},
{
"code": null,
"e": 27122,
"s": 26870,
"text": "Solution: There are in total of 40 students. 14 are taking Maths and 29 are taking computer. Therefore there have to be 3 students who are taking both the classes. So, 29 – 3 = 26 students are taking only Computer. So probability = 26/40 = 13/20 = 65%"
},
{
"code": null,
"e": 27317,
"s": 27122,
"text": "2. Find the number, the second digit of which is smaller than its first digit by 4, and if the number was divided by the digit’s sum, the quotient would be 7. a) 51 b) 62 c) 73 d) None of these "
},
{
"code": null,
"e": 27342,
"s": 27317,
"text": "Answer: d) None of these"
},
{
"code": null,
"e": 27475,
"s": 27342,
"text": "Solution: If we consider the number 84, then we get 8 – 4 = 4 and when the sum of digits that is 12 divides the number 84, we get 7."
},
{
"code": null,
"e": 27641,
"s": 27475,
"text": "3. If all 6s get inverted and become 9s, between 1 and 100 then by how much will the sum of all numbers change including both? a) 300 b) 330 c) 333 d) None of these "
},
{
"code": null,
"e": 27656,
"s": 27641,
"text": "Answer: b) 330"
},
{
"code": null,
"e": 28028,
"s": 27656,
"text": "Solution: For the 6 at the unit place: When the digits are changed to 9, each value will increase by 3. Since there are 10 such numbers, so total increase = 10 * 3 = 30 For the 6 at 10’s place: When the digits are changed to 9, each value will increase by 30. Since there are 10 such numbers, so total increase = 10 * 30 = 300 So the total increase will be 30 + 300 = 330"
},
{
"code": null,
"e": 28335,
"s": 28028,
"text": "4. Rajesh and Prabhu went to a bookshop. Rajesh purchased 5 pens, 3 notebooks, and 9 pencils and used up all her money. Prabhu purchased 6 pens, 6 notebooks, and 18 pencils and paid 50% more than what Rajesh paid. What % of the Rajesh money was spent on pens? a) 12.5 b) 62.5 c) 75 d) Cannot be determined "
},
{
"code": null,
"e": 28351,
"s": 28335,
"text": "Answer: a) 62.5"
},
{
"code": null,
"e": 28400,
"s": 28351,
"text": "Solution: Let the amount spent by Rajesh be ‘x’ "
},
{
"code": null,
"e": 28508,
"s": 28400,
"text": "According to the question, 5 pen + 3 notebooks + 9 pecils = x and 6 pens + 6 notebooks + 18 pencils = 1.5x "
},
{
"code": null,
"e": 28562,
"s": 28508,
"text": "By solving both the equations we get, 1 pen = 0.125x "
},
{
"code": null,
"e": 28609,
"s": 28562,
"text": "=> 5 pens = 5*(0.125x) = 0.625x = 62.5% of x."
},
{
"code": null,
"e": 28945,
"s": 28609,
"text": "5. In a group of persons travelling in a bus, 6 persons can speak Tamil, 15 can speak Hindi, and 6 can speak Gujarati. In that group, none can speak any other language. If 2 persons in the group can speak two languages and one person can speak all three languages, then how many persons are there in the group? a) 21 b) 22 c) 24 d) 23 "
},
{
"code": null,
"e": 28959,
"s": 28945,
"text": "Answer: d) 23"
},
{
"code": null,
"e": 29578,
"s": 28959,
"text": "Solution: Assuming the two persons who can speak two languages be Hindi and Tamil and the third person speaks all the three languages. Therefore, the number of people who can speak Tamil is 6. Only Tamil = 6 – 2 – 1 = 3 Therefore, the number of people who can speak Hindi is 15. Only Hindi = 15 – 2 – 1 = 12 Therefore, the number of people who can speak Gujarati is 6. Only Gujarati = 6 – 1 = 5 Thus the number of persons who can speak only one language is 3 + 12 + 5 = 20 Given, The number of persons who can speak two languages is 2 The number of people who speak all three languages is 1 Therefore the answer is 23."
},
{
"code": null,
"e": 29850,
"s": 29578,
"text": "6. There are 2 trucks facing each other at a distance of 500 cm from each other. Each truck moves forward by 100 cm at a speed of 50 cm/s and then moves backwards by 50 cm at a speed of 25 cm/s. How long will they take to collide? a) 12 sec b) 16 sec c) 13 sec d) 14 sec "
},
{
"code": null,
"e": 29869,
"s": 29850,
"text": "Answer: d) 14 sec "
},
{
"code": null,
"e": 29952,
"s": 29869,
"text": "Solution: If we observe the series carefully running from time = 2 sec and hence, "
},
{
"code": null,
"e": 30024,
"s": 29952,
"text": "Moving forward: At 2 secs each truck will move to a distance of 100cms "
},
{
"code": null,
"e": 30097,
"s": 30024,
"text": "Moving backwards: At 4 secs each truck will move to a distance of 50cms "
},
{
"code": null,
"e": 30169,
"s": 30097,
"text": "Moving forward: At 6 secs each truck will move to a distance of 150cms "
},
{
"code": null,
"e": 30243,
"s": 30169,
"text": "Moving backwards: At 8 secs each truck will move to a distance of 100cms "
},
{
"code": null,
"e": 30316,
"s": 30243,
"text": "Moving forward: At 10 secs each truck will move to a distance of 200cms "
},
{
"code": null,
"e": 30391,
"s": 30316,
"text": "Moving backwards: At 12 secs each truck will move to a distance of 150cms "
},
{
"code": null,
"e": 30520,
"s": 30391,
"text": "Moving forward: At 14 secs each truck will move to a distance of 250cms and in all 500 cms that are the point they must collide."
},
{
"code": null,
"e": 30667,
"s": 30520,
"text": "7. What is the greatest number that will divide 964, 1238, and 1400 and leave a remainder of 41, 31, and 51 respectively? a) 71 b) 58 c) 64 d) 79 "
},
{
"code": null,
"e": 30681,
"s": 30667,
"text": "Answer: a) 71"
},
{
"code": null,
"e": 30838,
"s": 30681,
"text": "Solution: To reach to the solution we just need to find the HCF of (964 – 41), (1238 – 31), (1400 – 51) = 923, 1207, 1349 The HCF of 923, 1207 and 1349 = 71"
},
{
"code": null,
"e": 31102,
"s": 30838,
"text": "8. The average temperature of Monday, Tuesday and Wednesday were 37°C and on Tuesday, Wednesday and Thursday was 34°C. If the temperature on Thursday was 4/5 th of that of Monday, then what was the temperature on Thursday? a) 36 °C b) 36.5 °C c) 34 °C d) 35.5 °C "
},
{
"code": null,
"e": 31119,
"s": 31102,
"text": "Answer: a) 36 °C"
},
{
"code": null,
"e": 31390,
"s": 31119,
"text": "Solution: According to the question, Monday + Tuesday + Wednesday = 37 °C Tuesday + Wednesday + Thursday = 34 °C Thursday = 4/5 of Monday On solving the first two equations and substituting the values from the third condition we get the temperature of Thursday = 36 °C "
},
{
"code": null,
"e": 31596,
"s": 31390,
"text": "9. There are 6 cities, and every city is connected to each other. How many different routes can one trace from A to B, such that no city is touched more than once in any one route? a) 72 b) 65 c) 60 d) 48 "
},
{
"code": null,
"e": 31610,
"s": 31596,
"text": "Answer: b) 65"
},
{
"code": null,
"e": 31838,
"s": 31610,
"text": "Solution: There must be 1 direct route. There are 4 ways to cover 1 city There are 4 * 3 = 12 ways to cover 2 cities There are 4 * 3 * 2 ways to cover 3 cities There are 4 * 3 * 2 * 1 ways to cover 4 cities Total ways = 65 ways"
},
{
"code": null,
"e": 32052,
"s": 31838,
"text": "10. A secret can be said by only 2 persons in 5 minutes. The same person tells the secret to 2 more persons and so on. How long will take to tell it to tell 768 persons? a) 500 min b) 50 min c) 47.5 min d) 49 min "
},
{
"code": null,
"e": 32073,
"s": 32052,
"text": "Answer: c) 47.5 min "
},
{
"code": null,
"e": 32629,
"s": 32073,
"text": "Solution: One person telling to 2 means he takes 2.5 min to tell the secret to 1 person, So 1 person telling the truth to another 2 people and the next two telling the truth to the next two who in turn are telling another 2 people and so on... Therefore a series is formed of 1 to 2, 2 to 4, 4 to 8, 8 to 16 and so on... Therefore a series of 1, 2, 4, 8, 16, 32,..., 512 Till 512 it would take Till this will take 45 minutes and now these people i.e., 256 will be telling the truth to only 1 of the total person will be 768, Therefore, 45 + 2.5 = 47.5 min"
},
{
"code": null,
"e": 32644,
"s": 32631,
"text": "rahulkumar96"
},
{
"code": null,
"e": 32656,
"s": 32644,
"text": "vrinda18amu"
},
{
"code": null,
"e": 32666,
"s": 32656,
"text": "Cognizant"
},
{
"code": null,
"e": 32688,
"s": 32666,
"text": "interview-preparation"
},
{
"code": null,
"e": 32710,
"s": 32688,
"text": "placement preparation"
},
{
"code": null,
"e": 32721,
"s": 32710,
"text": "Placements"
},
{
"code": null,
"e": 32819,
"s": 32721,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32871,
"s": 32819,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 32902,
"s": 32871,
"text": "Codenation Recruitment Process"
},
{
"code": null,
"e": 32962,
"s": 32902,
"text": "Must Do Questions for Companies like TCS, CTS, HCL, IBM ..."
},
{
"code": null,
"e": 33020,
"s": 32962,
"text": "Minimum changes required to make all Array elements Prime"
},
{
"code": null,
"e": 33035,
"s": 33020,
"text": "Work and Wages"
},
{
"code": null,
"e": 33061,
"s": 33035,
"text": "Progressions (AP, GP, HP)"
},
{
"code": null,
"e": 33089,
"s": 33061,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 33122,
"s": 33089,
"text": "How to Prepare for HR Interviews"
},
{
"code": null,
"e": 33144,
"s": 33122,
"text": "Interview Preparation"
}
] |
Extracting MAC address using Python - GeeksforGeeks
|
31 Mar, 2020
MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC’s.
Uses of MAC address :
Useful in places where IP address change frequently. Helps network admin. to get information regarding network traffic.
Helps us to configure which computers can be connected to our computers. By this way we can filter potential spam/virus attacks.
Helps in uniquely identifying computers from other computers around the world.
This article aims at extracting MAC address of computer using Python.
Method 1 : using mac moduleTo get the physical address of the device we use getmac module of Python.
>>>from getmac import get_mac_address as gma
>>>print(gma())
'3c:7e:94:8f:d0:34'
Method 2 : Using uuid.getnode()
getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.The illustrated code given below shows how to generate a UUID for a given host, identified by its MAC address, using the uuid1() function.
# Python Program to compute# MAC address of host# using UUID module import uuid # printing the value of unique MAC# address using uuid and getnode() function print (hex(uuid.getnode()))
Output :
0x163e990bdb
Drawback :
The visible drawback is that the output is not in the formatted form.
Method 3 : Using getnode() + format() [ for better formatting ]
# Python 3 code to print MAC# in formatted way. import uuid # joins elements of getnode() after each 2 digits. print ("The MAC address in formatted way is : ", end="")print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)for ele in range(0,8*6,8)][::-1]))
Output :
The MAC address in formatted way is : 00:16:3e:99:0b:db
Drawback :
This code appears to be complex.
Method 4 : Using getnode() + findall() + re() [ for reducing complexity ]
# Python 3 code to print MAC# in formatted way and easier# to understand import re, uuid # joins elements of getnode() after each 2 digits.# using regex expressionprint ("The MAC address in formatted and less complex way is : ", end="")print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
Output :
The MAC address in formatted and less complex way is : 00:16:3e:99:0b:db
DivyaVishwakarma1
Computer Networks
Python
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
Differences between TCP and UDP
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Differences between IPv4 and IPv6
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26075,
"s": 26047,
"text": "\n31 Mar, 2020"
},
{
"code": null,
"e": 26329,
"s": 26075,
"text": "MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC’s."
},
{
"code": null,
"e": 26351,
"s": 26329,
"text": "Uses of MAC address :"
},
{
"code": null,
"e": 26471,
"s": 26351,
"text": "Useful in places where IP address change frequently. Helps network admin. to get information regarding network traffic."
},
{
"code": null,
"e": 26600,
"s": 26471,
"text": "Helps us to configure which computers can be connected to our computers. By this way we can filter potential spam/virus attacks."
},
{
"code": null,
"e": 26679,
"s": 26600,
"text": "Helps in uniquely identifying computers from other computers around the world."
},
{
"code": null,
"e": 26749,
"s": 26679,
"text": "This article aims at extracting MAC address of computer using Python."
},
{
"code": null,
"e": 26850,
"s": 26749,
"text": "Method 1 : using mac moduleTo get the physical address of the device we use getmac module of Python."
},
{
"code": null,
"e": 26931,
"s": 26850,
"text": ">>>from getmac import get_mac_address as gma\n>>>print(gma())\n'3c:7e:94:8f:d0:34'"
},
{
"code": null,
"e": 26963,
"s": 26931,
"text": "Method 2 : Using uuid.getnode()"
},
{
"code": null,
"e": 27208,
"s": 26963,
"text": "getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.The illustrated code given below shows how to generate a UUID for a given host, identified by its MAC address, using the uuid1() function."
},
{
"code": "# Python Program to compute# MAC address of host# using UUID module import uuid # printing the value of unique MAC# address using uuid and getnode() function print (hex(uuid.getnode()))",
"e": 27396,
"s": 27208,
"text": null
},
{
"code": null,
"e": 27405,
"s": 27396,
"text": "Output :"
},
{
"code": null,
"e": 27419,
"s": 27405,
"text": "0x163e990bdb\n"
},
{
"code": null,
"e": 27430,
"s": 27419,
"text": "Drawback :"
},
{
"code": null,
"e": 27500,
"s": 27430,
"text": "The visible drawback is that the output is not in the formatted form."
},
{
"code": null,
"e": 27564,
"s": 27500,
"text": "Method 3 : Using getnode() + format() [ for better formatting ]"
},
{
"code": "# Python 3 code to print MAC# in formatted way. import uuid # joins elements of getnode() after each 2 digits. print (\"The MAC address in formatted way is : \", end=\"\")print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)for ele in range(0,8*6,8)][::-1]))",
"e": 27833,
"s": 27564,
"text": null
},
{
"code": null,
"e": 27842,
"s": 27833,
"text": "Output :"
},
{
"code": null,
"e": 27899,
"s": 27842,
"text": "The MAC address in formatted way is : 00:16:3e:99:0b:db\n"
},
{
"code": null,
"e": 27910,
"s": 27899,
"text": "Drawback :"
},
{
"code": null,
"e": 27943,
"s": 27910,
"text": "This code appears to be complex."
},
{
"code": null,
"e": 28017,
"s": 27943,
"text": "Method 4 : Using getnode() + findall() + re() [ for reducing complexity ]"
},
{
"code": "# Python 3 code to print MAC# in formatted way and easier# to understand import re, uuid # joins elements of getnode() after each 2 digits.# using regex expressionprint (\"The MAC address in formatted and less complex way is : \", end=\"\")print (':'.join(re.findall('..', '%012x' % uuid.getnode())))",
"e": 28316,
"s": 28017,
"text": null
},
{
"code": null,
"e": 28325,
"s": 28316,
"text": "Output :"
},
{
"code": null,
"e": 28399,
"s": 28325,
"text": "The MAC address in formatted and less complex way is : 00:16:3e:99:0b:db\n"
},
{
"code": null,
"e": 28417,
"s": 28399,
"text": "DivyaVishwakarma1"
},
{
"code": null,
"e": 28435,
"s": 28417,
"text": "Computer Networks"
},
{
"code": null,
"e": 28442,
"s": 28435,
"text": "Python"
},
{
"code": null,
"e": 28460,
"s": 28442,
"text": "Computer Networks"
},
{
"code": null,
"e": 28558,
"s": 28460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28588,
"s": 28558,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 28620,
"s": 28588,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28658,
"s": 28620,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28697,
"s": 28658,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 28731,
"s": 28697,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 28759,
"s": 28731,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28809,
"s": 28759,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28831,
"s": 28809,
"text": "Python map() function"
}
] |
Python - Add Phrase in middle of String - GeeksforGeeks
|
25 Oct, 2020
Given a String, add a phrase in the middle of it.
Input : test_str = ‘geekforgeeks is for geeks’, mid_str = “good” Output : geekforgeeks is good for geeks Explanation : Added just in middle, after 2 words.
Input : test_str = ‘geekforgeeks best’, mid_str = “is” Output : geekforgeeks is best Explanation : Added just in middle, after 1 word.
Method #1 : Using split() + slicing + join()
In this, Strings are converted to a list of words, then the middle position is extracted to append a new phrase. After addition, the string is back converted using join().
Python3
# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join() # initializing stringtest_str = 'geekforgeeks is for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing mid stringmid_str = "best" # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2 # appending in midres = temp[:mid_pos] + [mid_str] + temp[mid_pos:] # conversion backres = ' '.join(res) # printing resultprint("Formulated String : " + str(res))
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks
Method #2 : Using split() + slicing + join() [ more compact]
Similar to the above method, just one-liner way to solve this problem, for more compact.
Python3
# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join() # initializing stringtest_str = 'geekforgeeks is for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing mid stringmid_str = "best" # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2 # joining and construction using single lineres = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:]) # printing resultprint("Formulated String : " + str(res))
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
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": 26366,
"s": 26338,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 26416,
"s": 26366,
"text": "Given a String, add a phrase in the middle of it."
},
{
"code": null,
"e": 26572,
"s": 26416,
"text": "Input : test_str = ‘geekforgeeks is for geeks’, mid_str = “good” Output : geekforgeeks is good for geeks Explanation : Added just in middle, after 2 words."
},
{
"code": null,
"e": 26708,
"s": 26572,
"text": "Input : test_str = ‘geekforgeeks best’, mid_str = “is” Output : geekforgeeks is best Explanation : Added just in middle, after 1 word. "
},
{
"code": null,
"e": 26753,
"s": 26708,
"text": "Method #1 : Using split() + slicing + join()"
},
{
"code": null,
"e": 26925,
"s": 26753,
"text": "In this, Strings are converted to a list of words, then the middle position is extracted to append a new phrase. After addition, the string is back converted using join()."
},
{
"code": null,
"e": 26933,
"s": 26925,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join() # initializing stringtest_str = 'geekforgeeks is for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing mid stringmid_str = \"best\" # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2 # appending in midres = temp[:mid_pos] + [mid_str] + temp[mid_pos:] # conversion backres = ' '.join(res) # printing resultprint(\"Formulated String : \" + str(res))",
"e": 27463,
"s": 26933,
"text": null
},
{
"code": null,
"e": 27566,
"s": 27463,
"text": "The original string is : geekforgeeks is for geeks\nFormulated String : geekforgeeks is best for geeks\n"
},
{
"code": null,
"e": 27627,
"s": 27566,
"text": "Method #2 : Using split() + slicing + join() [ more compact]"
},
{
"code": null,
"e": 27716,
"s": 27627,
"text": "Similar to the above method, just one-liner way to solve this problem, for more compact."
},
{
"code": null,
"e": 27724,
"s": 27716,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join() # initializing stringtest_str = 'geekforgeeks is for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing mid stringmid_str = \"best\" # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2 # joining and construction using single lineres = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:]) # printing resultprint(\"Formulated String : \" + str(res))",
"e": 28252,
"s": 27724,
"text": null
},
{
"code": null,
"e": 28355,
"s": 28252,
"text": "The original string is : geekforgeeks is for geeks\nFormulated String : geekforgeeks is best for geeks\n"
},
{
"code": null,
"e": 28378,
"s": 28355,
"text": "Python string-programs"
},
{
"code": null,
"e": 28385,
"s": 28378,
"text": "Python"
},
{
"code": null,
"e": 28401,
"s": 28385,
"text": "Python Programs"
},
{
"code": null,
"e": 28499,
"s": 28401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28517,
"s": 28499,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28552,
"s": 28517,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28584,
"s": 28552,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28606,
"s": 28584,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28648,
"s": 28606,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28691,
"s": 28648,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28713,
"s": 28691,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28752,
"s": 28713,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28798,
"s": 28752,
"text": "Python | Split string into list of characters"
}
] |
How to create Material Bottom Tab Navigator in React Native ? - GeeksforGeeks
|
25 Jul, 2021
To create a Bottom Tab Navigator using Material, we need to use the createMaterialBottomTabNavigator function available in the react-navigation library. It is designed with the material theme tab bar on the bottom of the screen. It provides you with pleasing UI features and allows you to switch between different routes with animation. The most important highlight of the Material Bottom Tab Navigator is that routes are “lazily initialized”, i.e., the screen components corresponding to the routes are not mounted until they are focused upon.
Creating Application And Installing Modules:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init demo-app
Step 2: Now create a project by the following command.
expo init demo-app
Step 3: Now go into your project folder i.e.demo-appcd demo-app
Step 3: Now go into your project folder i.e.demo-app
cd demo-app
Step 4: Install the required packages using the following command:npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons
Step 4: Install the required packages using the following command:
npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons
Project Structure: The project directory should look like the following:
Project Structure
Example: Now, let’s set up our Material Bottom Tab Navigator, along with some basic CSS styling. There will be 3 screens in our demo application: Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens. First, we will add our App.js file which will hold the Material Bottom Tab Navigator logic. Along with the basic information regarding the screen and label, we will also add icons and basic styles while setting it up.
App. js
import React from "react";import { Ionicons } from "@expo/vector-icons";import { createAppContainer } from "react-navigation";import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs"; import HomeScreen from "./screens/HomeScreen";import UserScreen from "./screens/UserScreen";import SettingScreen from "./screens/SettingScreen"; const TabNavigator = createMaterialBottomTabNavigator( { Home: { screen: HomeScreen, navigationOptions: { tabBarLabel: "Home", tabBarIcon: (tabInfo) => ( <Ionicons name="md-home" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, User: { screen: UserScreen, navigationOptions: { tabBarLabel: "User", tabBarIcon: (tabInfo) => ( <Ionicons name="md-person-circle-outline" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, Setting: { screen: SettingScreen, navigationOptions: { tabBarLabel: "Setting", tabBarIcon: (tabInfo) => ( <Ionicons name="md-settings-outline" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, }, { initialRouteName: "Home", barStyle: { backgroundColor: "#006600" }, }); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}
Now, we need the three screens we will navigate to.
HomeScreen.js
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Home = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Home Screen!</Text> <Ionicons name="md-home" size={80} color="#006600" /> </View> );}; export default Home;
UserScreen.js
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const User = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>User Screen!</Text> <Ionicons name="md-person-circle-outline" size={80} color="#006600" /> </View> );}; export default User;
SettingScreen.js
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name="md-settings-outline" size={80} color="#006600" /> </View> );}; export default Settings;
Run the file: Start the server by using the following command.
expo start
Output: Notice when you tap on a single tab, there is a slight animation. This is automatically provided by the Material Bottom Tab Navigator.
Output
Reference: https://reactnavigation.org/docs/material-bottom-tab-navigator/
Picked
React-Native
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n25 Jul, 2021"
},
{
"code": null,
"e": 26714,
"s": 26169,
"text": "To create a Bottom Tab Navigator using Material, we need to use the createMaterialBottomTabNavigator function available in the react-navigation library. It is designed with the material theme tab bar on the bottom of the screen. It provides you with pleasing UI features and allows you to switch between different routes with animation. The most important highlight of the Material Bottom Tab Navigator is that routes are “lazily initialized”, i.e., the screen components corresponding to the routes are not mounted until they are focused upon."
},
{
"code": null,
"e": 26759,
"s": 26714,
"text": "Creating Application And Installing Modules:"
},
{
"code": null,
"e": 26856,
"s": 26759,
"text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli"
},
{
"code": null,
"e": 26930,
"s": 26856,
"text": "Step 1: Open your terminal and install expo-cli by the following command."
},
{
"code": null,
"e": 26954,
"s": 26930,
"text": "npm install -g expo-cli"
},
{
"code": null,
"e": 27028,
"s": 26954,
"text": "Step 2: Now create a project by the following command.expo init demo-app "
},
{
"code": null,
"e": 27083,
"s": 27028,
"text": "Step 2: Now create a project by the following command."
},
{
"code": null,
"e": 27102,
"s": 27083,
"text": "expo init demo-app"
},
{
"code": null,
"e": 27168,
"s": 27104,
"text": "Step 3: Now go into your project folder i.e.demo-appcd demo-app"
},
{
"code": null,
"e": 27221,
"s": 27168,
"text": "Step 3: Now go into your project folder i.e.demo-app"
},
{
"code": null,
"e": 27233,
"s": 27221,
"text": "cd demo-app"
},
{
"code": null,
"e": 27400,
"s": 27233,
"text": "Step 4: Install the required packages using the following command:npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons"
},
{
"code": null,
"e": 27467,
"s": 27400,
"text": "Step 4: Install the required packages using the following command:"
},
{
"code": null,
"e": 27568,
"s": 27467,
"text": "npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons"
},
{
"code": null,
"e": 27641,
"s": 27568,
"text": "Project Structure: The project directory should look like the following:"
},
{
"code": null,
"e": 27659,
"s": 27641,
"text": "Project Structure"
},
{
"code": null,
"e": 28133,
"s": 27659,
"text": "Example: Now, let’s set up our Material Bottom Tab Navigator, along with some basic CSS styling. There will be 3 screens in our demo application: Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens. First, we will add our App.js file which will hold the Material Bottom Tab Navigator logic. Along with the basic information regarding the screen and label, we will also add icons and basic styles while setting it up."
},
{
"code": null,
"e": 28141,
"s": 28133,
"text": "App. js"
},
{
"code": "import React from \"react\";import { Ionicons } from \"@expo/vector-icons\";import { createAppContainer } from \"react-navigation\";import { createMaterialBottomTabNavigator } from \"react-navigation-material-bottom-tabs\"; import HomeScreen from \"./screens/HomeScreen\";import UserScreen from \"./screens/UserScreen\";import SettingScreen from \"./screens/SettingScreen\"; const TabNavigator = createMaterialBottomTabNavigator( { Home: { screen: HomeScreen, navigationOptions: { tabBarLabel: \"Home\", tabBarIcon: (tabInfo) => ( <Ionicons name=\"md-home\" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, User: { screen: UserScreen, navigationOptions: { tabBarLabel: \"User\", tabBarIcon: (tabInfo) => ( <Ionicons name=\"md-person-circle-outline\" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, Setting: { screen: SettingScreen, navigationOptions: { tabBarLabel: \"Setting\", tabBarIcon: (tabInfo) => ( <Ionicons name=\"md-settings-outline\" size={tabInfo.focused ? 26 : 20} color={tabInfo.tintColor} /> ), }, }, }, { initialRouteName: \"Home\", barStyle: { backgroundColor: \"#006600\" }, }); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}",
"e": 29699,
"s": 28141,
"text": null
},
{
"code": null,
"e": 29751,
"s": 29699,
"text": "Now, we need the three screens we will navigate to."
},
{
"code": null,
"e": 29765,
"s": 29751,
"text": "HomeScreen.js"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Home = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Home Screen!</Text> <Ionicons name=\"md-home\" size={80} color=\"#006600\" /> </View> );}; export default Home;",
"e": 30162,
"s": 29765,
"text": null
},
{
"code": null,
"e": 30176,
"s": 30162,
"text": "UserScreen.js"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const User = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>User Screen!</Text> <Ionicons name=\"md-person-circle-outline\" size={80} color=\"#006600\" /> </View> );}; export default User;",
"e": 30590,
"s": 30176,
"text": null
},
{
"code": null,
"e": 30607,
"s": 30590,
"text": "SettingScreen.js"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name=\"md-settings-outline\" size={80} color=\"#006600\" /> </View> );}; export default Settings;",
"e": 31028,
"s": 30607,
"text": null
},
{
"code": null,
"e": 31091,
"s": 31028,
"text": "Run the file: Start the server by using the following command."
},
{
"code": null,
"e": 31102,
"s": 31091,
"text": "expo start"
},
{
"code": null,
"e": 31245,
"s": 31102,
"text": "Output: Notice when you tap on a single tab, there is a slight animation. This is automatically provided by the Material Bottom Tab Navigator."
},
{
"code": null,
"e": 31252,
"s": 31245,
"text": "Output"
},
{
"code": null,
"e": 31327,
"s": 31252,
"text": "Reference: https://reactnavigation.org/docs/material-bottom-tab-navigator/"
},
{
"code": null,
"e": 31334,
"s": 31327,
"text": "Picked"
},
{
"code": null,
"e": 31347,
"s": 31334,
"text": "React-Native"
},
{
"code": null,
"e": 31364,
"s": 31347,
"text": "Web Technologies"
},
{
"code": null,
"e": 31462,
"s": 31364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31502,
"s": 31462,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31547,
"s": 31502,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31590,
"s": 31547,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31651,
"s": 31590,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31723,
"s": 31651,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31778,
"s": 31723,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 31823,
"s": 31778,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 31873,
"s": 31823,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31897,
"s": 31873,
"text": "REST API (Introduction)"
}
] |
Golang program that uses switch, multiple value cases - GeeksforGeeks
|
10 May, 2020
Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a single case. This is achieved by separating the multiple values in the case with a comma.
Example 1:
// Golang program to illustrate the// use of switch with multiple value casespackage main import ( "fmt") func main() { // string to input month from user var month string fmt.Scanln(&month) // switch case for predicting // seasons for month entered // each switch case has more // than one values switch month { case "january", "december": fmt.Println("Winter.") case "february", "march": fmt.Println("Spring.") case "april", "may", "june": fmt.Println("Summer.") case "july", "august": fmt.Println("Monsoon.") case "september", "november": fmt.Println("Autumn.") }}
Input : january
Output : Winter.
Input : september
Output : Autumn.
Rather than making different individual cases for months having the same season, we clubbed different months with the same output. This saves us to write redundant pieces of code.
Example 2:
// Golang program to illustrate the// use of switch with multiple value casespackage main import ( "fmt") func main() { // integer to input number from // user (only 1-10) var number int fmt.Scanln(&number) // switch case for predicting // whether the number is even or odd // each switch case has more // than one values switch number { case 2, 4, 6, 8, 10: fmt.Println("You entered an even number.") case 1, 3, 5, 7, 9: fmt.Println("You entered an odd number.") }}
Input : 6
Output : You entered an even number.
Input : 5
Output : You entered an odd number.
Instead of writing 10 different cases to check whether the entered number is even or not, we could simply do the same in 2 switch cases using multiple case values.
Example 3:
// Golang program to illustrate the// use of switch with multiple value casespackage main import ( "fmt") func main() { // character input (a-z or A-Z) var alphabet string fmt.Scanln(&alphabet) // switch case for predicting // whether the character is // uppercase or lowercase // each switch case has more // than one values switch alphabet { case "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z": fmt.Println("Lowercase alphabet character.") case "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z": fmt.Println("Uppercase alphabet character.") }}
Input : g
Output : Lowercase alphabet character.
Input : F
Output : Uppercase alphabet character.
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Time Durations in Golang
Strings in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang
|
[
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26141,
"s": 25703,
"text": "Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a single case. This is achieved by separating the multiple values in the case with a comma."
},
{
"code": null,
"e": 26152,
"s": 26141,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the// use of switch with multiple value casespackage main import ( \"fmt\") func main() { // string to input month from user var month string fmt.Scanln(&month) // switch case for predicting // seasons for month entered // each switch case has more // than one values switch month { case \"january\", \"december\": fmt.Println(\"Winter.\") case \"february\", \"march\": fmt.Println(\"Spring.\") case \"april\", \"may\", \"june\": fmt.Println(\"Summer.\") case \"july\", \"august\": fmt.Println(\"Monsoon.\") case \"september\", \"november\": fmt.Println(\"Autumn.\") }}",
"e": 26853,
"s": 26152,
"text": null
},
{
"code": null,
"e": 26923,
"s": 26853,
"text": "Input : january\nOutput : Winter.\n\nInput : september\nOutput : Autumn.\n"
},
{
"code": null,
"e": 27103,
"s": 26923,
"text": "Rather than making different individual cases for months having the same season, we clubbed different months with the same output. This saves us to write redundant pieces of code."
},
{
"code": null,
"e": 27114,
"s": 27103,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the// use of switch with multiple value casespackage main import ( \"fmt\") func main() { // integer to input number from // user (only 1-10) var number int fmt.Scanln(&number) // switch case for predicting // whether the number is even or odd // each switch case has more // than one values switch number { case 2, 4, 6, 8, 10: fmt.Println(\"You entered an even number.\") case 1, 3, 5, 7, 9: fmt.Println(\"You entered an odd number.\") }}",
"e": 27668,
"s": 27114,
"text": null
},
{
"code": null,
"e": 27763,
"s": 27668,
"text": "Input : 6\nOutput : You entered an even number.\n\nInput : 5\nOutput : You entered an odd number.\n"
},
{
"code": null,
"e": 27927,
"s": 27763,
"text": "Instead of writing 10 different cases to check whether the entered number is even or not, we could simply do the same in 2 switch cases using multiple case values."
},
{
"code": null,
"e": 27938,
"s": 27927,
"text": "Example 3:"
},
{
"code": "// Golang program to illustrate the// use of switch with multiple value casespackage main import ( \"fmt\") func main() { // character input (a-z or A-Z) var alphabet string fmt.Scanln(&alphabet) // switch case for predicting // whether the character is // uppercase or lowercase // each switch case has more // than one values switch alphabet { case \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\": fmt.Println(\"Lowercase alphabet character.\") case \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\": fmt.Println(\"Uppercase alphabet character.\") }}",
"e": 28769,
"s": 27938,
"text": null
},
{
"code": null,
"e": 28869,
"s": 28769,
"text": "Input : g\nOutput : Lowercase alphabet character.\n\nInput : F\nOutput : Uppercase alphabet character.\n"
},
{
"code": null,
"e": 28884,
"s": 28869,
"text": "Golang-Program"
},
{
"code": null,
"e": 28891,
"s": 28884,
"text": "Picked"
},
{
"code": null,
"e": 28903,
"s": 28891,
"text": "Go Language"
},
{
"code": null,
"e": 29001,
"s": 28903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29047,
"s": 29001,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 29076,
"s": 29047,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 29101,
"s": 29076,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 29119,
"s": 29101,
"text": "Strings in Golang"
},
{
"code": null,
"e": 29140,
"s": 29119,
"text": "Structures in Golang"
},
{
"code": null,
"e": 29195,
"s": 29140,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 29210,
"s": 29195,
"text": "Rune in Golang"
},
{
"code": null,
"e": 29234,
"s": 29210,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 29255,
"s": 29234,
"text": "Loops in Go Language"
}
] |
context_click - Action Chains in Selenium Python - GeeksforGeeks
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around context_click method on Action Chains in Python Selenium. context_click method is used to perform a context-click (right click) on an element.
Syntax –
context_click(on_element=None)
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use context_click method as an Action chain as below –
context_click(on_element=element)
To demonstrate, context_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # context click the itemaction.context_click(on_element = element) # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25975,
"s": 25947,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 26570,
"s": 25975,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around context_click method on Action Chains in Python Selenium. context_click method is used to perform a context-click (right click) on an element."
},
{
"code": null,
"e": 26579,
"s": 26570,
"text": "Syntax –"
},
{
"code": null,
"e": 26610,
"s": 26579,
"text": "context_click(on_element=None)"
},
{
"code": null,
"e": 26620,
"s": 26610,
"text": "Example –"
},
{
"code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />",
"e": 26674,
"s": 26620,
"text": null
},
{
"code": null,
"e": 26755,
"s": 26674,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")",
"e": 26851,
"s": 26755,
"text": null
},
{
"code": null,
"e": 26918,
"s": 26851,
"text": "Now one can use context_click method as an Action chain as below –"
},
{
"code": null,
"e": 26953,
"s": 26918,
"text": "context_click(on_element=element)\n"
},
{
"code": null,
"e": 27098,
"s": 26953,
"text": "To demonstrate, context_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 27108,
"s": 27098,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # context click the itemaction.context_click(on_element = element) # perform the operationaction.perform()",
"e": 27607,
"s": 27108,
"text": null
},
{
"code": null,
"e": 27616,
"s": 27607,
"text": "Output –"
},
{
"code": null,
"e": 27632,
"s": 27616,
"text": "Python-selenium"
},
{
"code": null,
"e": 27641,
"s": 27632,
"text": "selenium"
},
{
"code": null,
"e": 27648,
"s": 27641,
"text": "Python"
},
{
"code": null,
"e": 27746,
"s": 27648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27764,
"s": 27746,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27796,
"s": 27764,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27818,
"s": 27796,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27860,
"s": 27818,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27890,
"s": 27860,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27916,
"s": 27890,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27945,
"s": 27916,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27989,
"s": 27945,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28026,
"s": 27989,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Minimum flips to make all 1s in left and 0s in right | Set 2 - GeeksforGeeks
|
24 May, 2021
Given a binary array, we can flip all the 1 are in the left part and all the 0 to the right part.Calculate the minimum flips required to make all 1s in left and all 0s in right.Examples :
Input: 1011000
Output: 1
1 flip is required to make it 1111000.
Input : 00001
Output : 2
2 flips required to make it 10000.
We have discussed a bitmask based solution in below post. Minimum flips to make all 1s in left and 0s in right | Set 1 (Using Bitmask)It can be done with O(N) time complexity (where N – number of bits) and O(N) extra memory
Calculate number of flips of ‘0’ needed to be done while moving from left to right to have all ‘1’ in bits.Calculate number of flips of ‘1’ needed to be done while moving from right to left to have all ‘0’ in bits.Traversing through all positions between bits and find minimal sum of ‘0’-flips+’1′-flips from both arrays.
Calculate number of flips of ‘0’ needed to be done while moving from left to right to have all ‘1’ in bits.
Calculate number of flips of ‘1’ needed to be done while moving from right to left to have all ‘0’ in bits.
Traversing through all positions between bits and find minimal sum of ‘0’-flips+’1′-flips from both arrays.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find minimum flips required// to make all 1s in left and 0s in right.#include <bits/stdc++.h>using namespace std; int minimalFilps(string bits){ int n = bits.length(); // two arrays will keep the count for number // of 0s' and 1s' to be flipped while // traversing from left to right and right to // left respectively int flipsFromLeft[n]; int flipsFromRight[n]; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. If sum // of leftflip and rightFlip is smaller than minflips, // then update minFlips int minFlips = INT_MAX; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips;} // Driver codeint main(){ string bits = "00001"; cout << minimalFilps(bits) << endl; return 0;}
// Java program to find minimum flips required// to make all 1s in left and 0s in right.import java.io.*; class GFG{ static int minimalFilps(String bits) { int n = bits.length(); // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively int flipsFromLeft[] = new int[n]; int flipsFromRight[] =new int[n] ; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits.charAt(i) == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits.charAt(i) == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. If sum // of leftflip and rightFlip is smaller than minflips, // then update minFlips int minFlips = Integer.MAX_VALUE; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } // Driver code public static void main (String[] args) { String bits = "00001"; System.out.println(minimalFilps(bits)); }} // This code is contributed by vt_m.
# Python 3 program to find minimum flips required# to make all 1s in left and 0s in right.import sys def minimalFilps(bits): n = len(bits) # two arrays will keep the count for number # of 0s' and 1s' to be flipped while # traversing from left to right and right to # left respectively flipsFromLeft = [0 for i in range(n)] flipsFromRight = [0 for i in range(n)] # Fill flipsFromLeft[] flips = 0 for i in range(0, n, 1): if (bits[i] == '0'): flips = flips + 1 flipsFromLeft[i] = flips # Fill flipsFromRight[] flips = 0 i = n - 1 while(i >= 0): if (bits[i] == '1'): flips = flips + 1 i = i - 1 flipsFromRight[i] = flips # initialize minFlip to highest int value. # If sum of leftflip and rightFlip is smaller # than minflips, then update minFlips minFlips = sys.maxsize for i in range(1, n, 1): if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips): minFlips = (flipsFromLeft[i - 1] + flipsFromRight[i]) return minFlips # Driver codeif __name__ == '__main__': bits = "00001" print(minimalFilps(bits)) # This code is contributed by# Surendra_Gangwar
// C# program to find minimum flips required// to make all 1s in left and 0s in right.using System; class GFG{ static int minimalFilps(String bits) { int n = bits.Length; // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively int []flipsFromLeft = new int[n]; int []flipsFromRight =new int[n] ; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. // If sum of leftflip and rightFlip is smaller // than minflips, then update minFlips int minFlips = int.MaxValue; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } // Driver code public static void Main () { string bits = "00001"; Console.WriteLine(minimalFilps(bits)); }} // This code is contributed by vt_m.
<?php// PHP program to find minimum// flips required to make all// 1s in left and 0s in right. function minimalFilps($bits){ $n = strlen($bits); // two arrays will keep the // count for number of 0s' // and 1s' to be flipped // while traversing from // left to right and right // to left respectively $flipsFromLeft[$n] = 0; $flipsFromRight[$n] = 0; // Fill flipsFromLeft[] $flips = 0; for ($i = 0; $i < $n; $i++) { if ($bits[$i] == '0') $flips++; $flipsFromLeft[$i] = $flips; } // Fill flipsFromRight[] $flips = 0; for ($i = $n - 1; $i >= 0; $i--) { if ($bits[$i] == '1') $flips++; $flipsFromRight[$i] = $flips; } // initialize minFlip to // highest int value. If sum // of leftflip and rightFlip // is smaller than minflips, // then update minFlips $INT_MAX=2147483647; $minFlips = $INT_MAX; for ($i = 1; $i < $n; $i++) { if ($flipsFromLeft[$i - 1] + $flipsFromRight[$i] < $minFlips) $minFlips = $flipsFromLeft[$i - 1] + $flipsFromRight[$i]; } return $minFlips;} // Driver Code $bits = "00001"; echo minimalFilps($bits) ; // This code is contributed by nitin mittal.?>
<script> // Javascript program to find minimum flips required // to make all 1s in left and 0s in right. function minimalFilps(bits) { let n = bits.length; // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively let flipsFromLeft = new Array(n); flipsFromLeft.fill(0); let flipsFromRight =new Array(n); flipsFromRight.fill(0); // Fill flipsFromLeft[] let flips = 0; for (let i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (let i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. // If sum of leftflip and rightFlip is smaller // than minflips, then update minFlips let minFlips = Number.MAX_VALUE; for (let i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } let bits = "00001"; document.write(minimalFilps(bits)); // This code is contributed by divyesh072019.</script>
Output:
2
vt_m
nitin mittal
SURENDRA_GANGWAR
divyesh072019
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Queue | Set 1 (Introduction and Array Implementation)
Array of Strings in C++ (5 Different Ways to Create)
|
[
{
"code": null,
"e": 26221,
"s": 26193,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 26411,
"s": 26221,
"text": "Given a binary array, we can flip all the 1 are in the left part and all the 0 to the right part.Calculate the minimum flips required to make all 1s in left and all 0s in right.Examples : "
},
{
"code": null,
"e": 26539,
"s": 26411,
"text": "Input: 1011000 \nOutput: 1\n1 flip is required to make it 1111000.\n\nInput : 00001 \nOutput : 2\n2 flips required to make it 10000."
},
{
"code": null,
"e": 26767,
"s": 26541,
"text": "We have discussed a bitmask based solution in below post. Minimum flips to make all 1s in left and 0s in right | Set 1 (Using Bitmask)It can be done with O(N) time complexity (where N – number of bits) and O(N) extra memory "
},
{
"code": null,
"e": 27089,
"s": 26767,
"text": "Calculate number of flips of ‘0’ needed to be done while moving from left to right to have all ‘1’ in bits.Calculate number of flips of ‘1’ needed to be done while moving from right to left to have all ‘0’ in bits.Traversing through all positions between bits and find minimal sum of ‘0’-flips+’1′-flips from both arrays."
},
{
"code": null,
"e": 27197,
"s": 27089,
"text": "Calculate number of flips of ‘0’ needed to be done while moving from left to right to have all ‘1’ in bits."
},
{
"code": null,
"e": 27305,
"s": 27197,
"text": "Calculate number of flips of ‘1’ needed to be done while moving from right to left to have all ‘0’ in bits."
},
{
"code": null,
"e": 27413,
"s": 27305,
"text": "Traversing through all positions between bits and find minimal sum of ‘0’-flips+’1′-flips from both arrays."
},
{
"code": null,
"e": 27419,
"s": 27415,
"text": "C++"
},
{
"code": null,
"e": 27424,
"s": 27419,
"text": "Java"
},
{
"code": null,
"e": 27432,
"s": 27424,
"text": "Python3"
},
{
"code": null,
"e": 27435,
"s": 27432,
"text": "C#"
},
{
"code": null,
"e": 27439,
"s": 27435,
"text": "PHP"
},
{
"code": null,
"e": 27450,
"s": 27439,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum flips required// to make all 1s in left and 0s in right.#include <bits/stdc++.h>using namespace std; int minimalFilps(string bits){ int n = bits.length(); // two arrays will keep the count for number // of 0s' and 1s' to be flipped while // traversing from left to right and right to // left respectively int flipsFromLeft[n]; int flipsFromRight[n]; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. If sum // of leftflip and rightFlip is smaller than minflips, // then update minFlips int minFlips = INT_MAX; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips;} // Driver codeint main(){ string bits = \"00001\"; cout << minimalFilps(bits) << endl; return 0;}",
"e": 28660,
"s": 27450,
"text": null
},
{
"code": "// Java program to find minimum flips required// to make all 1s in left and 0s in right.import java.io.*; class GFG{ static int minimalFilps(String bits) { int n = bits.length(); // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively int flipsFromLeft[] = new int[n]; int flipsFromRight[] =new int[n] ; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits.charAt(i) == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits.charAt(i) == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. If sum // of leftflip and rightFlip is smaller than minflips, // then update minFlips int minFlips = Integer.MAX_VALUE; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } // Driver code public static void main (String[] args) { String bits = \"00001\"; System.out.println(minimalFilps(bits)); }} // This code is contributed by vt_m.",
"e": 30258,
"s": 28660,
"text": null
},
{
"code": "# Python 3 program to find minimum flips required# to make all 1s in left and 0s in right.import sys def minimalFilps(bits): n = len(bits) # two arrays will keep the count for number # of 0s' and 1s' to be flipped while # traversing from left to right and right to # left respectively flipsFromLeft = [0 for i in range(n)] flipsFromRight = [0 for i in range(n)] # Fill flipsFromLeft[] flips = 0 for i in range(0, n, 1): if (bits[i] == '0'): flips = flips + 1 flipsFromLeft[i] = flips # Fill flipsFromRight[] flips = 0 i = n - 1 while(i >= 0): if (bits[i] == '1'): flips = flips + 1 i = i - 1 flipsFromRight[i] = flips # initialize minFlip to highest int value. # If sum of leftflip and rightFlip is smaller # than minflips, then update minFlips minFlips = sys.maxsize for i in range(1, n, 1): if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips): minFlips = (flipsFromLeft[i - 1] + flipsFromRight[i]) return minFlips # Driver codeif __name__ == '__main__': bits = \"00001\" print(minimalFilps(bits)) # This code is contributed by# Surendra_Gangwar",
"e": 31503,
"s": 30258,
"text": null
},
{
"code": "// C# program to find minimum flips required// to make all 1s in left and 0s in right.using System; class GFG{ static int minimalFilps(String bits) { int n = bits.Length; // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively int []flipsFromLeft = new int[n]; int []flipsFromRight =new int[n] ; // Fill flipsFromLeft[] int flips = 0; for (int i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (int i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. // If sum of leftflip and rightFlip is smaller // than minflips, then update minFlips int minFlips = int.MaxValue; for (int i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } // Driver code public static void Main () { string bits = \"00001\"; Console.WriteLine(minimalFilps(bits)); }} // This code is contributed by vt_m.",
"e": 32985,
"s": 31503,
"text": null
},
{
"code": "<?php// PHP program to find minimum// flips required to make all// 1s in left and 0s in right. function minimalFilps($bits){ $n = strlen($bits); // two arrays will keep the // count for number of 0s' // and 1s' to be flipped // while traversing from // left to right and right // to left respectively $flipsFromLeft[$n] = 0; $flipsFromRight[$n] = 0; // Fill flipsFromLeft[] $flips = 0; for ($i = 0; $i < $n; $i++) { if ($bits[$i] == '0') $flips++; $flipsFromLeft[$i] = $flips; } // Fill flipsFromRight[] $flips = 0; for ($i = $n - 1; $i >= 0; $i--) { if ($bits[$i] == '1') $flips++; $flipsFromRight[$i] = $flips; } // initialize minFlip to // highest int value. If sum // of leftflip and rightFlip // is smaller than minflips, // then update minFlips $INT_MAX=2147483647; $minFlips = $INT_MAX; for ($i = 1; $i < $n; $i++) { if ($flipsFromLeft[$i - 1] + $flipsFromRight[$i] < $minFlips) $minFlips = $flipsFromLeft[$i - 1] + $flipsFromRight[$i]; } return $minFlips;} // Driver Code $bits = \"00001\"; echo minimalFilps($bits) ; // This code is contributed by nitin mittal.?>",
"e": 34276,
"s": 32985,
"text": null
},
{
"code": "<script> // Javascript program to find minimum flips required // to make all 1s in left and 0s in right. function minimalFilps(bits) { let n = bits.length; // two arrays will keep the count // for number of 0s' and 1s' to be // flipped while traversing from // left to right and right to // left respectively let flipsFromLeft = new Array(n); flipsFromLeft.fill(0); let flipsFromRight =new Array(n); flipsFromRight.fill(0); // Fill flipsFromLeft[] let flips = 0; for (let i = 0; i < n; i++) { if (bits[i] == '0') flips++; flipsFromLeft[i] = flips; } // Fill flipsFromRight[] flips = 0; for (let i = n - 1; i >= 0; i--) { if (bits[i] == '1') flips++; flipsFromRight[i] = flips; } // initialize minFlip to highest int value. // If sum of leftflip and rightFlip is smaller // than minflips, then update minFlips let minFlips = Number.MAX_VALUE; for (let i = 1; i < n; i++) { if (flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips) minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]; } return minFlips; } let bits = \"00001\"; document.write(minimalFilps(bits)); // This code is contributed by divyesh072019.</script>",
"e": 35772,
"s": 34276,
"text": null
},
{
"code": null,
"e": 35782,
"s": 35772,
"text": "Output: "
},
{
"code": null,
"e": 35784,
"s": 35782,
"text": "2"
},
{
"code": null,
"e": 35791,
"s": 35786,
"text": "vt_m"
},
{
"code": null,
"e": 35804,
"s": 35791,
"text": "nitin mittal"
},
{
"code": null,
"e": 35821,
"s": 35804,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 35835,
"s": 35821,
"text": "divyesh072019"
},
{
"code": null,
"e": 35849,
"s": 35835,
"text": "binary-string"
},
{
"code": null,
"e": 35856,
"s": 35849,
"text": "Arrays"
},
{
"code": null,
"e": 35863,
"s": 35856,
"text": "Arrays"
},
{
"code": null,
"e": 35961,
"s": 35863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36029,
"s": 35961,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36052,
"s": 36029,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36084,
"s": 36052,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36098,
"s": 36084,
"text": "Linear Search"
},
{
"code": null,
"e": 36119,
"s": 36098,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36204,
"s": 36119,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 36249,
"s": 36204,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36297,
"s": 36249,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 36351,
"s": 36297,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
}
] |
Java Multiple Catch Block - GeeksforGeeks
|
07 Dec, 2021
Before Java 7, we had to catch only one exception type in each catch block. So, whenever we needed to handle more than one specific exception but take some action for all exceptions, we had to have more than one catch block containing the same code.
In the following code, we have to handle two different exceptions but take the same action for both. So we needed to have two different catch blocks as of Java 6.0.
Java
// A Java program to demonstrate that we needed// multiple catch blocks for multiple exceptions// prior to Java 7 import java.util.Scanner;public class Test{ public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (ArithmeticException ex) { System.out.println("Arithmetic " + ex); } catch (NumberFormatException ex) { System.out.println("Number Format Exception " + ex); } }}
Input 1:
GeeksforGeeks
Output 1:
Exception encountered java.lang.NumberFormatException:
For input string: "GeeksforGeeks"
Input 2:
0
Output 2:
Arithmetic Exception encountered java.lang.ArithmeticException: / by zero
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency. The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy.
Note: If a catch block handles multiple exceptions, the catch parameter is implicitly final. This means we cannot assign any values to catch parameters.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
Java
// A Java program to demonstrate// multicatch feature import java.util.Scanner; public class Test{ public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (NumberFormatException | ArithmeticException ex) { System.out.println("Exception encountered " + ex); } }}
Input 1:
GeeksforGeeks
Output 1:
Exception encountered java.lang.NumberFormatException:
For input string: "GeeksforGeeks"
Input 2:
0
Output 2:
Exception encountered
java.lang.ArithmeticException: / by zero
A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler. That is, the bytecode has no replication of exception handlers.
1. If all the exceptions belong to the same class hierarchy, we should be catching the base exception type. However, to catch each exception, it needs to be done separately in their catch blocks.
2. Single catch block can handle more than one type of exception. However, the base (or ancestor) class and subclass (or descendant) exceptions can not be caught in one statement. For Example
// Not Valid as Exception is an ancestor of
// NumberFormatException
catch(NumberFormatException | Exception ex)
3. All the exceptions must be separated by vertical bar pipe |.
This article is contributed by Aparna Vadlamani. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
nishkarshgandhi
Java-Exceptions
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
C++ Classes and Objects
Interfaces in Java
|
[
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 25923,
"s": 25673,
"text": "Before Java 7, we had to catch only one exception type in each catch block. So, whenever we needed to handle more than one specific exception but take some action for all exceptions, we had to have more than one catch block containing the same code."
},
{
"code": null,
"e": 26088,
"s": 25923,
"text": "In the following code, we have to handle two different exceptions but take the same action for both. So we needed to have two different catch blocks as of Java 6.0."
},
{
"code": null,
"e": 26093,
"s": 26088,
"text": "Java"
},
{
"code": "// A Java program to demonstrate that we needed// multiple catch blocks for multiple exceptions// prior to Java 7 import java.util.Scanner;public class Test{ public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + \" is a factor of 99\"); } catch (ArithmeticException ex) { System.out.println(\"Arithmetic \" + ex); } catch (NumberFormatException ex) { System.out.println(\"Number Format Exception \" + ex); } }}",
"e": 26758,
"s": 26093,
"text": null
},
{
"code": null,
"e": 26768,
"s": 26758,
"text": "Input 1: "
},
{
"code": null,
"e": 26782,
"s": 26768,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 26793,
"s": 26782,
"text": "Output 1: "
},
{
"code": null,
"e": 26884,
"s": 26793,
"text": "Exception encountered java.lang.NumberFormatException: \n\nFor input string: \"GeeksforGeeks\""
},
{
"code": null,
"e": 26894,
"s": 26884,
"text": "Input 2: "
},
{
"code": null,
"e": 26896,
"s": 26894,
"text": "0"
},
{
"code": null,
"e": 26907,
"s": 26896,
"text": "Output 2: "
},
{
"code": null,
"e": 26981,
"s": 26907,
"text": "Arithmetic Exception encountered java.lang.ArithmeticException: / by zero"
},
{
"code": null,
"e": 27134,
"s": 26981,
"text": "Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block."
},
{
"code": null,
"e": 27384,
"s": 27134,
"text": "Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency. The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy."
},
{
"code": null,
"e": 27537,
"s": 27384,
"text": "Note: If a catch block handles multiple exceptions, the catch parameter is implicitly final. This means we cannot assign any values to catch parameters."
},
{
"code": null,
"e": 27545,
"s": 27537,
"text": "Syntax:"
},
{
"code": null,
"e": 27636,
"s": 27545,
"text": "try { \n // code\n} \ncatch (ExceptionType1 | Exceptiontype2 ex){ \n // catch block\n}"
},
{
"code": null,
"e": 27641,
"s": 27636,
"text": "Java"
},
{
"code": "// A Java program to demonstrate// multicatch feature import java.util.Scanner; public class Test{ public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + \" is a factor of 99\"); } catch (NumberFormatException | ArithmeticException ex) { System.out.println(\"Exception encountered \" + ex); } }}",
"e": 28149,
"s": 27641,
"text": null
},
{
"code": null,
"e": 28159,
"s": 28149,
"text": "Input 1: "
},
{
"code": null,
"e": 28173,
"s": 28159,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 28185,
"s": 28173,
"text": "Output 1: "
},
{
"code": null,
"e": 28275,
"s": 28185,
"text": "Exception encountered java.lang.NumberFormatException:\n\nFor input string: \"GeeksforGeeks\""
},
{
"code": null,
"e": 28286,
"s": 28275,
"text": "Input 2: "
},
{
"code": null,
"e": 28288,
"s": 28286,
"text": "0"
},
{
"code": null,
"e": 28300,
"s": 28288,
"text": "Output 2: "
},
{
"code": null,
"e": 28365,
"s": 28300,
"text": "Exception encountered \n\njava.lang.ArithmeticException: / by zero"
},
{
"code": null,
"e": 28547,
"s": 28365,
"text": "A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler. That is, the bytecode has no replication of exception handlers."
},
{
"code": null,
"e": 28743,
"s": 28547,
"text": "1. If all the exceptions belong to the same class hierarchy, we should be catching the base exception type. However, to catch each exception, it needs to be done separately in their catch blocks."
},
{
"code": null,
"e": 28935,
"s": 28743,
"text": "2. Single catch block can handle more than one type of exception. However, the base (or ancestor) class and subclass (or descendant) exceptions can not be caught in one statement. For Example"
},
{
"code": null,
"e": 29050,
"s": 28935,
"text": "// Not Valid as Exception is an ancestor of \n// NumberFormatException\ncatch(NumberFormatException | Exception ex) "
},
{
"code": null,
"e": 29114,
"s": 29050,
"text": "3. All the exceptions must be separated by vertical bar pipe |."
},
{
"code": null,
"e": 29509,
"s": 29114,
"text": "This article is contributed by Aparna Vadlamani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 29525,
"s": 29509,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 29541,
"s": 29525,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 29546,
"s": 29541,
"text": "Java"
},
{
"code": null,
"e": 29565,
"s": 29546,
"text": "School Programming"
},
{
"code": null,
"e": 29570,
"s": 29565,
"text": "Java"
},
{
"code": null,
"e": 29668,
"s": 29570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29683,
"s": 29668,
"text": "Stream In Java"
},
{
"code": null,
"e": 29702,
"s": 29683,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29720,
"s": 29702,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29740,
"s": 29720,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29764,
"s": 29740,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29782,
"s": 29764,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29798,
"s": 29782,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29817,
"s": 29798,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29841,
"s": 29817,
"text": "C++ Classes and Objects"
}
] |
Python | Split URL from Query Parameters - GeeksforGeeks
|
07 Feb, 2022
Sometimes, while web development, we can come across a task in which we may require to perform a split of query parameters from URLs which is done by ‘?’ character. This has application over web development as well as other domains which involve URLs. Lets discuss certain ways in which this task can be performed.Method #1 : Using split() This is one of the way in which we can solve this problem. We split by ‘?’ and return the first part of split for result.
Python3
# Python3 code to demonstrate working of# Split URL from Query Parameters# Using split() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint("The original string is : " + str(test_str)) # Split URL from Query Parameters# Using split()res = test_str.split('?')[0] # printing resultprint("The base URL is : " + res)
The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org
Method #2 : Using rfind() This is another way in which we need to perform this task. In this, we find the first occurrence of ‘?’ from right and slice the string.
Python3
# Python3 code to demonstrate working of# Split URL from Query Parameters# Using rfind() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint("The original string is : " + str(test_str)) # Split URL from Query Parameters# Using rfind()res = test_str[:test_str.rfind('?')] # printing resultprint("The base URL is : " + res)
The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 26018,
"s": 25555,
"text": "Sometimes, while web development, we can come across a task in which we may require to perform a split of query parameters from URLs which is done by ‘?’ character. This has application over web development as well as other domains which involve URLs. Lets discuss certain ways in which this task can be performed.Method #1 : Using split() This is one of the way in which we can solve this problem. We split by ‘?’ and return the first part of split for result. "
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split URL from Query Parameters# Using split() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint(\"The original string is : \" + str(test_str)) # Split URL from Query Parameters# Using split()res = test_str.split('?')[0] # printing resultprint(\"The base URL is : \" + res)",
"e": 26386,
"s": 26026,
"text": null
},
{
"code": null,
"e": 26481,
"s": 26386,
"text": "The original string is : www.geeksforgeeks.org?is=best\nThe base URL is : www.geeksforgeeks.org"
},
{
"code": null,
"e": 26648,
"s": 26483,
"text": " Method #2 : Using rfind() This is another way in which we need to perform this task. In this, we find the first occurrence of ‘?’ from right and slice the string. "
},
{
"code": null,
"e": 26656,
"s": 26648,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split URL from Query Parameters# Using rfind() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint(\"The original string is : \" + str(test_str)) # Split URL from Query Parameters# Using rfind()res = test_str[:test_str.rfind('?')] # printing resultprint(\"The base URL is : \" + res)",
"e": 27024,
"s": 26656,
"text": null
},
{
"code": null,
"e": 27119,
"s": 27024,
"text": "The original string is : www.geeksforgeeks.org?is=best\nThe base URL is : www.geeksforgeeks.org"
},
{
"code": null,
"e": 27137,
"s": 27121,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27160,
"s": 27137,
"text": "Python string-programs"
},
{
"code": null,
"e": 27167,
"s": 27160,
"text": "Python"
},
{
"code": null,
"e": 27183,
"s": 27167,
"text": "Python Programs"
},
{
"code": null,
"e": 27281,
"s": 27183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27313,
"s": 27281,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27355,
"s": 27313,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27397,
"s": 27355,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27453,
"s": 27397,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27480,
"s": 27453,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27502,
"s": 27480,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27541,
"s": 27502,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27587,
"s": 27541,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27625,
"s": 27587,
"text": "Python | Convert a list to dictionary"
}
] |
Matplotlib.pyplot.clim() in Python - GeeksforGeeks
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The clim() function in pyplot module of matplotlib library is used to set the color limits of the current image.
Syntax: matplotlib.pyplot.clim(vmin=None, vmax=None)
Parameters: This method accepts only two parameters.
vmin, vmax : These parameters are used for color scaling.
Below examples illustrate the matplotlib.pyplot.clim() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)] z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() im = plt.imshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent = [x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower') plt.clim(vmin = 0, vmax = 2)plt.title('matplotlib.pyplot.clim Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, cmap ="Greens", alpha = 0.7, interpolation ='bilinear', extent = extent) plt.clim(0, 2)plt.title('matplotlib.pyplot.clim Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24184,
"s": 24156,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 24489,
"s": 24184,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 24602,
"s": 24489,
"text": "The clim() function in pyplot module of matplotlib library is used to set the color limits of the current image."
},
{
"code": null,
"e": 24655,
"s": 24602,
"text": "Syntax: matplotlib.pyplot.clim(vmin=None, vmax=None)"
},
{
"code": null,
"e": 24708,
"s": 24655,
"text": "Parameters: This method accepts only two parameters."
},
{
"code": null,
"e": 24766,
"s": 24708,
"text": "vmin, vmax : These parameters are used for color scaling."
},
{
"code": null,
"e": 24852,
"s": 24766,
"text": "Below examples illustrate the matplotlib.pyplot.clim() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 24863,
"s": 24852,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)] z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() im = plt.imshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent = [x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower') plt.clim(vmin = 0, vmax = 2)plt.title('matplotlib.pyplot.clim Example')plt.show()",
"e": 25614,
"s": 24863,
"text": null
},
{
"code": null,
"e": 25622,
"s": 25614,
"text": "Output:"
},
{
"code": null,
"e": 25633,
"s": 25622,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, cmap =\"Greens\", alpha = 0.7, interpolation ='bilinear', extent = extent) plt.clim(0, 2)plt.title('matplotlib.pyplot.clim Example')plt.show()",
"e": 26367,
"s": 25633,
"text": null
},
{
"code": null,
"e": 26375,
"s": 26367,
"text": "Output:"
},
{
"code": null,
"e": 26393,
"s": 26375,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26400,
"s": 26393,
"text": "Python"
},
{
"code": null,
"e": 26498,
"s": 26400,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26507,
"s": 26498,
"text": "Comments"
},
{
"code": null,
"e": 26520,
"s": 26507,
"text": "Old Comments"
},
{
"code": null,
"e": 26555,
"s": 26520,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26577,
"s": 26555,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26609,
"s": 26577,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26639,
"s": 26609,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26681,
"s": 26639,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26707,
"s": 26681,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26744,
"s": 26707,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26787,
"s": 26744,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26831,
"s": 26787,
"text": "Reading and Writing to text files in Python"
}
] |
Conway's Game Of Life (Python Implementation) - GeeksforGeeks
|
09 Nov, 2021
Conways’s Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc..
The “game” is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves, or, for advanced “players”, by creating patterns with particular properties.How the game works Because the Game of Life is built on a grid of nine squares, every cell has eight neighboring cells,as shown in the given figure. A given cell (i, j) in the simulation is accessed on a grid [i][j], where i and j are the row and column indices, respectively. The value of a given cell at a given instant of time depends on the state of its neighbors at the previous time step. Conway’s Game of Life has four rules.
If a cell is ON and has fewer than two neighbors that are ON, it turns OFFIf a cell is ON and has either two or three neighbors that are ON, it remains ON.If a cell is ON and has more than three neighbors that are ON, it turns OFF.If a cell is OFF and has exactly three neighbors that are ON, it turns ON.
If a cell is ON and has fewer than two neighbors that are ON, it turns OFF
If a cell is ON and has either two or three neighbors that are ON, it remains ON.
If a cell is ON and has more than three neighbors that are ON, it turns OFF.
If a cell is OFF and has exactly three neighbors that are ON, it turns ON.
So since we know how it works, the next thing we need to figure it out that how to make it work.Approach
1. Initialize the cells in the grid.
2. At each time step in the simulation, for each
cell (i, j) in the grid, do the following:
a. Update the value of cell (i, j) based on
its neighbors, taking into account the
boundary conditions.
b. Update the display of grid values.
After we done here lets get our hands on code.Requirements
numpymatplotlibargparsepygame
numpy
matplotlib
argparse
pygame
Now lets get it startedThe Code
Python3
# Python code to implement Conway's Game Of Lifeimport argparseimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animation # setting up the values for the gridON = 255OFF = 0vals = [ON, OFF] def randomGrid(N): """returns a grid of NxN random values""" return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N) def addGlider(i, j, grid): """adds a glider with top left cell at (i, j)""" glider = np.array([[0, 0, 255], [255, 0, 255], [0, 255, 255]]) grid[i:i+3, j:j+3] = glider def addGosperGliderGun(i, j, grid): """adds a Gosper Glider Gun with top left cell at (i, j)""" gun = np.zeros(11*38).reshape(11, 38) gun[5][1] = gun[5][2] = 255 gun[6][1] = gun[6][2] = 255 gun[3][13] = gun[3][14] = 255 gun[4][12] = gun[4][16] = 255 gun[5][11] = gun[5][17] = 255 gun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = 255 gun[7][11] = gun[7][17] = 255 gun[8][12] = gun[8][16] = 255 gun[9][13] = gun[9][14] = 255 gun[1][25] = 255 gun[2][23] = gun[2][25] = 255 gun[3][21] = gun[3][22] = 255 gun[4][21] = gun[4][22] = 255 gun[5][21] = gun[5][22] = 255 gun[6][23] = gun[6][25] = 255 gun[7][25] = 255 gun[3][35] = gun[3][36] = 255 gun[4][35] = gun[4][36] = 255 grid[i:i+11, j:j+38] = gun def update(frameNum, img, grid, N): # copy grid since we require 8 neighbors # for calculation and we go line by line newGrid = grid.copy() for i in range(N): for j in range(N): # compute 8-neighbor sum # using toroidal boundary conditions - x and y wrap around # so that the simulaton takes place on a toroidal surface. total = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] + grid[(i-1)%N, j] + grid[(i+1)%N, j] + grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] + grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255) # apply Conway's rules if grid[i, j] == ON: if (total < 2) or (total > 3): newGrid[i, j] = OFF else: if total == 3: newGrid[i, j] = ON # update data img.set_data(newGrid) grid[:] = newGrid[:] return img, # main() functiondef main(): # Command line args are in sys.argv[1], sys.argv[2] .. # sys.argv[0] is the script name itself and can be ignored # parse arguments parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.") # add arguments parser.add_argument('--grid-size', dest='N', required=False) parser.add_argument('--mov-file', dest='movfile', required=False) parser.add_argument('--interval', dest='interval', required=False) parser.add_argument('--glider', action='store_true', required=False) parser.add_argument('--gosper', action='store_true', required=False) args = parser.parse_args() # set grid size N = 100 if args.N and int(args.N) > 8: N = int(args.N) # set animation update interval updateInterval = 50 if args.interval: updateInterval = int(args.interval) # declare grid grid = np.array([]) # check if "glider" demo flag is specified if args.glider: grid = np.zeros(N*N).reshape(N, N) addGlider(1, 1, grid) elif args.gosper: grid = np.zeros(N*N).reshape(N, N) addGosperGliderGun(10, 10, grid) else: # populate grid with random on/off - # more off than on grid = randomGrid(N) # set up animation fig, ax = plt.subplots() img = ax.imshow(grid, interpolation='nearest') ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, ), frames = 10, interval=updateInterval, save_count=50) # # of frames? # set output file if args.movfile: ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264']) plt.show() # call mainif __name__ == '__main__': main()
Without passing any command line arguments.
Now lets turn up things a little, let’s see what happens if add updates the animation every 500 milliseconds and setting up the dimensions 32X32 and also using the initial glider pattern.
python 'filename.py' --grid-size 32 --interval 500 --glider
You can try manipulating this code to create different simulation using this.Reference Links:
Github Code for this articleBook: Python Playground: Geeky Projects for the Curious Programmerdocs-numpydocs matplotlib
Github Code for this article
Book: Python Playground: Geeky Projects for the Curious Programmer
docs-numpy
docs matplotlib
This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also 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.
ganesh_kavhar
varshagumber28
Matrix
Python
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
The Celebrity Problem
Count all possible paths from top left to bottom right of a mXn matrix
Python program to multiply two matrices
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24888,
"s": 24860,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 25093,
"s": 24888,
"text": "Conways’s Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc.. "
},
{
"code": null,
"e": 25832,
"s": 25093,
"text": "The “game” is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves, or, for advanced “players”, by creating patterns with particular properties.How the game works Because the Game of Life is built on a grid of nine squares, every cell has eight neighboring cells,as shown in the given figure. A given cell (i, j) in the simulation is accessed on a grid [i][j], where i and j are the row and column indices, respectively. The value of a given cell at a given instant of time depends on the state of its neighbors at the previous time step. Conway’s Game of Life has four rules. "
},
{
"code": null,
"e": 26138,
"s": 25832,
"text": "If a cell is ON and has fewer than two neighbors that are ON, it turns OFFIf a cell is ON and has either two or three neighbors that are ON, it remains ON.If a cell is ON and has more than three neighbors that are ON, it turns OFF.If a cell is OFF and has exactly three neighbors that are ON, it turns ON."
},
{
"code": null,
"e": 26213,
"s": 26138,
"text": "If a cell is ON and has fewer than two neighbors that are ON, it turns OFF"
},
{
"code": null,
"e": 26295,
"s": 26213,
"text": "If a cell is ON and has either two or three neighbors that are ON, it remains ON."
},
{
"code": null,
"e": 26372,
"s": 26295,
"text": "If a cell is ON and has more than three neighbors that are ON, it turns OFF."
},
{
"code": null,
"e": 26447,
"s": 26372,
"text": "If a cell is OFF and has exactly three neighbors that are ON, it turns ON."
},
{
"code": null,
"e": 26556,
"s": 26449,
"text": "So since we know how it works, the next thing we need to figure it out that how to make it work.Approach "
},
{
"code": null,
"e": 26851,
"s": 26556,
"text": "1. Initialize the cells in the grid.\n2. At each time step in the simulation, for each \n cell (i, j) in the grid, do the following:\n a. Update the value of cell (i, j) based on \n its neighbors, taking into account the \n boundary conditions.\n b. Update the display of grid values."
},
{
"code": null,
"e": 26912,
"s": 26851,
"text": "After we done here lets get our hands on code.Requirements "
},
{
"code": null,
"e": 26942,
"s": 26912,
"text": "numpymatplotlibargparsepygame"
},
{
"code": null,
"e": 26948,
"s": 26942,
"text": "numpy"
},
{
"code": null,
"e": 26959,
"s": 26948,
"text": "matplotlib"
},
{
"code": null,
"e": 26968,
"s": 26959,
"text": "argparse"
},
{
"code": null,
"e": 26975,
"s": 26968,
"text": "pygame"
},
{
"code": null,
"e": 27008,
"s": 26975,
"text": "Now lets get it startedThe Code "
},
{
"code": null,
"e": 27016,
"s": 27008,
"text": "Python3"
},
{
"code": "# Python code to implement Conway's Game Of Lifeimport argparseimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animation # setting up the values for the gridON = 255OFF = 0vals = [ON, OFF] def randomGrid(N): \"\"\"returns a grid of NxN random values\"\"\" return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N) def addGlider(i, j, grid): \"\"\"adds a glider with top left cell at (i, j)\"\"\" glider = np.array([[0, 0, 255], [255, 0, 255], [0, 255, 255]]) grid[i:i+3, j:j+3] = glider def addGosperGliderGun(i, j, grid): \"\"\"adds a Gosper Glider Gun with top left cell at (i, j)\"\"\" gun = np.zeros(11*38).reshape(11, 38) gun[5][1] = gun[5][2] = 255 gun[6][1] = gun[6][2] = 255 gun[3][13] = gun[3][14] = 255 gun[4][12] = gun[4][16] = 255 gun[5][11] = gun[5][17] = 255 gun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = 255 gun[7][11] = gun[7][17] = 255 gun[8][12] = gun[8][16] = 255 gun[9][13] = gun[9][14] = 255 gun[1][25] = 255 gun[2][23] = gun[2][25] = 255 gun[3][21] = gun[3][22] = 255 gun[4][21] = gun[4][22] = 255 gun[5][21] = gun[5][22] = 255 gun[6][23] = gun[6][25] = 255 gun[7][25] = 255 gun[3][35] = gun[3][36] = 255 gun[4][35] = gun[4][36] = 255 grid[i:i+11, j:j+38] = gun def update(frameNum, img, grid, N): # copy grid since we require 8 neighbors # for calculation and we go line by line newGrid = grid.copy() for i in range(N): for j in range(N): # compute 8-neighbor sum # using toroidal boundary conditions - x and y wrap around # so that the simulaton takes place on a toroidal surface. total = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] + grid[(i-1)%N, j] + grid[(i+1)%N, j] + grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] + grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255) # apply Conway's rules if grid[i, j] == ON: if (total < 2) or (total > 3): newGrid[i, j] = OFF else: if total == 3: newGrid[i, j] = ON # update data img.set_data(newGrid) grid[:] = newGrid[:] return img, # main() functiondef main(): # Command line args are in sys.argv[1], sys.argv[2] .. # sys.argv[0] is the script name itself and can be ignored # parse arguments parser = argparse.ArgumentParser(description=\"Runs Conway's Game of Life simulation.\") # add arguments parser.add_argument('--grid-size', dest='N', required=False) parser.add_argument('--mov-file', dest='movfile', required=False) parser.add_argument('--interval', dest='interval', required=False) parser.add_argument('--glider', action='store_true', required=False) parser.add_argument('--gosper', action='store_true', required=False) args = parser.parse_args() # set grid size N = 100 if args.N and int(args.N) > 8: N = int(args.N) # set animation update interval updateInterval = 50 if args.interval: updateInterval = int(args.interval) # declare grid grid = np.array([]) # check if \"glider\" demo flag is specified if args.glider: grid = np.zeros(N*N).reshape(N, N) addGlider(1, 1, grid) elif args.gosper: grid = np.zeros(N*N).reshape(N, N) addGosperGliderGun(10, 10, grid) else: # populate grid with random on/off - # more off than on grid = randomGrid(N) # set up animation fig, ax = plt.subplots() img = ax.imshow(grid, interpolation='nearest') ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, ), frames = 10, interval=updateInterval, save_count=50) # # of frames? # set output file if args.movfile: ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264']) plt.show() # call mainif __name__ == '__main__': main()",
"e": 31126,
"s": 27016,
"text": null
},
{
"code": null,
"e": 31172,
"s": 31126,
"text": "Without passing any command line arguments. "
},
{
"code": null,
"e": 31361,
"s": 31172,
"text": "Now lets turn up things a little, let’s see what happens if add updates the animation every 500 milliseconds and setting up the dimensions 32X32 and also using the initial glider pattern. "
},
{
"code": null,
"e": 31421,
"s": 31361,
"text": "python 'filename.py' --grid-size 32 --interval 500 --glider"
},
{
"code": null,
"e": 31519,
"s": 31423,
"text": "You can try manipulating this code to create different simulation using this.Reference Links: "
},
{
"code": null,
"e": 31639,
"s": 31519,
"text": "Github Code for this articleBook: Python Playground: Geeky Projects for the Curious Programmerdocs-numpydocs matplotlib"
},
{
"code": null,
"e": 31668,
"s": 31639,
"text": "Github Code for this article"
},
{
"code": null,
"e": 31735,
"s": 31668,
"text": "Book: Python Playground: Geeky Projects for the Curious Programmer"
},
{
"code": null,
"e": 31746,
"s": 31735,
"text": "docs-numpy"
},
{
"code": null,
"e": 31762,
"s": 31746,
"text": "docs matplotlib"
},
{
"code": null,
"e": 32134,
"s": 31762,
"text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32148,
"s": 32134,
"text": "ganesh_kavhar"
},
{
"code": null,
"e": 32163,
"s": 32148,
"text": "varshagumber28"
},
{
"code": null,
"e": 32170,
"s": 32163,
"text": "Matrix"
},
{
"code": null,
"e": 32177,
"s": 32170,
"text": "Python"
},
{
"code": null,
"e": 32184,
"s": 32177,
"text": "Matrix"
},
{
"code": null,
"e": 32282,
"s": 32184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32291,
"s": 32282,
"text": "Comments"
},
{
"code": null,
"e": 32304,
"s": 32291,
"text": "Old Comments"
},
{
"code": null,
"e": 32366,
"s": 32304,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 32399,
"s": 32366,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32421,
"s": 32399,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 32492,
"s": 32421,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 32532,
"s": 32492,
"text": "Python program to multiply two matrices"
},
{
"code": null,
"e": 32560,
"s": 32532,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 32610,
"s": 32560,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32632,
"s": 32610,
"text": "Python map() function"
}
] |
Ethereum - Interacting with Deployed Contract
|
Now, you are ready to interact with the contract that you have deployed. Go back to MyEtherWallet desktop and click on the “Interact with Contract” tab as shown in the screenshot below −
Paste the contract address that you previously copied in the “Contract Address” field. You also need to paste the “ABI / JSON Interface” of the contract on the above screen.
To get the ABI, go to the Remix window and click on the ABI button as shown in the screenshot below.
The ABI / JSON interface will be copied to the clipboard. Paste this in your favorite editor to examine the generated interface, which is shown below −
ABI / JSON Interface
[
{
"constant": false,
"inputs": [
{
"name": "newDeposit",
"type": "uint256"
}
],
"name": "send",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"name": "initialAmount",
"type": "uint256"
},
{
"name": "initialValue",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": true,
"inputs": [],
"name": "getAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getBalance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
After you paste this JSON in the MyEtherWallet interface, you will notice that the ACCESS button below the JSON interface is now activated, as shown below −
Click Access button to access the contract.
Upon clicking the Access button, the contract address and function selection dropdown will appear on the screen like in the Remix editor. This is shown in the screenshot below −
You may check the various functions of the contract as in the case of Remix deployment. Note that the contact is now deployed on an external Ganache Blockchain. Check the getAmount function; you will get the Amount value of zero and the getBalance will show a balance of 1000.
Now try sending some money. It will present you a textedit control for entering the amount. When you write the contract, some “gas” would be used and you will be asked to confirm the transaction before writing it to the Blockchain. The transaction would be executed in a short while depending on the mining timing set by you on the Ganache server. After this, you can reexamine the value and the amount fields of the contract to verify that these are indeed modified.
You may now examine the Ganache desktop to view the transactions that you have performed so far. A sample output is shown below −
So far, you were both the contract creator and the contract executor. This does not make much sense, as you expect others to use your contract. For this, we will create another client for our Ganache Blockchain and send some money from the newly created account # 2 to the contract creator at account # 1.
38 Lectures
4.5 hours
Abhilash Nelson
53 Lectures
9.5 hours
Frahaan Hussain
62 Lectures
8.5 hours
Frahaan Hussain
103 Lectures
9.5 hours
Total Seminars
31 Lectures
3.5 hours
Swapnil Kole
64 Lectures
12.5 hours
Blockchain Post
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2350,
"s": 2163,
"text": "Now, you are ready to interact with the contract that you have deployed. Go back to MyEtherWallet desktop and click on the “Interact with Contract” tab as shown in the screenshot below −"
},
{
"code": null,
"e": 2524,
"s": 2350,
"text": "Paste the contract address that you previously copied in the “Contract Address” field. You also need to paste the “ABI / JSON Interface” of the contract on the above screen."
},
{
"code": null,
"e": 2625,
"s": 2524,
"text": "To get the ABI, go to the Remix window and click on the ABI button as shown in the screenshot below."
},
{
"code": null,
"e": 2777,
"s": 2625,
"text": "The ABI / JSON interface will be copied to the clipboard. Paste this in your favorite editor to examine the generated interface, which is shown below −"
},
{
"code": null,
"e": 3925,
"s": 2777,
"text": "ABI / JSON Interface\n[\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"newDeposit\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"send\",\n \"outputs\": [],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"name\": \"initialAmount\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"initialValue\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"getAmount\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"getBalance\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]"
},
{
"code": null,
"e": 4082,
"s": 3925,
"text": "After you paste this JSON in the MyEtherWallet interface, you will notice that the ACCESS button below the JSON interface is now activated, as shown below −"
},
{
"code": null,
"e": 4126,
"s": 4082,
"text": "Click Access button to access the contract."
},
{
"code": null,
"e": 4304,
"s": 4126,
"text": "Upon clicking the Access button, the contract address and function selection dropdown will appear on the screen like in the Remix editor. This is shown in the screenshot below −"
},
{
"code": null,
"e": 4581,
"s": 4304,
"text": "You may check the various functions of the contract as in the case of Remix deployment. Note that the contact is now deployed on an external Ganache Blockchain. Check the getAmount function; you will get the Amount value of zero and the getBalance will show a balance of 1000."
},
{
"code": null,
"e": 5049,
"s": 4581,
"text": "Now try sending some money. It will present you a textedit control for entering the amount. When you write the contract, some “gas” would be used and you will be asked to confirm the transaction before writing it to the Blockchain. The transaction would be executed in a short while depending on the mining timing set by you on the Ganache server. After this, you can reexamine the value and the amount fields of the contract to verify that these are indeed modified."
},
{
"code": null,
"e": 5179,
"s": 5049,
"text": "You may now examine the Ganache desktop to view the transactions that you have performed so far. A sample output is shown below −"
},
{
"code": null,
"e": 5485,
"s": 5179,
"text": "So far, you were both the contract creator and the contract executor. This does not make much sense, as you expect others to use your contract. For this, we will create another client for our Ganache Blockchain and send some money from the newly created account # 2 to the contract creator at account # 1."
},
{
"code": null,
"e": 5520,
"s": 5485,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5537,
"s": 5520,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5572,
"s": 5537,
"text": "\n 53 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5589,
"s": 5572,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5624,
"s": 5589,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5641,
"s": 5624,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5677,
"s": 5641,
"text": "\n 103 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5693,
"s": 5677,
"text": " Total Seminars"
},
{
"code": null,
"e": 5728,
"s": 5693,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5742,
"s": 5728,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 5778,
"s": 5742,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5795,
"s": 5778,
"text": " Blockchain Post"
},
{
"code": null,
"e": 5802,
"s": 5795,
"text": " Print"
},
{
"code": null,
"e": 5813,
"s": 5802,
"text": " Add Notes"
}
] |
Haskell - Input & Output
|
All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell.
We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file.
Let us create a file and name it "abc.txt". Next, enter the following lines in this text file: "Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell."
Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character.
main = do
let file = "abc.txt"
contents <- readFile file
putStrLn contents
The above piece of code will read the file "abc.txt" as a String until it encounters any End of File character. This piece of code will generate the following output.
Welcome to Tutorialspoint
Here, you will get the best resource to learn Haskell.
Observe that whatever it is printing on the terminal is written in that file.
Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type "ghci". Then, type the following set of commands −
let file = "abc.txt"
writeFile file "I am just experimenting here."
readFile file
Here, we have created a text file called "abc.txt". Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output −
I am just experimenting here.
An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling.
If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors.
The function definition of try looks like "try :: Exception e => IO a -> IO (Either e a)". Take a look at the following example code. It shows how you can catch the "Divide by Zero" exception.
import Control.Exception
main = do
result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int)
case result of
Left ex -> putStrLn $ "Caught exception: " ++ show ex
Right val -> putStrLn $ "The answer was: " ++ show val
In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen.
Caught exception: divide by zero
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2127,
"s": 1915,
"text": "All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell."
},
{
"code": null,
"e": 2304,
"s": 2127,
"text": "We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file."
},
{
"code": null,
"e": 2483,
"s": 2304,
"text": "Let us create a file and name it \"abc.txt\". Next, enter the following lines in this text file: \"Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell.\""
},
{
"code": null,
"e": 2678,
"s": 2483,
"text": "Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character."
},
{
"code": null,
"e": 2769,
"s": 2678,
"text": "main = do \n let file = \"abc.txt\" \n contents <- readFile file \n putStrLn contents "
},
{
"code": null,
"e": 2937,
"s": 2769,
"text": "The above piece of code will read the file \"abc.txt\" as a String until it encounters any End of File character. This piece of code will generate the following output."
},
{
"code": null,
"e": 3019,
"s": 2937,
"text": "Welcome to Tutorialspoint\nHere, you will get the best resource to learn Haskell.\n"
},
{
"code": null,
"e": 3097,
"s": 3019,
"text": "Observe that whatever it is printing on the terminal is written in that file."
},
{
"code": null,
"e": 3270,
"s": 3097,
"text": "Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type \"ghci\". Then, type the following set of commands −"
},
{
"code": null,
"e": 3356,
"s": 3270,
"text": "let file = \"abc.txt\" \nwriteFile file \"I am just experimenting here.\" \nreadFile file \n"
},
{
"code": null,
"e": 3622,
"s": 3356,
"text": "Here, we have created a text file called \"abc.txt\". Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output −"
},
{
"code": null,
"e": 3653,
"s": 3622,
"text": "I am just experimenting here.\n"
},
{
"code": null,
"e": 3886,
"s": 3653,
"text": "An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling."
},
{
"code": null,
"e": 4096,
"s": 3886,
"text": "If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors."
},
{
"code": null,
"e": 4289,
"s": 4096,
"text": "The function definition of try looks like \"try :: Exception e => IO a -> IO (Either e a)\". Take a look at the following example code. It shows how you can catch the \"Divide by Zero\" exception."
},
{
"code": null,
"e": 4545,
"s": 4289,
"text": "import Control.Exception \n\nmain = do \n result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int) \n case result of \n Left ex -> putStrLn $ \"Caught exception: \" ++ show ex \n Right val -> putStrLn $ \"The answer was: \" ++ show val "
},
{
"code": null,
"e": 4745,
"s": 4545,
"text": "In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen."
},
{
"code": null,
"e": 4780,
"s": 4745,
"text": "Caught exception: divide by zero \n"
},
{
"code": null,
"e": 4787,
"s": 4780,
"text": " Print"
},
{
"code": null,
"e": 4798,
"s": 4787,
"text": " Add Notes"
}
] |
How can I change the font family and font size with jQuery?
|
To change the font family and font size with jQuery, use the jQuery css() method. The css property font-family and font-size is used. You can try to run the following code to learn how to change font family and font size with jQuery −
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() {
$("p").on({
mouseenter: function() {
$(this).css({"font-family": "Arial, Helvetica, sans-serif", "font-size": "200%"});
}
});
});
</script>
</head>
<body>
<p>Move the mouse pointer on the text to change the font family and size.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1297,
"s": 1062,
"text": "To change the font family and font size with jQuery, use the jQuery css() method. The css property font-family and font-size is used. You can try to run the following code to learn how to change font family and font size with jQuery −"
},
{
"code": null,
"e": 1307,
"s": 1297,
"text": "Live Demo"
},
{
"code": null,
"e": 1743,
"s": 1307,
"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 $(\"p\").on({\n mouseenter: function() {\n $(this).css({\"font-family\": \"Arial, Helvetica, sans-serif\", \"font-size\": \"200%\"});\n }\n }); \n});\n</script>\n</head>\n<body>\n<p>Move the mouse pointer on the text to change the font family and size.</p>\n</body>\n</html>"
}
] |
How to calculate an average value across database rows in MySQL?
|
For this, you can use AVG(). Following is the syntax −
select avg(yourColumnName1) as anyAliasName1,
avg(yourColumnName2) as anyAliasName2,
avg(yourColumnName3) as anyAliasName3,
.
.
N
from yourTableName;
Let us create a table −
mysql> create table demo31
−> (
−> value1 int,
−> value2 int,
−> value3 int
−> );
Query OK, 0 rows affected (2.27 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo31 values(34,55,67);
Query OK, 1 row affected (0.27 sec)
mysql> insert into demo31 values(50,60,70);
Query OK, 1 row affected (0.16 sec)
mysql> insert into demo31 values(100,200,300);
Query OK, 1 row affected (0.14 sec)
mysql> insert into demo31 values(10,300,200);
Query OK, 1 row affected (0.15 sec)
Display records from the table using select statement −
mysql> select *from demo31;
This will produce the following output −
+--------+--------+--------+
| value1 | value2 | value3 |
+--------+--------+--------+
| 34 | 55 | 67 |
| 50 | 60 | 70 |
| 100 | 200 | 300 |
| 10 | 300 | 200 |
+--------+--------+--------+
4 rows in set (0.00 sec)
Following is the query to calculate an average value across database rows −
mysql> select avg(value1) as Value1_AVG,
−> avg(value2) as Value2_AVG,
−> avg(value3) as Value3_AVG
−> from demo31;
This will produce the following output −
+------------+------------+------------+
| Value1_AVG | Value2_AVG | Value3_AVG |
+------------+------------+------------+
| 48.5000 | 153.7500 | 159.2500 |
+------------+------------+------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "For this, you can use AVG(). Following is the syntax −"
},
{
"code": null,
"e": 1267,
"s": 1117,
"text": "select avg(yourColumnName1) as anyAliasName1,\navg(yourColumnName2) as anyAliasName2,\navg(yourColumnName3) as anyAliasName3,\n.\n.\nN\nfrom yourTableName;"
},
{
"code": null,
"e": 1291,
"s": 1267,
"text": "Let us create a table −"
},
{
"code": null,
"e": 1410,
"s": 1291,
"text": "mysql> create table demo31\n−> (\n−> value1 int,\n−> value2 int,\n−> value3 int\n−> );\nQuery OK, 0 rows affected (2.27 sec)"
},
{
"code": null,
"e": 1479,
"s": 1410,
"text": "Insert some records into the table with the help of insert command −"
},
{
"code": null,
"e": 1807,
"s": 1479,
"text": "mysql> insert into demo31 values(34,55,67);\nQuery OK, 1 row affected (0.27 sec)\n\nmysql> insert into demo31 values(50,60,70);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into demo31 values(100,200,300);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into demo31 values(10,300,200);\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 1863,
"s": 1807,
"text": "Display records from the table using select statement −"
},
{
"code": null,
"e": 1891,
"s": 1863,
"text": "mysql> select *from demo31;"
},
{
"code": null,
"e": 1932,
"s": 1891,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2189,
"s": 1932,
"text": "+--------+--------+--------+\n| value1 | value2 | value3 |\n+--------+--------+--------+\n| 34 | 55 | 67 |\n| 50 | 60 | 70 |\n| 100 | 200 | 300 |\n| 10 | 300 | 200 |\n+--------+--------+--------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2265,
"s": 2189,
"text": "Following is the query to calculate an average value across database rows −"
},
{
"code": null,
"e": 2381,
"s": 2265,
"text": "mysql> select avg(value1) as Value1_AVG,\n−> avg(value2) as Value2_AVG,\n−> avg(value3) as Value3_AVG\n−> from demo31;"
},
{
"code": null,
"e": 2422,
"s": 2381,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2651,
"s": 2422,
"text": "+------------+------------+------------+\n| Value1_AVG | Value2_AVG | Value3_AVG |\n+------------+------------+------------+\n| 48.5000 | 153.7500 | 159.2500 |\n+------------+------------+------------+\n1 row in set (0.00 sec)"
}
] |
How to create an AI that chats like you | by Simone Guardati | Towards Data Science
|
The goal of this guide is to build a system capable of chatting like you, using your own WhatsApp and Telegram chats as an ML dataset.
What we will do could be summarized in the following steps:
Get your WhatsApp and Telegram dataParse it to build an ML-ready datasetTrain a GPT-2 modelChat with the model
Get your WhatsApp and Telegram data
Parse it to build an ML-ready dataset
Train a GPT-2 model
Chat with the model
So let’s start our adventure!
Do you want to see some results? Check the official webpage, note that they’re in Italian as they’re based on on my personal chats.
It’s always better not to run random scripts on personal information (like personal chat messages).
I guarantee there’s no catch, but you can always check the native code that’s being used: messaging-chat-parser and pistoBot, all the sources are open-source on github.
First of all, we need to gather the data from our chat applications. We will now learn how to export data from two of the most commonly used instant messaging apps: WhatsApp and Telegram.
We have to export one .txt file for each chat we want to include in the final dataset. So, as described on the official WhatsApp website:
Open your WhatsApp mobile appPick an individual chat one individual chat (e.g. a chat with one friend) > Tap “more options” (three vertical dots)Select the More voice > Export chat voiceSelect Without Media on the pop-upSelect an Email service (e.g. Gmail app) and add your e-mail address as a recipientWait to receive the mail with chat history as txt file attachmentDownload and store the txt attachment on the computerRepeat those steps for every individual chat you want to include
Open your WhatsApp mobile app
Pick an individual chat one individual chat (e.g. a chat with one friend) > Tap “more options” (three vertical dots)
Select the More voice > Export chat voice
Select Without Media on the pop-up
Select an Email service (e.g. Gmail app) and add your e-mail address as a recipient
Wait to receive the mail with chat history as txt file attachment
Download and store the txt attachment on the computer
Repeat those steps for every individual chat you want to include
Note that only 1 to 1 chats are allowed (namely individual), we suggest to export chats with the highest number of messages, in order to achieve a bigger dataset and get better final results.
Now you should have more files, each with a structure that looks like the snippet below:
12/12/19, 02:09 — <FriendName>: bla bla bla bla12/12/19, 08:40 — <YourName>: bla bla bla bla
Take note of the text you find under <YourName> placeholder in your exported chats. This parameter is your name for the WhatsApp app and we will use this value later.
The process here will be faster than WhatsApp because Telegram will export everything in a single .json file, without having the limit of exporting one chat at a time.
So, as described on the official Telegram website:
Open the Telegram Desktop appOpen the menu on the upper left screen (three horizontal lines)Go to settings voice > Click on Advanced >Select Export Telegram dataOnly these fields should be selected: Account information, Contact list, Personal chats, Machine-readable JSONBe sure nothing is selected under Media export settings and set the size limit to the maximumLaunch the export and waitRename the output file as “telegram_dump.json”
Open the Telegram Desktop app
Open the menu on the upper left screen (three horizontal lines)
Go to settings voice > Click on Advanced >Select Export Telegram data
Only these fields should be selected: Account information, Contact list, Personal chats, Machine-readable JSON
Be sure nothing is selected under Media export settings and set the size limit to the maximum
Launch the export and wait
Rename the output file as “telegram_dump.json”
Now you should have one file named telegram_dump.json with this structure:
{ "about": "Here is ...", "personal_information": { "user_id": 123456789, "first_name": "your_name_here", "last_name": "", ....
To train a GPT-2 neural network, first of all we need to pre-process the data, in order to obtain a single .txt with a machine-learning compatible structure.
For the sake of simplicity and since the ML model we will use requires a GPU to work, we are going to use Google Colab for the next step.
If you don’t know what Google Colab is, check this other article:
towardsdatascience.com
Open this Colab notebook and follow these steps:
Run the first block of cells called under the “0️⃣ Init” chapterPress “Run Anyway” on the pop-upMake sure that the first command !nvidia-smi shows that a GPU is connected (p100 is suggested)If no GPU is connected, go to Runtime > Change Runtime type > Hardware accelerator > GPU
Run the first block of cells called under the “0️⃣ Init” chapter
Press “Run Anyway” on the pop-up
Make sure that the first command !nvidia-smi shows that a GPU is connected (p100 is suggested)
If no GPU is connected, go to Runtime > Change Runtime type > Hardware accelerator > GPU
To work with the data, we need to upload them on Colab, into the right folders.
WhatsApp chatsSelect all your .txt files and upload everything into the following notebook folder:./messaging-chat-parser/data/chat_raw/whatsapp/
Telegram JSONGet the file telegram_dump.json and upload it into the following notebook folder:./messaging-chat-parser/data/chat_raw/telegram/
Now, run all the cells up until the block “2️⃣ Parse the data”.
Here we need to replace the variable “whatsapp_user_name” with your WhatsApp name, called <YourName> on the 1.1 chapter.
You can also change the date format parsing system if some of the exported data show a different format due to local time formatting.
So, for example, if my name is “Bob” and I’m from America, the code I should use is the following:
Now execute the cell under the “3️⃣ Train a GTP2 model” notebook chapter, it will run a new training using your provided data.
A progress bar will be shown, and the training could take up to 10 hours, it depends mostly on which GPU type Colab is running and how many much messages were provided.
Wait until the process ends.
After the training is completed, run all the remaining notebook cells: the last one will show a text block with a ✍ symbol on the left.
You could use this text box to insert the messages you want to “send” to the ML model. So write your message and then press enter.
After the first message is sent, the system will prompt some information about the conversation.
You will now see the most interesting results as a list of messages:
Messages starting with the tag [others]:The ones you have sent to the model
Messages starting with the tag [me]:The ones generated by the model.
After the replied message is generated, you could continue to chat for a total of 5 messages. After this, you could re-run the cell to start a new conversation with the model.
So in this guide we have seen how simple it is to train your GPT-2 model from scratch, the task is simple (but not trivial!) only thanks to to aitextgen package that runs under the pistoBot hood.
Note that if your chat messages are in English you could easily obtain better results than the ones we got with this standard approach, since you could use the transfer learning from a GPT-2 pretrained model.
The pistoBot repository allows you to train (or fine-tune) different models, including the chance to start from a GPT-2 pretrained model: check the repository folder for more information.
We have chosen the standard, un-trained GPT-2 model so that even the non-english users could use this AI.
Some rights reserved
|
[
{
"code": null,
"e": 307,
"s": 172,
"text": "The goal of this guide is to build a system capable of chatting like you, using your own WhatsApp and Telegram chats as an ML dataset."
},
{
"code": null,
"e": 367,
"s": 307,
"text": "What we will do could be summarized in the following steps:"
},
{
"code": null,
"e": 478,
"s": 367,
"text": "Get your WhatsApp and Telegram dataParse it to build an ML-ready datasetTrain a GPT-2 modelChat with the model"
},
{
"code": null,
"e": 514,
"s": 478,
"text": "Get your WhatsApp and Telegram data"
},
{
"code": null,
"e": 552,
"s": 514,
"text": "Parse it to build an ML-ready dataset"
},
{
"code": null,
"e": 572,
"s": 552,
"text": "Train a GPT-2 model"
},
{
"code": null,
"e": 592,
"s": 572,
"text": "Chat with the model"
},
{
"code": null,
"e": 622,
"s": 592,
"text": "So let’s start our adventure!"
},
{
"code": null,
"e": 754,
"s": 622,
"text": "Do you want to see some results? Check the official webpage, note that they’re in Italian as they’re based on on my personal chats."
},
{
"code": null,
"e": 854,
"s": 754,
"text": "It’s always better not to run random scripts on personal information (like personal chat messages)."
},
{
"code": null,
"e": 1023,
"s": 854,
"text": "I guarantee there’s no catch, but you can always check the native code that’s being used: messaging-chat-parser and pistoBot, all the sources are open-source on github."
},
{
"code": null,
"e": 1211,
"s": 1023,
"text": "First of all, we need to gather the data from our chat applications. We will now learn how to export data from two of the most commonly used instant messaging apps: WhatsApp and Telegram."
},
{
"code": null,
"e": 1349,
"s": 1211,
"text": "We have to export one .txt file for each chat we want to include in the final dataset. So, as described on the official WhatsApp website:"
},
{
"code": null,
"e": 1835,
"s": 1349,
"text": "Open your WhatsApp mobile appPick an individual chat one individual chat (e.g. a chat with one friend) > Tap “more options” (three vertical dots)Select the More voice > Export chat voiceSelect Without Media on the pop-upSelect an Email service (e.g. Gmail app) and add your e-mail address as a recipientWait to receive the mail with chat history as txt file attachmentDownload and store the txt attachment on the computerRepeat those steps for every individual chat you want to include"
},
{
"code": null,
"e": 1865,
"s": 1835,
"text": "Open your WhatsApp mobile app"
},
{
"code": null,
"e": 1982,
"s": 1865,
"text": "Pick an individual chat one individual chat (e.g. a chat with one friend) > Tap “more options” (three vertical dots)"
},
{
"code": null,
"e": 2024,
"s": 1982,
"text": "Select the More voice > Export chat voice"
},
{
"code": null,
"e": 2059,
"s": 2024,
"text": "Select Without Media on the pop-up"
},
{
"code": null,
"e": 2143,
"s": 2059,
"text": "Select an Email service (e.g. Gmail app) and add your e-mail address as a recipient"
},
{
"code": null,
"e": 2209,
"s": 2143,
"text": "Wait to receive the mail with chat history as txt file attachment"
},
{
"code": null,
"e": 2263,
"s": 2209,
"text": "Download and store the txt attachment on the computer"
},
{
"code": null,
"e": 2328,
"s": 2263,
"text": "Repeat those steps for every individual chat you want to include"
},
{
"code": null,
"e": 2520,
"s": 2328,
"text": "Note that only 1 to 1 chats are allowed (namely individual), we suggest to export chats with the highest number of messages, in order to achieve a bigger dataset and get better final results."
},
{
"code": null,
"e": 2609,
"s": 2520,
"text": "Now you should have more files, each with a structure that looks like the snippet below:"
},
{
"code": null,
"e": 2702,
"s": 2609,
"text": "12/12/19, 02:09 — <FriendName>: bla bla bla bla12/12/19, 08:40 — <YourName>: bla bla bla bla"
},
{
"code": null,
"e": 2869,
"s": 2702,
"text": "Take note of the text you find under <YourName> placeholder in your exported chats. This parameter is your name for the WhatsApp app and we will use this value later."
},
{
"code": null,
"e": 3037,
"s": 2869,
"text": "The process here will be faster than WhatsApp because Telegram will export everything in a single .json file, without having the limit of exporting one chat at a time."
},
{
"code": null,
"e": 3088,
"s": 3037,
"text": "So, as described on the official Telegram website:"
},
{
"code": null,
"e": 3525,
"s": 3088,
"text": "Open the Telegram Desktop appOpen the menu on the upper left screen (three horizontal lines)Go to settings voice > Click on Advanced >Select Export Telegram dataOnly these fields should be selected: Account information, Contact list, Personal chats, Machine-readable JSONBe sure nothing is selected under Media export settings and set the size limit to the maximumLaunch the export and waitRename the output file as “telegram_dump.json”"
},
{
"code": null,
"e": 3555,
"s": 3525,
"text": "Open the Telegram Desktop app"
},
{
"code": null,
"e": 3619,
"s": 3555,
"text": "Open the menu on the upper left screen (three horizontal lines)"
},
{
"code": null,
"e": 3689,
"s": 3619,
"text": "Go to settings voice > Click on Advanced >Select Export Telegram data"
},
{
"code": null,
"e": 3800,
"s": 3689,
"text": "Only these fields should be selected: Account information, Contact list, Personal chats, Machine-readable JSON"
},
{
"code": null,
"e": 3894,
"s": 3800,
"text": "Be sure nothing is selected under Media export settings and set the size limit to the maximum"
},
{
"code": null,
"e": 3921,
"s": 3894,
"text": "Launch the export and wait"
},
{
"code": null,
"e": 3968,
"s": 3921,
"text": "Rename the output file as “telegram_dump.json”"
},
{
"code": null,
"e": 4043,
"s": 3968,
"text": "Now you should have one file named telegram_dump.json with this structure:"
},
{
"code": null,
"e": 4171,
"s": 4043,
"text": "{ \"about\": \"Here is ...\", \"personal_information\": { \"user_id\": 123456789, \"first_name\": \"your_name_here\", \"last_name\": \"\", ...."
},
{
"code": null,
"e": 4329,
"s": 4171,
"text": "To train a GPT-2 neural network, first of all we need to pre-process the data, in order to obtain a single .txt with a machine-learning compatible structure."
},
{
"code": null,
"e": 4467,
"s": 4329,
"text": "For the sake of simplicity and since the ML model we will use requires a GPU to work, we are going to use Google Colab for the next step."
},
{
"code": null,
"e": 4533,
"s": 4467,
"text": "If you don’t know what Google Colab is, check this other article:"
},
{
"code": null,
"e": 4556,
"s": 4533,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4605,
"s": 4556,
"text": "Open this Colab notebook and follow these steps:"
},
{
"code": null,
"e": 4884,
"s": 4605,
"text": "Run the first block of cells called under the “0️⃣ Init” chapterPress “Run Anyway” on the pop-upMake sure that the first command !nvidia-smi shows that a GPU is connected (p100 is suggested)If no GPU is connected, go to Runtime > Change Runtime type > Hardware accelerator > GPU"
},
{
"code": null,
"e": 4949,
"s": 4884,
"text": "Run the first block of cells called under the “0️⃣ Init” chapter"
},
{
"code": null,
"e": 4982,
"s": 4949,
"text": "Press “Run Anyway” on the pop-up"
},
{
"code": null,
"e": 5077,
"s": 4982,
"text": "Make sure that the first command !nvidia-smi shows that a GPU is connected (p100 is suggested)"
},
{
"code": null,
"e": 5166,
"s": 5077,
"text": "If no GPU is connected, go to Runtime > Change Runtime type > Hardware accelerator > GPU"
},
{
"code": null,
"e": 5246,
"s": 5166,
"text": "To work with the data, we need to upload them on Colab, into the right folders."
},
{
"code": null,
"e": 5392,
"s": 5246,
"text": "WhatsApp chatsSelect all your .txt files and upload everything into the following notebook folder:./messaging-chat-parser/data/chat_raw/whatsapp/"
},
{
"code": null,
"e": 5534,
"s": 5392,
"text": "Telegram JSONGet the file telegram_dump.json and upload it into the following notebook folder:./messaging-chat-parser/data/chat_raw/telegram/"
},
{
"code": null,
"e": 5598,
"s": 5534,
"text": "Now, run all the cells up until the block “2️⃣ Parse the data”."
},
{
"code": null,
"e": 5719,
"s": 5598,
"text": "Here we need to replace the variable “whatsapp_user_name” with your WhatsApp name, called <YourName> on the 1.1 chapter."
},
{
"code": null,
"e": 5853,
"s": 5719,
"text": "You can also change the date format parsing system if some of the exported data show a different format due to local time formatting."
},
{
"code": null,
"e": 5952,
"s": 5853,
"text": "So, for example, if my name is “Bob” and I’m from America, the code I should use is the following:"
},
{
"code": null,
"e": 6079,
"s": 5952,
"text": "Now execute the cell under the “3️⃣ Train a GTP2 model” notebook chapter, it will run a new training using your provided data."
},
{
"code": null,
"e": 6248,
"s": 6079,
"text": "A progress bar will be shown, and the training could take up to 10 hours, it depends mostly on which GPU type Colab is running and how many much messages were provided."
},
{
"code": null,
"e": 6277,
"s": 6248,
"text": "Wait until the process ends."
},
{
"code": null,
"e": 6413,
"s": 6277,
"text": "After the training is completed, run all the remaining notebook cells: the last one will show a text block with a ✍ symbol on the left."
},
{
"code": null,
"e": 6544,
"s": 6413,
"text": "You could use this text box to insert the messages you want to “send” to the ML model. So write your message and then press enter."
},
{
"code": null,
"e": 6641,
"s": 6544,
"text": "After the first message is sent, the system will prompt some information about the conversation."
},
{
"code": null,
"e": 6710,
"s": 6641,
"text": "You will now see the most interesting results as a list of messages:"
},
{
"code": null,
"e": 6786,
"s": 6710,
"text": "Messages starting with the tag [others]:The ones you have sent to the model"
},
{
"code": null,
"e": 6855,
"s": 6786,
"text": "Messages starting with the tag [me]:The ones generated by the model."
},
{
"code": null,
"e": 7031,
"s": 6855,
"text": "After the replied message is generated, you could continue to chat for a total of 5 messages. After this, you could re-run the cell to start a new conversation with the model."
},
{
"code": null,
"e": 7227,
"s": 7031,
"text": "So in this guide we have seen how simple it is to train your GPT-2 model from scratch, the task is simple (but not trivial!) only thanks to to aitextgen package that runs under the pistoBot hood."
},
{
"code": null,
"e": 7436,
"s": 7227,
"text": "Note that if your chat messages are in English you could easily obtain better results than the ones we got with this standard approach, since you could use the transfer learning from a GPT-2 pretrained model."
},
{
"code": null,
"e": 7624,
"s": 7436,
"text": "The pistoBot repository allows you to train (or fine-tune) different models, including the chance to start from a GPT-2 pretrained model: check the repository folder for more information."
},
{
"code": null,
"e": 7730,
"s": 7624,
"text": "We have chosen the standard, un-trained GPT-2 model so that even the non-english users could use this AI."
}
] |
KeyValue Class in JavaTuples - GeeksforGeeks
|
05 Aug, 2021
A KeyValue is a Tuple from JavaTuples library that deals with only 2 elements – a key and a value. Since this KeyValue is a generic class, it can hold any type of value in it.
Since KeyValue is a Tuple, hence it also has all the characteristics of JavaTuples:
They are Typesafe
They are Immutable
They are Iterable
They are Serializable
They are Comparable (implements Comparable<Tuple>)
They implement equals() and hashCode()
They also implement toString()
public final class KeyValue<A, B> extends Tuple
implements IValueKey<A>, IValueValue<B>
Object
↳ org.javatuples.Tuple
↳ org.javatuples.KeyValue<A, B>
From Constructor:Syntax:
KeyValue<A, B> kv = new KeyValue<A, B>(value1, value2);
Example:
Java
// Below is a Java program to create// a KeyValue tuple from Constructor import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = new KeyValue<Integer, String>(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(kv); }}
Output:
[1, GeeksforGeeks]
Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax:
KeyValue<type1, type2> kv = KeyValue.with(value1, value2);
Example:
Java
// Below is a Java program to create// a KeyValue tuple from with() method import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(kv); }}
Output:
[1, GeeksforGeeks]
From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax:
KeyValue<type1, type2> kv = KeyValue.fromCollection(collectionWith_2_value);
KeyValue<type1, type2> kv = KeyValue.fromArray(arrayWith_2_value);
Example:
Java
// Below is a Java program to create// a KeyValue tuple from Collection import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating KeyValue from List List<String> list = new ArrayList<String>(); list.add("GeeksforGeeks"); list.add("A computer portal"); KeyValue<String, String> kv = KeyValue.fromCollection(list); // Creating KeyValue from Array String[] arr = { "GeeksforGeeks", "A computer portal" }; KeyValue<String, String> otherKeyValue = KeyValue.fromArray(arr); System.out.println(kv); System.out.println(otherKeyValue); }}
Output:
[GeeksforGeeks, A computer portal]
[GeeksforGeeks, A computer portal]
The getValue() and getKey() methods can be used to fetch the value and key respectively in a KeyValue Tuple.
getKey():Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
type2 val1 = kv.getKey();
Example:
Java
// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(kv.getKey()); }}
Output:
1
getValue():Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
type2 val1 = kv.getValue();
Example:
Java
// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(kv.getValue()); }}
Output:
GeeksforGeeks
Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setKey(value) and setValue(value) which creates a copy of the KeyValue with a new value according to method used, and returns a new KeyValue object.
setKey():Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
KeyValue<type1, type2> kvNew = kv.setKey(valueNew);
Example:
Java
// Below is a Java program to set// a KeyValue Key import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); KeyValue<Integer, String> otherKeyValue = kv.setKey(10); System.out.println(otherKeyValue); }}
Output:
[10, GeeksforGeeks]
setValue():Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
KeyValue<type1, type2> kvNew = kv.setValue(valueNew);
Example:
Java
// Below is a Java program to set// a KeyValue Value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); KeyValue<Integer, String> otherKeyValue = kv.setValue("A computer science portal"); System.out.println(otherKeyValue); }}
Output:
[1, A computer science portal]
An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not.
Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
boolean res = kv.contains(value2);
Example:
Java
// Below is a Java program to search// a value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); // Using contains for True result boolean exist = kv.contains("GeeksforGeeks"); // Using contains for False result boolean exist1 = kv.contains(4); System.out.println(exist); System.out.println(exist1); }}
Output:
true
false
Since KeyValue implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays.
Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
for (Object item : kv) {
...
}
Example:
Java
// Below is a Java program to iterate// a KeyValue import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "GeeksforGeeks"); for (Object item : kv) System.out.println(item); }}
Output:
1
GeeksforGeeks
kk9826225
Java-Class and Object
JavaTuples
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 24162,
"s": 24134,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 24338,
"s": 24162,
"text": "A KeyValue is a Tuple from JavaTuples library that deals with only 2 elements – a key and a value. Since this KeyValue is a generic class, it can hold any type of value in it."
},
{
"code": null,
"e": 24424,
"s": 24338,
"text": "Since KeyValue is a Tuple, hence it also has all the characteristics of JavaTuples: "
},
{
"code": null,
"e": 24442,
"s": 24424,
"text": "They are Typesafe"
},
{
"code": null,
"e": 24461,
"s": 24442,
"text": "They are Immutable"
},
{
"code": null,
"e": 24479,
"s": 24461,
"text": "They are Iterable"
},
{
"code": null,
"e": 24501,
"s": 24479,
"text": "They are Serializable"
},
{
"code": null,
"e": 24552,
"s": 24501,
"text": "They are Comparable (implements Comparable<Tuple>)"
},
{
"code": null,
"e": 24591,
"s": 24552,
"text": "They implement equals() and hashCode()"
},
{
"code": null,
"e": 24622,
"s": 24591,
"text": "They also implement toString()"
},
{
"code": null,
"e": 24722,
"s": 24622,
"text": "public final class KeyValue<A, B> extends Tuple \n implements IValueKey<A>, IValueValue<B>"
},
{
"code": null,
"e": 24792,
"s": 24722,
"text": "Object\n ↳ org.javatuples.Tuple\n ↳ org.javatuples.KeyValue<A, B>"
},
{
"code": null,
"e": 24818,
"s": 24792,
"text": "From Constructor:Syntax: "
},
{
"code": null,
"e": 24874,
"s": 24818,
"text": "KeyValue<A, B> kv = new KeyValue<A, B>(value1, value2);"
},
{
"code": null,
"e": 24884,
"s": 24874,
"text": "Example: "
},
{
"code": null,
"e": 24889,
"s": 24884,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a KeyValue tuple from Constructor import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = new KeyValue<Integer, String>(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(kv); }}",
"e": 25227,
"s": 24889,
"text": null
},
{
"code": null,
"e": 25236,
"s": 25227,
"text": "Output: "
},
{
"code": null,
"e": 25255,
"s": 25236,
"text": "[1, GeeksforGeeks]"
},
{
"code": null,
"e": 25396,
"s": 25255,
"text": "Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax: "
},
{
"code": null,
"e": 25455,
"s": 25396,
"text": "KeyValue<type1, type2> kv = KeyValue.with(value1, value2);"
},
{
"code": null,
"e": 25465,
"s": 25455,
"text": "Example: "
},
{
"code": null,
"e": 25470,
"s": 25465,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a KeyValue tuple from with() method import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(kv); }}",
"e": 25794,
"s": 25470,
"text": null
},
{
"code": null,
"e": 25803,
"s": 25794,
"text": "Output: "
},
{
"code": null,
"e": 25822,
"s": 25803,
"text": "[1, GeeksforGeeks]"
},
{
"code": null,
"e": 26121,
"s": 25822,
"text": "From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax: "
},
{
"code": null,
"e": 26265,
"s": 26121,
"text": "KeyValue<type1, type2> kv = KeyValue.fromCollection(collectionWith_2_value);\nKeyValue<type1, type2> kv = KeyValue.fromArray(arrayWith_2_value);"
},
{
"code": null,
"e": 26275,
"s": 26265,
"text": "Example: "
},
{
"code": null,
"e": 26280,
"s": 26275,
"text": "Java"
},
{
"code": "// Below is a Java program to create// a KeyValue tuple from Collection import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating KeyValue from List List<String> list = new ArrayList<String>(); list.add(\"GeeksforGeeks\"); list.add(\"A computer portal\"); KeyValue<String, String> kv = KeyValue.fromCollection(list); // Creating KeyValue from Array String[] arr = { \"GeeksforGeeks\", \"A computer portal\" }; KeyValue<String, String> otherKeyValue = KeyValue.fromArray(arr); System.out.println(kv); System.out.println(otherKeyValue); }}",
"e": 26971,
"s": 26280,
"text": null
},
{
"code": null,
"e": 26980,
"s": 26971,
"text": "Output: "
},
{
"code": null,
"e": 27050,
"s": 26980,
"text": "[GeeksforGeeks, A computer portal]\n[GeeksforGeeks, A computer portal]"
},
{
"code": null,
"e": 27160,
"s": 27050,
"text": "The getValue() and getKey() methods can be used to fetch the value and key respectively in a KeyValue Tuple. "
},
{
"code": null,
"e": 27178,
"s": 27160,
"text": "getKey():Syntax: "
},
{
"code": null,
"e": 27282,
"s": 27178,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\ntype2 val1 = kv.getKey();"
},
{
"code": null,
"e": 27292,
"s": 27282,
"text": "Example: "
},
{
"code": null,
"e": 27297,
"s": 27292,
"text": "Java"
},
{
"code": "// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(kv.getKey()); }}",
"e": 27608,
"s": 27297,
"text": null
},
{
"code": null,
"e": 27617,
"s": 27608,
"text": "Output: "
},
{
"code": null,
"e": 27619,
"s": 27617,
"text": "1"
},
{
"code": null,
"e": 27639,
"s": 27619,
"text": "getValue():Syntax: "
},
{
"code": null,
"e": 27745,
"s": 27639,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\ntype2 val1 = kv.getValue();"
},
{
"code": null,
"e": 27755,
"s": 27745,
"text": "Example: "
},
{
"code": null,
"e": 27760,
"s": 27755,
"text": "Java"
},
{
"code": "// Below is a Java program to get// a KeyValue value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(kv.getValue()); }}",
"e": 28073,
"s": 27760,
"text": null
},
{
"code": null,
"e": 28082,
"s": 28073,
"text": "Output: "
},
{
"code": null,
"e": 28096,
"s": 28082,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 28362,
"s": 28096,
"text": "Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setKey(value) and setValue(value) which creates a copy of the KeyValue with a new value according to method used, and returns a new KeyValue object."
},
{
"code": null,
"e": 28380,
"s": 28362,
"text": "setKey():Syntax: "
},
{
"code": null,
"e": 28510,
"s": 28380,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\nKeyValue<type1, type2> kvNew = kv.setKey(valueNew);"
},
{
"code": null,
"e": 28520,
"s": 28510,
"text": "Example: "
},
{
"code": null,
"e": 28525,
"s": 28520,
"text": "Java"
},
{
"code": "// Below is a Java program to set// a KeyValue Key import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); KeyValue<Integer, String> otherKeyValue = kv.setKey(10); System.out.println(otherKeyValue); }}",
"e": 28912,
"s": 28525,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28912,
"text": "Output: "
},
{
"code": null,
"e": 28941,
"s": 28921,
"text": "[10, GeeksforGeeks]"
},
{
"code": null,
"e": 28961,
"s": 28941,
"text": "setValue():Syntax: "
},
{
"code": null,
"e": 29093,
"s": 28961,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\nKeyValue<type1, type2> kvNew = kv.setValue(valueNew);"
},
{
"code": null,
"e": 29103,
"s": 29093,
"text": "Example: "
},
{
"code": null,
"e": 29108,
"s": 29103,
"text": "Java"
},
{
"code": "// Below is a Java program to set// a KeyValue Value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); KeyValue<Integer, String> otherKeyValue = kv.setValue(\"A computer science portal\"); System.out.println(otherKeyValue); }}",
"e": 29524,
"s": 29108,
"text": null
},
{
"code": null,
"e": 29533,
"s": 29524,
"text": "Output: "
},
{
"code": null,
"e": 29564,
"s": 29533,
"text": "[1, A computer science portal]"
},
{
"code": null,
"e": 29706,
"s": 29564,
"text": "An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not."
},
{
"code": null,
"e": 29714,
"s": 29706,
"text": "Syntax:"
},
{
"code": null,
"e": 29827,
"s": 29714,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\nboolean res = kv.contains(value2);"
},
{
"code": null,
"e": 29836,
"s": 29827,
"text": "Example:"
},
{
"code": null,
"e": 29841,
"s": 29836,
"text": "Java"
},
{
"code": "// Below is a Java program to search// a value import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); // Using contains for True result boolean exist = kv.contains(\"GeeksforGeeks\"); // Using contains for False result boolean exist1 = kv.contains(4); System.out.println(exist); System.out.println(exist1); }}",
"e": 30353,
"s": 29841,
"text": null
},
{
"code": null,
"e": 30361,
"s": 30353,
"text": "Output:"
},
{
"code": null,
"e": 30372,
"s": 30361,
"text": "true\nfalse"
},
{
"code": null,
"e": 30506,
"s": 30372,
"text": "Since KeyValue implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays."
},
{
"code": null,
"e": 30514,
"s": 30506,
"text": "Syntax:"
},
{
"code": null,
"e": 30631,
"s": 30514,
"text": "KeyValue<type1, type2> kv = \n new KeyValue<type1, type2>(value1, value2);\n\nfor (Object item : kv) {\n ...\n}"
},
{
"code": null,
"e": 30640,
"s": 30631,
"text": "Example:"
},
{
"code": null,
"e": 30645,
"s": 30640,
"text": "Java"
},
{
"code": "// Below is a Java program to iterate// a KeyValue import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); for (Object item : kv) System.out.println(item); }}",
"e": 30981,
"s": 30645,
"text": null
},
{
"code": null,
"e": 30989,
"s": 30981,
"text": "Output:"
},
{
"code": null,
"e": 31005,
"s": 30989,
"text": "1\nGeeksforGeeks"
},
{
"code": null,
"e": 31017,
"s": 31007,
"text": "kk9826225"
},
{
"code": null,
"e": 31039,
"s": 31017,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 31050,
"s": 31039,
"text": "JavaTuples"
},
{
"code": null,
"e": 31055,
"s": 31050,
"text": "Java"
},
{
"code": null,
"e": 31077,
"s": 31055,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 31082,
"s": 31077,
"text": "Java"
},
{
"code": null,
"e": 31180,
"s": 31082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31189,
"s": 31180,
"text": "Comments"
},
{
"code": null,
"e": 31202,
"s": 31189,
"text": "Old Comments"
},
{
"code": null,
"e": 31217,
"s": 31202,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31261,
"s": 31217,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31283,
"s": 31261,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31319,
"s": 31283,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31344,
"s": 31319,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31376,
"s": 31344,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31406,
"s": 31376,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31425,
"s": 31406,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31476,
"s": 31425,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
D3.js interrupt() Function - GeeksforGeeks
|
23 Sep, 2020
The d3.interrupt() function in D3.js is used to interrupts the active transition of the specified name on the specified node and cancels any pending transitions with the specified name. This function is similar to the selection.interrupt() function.
Syntax:
d3.interrupt(node[, name])
Parameters: This function accepts the following parameter as mentioned above and described below:
name: This parameter is the transition instance.
node: This parameter is the node for the passing argument.
Return Value: This function returns an interrupted active transition.
Below programs illustrate the d3.interrupt() function in D3.js.
Example 1:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"> </script></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.interrupt() Function</h3> <svg width="400" height="250"></svg> <script> var svg = d3.select("svg") var circle = svg.selectAll("circle") .data([1, 2, 3, 4]) .enter() .append("circle") .style("fill", "red") .attr("cx", 50) .attr("cy", function(d) { return d * 50 }) .attr("r", 25) .on("click", function() { d3.interrupt(d3.select(this)) }) circle.transition() .delay(function(d) { return d * 500; }) .duration(function(d) { return d * 1000; }) .attr("cx", 360) .on("interrupt", function() { var elem = this; var targetValue = d3.active(this) .attrTween("cx") .call(this)(1); d3.select(this).attr("cx", targetValue) }) </script> </center></body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"> </script> <style> svg { background-color: green; display: block; }; </style></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.interrupt() Function</h3> <button>Stop</button> <svg width="500" height="150"></svg> <script> const svg = d3.select("svg"); const local = d3.local(); const button = d3.select("button"); const circle = svg.append("circle") .attr("r", 25) .attr("cx", 30) .attr("cy", 75) .style("fill", "yellow") .style("stroke", "black"); circle.transition() .delay(5000) .duration(10000) .ease(d3.easeLinear) .attr("cx", 580) .on("interrupt", function() { local.set(this, +d3.select(this) .attr("cx")) }); button.on("click", function() { if (d3.active(circle.node())) { d3.interrupt(circle); this.textContent = "Resume"; } else { circle.transition() .ease(d3.easeLinear) .duration(function() { return 10000 * (560 - local.get(this)) / 560; }) .attr("cx", 580) this.textContent = "Stop"; } }) </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24862,
"s": 24834,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 25112,
"s": 24862,
"text": "The d3.interrupt() function in D3.js is used to interrupts the active transition of the specified name on the specified node and cancels any pending transitions with the specified name. This function is similar to the selection.interrupt() function."
},
{
"code": null,
"e": 25120,
"s": 25112,
"text": "Syntax:"
},
{
"code": null,
"e": 25148,
"s": 25120,
"text": "d3.interrupt(node[, name])\n"
},
{
"code": null,
"e": 25246,
"s": 25148,
"text": "Parameters: This function accepts the following parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25295,
"s": 25246,
"text": "name: This parameter is the transition instance."
},
{
"code": null,
"e": 25354,
"s": 25295,
"text": "node: This parameter is the node for the passing argument."
},
{
"code": null,
"e": 25424,
"s": 25354,
"text": "Return Value: This function returns an interrupted active transition."
},
{
"code": null,
"e": 25488,
"s": 25424,
"text": "Below programs illustrate the d3.interrupt() function in D3.js."
},
{
"code": null,
"e": 25499,
"s": 25488,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v5.min.js\"> </script></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.interrupt() Function</h3> <svg width=\"400\" height=\"250\"></svg> <script> var svg = d3.select(\"svg\") var circle = svg.selectAll(\"circle\") .data([1, 2, 3, 4]) .enter() .append(\"circle\") .style(\"fill\", \"red\") .attr(\"cx\", 50) .attr(\"cy\", function(d) { return d * 50 }) .attr(\"r\", 25) .on(\"click\", function() { d3.interrupt(d3.select(this)) }) circle.transition() .delay(function(d) { return d * 500; }) .duration(function(d) { return d * 1000; }) .attr(\"cx\", 360) .on(\"interrupt\", function() { var elem = this; var targetValue = d3.active(this) .attrTween(\"cx\") .call(this)(1); d3.select(this).attr(\"cx\", targetValue) }) </script> </center></body> </html>",
"e": 26963,
"s": 25499,
"text": null
},
{
"code": null,
"e": 26971,
"s": 26963,
"text": "Output:"
},
{
"code": null,
"e": 26982,
"s": 26971,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v5.min.js\"> </script> <style> svg { background-color: green; display: block; }; </style></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.interrupt() Function</h3> <button>Stop</button> <svg width=\"500\" height=\"150\"></svg> <script> const svg = d3.select(\"svg\"); const local = d3.local(); const button = d3.select(\"button\"); const circle = svg.append(\"circle\") .attr(\"r\", 25) .attr(\"cx\", 30) .attr(\"cy\", 75) .style(\"fill\", \"yellow\") .style(\"stroke\", \"black\"); circle.transition() .delay(5000) .duration(10000) .ease(d3.easeLinear) .attr(\"cx\", 580) .on(\"interrupt\", function() { local.set(this, +d3.select(this) .attr(\"cx\")) }); button.on(\"click\", function() { if (d3.active(circle.node())) { d3.interrupt(circle); this.textContent = \"Resume\"; } else { circle.transition() .ease(d3.easeLinear) .duration(function() { return 10000 * (560 - local.get(this)) / 560; }) .attr(\"cx\", 580) this.textContent = \"Stop\"; } }) </script> </center></body> </html>",
"e": 28789,
"s": 26982,
"text": null
},
{
"code": null,
"e": 28797,
"s": 28789,
"text": "Output:"
},
{
"code": null,
"e": 28803,
"s": 28797,
"text": "D3.js"
},
{
"code": null,
"e": 28814,
"s": 28803,
"text": "JavaScript"
},
{
"code": null,
"e": 28831,
"s": 28814,
"text": "Web Technologies"
},
{
"code": null,
"e": 28929,
"s": 28831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28974,
"s": 28929,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29035,
"s": 28974,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29107,
"s": 29035,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29159,
"s": 29107,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29205,
"s": 29159,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29247,
"s": 29205,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29309,
"s": 29247,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29342,
"s": 29309,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29385,
"s": 29342,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Batch Script - Create String
|
A string can be created in DOS in the following way.
@echo off
:: This program just displays Hello World
set message = Hello World
echo %message%
The above command produces the following output.
Hello World
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2222,
"s": 2169,
"text": "A string can be created in DOS in the following way."
},
{
"code": null,
"e": 2318,
"s": 2222,
"text": "@echo off \n:: This program just displays Hello World \nset message = Hello World \necho %message%"
},
{
"code": null,
"e": 2367,
"s": 2318,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2380,
"s": 2367,
"text": "Hello World\n"
},
{
"code": null,
"e": 2387,
"s": 2380,
"text": " Print"
},
{
"code": null,
"e": 2398,
"s": 2387,
"text": " Add Notes"
}
] |
TypeScript - Array sort()
|
sort() method sorts the elements of an array.
array.sort( compareFunction );
compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically.
Returns a sorted array.
var arr = new Array("orange", "mango", "banana", "sugar");
var sorted = arr.sort();
console.log("Returned string is : " + sorted );
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned string is : banana,mango,orange,sugar
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2094,
"s": 2048,
"text": "sort() method sorts the elements of an array."
},
{
"code": null,
"e": 2126,
"s": 2094,
"text": "array.sort( compareFunction );\n"
},
{
"code": null,
"e": 2245,
"s": 2126,
"text": "compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically."
},
{
"code": null,
"e": 2269,
"s": 2245,
"text": "Returns a sorted array."
},
{
"code": null,
"e": 2404,
"s": 2269,
"text": "var arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\"); \nvar sorted = arr.sort(); \nconsole.log(\"Returned string is : \" + sorted );\n"
},
{
"code": null,
"e": 2464,
"s": 2404,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2491,
"s": 2464,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2539,
"s": 2491,
"text": "Returned string is : banana,mango,orange,sugar\n"
},
{
"code": null,
"e": 2572,
"s": 2539,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2586,
"s": 2572,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2619,
"s": 2586,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2633,
"s": 2619,
"text": " Haider Malik"
},
{
"code": null,
"e": 2668,
"s": 2633,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2688,
"s": 2668,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2721,
"s": 2688,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2735,
"s": 2721,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2770,
"s": 2735,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2786,
"s": 2770,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2819,
"s": 2786,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2839,
"s": 2819,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 2846,
"s": 2839,
"text": " Print"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": " Add Notes"
}
] |
How to display R-squared value on scatterplot with regression model line in R?
|
The R-squared value is the coefficient of determination, it gives us the percentage or proportion of variation in dependent variable explained by the independent variable. To display this value on the scatterplot with regression model line without taking help from any package, we can use plot function with abline and legend functions.
Consider the below data frame −
Live Demo
set.seed(1234)
x<-rnorm(20,1,0.096)
y<-rnorm(20,2,0.06)
df<-data.frame(x,y)
df
x y
1 0.8841217 2.008045
2 1.0266332 1.970559
3 1.1041064 1.973567
4 0.7748130 2.027575
5 1.0411960 1.958377
6 1.0485814 1.913108
7 0.9448250 2.034485
8 0.9475233 1.938581
9 0.9458126 1.999092
10 0.9145564 1.943843
11 0.9541895 2.066138
12 0.9041549 1.971464
13 0.9254796 1.957434
14 1.0061880 1.969925
15 1.0921114 1.902254
16 0.9894126 1.929943
17 0.9509431 1.869198
18 0.9125252 1.919540
19 0.9196315 1.982342
20 1.2319202 1.972046
Creating the regression model to predict y from x −
Model<-lm(y~x,data=df)
summary(Model)
Call −
lm(formula = y ~ x, data = df)
Residuals:
Min 1Q Median 3Q Max
-0.09955 -0.03138 0.00522 0.02981 0.09783
Coefficients −
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.0971 0.1084 19.349 1.7e-13 ***
x -0.1350 0.1105 -1.221 0.238 ---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.04689 on 18 degrees of freedom
Multiple R-squared: 0.07649, Adjusted R-squared: 0.02519
F-statistic: 1.491 on 1 and 18 DF, p-value: 0.2378
Creating the scatterplot with R-squared value on the plot −
plot(x,y)
abline(Model) legend("topleft",legend=paste("R2 is", format(summary(Model)$r.squared,digits=3)))
|
[
{
"code": null,
"e": 1399,
"s": 1062,
"text": "The R-squared value is the coefficient of determination, it gives us the percentage or proportion of variation in dependent variable explained by the independent variable. To display this value on the scatterplot with regression model line without taking help from any package, we can use plot function with abline and legend functions."
},
{
"code": null,
"e": 1431,
"s": 1399,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1442,
"s": 1431,
"text": " Live Demo"
},
{
"code": null,
"e": 1521,
"s": 1442,
"text": "set.seed(1234)\nx<-rnorm(20,1,0.096)\ny<-rnorm(20,2,0.06)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 2094,
"s": 1521,
"text": " x y\n1 0.8841217 2.008045\n2 1.0266332 1.970559\n3 1.1041064 1.973567\n4 0.7748130 2.027575\n5 1.0411960 1.958377\n6 1.0485814 1.913108\n7 0.9448250 2.034485\n8 0.9475233 1.938581\n9 0.9458126 1.999092\n10 0.9145564 1.943843\n11 0.9541895 2.066138\n12 0.9041549 1.971464\n13 0.9254796 1.957434\n14 1.0061880 1.969925\n15 1.0921114 1.902254\n16 0.9894126 1.929943\n17 0.9509431 1.869198\n18 0.9125252 1.919540\n19 0.9196315 1.982342\n20 1.2319202 1.972046"
},
{
"code": null,
"e": 2146,
"s": 2094,
"text": "Creating the regression model to predict y from x −"
},
{
"code": null,
"e": 2184,
"s": 2146,
"text": "Model<-lm(y~x,data=df)\nsummary(Model)"
},
{
"code": null,
"e": 2191,
"s": 2184,
"text": "Call −"
},
{
"code": null,
"e": 2296,
"s": 2191,
"text": "lm(formula = y ~ x, data = df)\nResiduals:\nMin 1Q Median 3Q Max\n-0.09955 -0.03138 0.00522 0.02981 0.09783"
},
{
"code": null,
"e": 2311,
"s": 2296,
"text": "Coefficients −"
},
{
"code": null,
"e": 2655,
"s": 2311,
"text": "Estimate Std. Error t value Pr(>|t|)\n(Intercept) 2.0971 0.1084 19.349 1.7e-13 ***\nx -0.1350 0.1105 -1.221 0.238 ---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\nResidual standard error: 0.04689 on 18 degrees of freedom\nMultiple R-squared: 0.07649, Adjusted R-squared: 0.02519\nF-statistic: 1.491 on 1 and 18 DF, p-value: 0.2378"
},
{
"code": null,
"e": 2715,
"s": 2655,
"text": "Creating the scatterplot with R-squared value on the plot −"
},
{
"code": null,
"e": 2822,
"s": 2715,
"text": "plot(x,y)\nabline(Model) legend(\"topleft\",legend=paste(\"R2 is\", format(summary(Model)$r.squared,digits=3)))"
}
] |
KnockoutJS - Options Binding
|
This binding is used to define the options for a select element. This can be used for either drop-down list or a multi-select list. This binding cannot be used with anything other than <select> elements.
Syntax
options: <binding-array>
Parameters
Parameter to be passed here is an array. For each entry in array, the option will be added for respective select node. Earlier option will be removed.
Parameter to be passed here is an array. For each entry in array, the option will be added for respective select node. Earlier option will be removed.
If the parameter is an observable value, then the element's available options will be updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.
If the parameter is an observable value, then the element's available options will be updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.
Additional Parameters
optionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'.
optionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used.
optionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements.
optionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array.
optionsAfterRender − Use this for running some custom logic on the existing option elements.
selectedOptions − This is used to read and write the selected options from a multi select list.
valueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time.
Additional Parameters
optionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'.
optionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'.
optionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used.
optionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used.
optionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements.
optionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements.
optionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array.
optionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array.
optionsAfterRender − Use this for running some custom logic on the existing option elements.
optionsAfterRender − Use this for running some custom logic on the existing option elements.
selectedOptions − This is used to read and write the selected options from a multi select list.
selectedOptions − This is used to read and write the selected options from a multi select list.
valueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time.
valueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time.
Example
Let us take a look at the following example which demonstrates the use of options binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Options Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Tutorials Library:
<select data-bind = "
options: availableTutorials,
value: selectedTutorial,
optionsCaption: 'Choose tutuorial...',
"></select></p>
<p>You have selected <b><span
data-bind = "text:selectedTutorial"></span></b></p>
<script type = "text/javascript">
function ViewModel() {
this.selectedTutorial = ko.observable();
this.availableTutorials = ko.observableArray ([
'Academic','Big Data',
'Databases','Java Technologies',
'Mainframe','Management',
'Microsoft Technologies','Mobile Development',
'Programming','Software Quality'
]);
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in options-bind.htm file.
Save the above code in options-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Note that the value binding is used to read thecurrent selected item from the dropdown.
Note that the value binding is used to read thecurrent selected item from the dropdown.
Tutorials Library:
Choose tutuorial...AcademicBig DataDatabasesJava TechnologiesMainframeManagementMicrosoft TechnologiesMobile DevelopmentProgrammingSoftware Quality
You have selected
KO will leave the user's selection unchanged where possible, while the options binding updates the set of options in <select> element. For a single select in the drop-down list, the previously selected value will still be preserved. For multi select list, all previously selected options will be preserved.
The generated options can be post processed for some further custom logic with the help of optionsAfterRender callback. This function is executed after each element is inserted into the list, with the following parameters −
The option element which is inserted.
The option element which is inserted.
The data item against which it is bound; this will be undefined for the caption element.
The data item against which it is bound; this will be undefined for the caption element.
Example
Let us take a look at the following example which uses optionsAfterRender to add a disable binding to each option.
<!DOCTYPE html>
<head>
<title>KnockoutJS Options Binding - using optionsAfterRender </title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<select size = 3 data-bind = "
options: myItems,
optionsText: 'name',
optionsValue: 'id',
optionsAfterRender: setOptionDisable">
</select>
<script type = "text/javascript">
function ViewModel() {
myItems = [
{ name: 'First Class', id: 1, disable: ko.observable(false)},
{ name: 'Executive Class', id: 2, disable: ko.observable(true)},
{ name: 'Second Class', id: 3, disable: ko.observable(false)}
];
setOptionDisable = function(option, item) {
ko.applyBindingsToNode(option, {disable: item.disable}, item);
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in options-bind-optionsafterrender.htm file.
Save the above code in options-bind-optionsafterrender.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Option with id 2 is disabled using optionsAfterRender callback.
Option with id 2 is disabled using optionsAfterRender callback.
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2056,
"s": 1852,
"text": "This binding is used to define the options for a select element. This can be used for either drop-down list or a multi-select list. This binding cannot be used with anything other than <select> elements."
},
{
"code": null,
"e": 2063,
"s": 2056,
"text": "Syntax"
},
{
"code": null,
"e": 2089,
"s": 2063,
"text": "options: <binding-array>\n"
},
{
"code": null,
"e": 2100,
"s": 2089,
"text": "Parameters"
},
{
"code": null,
"e": 2251,
"s": 2100,
"text": "Parameter to be passed here is an array. For each entry in array, the option will be added for respective select node. Earlier option will be removed."
},
{
"code": null,
"e": 2402,
"s": 2251,
"text": "Parameter to be passed here is an array. For each entry in array, the option will be added for respective select node. Earlier option will be removed."
},
{
"code": null,
"e": 2604,
"s": 2402,
"text": "If the parameter is an observable value, then the element's available options will be updated as and when the underlying observable is changed. Element is processed only once, if no observable is used."
},
{
"code": null,
"e": 2806,
"s": 2604,
"text": "If the parameter is an observable value, then the element's available options will be updated as and when the underlying observable is changed. Element is processed only once, if no observable is used."
},
{
"code": null,
"e": 3904,
"s": 2806,
"text": "Additional Parameters\n\noptionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'.\noptionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used.\noptionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements.\noptionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array.\noptionsAfterRender − Use this for running some custom logic on the existing option elements.\nselectedOptions − This is used to read and write the selected options from a multi select list.\nvalueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time.\n"
},
{
"code": null,
"e": 3926,
"s": 3904,
"text": "Additional Parameters"
},
{
"code": null,
"e": 4043,
"s": 3926,
"text": "optionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'."
},
{
"code": null,
"e": 4160,
"s": 4043,
"text": "optionsCaption − This is just a default dummy value, which reads as 'Select item from below' or 'Choose from below'."
},
{
"code": null,
"e": 4362,
"s": 4160,
"text": "optionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used."
},
{
"code": null,
"e": 4564,
"s": 4362,
"text": "optionsText − This parameter allows you to specify which object property you want to set as text in the dropdown list. This parameter can also include a function, which returns the property to be used."
},
{
"code": null,
"e": 4721,
"s": 4564,
"text": "optionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements."
},
{
"code": null,
"e": 4878,
"s": 4721,
"text": "optionsValue − Similar to optionsText. This parameter allows to specify which object property can be used to set the value attribute of the option elements."
},
{
"code": null,
"e": 5041,
"s": 4878,
"text": "optionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array."
},
{
"code": null,
"e": 5204,
"s": 5041,
"text": "optionsIncludeDestroyed − Specify this parameter if you want to see array items which are marked as destroyed and are not actually deleted from observable array."
},
{
"code": null,
"e": 5297,
"s": 5204,
"text": "optionsAfterRender − Use this for running some custom logic on the existing option elements."
},
{
"code": null,
"e": 5390,
"s": 5297,
"text": "optionsAfterRender − Use this for running some custom logic on the existing option elements."
},
{
"code": null,
"e": 5486,
"s": 5390,
"text": "selectedOptions − This is used to read and write the selected options from a multi select list."
},
{
"code": null,
"e": 5582,
"s": 5486,
"text": "selectedOptions − This is used to read and write the selected options from a multi select list."
},
{
"code": null,
"e": 5828,
"s": 5582,
"text": "valueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time."
},
{
"code": null,
"e": 6074,
"s": 5828,
"text": "valueAllowUnset − Using this parameter, it is possible to set model property with the value which does not actually exist in the select element. This way one can keep default option as blank when the user views drop-down for the very first time."
},
{
"code": null,
"e": 6082,
"s": 6074,
"text": "Example"
},
{
"code": null,
"e": 6173,
"s": 6082,
"text": "Let us take a look at the following example which demonstrates the use of options binding."
},
{
"code": null,
"e": 7276,
"s": 6173,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Options Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p>Tutorials Library:\n <select data-bind = \"\n options: availableTutorials,\n value: selectedTutorial,\n optionsCaption: 'Choose tutuorial...',\n \"></select></p>\n \n <p>You have selected <b><span \n data-bind = \"text:selectedTutorial\"></span></b></p>\n\n <script type = \"text/javascript\">\n function ViewModel() {\n this.selectedTutorial = ko.observable();\n \n this.availableTutorials = ko.observableArray ([\n 'Academic','Big Data',\n 'Databases','Java Technologies',\n 'Mainframe','Management',\n 'Microsoft Technologies','Mobile Development',\n 'Programming','Software Quality'\n ]);\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7283,
"s": 7276,
"text": "Output"
},
{
"code": null,
"e": 7353,
"s": 7283,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 7399,
"s": 7353,
"text": "Save the above code in options-bind.htm file."
},
{
"code": null,
"e": 7445,
"s": 7399,
"text": "Save the above code in options-bind.htm file."
},
{
"code": null,
"e": 7479,
"s": 7445,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7513,
"s": 7479,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7601,
"s": 7513,
"text": "Note that the value binding is used to read thecurrent selected item from the dropdown."
},
{
"code": null,
"e": 7689,
"s": 7601,
"text": "Note that the value binding is used to read thecurrent selected item from the dropdown."
},
{
"code": null,
"e": 7862,
"s": 7689,
"text": "Tutorials Library:\n Choose tutuorial...AcademicBig DataDatabasesJava TechnologiesMainframeManagementMicrosoft TechnologiesMobile DevelopmentProgrammingSoftware Quality"
},
{
"code": null,
"e": 7883,
"s": 7862,
"text": "You have selected \n\n"
},
{
"code": null,
"e": 8191,
"s": 7883,
"text": "KO will leave the user's selection unchanged where possible, while the options binding updates the set of options in <select> element. For a single select in the drop-down list, the previously selected value will still be preserved. For multi select list, all previously selected options will be preserved. "
},
{
"code": null,
"e": 8415,
"s": 8191,
"text": "The generated options can be post processed for some further custom logic with the help of optionsAfterRender callback. This function is executed after each element is inserted into the list, with the following parameters −"
},
{
"code": null,
"e": 8453,
"s": 8415,
"text": "The option element which is inserted."
},
{
"code": null,
"e": 8491,
"s": 8453,
"text": "The option element which is inserted."
},
{
"code": null,
"e": 8580,
"s": 8491,
"text": "The data item against which it is bound; this will be undefined for the caption element."
},
{
"code": null,
"e": 8669,
"s": 8580,
"text": "The data item against which it is bound; this will be undefined for the caption element."
},
{
"code": null,
"e": 8677,
"s": 8669,
"text": "Example"
},
{
"code": null,
"e": 8792,
"s": 8677,
"text": "Let us take a look at the following example which uses optionsAfterRender to add a disable binding to each option."
},
{
"code": null,
"e": 9862,
"s": 8792,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Options Binding - using optionsAfterRender </title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <select size = 3 data-bind = \"\n options: myItems,\n optionsText: 'name',\n optionsValue: 'id',\n optionsAfterRender: setOptionDisable\">\n </select>\n\n <script type = \"text/javascript\">\n function ViewModel() {\n myItems = [\n { name: 'First Class', id: 1, disable: ko.observable(false)},\n { name: 'Executive Class', id: 2, disable: ko.observable(true)},\n { name: 'Second Class', id: 3, disable: ko.observable(false)}\n ];\n \n setOptionDisable = function(option, item) {\n ko.applyBindingsToNode(option, {disable: item.disable}, item);\n }\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 9869,
"s": 9862,
"text": "Output"
},
{
"code": null,
"e": 9939,
"s": 9869,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 10004,
"s": 9939,
"text": "Save the above code in options-bind-optionsafterrender.htm file."
},
{
"code": null,
"e": 10069,
"s": 10004,
"text": "Save the above code in options-bind-optionsafterrender.htm file."
},
{
"code": null,
"e": 10103,
"s": 10069,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10137,
"s": 10103,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10201,
"s": 10137,
"text": "Option with id 2 is disabled using optionsAfterRender callback."
},
{
"code": null,
"e": 10265,
"s": 10201,
"text": "Option with id 2 is disabled using optionsAfterRender callback."
},
{
"code": null,
"e": 10298,
"s": 10265,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10318,
"s": 10298,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10325,
"s": 10318,
"text": " Print"
},
{
"code": null,
"e": 10336,
"s": 10325,
"text": " Add Notes"
}
] |
Long.parse method in C#
|
To convert a string to a long, use the Long.parse method in C# −
Firstly, set a string −
string str = "7864646475767";
Now, convert it to long −
long.Parse(str);
Here is the complete code −
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
string str = "7864646475767";
long res = long.Parse(str);
Console.WriteLine(res);
}
}
7864646475767
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "To convert a string to a long, use the Long.parse method in C# −"
},
{
"code": null,
"e": 1151,
"s": 1127,
"text": "Firstly, set a string −"
},
{
"code": null,
"e": 1181,
"s": 1151,
"text": "string str = \"7864646475767\";"
},
{
"code": null,
"e": 1207,
"s": 1181,
"text": "Now, convert it to long −"
},
{
"code": null,
"e": 1224,
"s": 1207,
"text": "long.Parse(str);"
},
{
"code": null,
"e": 1252,
"s": 1224,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1263,
"s": 1252,
"text": " Live Demo"
},
{
"code": null,
"e": 1440,
"s": 1263,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n string str = \"7864646475767\";\n long res = long.Parse(str);\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 1454,
"s": 1440,
"text": "7864646475767"
}
] |
Canonical Cover of Functional Dependencies in DBMS - GeeksforGeeks
|
20 Aug, 2019
Whenever a user updates the database, the system must check whether any of the functional dependencies are getting violated in this process. If there is a violation of dependencies in the new database state, the system must roll back. Working with a huge set of functional dependencies can cause unnecessary added computational time. This is where the canonical cover comes into play.A canonical cover of a set of functional dependencies F is a simplified set of functional dependencies that has the same closure as the original set F.
Important definitions:
Extraneous attributes: An attribute of a functional dependency is said to be extraneous if we can remove it without changing the closure of the set of functional dependencies.Canonical cover: A canonical cover of a set of functional dependencies F such that ALL the following properties are satisfied:
F logically implies all dependencies in .
logically implies all dependencies in F.
No functional dependency in contains an extraneous attribute.
Each left side of a functional dependency in is unique. That is, there are no two dependencies and in such that .
Finding Canonical Cover
Algorithm to compute canonical cover of set F:
repeat
1. Use the union rule to replace any dependencies in
and with .
2. Find a functional dependency with an
extraneous attribute either in or in .
3. If an extraneous attribute is found, delete it from .
until F does not change
Example1:
Consider the following set F of functional dependencies:
F= {A BCB CA BAB C}
Steps to find canonical cover:
There are two functional dependencies with the same set of attributes on the left:A BCA BThese two can be combined to getA BC.Now, the revised set F becomes:F= {A BCB CAB C}There is an extraneous attribute in AB C because even after removing AB C from the set F, we get the same closures. This is because B C is already a part of F.Now, the revised set F becomes:F= {A BCB C}C is an extraneous attribute in A BC, also A B is logically implied by A B and B C (by transitivity).F= {A BB C}After this step, F does not change anymore. So,Hence the required canonical cover is,= {A BB C}
There are two functional dependencies with the same set of attributes on the left:A BCA BThese two can be combined to getA BC.Now, the revised set F becomes:F= {A BCB CAB C}
These two can be combined to getA BC.
Now, the revised set F becomes:
F= {A BCB CAB C}
There is an extraneous attribute in AB C because even after removing AB C from the set F, we get the same closures. This is because B C is already a part of F.Now, the revised set F becomes:F= {A BCB C}
Now, the revised set F becomes:
F= {A BCB C}
C is an extraneous attribute in A BC, also A B is logically implied by A B and B C (by transitivity).F= {A BB C}
F= {A BB C}
After this step, F does not change anymore. So,Hence the required canonical cover is,= {A BB C}
Example2:
Consider another set F of functional dependencies:
F={A BCCD EB DE A}
The left side of each functional dependency in F is unique.None of the attributes in the left or right side of any functional dependency is extraneous (Checked by applying definition of extraneous attributes on every functional dependency).Hence, the canonical cover is equal to F.
The left side of each functional dependency in F is unique.
None of the attributes in the left or right side of any functional dependency is extraneous (Checked by applying definition of extraneous attributes on every functional dependency).
Hence, the canonical cover is equal to F.
Note: There can be more than one canonical cover of a set F of functional dependencies.
How to check whether a set of f.d.’s F canonically cover another set of f.d.’s G?
Consider the following two sets of functional dependencies:
F = {A BAB CD ACD E}
G = {A BCD AB}
Now, we are required to find out whether one of these f.d.’s canonically covers the other set of f.d.’s. This means, we need to find out whether F canonically covers G, G canonically covers F, or none of the two canonically cover the other.
To find out, we follow the following steps:
Create a singleton right hand side. This means, the attributes to the right side of the f.d. arrow should all be singleton.The functional dependency D AC gets broken down into two functional dependencies, D A and D C.F = {A BAB CD AD CD E}
F = {A BAB CD AD CD E}
Remove all extraneous attributes.Consider any functional dependency XY Z. If X in itself can determine Z, then the attribute Y is extraneous and can be removed. As we can see, the occurrence of extraneous attributes is possible only in those functional dependencies where there are more than one attributes in the LHS.So, consider the functional dependency AB C.Now, we must find the closures of A and B to find whether any of these is extraneous.=AB=BAs we can see, B can be determined from A. This means we can remove B from the functional dependency AB C.F = {A BA CD AD CD E}
Consider any functional dependency XY Z. If X in itself can determine Z, then the attribute Y is extraneous and can be removed. As we can see, the occurrence of extraneous attributes is possible only in those functional dependencies where there are more than one attributes in the LHS.
So, consider the functional dependency AB C.Now, we must find the closures of A and B to find whether any of these is extraneous.
=AB=B
As we can see, B can be determined from A. This means we can remove B from the functional dependency AB C.
F = {A BA CD AD CD E}
Remove all redundant functional dependencies.Check all f.d.’s one by one, and see if by removing a f.d. X Y, we can still find out Y from X by some other f.d. A more formal way to state this is find without making use of the f.d. we are testing and check whether Y is a part of the closure. If yes, then the f.d. is redundant.Here, when checking for the f.d. D C, we observe that even after hiding it, the closure of D contains C. This is because we can obtain C from D by the combination of two other f.d.’s D A and A C. So, C is redundant.F = {A BA CD AD E}
Check all f.d.’s one by one, and see if by removing a f.d. X Y, we can still find out Y from X by some other f.d. A more formal way to state this is find without making use of the f.d. we are testing and check whether Y is a part of the closure. If yes, then the f.d. is redundant.
Here, when checking for the f.d. D C, we observe that even after hiding it, the closure of D contains C. This is because we can obtain C from D by the combination of two other f.d.’s D A and A C. So, C is redundant.
F = {A BA CD AD E}
Now, do the same for G.
Create a singleton right hand side. This means, the attributes to the right side of the f.d. arrow should all be singleton.G = {A BA CD AD B}
G = {A BA CD AD B}
Remove all extraneous attributes.Since the RHS of all f.d.’s contains only 1 attribute, there is no extraneous attribute possible.
Remove all redundant functional dependencies.By looping over all f.d.’s and checking the closure of the LHS in all cases, we observe that the f.d. D B is redundant as it can be obtained through a combination of 2 other f.d.’s, D A and A B.G = {A BA CD A}
By looping over all f.d.’s and checking the closure of the LHS in all cases, we observe that the f.d. D B is redundant as it can be obtained through a combination of 2 other f.d.’s, D A and A B.
G = {A BA CD A}
Now, since all f.d.’s of G are already covered in F, we conclude that F covers G.
This article is contributed by Anannya Uberoi. 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.
Sankalp Pahade
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
SQL query to find second highest salary?
CTE in SQL
SQL Interview Questions
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between DDL and DML in DBMS
SQL | GROUP BY
|
[
{
"code": null,
"e": 30871,
"s": 30843,
"text": "\n20 Aug, 2019"
},
{
"code": null,
"e": 31407,
"s": 30871,
"text": "Whenever a user updates the database, the system must check whether any of the functional dependencies are getting violated in this process. If there is a violation of dependencies in the new database state, the system must roll back. Working with a huge set of functional dependencies can cause unnecessary added computational time. This is where the canonical cover comes into play.A canonical cover of a set of functional dependencies F is a simplified set of functional dependencies that has the same closure as the original set F."
},
{
"code": null,
"e": 31430,
"s": 31407,
"text": "Important definitions:"
},
{
"code": null,
"e": 31733,
"s": 31430,
"text": "Extraneous attributes: An attribute of a functional dependency is said to be extraneous if we can remove it without changing the closure of the set of functional dependencies.Canonical cover: A canonical cover of a set of functional dependencies F such that ALL the following properties are satisfied:"
},
{
"code": null,
"e": 31775,
"s": 31733,
"text": "F logically implies all dependencies in ."
},
{
"code": null,
"e": 31817,
"s": 31775,
"text": " logically implies all dependencies in F."
},
{
"code": null,
"e": 31880,
"s": 31817,
"text": "No functional dependency in contains an extraneous attribute."
},
{
"code": null,
"e": 31997,
"s": 31880,
"text": "Each left side of a functional dependency in is unique. That is, there are no two dependencies and in such that ."
},
{
"code": null,
"e": 32021,
"s": 31997,
"text": "Finding Canonical Cover"
},
{
"code": null,
"e": 32068,
"s": 32021,
"text": "Algorithm to compute canonical cover of set F:"
},
{
"code": null,
"e": 32339,
"s": 32068,
"text": "repeat\n 1. Use the union rule to replace any dependencies in \n and with .\n 2. Find a functional dependency with an \n extraneous attribute either in or in .\n 3. If an extraneous attribute is found, delete it from .\n until F does not change\n"
},
{
"code": null,
"e": 32349,
"s": 32339,
"text": "Example1:"
},
{
"code": null,
"e": 32406,
"s": 32349,
"text": "Consider the following set F of functional dependencies:"
},
{
"code": null,
"e": 32430,
"s": 32406,
"text": "F= {A BCB CA BAB C}"
},
{
"code": null,
"e": 32461,
"s": 32430,
"text": "Steps to find canonical cover:"
},
{
"code": null,
"e": 33063,
"s": 32461,
"text": "There are two functional dependencies with the same set of attributes on the left:A BCA BThese two can be combined to getA BC.Now, the revised set F becomes:F= {A BCB CAB C}There is an extraneous attribute in AB C because even after removing AB C from the set F, we get the same closures. This is because B C is already a part of F.Now, the revised set F becomes:F= {A BCB C}C is an extraneous attribute in A BC, also A B is logically implied by A B and B C (by transitivity).F= {A BB C}After this step, F does not change anymore. So,Hence the required canonical cover is,= {A BB C}"
},
{
"code": null,
"e": 33243,
"s": 33063,
"text": "There are two functional dependencies with the same set of attributes on the left:A BCA BThese two can be combined to getA BC.Now, the revised set F becomes:F= {A BCB CAB C}"
},
{
"code": null,
"e": 33282,
"s": 33243,
"text": "These two can be combined to getA BC."
},
{
"code": null,
"e": 33314,
"s": 33282,
"text": "Now, the revised set F becomes:"
},
{
"code": null,
"e": 33334,
"s": 33314,
"text": "F= {A BCB CAB C}"
},
{
"code": null,
"e": 33542,
"s": 33334,
"text": "There is an extraneous attribute in AB C because even after removing AB C from the set F, we get the same closures. This is because B C is already a part of F.Now, the revised set F becomes:F= {A BCB C}"
},
{
"code": null,
"e": 33574,
"s": 33542,
"text": "Now, the revised set F becomes:"
},
{
"code": null,
"e": 33589,
"s": 33574,
"text": "F= {A BCB C}"
},
{
"code": null,
"e": 33708,
"s": 33589,
"text": "C is an extraneous attribute in A BC, also A B is logically implied by A B and B C (by transitivity).F= {A BB C}"
},
{
"code": null,
"e": 33722,
"s": 33708,
"text": "F= {A BB C}"
},
{
"code": null,
"e": 33820,
"s": 33722,
"text": "After this step, F does not change anymore. So,Hence the required canonical cover is,= {A BB C}"
},
{
"code": null,
"e": 33830,
"s": 33820,
"text": "Example2:"
},
{
"code": null,
"e": 33881,
"s": 33830,
"text": "Consider another set F of functional dependencies:"
},
{
"code": null,
"e": 33904,
"s": 33881,
"text": "F={A BCCD EB DE A}"
},
{
"code": null,
"e": 34187,
"s": 33904,
"text": "The left side of each functional dependency in F is unique.None of the attributes in the left or right side of any functional dependency is extraneous (Checked by applying definition of extraneous attributes on every functional dependency).Hence, the canonical cover is equal to F."
},
{
"code": null,
"e": 34247,
"s": 34187,
"text": "The left side of each functional dependency in F is unique."
},
{
"code": null,
"e": 34429,
"s": 34247,
"text": "None of the attributes in the left or right side of any functional dependency is extraneous (Checked by applying definition of extraneous attributes on every functional dependency)."
},
{
"code": null,
"e": 34472,
"s": 34429,
"text": "Hence, the canonical cover is equal to F."
},
{
"code": null,
"e": 34561,
"s": 34472,
"text": "Note: There can be more than one canonical cover of a set F of functional dependencies."
},
{
"code": null,
"e": 34643,
"s": 34561,
"text": "How to check whether a set of f.d.’s F canonically cover another set of f.d.’s G?"
},
{
"code": null,
"e": 34703,
"s": 34643,
"text": "Consider the following two sets of functional dependencies:"
},
{
"code": null,
"e": 34728,
"s": 34703,
"text": "F = {A BAB CD ACD E}"
},
{
"code": null,
"e": 34745,
"s": 34728,
"text": "G = {A BCD AB}"
},
{
"code": null,
"e": 34986,
"s": 34745,
"text": "Now, we are required to find out whether one of these f.d.’s canonically covers the other set of f.d.’s. This means, we need to find out whether F canonically covers G, G canonically covers F, or none of the two canonically cover the other."
},
{
"code": null,
"e": 35030,
"s": 34986,
"text": "To find out, we follow the following steps:"
},
{
"code": null,
"e": 35278,
"s": 35030,
"text": "Create a singleton right hand side. This means, the attributes to the right side of the f.d. arrow should all be singleton.The functional dependency D AC gets broken down into two functional dependencies, D A and D C.F = {A BAB CD AD CD E}"
},
{
"code": null,
"e": 35306,
"s": 35278,
"text": "F = {A BAB CD AD CD E}"
},
{
"code": null,
"e": 35894,
"s": 35306,
"text": "Remove all extraneous attributes.Consider any functional dependency XY Z. If X in itself can determine Z, then the attribute Y is extraneous and can be removed. As we can see, the occurrence of extraneous attributes is possible only in those functional dependencies where there are more than one attributes in the LHS.So, consider the functional dependency AB C.Now, we must find the closures of A and B to find whether any of these is extraneous.=AB=BAs we can see, B can be determined from A. This means we can remove B from the functional dependency AB C.F = {A BA CD AD CD E}"
},
{
"code": null,
"e": 36181,
"s": 35894,
"text": "Consider any functional dependency XY Z. If X in itself can determine Z, then the attribute Y is extraneous and can be removed. As we can see, the occurrence of extraneous attributes is possible only in those functional dependencies where there are more than one attributes in the LHS."
},
{
"code": null,
"e": 36312,
"s": 36181,
"text": "So, consider the functional dependency AB C.Now, we must find the closures of A and B to find whether any of these is extraneous."
},
{
"code": null,
"e": 36318,
"s": 36312,
"text": "=AB=B"
},
{
"code": null,
"e": 36426,
"s": 36318,
"text": "As we can see, B can be determined from A. This means we can remove B from the functional dependency AB C."
},
{
"code": null,
"e": 36453,
"s": 36426,
"text": "F = {A BA CD AD CD E}"
},
{
"code": null,
"e": 37023,
"s": 36453,
"text": "Remove all redundant functional dependencies.Check all f.d.’s one by one, and see if by removing a f.d. X Y, we can still find out Y from X by some other f.d. A more formal way to state this is find without making use of the f.d. we are testing and check whether Y is a part of the closure. If yes, then the f.d. is redundant.Here, when checking for the f.d. D C, we observe that even after hiding it, the closure of D contains C. This is because we can obtain C from D by the combination of two other f.d.’s D A and A C. So, C is redundant.F = {A BA CD AD E}"
},
{
"code": null,
"e": 37307,
"s": 37023,
"text": "Check all f.d.’s one by one, and see if by removing a f.d. X Y, we can still find out Y from X by some other f.d. A more formal way to state this is find without making use of the f.d. we are testing and check whether Y is a part of the closure. If yes, then the f.d. is redundant."
},
{
"code": null,
"e": 37527,
"s": 37307,
"text": "Here, when checking for the f.d. D C, we observe that even after hiding it, the closure of D contains C. This is because we can obtain C from D by the combination of two other f.d.’s D A and A C. So, C is redundant."
},
{
"code": null,
"e": 37550,
"s": 37527,
"text": "F = {A BA CD AD E}"
},
{
"code": null,
"e": 37574,
"s": 37550,
"text": "Now, do the same for G."
},
{
"code": null,
"e": 37720,
"s": 37574,
"text": "Create a singleton right hand side. This means, the attributes to the right side of the f.d. arrow should all be singleton.G = {A BA CD AD B}"
},
{
"code": null,
"e": 37743,
"s": 37720,
"text": "G = {A BA CD AD B}"
},
{
"code": null,
"e": 37874,
"s": 37743,
"text": "Remove all extraneous attributes.Since the RHS of all f.d.’s contains only 1 attribute, there is no extraneous attribute possible."
},
{
"code": null,
"e": 38135,
"s": 37874,
"text": "Remove all redundant functional dependencies.By looping over all f.d.’s and checking the closure of the LHS in all cases, we observe that the f.d. D B is redundant as it can be obtained through a combination of 2 other f.d.’s, D A and A B.G = {A BA CD A}"
},
{
"code": null,
"e": 38333,
"s": 38135,
"text": "By looping over all f.d.’s and checking the closure of the LHS in all cases, we observe that the f.d. D B is redundant as it can be obtained through a combination of 2 other f.d.’s, D A and A B."
},
{
"code": null,
"e": 38352,
"s": 38333,
"text": "G = {A BA CD A}"
},
{
"code": null,
"e": 38434,
"s": 38352,
"text": "Now, since all f.d.’s of G are already covered in F, we conclude that F covers G."
},
{
"code": null,
"e": 38736,
"s": 38434,
"text": "This article is contributed by Anannya Uberoi. 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": 38861,
"s": 38736,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38876,
"s": 38861,
"text": "Sankalp Pahade"
},
{
"code": null,
"e": 38881,
"s": 38876,
"text": "DBMS"
},
{
"code": null,
"e": 38886,
"s": 38881,
"text": "DBMS"
},
{
"code": null,
"e": 38984,
"s": 38886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39002,
"s": 38984,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 39049,
"s": 39002,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 39090,
"s": 39049,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 39101,
"s": 39090,
"text": "CTE in SQL"
},
{
"code": null,
"e": 39125,
"s": 39101,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 39156,
"s": 39125,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 39209,
"s": 39156,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 39243,
"s": 39209,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 39282,
"s": 39243,
"text": "Difference between DDL and DML in DBMS"
}
] |
Vim - Installation And Configuration
|
Vim is lightweight package and its installation is really simple. In this chapter, we will discuss following items −
Installation on Windows platform
Installation on Debian based Linux
Installation on RPM based Linux
Vim doesn’t have any specific requirements. It is simple software bundle which provides all dependencies.
To download Vim visit vim.org
To download Vim visit vim.org
Click on Download option from left pane
Click on Download option from left pane
Click on PC - MS-DOS and MS-Windows option
Click on PC - MS-DOS and MS-Windows option
Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe
Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe
Double click on installer and follow on screen instructions to complete installation
Double click on installer and follow on screen instructions to complete installation
Vim stores its configuration in simple text file namely _vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo %userprofile%
Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Installation on Linux platform is quite simple as compared to Windows. This section describes installation and configuration on Debian based Linux.
Execute below command in terminal −
Execute below command in terminal −
$ sudo apt-get update
$ sudo apt-get install vim
To ensure Vim is correctly installed execute below command −
To ensure Vim is correctly installed execute below command −
$ which vim
It should print the location of Vim binary. In my case it was −
It should print the location of Vim binary. In my case it was −
/usr/bin/vim
Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo $HOME
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
This section describes installation and configuration on RPM based Linux.
Execute below command in terminal −
Execute below command in terminal −
$ su -
$ yum install vim
To ensure Vim is correctly installed execute below command −
To ensure Vim is correctly installed execute below command −
$ which vim
It should print the location of Vim binary. In my case it was −
It should print the location of Vim binary. In my case it was −
/usr/bin/vim
Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo $HOME
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
46 Lectures
5.5 hours
Jason Cannon
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2087,
"s": 1970,
"text": "Vim is lightweight package and its installation is really simple. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 2120,
"s": 2087,
"text": "Installation on Windows platform"
},
{
"code": null,
"e": 2155,
"s": 2120,
"text": "Installation on Debian based Linux"
},
{
"code": null,
"e": 2187,
"s": 2155,
"text": "Installation on RPM based Linux"
},
{
"code": null,
"e": 2293,
"s": 2187,
"text": "Vim doesn’t have any specific requirements. It is simple software bundle which provides all dependencies."
},
{
"code": null,
"e": 2323,
"s": 2293,
"text": "To download Vim visit vim.org"
},
{
"code": null,
"e": 2353,
"s": 2323,
"text": "To download Vim visit vim.org"
},
{
"code": null,
"e": 2393,
"s": 2353,
"text": "Click on Download option from left pane"
},
{
"code": null,
"e": 2433,
"s": 2393,
"text": "Click on Download option from left pane"
},
{
"code": null,
"e": 2476,
"s": 2433,
"text": "Click on PC - MS-DOS and MS-Windows option"
},
{
"code": null,
"e": 2519,
"s": 2476,
"text": "Click on PC - MS-DOS and MS-Windows option"
},
{
"code": null,
"e": 2626,
"s": 2519,
"text": "Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe"
},
{
"code": null,
"e": 2733,
"s": 2626,
"text": "Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe"
},
{
"code": null,
"e": 2818,
"s": 2733,
"text": "Double click on installer and follow on screen instructions to complete installation"
},
{
"code": null,
"e": 2903,
"s": 2818,
"text": "Double click on installer and follow on screen instructions to complete installation"
},
{
"code": null,
"e": 3014,
"s": 2903,
"text": "Vim stores its configuration in simple text file namely _vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 3088,
"s": 3014,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 3162,
"s": 3088,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 3184,
"s": 3162,
"text": "$ echo %userprofile%\n"
},
{
"code": null,
"e": 3298,
"s": 3184,
"text": "Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 3412,
"s": 3298,
"text": "Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 3478,
"s": 3412,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 3544,
"s": 3478,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 3552,
"s": 3544,
"text": "set nu\n"
},
{
"code": null,
"e": 3651,
"s": 3552,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 3750,
"s": 3651,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 3898,
"s": 3750,
"text": "Installation on Linux platform is quite simple as compared to Windows. This section describes installation and configuration on Debian based Linux."
},
{
"code": null,
"e": 3934,
"s": 3898,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 3970,
"s": 3934,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 4021,
"s": 3970,
"text": "$ sudo apt-get update \n$ sudo apt-get install vim\n"
},
{
"code": null,
"e": 4082,
"s": 4021,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 4143,
"s": 4082,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 4156,
"s": 4143,
"text": "$ which vim\n"
},
{
"code": null,
"e": 4220,
"s": 4156,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 4284,
"s": 4220,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 4298,
"s": 4284,
"text": "/usr/bin/vim\n"
},
{
"code": null,
"e": 4409,
"s": 4298,
"text": "Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 4483,
"s": 4409,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 4557,
"s": 4483,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 4571,
"s": 4557,
"text": "$ echo $HOME\n"
},
{
"code": null,
"e": 4685,
"s": 4571,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 4799,
"s": 4685,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 4865,
"s": 4799,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 4931,
"s": 4865,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 4939,
"s": 4931,
"text": "set nu\n"
},
{
"code": null,
"e": 5038,
"s": 4939,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 5137,
"s": 5038,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 5211,
"s": 5137,
"text": "This section describes installation and configuration on RPM based Linux."
},
{
"code": null,
"e": 5247,
"s": 5211,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 5283,
"s": 5247,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 5310,
"s": 5283,
"text": "$ su - \n$ yum install vim\n"
},
{
"code": null,
"e": 5371,
"s": 5310,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 5432,
"s": 5371,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 5445,
"s": 5432,
"text": "$ which vim\n"
},
{
"code": null,
"e": 5509,
"s": 5445,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 5573,
"s": 5509,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 5587,
"s": 5573,
"text": "/usr/bin/vim\n"
},
{
"code": null,
"e": 5698,
"s": 5587,
"text": "Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 5772,
"s": 5698,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 5846,
"s": 5772,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 5860,
"s": 5846,
"text": "$ echo $HOME\n"
},
{
"code": null,
"e": 5974,
"s": 5860,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 6088,
"s": 5974,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 6154,
"s": 6088,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 6220,
"s": 6154,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 6228,
"s": 6220,
"text": "set nu\n"
},
{
"code": null,
"e": 6327,
"s": 6228,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 6426,
"s": 6327,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 6461,
"s": 6426,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6475,
"s": 6461,
"text": " Jason Cannon"
},
{
"code": null,
"e": 6482,
"s": 6475,
"text": " Print"
},
{
"code": null,
"e": 6493,
"s": 6482,
"text": " Add Notes"
}
] |
Bootstrap 4 .flex-*-column-reverse class
|
Use the flex-*-column-reverse class to display flex items vertically and reversed on different screen sizes.
Here’s the example of reversing flex items on medium device using “flex-md-column-reverse” class −
<div class="d-flex flex-md-column-reverse mb-3">
<div class="p-2 bg-warning">One</div>
<div class="p-2 bg-danger">Two</div>
<div class="p-2 bg-secondary">Three</div>
</div>
In the same way, set for large devices using “flex-lg-column-reverse” class −
<div class="d-flex flex-lg-column-reverse mb-3">
<div class="p-2 bg-warning">One</div>
<div class="p-2 bg-danger">Two</div>
<div class="p-2 bg-secondary">Three</div>
</div>
Implementing the .flex-*-column-reverse class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h2>Example</h2>
<p>Change the browser size to see the effect:<p>
<p>Default </p>
<div class="d-flex flex-column">
<div class="p-2 bg-primary">One</div>
<div class="p-2 bg-secondary">Two</div>
<div class="p-2 bg-info">Three</div>
</div>
<p>Flex on differet screen size (Medium-Reverse)</p>
<div class="d-flex flex-md-column-reverse mb-3">
<div class="p-2 bg-warning">One</div>
<div class="p-2 bg-danger">Two</div>
<div class="p-2 bg-secondary">Three</div>
</div>
<p>Flex on different screen size (Large-Reverse)</p>
<div class="d-flex flex-lg-column-reverse mb-3">
<div class="p-2 bg-warning">One</div>
<div class="p-2 bg-danger">Two</div>
<div class="p-2 bg-secondary">Three</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "Use the flex-*-column-reverse class to display flex items vertically and reversed on different screen sizes."
},
{
"code": null,
"e": 1270,
"s": 1171,
"text": "Here’s the example of reversing flex items on medium device using “flex-md-column-reverse” class −"
},
{
"code": null,
"e": 1449,
"s": 1270,
"text": "<div class=\"d-flex flex-md-column-reverse mb-3\">\n <div class=\"p-2 bg-warning\">One</div>\n <div class=\"p-2 bg-danger\">Two</div>\n <div class=\"p-2 bg-secondary\">Three</div>\n</div>"
},
{
"code": null,
"e": 1527,
"s": 1449,
"text": "In the same way, set for large devices using “flex-lg-column-reverse” class −"
},
{
"code": null,
"e": 1706,
"s": 1527,
"text": "<div class=\"d-flex flex-lg-column-reverse mb-3\">\n <div class=\"p-2 bg-warning\">One</div>\n <div class=\"p-2 bg-danger\">Two</div>\n <div class=\"p-2 bg-secondary\">Three</div>\n</div>"
},
{
"code": null,
"e": 1754,
"s": 1706,
"text": "Implementing the .flex-*-column-reverse class −"
},
{
"code": null,
"e": 1764,
"s": 1754,
"text": "Live Demo"
},
{
"code": null,
"e": 3098,
"s": 1764,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container mt-3\">\n <h2>Example</h2>\n <p>Change the browser size to see the effect:<p>\n <p>Default </p>\n <div class=\"d-flex flex-column\">\n <div class=\"p-2 bg-primary\">One</div>\n <div class=\"p-2 bg-secondary\">Two</div>\n <div class=\"p-2 bg-info\">Three</div>\n </div>\n <p>Flex on differet screen size (Medium-Reverse)</p>\n <div class=\"d-flex flex-md-column-reverse mb-3\">\n <div class=\"p-2 bg-warning\">One</div>\n <div class=\"p-2 bg-danger\">Two</div>\n <div class=\"p-2 bg-secondary\">Three</div>\n </div>\n <p>Flex on different screen size (Large-Reverse)</p>\n <div class=\"d-flex flex-lg-column-reverse mb-3\">\n <div class=\"p-2 bg-warning\">One</div>\n <div class=\"p-2 bg-danger\">Two</div>\n <div class=\"p-2 bg-secondary\">Three</div>\n </div>\n </div>\n\n</body>\n</html>"
}
] |
Minimum no. of iterations to pass information to all nodes in the tree - GeeksforGeeks
|
10 Sep, 2021
Given a very large n-ary tree. Where the root node has some information which it wants to pass to all of its children down to the leaves with the constraint that it can only pass the information to one of its children at a time (take it as one iteration). Now in the next iteration the child node can transfer that information to only one of its children and at the same time instance the child’s parent i.e. root can pass the info to one of its remaining children. Continuing in this way we have to find the minimum no of iterations required to pass the information to all nodes in the tree.Minimum no of iterations for tree below is 6. The root A first passes information to B. In next iteration, A passes information to E and B passes information to H and so on.
We strongly recommend to minimize the browser and try this yourself first.This can be done using Post Order Traversal. The idea is to consider height and children count on each and every node. If a child node i takes ci iterations to pass info below its subtree, then its parent will take (ci + 1) iterations to pass info to subtree rooted at that child i. If parent has more children, it will pass info to them in subsequent iterations. Let’s say children of a parent takes c1, c2, c3, c4, ..., cn iterations to pass info in their own subtree, Now parent has to pass info to these n children one by one in n iterations. If parent picks child i in ith iteration, then parent will take (i + ci) iterations to pass info to child i and all it’s subtree. In any iteration, when parent passes info a child i+1, children (1 to i) which got info from parent already in previous iterations, will pass info to further down in subsequent iterations, if any child (1 to i) has its own child further down. To pass info to whole tree in minimum iterations, it needs to be made sure that bandwidth is utilized as efficiently as possible (i.e. maximum passable no of nodes should pass info further down in any iteration) The best possible scenario would be that in nth iteration, n different nodes pass info to their child. Nodes with height = 0: (Trivial case) Leaf node has no children (no information passing needed), so no of iterations would be ZERO. Nodes with height = 1: Here node has to pass info to all the children one by one (all children are leaf node, so no more information passing further down). Since all children are leaf, node can pass info to any child in any order (pick any child who didn’t receive the info yet). One iteration needed for each child and so no of iterations would be no of children.So node with height 1 with n children will take n iterations. Take a counter initialized with ZERO, loop through all children and keep incrementing counter. Nodes with height > 1: Let’s assume that there are n children (1 to n) of a node and minimum no iterations for all n children are c1, c2, ...., cn. To make sure maximum no of nodes participate in info passing in any iteration, parent should 1st pass info to that child who will take maximum iteration to pass info further down in subsequent iterations. i.e. in any iteration, parent should choose the child who takes maximum iteration later on. It can be thought of as a greedy approach where parent choose that child 1st, who needs maximum no of iterations so that all subsequent iterations can be utilized efficiently. If parent goes in any other fashion, then in the end, there could be some nodes which are done quite early, sitting idle and so bandwidth is not utilized efficiently in further iterations. If there are two children i and j with minimum iterations ci and cj where ci > cj, then If parent picks child j 1st then no of iterations needed by parent to pass info to both children and their subtree would be:max (1 + cj, 2 + ci) = 2 + ci If parent picks child i 1st then no of iterations needed by parent to pass info to both children and their subtree would be: max(1 + ci, 2 + cj) = 1 + ci (So picking ci gives better result than picking cj)This tells that parent should always choose child i with max ci value in any iteration. SO here greedy approach is: sort all ci values decreasing order, let’s say after sorting, values are c1 > c2 > c3 > .... > cn take a counter c, set c = 1 + c1 (for child with maximum no of iterations) for all children i from 2 to n, c = c + 1 + ci then total no of iterations needed by parent is max(n, c)Let minItr(A) be the minimum iteration needed to pass info from node A to it’s all the sub-tree. Let child(A) be the count of all children for node A. So recursive relation would be:
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A)
For children B from i = 0 to child(A)
minItr(A) = max ( minItr(A), minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
Following is the implementation of above idea.
C++
Java
C#
Javascript
// C++ program to find minimum number of iterations to pass// information from root to all nodes in an n-ary tree#include<bits/stdc++.h>using namespace std; // A class to represent n-ary tree (Note that the implementation// is similar to graph for simplicity of implementationclass NAryTree{ int N; // No. of nodes in Tree // Pointer to an array containing list of children list<int> *adj; // A function used by getMinIter(), it basically does postorder void getMinIterUtil(int v, int minItr[]);public: NAryTree(int N); // Constructor // function to add a child w to v void addChild(int v, int w); // The main function to find minimum iterations int getMinIter(); static int compare(const void * a, const void * b);}; NAryTree::NAryTree(int N){ this->N = N; adj = new list<int>[N];} // To add a child w to vvoid NAryTree::addChild(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} /* A recursive function to used by getMinIter(). This function// mainly does postorder traversal and get minimum iteration of all children// of node u, sort them in decreasing order and then get minimum iteration// of node u 1. Get minItr(B) of all children (B) of a node (A)2. Sort all minItr(B) in descending order3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max ( minItr(A), minItr(B) + i + 1) Base cases would be:If node is leaf, minItr = 0If node's height is 1, minItr = children count*/ void NAryTree::getMinIterUtil(int u, int minItr[]){ minItr[u] = adj[u].size(); int *minItrTemp = new int[minItr[u]]; int k = 0, tmp = 0; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[u].begin(); i!= adj[u].end(); ++i) { getMinIterUtil(*i, minItr); minItrTemp[k++] = minItr[*i]; } qsort(minItrTemp, minItr[u], sizeof (int), compare); for (k = 0; k < adj[u].size(); k++) { tmp = minItrTemp[k] + k + 1; minItr[u] = max(minItr[u], tmp); } delete[] minItrTemp;} // The function to do PostOrder traversal. It uses// recursive getMinIterUtil()int NAryTree::getMinIter(){ // Set minimum iteration all the vertices as zero int *minItr = new int[N]; int res = -1; for (int i = 0; i < N; i++) minItr[i] = 0; // Start Post Order Traversal from Root getMinIterUtil(0, minItr); res = minItr[0]; delete[] minItr; return res;} int NAryTree::compare(const void * a, const void * b){ return ( *(int*)b - *(int*)a );} // Driver function to test above functionsint main(){ // TestCase 1 NAryTree tree1(17); tree1.addChild(0, 1); tree1.addChild(0, 2); tree1.addChild(0, 3); tree1.addChild(0, 4); tree1.addChild(0, 5); tree1.addChild(0, 6); tree1.addChild(1, 7); tree1.addChild(1, 8); tree1.addChild(1, 9); tree1.addChild(4, 10); tree1.addChild(4, 11); tree1.addChild(6, 12); tree1.addChild(7, 13); tree1.addChild(7, 14); tree1.addChild(10, 15); tree1.addChild(11, 16); cout << "TestCase 1 - Minimum Iteration: " << tree1.getMinIter() << endl; // TestCase 2 NAryTree tree2(3); tree2.addChild(0, 1); tree2.addChild(0, 2); cout << "TestCase 2 - Minimum Iteration: " << tree2.getMinIter() << endl; // TestCase 3 NAryTree tree3(1); cout << "TestCase 3 - Minimum Iteration: " << tree3.getMinIter() << endl; // TestCase 4 NAryTree tree4(6); tree4.addChild(0, 1); tree4.addChild(1, 2); tree4.addChild(2, 3); tree4.addChild(3, 4); tree4.addChild(4, 5); cout << "TestCase 4 - Minimum Iteration: " << tree4.getMinIter() << endl; // TestCase 5 NAryTree tree5(6); tree5.addChild(0, 1); tree5.addChild(0, 2); tree5.addChild(2, 3); tree5.addChild(2, 4); tree5.addChild(2, 5); cout << "TestCase 5 - Minimum Iteration: " << tree5.getMinIter() << endl; // TestCase 6 NAryTree tree6(6); tree6.addChild(0, 1); tree6.addChild(0, 2); tree6.addChild(2, 3); tree6.addChild(2, 4); tree6.addChild(3, 5); cout << "TestCase 6 - Minimum Iteration: " << tree6.getMinIter() << endl; // TestCase 7 NAryTree tree7(14); tree7.addChild(0, 1); tree7.addChild(0, 2); tree7.addChild(0, 3); tree7.addChild(1, 4); tree7.addChild(2, 5); tree7.addChild(2, 6); tree7.addChild(4, 7); tree7.addChild(5, 8); tree7.addChild(5, 9); tree7.addChild(7, 10); tree7.addChild(8, 11); tree7.addChild(8, 12); tree7.addChild(10, 13); cout << "TestCase 7 - Minimum Iteration: " << tree7.getMinIter() << endl; // TestCase 8 NAryTree tree8(14); tree8.addChild(0, 1); tree8.addChild(0, 2); tree8.addChild(0, 3); tree8.addChild(0, 4); tree8.addChild(0, 5); tree8.addChild(1, 6); tree8.addChild(2, 7); tree8.addChild(3, 8); tree8.addChild(4, 9); tree8.addChild(6, 10); tree8.addChild(7, 11); tree8.addChild(8, 12); tree8.addChild(9, 13); cout << "TestCase 8 - Minimum Iteration: " << tree8.getMinIter() << endl; // TestCase 9 NAryTree tree9(25); tree9.addChild(0, 1); tree9.addChild(0, 2); tree9.addChild(0, 3); tree9.addChild(0, 4); tree9.addChild(0, 5); tree9.addChild(0, 6); tree9.addChild(1, 7); tree9.addChild(2, 8); tree9.addChild(3, 9); tree9.addChild(4, 10); tree9.addChild(5, 11); tree9.addChild(6, 12); tree9.addChild(7, 13); tree9.addChild(8, 14); tree9.addChild(9, 15); tree9.addChild(10, 16); tree9.addChild(11, 17); tree9.addChild(12, 18); tree9.addChild(13, 19); tree9.addChild(14, 20); tree9.addChild(15, 21); tree9.addChild(16, 22); tree9.addChild(17, 23); tree9.addChild(19, 24); cout << "TestCase 9 - Minimum Iteration: " << tree9.getMinIter() << endl; return 0;}
// Java program to find minimum number of// iterations to pass information from// root to all nodes in an n-ary treeimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Iterator;import java.util.List; class GFG{ // No. of nodes private static int N; // Adjacency list containing // list of children private static List<List<Integer>> adj; GFG(int N) { this.N = N; adj = new ArrayList<>(N); for (int i = 0; i < N; i++) adj.add(new ArrayList<>()); } // function to add a child w to v void addChild(int v, int w) { adj.get(v).add(w); } // Main function to find the // minimum iterations private int getMinIteration() { // Base case : if height = 0 or 1; if (N == 0 || N == 1) return 0; int[] mintItr = new int[N]; // Start Post Order Traversal from Root getMinIterUtil(0, mintItr); return mintItr[0]; } /* A recursive function to used by getMinIter(). This function mainly does postorder traversal and get minimum iteration of all children of parent node, sort them in decreasing order and then get minimum iteration of parent node 1. Get minItr(B) of all children (B) of a node (A) 2. Sort all minItr(B) in descending order 3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max (minItr(A), minItr(B) + i + 1) Base cases would be: If node is leaf, minItr = 0 If node's height is 1, minItr = children count */ private void getMinIterUtil(int u, int[] minItr) { // Base case : Leaf node if (adj.get(u).size() == 0) return; minItr[u] = adj.get(u).size(); Integer[] minItrTemp = new Integer[minItr[u]]; int k = 0; Iterator itr = adj.get(u).iterator(); while (itr.hasNext()) { int currentChild = (int) itr.next(); getMinIterUtil(currentChild, minItr); minItrTemp[k++] = minItr[currentChild]; } Arrays.sort(minItrTemp, Collections.reverseOrder()); for (k = 0; k < adj.get(u).size(); k++) { int temp = minItrTemp[k] + k + 1; minItr[u] = Math.max(minItr[u], temp); } } // Driver Code public static void main(String args[]) { // TestCase1 GFG testCase1 = new GFG(17); testCase1.addChild(0, 1); testCase1.addChild(0, 2); testCase1.addChild(0, 3); testCase1.addChild(0, 4); testCase1.addChild(0, 5); testCase1.addChild(0, 6); testCase1.addChild(1, 7); testCase1.addChild(1, 8); testCase1.addChild(1, 9); testCase1.addChild(4, 10); testCase1.addChild(4, 11); testCase1.addChild(6, 12); testCase1.addChild(7, 13); testCase1.addChild(7, 14); testCase1.addChild(10, 15); testCase1.addChild(11, 16); System.out.println("TestCase 1 - Minimum Iteration: " + testCase1.getMinIteration()); // TestCase2 GFG testCase2 = new GFG(3); testCase2.addChild(0, 1); testCase2.addChild(0, 2); System.out.println("TestCase 2 - Minimum Iteration: " + testCase2.getMinIteration()); // TestCase3 GFG testCase3 = new GFG(1); System.out.println("TestCase 3 - Minimum Iteration: " + testCase3.getMinIteration()); // TestCase4 GFG testCase4 = new GFG(6); testCase4.addChild(0, 1); testCase4.addChild(1, 2); testCase4.addChild(2, 3); testCase4.addChild(3, 4); testCase4.addChild(4, 5); System.out.println("TestCase 4 - Minimum Iteration: " + testCase4.getMinIteration()); // TestCase 5 GFG testCase5 = new GFG(6); testCase5.addChild(0, 1); testCase5.addChild(0, 2); testCase5.addChild(2, 3); testCase5.addChild(2, 4); testCase5.addChild(2, 5); System.out.println("TestCase 5 - Minimum Iteration: " + testCase5.getMinIteration()); // TestCase 6 GFG testCase6 = new GFG(6); testCase6.addChild(0, 1); testCase6.addChild(0, 2); testCase6.addChild(2, 3); testCase6.addChild(2, 4); testCase6.addChild(3, 5); System.out.println("TestCase 6 - Minimum Iteration: " + testCase6.getMinIteration()); // TestCase 7 GFG testCase7 = new GFG(14); testCase7.addChild(0, 1); testCase7.addChild(0, 2); testCase7.addChild(0, 3); testCase7.addChild(1, 4); testCase7.addChild(2, 5); testCase7.addChild(2, 6); testCase7.addChild(4, 7); testCase7.addChild(5, 8); testCase7.addChild(5, 9); testCase7.addChild(7, 10); testCase7.addChild(8, 11); testCase7.addChild(8, 12); testCase7.addChild(10, 13); System.out.println("TestCase 7 - Minimum Iteration: " + testCase7.getMinIteration()); // TestCase 8 GFG testCase8 = new GFG(14); testCase8.addChild(0, 1); testCase8.addChild(0, 2); testCase8.addChild(0, 3); testCase8.addChild(0, 4); testCase8.addChild(0, 5); testCase8.addChild(1, 6); testCase8.addChild(2, 7); testCase8.addChild(3, 8); testCase8.addChild(4, 9); testCase8.addChild(6, 10); testCase8.addChild(7, 11); testCase8.addChild(8, 12); testCase8.addChild(9, 13); System.out.println("TestCase 8 - Minimum Iteration: " + testCase8.getMinIteration()); // TestCase 9 GFG testCase9 = new GFG(25); testCase9.addChild(0, 1); testCase9.addChild(0, 2); testCase9.addChild(0, 3); testCase9.addChild(0, 4); testCase9.addChild(0, 5); testCase9.addChild(0, 6); testCase9.addChild(1, 7); testCase9.addChild(2, 8); testCase9.addChild(3, 9); testCase9.addChild(4, 10); testCase9.addChild(5, 11); testCase9.addChild(6, 12); testCase9.addChild(7, 13); testCase9.addChild(8, 14); testCase9.addChild(9, 15); testCase9.addChild(10, 16); testCase9.addChild(11, 17); testCase9.addChild(12, 18); testCase9.addChild(13, 19); testCase9.addChild(14, 20); testCase9.addChild(15, 21); testCase9.addChild(16, 22); testCase9.addChild(17, 23); testCase9.addChild(19, 24); System.out.println("TestCase 9 - Minimum Iteration: " + testCase9.getMinIteration()); }} // This code is contributed// by MitaliSrivastava
// C# program to find minimum number of// iterations to pass information from// root to all nodes in an n-ary treeusing System;using System.Collections.Generic;class GFG{ // No. of nodes public int N; // Adjacency list containing // list of children static List<List<int>> adj; public GFG(int N) { this.N = N; adj = new List<List<int>>(N); for (int i = 0; i < N; i++) adj.Add(new List<int>()); } // function to add a child w to v void addChild(int v, int w) { adj[v].Add(w); } // Main function to find the // minimum iterations private int getMinIteration() { // Base case : if height = 0 or 1; if (N == 0 || N == 1) return 0; int[] mintItr = new int[N]; // Start Post Order Traversal from Root getMinIterUtil(0, mintItr); return mintItr[0]; } /* A recursive function to used by getMinIter(). This function mainly does postorder traversal and get minimum iteration of all children of parent node, sort them in decreasing order and then get minimum iteration of parent node 1. Get minItr(B) of all children (B) of a node (A) 2. Sort all minItr(B) in descending order 3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max (minItr(A), minItr(B) + i + 1) Base cases would be: If node is leaf, minItr = 0 If node's height is 1, minItr = children count */ private void getMinIterUtil(int u, int[] minItr) { // Base case : Leaf node if (adj[u].Count == 0) return; minItr[u] = adj[u].Count; int[] minItrTemp = new int[minItr[u]]; int k = 0; // Iterator itr = adj.get(u).iterator(); foreach (int itr in adj[u]) { int currentChild = (int) itr; getMinIterUtil(currentChild, minItr); minItrTemp[k++] = minItr[currentChild]; } Array.Sort(minItrTemp); for(int i =0, j = minItrTemp.Length-1; i<j;i++,j--){ int temp = minItrTemp[i]; minItrTemp[i] = minItrTemp[j]; minItrTemp[j] = temp; } for (k = 0; k < adj[u].Count; k++) { int temp = minItrTemp[k] + k + 1; minItr[u] = Math.Max(minItr[u], temp); } } // Driver Code public static void Main(String []args) { // TestCase1 GFG testCase1 = new GFG(17); testCase1.addChild(0, 1); testCase1.addChild(0, 2); testCase1.addChild(0, 3); testCase1.addChild(0, 4); testCase1.addChild(0, 5); testCase1.addChild(0, 6); testCase1.addChild(1, 7); testCase1.addChild(1, 8); testCase1.addChild(1, 9); testCase1.addChild(4, 10); testCase1.addChild(4, 11); testCase1.addChild(6, 12); testCase1.addChild(7, 13); testCase1.addChild(7, 14); testCase1.addChild(10, 15); testCase1.addChild(11, 16); Console.WriteLine("TestCase 1 - Minimum Iteration: " + testCase1.getMinIteration()); // TestCase2 GFG testCase2 = new GFG(3); testCase2.addChild(0, 1); testCase2.addChild(0, 2); Console.WriteLine("TestCase 2 - Minimum Iteration: " + testCase2.getMinIteration()); // TestCase3 GFG testCase3 = new GFG(1); Console.WriteLine("TestCase 3 - Minimum Iteration: " + testCase3.getMinIteration()); // TestCase4 GFG testCase4 = new GFG(6); testCase4.addChild(0, 1); testCase4.addChild(1, 2); testCase4.addChild(2, 3); testCase4.addChild(3, 4); testCase4.addChild(4, 5); Console.WriteLine("TestCase 4 - Minimum Iteration: " + testCase4.getMinIteration()); // TestCase 5 GFG testCase5 = new GFG(6); testCase5.addChild(0, 1); testCase5.addChild(0, 2); testCase5.addChild(2, 3); testCase5.addChild(2, 4); testCase5.addChild(2, 5); Console.WriteLine("TestCase 5 - Minimum Iteration: " + testCase5.getMinIteration()); // TestCase 6 GFG testCase6 = new GFG(6); testCase6.addChild(0, 1); testCase6.addChild(0, 2); testCase6.addChild(2, 3); testCase6.addChild(2, 4); testCase6.addChild(3, 5); Console.WriteLine("TestCase 6 - Minimum Iteration: " + testCase6.getMinIteration()); // TestCase 7 GFG testCase7 = new GFG(14); testCase7.addChild(0, 1); testCase7.addChild(0, 2); testCase7.addChild(0, 3); testCase7.addChild(1, 4); testCase7.addChild(2, 5); testCase7.addChild(2, 6); testCase7.addChild(4, 7); testCase7.addChild(5, 8); testCase7.addChild(5, 9); testCase7.addChild(7, 10); testCase7.addChild(8, 11); testCase7.addChild(8, 12); testCase7.addChild(10, 13); Console.WriteLine("TestCase 7 - Minimum Iteration: " + testCase7.getMinIteration()); // TestCase 8 GFG testCase8 = new GFG(14); testCase8.addChild(0, 1); testCase8.addChild(0, 2); testCase8.addChild(0, 3); testCase8.addChild(0, 4); testCase8.addChild(0, 5); testCase8.addChild(1, 6); testCase8.addChild(2, 7); testCase8.addChild(3, 8); testCase8.addChild(4, 9); testCase8.addChild(6, 10); testCase8.addChild(7, 11); testCase8.addChild(8, 12); testCase8.addChild(9, 13); Console.WriteLine("TestCase 8 - Minimum Iteration: " + testCase8.getMinIteration()); // TestCase 9 GFG testCase9 = new GFG(25); testCase9.addChild(0, 1); testCase9.addChild(0, 2); testCase9.addChild(0, 3); testCase9.addChild(0, 4); testCase9.addChild(0, 5); testCase9.addChild(0, 6); testCase9.addChild(1, 7); testCase9.addChild(2, 8); testCase9.addChild(3, 9); testCase9.addChild(4, 10); testCase9.addChild(5, 11); testCase9.addChild(6, 12); testCase9.addChild(7, 13); testCase9.addChild(8, 14); testCase9.addChild(9, 15); testCase9.addChild(10, 16); testCase9.addChild(11, 17); testCase9.addChild(12, 18); testCase9.addChild(13, 19); testCase9.addChild(14, 20); testCase9.addChild(15, 21); testCase9.addChild(16, 22); testCase9.addChild(17, 23); testCase9.addChild(19, 24); Console.WriteLine("TestCase 9 - Minimum Iteration: " + testCase9.getMinIteration()); }} // This code is contributed by aashish1995
<script> var height;var graph; function findHeight(node , h){ height[node] = h; for(let i=0;i<graph[node].length;i++) { let v = graph[node][i]; findHeight(v , h + 1); }} function getMinIteration(){ findHeight(0 , 0); let max_height = 0; for(let i=0;i<height.length;i++) { if(height[i] > max_height) { max_height = height[i]; } } for(let i=0;i<height.length;i++) { height[i] = max_height - height[i]; } return getMinIterationUtil(0);} function getMinIterationUtil(node){ if(height[node] == 0 ) { return 0; } if(height[node] == 1 ) { return graph[node].length; } let edges =[...graph[node] ]; let edgeLenArr = []; for(let i=0;i<edges.length;i++ ) { edgeLenArr.push( graph[ graph[node][i] ].length ); } for (let i = 0; i < edgeLenArr.length - 1; i++) { for (let j = i + 1; j < edgeLenArr.length; j++) { if(edgeLenArr[i] < edgeLenArr[j]) { let temp = edgeLenArr[i]; edgeLenArr[i] = edgeLenArr[j]; edgeLenArr[j] = temp; let temp1 = edges[i]; edges[i] = edges[j]; edges[j] = temp1; } } } let max_data = edges.length; for(let i=0;i<edges.length;i++) { max_data = Math.max( max_data , i + 1 + getMinIterationUtil(edges[i])); } return max_data;} function addChild(a , b){ graph[a].push(b);} function intializeGraph(n){ height = new Array(n); height.fill(0); graph = new Array(n); for(let i=0;i<graph.length;i++) { graph[i] = []; }} // TestCase1intializeGraph(17);addChild(0, 1);addChild(0, 2);addChild(0, 3);addChild(0, 4);addChild(0, 5);addChild(0, 6);addChild(1, 7);addChild(1, 8);addChild(1, 9);addChild(4, 10);addChild(4, 11);addChild(6, 12);addChild(7, 13);addChild(7, 14);addChild(10, 15);addChild(11, 16); document.write("TestCase 1 - Minimum Iteration: " + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase2 intializeGraph(3); addChild(0, 1); addChild(0, 2); document.write("TestCase 2 - Minimum Iteration: " + getMinIteration()); document.write('<br>'); document.write('<br>'); // TestCase3 intializeGraph(1); document.write("TestCase 3 - Minimum Iteration: " + getMinIteration(1)); document.write('<br>'); document.write('<br>'); // // TestCase4intializeGraph(6); addChild(0, 1); addChild(1, 2); addChild(2, 3); addChild(3, 4); addChild(4, 5); document.write("TestCase 4 - Minimum Iteration: " + getMinIteration()); document.write('<br>'); document.write('<br>'); // TestCase 5 intializeGraph(6); addChild(0, 1); addChild(0, 2); addChild(2, 3); addChild(2, 4); addChild(2, 5); document.write("TestCase 5 - Minimum Iteration: " + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 6 intializeGraph(6); addChild(0, 1); addChild(0, 2); addChild(2, 3); addChild(2, 4); addChild(3, 5); document.write("TestCase 6 - Minimum Iteration: " + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 7 intializeGraph(14); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(1, 4); addChild(2, 5); addChild(2, 6); addChild(4, 7); addChild(5, 8); addChild(5, 9); addChild(7, 10); addChild(8, 11); addChild(8, 12); addChild(10, 13); document.write("TestCase 7 - Minimum Iteration: " + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 8 intializeGraph(14); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(0, 4); addChild(0, 5); addChild(1, 6); addChild(2, 7); addChild(3, 8); addChild(4, 9); addChild(6, 10); addChild(7, 11); addChild(8, 12); addChild(9, 13); document.write("TestCase 8 - Minimum Iteration: " + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 9 intializeGraph(25); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(0, 4); addChild(0, 5); addChild(0, 6); addChild(1, 7); addChild(2, 8); addChild(3, 9); addChild(4, 10); addChild(5, 11); addChild(6, 12); addChild(7, 13); addChild(8, 14); addChild(9, 15); addChild(10, 16); addChild(11, 17); addChild(12, 18); addChild(13, 19); addChild(14, 20); addChild(15, 21); addChild(16, 22); addChild(17, 23); addChild(19, 24); document.write("TestCase 9 - Minimum Iteration: " + getMinIteration(25));document.write('<br>');document.write('<br>'); //this code is contributed by gaurav2146 </script>
Output:
TestCase 1 - Minimum Iteration: 6
TestCase 2 - Minimum Iteration: 2
TestCase 3 - Minimum Iteration: 0
TestCase 4 - Minimum Iteration: 5
TestCase 5 - Minimum Iteration: 4
TestCase 6 - Minimum Iteration: 3
TestCase 7 - Minimum Iteration: 6
TestCase 8 - Minimum Iteration: 6
TestCase 9 - Minimum Iteration: 8
This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
MitaliSrivastava
aashish1995
gaurav2146
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Write a Program to Find the Maximum Depth or Height of a Tree
Decision Tree
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 35768,
"s": 35740,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 36536,
"s": 35768,
"text": "Given a very large n-ary tree. Where the root node has some information which it wants to pass to all of its children down to the leaves with the constraint that it can only pass the information to one of its children at a time (take it as one iteration). Now in the next iteration the child node can transfer that information to only one of its children and at the same time instance the child’s parent i.e. root can pass the info to one of its remaining children. Continuing in this way we have to find the minimum no of iterations required to pass the information to all nodes in the tree.Minimum no of iterations for tree below is 6. The root A first passes information to B. In next iteration, A passes information to E and B passes information to H and so on. "
},
{
"code": null,
"e": 40332,
"s": 36536,
"text": "We strongly recommend to minimize the browser and try this yourself first.This can be done using Post Order Traversal. The idea is to consider height and children count on each and every node. If a child node i takes ci iterations to pass info below its subtree, then its parent will take (ci + 1) iterations to pass info to subtree rooted at that child i. If parent has more children, it will pass info to them in subsequent iterations. Let’s say children of a parent takes c1, c2, c3, c4, ..., cn iterations to pass info in their own subtree, Now parent has to pass info to these n children one by one in n iterations. If parent picks child i in ith iteration, then parent will take (i + ci) iterations to pass info to child i and all it’s subtree. In any iteration, when parent passes info a child i+1, children (1 to i) which got info from parent already in previous iterations, will pass info to further down in subsequent iterations, if any child (1 to i) has its own child further down. To pass info to whole tree in minimum iterations, it needs to be made sure that bandwidth is utilized as efficiently as possible (i.e. maximum passable no of nodes should pass info further down in any iteration) The best possible scenario would be that in nth iteration, n different nodes pass info to their child. Nodes with height = 0: (Trivial case) Leaf node has no children (no information passing needed), so no of iterations would be ZERO. Nodes with height = 1: Here node has to pass info to all the children one by one (all children are leaf node, so no more information passing further down). Since all children are leaf, node can pass info to any child in any order (pick any child who didn’t receive the info yet). One iteration needed for each child and so no of iterations would be no of children.So node with height 1 with n children will take n iterations. Take a counter initialized with ZERO, loop through all children and keep incrementing counter. Nodes with height > 1: Let’s assume that there are n children (1 to n) of a node and minimum no iterations for all n children are c1, c2, ...., cn. To make sure maximum no of nodes participate in info passing in any iteration, parent should 1st pass info to that child who will take maximum iteration to pass info further down in subsequent iterations. i.e. in any iteration, parent should choose the child who takes maximum iteration later on. It can be thought of as a greedy approach where parent choose that child 1st, who needs maximum no of iterations so that all subsequent iterations can be utilized efficiently. If parent goes in any other fashion, then in the end, there could be some nodes which are done quite early, sitting idle and so bandwidth is not utilized efficiently in further iterations. If there are two children i and j with minimum iterations ci and cj where ci > cj, then If parent picks child j 1st then no of iterations needed by parent to pass info to both children and their subtree would be:max (1 + cj, 2 + ci) = 2 + ci If parent picks child i 1st then no of iterations needed by parent to pass info to both children and their subtree would be: max(1 + ci, 2 + cj) = 1 + ci (So picking ci gives better result than picking cj)This tells that parent should always choose child i with max ci value in any iteration. SO here greedy approach is: sort all ci values decreasing order, let’s say after sorting, values are c1 > c2 > c3 > .... > cn take a counter c, set c = 1 + c1 (for child with maximum no of iterations) for all children i from 2 to n, c = c + 1 + ci then total no of iterations needed by parent is max(n, c)Let minItr(A) be the minimum iteration needed to pass info from node A to it’s all the sub-tree. Let child(A) be the count of all children for node A. So recursive relation would be: "
},
{
"code": null,
"e": 40693,
"s": 40332,
"text": "1. Get minItr(B) of all children (B) of a node (A)\n2. Sort all minItr(B) in descending order\n3. Get minItr of A based on all minItr(B)\n minItr(A) = child(A)\n For children B from i = 0 to child(A)\n minItr(A) = max ( minItr(A), minItr(B) + i + 1)\n\nBase cases would be:\nIf node is leaf, minItr = 0\nIf node's height is 1, minItr = children count "
},
{
"code": null,
"e": 40742,
"s": 40693,
"text": "Following is the implementation of above idea. "
},
{
"code": null,
"e": 40746,
"s": 40742,
"text": "C++"
},
{
"code": null,
"e": 40751,
"s": 40746,
"text": "Java"
},
{
"code": null,
"e": 40754,
"s": 40751,
"text": "C#"
},
{
"code": null,
"e": 40765,
"s": 40754,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number of iterations to pass// information from root to all nodes in an n-ary tree#include<bits/stdc++.h>using namespace std; // A class to represent n-ary tree (Note that the implementation// is similar to graph for simplicity of implementationclass NAryTree{ int N; // No. of nodes in Tree // Pointer to an array containing list of children list<int> *adj; // A function used by getMinIter(), it basically does postorder void getMinIterUtil(int v, int minItr[]);public: NAryTree(int N); // Constructor // function to add a child w to v void addChild(int v, int w); // The main function to find minimum iterations int getMinIter(); static int compare(const void * a, const void * b);}; NAryTree::NAryTree(int N){ this->N = N; adj = new list<int>[N];} // To add a child w to vvoid NAryTree::addChild(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} /* A recursive function to used by getMinIter(). This function// mainly does postorder traversal and get minimum iteration of all children// of node u, sort them in decreasing order and then get minimum iteration// of node u 1. Get minItr(B) of all children (B) of a node (A)2. Sort all minItr(B) in descending order3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max ( minItr(A), minItr(B) + i + 1) Base cases would be:If node is leaf, minItr = 0If node's height is 1, minItr = children count*/ void NAryTree::getMinIterUtil(int u, int minItr[]){ minItr[u] = adj[u].size(); int *minItrTemp = new int[minItr[u]]; int k = 0, tmp = 0; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[u].begin(); i!= adj[u].end(); ++i) { getMinIterUtil(*i, minItr); minItrTemp[k++] = minItr[*i]; } qsort(minItrTemp, minItr[u], sizeof (int), compare); for (k = 0; k < adj[u].size(); k++) { tmp = minItrTemp[k] + k + 1; minItr[u] = max(minItr[u], tmp); } delete[] minItrTemp;} // The function to do PostOrder traversal. It uses// recursive getMinIterUtil()int NAryTree::getMinIter(){ // Set minimum iteration all the vertices as zero int *minItr = new int[N]; int res = -1; for (int i = 0; i < N; i++) minItr[i] = 0; // Start Post Order Traversal from Root getMinIterUtil(0, minItr); res = minItr[0]; delete[] minItr; return res;} int NAryTree::compare(const void * a, const void * b){ return ( *(int*)b - *(int*)a );} // Driver function to test above functionsint main(){ // TestCase 1 NAryTree tree1(17); tree1.addChild(0, 1); tree1.addChild(0, 2); tree1.addChild(0, 3); tree1.addChild(0, 4); tree1.addChild(0, 5); tree1.addChild(0, 6); tree1.addChild(1, 7); tree1.addChild(1, 8); tree1.addChild(1, 9); tree1.addChild(4, 10); tree1.addChild(4, 11); tree1.addChild(6, 12); tree1.addChild(7, 13); tree1.addChild(7, 14); tree1.addChild(10, 15); tree1.addChild(11, 16); cout << \"TestCase 1 - Minimum Iteration: \" << tree1.getMinIter() << endl; // TestCase 2 NAryTree tree2(3); tree2.addChild(0, 1); tree2.addChild(0, 2); cout << \"TestCase 2 - Minimum Iteration: \" << tree2.getMinIter() << endl; // TestCase 3 NAryTree tree3(1); cout << \"TestCase 3 - Minimum Iteration: \" << tree3.getMinIter() << endl; // TestCase 4 NAryTree tree4(6); tree4.addChild(0, 1); tree4.addChild(1, 2); tree4.addChild(2, 3); tree4.addChild(3, 4); tree4.addChild(4, 5); cout << \"TestCase 4 - Minimum Iteration: \" << tree4.getMinIter() << endl; // TestCase 5 NAryTree tree5(6); tree5.addChild(0, 1); tree5.addChild(0, 2); tree5.addChild(2, 3); tree5.addChild(2, 4); tree5.addChild(2, 5); cout << \"TestCase 5 - Minimum Iteration: \" << tree5.getMinIter() << endl; // TestCase 6 NAryTree tree6(6); tree6.addChild(0, 1); tree6.addChild(0, 2); tree6.addChild(2, 3); tree6.addChild(2, 4); tree6.addChild(3, 5); cout << \"TestCase 6 - Minimum Iteration: \" << tree6.getMinIter() << endl; // TestCase 7 NAryTree tree7(14); tree7.addChild(0, 1); tree7.addChild(0, 2); tree7.addChild(0, 3); tree7.addChild(1, 4); tree7.addChild(2, 5); tree7.addChild(2, 6); tree7.addChild(4, 7); tree7.addChild(5, 8); tree7.addChild(5, 9); tree7.addChild(7, 10); tree7.addChild(8, 11); tree7.addChild(8, 12); tree7.addChild(10, 13); cout << \"TestCase 7 - Minimum Iteration: \" << tree7.getMinIter() << endl; // TestCase 8 NAryTree tree8(14); tree8.addChild(0, 1); tree8.addChild(0, 2); tree8.addChild(0, 3); tree8.addChild(0, 4); tree8.addChild(0, 5); tree8.addChild(1, 6); tree8.addChild(2, 7); tree8.addChild(3, 8); tree8.addChild(4, 9); tree8.addChild(6, 10); tree8.addChild(7, 11); tree8.addChild(8, 12); tree8.addChild(9, 13); cout << \"TestCase 8 - Minimum Iteration: \" << tree8.getMinIter() << endl; // TestCase 9 NAryTree tree9(25); tree9.addChild(0, 1); tree9.addChild(0, 2); tree9.addChild(0, 3); tree9.addChild(0, 4); tree9.addChild(0, 5); tree9.addChild(0, 6); tree9.addChild(1, 7); tree9.addChild(2, 8); tree9.addChild(3, 9); tree9.addChild(4, 10); tree9.addChild(5, 11); tree9.addChild(6, 12); tree9.addChild(7, 13); tree9.addChild(8, 14); tree9.addChild(9, 15); tree9.addChild(10, 16); tree9.addChild(11, 17); tree9.addChild(12, 18); tree9.addChild(13, 19); tree9.addChild(14, 20); tree9.addChild(15, 21); tree9.addChild(16, 22); tree9.addChild(17, 23); tree9.addChild(19, 24); cout << \"TestCase 9 - Minimum Iteration: \" << tree9.getMinIter() << endl; return 0;}",
"e": 46732,
"s": 40765,
"text": null
},
{
"code": "// Java program to find minimum number of// iterations to pass information from// root to all nodes in an n-ary treeimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Iterator;import java.util.List; class GFG{ // No. of nodes private static int N; // Adjacency list containing // list of children private static List<List<Integer>> adj; GFG(int N) { this.N = N; adj = new ArrayList<>(N); for (int i = 0; i < N; i++) adj.add(new ArrayList<>()); } // function to add a child w to v void addChild(int v, int w) { adj.get(v).add(w); } // Main function to find the // minimum iterations private int getMinIteration() { // Base case : if height = 0 or 1; if (N == 0 || N == 1) return 0; int[] mintItr = new int[N]; // Start Post Order Traversal from Root getMinIterUtil(0, mintItr); return mintItr[0]; } /* A recursive function to used by getMinIter(). This function mainly does postorder traversal and get minimum iteration of all children of parent node, sort them in decreasing order and then get minimum iteration of parent node 1. Get minItr(B) of all children (B) of a node (A) 2. Sort all minItr(B) in descending order 3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max (minItr(A), minItr(B) + i + 1) Base cases would be: If node is leaf, minItr = 0 If node's height is 1, minItr = children count */ private void getMinIterUtil(int u, int[] minItr) { // Base case : Leaf node if (adj.get(u).size() == 0) return; minItr[u] = adj.get(u).size(); Integer[] minItrTemp = new Integer[minItr[u]]; int k = 0; Iterator itr = adj.get(u).iterator(); while (itr.hasNext()) { int currentChild = (int) itr.next(); getMinIterUtil(currentChild, minItr); minItrTemp[k++] = minItr[currentChild]; } Arrays.sort(minItrTemp, Collections.reverseOrder()); for (k = 0; k < adj.get(u).size(); k++) { int temp = minItrTemp[k] + k + 1; minItr[u] = Math.max(minItr[u], temp); } } // Driver Code public static void main(String args[]) { // TestCase1 GFG testCase1 = new GFG(17); testCase1.addChild(0, 1); testCase1.addChild(0, 2); testCase1.addChild(0, 3); testCase1.addChild(0, 4); testCase1.addChild(0, 5); testCase1.addChild(0, 6); testCase1.addChild(1, 7); testCase1.addChild(1, 8); testCase1.addChild(1, 9); testCase1.addChild(4, 10); testCase1.addChild(4, 11); testCase1.addChild(6, 12); testCase1.addChild(7, 13); testCase1.addChild(7, 14); testCase1.addChild(10, 15); testCase1.addChild(11, 16); System.out.println(\"TestCase 1 - Minimum Iteration: \" + testCase1.getMinIteration()); // TestCase2 GFG testCase2 = new GFG(3); testCase2.addChild(0, 1); testCase2.addChild(0, 2); System.out.println(\"TestCase 2 - Minimum Iteration: \" + testCase2.getMinIteration()); // TestCase3 GFG testCase3 = new GFG(1); System.out.println(\"TestCase 3 - Minimum Iteration: \" + testCase3.getMinIteration()); // TestCase4 GFG testCase4 = new GFG(6); testCase4.addChild(0, 1); testCase4.addChild(1, 2); testCase4.addChild(2, 3); testCase4.addChild(3, 4); testCase4.addChild(4, 5); System.out.println(\"TestCase 4 - Minimum Iteration: \" + testCase4.getMinIteration()); // TestCase 5 GFG testCase5 = new GFG(6); testCase5.addChild(0, 1); testCase5.addChild(0, 2); testCase5.addChild(2, 3); testCase5.addChild(2, 4); testCase5.addChild(2, 5); System.out.println(\"TestCase 5 - Minimum Iteration: \" + testCase5.getMinIteration()); // TestCase 6 GFG testCase6 = new GFG(6); testCase6.addChild(0, 1); testCase6.addChild(0, 2); testCase6.addChild(2, 3); testCase6.addChild(2, 4); testCase6.addChild(3, 5); System.out.println(\"TestCase 6 - Minimum Iteration: \" + testCase6.getMinIteration()); // TestCase 7 GFG testCase7 = new GFG(14); testCase7.addChild(0, 1); testCase7.addChild(0, 2); testCase7.addChild(0, 3); testCase7.addChild(1, 4); testCase7.addChild(2, 5); testCase7.addChild(2, 6); testCase7.addChild(4, 7); testCase7.addChild(5, 8); testCase7.addChild(5, 9); testCase7.addChild(7, 10); testCase7.addChild(8, 11); testCase7.addChild(8, 12); testCase7.addChild(10, 13); System.out.println(\"TestCase 7 - Minimum Iteration: \" + testCase7.getMinIteration()); // TestCase 8 GFG testCase8 = new GFG(14); testCase8.addChild(0, 1); testCase8.addChild(0, 2); testCase8.addChild(0, 3); testCase8.addChild(0, 4); testCase8.addChild(0, 5); testCase8.addChild(1, 6); testCase8.addChild(2, 7); testCase8.addChild(3, 8); testCase8.addChild(4, 9); testCase8.addChild(6, 10); testCase8.addChild(7, 11); testCase8.addChild(8, 12); testCase8.addChild(9, 13); System.out.println(\"TestCase 8 - Minimum Iteration: \" + testCase8.getMinIteration()); // TestCase 9 GFG testCase9 = new GFG(25); testCase9.addChild(0, 1); testCase9.addChild(0, 2); testCase9.addChild(0, 3); testCase9.addChild(0, 4); testCase9.addChild(0, 5); testCase9.addChild(0, 6); testCase9.addChild(1, 7); testCase9.addChild(2, 8); testCase9.addChild(3, 9); testCase9.addChild(4, 10); testCase9.addChild(5, 11); testCase9.addChild(6, 12); testCase9.addChild(7, 13); testCase9.addChild(8, 14); testCase9.addChild(9, 15); testCase9.addChild(10, 16); testCase9.addChild(11, 17); testCase9.addChild(12, 18); testCase9.addChild(13, 19); testCase9.addChild(14, 20); testCase9.addChild(15, 21); testCase9.addChild(16, 22); testCase9.addChild(17, 23); testCase9.addChild(19, 24); System.out.println(\"TestCase 9 - Minimum Iteration: \" + testCase9.getMinIteration()); }} // This code is contributed// by MitaliSrivastava",
"e": 53742,
"s": 46732,
"text": null
},
{
"code": "// C# program to find minimum number of// iterations to pass information from// root to all nodes in an n-ary treeusing System;using System.Collections.Generic;class GFG{ // No. of nodes public int N; // Adjacency list containing // list of children static List<List<int>> adj; public GFG(int N) { this.N = N; adj = new List<List<int>>(N); for (int i = 0; i < N; i++) adj.Add(new List<int>()); } // function to add a child w to v void addChild(int v, int w) { adj[v].Add(w); } // Main function to find the // minimum iterations private int getMinIteration() { // Base case : if height = 0 or 1; if (N == 0 || N == 1) return 0; int[] mintItr = new int[N]; // Start Post Order Traversal from Root getMinIterUtil(0, mintItr); return mintItr[0]; } /* A recursive function to used by getMinIter(). This function mainly does postorder traversal and get minimum iteration of all children of parent node, sort them in decreasing order and then get minimum iteration of parent node 1. Get minItr(B) of all children (B) of a node (A) 2. Sort all minItr(B) in descending order 3. Get minItr of A based on all minItr(B) minItr(A) = child(A) -->> child(A) is children count of node A For children B from i = 0 to child(A) minItr(A) = max (minItr(A), minItr(B) + i + 1) Base cases would be: If node is leaf, minItr = 0 If node's height is 1, minItr = children count */ private void getMinIterUtil(int u, int[] minItr) { // Base case : Leaf node if (adj[u].Count == 0) return; minItr[u] = adj[u].Count; int[] minItrTemp = new int[minItr[u]]; int k = 0; // Iterator itr = adj.get(u).iterator(); foreach (int itr in adj[u]) { int currentChild = (int) itr; getMinIterUtil(currentChild, minItr); minItrTemp[k++] = minItr[currentChild]; } Array.Sort(minItrTemp); for(int i =0, j = minItrTemp.Length-1; i<j;i++,j--){ int temp = minItrTemp[i]; minItrTemp[i] = minItrTemp[j]; minItrTemp[j] = temp; } for (k = 0; k < adj[u].Count; k++) { int temp = minItrTemp[k] + k + 1; minItr[u] = Math.Max(minItr[u], temp); } } // Driver Code public static void Main(String []args) { // TestCase1 GFG testCase1 = new GFG(17); testCase1.addChild(0, 1); testCase1.addChild(0, 2); testCase1.addChild(0, 3); testCase1.addChild(0, 4); testCase1.addChild(0, 5); testCase1.addChild(0, 6); testCase1.addChild(1, 7); testCase1.addChild(1, 8); testCase1.addChild(1, 9); testCase1.addChild(4, 10); testCase1.addChild(4, 11); testCase1.addChild(6, 12); testCase1.addChild(7, 13); testCase1.addChild(7, 14); testCase1.addChild(10, 15); testCase1.addChild(11, 16); Console.WriteLine(\"TestCase 1 - Minimum Iteration: \" + testCase1.getMinIteration()); // TestCase2 GFG testCase2 = new GFG(3); testCase2.addChild(0, 1); testCase2.addChild(0, 2); Console.WriteLine(\"TestCase 2 - Minimum Iteration: \" + testCase2.getMinIteration()); // TestCase3 GFG testCase3 = new GFG(1); Console.WriteLine(\"TestCase 3 - Minimum Iteration: \" + testCase3.getMinIteration()); // TestCase4 GFG testCase4 = new GFG(6); testCase4.addChild(0, 1); testCase4.addChild(1, 2); testCase4.addChild(2, 3); testCase4.addChild(3, 4); testCase4.addChild(4, 5); Console.WriteLine(\"TestCase 4 - Minimum Iteration: \" + testCase4.getMinIteration()); // TestCase 5 GFG testCase5 = new GFG(6); testCase5.addChild(0, 1); testCase5.addChild(0, 2); testCase5.addChild(2, 3); testCase5.addChild(2, 4); testCase5.addChild(2, 5); Console.WriteLine(\"TestCase 5 - Minimum Iteration: \" + testCase5.getMinIteration()); // TestCase 6 GFG testCase6 = new GFG(6); testCase6.addChild(0, 1); testCase6.addChild(0, 2); testCase6.addChild(2, 3); testCase6.addChild(2, 4); testCase6.addChild(3, 5); Console.WriteLine(\"TestCase 6 - Minimum Iteration: \" + testCase6.getMinIteration()); // TestCase 7 GFG testCase7 = new GFG(14); testCase7.addChild(0, 1); testCase7.addChild(0, 2); testCase7.addChild(0, 3); testCase7.addChild(1, 4); testCase7.addChild(2, 5); testCase7.addChild(2, 6); testCase7.addChild(4, 7); testCase7.addChild(5, 8); testCase7.addChild(5, 9); testCase7.addChild(7, 10); testCase7.addChild(8, 11); testCase7.addChild(8, 12); testCase7.addChild(10, 13); Console.WriteLine(\"TestCase 7 - Minimum Iteration: \" + testCase7.getMinIteration()); // TestCase 8 GFG testCase8 = new GFG(14); testCase8.addChild(0, 1); testCase8.addChild(0, 2); testCase8.addChild(0, 3); testCase8.addChild(0, 4); testCase8.addChild(0, 5); testCase8.addChild(1, 6); testCase8.addChild(2, 7); testCase8.addChild(3, 8); testCase8.addChild(4, 9); testCase8.addChild(6, 10); testCase8.addChild(7, 11); testCase8.addChild(8, 12); testCase8.addChild(9, 13); Console.WriteLine(\"TestCase 8 - Minimum Iteration: \" + testCase8.getMinIteration()); // TestCase 9 GFG testCase9 = new GFG(25); testCase9.addChild(0, 1); testCase9.addChild(0, 2); testCase9.addChild(0, 3); testCase9.addChild(0, 4); testCase9.addChild(0, 5); testCase9.addChild(0, 6); testCase9.addChild(1, 7); testCase9.addChild(2, 8); testCase9.addChild(3, 9); testCase9.addChild(4, 10); testCase9.addChild(5, 11); testCase9.addChild(6, 12); testCase9.addChild(7, 13); testCase9.addChild(8, 14); testCase9.addChild(9, 15); testCase9.addChild(10, 16); testCase9.addChild(11, 17); testCase9.addChild(12, 18); testCase9.addChild(13, 19); testCase9.addChild(14, 20); testCase9.addChild(15, 21); testCase9.addChild(16, 22); testCase9.addChild(17, 23); testCase9.addChild(19, 24); Console.WriteLine(\"TestCase 9 - Minimum Iteration: \" + testCase9.getMinIteration()); }} // This code is contributed by aashish1995",
"e": 59984,
"s": 53742,
"text": null
},
{
"code": "<script> var height;var graph; function findHeight(node , h){ height[node] = h; for(let i=0;i<graph[node].length;i++) { let v = graph[node][i]; findHeight(v , h + 1); }} function getMinIteration(){ findHeight(0 , 0); let max_height = 0; for(let i=0;i<height.length;i++) { if(height[i] > max_height) { max_height = height[i]; } } for(let i=0;i<height.length;i++) { height[i] = max_height - height[i]; } return getMinIterationUtil(0);} function getMinIterationUtil(node){ if(height[node] == 0 ) { return 0; } if(height[node] == 1 ) { return graph[node].length; } let edges =[...graph[node] ]; let edgeLenArr = []; for(let i=0;i<edges.length;i++ ) { edgeLenArr.push( graph[ graph[node][i] ].length ); } for (let i = 0; i < edgeLenArr.length - 1; i++) { for (let j = i + 1; j < edgeLenArr.length; j++) { if(edgeLenArr[i] < edgeLenArr[j]) { let temp = edgeLenArr[i]; edgeLenArr[i] = edgeLenArr[j]; edgeLenArr[j] = temp; let temp1 = edges[i]; edges[i] = edges[j]; edges[j] = temp1; } } } let max_data = edges.length; for(let i=0;i<edges.length;i++) { max_data = Math.max( max_data , i + 1 + getMinIterationUtil(edges[i])); } return max_data;} function addChild(a , b){ graph[a].push(b);} function intializeGraph(n){ height = new Array(n); height.fill(0); graph = new Array(n); for(let i=0;i<graph.length;i++) { graph[i] = []; }} // TestCase1intializeGraph(17);addChild(0, 1);addChild(0, 2);addChild(0, 3);addChild(0, 4);addChild(0, 5);addChild(0, 6);addChild(1, 7);addChild(1, 8);addChild(1, 9);addChild(4, 10);addChild(4, 11);addChild(6, 12);addChild(7, 13);addChild(7, 14);addChild(10, 15);addChild(11, 16); document.write(\"TestCase 1 - Minimum Iteration: \" + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase2 intializeGraph(3); addChild(0, 1); addChild(0, 2); document.write(\"TestCase 2 - Minimum Iteration: \" + getMinIteration()); document.write('<br>'); document.write('<br>'); // TestCase3 intializeGraph(1); document.write(\"TestCase 3 - Minimum Iteration: \" + getMinIteration(1)); document.write('<br>'); document.write('<br>'); // // TestCase4intializeGraph(6); addChild(0, 1); addChild(1, 2); addChild(2, 3); addChild(3, 4); addChild(4, 5); document.write(\"TestCase 4 - Minimum Iteration: \" + getMinIteration()); document.write('<br>'); document.write('<br>'); // TestCase 5 intializeGraph(6); addChild(0, 1); addChild(0, 2); addChild(2, 3); addChild(2, 4); addChild(2, 5); document.write(\"TestCase 5 - Minimum Iteration: \" + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 6 intializeGraph(6); addChild(0, 1); addChild(0, 2); addChild(2, 3); addChild(2, 4); addChild(3, 5); document.write(\"TestCase 6 - Minimum Iteration: \" + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 7 intializeGraph(14); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(1, 4); addChild(2, 5); addChild(2, 6); addChild(4, 7); addChild(5, 8); addChild(5, 9); addChild(7, 10); addChild(8, 11); addChild(8, 12); addChild(10, 13); document.write(\"TestCase 7 - Minimum Iteration: \" + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 8 intializeGraph(14); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(0, 4); addChild(0, 5); addChild(1, 6); addChild(2, 7); addChild(3, 8); addChild(4, 9); addChild(6, 10); addChild(7, 11); addChild(8, 12); addChild(9, 13); document.write(\"TestCase 8 - Minimum Iteration: \" + getMinIteration());document.write('<br>');document.write('<br>'); // TestCase 9 intializeGraph(25); addChild(0, 1); addChild(0, 2); addChild(0, 3); addChild(0, 4); addChild(0, 5); addChild(0, 6); addChild(1, 7); addChild(2, 8); addChild(3, 9); addChild(4, 10); addChild(5, 11); addChild(6, 12); addChild(7, 13); addChild(8, 14); addChild(9, 15); addChild(10, 16); addChild(11, 17); addChild(12, 18); addChild(13, 19); addChild(14, 20); addChild(15, 21); addChild(16, 22); addChild(17, 23); addChild(19, 24); document.write(\"TestCase 9 - Minimum Iteration: \" + getMinIteration(25));document.write('<br>');document.write('<br>'); //this code is contributed by gaurav2146 </script>",
"e": 64442,
"s": 59984,
"text": null
},
{
"code": null,
"e": 64452,
"s": 64442,
"text": "Output: "
},
{
"code": null,
"e": 64758,
"s": 64452,
"text": "TestCase 1 - Minimum Iteration: 6\nTestCase 2 - Minimum Iteration: 2\nTestCase 3 - Minimum Iteration: 0\nTestCase 4 - Minimum Iteration: 5\nTestCase 5 - Minimum Iteration: 4\nTestCase 6 - Minimum Iteration: 3\nTestCase 7 - Minimum Iteration: 6\nTestCase 8 - Minimum Iteration: 6\nTestCase 9 - Minimum Iteration: 8"
},
{
"code": null,
"e": 64929,
"s": 64758,
"text": "This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 64946,
"s": 64929,
"text": "MitaliSrivastava"
},
{
"code": null,
"e": 64958,
"s": 64946,
"text": "aashish1995"
},
{
"code": null,
"e": 64969,
"s": 64958,
"text": "gaurav2146"
},
{
"code": null,
"e": 64974,
"s": 64969,
"text": "Tree"
},
{
"code": null,
"e": 64979,
"s": 64974,
"text": "Tree"
},
{
"code": null,
"e": 65077,
"s": 64979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 65086,
"s": 65077,
"text": "Comments"
},
{
"code": null,
"e": 65099,
"s": 65086,
"text": "Old Comments"
},
{
"code": null,
"e": 65149,
"s": 65099,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 65184,
"s": 65149,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 65218,
"s": 65184,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 65247,
"s": 65218,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 65288,
"s": 65247,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 65331,
"s": 65288,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 65364,
"s": 65331,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 65426,
"s": 65364,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 65440,
"s": 65426,
"text": "Decision Tree"
}
] |
Explain the positions property in CSS - GeeksforGeeks
|
29 Sep, 2021
In this article, we will see what is position property, how to use this property wisely in order to make web pages. The position property is used to align the different elements in the HTML page. Position Property plays an important role to make high-quality web pages.
There are 5 position properties in CSS:
static (default)
relative
absolute
fixed
sticky
Syntax:
selector{
position: value;
}
value = static, relative, absolute, fixed, sticky
Let’s understand each of these properties one by one.
1. position: static It is the default position value for the element. Under static position, elements positioned according to the normal flow of the page.
Note: left, right, top, and bottom properties will not affect if position is static.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: static; font-size: 1.5rem; padding: 10px; height: 200px; width: 200px; background-color: cyan; } </style></head> <body> <div class="purple"> I am reference </div> <div class="cyan"> I am static element </div></body> </html>
Output:
2. Position: Relative In this case, the element remains in the normal flow of the document but left, right, top, and bottom affects. Elements get shifted from their original position in the document creating vacant space and other elements may adjust themselves according to the vacant space left by the element.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: relative; left: 100px; top: 90px; font-size: 1.5rem; padding: 10px; height: 200px; width: 200px; background-color: cyan; } </style></head> <body> <div class="purple"> I am reference </div> <div class="cyan"> I am relative element </div></body> </html>
Output:
Explanation: We can see here element change its left and top from the original position creating some space.
3. position: absolute Absolute elements do not follow the normal flow document instead they position themselves relative to the closest positioned ancestor. Its final position is determined using the top, bottom, left and right.
Note: The positioned element means element having position property other than static.
These element does not occupy any space and other elements treats absolute elements like there is no element. Parent element should be positioned and position property other than absolute and If parent element is not positioned then absolute element position themselves according to nearest positioned ancestor. We generally set z-index when using absolute position.
Consider Two cases to understand absolute position:
1st case: When parent property value is positioned means position property of parent is not equal to static.
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { position: relative; height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: absolute; bottom: 10px; left: 70px; font-size: 1.5rem; padding: 10px; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class="purple"> I am positioned and parent <div class="cyan"> I am absolute element </div> </div></body> </html>
Output:
Explanation: Here we can see child element has adjusted itself according to parent and no extra space is assign to it.
2nd Case: When parent element is not positioned.
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { position: static; height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: absolute; bottom: 10px; left: 70px; font-size: 1.5rem; padding: 10px; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class="purple"> I am not-positioned and parent <div class="cyan"> I am absolute element </div> </div></body> </html>
Output:
Explanation: As the parent is not positioned, the child element will try to adjust itself relative to nearest positioned ancestor. Here nearest positioned ancestor is <HTML> so element gets adjust according to <HTML>.
4. position: Fixed Fixed element does not follow normal document flow and position themselves relative to <HTML> tag. This element always stick to the screen.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { position: relative; height: 2000px; width: 200px; color: black; font-size: 1.5rem; font-family: sans-serif; padding: 10px; background-color: purple; } .cyan { position: fixed; top: 200px; left: 10px; padding: 10px; font-size: 1rem; color: black; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class="purple"> I am reference <div class="cyan"> I am fixed element </div> </div></body> </html>
Output:
You can see the fixed element remain at its position even after scrolling up and down.
5. position: sticky It’s kind of little tricky but very easy to understand. We can think of sticky as combination of relative and fixed. Remember in fixed element remain fixed at some position but in sticky element will behave like relative to certain point and after behave like fixed.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> .purple { position: absolute; height: 2000px; width: 200px; color: black; font-size: 1.5rem; font-family: sans-serif; padding: 10px; background-color: purple; } .cyan { position: sticky; top: 10px; left: 0px; padding: 10px; font-size: 1rem; color: black; height: 100px; width: 100px; background-color: cyan; z-index: 2; } .yellow { padding: 10px; position: relative; height: 100px; width: 100px; background-color: yellow; } </style></head> <body> <div class="purple"> <div class="yellow">I am reference</div> <div class="cyan"> I am sticky element </div> <div class="yellow">I am reference</div> </div></body> </html>
Output:
Explanation: In the above output, you can see the sticky element behaves like a relative element until it reaches a particular offset. Then beyond that point, it sticks to the page and behaves like fixed (here that offset is 10px from top).
Note: In sticky left, right, top and bottom does not determine the position of the element in the relative state but it specifies at what position element should behave like fixed.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set input type date in dd-mm-yyyy format using HTML ?
Form validation using HTML and JavaScript
HTML | <img> align Attribute
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 25255,
"s": 24985,
"text": "In this article, we will see what is position property, how to use this property wisely in order to make web pages. The position property is used to align the different elements in the HTML page. Position Property plays an important role to make high-quality web pages."
},
{
"code": null,
"e": 25295,
"s": 25255,
"text": "There are 5 position properties in CSS:"
},
{
"code": null,
"e": 25312,
"s": 25295,
"text": "static (default)"
},
{
"code": null,
"e": 25321,
"s": 25312,
"text": "relative"
},
{
"code": null,
"e": 25330,
"s": 25321,
"text": "absolute"
},
{
"code": null,
"e": 25336,
"s": 25330,
"text": "fixed"
},
{
"code": null,
"e": 25343,
"s": 25336,
"text": "sticky"
},
{
"code": null,
"e": 25351,
"s": 25343,
"text": "Syntax:"
},
{
"code": null,
"e": 25434,
"s": 25351,
"text": "selector{\n position: value;\n}\nvalue = static, relative, absolute, fixed, sticky"
},
{
"code": null,
"e": 25488,
"s": 25434,
"text": "Let’s understand each of these properties one by one."
},
{
"code": null,
"e": 25645,
"s": 25490,
"text": "1. position: static It is the default position value for the element. Under static position, elements positioned according to the normal flow of the page."
},
{
"code": null,
"e": 25730,
"s": 25645,
"text": "Note: left, right, top, and bottom properties will not affect if position is static."
},
{
"code": null,
"e": 25739,
"s": 25730,
"text": "Example:"
},
{
"code": null,
"e": 25744,
"s": 25739,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: static; font-size: 1.5rem; padding: 10px; height: 200px; width: 200px; background-color: cyan; } </style></head> <body> <div class=\"purple\"> I am reference </div> <div class=\"cyan\"> I am static element </div></body> </html>",
"e": 26345,
"s": 25744,
"text": null
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Output:"
},
{
"code": null,
"e": 26666,
"s": 26353,
"text": "2. Position: Relative In this case, the element remains in the normal flow of the document but left, right, top, and bottom affects. Elements get shifted from their original position in the document creating vacant space and other elements may adjust themselves according to the vacant space left by the element."
},
{
"code": null,
"e": 26677,
"s": 26668,
"text": "Example:"
},
{
"code": null,
"e": 26682,
"s": 26677,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: relative; left: 100px; top: 90px; font-size: 1.5rem; padding: 10px; height: 200px; width: 200px; background-color: cyan; } </style></head> <body> <div class=\"purple\"> I am reference </div> <div class=\"cyan\"> I am relative element </div></body> </html>",
"e": 27313,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27321,
"s": 27313,
"text": "Output:"
},
{
"code": null,
"e": 27430,
"s": 27321,
"text": "Explanation: We can see here element change its left and top from the original position creating some space."
},
{
"code": null,
"e": 27660,
"s": 27430,
"text": "3. position: absolute Absolute elements do not follow the normal flow document instead they position themselves relative to the closest positioned ancestor. Its final position is determined using the top, bottom, left and right."
},
{
"code": null,
"e": 27747,
"s": 27660,
"text": "Note: The positioned element means element having position property other than static."
},
{
"code": null,
"e": 28114,
"s": 27747,
"text": "These element does not occupy any space and other elements treats absolute elements like there is no element. Parent element should be positioned and position property other than absolute and If parent element is not positioned then absolute element position themselves according to nearest positioned ancestor. We generally set z-index when using absolute position."
},
{
"code": null,
"e": 28168,
"s": 28116,
"text": "Consider Two cases to understand absolute position:"
},
{
"code": null,
"e": 28277,
"s": 28168,
"text": "1st case: When parent property value is positioned means position property of parent is not equal to static."
},
{
"code": null,
"e": 28282,
"s": 28277,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { position: relative; height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: absolute; bottom: 10px; left: 70px; font-size: 1.5rem; padding: 10px; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class=\"purple\"> I am positioned and parent <div class=\"cyan\"> I am absolute element </div> </div></body> </html>",
"e": 28972,
"s": 28282,
"text": null
},
{
"code": null,
"e": 28980,
"s": 28972,
"text": "Output:"
},
{
"code": null,
"e": 29099,
"s": 28980,
"text": "Explanation: Here we can see child element has adjusted itself according to parent and no extra space is assign to it."
},
{
"code": null,
"e": 29148,
"s": 29099,
"text": "2nd Case: When parent element is not positioned."
},
{
"code": null,
"e": 29153,
"s": 29148,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { position: static; height: 200px; width: 200px; color: black; font-size: 1.5rem; padding: 10px; background-color: purple; } .cyan { position: absolute; bottom: 10px; left: 70px; font-size: 1.5rem; padding: 10px; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class=\"purple\"> I am not-positioned and parent <div class=\"cyan\"> I am absolute element </div> </div></body> </html>",
"e": 29845,
"s": 29153,
"text": null
},
{
"code": null,
"e": 29853,
"s": 29845,
"text": "Output:"
},
{
"code": null,
"e": 30071,
"s": 29853,
"text": "Explanation: As the parent is not positioned, the child element will try to adjust itself relative to nearest positioned ancestor. Here nearest positioned ancestor is <HTML> so element gets adjust according to <HTML>."
},
{
"code": null,
"e": 30230,
"s": 30071,
"text": "4. position: Fixed Fixed element does not follow normal document flow and position themselves relative to <HTML> tag. This element always stick to the screen."
},
{
"code": null,
"e": 30241,
"s": 30232,
"text": "Example:"
},
{
"code": null,
"e": 30246,
"s": 30241,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { position: relative; height: 2000px; width: 200px; color: black; font-size: 1.5rem; font-family: sans-serif; padding: 10px; background-color: purple; } .cyan { position: fixed; top: 200px; left: 10px; padding: 10px; font-size: 1rem; color: black; height: 100px; width: 100px; background-color: cyan; } </style></head> <body> <div class=\"purple\"> I am reference <div class=\"cyan\"> I am fixed element </div> </div></body> </html>",
"e": 30994,
"s": 30246,
"text": null
},
{
"code": null,
"e": 31002,
"s": 30994,
"text": "Output:"
},
{
"code": null,
"e": 31090,
"s": 31002,
"text": "You can see the fixed element remain at its position even after scrolling up and down. "
},
{
"code": null,
"e": 31377,
"s": 31090,
"text": "5. position: sticky It’s kind of little tricky but very easy to understand. We can think of sticky as combination of relative and fixed. Remember in fixed element remain fixed at some position but in sticky element will behave like relative to certain point and after behave like fixed."
},
{
"code": null,
"e": 31386,
"s": 31377,
"text": "Example:"
},
{
"code": null,
"e": 31391,
"s": 31386,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .purple { position: absolute; height: 2000px; width: 200px; color: black; font-size: 1.5rem; font-family: sans-serif; padding: 10px; background-color: purple; } .cyan { position: sticky; top: 10px; left: 0px; padding: 10px; font-size: 1rem; color: black; height: 100px; width: 100px; background-color: cyan; z-index: 2; } .yellow { padding: 10px; position: relative; height: 100px; width: 100px; background-color: yellow; } </style></head> <body> <div class=\"purple\"> <div class=\"yellow\">I am reference</div> <div class=\"cyan\"> I am sticky element </div> <div class=\"yellow\">I am reference</div> </div></body> </html>",
"e": 32409,
"s": 31391,
"text": null
},
{
"code": null,
"e": 32417,
"s": 32409,
"text": "Output:"
},
{
"code": null,
"e": 32658,
"s": 32417,
"text": "Explanation: In the above output, you can see the sticky element behaves like a relative element until it reaches a particular offset. Then beyond that point, it sticks to the page and behaves like fixed (here that offset is 10px from top)."
},
{
"code": null,
"e": 32839,
"s": 32658,
"text": "Note: In sticky left, right, top and bottom does not determine the position of the element in the relative state but it specifies at what position element should behave like fixed."
},
{
"code": null,
"e": 32976,
"s": 32839,
"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": 32991,
"s": 32976,
"text": "CSS-Properties"
},
{
"code": null,
"e": 33005,
"s": 32991,
"text": "CSS-Questions"
},
{
"code": null,
"e": 33020,
"s": 33005,
"text": "HTML-Questions"
},
{
"code": null,
"e": 33027,
"s": 33020,
"text": "Picked"
},
{
"code": null,
"e": 33031,
"s": 33027,
"text": "CSS"
},
{
"code": null,
"e": 33036,
"s": 33031,
"text": "HTML"
},
{
"code": null,
"e": 33053,
"s": 33036,
"text": "Web Technologies"
},
{
"code": null,
"e": 33058,
"s": 33053,
"text": "HTML"
},
{
"code": null,
"e": 33156,
"s": 33058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33165,
"s": 33156,
"text": "Comments"
},
{
"code": null,
"e": 33178,
"s": 33165,
"text": "Old Comments"
},
{
"code": null,
"e": 33215,
"s": 33178,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33244,
"s": 33215,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 33283,
"s": 33244,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 33325,
"s": 33283,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 33360,
"s": 33325,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 33421,
"s": 33360,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 33463,
"s": 33421,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 33492,
"s": 33463,
"text": "HTML | <img> align Attribute"
}
] |
Matplotlib.pyplot.specgram() in Python
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The specgram() function in pyplot module of matplotlib library is used to plot a spectrogram.
Syntax: matplotlib.pyplot.specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is a sequence of data.
Fs : This parameter is a scalar. Its default value is 2.
window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()
sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’.
pad_to : This parameter contains the integer value to which the data segment is padded.
Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0
NFFT : This parameter contains the number of data points used in each block for the FFT.
detrend : This parameter contains the function applied to each segment before fft-ing, designed to remove the mean or linear trend {‘none’, ‘mean’, ‘linear’}.
scale_by_freq : This parameter is allows for integration over the returned frequency values.
mode : This parameter is that what sort of spectrum to use {‘default’, ‘psd’, ‘magnitude’, ‘angle’, ‘phase’}.
noverlap : This parameter is the number of points of overlap between blocks.
scale : This parameter contains the scaling of the values in the spec {‘default’, ‘linear’, ‘dB’}.
Fc : This parameter is the center frequency of x.
camp: This parameter is a matplotlib.colors.Colormap instance.
Returns: This returns the following:
spectrum :This returns the angle spectrum in radians.
freqs :This returns the frequencies corresponding to the elements in spectrum.
t: This returns the times corresponding to midpoints of segments.
im: This returns the image created by imshow containing the spectrogram.
The resultant is (spectrum, freqs, t, im)
Below examples illustrate the matplotlib.pyplot.specgram() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt import numpy as np dt = 0.005t = np.arange(0.0, 20.0, dt) x = np.sin(np.pi * t) + 1.5 * np.cos(np.pi * 2*t) plt.specgram(x, Fs = 1)plt.title('matplotlib.pyplot.specgram() Example\n', fontsize = 14, fontweight ='bold') plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt import numpy as np np.random.seed(9360801) dt = 0.0005t = np.arange(0.0, 20.0, dt) s1 = np.sin(4 * np.pi * 100 * t) s2 = 1.5 * np.sin(1.5 * np.pi * 400 * t) s2[t <= 10] = s2[12 <= t] = 0 nse = 0.2 * np.random.random(size = len(t)) x = s1 + s2 + nse NFFT = 512 Fs = int(1.0 / dt) plt.specgram(x, Fs = Fs, cmap = plt.cm.bone) plt.title('matplotlib.pyplot.specgram() Example\n', fontsize = 14, fontweight ='bold') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 317,
"s": 223,
"text": "The specgram() function in pyplot module of matplotlib library is used to plot a spectrogram."
},
{
"code": null,
"e": 565,
"s": 317,
"text": "Syntax: matplotlib.pyplot.specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, *, data=None, **kwargs)"
},
{
"code": null,
"e": 647,
"s": 565,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 688,
"s": 647,
"text": "x: This parameter is a sequence of data."
},
{
"code": null,
"e": 745,
"s": 688,
"text": "Fs : This parameter is a scalar. Its default value is 2."
},
{
"code": null,
"e": 889,
"s": 745,
"text": "window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()"
},
{
"code": null,
"e": 1031,
"s": 889,
"text": "sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’."
},
{
"code": null,
"e": 1119,
"s": 1031,
"text": "pad_to : This parameter contains the integer value to which the data segment is padded."
},
{
"code": null,
"e": 1265,
"s": 1119,
"text": "Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0"
},
{
"code": null,
"e": 1354,
"s": 1265,
"text": "NFFT : This parameter contains the number of data points used in each block for the FFT."
},
{
"code": null,
"e": 1513,
"s": 1354,
"text": "detrend : This parameter contains the function applied to each segment before fft-ing, designed to remove the mean or linear trend {‘none’, ‘mean’, ‘linear’}."
},
{
"code": null,
"e": 1606,
"s": 1513,
"text": "scale_by_freq : This parameter is allows for integration over the returned frequency values."
},
{
"code": null,
"e": 1716,
"s": 1606,
"text": "mode : This parameter is that what sort of spectrum to use {‘default’, ‘psd’, ‘magnitude’, ‘angle’, ‘phase’}."
},
{
"code": null,
"e": 1793,
"s": 1716,
"text": "noverlap : This parameter is the number of points of overlap between blocks."
},
{
"code": null,
"e": 1892,
"s": 1793,
"text": "scale : This parameter contains the scaling of the values in the spec {‘default’, ‘linear’, ‘dB’}."
},
{
"code": null,
"e": 1942,
"s": 1892,
"text": "Fc : This parameter is the center frequency of x."
},
{
"code": null,
"e": 2005,
"s": 1942,
"text": "camp: This parameter is a matplotlib.colors.Colormap instance."
},
{
"code": null,
"e": 2042,
"s": 2005,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 2096,
"s": 2042,
"text": "spectrum :This returns the angle spectrum in radians."
},
{
"code": null,
"e": 2175,
"s": 2096,
"text": "freqs :This returns the frequencies corresponding to the elements in spectrum."
},
{
"code": null,
"e": 2241,
"s": 2175,
"text": "t: This returns the times corresponding to midpoints of segments."
},
{
"code": null,
"e": 2314,
"s": 2241,
"text": "im: This returns the image created by imshow containing the spectrogram."
},
{
"code": null,
"e": 2356,
"s": 2314,
"text": "The resultant is (spectrum, freqs, t, im)"
},
{
"code": null,
"e": 2446,
"s": 2356,
"text": "Below examples illustrate the matplotlib.pyplot.specgram() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 2457,
"s": 2446,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt import numpy as np dt = 0.005t = np.arange(0.0, 20.0, dt) x = np.sin(np.pi * t) + 1.5 * np.cos(np.pi * 2*t) plt.specgram(x, Fs = 1)plt.title('matplotlib.pyplot.specgram() Example\\n', fontsize = 14, fontweight ='bold') plt.show()",
"e": 2776,
"s": 2457,
"text": null
},
{
"code": null,
"e": 2784,
"s": 2776,
"text": "Output:"
},
{
"code": null,
"e": 2795,
"s": 2784,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt import numpy as np np.random.seed(9360801) dt = 0.0005t = np.arange(0.0, 20.0, dt) s1 = np.sin(4 * np.pi * 100 * t) s2 = 1.5 * np.sin(1.5 * np.pi * 400 * t) s2[t <= 10] = s2[12 <= t] = 0 nse = 0.2 * np.random.random(size = len(t)) x = s1 + s2 + nse NFFT = 512 Fs = int(1.0 / dt) plt.specgram(x, Fs = Fs, cmap = plt.cm.bone) plt.title('matplotlib.pyplot.specgram() Example\\n', fontsize = 14, fontweight ='bold') plt.show()",
"e": 3322,
"s": 2795,
"text": null
},
{
"code": null,
"e": 3330,
"s": 3322,
"text": "Output:"
},
{
"code": null,
"e": 3348,
"s": 3330,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3355,
"s": 3348,
"text": "Python"
},
{
"code": null,
"e": 3453,
"s": 3355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3471,
"s": 3453,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3513,
"s": 3471,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3535,
"s": 3513,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3570,
"s": 3535,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3596,
"s": 3570,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3628,
"s": 3596,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3657,
"s": 3628,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3684,
"s": 3657,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3714,
"s": 3684,
"text": "Iterate over a list in Python"
}
] |
Python | Boolean list initialization
|
01 Feb, 2022
Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let’s discuss certain ways in which this can be achieved.
Method #1: Using list comprehension This can easily be done with the naive method, hence, can also be converted into a compact version using list comprehension. This is the most basic way to perform this task.
Python3
# Python3 code to demonstrate# to perform boolean list initializing# using list comprehension # using list comprehension# to perform boolean list initializingres = [True for i in range(6)] # printing resultprint ("The True initialized list is : " + str(res))
The True initialized list is : [True, True, True, True, True, True]
Method #2: Using * operator This can be done using the * operator in a comparatively more readable and compact way. We multiply the single list N no. of times to get the desired result.
Python3
# Python3 code to demonstrate# to perform boolean list initializing# using * operator # using * operator# to perform boolean list initializingres = [True] * 6 # printing resultprint ("The True initialized list is : " + str(res))
The True initialized list is : [True, True, True, True, True, True]
Method #3 : Using bytearray() This method can be used to perform the list initialization, but this argument can only be extended to False value initializations. It doesn’t work when we require to initialize with the True values.
Python3
# Python3 code to demonstrate# to perform boolean list initializing# using bytearray() # using bytearray()# to perform boolean list initializingres = list(bytearray(6)) # printing resultprint ("The False initialized list is : " + str(res))
The False initialized list is : [0, 0, 0, 0, 0, 0]
chhabradhanvi
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 286,
"s": 28,
"text": "Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let’s discuss certain ways in which this can be achieved."
},
{
"code": null,
"e": 496,
"s": 286,
"text": "Method #1: Using list comprehension This can easily be done with the naive method, hence, can also be converted into a compact version using list comprehension. This is the most basic way to perform this task."
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to perform boolean list initializing# using list comprehension # using list comprehension# to perform boolean list initializingres = [True for i in range(6)] # printing resultprint (\"The True initialized list is : \" + str(res))",
"e": 765,
"s": 504,
"text": null
},
{
"code": null,
"e": 833,
"s": 765,
"text": "The True initialized list is : [True, True, True, True, True, True]"
},
{
"code": null,
"e": 1023,
"s": 835,
"text": " Method #2: Using * operator This can be done using the * operator in a comparatively more readable and compact way. We multiply the single list N no. of times to get the desired result."
},
{
"code": null,
"e": 1031,
"s": 1023,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to perform boolean list initializing# using * operator # using * operator# to perform boolean list initializingres = [True] * 6 # printing resultprint (\"The True initialized list is : \" + str(res))",
"e": 1262,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1330,
"s": 1262,
"text": "The True initialized list is : [True, True, True, True, True, True]"
},
{
"code": null,
"e": 1563,
"s": 1332,
"text": " Method #3 : Using bytearray() This method can be used to perform the list initialization, but this argument can only be extended to False value initializations. It doesn’t work when we require to initialize with the True values."
},
{
"code": null,
"e": 1571,
"s": 1563,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to perform boolean list initializing# using bytearray() # using bytearray()# to perform boolean list initializingres = list(bytearray(6)) # printing resultprint (\"The False initialized list is : \" + str(res))",
"e": 1812,
"s": 1571,
"text": null
},
{
"code": null,
"e": 1863,
"s": 1812,
"text": "The False initialized list is : [0, 0, 0, 0, 0, 0]"
},
{
"code": null,
"e": 1879,
"s": 1865,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1900,
"s": 1879,
"text": "Python list-programs"
},
{
"code": null,
"e": 1907,
"s": 1900,
"text": "Python"
},
{
"code": null,
"e": 1923,
"s": 1907,
"text": "Python Programs"
},
{
"code": null,
"e": 2021,
"s": 1923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2043,
"s": 2021,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2085,
"s": 2043,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2120,
"s": 2085,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2152,
"s": 2120,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2178,
"s": 2152,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2221,
"s": 2178,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2243,
"s": 2221,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2282,
"s": 2243,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2320,
"s": 2282,
"text": "Python | Convert a list to dictionary"
}
] |
verbose_name – Django Built-in Field Validation
|
13 Feb, 2020
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. verbose_name is a human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.
Syntax –
field_name = models.Field(verbose_name = "name")
Illustration of verbose_name using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, )
After running makemigrations and migrate on Django and rendering the above model, let us check the display name for geeks_field.
Now let us modify this using verbose_name attribute. change models.py to
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, verbose_name = "Geeksforgeeks" )
Since models.py is modified run makemigrations and migrate again on the project. Open admin interface and check the name of that field again, it is changes to “Geeksforgeeks”.You can see the modified image. Therefore, verbose_name modifies the field name.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 607,
"s": 53,
"text": "Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. verbose_name is a human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface."
},
{
"code": null,
"e": 616,
"s": 607,
"text": "Syntax –"
},
{
"code": null,
"e": 665,
"s": 616,
"text": "field_name = models.Field(verbose_name = \"name\")"
},
{
"code": null,
"e": 778,
"s": 665,
"text": "Illustration of verbose_name using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 865,
"s": 778,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 916,
"s": 865,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 949,
"s": 916,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1076,
"s": 949,
"text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, )",
"e": 1286,
"s": 1076,
"text": null
},
{
"code": null,
"e": 1415,
"s": 1286,
"text": "After running makemigrations and migrate on Django and rendering the above model, let us check the display name for geeks_field."
},
{
"code": null,
"e": 1488,
"s": 1415,
"text": "Now let us modify this using verbose_name attribute. change models.py to"
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, verbose_name = \"Geeksforgeeks\" )",
"e": 1748,
"s": 1488,
"text": null
},
{
"code": null,
"e": 2004,
"s": 1748,
"text": "Since models.py is modified run makemigrations and migrate again on the project. Open admin interface and check the name of that field again, it is changes to “Geeksforgeeks”.You can see the modified image. Therefore, verbose_name modifies the field name."
},
{
"code": null,
"e": 2016,
"s": 2004,
"text": "NaveenArora"
},
{
"code": null,
"e": 2030,
"s": 2016,
"text": "Django-models"
},
{
"code": null,
"e": 2044,
"s": 2030,
"text": "Python Django"
},
{
"code": null,
"e": 2051,
"s": 2044,
"text": "Python"
}
] |
HTML | <input> pattern Attribute - GeeksforGeeks
|
28 Jun, 2019
The HTML <input> pattern attribute is used to specify the regular expression on which the input elements value is checked against. This attribute works with the following input types: text, password, date, search, email, etc. Use the Global title attribute to describe the pattern for helping the user.
Syntax:
<input pattern = "regular_exp">
Example: This example illustrates the use of pattern attribute in <input> element.
<!DOCTYPE html> <html> <head> <title> HTML input pattern attribute </title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input>pattern attribute</h2> <form action="#"> Password: <input type="text" name="Password" pattern="[A-Za-z]{3}" title="Three letter Password"> <input type="submit"> </form> </body> </html>
Output:
Supported Browsers: The browser supported by HTML <input> pattern attribute are listed below:
Google Chrome 5.0
Internet Explorer 10.0
Firefox 4.0
Safari 10.1
Opera 9.6
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24349,
"s": 24321,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 24652,
"s": 24349,
"text": "The HTML <input> pattern attribute is used to specify the regular expression on which the input elements value is checked against. This attribute works with the following input types: text, password, date, search, email, etc. Use the Global title attribute to describe the pattern for helping the user."
},
{
"code": null,
"e": 24660,
"s": 24652,
"text": "Syntax:"
},
{
"code": null,
"e": 24692,
"s": 24660,
"text": "<input pattern = \"regular_exp\">"
},
{
"code": null,
"e": 24775,
"s": 24692,
"text": "Example: This example illustrates the use of pattern attribute in <input> element."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML input pattern attribute </title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input>pattern attribute</h2> <form action=\"#\"> Password: <input type=\"text\" name=\"Password\" pattern=\"[A-Za-z]{3}\" title=\"Three letter Password\"> <input type=\"submit\"> </form> </body> </html>",
"e": 25424,
"s": 24775,
"text": null
},
{
"code": null,
"e": 25432,
"s": 25424,
"text": "Output:"
},
{
"code": null,
"e": 25526,
"s": 25432,
"text": "Supported Browsers: The browser supported by HTML <input> pattern attribute are listed below:"
},
{
"code": null,
"e": 25544,
"s": 25526,
"text": "Google Chrome 5.0"
},
{
"code": null,
"e": 25567,
"s": 25544,
"text": "Internet Explorer 10.0"
},
{
"code": null,
"e": 25579,
"s": 25567,
"text": "Firefox 4.0"
},
{
"code": null,
"e": 25591,
"s": 25579,
"text": "Safari 10.1"
},
{
"code": null,
"e": 25601,
"s": 25591,
"text": "Opera 9.6"
},
{
"code": null,
"e": 25738,
"s": 25601,
"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": 25754,
"s": 25738,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25759,
"s": 25754,
"text": "HTML"
},
{
"code": null,
"e": 25776,
"s": 25759,
"text": "Web Technologies"
},
{
"code": null,
"e": 25781,
"s": 25776,
"text": "HTML"
},
{
"code": null,
"e": 25879,
"s": 25781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25888,
"s": 25879,
"text": "Comments"
},
{
"code": null,
"e": 25901,
"s": 25888,
"text": "Old Comments"
},
{
"code": null,
"e": 25949,
"s": 25901,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25986,
"s": 25949,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26036,
"s": 25986,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26086,
"s": 26036,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26110,
"s": 26086,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26166,
"s": 26110,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26199,
"s": 26166,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26242,
"s": 26199,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26303,
"s": 26242,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
MySQL GROUP BY and CONCAT() to display distinct first and last name
|
Let us first create a table −
mysql> create table DemoTable
(
FirstName varchar(100),
LastName varchar(100)
);
Query OK, 0 rows affected (0.92 sec)
mysql> alter table DemoTable add index(FirstName,LastName);
Query OK, 0 rows affected (1.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.73 sec)
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (1.17 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Carol','Taylor');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.66 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam | Smith |
| Adam | Smith |
| Carol | Taylor |
| John | Doe |
| John | Doe |
+-----------+----------+
5 rows in set (0.00 sec)
Following is the query to combine distinct First and Last Name −
mysql> select concat(FirstName,' ',LastName) as combinedName from DemoTable
group by LastName,FirstName;
This will produce the following output −
+--------------+
| combinedName |
+--------------+
| Adam Smith |
| Carol Taylor |
| John Doe |
+--------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1350,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n FirstName varchar(100),\n LastName varchar(100)\n);\nQuery OK, 0 rows affected (0.92 sec)\nmysql> alter table DemoTable add index(FirstName,LastName);\nQuery OK, 0 rows affected (1.00 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1406,
"s": 1350,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1849,
"s": 1406,
"text": "mysql> insert into DemoTable values('Adam','Smith');\nQuery OK, 1 row affected (0.73 sec)\nmysql> insert into DemoTable values('Adam','Smith');\nQuery OK, 1 row affected (1.17 sec)\nmysql> insert into DemoTable values('John','Doe');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('Carol','Taylor');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable values('John','Doe');\nQuery OK, 1 row affected (0.66 sec)"
},
{
"code": null,
"e": 1909,
"s": 1849,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1940,
"s": 1909,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1981,
"s": 1940,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2231,
"s": 1981,
"text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| Adam | Smith |\n| Adam | Smith |\n| Carol | Taylor |\n| John | Doe |\n| John | Doe |\n+-----------+----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2296,
"s": 2231,
"text": "Following is the query to combine distinct First and Last Name −"
},
{
"code": null,
"e": 2401,
"s": 2296,
"text": "mysql> select concat(FirstName,' ',LastName) as combinedName from DemoTable\ngroup by LastName,FirstName;"
},
{
"code": null,
"e": 2442,
"s": 2401,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2586,
"s": 2442,
"text": "+--------------+\n| combinedName |\n+--------------+\n| Adam Smith |\n| Carol Taylor |\n| John Doe |\n+--------------+\n3 rows in set (0.00 sec)"
}
] |
base64.decodebytes(s) in Python - GeeksforGeeks
|
22 Apr, 2020
With the help of base64.decodebytes(s) method, we can decode the binary string with the help of base64 data into normal form.
Syntax : base64.decodebytes(b_string)
Return : Return the decoded string.
Example #1 :In this example we can see that by using base64.decodebytes(s) method, we are able to get the decoded string which can be in binary form by using this method.
# import base64from base64 import encodebytesfrom base64 import decodebytes s = b'GeeksForGeeks's = encodebytes(s)# Using base64.decodebytes(s) methodgfg = decodebytes(s) print(gfg)
Output :
b’GeeksForGeeks’
Example #2 :
# import base64from base64 import encodebytesfrom base64 import decodebytes s = b'Hello World's = encodebytes(s)# Using base64.decodebytes(s) methodgfg = decodebytes(s) print(gfg)
Output :
b’Hello World’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25681,
"s": 25555,
"text": "With the help of base64.decodebytes(s) method, we can decode the binary string with the help of base64 data into normal form."
},
{
"code": null,
"e": 25719,
"s": 25681,
"text": "Syntax : base64.decodebytes(b_string)"
},
{
"code": null,
"e": 25755,
"s": 25719,
"text": "Return : Return the decoded string."
},
{
"code": null,
"e": 25926,
"s": 25755,
"text": "Example #1 :In this example we can see that by using base64.decodebytes(s) method, we are able to get the decoded string which can be in binary form by using this method."
},
{
"code": "# import base64from base64 import encodebytesfrom base64 import decodebytes s = b'GeeksForGeeks's = encodebytes(s)# Using base64.decodebytes(s) methodgfg = decodebytes(s) print(gfg)",
"e": 26110,
"s": 25926,
"text": null
},
{
"code": null,
"e": 26119,
"s": 26110,
"text": "Output :"
},
{
"code": null,
"e": 26136,
"s": 26119,
"text": "b’GeeksForGeeks’"
},
{
"code": null,
"e": 26149,
"s": 26136,
"text": "Example #2 :"
},
{
"code": "# import base64from base64 import encodebytesfrom base64 import decodebytes s = b'Hello World's = encodebytes(s)# Using base64.decodebytes(s) methodgfg = decodebytes(s) print(gfg)",
"e": 26331,
"s": 26149,
"text": null
},
{
"code": null,
"e": 26340,
"s": 26331,
"text": "Output :"
},
{
"code": null,
"e": 26355,
"s": 26340,
"text": "b’Hello World’"
},
{
"code": null,
"e": 26376,
"s": 26355,
"text": "Python base64-module"
},
{
"code": null,
"e": 26383,
"s": 26376,
"text": "Python"
},
{
"code": null,
"e": 26481,
"s": 26383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26513,
"s": 26481,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26555,
"s": 26513,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26597,
"s": 26555,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26653,
"s": 26597,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26680,
"s": 26653,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26711,
"s": 26680,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26740,
"s": 26711,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26762,
"s": 26740,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26801,
"s": 26762,
"text": "Python | Get unique values from a list"
}
] |
How To Develop a Machine Learning Model From Scratch | by Victor Roman | Towards Data Science
|
In this article we are going to study in depth how the process for developing a machine learning model is done. There will be a lot of concepts explained and we will reserve others, that are more specific, to future articles.
Concretely, in the article it will be discussed how to:
Define adequately our problem (objective, desired outputs...).
Gather data.
Choose a measure of success.
Set an evaluation protocol and the different protocols available.
Prepare the data (dealing with missing values, with categorial values...).
Spilit correctly the data.
Differentiate between over and underfitting, defining what they are and explaining the best ways to avoid them.
An overview of how a model learns.
What is regularization and when is appropiate to use it.
Develop a benchmark model.
Choose an adequate model and tune it to get the best performance possible.
The first, and one of the most critical things to do, is to find out what are the inputs and the expected outputs. The following questions must be answered:
What is the main objective? What are we trying to predict?
What are the target features?
What is the input data? Is it available?
What kind of problem are we facing? Binary classification? Clustering?
What is the expected improvement?
What is the current status of the target feature?
How is going to be measured the target feature?
Not every problem can be solved, until we have a working model we just can make certain hypothesis:
Our outputs can be predicted given the inputs.
Our available data is sufficient informative to learn the relationship between the inputs and the outputs
It is crucial to keep in mind that machine learning can only be used to memorize patterns that are present in the training data, so we can only recognize what we have seen before. When using Machine Learning we are making the assumption that the future will behave like the past, and this isn’t always true.
This is the first real step towards the real development of a machine learning model, collecting data. This is a critical step that will cascade in how good the model will be, the more and better data that we get, the better our model will perform.
There are several techniques to collect the data, like web scraping, but they are out of the scope of this article.
Tipically our data will have the following shape:
Note: The previous table corresponds to the famous boston housing dataset, a classical dataset frequently used to develop siemple machine learning models. Each row represents a different Boston’s neighborhood and each column indicates some characteristic of the neighborhood (criminality rate, average age... etc). The last column represents the median house price of the neighborhood and it is the target, the one that will be predicted taking into account the other.
Peter Drucker, Harvard teacher and author of The Effective Executive and Managing Oneself, had a famous saying:
“If you can’t measure it you can’t improve it”.
If you want to control something it should be observable, and in order to achieve sucess, it is essential to define what is considered success: Maybe precision? accuracy? Customer-retention rate?
This measure should be directly aligned with the higher level goals of the bussines at hand. And it is also directly related with the kind of problem we are facing:
Regression problems use certain evaluation metrics such as mean squared error (MSE).
Classification problems use evaluation metrics as precision, accuracy and recall.
On the next articles we’ll explore in depth these metrics, what are the most adequate to use considering the problem faced, and learn how to set them up.
Once the goal is clear, it should be decided how is going to be measured the progress towards achieving the goal. The most common evaluation protocols are:
This mehod consists on setting apart some portion of the data as the test set.
The process would be to train the model with the remaining fraction of the data, tunning its parameters with the validation set and finally evaluating its performance on the test set.
The reason to split data in three parts is to avoid information leaks. The main inconvenient of this method is that if there is little data available, the validation and test sets will contain so few samples that the tuning and evaluatation processes of the model will not be effective.
K-Fold consists in splitting the data into K partitions of equal size. For each partition i, the model is trained with the remaining K-1 partitions and it is evaluated on partition i.
The final score is the average of the K scored obtained. This technique is specially helpful when the performance of the model is significantly different from the train-test split.
This technique is specially relevant when having little data available and it is needed to evaluate the model as precisely as possible (it is the standard approach on Kaggle competitions).
It consist on applying K-Fold validation several times and shuffling the data every time before splitting it into K partitions. The Final score is the average of the scores obtained at the end of each run of K-Fold validation.
This method can be very computationally expensive, as the number of trained and evaluating models would be I x K times. Being I the number of iterations and K the number of partitions.
Note: It is crucial to keep in mind the following points when choosing an evaluation protocol:
In classification problems, both training and testing data should be representative of the data, so we should shuffle our data before splitting it, to make sure that is covered the whole spectrum of the dataset.
When trying to predict the future given the past (weather prediction, stock price prediction...), data should not be shuffled, as the sequence of data is a crucial feature and doing so would create a temporal leak.
We should always check if there are dupicates in our data in order to remove them. Otherwise the redundat data may appear both in the training and testing sets and cause unaccurate learning on our model.
Before begining to train models we should transform our data in a way that can be fed into a Machine Learning model. The most common techniques are:
It is quite common in real-world problems to miss some values of our data samples. It may be due to errors on the data collection, blank spaces on surveys, measurements not applicable...etc
Missing values are tipically represented with the “NaN” or “Null” indicators. The problem is that most algorithms can’t handle those missing values so we need to take care of them before feeding data to our models. Once they are identified, there are several ways to deal with them:
Eliminating the samples or features with missing values. (we risk to delete relevant information or too many samples)Imputing the missing values, with some pre-built estimators such as the Imputer class from scikit learn. We’ll fit our data and then transform it to estimate them. One common approach is to set the missing values as the mean value of the rest of the samples.
Eliminating the samples or features with missing values. (we risk to delete relevant information or too many samples)
Imputing the missing values, with some pre-built estimators such as the Imputer class from scikit learn. We’ll fit our data and then transform it to estimate them. One common approach is to set the missing values as the mean value of the rest of the samples.
When dealing with categorical data, we work with ordinal and nominal features. Ordinal features are categorical features that can be sorted (cloth’s size: L<M<S). While nominal features don’t imply any order (cloth’s color: yellow, green, red).
The methods to deal with ordinal and nominal features are:
Mapping ordinal features: to make sure that the algorithm interprets the ordinal features correctly, we need to convert the categorical string values into integers. Frequently we will do this mapping manually. Example: L:2, M:1, S:0.
Encoding nominal class labels: The most common approach is to perform one-hot encoding, which consists in creating a new dummy feature for each unique value in the nominal feature column. Example: in the color column, if we have three classes: yellow, red, green and perform one-hot encoding, we will get three new columns, one for each unique class. Then, if we have a yellow shirt, it will be sampled as: yellow = 1, green = 0, red = 0. This is done for ensuring the good performance of the algorithm as they are much more efficient when dealing with a sparse matrix (low dense matrixes, with a lot of 0’s values).
This is a crucial step in the preprocessing phase as the majority of machine learning algorithms perform much better when dealing with features that are on the same scale. The most common techniques are:
Normalization: it refers to rescaling the features to a range of [0,1], which is a special case of min-max scaling. To normalize our data we’ll simply need to apply the min-max scaling method to each feature column.
Standardization: it consists in centering the feature columns at mean 0 with standard deviation 1 so that the feature columns have the same parameters as a standard normal distribution (zero mean and unit variance). This makes much more easier for the learning algorithms to learn the weights of the parameters. In addition, it keeps useful information about outliers and makes the algorithms less sensitive to them.
As we will see later, one of the main reasons that causes machine learning models to overfit is because of having redundancy in our data, which makes the model to be too complex for the given training data and unable to generalize well on unseen data.
One of the most common solution to avoid overfitting is to reduce data’s dimensionality. This is frequently done by reducing the number of features of our dataset via Principal Component Analysis (PCA) which is a type of Unsupervised Machine Learning algorithm.
PCA identifies patterns in our data based on the correlations between the features. This correlation imply that there is redundancy in our data, in other words, that there is some part of the data that can be explained with other parts of it.
This correlated data is not essential for the model to learn its weights appropiately and so, it can be removed. It may be removed by directly eliminating certain columns (features) or by combining a number of them and getting new ones that hold the most part of the information. We will dig deeper in this technique in future articles.
In general, we will split our data in three parts: training, testing and validating sets. We train our model with training data, evaluate it on validation data and finally, once it is ready to use, test it one last time on test data.
Now, is reasonable to ask the the following question : Why not having only two sets, training and testing? In that way, the process will be much simpler, just train the model on training data and test it on testing data.
The answer is that, developing a model involves tunning its configuration, in other words, choosing certain values for their hyperparameters (which are different from the parameters of the model — network’s weights). This tunning is done with the feedback recieved from the validation set, and is in essence, a form of learning.
The ultimate goal is that the model can generalize well on unseen data, in other words, predict accurate results from new data, based on its internal parameters adjusted while it was trained and validated.
We can take a closer look at how the learning process is done by studying one of the simplest algorithms: Linear Regression.
In Linear regression we are given a number of predictor (explanatory) variables and a continuous response variable (outcome), and we try to find a relationship between those variables that allows us to predict a continuous outcome.
An example of linear regression: given X and Y, we fit a straight line that minimize the distance using some methods to estimate the coefficients (like Ordinary Least Squares and Gradient Descent) between the sample points and the fitted line. Then, we’ll use the intercept and slope learned, that form the fitted line, to predict the outcome of new data.
The formula for the straight line is y = B0 + B1x +u. Where x is the input, B1 is the slope, B0 the y-intercept, u the residual and y is the value of the line at the postion x.
The values available for being trained are B0 and B1, which are the values that affect the position of the line, since the only other variables are x (the input and y, the output (the residual is not considered). These values (B0 and B1) are the “weights” of the predicting funtion.
These weights and other, called biases, are the parameters that will be arranged together as matrixes (W for the weights and b for the biases).
The training process involves initializing some random values for each of the training matrixes and attempt to predict the output of the input data using the initial random values. At the beginning, the error will be large, but comparing the model’s prediction with the correct output, the model is able to adjust the weights and biases values until having a good predicting model.
The process is repeated, one iteration (or step) at a time. In each iteration the initial random line moves closer to the ideal and more accurate one.
One of the most important problems when considering the training of models is the tension between optimization and generalization.
Optimization is the process of adjusting a model to get the best performance possible on training data (the learning process).
Generalization is how well the model performs on unseen data. The goal is to obtain the best generalization ability.
At the beginning of training, those two issues are correlated, the lower the loss on training data, the lower the loss on test data. This happens while the model is still underfitted: there is still learning to be done, it hasn’t been modeled yet all the relevant parameters of the model.
But, after a number of iterations on the training data, generalization stops to improve and the validation metrics freeze first, and then start to degrade. The model is starting to overfit: it has learned so well the training data that has learned patternts that are too specific to training data and irrelevant to new data.
There are two ways to avoid this overfitting, getting more data and regularization.
Getting more data is usually the best solution, a model trained on more data will naturally generalize better.
Regularization is done when the latter is not possible, it is the process of modulating the quantity of information that the model can store or to add constraints on what information it is allowed to keep. If the model can only memorize a small number of patterns, the optimization will make it to focus on the most relevant ones, improving the chance of generalizing well.
Regularization is done mainly by the following techniques:
Reducing the model’s size: Reducing the number of learnable parameters in the model, and with them its learning capacity. The goal is to get to a sweet spot between too much and not enough learning capacity. Unfortunately, there aren’t any magical formulas to determine this balance, it must be tested and evaluated by setting different number of parameters and observing its performance.Adding weight regularization: In general, the simpler the model the better. As long it can learn well, a simpler model is much less likely to overfit. A common way to achieve this, is to constraint the complexity of the network by forcing its weights to only take small values, regularizating the distribution of weight values. This is done by adding to the loss function of the network a cost associated with having large weights. The cost comes in two ways:
Reducing the model’s size: Reducing the number of learnable parameters in the model, and with them its learning capacity. The goal is to get to a sweet spot between too much and not enough learning capacity. Unfortunately, there aren’t any magical formulas to determine this balance, it must be tested and evaluated by setting different number of parameters and observing its performance.
Adding weight regularization: In general, the simpler the model the better. As long it can learn well, a simpler model is much less likely to overfit. A common way to achieve this, is to constraint the complexity of the network by forcing its weights to only take small values, regularizating the distribution of weight values. This is done by adding to the loss function of the network a cost associated with having large weights. The cost comes in two ways:
L1 regularization: The cost is proportional to theabsolutethe value of the weights coefficients (L1 norm of the weights).
L2 regularization: The cost is proportional to the square of the value of the weight coefficients (l2 norm of the weights)
To decide which of them to apply to our model, is recommended to keep the in mind following information and take into account the nature of our problem:
The goal in this step of the process is to develop a benchamark model that serves us as a baseline, upon we’ll measure the performance of a better and more attuned algorithm.
Benchmarking requires experiments to be comparable, measurable, and reproducible. It is important to emphasize on the reproducible part of the last statement. Nowaday’s data science libraries perform random splits of data, this randomness must be consistent through all runs. Most random generators support setting a seed for this pourpose. In Python we will use the random.seed method from the random package.
As found on “https://blog.dominodatalab.com/benchmarking-predictive-models/”
“It is often valuable to compare model improvement over a simplified baseline model such as a kNN or Naive Bayes for categorical data, or the EWMA of a value in time series data. These baselines provide an understanding of the possible predictive power of a dataset.
The models often require far less time and compute power to train and predict, making them a useful cross-check as to the viability of an answer. Neither kNN nor Naive Bayes models are likely to capture complex interactions. They will, however, provide a reasonable estimate of the minimum bound of predictive capabilities of a benchmarked model.
Additionally, this exercise provides the opportunity to test the benchmarking pipeline. It is important that benchmark pipelines provide stable results for a model with understood performance characteristics. A kNN or a Naive Bayes on the raw dataset, or minimally manipulated with column centering or scaling, will often provide a weak, but adequate learner, with characteristics that are useful for the purposes of comparison. The characteristics of more complex models may be less understood and prove challenging.”
One of the most common methods for finding a good model is cross validation. In cross validation we will set:
A number of folds in which we will split our data.
A scoring method (that will vary depending on the problem’s nature — regression, classification...).
Some appropiate algorithms that we want to check.
We’ll passs our dataset to our cross validation score function and get the model that yielded the best score. That will be the one that we will optimize, tunning its hyperparameters accordingly.
# Test Options and Evaluation Metricsnum_folds = 10scoring = "neg_mean_squared_error"# Spot Check Algorithmsmodels = []models.append(('LR', LinearRegression()))models.append(('LASSO', Lasso()))models.append(('EN', ElasticNet()))models.append(('KNN', KNeighborsRegressor()))models.append(('CART', DecisionTreeRegressor()))models.append(('SVR', SVR()))results = []names = []for name, model in models: kfold = KFold(n_splits=num_folds, random_state=seed) cv_results = cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg)
# Compare Algorithmsfig = pyplot.figure()fig.suptitle('Algorithm Comparison')ax = fig.add_subplot(111)pyplot.boxplot(results)ax.set_xticklabels(names)pyplot.show()
A machine learning algorithm has two types of parameters. the first type are the parameters that are learned through the training phase and the second type are the hyperparameters that we pass to the machine learning model.
Once identified the model that we will use, the next step is to tune its hyperparameters to obtain the best predictive power possible. The most common way to find the best combination of hyperparameters is called Grid Search Cross Validation.
The process would be the following:
Set the parameter grid that we will evaluate. We will do this by creating a dictionary of all the parameters and their corresponding set of values that you want to test for best performance
Set the number of folds and the random state and a scoring method.
Build a K-Fold object with the selected number of folds.
Build a Grid Search Object with the selected model and fit it.
# Build a scalerscaler = StandardScaler().fit(X_train)rescaledX = scaler.transform(X_train)# Build parameter gridc_values = [0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 1.3, 1.5, 1.7, 2.0]kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']param_grid = dict(C=c_values, kernel=kernel_values)# Build the modelmodel = SVC()kfold = KFold(n_splits=num_folds, random_state=seed)grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scoring, cv=kfold)grid_result = grid.fit(rescaledX, y_train)# Show the resultsprint("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))means = grid_result.cv_results_['mean_test_score']stds = grid_result.cv_results_['std_test_score']params = grid_result.cv_results_['params']for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param))
This method returns a set of hyperparameters that fits best with the problem at hand. Once they are determined, our model is ready to be used. So we’ll make the appropiate predictions on the validation dataset and save the model for later use.
We have covered a lot of important concepts through this article. Although having provided a high level overview of them, this is necessary to gain a good intuition on how and when to apply the methods explained.
We will explore these methods in more depth as they will keep coming up in the next articles, as well as its python implementations.
In the next article we will begin with the first and most common type of Machine Learning problems: Regression.
If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here.
If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
|
[
{
"code": null,
"e": 398,
"s": 172,
"text": "In this article we are going to study in depth how the process for developing a machine learning model is done. There will be a lot of concepts explained and we will reserve others, that are more specific, to future articles."
},
{
"code": null,
"e": 454,
"s": 398,
"text": "Concretely, in the article it will be discussed how to:"
},
{
"code": null,
"e": 517,
"s": 454,
"text": "Define adequately our problem (objective, desired outputs...)."
},
{
"code": null,
"e": 530,
"s": 517,
"text": "Gather data."
},
{
"code": null,
"e": 559,
"s": 530,
"text": "Choose a measure of success."
},
{
"code": null,
"e": 625,
"s": 559,
"text": "Set an evaluation protocol and the different protocols available."
},
{
"code": null,
"e": 700,
"s": 625,
"text": "Prepare the data (dealing with missing values, with categorial values...)."
},
{
"code": null,
"e": 727,
"s": 700,
"text": "Spilit correctly the data."
},
{
"code": null,
"e": 839,
"s": 727,
"text": "Differentiate between over and underfitting, defining what they are and explaining the best ways to avoid them."
},
{
"code": null,
"e": 874,
"s": 839,
"text": "An overview of how a model learns."
},
{
"code": null,
"e": 931,
"s": 874,
"text": "What is regularization and when is appropiate to use it."
},
{
"code": null,
"e": 958,
"s": 931,
"text": "Develop a benchmark model."
},
{
"code": null,
"e": 1033,
"s": 958,
"text": "Choose an adequate model and tune it to get the best performance possible."
},
{
"code": null,
"e": 1190,
"s": 1033,
"text": "The first, and one of the most critical things to do, is to find out what are the inputs and the expected outputs. The following questions must be answered:"
},
{
"code": null,
"e": 1249,
"s": 1190,
"text": "What is the main objective? What are we trying to predict?"
},
{
"code": null,
"e": 1279,
"s": 1249,
"text": "What are the target features?"
},
{
"code": null,
"e": 1320,
"s": 1279,
"text": "What is the input data? Is it available?"
},
{
"code": null,
"e": 1391,
"s": 1320,
"text": "What kind of problem are we facing? Binary classification? Clustering?"
},
{
"code": null,
"e": 1425,
"s": 1391,
"text": "What is the expected improvement?"
},
{
"code": null,
"e": 1475,
"s": 1425,
"text": "What is the current status of the target feature?"
},
{
"code": null,
"e": 1523,
"s": 1475,
"text": "How is going to be measured the target feature?"
},
{
"code": null,
"e": 1623,
"s": 1523,
"text": "Not every problem can be solved, until we have a working model we just can make certain hypothesis:"
},
{
"code": null,
"e": 1670,
"s": 1623,
"text": "Our outputs can be predicted given the inputs."
},
{
"code": null,
"e": 1776,
"s": 1670,
"text": "Our available data is sufficient informative to learn the relationship between the inputs and the outputs"
},
{
"code": null,
"e": 2084,
"s": 1776,
"text": "It is crucial to keep in mind that machine learning can only be used to memorize patterns that are present in the training data, so we can only recognize what we have seen before. When using Machine Learning we are making the assumption that the future will behave like the past, and this isn’t always true."
},
{
"code": null,
"e": 2333,
"s": 2084,
"text": "This is the first real step towards the real development of a machine learning model, collecting data. This is a critical step that will cascade in how good the model will be, the more and better data that we get, the better our model will perform."
},
{
"code": null,
"e": 2449,
"s": 2333,
"text": "There are several techniques to collect the data, like web scraping, but they are out of the scope of this article."
},
{
"code": null,
"e": 2499,
"s": 2449,
"text": "Tipically our data will have the following shape:"
},
{
"code": null,
"e": 2968,
"s": 2499,
"text": "Note: The previous table corresponds to the famous boston housing dataset, a classical dataset frequently used to develop siemple machine learning models. Each row represents a different Boston’s neighborhood and each column indicates some characteristic of the neighborhood (criminality rate, average age... etc). The last column represents the median house price of the neighborhood and it is the target, the one that will be predicted taking into account the other."
},
{
"code": null,
"e": 3080,
"s": 2968,
"text": "Peter Drucker, Harvard teacher and author of The Effective Executive and Managing Oneself, had a famous saying:"
},
{
"code": null,
"e": 3128,
"s": 3080,
"text": "“If you can’t measure it you can’t improve it”."
},
{
"code": null,
"e": 3324,
"s": 3128,
"text": "If you want to control something it should be observable, and in order to achieve sucess, it is essential to define what is considered success: Maybe precision? accuracy? Customer-retention rate?"
},
{
"code": null,
"e": 3489,
"s": 3324,
"text": "This measure should be directly aligned with the higher level goals of the bussines at hand. And it is also directly related with the kind of problem we are facing:"
},
{
"code": null,
"e": 3574,
"s": 3489,
"text": "Regression problems use certain evaluation metrics such as mean squared error (MSE)."
},
{
"code": null,
"e": 3656,
"s": 3574,
"text": "Classification problems use evaluation metrics as precision, accuracy and recall."
},
{
"code": null,
"e": 3810,
"s": 3656,
"text": "On the next articles we’ll explore in depth these metrics, what are the most adequate to use considering the problem faced, and learn how to set them up."
},
{
"code": null,
"e": 3966,
"s": 3810,
"text": "Once the goal is clear, it should be decided how is going to be measured the progress towards achieving the goal. The most common evaluation protocols are:"
},
{
"code": null,
"e": 4045,
"s": 3966,
"text": "This mehod consists on setting apart some portion of the data as the test set."
},
{
"code": null,
"e": 4229,
"s": 4045,
"text": "The process would be to train the model with the remaining fraction of the data, tunning its parameters with the validation set and finally evaluating its performance on the test set."
},
{
"code": null,
"e": 4516,
"s": 4229,
"text": "The reason to split data in three parts is to avoid information leaks. The main inconvenient of this method is that if there is little data available, the validation and test sets will contain so few samples that the tuning and evaluatation processes of the model will not be effective."
},
{
"code": null,
"e": 4700,
"s": 4516,
"text": "K-Fold consists in splitting the data into K partitions of equal size. For each partition i, the model is trained with the remaining K-1 partitions and it is evaluated on partition i."
},
{
"code": null,
"e": 4881,
"s": 4700,
"text": "The final score is the average of the K scored obtained. This technique is specially helpful when the performance of the model is significantly different from the train-test split."
},
{
"code": null,
"e": 5070,
"s": 4881,
"text": "This technique is specially relevant when having little data available and it is needed to evaluate the model as precisely as possible (it is the standard approach on Kaggle competitions)."
},
{
"code": null,
"e": 5297,
"s": 5070,
"text": "It consist on applying K-Fold validation several times and shuffling the data every time before splitting it into K partitions. The Final score is the average of the scores obtained at the end of each run of K-Fold validation."
},
{
"code": null,
"e": 5482,
"s": 5297,
"text": "This method can be very computationally expensive, as the number of trained and evaluating models would be I x K times. Being I the number of iterations and K the number of partitions."
},
{
"code": null,
"e": 5577,
"s": 5482,
"text": "Note: It is crucial to keep in mind the following points when choosing an evaluation protocol:"
},
{
"code": null,
"e": 5789,
"s": 5577,
"text": "In classification problems, both training and testing data should be representative of the data, so we should shuffle our data before splitting it, to make sure that is covered the whole spectrum of the dataset."
},
{
"code": null,
"e": 6004,
"s": 5789,
"text": "When trying to predict the future given the past (weather prediction, stock price prediction...), data should not be shuffled, as the sequence of data is a crucial feature and doing so would create a temporal leak."
},
{
"code": null,
"e": 6208,
"s": 6004,
"text": "We should always check if there are dupicates in our data in order to remove them. Otherwise the redundat data may appear both in the training and testing sets and cause unaccurate learning on our model."
},
{
"code": null,
"e": 6357,
"s": 6208,
"text": "Before begining to train models we should transform our data in a way that can be fed into a Machine Learning model. The most common techniques are:"
},
{
"code": null,
"e": 6547,
"s": 6357,
"text": "It is quite common in real-world problems to miss some values of our data samples. It may be due to errors on the data collection, blank spaces on surveys, measurements not applicable...etc"
},
{
"code": null,
"e": 6830,
"s": 6547,
"text": "Missing values are tipically represented with the “NaN” or “Null” indicators. The problem is that most algorithms can’t handle those missing values so we need to take care of them before feeding data to our models. Once they are identified, there are several ways to deal with them:"
},
{
"code": null,
"e": 7206,
"s": 6830,
"text": "Eliminating the samples or features with missing values. (we risk to delete relevant information or too many samples)Imputing the missing values, with some pre-built estimators such as the Imputer class from scikit learn. We’ll fit our data and then transform it to estimate them. One common approach is to set the missing values as the mean value of the rest of the samples."
},
{
"code": null,
"e": 7324,
"s": 7206,
"text": "Eliminating the samples or features with missing values. (we risk to delete relevant information or too many samples)"
},
{
"code": null,
"e": 7583,
"s": 7324,
"text": "Imputing the missing values, with some pre-built estimators such as the Imputer class from scikit learn. We’ll fit our data and then transform it to estimate them. One common approach is to set the missing values as the mean value of the rest of the samples."
},
{
"code": null,
"e": 7828,
"s": 7583,
"text": "When dealing with categorical data, we work with ordinal and nominal features. Ordinal features are categorical features that can be sorted (cloth’s size: L<M<S). While nominal features don’t imply any order (cloth’s color: yellow, green, red)."
},
{
"code": null,
"e": 7887,
"s": 7828,
"text": "The methods to deal with ordinal and nominal features are:"
},
{
"code": null,
"e": 8121,
"s": 7887,
"text": "Mapping ordinal features: to make sure that the algorithm interprets the ordinal features correctly, we need to convert the categorical string values into integers. Frequently we will do this mapping manually. Example: L:2, M:1, S:0."
},
{
"code": null,
"e": 8738,
"s": 8121,
"text": "Encoding nominal class labels: The most common approach is to perform one-hot encoding, which consists in creating a new dummy feature for each unique value in the nominal feature column. Example: in the color column, if we have three classes: yellow, red, green and perform one-hot encoding, we will get three new columns, one for each unique class. Then, if we have a yellow shirt, it will be sampled as: yellow = 1, green = 0, red = 0. This is done for ensuring the good performance of the algorithm as they are much more efficient when dealing with a sparse matrix (low dense matrixes, with a lot of 0’s values)."
},
{
"code": null,
"e": 8942,
"s": 8738,
"text": "This is a crucial step in the preprocessing phase as the majority of machine learning algorithms perform much better when dealing with features that are on the same scale. The most common techniques are:"
},
{
"code": null,
"e": 9158,
"s": 8942,
"text": "Normalization: it refers to rescaling the features to a range of [0,1], which is a special case of min-max scaling. To normalize our data we’ll simply need to apply the min-max scaling method to each feature column."
},
{
"code": null,
"e": 9575,
"s": 9158,
"text": "Standardization: it consists in centering the feature columns at mean 0 with standard deviation 1 so that the feature columns have the same parameters as a standard normal distribution (zero mean and unit variance). This makes much more easier for the learning algorithms to learn the weights of the parameters. In addition, it keeps useful information about outliers and makes the algorithms less sensitive to them."
},
{
"code": null,
"e": 9827,
"s": 9575,
"text": "As we will see later, one of the main reasons that causes machine learning models to overfit is because of having redundancy in our data, which makes the model to be too complex for the given training data and unable to generalize well on unseen data."
},
{
"code": null,
"e": 10089,
"s": 9827,
"text": "One of the most common solution to avoid overfitting is to reduce data’s dimensionality. This is frequently done by reducing the number of features of our dataset via Principal Component Analysis (PCA) which is a type of Unsupervised Machine Learning algorithm."
},
{
"code": null,
"e": 10332,
"s": 10089,
"text": "PCA identifies patterns in our data based on the correlations between the features. This correlation imply that there is redundancy in our data, in other words, that there is some part of the data that can be explained with other parts of it."
},
{
"code": null,
"e": 10669,
"s": 10332,
"text": "This correlated data is not essential for the model to learn its weights appropiately and so, it can be removed. It may be removed by directly eliminating certain columns (features) or by combining a number of them and getting new ones that hold the most part of the information. We will dig deeper in this technique in future articles."
},
{
"code": null,
"e": 10903,
"s": 10669,
"text": "In general, we will split our data in three parts: training, testing and validating sets. We train our model with training data, evaluate it on validation data and finally, once it is ready to use, test it one last time on test data."
},
{
"code": null,
"e": 11124,
"s": 10903,
"text": "Now, is reasonable to ask the the following question : Why not having only two sets, training and testing? In that way, the process will be much simpler, just train the model on training data and test it on testing data."
},
{
"code": null,
"e": 11453,
"s": 11124,
"text": "The answer is that, developing a model involves tunning its configuration, in other words, choosing certain values for their hyperparameters (which are different from the parameters of the model — network’s weights). This tunning is done with the feedback recieved from the validation set, and is in essence, a form of learning."
},
{
"code": null,
"e": 11659,
"s": 11453,
"text": "The ultimate goal is that the model can generalize well on unseen data, in other words, predict accurate results from new data, based on its internal parameters adjusted while it was trained and validated."
},
{
"code": null,
"e": 11784,
"s": 11659,
"text": "We can take a closer look at how the learning process is done by studying one of the simplest algorithms: Linear Regression."
},
{
"code": null,
"e": 12016,
"s": 11784,
"text": "In Linear regression we are given a number of predictor (explanatory) variables and a continuous response variable (outcome), and we try to find a relationship between those variables that allows us to predict a continuous outcome."
},
{
"code": null,
"e": 12372,
"s": 12016,
"text": "An example of linear regression: given X and Y, we fit a straight line that minimize the distance using some methods to estimate the coefficients (like Ordinary Least Squares and Gradient Descent) between the sample points and the fitted line. Then, we’ll use the intercept and slope learned, that form the fitted line, to predict the outcome of new data."
},
{
"code": null,
"e": 12549,
"s": 12372,
"text": "The formula for the straight line is y = B0 + B1x +u. Where x is the input, B1 is the slope, B0 the y-intercept, u the residual and y is the value of the line at the postion x."
},
{
"code": null,
"e": 12832,
"s": 12549,
"text": "The values available for being trained are B0 and B1, which are the values that affect the position of the line, since the only other variables are x (the input and y, the output (the residual is not considered). These values (B0 and B1) are the “weights” of the predicting funtion."
},
{
"code": null,
"e": 12976,
"s": 12832,
"text": "These weights and other, called biases, are the parameters that will be arranged together as matrixes (W for the weights and b for the biases)."
},
{
"code": null,
"e": 13358,
"s": 12976,
"text": "The training process involves initializing some random values for each of the training matrixes and attempt to predict the output of the input data using the initial random values. At the beginning, the error will be large, but comparing the model’s prediction with the correct output, the model is able to adjust the weights and biases values until having a good predicting model."
},
{
"code": null,
"e": 13509,
"s": 13358,
"text": "The process is repeated, one iteration (or step) at a time. In each iteration the initial random line moves closer to the ideal and more accurate one."
},
{
"code": null,
"e": 13640,
"s": 13509,
"text": "One of the most important problems when considering the training of models is the tension between optimization and generalization."
},
{
"code": null,
"e": 13767,
"s": 13640,
"text": "Optimization is the process of adjusting a model to get the best performance possible on training data (the learning process)."
},
{
"code": null,
"e": 13884,
"s": 13767,
"text": "Generalization is how well the model performs on unseen data. The goal is to obtain the best generalization ability."
},
{
"code": null,
"e": 14173,
"s": 13884,
"text": "At the beginning of training, those two issues are correlated, the lower the loss on training data, the lower the loss on test data. This happens while the model is still underfitted: there is still learning to be done, it hasn’t been modeled yet all the relevant parameters of the model."
},
{
"code": null,
"e": 14498,
"s": 14173,
"text": "But, after a number of iterations on the training data, generalization stops to improve and the validation metrics freeze first, and then start to degrade. The model is starting to overfit: it has learned so well the training data that has learned patternts that are too specific to training data and irrelevant to new data."
},
{
"code": null,
"e": 14582,
"s": 14498,
"text": "There are two ways to avoid this overfitting, getting more data and regularization."
},
{
"code": null,
"e": 14693,
"s": 14582,
"text": "Getting more data is usually the best solution, a model trained on more data will naturally generalize better."
},
{
"code": null,
"e": 15067,
"s": 14693,
"text": "Regularization is done when the latter is not possible, it is the process of modulating the quantity of information that the model can store or to add constraints on what information it is allowed to keep. If the model can only memorize a small number of patterns, the optimization will make it to focus on the most relevant ones, improving the chance of generalizing well."
},
{
"code": null,
"e": 15126,
"s": 15067,
"text": "Regularization is done mainly by the following techniques:"
},
{
"code": null,
"e": 15974,
"s": 15126,
"text": "Reducing the model’s size: Reducing the number of learnable parameters in the model, and with them its learning capacity. The goal is to get to a sweet spot between too much and not enough learning capacity. Unfortunately, there aren’t any magical formulas to determine this balance, it must be tested and evaluated by setting different number of parameters and observing its performance.Adding weight regularization: In general, the simpler the model the better. As long it can learn well, a simpler model is much less likely to overfit. A common way to achieve this, is to constraint the complexity of the network by forcing its weights to only take small values, regularizating the distribution of weight values. This is done by adding to the loss function of the network a cost associated with having large weights. The cost comes in two ways:"
},
{
"code": null,
"e": 16363,
"s": 15974,
"text": "Reducing the model’s size: Reducing the number of learnable parameters in the model, and with them its learning capacity. The goal is to get to a sweet spot between too much and not enough learning capacity. Unfortunately, there aren’t any magical formulas to determine this balance, it must be tested and evaluated by setting different number of parameters and observing its performance."
},
{
"code": null,
"e": 16823,
"s": 16363,
"text": "Adding weight regularization: In general, the simpler the model the better. As long it can learn well, a simpler model is much less likely to overfit. A common way to achieve this, is to constraint the complexity of the network by forcing its weights to only take small values, regularizating the distribution of weight values. This is done by adding to the loss function of the network a cost associated with having large weights. The cost comes in two ways:"
},
{
"code": null,
"e": 16945,
"s": 16823,
"text": "L1 regularization: The cost is proportional to theabsolutethe value of the weights coefficients (L1 norm of the weights)."
},
{
"code": null,
"e": 17068,
"s": 16945,
"text": "L2 regularization: The cost is proportional to the square of the value of the weight coefficients (l2 norm of the weights)"
},
{
"code": null,
"e": 17221,
"s": 17068,
"text": "To decide which of them to apply to our model, is recommended to keep the in mind following information and take into account the nature of our problem:"
},
{
"code": null,
"e": 17396,
"s": 17221,
"text": "The goal in this step of the process is to develop a benchamark model that serves us as a baseline, upon we’ll measure the performance of a better and more attuned algorithm."
},
{
"code": null,
"e": 17807,
"s": 17396,
"text": "Benchmarking requires experiments to be comparable, measurable, and reproducible. It is important to emphasize on the reproducible part of the last statement. Nowaday’s data science libraries perform random splits of data, this randomness must be consistent through all runs. Most random generators support setting a seed for this pourpose. In Python we will use the random.seed method from the random package."
},
{
"code": null,
"e": 17884,
"s": 17807,
"text": "As found on “https://blog.dominodatalab.com/benchmarking-predictive-models/”"
},
{
"code": null,
"e": 18151,
"s": 17884,
"text": "“It is often valuable to compare model improvement over a simplified baseline model such as a kNN or Naive Bayes for categorical data, or the EWMA of a value in time series data. These baselines provide an understanding of the possible predictive power of a dataset."
},
{
"code": null,
"e": 18498,
"s": 18151,
"text": "The models often require far less time and compute power to train and predict, making them a useful cross-check as to the viability of an answer. Neither kNN nor Naive Bayes models are likely to capture complex interactions. They will, however, provide a reasonable estimate of the minimum bound of predictive capabilities of a benchmarked model."
},
{
"code": null,
"e": 19017,
"s": 18498,
"text": "Additionally, this exercise provides the opportunity to test the benchmarking pipeline. It is important that benchmark pipelines provide stable results for a model with understood performance characteristics. A kNN or a Naive Bayes on the raw dataset, or minimally manipulated with column centering or scaling, will often provide a weak, but adequate learner, with characteristics that are useful for the purposes of comparison. The characteristics of more complex models may be less understood and prove challenging.”"
},
{
"code": null,
"e": 19127,
"s": 19017,
"text": "One of the most common methods for finding a good model is cross validation. In cross validation we will set:"
},
{
"code": null,
"e": 19178,
"s": 19127,
"text": "A number of folds in which we will split our data."
},
{
"code": null,
"e": 19279,
"s": 19178,
"text": "A scoring method (that will vary depending on the problem’s nature — regression, classification...)."
},
{
"code": null,
"e": 19329,
"s": 19279,
"text": "Some appropiate algorithms that we want to check."
},
{
"code": null,
"e": 19524,
"s": 19329,
"text": "We’ll passs our dataset to our cross validation score function and get the model that yielded the best score. That will be the one that we will optimize, tunning its hyperparameters accordingly."
},
{
"code": null,
"e": 20203,
"s": 19524,
"text": "# Test Options and Evaluation Metricsnum_folds = 10scoring = \"neg_mean_squared_error\"# Spot Check Algorithmsmodels = []models.append(('LR', LinearRegression()))models.append(('LASSO', Lasso()))models.append(('EN', ElasticNet()))models.append(('KNN', KNeighborsRegressor()))models.append(('CART', DecisionTreeRegressor()))models.append(('SVR', SVR()))results = []names = []for name, model in models: kfold = KFold(n_splits=num_folds, random_state=seed) cv_results = cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring) results.append(cv_results) names.append(name) msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std()) print(msg)"
},
{
"code": null,
"e": 20367,
"s": 20203,
"text": "# Compare Algorithmsfig = pyplot.figure()fig.suptitle('Algorithm Comparison')ax = fig.add_subplot(111)pyplot.boxplot(results)ax.set_xticklabels(names)pyplot.show()"
},
{
"code": null,
"e": 20591,
"s": 20367,
"text": "A machine learning algorithm has two types of parameters. the first type are the parameters that are learned through the training phase and the second type are the hyperparameters that we pass to the machine learning model."
},
{
"code": null,
"e": 20834,
"s": 20591,
"text": "Once identified the model that we will use, the next step is to tune its hyperparameters to obtain the best predictive power possible. The most common way to find the best combination of hyperparameters is called Grid Search Cross Validation."
},
{
"code": null,
"e": 20870,
"s": 20834,
"text": "The process would be the following:"
},
{
"code": null,
"e": 21060,
"s": 20870,
"text": "Set the parameter grid that we will evaluate. We will do this by creating a dictionary of all the parameters and their corresponding set of values that you want to test for best performance"
},
{
"code": null,
"e": 21127,
"s": 21060,
"text": "Set the number of folds and the random state and a scoring method."
},
{
"code": null,
"e": 21184,
"s": 21127,
"text": "Build a K-Fold object with the selected number of folds."
},
{
"code": null,
"e": 21247,
"s": 21184,
"text": "Build a Grid Search Object with the selected model and fit it."
},
{
"code": null,
"e": 22076,
"s": 21247,
"text": "# Build a scalerscaler = StandardScaler().fit(X_train)rescaledX = scaler.transform(X_train)# Build parameter gridc_values = [0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 1.3, 1.5, 1.7, 2.0]kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']param_grid = dict(C=c_values, kernel=kernel_values)# Build the modelmodel = SVC()kfold = KFold(n_splits=num_folds, random_state=seed)grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scoring, cv=kfold)grid_result = grid.fit(rescaledX, y_train)# Show the resultsprint(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))means = grid_result.cv_results_['mean_test_score']stds = grid_result.cv_results_['std_test_score']params = grid_result.cv_results_['params']for mean, stdev, param in zip(means, stds, params): print(\"%f (%f) with: %r\" % (mean, stdev, param))"
},
{
"code": null,
"e": 22320,
"s": 22076,
"text": "This method returns a set of hyperparameters that fits best with the problem at hand. Once they are determined, our model is ready to be used. So we’ll make the appropiate predictions on the validation dataset and save the model for later use."
},
{
"code": null,
"e": 22533,
"s": 22320,
"text": "We have covered a lot of important concepts through this article. Although having provided a high level overview of them, this is necessary to gain a good intuition on how and when to apply the methods explained."
},
{
"code": null,
"e": 22666,
"s": 22533,
"text": "We will explore these methods in more depth as they will keep coming up in the next articles, as well as its python implementations."
},
{
"code": null,
"e": 22778,
"s": 22666,
"text": "In the next article we will begin with the first and most common type of Machine Learning problems: Regression."
},
{
"code": null,
"e": 22887,
"s": 22778,
"text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here."
}
] |
Python os.chdir() Method
|
Python method chdir() changes the current working directory to the given path.It returns None in all the cases.
Following is the syntax for chdir() method −
os.chdir(path)
path − This is complete path of the directory to be changed to a new location.
path − This is complete path of the directory to be changed to a new location.
This method does not return any value.
The following example shows the usage of chdir() method.
#!/usr/bin/python
import os
path = "/usr/tmp"
# Check current working directory.
retval = os.getcwd()
print "Current working directory %s" % retval
# Now change the directory
os.chdir( path )
# Check current working directory.
retval = os.getcwd()
print "Directory changed successfully %s" % retval
When we run above program, it produces following result −
Current working directory /usr
Directory changed successfully /usr/tmp
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2356,
"s": 2244,
"text": "Python method chdir() changes the current working directory to the given path.It returns None in all the cases."
},
{
"code": null,
"e": 2401,
"s": 2356,
"text": "Following is the syntax for chdir() method −"
},
{
"code": null,
"e": 2417,
"s": 2401,
"text": "os.chdir(path)\n"
},
{
"code": null,
"e": 2496,
"s": 2417,
"text": "path − This is complete path of the directory to be changed to a new location."
},
{
"code": null,
"e": 2575,
"s": 2496,
"text": "path − This is complete path of the directory to be changed to a new location."
},
{
"code": null,
"e": 2614,
"s": 2575,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2671,
"s": 2614,
"text": "The following example shows the usage of chdir() method."
},
{
"code": null,
"e": 2975,
"s": 2671,
"text": "#!/usr/bin/python\nimport os\n\npath = \"/usr/tmp\"\n\n# Check current working directory.\nretval = os.getcwd()\nprint \"Current working directory %s\" % retval\n\n# Now change the directory\nos.chdir( path )\n\n# Check current working directory.\nretval = os.getcwd()\n\nprint \"Directory changed successfully %s\" % retval"
},
{
"code": null,
"e": 3033,
"s": 2975,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3105,
"s": 3033,
"text": "Current working directory /usr\nDirectory changed successfully /usr/tmp\n"
},
{
"code": null,
"e": 3142,
"s": 3105,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3158,
"s": 3142,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3191,
"s": 3158,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3210,
"s": 3191,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3245,
"s": 3210,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3267,
"s": 3245,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3301,
"s": 3267,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3329,
"s": 3301,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3364,
"s": 3329,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3378,
"s": 3364,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3411,
"s": 3378,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3428,
"s": 3411,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3435,
"s": 3428,
"text": " Print"
},
{
"code": null,
"e": 3446,
"s": 3435,
"text": " Add Notes"
}
] |
Express.js res.render() Function - GeeksforGeeks
|
19 Aug, 2021
The res.render() function is used to render a view and sends the rendered HTML string to the client.
Syntax:
res.render(view [, locals] [, callback])
Parameters: This function accept two parameters as mentioned above and described below:
Locals: It is basically an object whose properties define local variables for the view.
Callback It is a callback function.
Returns: It returns an Object.
Installation of express module:
1. You can visit the link to Install express module. You can install this package by using this command.
npm install express
2. After installing the express module, you can check your express version in command prompt using the command.
npm version express
3. After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
Javascript
var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); // Without middlewareapp.get('/user', function(req, res){ // Rendering home.ejs page res.render('home');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Create a home.ejs file in views folder with the following code: Filename: home.ejs
HTML
<html><head> <title>res.render() Demo</title></head><body> <h2>Welcome to GeeksforGeeks</h2></body></html>
Steps to run the program:
1. Make sure you have installed express and ejs module using the following command:
npm install express
npm install ejs
2. Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000
3. Now open browser and go to http://localhost:3000/user, you can see the following output on your screen:
Welcome to GeeksforGeeks
Example 2: Filename: index.js
Javascript
var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); // With middlewareapp.use('/', function(req, res, next){ res.render('User') next();}); app.get('/', function(req, res){ console.log("Render Working") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Create a User.ejs file in views folder with the following code: Filename: User.ejs
HTML
<html><head> <title>res.render() Demo</title></head><body> <h2>Render Function Demo</h2></body></html>
Run index.js file using below command:
node index.js
After running above command, you will see the following output on your console screen:
Server listening on PORT 3000
Render Working
Now open browser and go to http://localhost:3000, you can see the following output on your screen:
Render Function Demo
Reference: https://expressjs.com/en/5x/api.html#res.render
kalrap615
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Top 10 Front End Developer Skills That You Need in 2022
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?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24048,
"s": 24020,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 24150,
"s": 24048,
"text": "The res.render() function is used to render a view and sends the rendered HTML string to the client. "
},
{
"code": null,
"e": 24159,
"s": 24150,
"text": "Syntax: "
},
{
"code": null,
"e": 24200,
"s": 24159,
"text": "res.render(view [, locals] [, callback])"
},
{
"code": null,
"e": 24290,
"s": 24200,
"text": "Parameters: This function accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 24378,
"s": 24290,
"text": "Locals: It is basically an object whose properties define local variables for the view."
},
{
"code": null,
"e": 24414,
"s": 24378,
"text": "Callback It is a callback function."
},
{
"code": null,
"e": 24445,
"s": 24414,
"text": "Returns: It returns an Object."
},
{
"code": null,
"e": 24478,
"s": 24445,
"text": "Installation of express module: "
},
{
"code": null,
"e": 24584,
"s": 24478,
"text": "1. You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 24604,
"s": 24584,
"text": "npm install express"
},
{
"code": null,
"e": 24717,
"s": 24604,
"text": "2. After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 24737,
"s": 24717,
"text": "npm version express"
},
{
"code": null,
"e": 24871,
"s": 24737,
"text": "3. After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 24885,
"s": 24871,
"text": "node index.js"
},
{
"code": null,
"e": 24917,
"s": 24885,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 24928,
"s": 24917,
"text": "Javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); // Without middlewareapp.get('/user', function(req, res){ // Rendering home.ejs page res.render('home');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 25278,
"s": 24928,
"text": null
},
{
"code": null,
"e": 25362,
"s": 25278,
"text": "Create a home.ejs file in views folder with the following code: Filename: home.ejs "
},
{
"code": null,
"e": 25367,
"s": 25362,
"text": "HTML"
},
{
"code": "<html><head> <title>res.render() Demo</title></head><body> <h2>Welcome to GeeksforGeeks</h2></body></html>",
"e": 25480,
"s": 25367,
"text": null
},
{
"code": null,
"e": 25507,
"s": 25480,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 25592,
"s": 25507,
"text": "1. Make sure you have installed express and ejs module using the following command: "
},
{
"code": null,
"e": 25628,
"s": 25592,
"text": "npm install express\nnpm install ejs"
},
{
"code": null,
"e": 25671,
"s": 25628,
"text": "2. Run index.js file using below command: "
},
{
"code": null,
"e": 25685,
"s": 25671,
"text": "node index.js"
},
{
"code": null,
"e": 25694,
"s": 25685,
"text": "Output: "
},
{
"code": null,
"e": 25724,
"s": 25694,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 25832,
"s": 25724,
"text": "3. Now open browser and go to http://localhost:3000/user, you can see the following output on your screen: "
},
{
"code": null,
"e": 25857,
"s": 25832,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 25889,
"s": 25857,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 25900,
"s": 25889,
"text": "Javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); // With middlewareapp.use('/', function(req, res, next){ res.render('User') next();}); app.get('/', function(req, res){ console.log(\"Render Working\") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 26313,
"s": 25900,
"text": null
},
{
"code": null,
"e": 26397,
"s": 26313,
"text": "Create a User.ejs file in views folder with the following code: Filename: User.ejs "
},
{
"code": null,
"e": 26402,
"s": 26397,
"text": "HTML"
},
{
"code": "<html><head> <title>res.render() Demo</title></head><body> <h2>Render Function Demo</h2></body></html>",
"e": 26511,
"s": 26402,
"text": null
},
{
"code": null,
"e": 26551,
"s": 26511,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 26565,
"s": 26551,
"text": "node index.js"
},
{
"code": null,
"e": 26654,
"s": 26565,
"text": "After running above command, you will see the following output on your console screen: "
},
{
"code": null,
"e": 26699,
"s": 26654,
"text": "Server listening on PORT 3000\nRender Working"
},
{
"code": null,
"e": 26800,
"s": 26699,
"text": "Now open browser and go to http://localhost:3000, you can see the following output on your screen: "
},
{
"code": null,
"e": 26821,
"s": 26800,
"text": "Render Function Demo"
},
{
"code": null,
"e": 26881,
"s": 26821,
"text": "Reference: https://expressjs.com/en/5x/api.html#res.render "
},
{
"code": null,
"e": 26891,
"s": 26881,
"text": "kalrap615"
},
{
"code": null,
"e": 26902,
"s": 26891,
"text": "Express.js"
},
{
"code": null,
"e": 26910,
"s": 26902,
"text": "Node.js"
},
{
"code": null,
"e": 26927,
"s": 26910,
"text": "Web Technologies"
},
{
"code": null,
"e": 27025,
"s": 26927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27034,
"s": 27025,
"text": "Comments"
},
{
"code": null,
"e": 27047,
"s": 27034,
"text": "Old Comments"
},
{
"code": null,
"e": 27076,
"s": 27047,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 27106,
"s": 27076,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 27163,
"s": 27106,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 27217,
"s": 27163,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 27254,
"s": 27217,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 27310,
"s": 27254,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27372,
"s": 27310,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27415,
"s": 27372,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27465,
"s": 27415,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Multilingual Machine Learning. Exploring BLEU Scores using Patent Data | by Lee Mackey | Towards Data Science
|
Does your machine learn in Chinese? I don’t speak Mandarin or Cantonese so Google Translate gets all the credit — good or bad — for translating the preceding sentence into “您的機器學習中文嗎?” But how might a researcher quickly evaluate the quality of machine translations? This question encapsulates the basic challenge that gives rise to the BLEU metric. BLEU, which stands for bilingual language understudy, is a default measure of machine translation quality and is also sometimes applied to cross-lingual natural language processing (NLP) tasks. The metric is well-established in the machine translation space but some analysts question the algorithm’s applicability to a wider set of tasks beyond the measure’s original objectives. This article takes an initial dive into the lessons, implementations, and limits of BLEU using examples drawn from multilingual patent documents.
Researchers at IBM developed the BLEU algorithm in 2002 as an efficient method to evaluate the quality of machine translation in reference to benchmark human translations. The original paper by the developers, Papineni, and colleagues, is a good place to start if you’re interested in the founding context and objectives of the algorithm. BLEU is an adjusted precision measure of the matching word sequences between a “candidate” machine translation and one or multiple “reference” human translations. BLEU counts “n-grams”, a term for word sequences of length n, in a machine translation that match the n-grams in a human translation, divided by the total count of n-grams in the machine translation. The measure is adjusted in that it clips the match count to the maximum number of n-gram occurrences in a human translation and also penalizes machine translations that diverge in word length from the reference translation.
The resulting BLEU score is a number between 0 and 1, in which 0 represents zero n-gram matches between candidate and reference texts and 1 might equal a machine translation that is exactly similar to one of the references. In practice, the measure counts matches across multiple word sequence lengths — 4-grams (four-word sequences), tri-grams (three-word sequences), bi-grams (two-word sequences), and uni-grams (one-word sequences) — via a geometric mean of the respective n-gram calculations. The algorithm was designed for comparisons at the level of a corpus of sentences, with n-gram matches calculated at the basic unit of a sentence and then combined into a corpus-level score. To clarify terminology, the use of the term “document” in the present article refers to a corpus of sentences. If you’re interested in additional resources to understand the algorithm, you might check out the video tutorial at deeplearning.ai that discusses the details of the algorithm or the written tutorial at machinelearningmastery.com that explores the NLTK implementation. To explore the tangible use cases of the metric, I next apply BLEU using translations of Chinese-language patents.
A growing share of patents in the machine learning space is written and filed in Chinese according to a recent report by WIPO (World Intellectual Property Organization), the global organization that governs patents. To explore the basics of BLEU in this multilingual space, you can first begin with a domestic Chinese patent of an NLP innovation that the e-commerce company Alibaba extended to global coverage. The title of the Chinese language patent is displayed below. For additional details surrounding the example patent,
original_title_cn = "机器处理及文本纠错方法和装置、计算设备以及存储介质"
WIPO’s data query tool provides both English and Chinese language versions that you can inspect in your browser.
Human specialists often produce translations of equivalent quality that nonetheless differ in word choice and structure. BLEU, therefore, accepts single or multiple human translations as the references for comparison. To explore the production of reference translations more directly, I obtain two Chinese-to-English translations of the Chinese language patent from two different human translators via Gengo, a web-based platform for human translators. Next, you can source “candidate” machine translations from two
reference_human1_summary = "The invention discloses a machine processing and text error correction method and device, a computing device, and a storage medium, specifically comprising corrected and rewritten text pairs of incorrect text and corresponding correct text. The corrected and rewritten text pairs serving as a training corpus to train the machine processing model, thereby preparing a machine processing model suitable for text error correction. Through extraction of corrected and rewritten text pairs from a log, the machine processing model can be trained and thus made fit for text correction by inputting the first text into the machine processing model to get the second text, that is the error correction result text. In addition, the language model or the common lexicon can be used to determine whether the first text needs to be corrected. The training corpus extracted from a log can be used to train the language model, or the common lexicon can be sorted by segmenting and counting text in the log. This is how to easily implement text error correction."reference_human2_summary = "This invention makes public a machine processing and text error correction method and hardware, computing equipment and storage medium, and specifically pairs error text with the corresponding corrected and modified correct text. It uses this text pair as training material for the machine processing model, and from there prepares the machine processing model that is applied to the text correction. It can train the machine processing model using a diary or daily journal and make it suitable for text correction. The first text version is inputted into the machine processing model to get the second text version, which is the corrected text. Additionally, it can also use a stored language model or common vocabulary bank to determine if the first text version needs correction. It can use the practice language material gathered from the diary or daily journal to train the language model, and it can also initialize the common vocabulary bank through the segmentation and analysis of the diary or daily journal text. Through all this, text correction is conveniently implemented."
separate machine learning algorithms, Google Translate and the World Intellectual Property Organization (WIPO), which are displayed below.
candidate_google_summary = "The invention discloses a machine processing and text error correction method and device, a computing device and a storage medium, and particularly comprises an error correction rewriting pair of an error text and a corresponding correct text, and an error correction rewriting pair as a training corpus, and a machine processing model. Training is performed, thereby preparing a machine processing model suitable for text correction. The machine processing model can be trained to mine the error correction by mining the error correction rewrite pair from the log. The first text is input into the machine processing model to obtain a second text, that is, an error correction result text. In addition, you can use the language model or common lexicon to determine whether the first text needs to be corrected. The language model can be trained using the training corpus extracted from the log, or the common lexicon can be organized by segmenting and counting the text in the log. Thereby, text correction is facilitated."candidate_wipo_summary = "The present invention discloses a machine processing and text correction method and device, computing equipment and a storage medium. Specifically comprising corrected and rewritten text pairs of incorrect text and corresponding correct text, the corrected and rewritten text pairs serving as a training corpus for training a machine processing model, and in this way developing a machine processing model for use in text correction. Through extraction of corrected and rewritten text pairs from a log, the machine processing model can be trained and thus made fit for text correction by inputting a first text into the machine processing model to obtain a second text i.e. a corrected text result. Moreover, a language model or a lexicon of commonly used words can be used to assess whether text needs correction. The training corpus extracted from the log can be used to train the language model and also, through text segmentation and statistical analysis of text in the log compile a lexicon of commonly used words. Thus, text correction can be made easier and more convenient."
There are multiple implementations and extensions of BLEU, such as the popular sacreBLEU package, among others. The present example begins by calculating scores using the bleu_score module in the Natural Language Toolkit (NLTK), which is based on the original implementation by Papineni et al. The corpus_bleu function accepts reference and candidate translations represented as individual word tokens that you can create through standard NLP pre-processing steps. For a document with multiple sentences, the original BLEU implementation computes the n-gram matches sentence by sentence, then sums the clipped n-gram counts for all the candidate sentences and, lastly, divides by the number of candidate n-grams in the document. As the NLTK documentation states: the BLEU metric “calculates the micro-average precision (i.e. summing the numerators and denominators for each hypothesis-reference(s) pairs before the division).” By default, corpus_bleu calculates the geometric mean of equally-weighted n-gram scores comprising 4-grams, tri-grams, bi-grams, and unigrams.
What are the results of the BLEU score calculations for the two machine translation examples? The results indicate that the Google and WIPO translations are of similar quality in relation to the reference translations from human translators on Gengo. The score of the first candidate translation by Google Translate is 0.53 and the score of WIPO is 0.54, as displayed below.
# calculate BLEU score of Google translationbleu_google = round(corpus_bleu(refs_list_6, can_google_summary[:]), 2)# calculate BLEU score of WIPO translationbleu_wipo = round(corpus_bleu(refs_list_5, can_wipo_summary[:]), 2)print(f"Google Translate BLEU score: {bleu_google}")print(f"WIPO BLEU score: {bleu_wipo}")
With this tangible example of the application of BLEU in mind, it is helpful to establish the potential scope of the algorithm’s applicability to machine translation and natural language processing tasks.
There is a general agreement among researchers that BLEU is expedient for evaluations of machine translation systems. However, some researchers caution that BLEU may not be appropriate for certain aspects of machine translation or wider NLP tasks. A key critique is that BLEU scores may not necessarily correlate well with significant quality differences in human translations. As Callison-Burch and colleagues argue in a highly-cited paper: “there are instances when an improvement in BLEU is not sufficient to reflect a genuine improvement in translation quality, and in other circumstances that it is not necessary to improve BLEU to achieve a noticeable improvement in translation quality.” These authors also suggest that BLEU may not be appropriate for comparing machine translation systems that utilize different techniques, detecting aspects of translation that BLEU doesn’t model, or evaluating infrequent improvements within a test corpus.
Researchers that conduct a literature review of BLEU argue in a recent paper that BLEU–human correlations may vary with the details of the systems being evaluated, the particular corpus texts used, and the exact protocol utilized for human evaluations. The authors, Reiter and colleagues, suggest that BLEU should be evaluated by real-world human evaluations such as A/B tests to determine contexts in which BLEU reliably correlates with real-world effectiveness. Based on the results of the literature review, these authors caution that researchers should approach BLEU as a diagnostic for machine translation at the system level but not as an evaluation technique to measure the output of a system. With the literature suggesting a general recognition of both the utility and shortcomings of the measure, some researchers, such as the author of a recent paper, focus on increased clarity in the reporting of BLEU scores. This would include, for example, having researchers include preprocessing schemes and other standardized conventions for reporting the implementation and scoring details of BLEU scores. The points raised in these papers sound notes in caution in applying and interpreting BLEU scores in the patent space and across different use cases.
This article outlines objectives, examples, and limits of BLEU scores. To run the full Python code that accompanies this article in a Jupyter notebook, you can head to the Github repository for Multilingual Machine Learning. For more background on my interest in this space, check out my website at lee-mackey.com. As patent documents in the machine learning space continue to become increasingly multilingual, particularly from Chinese language patents, the points raised in this article hopefully help you to surface and contextualize considerations when applying this algorithm to your particular use cases. If you’re working across languages in your NLP workflows, understanding these details of BLEU will help to select if, when, and how to use this metric in your projects.
|
[
{
"code": null,
"e": 1047,
"s": 171,
"text": "Does your machine learn in Chinese? I don’t speak Mandarin or Cantonese so Google Translate gets all the credit — good or bad — for translating the preceding sentence into “您的機器學習中文嗎?” But how might a researcher quickly evaluate the quality of machine translations? This question encapsulates the basic challenge that gives rise to the BLEU metric. BLEU, which stands for bilingual language understudy, is a default measure of machine translation quality and is also sometimes applied to cross-lingual natural language processing (NLP) tasks. The metric is well-established in the machine translation space but some analysts question the algorithm’s applicability to a wider set of tasks beyond the measure’s original objectives. This article takes an initial dive into the lessons, implementations, and limits of BLEU using examples drawn from multilingual patent documents."
},
{
"code": null,
"e": 1973,
"s": 1047,
"text": "Researchers at IBM developed the BLEU algorithm in 2002 as an efficient method to evaluate the quality of machine translation in reference to benchmark human translations. The original paper by the developers, Papineni, and colleagues, is a good place to start if you’re interested in the founding context and objectives of the algorithm. BLEU is an adjusted precision measure of the matching word sequences between a “candidate” machine translation and one or multiple “reference” human translations. BLEU counts “n-grams”, a term for word sequences of length n, in a machine translation that match the n-grams in a human translation, divided by the total count of n-grams in the machine translation. The measure is adjusted in that it clips the match count to the maximum number of n-gram occurrences in a human translation and also penalizes machine translations that diverge in word length from the reference translation."
},
{
"code": null,
"e": 3155,
"s": 1973,
"text": "The resulting BLEU score is a number between 0 and 1, in which 0 represents zero n-gram matches between candidate and reference texts and 1 might equal a machine translation that is exactly similar to one of the references. In practice, the measure counts matches across multiple word sequence lengths — 4-grams (four-word sequences), tri-grams (three-word sequences), bi-grams (two-word sequences), and uni-grams (one-word sequences) — via a geometric mean of the respective n-gram calculations. The algorithm was designed for comparisons at the level of a corpus of sentences, with n-gram matches calculated at the basic unit of a sentence and then combined into a corpus-level score. To clarify terminology, the use of the term “document” in the present article refers to a corpus of sentences. If you’re interested in additional resources to understand the algorithm, you might check out the video tutorial at deeplearning.ai that discusses the details of the algorithm or the written tutorial at machinelearningmastery.com that explores the NLTK implementation. To explore the tangible use cases of the metric, I next apply BLEU using translations of Chinese-language patents."
},
{
"code": null,
"e": 3682,
"s": 3155,
"text": "A growing share of patents in the machine learning space is written and filed in Chinese according to a recent report by WIPO (World Intellectual Property Organization), the global organization that governs patents. To explore the basics of BLEU in this multilingual space, you can first begin with a domestic Chinese patent of an NLP innovation that the e-commerce company Alibaba extended to global coverage. The title of the Chinese language patent is displayed below. For additional details surrounding the example patent,"
},
{
"code": null,
"e": 3730,
"s": 3682,
"text": "original_title_cn = \"机器处理及文本纠错方法和装置、计算设备以及存储介质\""
},
{
"code": null,
"e": 3843,
"s": 3730,
"text": "WIPO’s data query tool provides both English and Chinese language versions that you can inspect in your browser."
},
{
"code": null,
"e": 4359,
"s": 3843,
"text": "Human specialists often produce translations of equivalent quality that nonetheless differ in word choice and structure. BLEU, therefore, accepts single or multiple human translations as the references for comparison. To explore the production of reference translations more directly, I obtain two Chinese-to-English translations of the Chinese language patent from two different human translators via Gengo, a web-based platform for human translators. Next, you can source “candidate” machine translations from two"
},
{
"code": null,
"e": 6552,
"s": 4359,
"text": "reference_human1_summary = \"The invention discloses a machine processing and text error correction method and device, a computing device, and a storage medium, specifically comprising corrected and rewritten text pairs of incorrect text and corresponding correct text. The corrected and rewritten text pairs serving as a training corpus to train the machine processing model, thereby preparing a machine processing model suitable for text error correction. Through extraction of corrected and rewritten text pairs from a log, the machine processing model can be trained and thus made fit for text correction by inputting the first text into the machine processing model to get the second text, that is the error correction result text. In addition, the language model or the common lexicon can be used to determine whether the first text needs to be corrected. The training corpus extracted from a log can be used to train the language model, or the common lexicon can be sorted by segmenting and counting text in the log. This is how to easily implement text error correction.\"reference_human2_summary = \"This invention makes public a machine processing and text error correction method and hardware, computing equipment and storage medium, and specifically pairs error text with the corresponding corrected and modified correct text. It uses this text pair as training material for the machine processing model, and from there prepares the machine processing model that is applied to the text correction. It can train the machine processing model using a diary or daily journal and make it suitable for text correction. The first text version is inputted into the machine processing model to get the second text version, which is the corrected text. Additionally, it can also use a stored language model or common vocabulary bank to determine if the first text version needs correction. It can use the practice language material gathered from the diary or daily journal to train the language model, and it can also initialize the common vocabulary bank through the segmentation and analysis of the diary or daily journal text. Through all this, text correction is conveniently implemented.\""
},
{
"code": null,
"e": 6691,
"s": 6552,
"text": "separate machine learning algorithms, Google Translate and the World Intellectual Property Organization (WIPO), which are displayed below."
},
{
"code": null,
"e": 8852,
"s": 6691,
"text": "candidate_google_summary = \"The invention discloses a machine processing and text error correction method and device, a computing device and a storage medium, and particularly comprises an error correction rewriting pair of an error text and a corresponding correct text, and an error correction rewriting pair as a training corpus, and a machine processing model. Training is performed, thereby preparing a machine processing model suitable for text correction. The machine processing model can be trained to mine the error correction by mining the error correction rewrite pair from the log. The first text is input into the machine processing model to obtain a second text, that is, an error correction result text. In addition, you can use the language model or common lexicon to determine whether the first text needs to be corrected. The language model can be trained using the training corpus extracted from the log, or the common lexicon can be organized by segmenting and counting the text in the log. Thereby, text correction is facilitated.\"candidate_wipo_summary = \"The present invention discloses a machine processing and text correction method and device, computing equipment and a storage medium. Specifically comprising corrected and rewritten text pairs of incorrect text and corresponding correct text, the corrected and rewritten text pairs serving as a training corpus for training a machine processing model, and in this way developing a machine processing model for use in text correction. Through extraction of corrected and rewritten text pairs from a log, the machine processing model can be trained and thus made fit for text correction by inputting a first text into the machine processing model to obtain a second text i.e. a corrected text result. Moreover, a language model or a lexicon of commonly used words can be used to assess whether text needs correction. The training corpus extracted from the log can be used to train the language model and also, through text segmentation and statistical analysis of text in the log compile a lexicon of commonly used words. Thus, text correction can be made easier and more convenient.\""
},
{
"code": null,
"e": 9922,
"s": 8852,
"text": "There are multiple implementations and extensions of BLEU, such as the popular sacreBLEU package, among others. The present example begins by calculating scores using the bleu_score module in the Natural Language Toolkit (NLTK), which is based on the original implementation by Papineni et al. The corpus_bleu function accepts reference and candidate translations represented as individual word tokens that you can create through standard NLP pre-processing steps. For a document with multiple sentences, the original BLEU implementation computes the n-gram matches sentence by sentence, then sums the clipped n-gram counts for all the candidate sentences and, lastly, divides by the number of candidate n-grams in the document. As the NLTK documentation states: the BLEU metric “calculates the micro-average precision (i.e. summing the numerators and denominators for each hypothesis-reference(s) pairs before the division).” By default, corpus_bleu calculates the geometric mean of equally-weighted n-gram scores comprising 4-grams, tri-grams, bi-grams, and unigrams."
},
{
"code": null,
"e": 10297,
"s": 9922,
"text": "What are the results of the BLEU score calculations for the two machine translation examples? The results indicate that the Google and WIPO translations are of similar quality in relation to the reference translations from human translators on Gengo. The score of the first candidate translation by Google Translate is 0.53 and the score of WIPO is 0.54, as displayed below."
},
{
"code": null,
"e": 10640,
"s": 10297,
"text": "# calculate BLEU score of Google translationbleu_google = round(corpus_bleu(refs_list_6, can_google_summary[:]), 2)# calculate BLEU score of WIPO translationbleu_wipo = round(corpus_bleu(refs_list_5, can_wipo_summary[:]), 2)print(f\"Google Translate BLEU score: {bleu_google}\")print(f\"WIPO BLEU score: {bleu_wipo}\")"
},
{
"code": null,
"e": 10845,
"s": 10640,
"text": "With this tangible example of the application of BLEU in mind, it is helpful to establish the potential scope of the algorithm’s applicability to machine translation and natural language processing tasks."
},
{
"code": null,
"e": 11795,
"s": 10845,
"text": "There is a general agreement among researchers that BLEU is expedient for evaluations of machine translation systems. However, some researchers caution that BLEU may not be appropriate for certain aspects of machine translation or wider NLP tasks. A key critique is that BLEU scores may not necessarily correlate well with significant quality differences in human translations. As Callison-Burch and colleagues argue in a highly-cited paper: “there are instances when an improvement in BLEU is not sufficient to reflect a genuine improvement in translation quality, and in other circumstances that it is not necessary to improve BLEU to achieve a noticeable improvement in translation quality.” These authors also suggest that BLEU may not be appropriate for comparing machine translation systems that utilize different techniques, detecting aspects of translation that BLEU doesn’t model, or evaluating infrequent improvements within a test corpus."
},
{
"code": null,
"e": 13054,
"s": 11795,
"text": "Researchers that conduct a literature review of BLEU argue in a recent paper that BLEU–human correlations may vary with the details of the systems being evaluated, the particular corpus texts used, and the exact protocol utilized for human evaluations. The authors, Reiter and colleagues, suggest that BLEU should be evaluated by real-world human evaluations such as A/B tests to determine contexts in which BLEU reliably correlates with real-world effectiveness. Based on the results of the literature review, these authors caution that researchers should approach BLEU as a diagnostic for machine translation at the system level but not as an evaluation technique to measure the output of a system. With the literature suggesting a general recognition of both the utility and shortcomings of the measure, some researchers, such as the author of a recent paper, focus on increased clarity in the reporting of BLEU scores. This would include, for example, having researchers include preprocessing schemes and other standardized conventions for reporting the implementation and scoring details of BLEU scores. The points raised in these papers sound notes in caution in applying and interpreting BLEU scores in the patent space and across different use cases."
}
] |
C# Program to Display Date in String - GeeksforGeeks
|
27 Dec, 2021
System namespace and mscorlib.dll assembly in C# language provide a variety of classes and structures. It also provides DateTime struct using which we can initialize Data and Time objects. Using this struct we can also determine the year, month, weekday, etc.
1. DateTime Constructor: DateTime constructor is used for initializing an instance of the DateTime struct. The constructor method accepts year, month, day, time as parameters.
Syntax:
DateTime myDate = new DateTime(YYYY, MM, DD);
Note that the DateTime struct consists of a total of eleven overloaded constructors defined for different purposes. This article only focuses upon how we can display Date in string format in C# so we would not discuss all the remaining constructors.
2. DateTime.now() method: To get the current date and time DateTime.now() method of the DateTime struct is used. It returns an object of the DateTime struct which can be presented as a string using the ToString() method as explained below.
Syntax:
DateTime.now(format);
Return type: Returns an object of DateTime struct that contains the current date and time
3. ToString() method: This is quite useful whenever we want to print an object in string format. This method is used to convert the current DateTime object value to a string using the specified format.
Syntax:
DateTime.ToString(format);
Return type: Returns a string that represents the current date and time
There are numerous formats to display a date in the console. For example, Date/Month/Year, Month/Date/Year, etc. C# provides a number of overloaded DateTime.now() constructor methods that help to print date in various formats. Some of the commonly used methods are discussed below in detail:
1. This method is used to create an object of DateTime struct that contains current data in the format “Month/Day/Year”. Since it returns an instance of the DateTime struct so we can use it as a string by using the ToString() method. For example, 12/04/2021.
Syntax:
DateTime.Now.ToString(“MM/dd/yyyy”)
Return type: Returns a string format of the current date
2. This method is used to create an object of DateTime struct that contains current data in the format “Month Date”. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, December 04
Syntax:
DateTime.Now.ToString(“MMMM dd”)
Return type: Returns a string format of the current date
3. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday,03 December 2021 04:10 AM
Syntax:
DateTime.Now.ToString(“dddd, dd MMMM yyyy”)
Return type: Returns a string format of the current date
4. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday, 04 December 2021 06:40:59
Syntax:
DateTime.Now.ToString(“dddd, dd MMMM yyyy HH:mm:ss”)
Return type: Returns a string format of the current date
5. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:41
Syntax:
DateTime.Now.ToString(“MM/dd/yyyy HH:mm”)
Return type: Returns a string format of the current date
6. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:44 AM
Syntax:
DateTime.Now.ToString(“MM/dd/yyyy hh:mm tt”)
Return type: Returns a string format of the current date
7. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 6:44
Syntax:
DateTime.Now.ToString(“MM/dd/yyyy H:mm”)
Return type: Returns a string format of the current date
8. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’33’:’15.9841280+00:00
Syntax:
DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK”)
Return type: Returns a string format of the current date
9. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Sat, 04 Dec 2021 07’:’34’:’42 ‘G12T
Syntax:
DateTime.Now.ToString(“ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT”)
Return type: Returns a string format of the current date
10. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’41’:’12
Syntax:
DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss”)
Return type: Returns a string format of the current date
Below is the implementation to illustrate these methods.
Example:
C#
// C# program to illustrate how we can// display date and time in a string formatusing System; class GFG{ static public void Main(){ // Getting the string form of the current date in // a format i.e, 12/04/2021 string currentDate1 = DateTime.Now.ToString("MM/dd/yyyy"); // Displaying the current date Console.WriteLine("currentDate1 : " + currentDate1); // Getting the string form of the current date in // a format i.e, Saturday, 04 December 2021 string currentDate2 = DateTime.Now.ToString("dddd, dd MMMM yyyy"); // Displaying the current date Console.WriteLine("currentDate2 : " + currentDate2); // Getting the string form of the current date // in a format i.e, December 04 string currentDate3 = DateTime.Now.ToString("MMMM dd"); // Displaying current date Console.WriteLine("currentDate3 : " + currentDate3); // Getting the string form of the current date // in a format, Saturday, i.e, 04 December 2021 19:12:29 string currentDate4 = DateTime.Now.ToString( "dddd, dd MMMM yyyy HH:mm:ss"); // Displaying current date Console.WriteLine("currentDate4 : " + currentDate4); // Getting the string form of the current date // in a format, i.e, 12/04/2021 19:12 string currentDate5 = DateTime.Now.ToString("MM/dd/yyyy HH:mm"); // Displaying current date Console.WriteLine("currentDate5 : " + currentDate5); // Getting the string form of the current date // in a format, i.e, 12/04/2021 07:12 PM string currentDate6 = DateTime.Now.ToString("MM/dd/yyyy hh:mm tt"); // Displaying current date Console.WriteLine("currentDate6 : " + currentDate6); // Getting the string form of the current date in // a format,i.e, 12/04/2021 19:12 string currentDate7 = DateTime.Now.ToString("MM/dd/yyyy H:mm"); // Displaying current date Console.WriteLine("currentDate7 : " + currentDate7); // Getting the string form of the current date in // a format, 2021’-‘12’-‘04’T’19’:’12’:’29.6715830+00:00 string currentDate8 = DateTime.Now.ToString( "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK"); // Displaying current date Console.WriteLine("currentDate8 : " + currentDate8); // Getting the string form of the current date in // a format, Sat, 04 Dec 2021 19’:’12’:’29 ‘G12T string currentDate9 = DateTime.Now.ToString( "ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT"); // Displaying current date Console.WriteLine("currentDate9 : " + currentDate9); // Getting the string form of the current date in // a format, 2021’-‘12’-‘04’T’19’:’12’:’29 string currentDate10 = DateTime.Now.ToString( "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss"); // Displaying current date Console.WriteLine("currentDate10 : " + currentDate10);}}
Output:
currentDate1 : 12/07/2021
currentDate2 : Tuesday, 07 December 2021
currentDate3 : December 07
currentDate4 : Tuesday, 07 December 2021 09:00:37
currentDate5 : 12/07/2021 09:00
currentDate6 : 12/07/2021 09:00 AM
currentDate7 : 12/07/2021 9:00
currentDate8 : 2021’-‘12’-‘07’T’09’:’00’:’37.9475430+05:30
currentDate9 : Tue, 07 Dec 2021 09’:’00’:’37 ‘G12T
currentDate10 : 2021’-‘12’-‘07’T’09’:’00’:’37
surinderdawra388
CSharp-Strings-Programs
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 24562,
"s": 24302,
"text": "System namespace and mscorlib.dll assembly in C# language provide a variety of classes and structures. It also provides DateTime struct using which we can initialize Data and Time objects. Using this struct we can also determine the year, month, weekday, etc."
},
{
"code": null,
"e": 24739,
"s": 24562,
"text": "1. DateTime Constructor: DateTime constructor is used for initializing an instance of the DateTime struct. The constructor method accepts year, month, day, time as parameters. "
},
{
"code": null,
"e": 24747,
"s": 24739,
"text": "Syntax:"
},
{
"code": null,
"e": 24797,
"s": 24747,
"text": "DateTime myDate = new DateTime(YYYY, MM, DD); "
},
{
"code": null,
"e": 25047,
"s": 24797,
"text": "Note that the DateTime struct consists of a total of eleven overloaded constructors defined for different purposes. This article only focuses upon how we can display Date in string format in C# so we would not discuss all the remaining constructors."
},
{
"code": null,
"e": 25287,
"s": 25047,
"text": "2. DateTime.now() method: To get the current date and time DateTime.now() method of the DateTime struct is used. It returns an object of the DateTime struct which can be presented as a string using the ToString() method as explained below."
},
{
"code": null,
"e": 25295,
"s": 25287,
"text": "Syntax:"
},
{
"code": null,
"e": 25317,
"s": 25295,
"text": "DateTime.now(format);"
},
{
"code": null,
"e": 25407,
"s": 25317,
"text": "Return type: Returns an object of DateTime struct that contains the current date and time"
},
{
"code": null,
"e": 25609,
"s": 25407,
"text": "3. ToString() method: This is quite useful whenever we want to print an object in string format. This method is used to convert the current DateTime object value to a string using the specified format."
},
{
"code": null,
"e": 25617,
"s": 25609,
"text": "Syntax:"
},
{
"code": null,
"e": 25644,
"s": 25617,
"text": "DateTime.ToString(format);"
},
{
"code": null,
"e": 25716,
"s": 25644,
"text": "Return type: Returns a string that represents the current date and time"
},
{
"code": null,
"e": 26008,
"s": 25716,
"text": "There are numerous formats to display a date in the console. For example, Date/Month/Year, Month/Date/Year, etc. C# provides a number of overloaded DateTime.now() constructor methods that help to print date in various formats. Some of the commonly used methods are discussed below in detail:"
},
{
"code": null,
"e": 26267,
"s": 26008,
"text": "1. This method is used to create an object of DateTime struct that contains current data in the format “Month/Day/Year”. Since it returns an instance of the DateTime struct so we can use it as a string by using the ToString() method. For example, 12/04/2021."
},
{
"code": null,
"e": 26275,
"s": 26267,
"text": "Syntax:"
},
{
"code": null,
"e": 26311,
"s": 26275,
"text": "DateTime.Now.ToString(“MM/dd/yyyy”)"
},
{
"code": null,
"e": 26368,
"s": 26311,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 26620,
"s": 26368,
"text": "2. This method is used to create an object of DateTime struct that contains current data in the format “Month Date”. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, December 04"
},
{
"code": null,
"e": 26628,
"s": 26620,
"text": "Syntax:"
},
{
"code": null,
"e": 26661,
"s": 26628,
"text": "DateTime.Now.ToString(“MMMM dd”)"
},
{
"code": null,
"e": 26718,
"s": 26661,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 26984,
"s": 26718,
"text": "3. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday,03 December 2021 04:10 AM"
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Syntax:"
},
{
"code": null,
"e": 27037,
"s": 26992,
"text": "DateTime.Now.ToString(“dddd, dd MMMM yyyy”) "
},
{
"code": null,
"e": 27094,
"s": 27037,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 27361,
"s": 27094,
"text": "4. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday, 04 December 2021 06:40:59"
},
{
"code": null,
"e": 27369,
"s": 27361,
"text": "Syntax:"
},
{
"code": null,
"e": 27422,
"s": 27369,
"text": "DateTime.Now.ToString(“dddd, dd MMMM yyyy HH:mm:ss”)"
},
{
"code": null,
"e": 27479,
"s": 27422,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 27727,
"s": 27479,
"text": "5. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:41"
},
{
"code": null,
"e": 27735,
"s": 27727,
"text": "Syntax:"
},
{
"code": null,
"e": 27777,
"s": 27735,
"text": "DateTime.Now.ToString(“MM/dd/yyyy HH:mm”)"
},
{
"code": null,
"e": 27834,
"s": 27777,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 28085,
"s": 27834,
"text": "6. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:44 AM"
},
{
"code": null,
"e": 28093,
"s": 28085,
"text": "Syntax:"
},
{
"code": null,
"e": 28138,
"s": 28093,
"text": "DateTime.Now.ToString(“MM/dd/yyyy hh:mm tt”)"
},
{
"code": null,
"e": 28195,
"s": 28138,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 28442,
"s": 28195,
"text": "7. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 6:44"
},
{
"code": null,
"e": 28450,
"s": 28442,
"text": "Syntax:"
},
{
"code": null,
"e": 28491,
"s": 28450,
"text": "DateTime.Now.ToString(“MM/dd/yyyy H:mm”)"
},
{
"code": null,
"e": 28548,
"s": 28491,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 28823,
"s": 28548,
"text": "8. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’33’:’15.9841280+00:00"
},
{
"code": null,
"e": 28831,
"s": 28823,
"text": "Syntax:"
},
{
"code": null,
"e": 28895,
"s": 28831,
"text": "DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK”)"
},
{
"code": null,
"e": 28952,
"s": 28895,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 29219,
"s": 28952,
"text": "9. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Sat, 04 Dec 2021 07’:’34’:’42 ‘G12T"
},
{
"code": null,
"e": 29227,
"s": 29219,
"text": "Syntax:"
},
{
"code": null,
"e": 29286,
"s": 29227,
"text": "DateTime.Now.ToString(“ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT”)"
},
{
"code": null,
"e": 29343,
"s": 29286,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 29605,
"s": 29343,
"text": "10. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’41’:’12"
},
{
"code": null,
"e": 29613,
"s": 29605,
"text": "Syntax:"
},
{
"code": null,
"e": 29668,
"s": 29613,
"text": "DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss”)"
},
{
"code": null,
"e": 29725,
"s": 29668,
"text": "Return type: Returns a string format of the current date"
},
{
"code": null,
"e": 29782,
"s": 29725,
"text": "Below is the implementation to illustrate these methods."
},
{
"code": null,
"e": 29791,
"s": 29782,
"text": "Example:"
},
{
"code": null,
"e": 29794,
"s": 29791,
"text": "C#"
},
{
"code": "// C# program to illustrate how we can// display date and time in a string formatusing System; class GFG{ static public void Main(){ // Getting the string form of the current date in // a format i.e, 12/04/2021 string currentDate1 = DateTime.Now.ToString(\"MM/dd/yyyy\"); // Displaying the current date Console.WriteLine(\"currentDate1 : \" + currentDate1); // Getting the string form of the current date in // a format i.e, Saturday, 04 December 2021 string currentDate2 = DateTime.Now.ToString(\"dddd, dd MMMM yyyy\"); // Displaying the current date Console.WriteLine(\"currentDate2 : \" + currentDate2); // Getting the string form of the current date // in a format i.e, December 04 string currentDate3 = DateTime.Now.ToString(\"MMMM dd\"); // Displaying current date Console.WriteLine(\"currentDate3 : \" + currentDate3); // Getting the string form of the current date // in a format, Saturday, i.e, 04 December 2021 19:12:29 string currentDate4 = DateTime.Now.ToString( \"dddd, dd MMMM yyyy HH:mm:ss\"); // Displaying current date Console.WriteLine(\"currentDate4 : \" + currentDate4); // Getting the string form of the current date // in a format, i.e, 12/04/2021 19:12 string currentDate5 = DateTime.Now.ToString(\"MM/dd/yyyy HH:mm\"); // Displaying current date Console.WriteLine(\"currentDate5 : \" + currentDate5); // Getting the string form of the current date // in a format, i.e, 12/04/2021 07:12 PM string currentDate6 = DateTime.Now.ToString(\"MM/dd/yyyy hh:mm tt\"); // Displaying current date Console.WriteLine(\"currentDate6 : \" + currentDate6); // Getting the string form of the current date in // a format,i.e, 12/04/2021 19:12 string currentDate7 = DateTime.Now.ToString(\"MM/dd/yyyy H:mm\"); // Displaying current date Console.WriteLine(\"currentDate7 : \" + currentDate7); // Getting the string form of the current date in // a format, 2021’-‘12’-‘04’T’19’:’12’:’29.6715830+00:00 string currentDate8 = DateTime.Now.ToString( \"yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK\"); // Displaying current date Console.WriteLine(\"currentDate8 : \" + currentDate8); // Getting the string form of the current date in // a format, Sat, 04 Dec 2021 19’:’12’:’29 ‘G12T string currentDate9 = DateTime.Now.ToString( \"ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT\"); // Displaying current date Console.WriteLine(\"currentDate9 : \" + currentDate9); // Getting the string form of the current date in // a format, 2021’-‘12’-‘04’T’19’:’12’:’29 string currentDate10 = DateTime.Now.ToString( \"yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss\"); // Displaying current date Console.WriteLine(\"currentDate10 : \" + currentDate10);}}",
"e": 32712,
"s": 29794,
"text": null
},
{
"code": null,
"e": 32720,
"s": 32712,
"text": "Output:"
},
{
"code": null,
"e": 33118,
"s": 32720,
"text": "currentDate1 : 12/07/2021\ncurrentDate2 : Tuesday, 07 December 2021\ncurrentDate3 : December 07\ncurrentDate4 : Tuesday, 07 December 2021 09:00:37\ncurrentDate5 : 12/07/2021 09:00\ncurrentDate6 : 12/07/2021 09:00 AM\ncurrentDate7 : 12/07/2021 9:00\ncurrentDate8 : 2021’-‘12’-‘07’T’09’:’00’:’37.9475430+05:30\ncurrentDate9 : Tue, 07 Dec 2021 09’:’00’:’37 ‘G12T\ncurrentDate10 : 2021’-‘12’-‘07’T’09’:’00’:’37"
},
{
"code": null,
"e": 33135,
"s": 33118,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33159,
"s": 33135,
"text": "CSharp-Strings-Programs"
},
{
"code": null,
"e": 33166,
"s": 33159,
"text": "Picked"
},
{
"code": null,
"e": 33169,
"s": 33166,
"text": "C#"
},
{
"code": null,
"e": 33181,
"s": 33169,
"text": "C# Programs"
},
{
"code": null,
"e": 33279,
"s": 33181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33297,
"s": 33279,
"text": "Destructors in C#"
},
{
"code": null,
"e": 33320,
"s": 33297,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 33348,
"s": 33320,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 33388,
"s": 33348,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 33431,
"s": 33388,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 33471,
"s": 33431,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 33496,
"s": 33471,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 33530,
"s": 33496,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 33576,
"s": 33530,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
C# | How to get Third Element of the Tuple? - GeeksforGeeks
|
30 Apr, 2019
Tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. Item3 Property is used to get the third element of the given tuple. It is not applicable on 1-Tuple, 2-Tuple but applicable on all other remaining tuples.
Syntax:
public T3 Item3 { get; }
Here, T3 is the value of the current Tuple<> object’s third component. This Tuple<> can be 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple.
Example: In the below code, you can see that we are accessing the third element of each tuple.
// C# program to illustrate how to get // the third element of the tupleusing System; class GFG { // Main method static public void Main() { // Taking 3-tuple var st3 = Tuple.Create("Soniya", 30, "CSE"); Console.WriteLine("Student-3 Branch: " + st3.Item3); // Taking 4-tuple var st4 = Tuple.Create("Rohan", 29, "EC", 2015); Console.WriteLine("Student-4 Branch: " + st4.Item3); // Taking 5-tuple var st5 = Tuple.Create("Siya", 22, "EEE", 2017, "20-Mar-1993"); Console.WriteLine("Student-5 Branch: " + st5.Item3); // Taking 6-tuple var st6 = Tuple.Create("Riya", 24, "ME", 2015, "30-May-2015", 230134832); Console.WriteLine("Student-6 Branch: " + st6.Item3); // Taking 7-tuple var st7 = Tuple.Create("Rohit", 21, "IT", 2017, "21-Apr-1998", 384749829, 20000); Console.WriteLine("Student-7 Branch: " + st7.Item3); // Taking 8-tuple var st8 = Tuple.Create("Manita", 24, "CSE", 2016, "03-Aug-1991", 235678909, 34000, "C#"); Console.WriteLine("Student-8 Branch: " + st8.Item3); }}
Student-3 Branch: CSE
Student-4 Branch: EC
Student-5 Branch: EEE
Student-6 Branch: ME
Student-7 Branch: IT
Student-8 Branch: CSE
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 24608,
"s": 24302,
"text": "Tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. Item3 Property is used to get the third element of the given tuple. It is not applicable on 1-Tuple, 2-Tuple but applicable on all other remaining tuples."
},
{
"code": null,
"e": 24616,
"s": 24608,
"text": "Syntax:"
},
{
"code": null,
"e": 24641,
"s": 24616,
"text": "public T3 Item3 { get; }"
},
{
"code": null,
"e": 24801,
"s": 24641,
"text": "Here, T3 is the value of the current Tuple<> object’s third component. This Tuple<> can be 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple."
},
{
"code": null,
"e": 24896,
"s": 24801,
"text": "Example: In the below code, you can see that we are accessing the third element of each tuple."
},
{
"code": "// C# program to illustrate how to get // the third element of the tupleusing System; class GFG { // Main method static public void Main() { // Taking 3-tuple var st3 = Tuple.Create(\"Soniya\", 30, \"CSE\"); Console.WriteLine(\"Student-3 Branch: \" + st3.Item3); // Taking 4-tuple var st4 = Tuple.Create(\"Rohan\", 29, \"EC\", 2015); Console.WriteLine(\"Student-4 Branch: \" + st4.Item3); // Taking 5-tuple var st5 = Tuple.Create(\"Siya\", 22, \"EEE\", 2017, \"20-Mar-1993\"); Console.WriteLine(\"Student-5 Branch: \" + st5.Item3); // Taking 6-tuple var st6 = Tuple.Create(\"Riya\", 24, \"ME\", 2015, \"30-May-2015\", 230134832); Console.WriteLine(\"Student-6 Branch: \" + st6.Item3); // Taking 7-tuple var st7 = Tuple.Create(\"Rohit\", 21, \"IT\", 2017, \"21-Apr-1998\", 384749829, 20000); Console.WriteLine(\"Student-7 Branch: \" + st7.Item3); // Taking 8-tuple var st8 = Tuple.Create(\"Manita\", 24, \"CSE\", 2016, \"03-Aug-1991\", 235678909, 34000, \"C#\"); Console.WriteLine(\"Student-8 Branch: \" + st8.Item3); }}",
"e": 26146,
"s": 24896,
"text": null
},
{
"code": null,
"e": 26276,
"s": 26146,
"text": "Student-3 Branch: CSE\nStudent-4 Branch: EC\nStudent-5 Branch: EEE\nStudent-6 Branch: ME\nStudent-7 Branch: IT\nStudent-8 Branch: CSE\n"
},
{
"code": null,
"e": 26289,
"s": 26276,
"text": "CSharp-Tuple"
},
{
"code": null,
"e": 26292,
"s": 26289,
"text": "C#"
},
{
"code": null,
"e": 26390,
"s": 26292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26408,
"s": 26390,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26431,
"s": 26408,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26459,
"s": 26431,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26499,
"s": 26459,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26542,
"s": 26499,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26564,
"s": 26542,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26581,
"s": 26564,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26597,
"s": 26581,
"text": "C# | List Class"
},
{
"code": null,
"e": 26647,
"s": 26597,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
String Handling in Java
|
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.
Live Demo
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
hello.
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects."
},
{
"code": null,
"e": 1284,
"s": 1206,
"text": "The Java platform provides the String class to create and manipulate strings."
},
{
"code": null,
"e": 1337,
"s": 1284,
"text": "The most direct way to create a string is to write −"
},
{
"code": null,
"e": 1371,
"s": 1337,
"text": "String greeting = \"Hello world!\";"
},
{
"code": null,
"e": 1507,
"s": 1371,
"text": "Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, \"Hello world!'."
},
{
"code": null,
"e": 1517,
"s": 1507,
"text": "Live Demo"
},
{
"code": null,
"e": 1746,
"s": 1517,
"text": "public class StringDemo {\n public static void main(String args[]) {\n char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };\n String helloString = new String(helloArray);\n System.out.println( helloString );\n }\n}"
},
{
"code": null,
"e": 1753,
"s": 1746,
"text": "hello."
}
] |
Python String lower() Method
|
Python string method lower() returns a copy of the string in which all case-based characters have been lowercased.
Following is the syntax for lower() method −
str.lower()
NA
NA
This method returns a copy of the string in which all case-based characters have been lowercased.
The following example shows the usage of lower() method.
#!/usr/bin/python
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()
When we run above program, it produces following result −
this is string example....wow!!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2360,
"s": 2244,
"text": "Python string method lower() returns a copy of the string in which all case-based characters have been lowercased."
},
{
"code": null,
"e": 2405,
"s": 2360,
"text": "Following is the syntax for lower() method −"
},
{
"code": null,
"e": 2418,
"s": 2405,
"text": "str.lower()\n"
},
{
"code": null,
"e": 2421,
"s": 2418,
"text": "NA"
},
{
"code": null,
"e": 2424,
"s": 2421,
"text": "NA"
},
{
"code": null,
"e": 2522,
"s": 2424,
"text": "This method returns a copy of the string in which all case-based characters have been lowercased."
},
{
"code": null,
"e": 2579,
"s": 2522,
"text": "The following example shows the usage of lower() method."
},
{
"code": null,
"e": 2658,
"s": 2579,
"text": "#!/usr/bin/python\n\nstr = \"THIS IS STRING EXAMPLE....WOW!!!\";\nprint str.lower()"
},
{
"code": null,
"e": 2716,
"s": 2658,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2750,
"s": 2716,
"text": "this is string example....wow!!!\n"
},
{
"code": null,
"e": 2787,
"s": 2750,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2803,
"s": 2787,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2836,
"s": 2803,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2855,
"s": 2836,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2890,
"s": 2855,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2912,
"s": 2890,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 2946,
"s": 2912,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 2974,
"s": 2946,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3009,
"s": 2974,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3023,
"s": 3009,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3056,
"s": 3023,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3073,
"s": 3056,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3080,
"s": 3073,
"text": " Print"
},
{
"code": null,
"e": 3091,
"s": 3080,
"text": " Add Notes"
}
] |
Finding LCM of more than two (or array) numbers without using GCD - GeeksforGeeks
|
22 Apr, 2021
Given an array of positive integers, find LCM of the elements present in array.Examples:
Input : arr[] = {1, 2, 3, 4, 28}
Output : 84
Input : arr[] = {4, 6, 12, 24, 30}
Output : 120
We have discussed LCM of array using GCD.In this post a different approach is discussed that doesn’t require computation of GCD. Below are steps.
Initialize result = 1Find a common factors of two or more array elements.Multiply the result by common factor and divide all the array elements by this common factor.Repeat steps 2 and 3 while there is a common factor of two or more elements.Multiply the result by reduced (or divided) array elements.
Initialize result = 1
Find a common factors of two or more array elements.
Multiply the result by common factor and divide all the array elements by this common factor.
Repeat steps 2 and 3 while there is a common factor of two or more elements.
Multiply the result by reduced (or divided) array elements.
Illustration :
Let we have to find the LCM of
arr[] = {1, 2, 3, 4, 28}
We initialize result = 1.
2 is a common factor that appears in
two or more elements. We divide all
multiples by two and multiply result
with 2.
arr[] = {1, 1, 3, 2, 14}
result = 2
2 is again a common factor that appears
in two or more elements. We divide all
multiples by two and multiply result
with 2.
arr[] = {1, 1, 3, 1, 7}
result = 4
Now there is no common factor that appears
in two or more array elements. We multiply
all modified array elements with result, we
get.
result = 4 * 1 * 1 * 3 * 1 * 7
= 84
Below is the implementation of above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find LCM of array without// using GCD.#include<bits/stdc++.h>using namespace std; // Returns LCM of arr[0..n-1]unsigned long long int LCM(int arr[], int n){ // Find the maximum value in arr[] int max_num = 0; for (int i=0; i<n; i++) if (max_num < arr[i]) max_num = arr[i]; // Initialize result unsigned long long int res = 1; // Find all factors that are present in // two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. vector<int> indexes; for (int j=0; j<n; j++) if (arr[j]%x == 0) indexes.push_back(j); // If there are 2 or more array elements // that are divisible by x. if (indexes.size() >= 2) { // Reduce all array elements divisible // by x. for (int j=0; j<indexes.size(); j++) arr[indexes[j]] = arr[indexes[j]]/x; res = res * x; } else x++; } // Then multiply all reduced array elements for (int i=0; i<n; i++) res = res*arr[i]; return res;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 10, 20, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << LCM(arr, n) << "\n"; return 0;}
import java.util.Vector; // Java program to find LCM of array without// using GCD.class GFG { // Returns LCM of arr[0..n-1] static long LCM(int arr[], int n) { // Find the maximum value in arr[] int max_num = 0; for (int i = 0; i < n; i++) { if (max_num < arr[i]) { max_num = arr[i]; } } // Initialize result long res = 1; // Find all factors that are present in // two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. Vector<Integer> indexes = new Vector<>(); for (int j = 0; j < n; j++) { if (arr[j] % x == 0) { indexes.add(indexes.size(), j); } } // If there are 2 or more array elements // that are divisible by x. if (indexes.size() >= 2) { // Reduce all array elements divisible // by x. for (int j = 0; j < indexes.size(); j++) { arr[indexes.get(j)] = arr[indexes.get(j)] / x; } res = res * x; } else { x++; } } // Then multiply all reduced array elements for (int i = 0; i < n; i++) { res = res * arr[i]; } return res; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 10, 20, 35}; int n = arr.length; System.out.println(LCM(arr, n)); }}
# Python3 program to find LCM of array# without using GCD. # Returns LCM of arr[0..n-1]def LCM(arr, n): # Find the maximum value in arr[] max_num = 0; for i in range(n): if (max_num < arr[i]): max_num = arr[i]; # Initialize result res = 1; # Find all factors that are present # in two or more array elements. x = 2; # Current factor. while (x <= max_num): # To store indexes of all array # elements that are divisible by x. indexes = []; for j in range(n): if (arr[j] % x == 0): indexes.append(j); # If there are 2 or more array # elements that are divisible by x. if (len(indexes) >= 2): # Reduce all array elements # divisible by x. for j in range(len(indexes)): arr[indexes[j]] = int(arr[indexes[j]] / x); res = res * x; else: x += 1; # Then multiply all reduced # array elements for i in range(n): res = res * arr[i]; return res; # Driver codearr = [1, 2, 3, 4, 5, 10, 20, 35];n = len(arr);print(LCM(arr, n)); # This code is contributed by chandan_jnu
// C# program to find LCM of array// without using GCD.using System;using System.Collections;class GFG{ // Returns LCM of arr[0..n-1]static long LCM(int []arr, int n){ // Find the maximum value in arr[] int max_num = 0; for (int i = 0; i < n; i++) { if (max_num < arr[i]) { max_num = arr[i]; } } // Initialize result long res = 1; // Find all factors that are present // in two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. ArrayList indexes = new ArrayList(); for (int j = 0; j < n; j++) { if (arr[j] % x == 0) { indexes.Add(j); } } // If there are 2 or more array elements // that are divisible by x. if (indexes.Count >= 2) { // Reduce all array elements divisible // by x. for (int j = 0; j < indexes.Count; j++) { arr[(int)indexes[j]] = arr[(int)indexes[j]] / x; } res = res * x; } else { x++; } } // Then multiply all reduced // array elements for (int i = 0; i < n; i++) { res = res * arr[i]; } return res;} // Driver codepublic static void Main(){ int []arr = {1, 2, 3, 4, 5, 10, 20, 35}; int n = arr.Length; Console.WriteLine(LCM(arr, n));}} // This code is contributed by mits
<?php// PHP program to find LCM of array// without using GCD. // Returns LCM of arr[0..n-1]function LCM($arr, $n){ // Find the maximum value in arr[] $max_num = 0; for ($i = 0; $i < $n; $i++) if ($max_num < $arr[$i]) $max_num = $arr[$i]; // Initialize result $res = 1; // Find all factors that are present // in two or more array elements. $x = 2; // Current factor. while ($x <= $max_num) { // To store indexes of all array // elements that are divisible by x. $indexes = array(); for ($j = 0; $j < $n; $j++) if ($arr[$j] % $x == 0) array_push($indexes, $j); // If there are 2 or more array // elements that are divisible by x. if (count($indexes) >= 2) { // Reduce all array elements // divisible by x. for ($j = 0; $j < count($indexes); $j++) $arr[$indexes[$j]] = (int)($arr[$indexes[$j]] / $x); $res = $res * $x; } else $x++; } // Then multiply all reduced // array elements for ($i = 0; $i < $n; $i++) $res = $res * $arr[$i]; return $res;} // Driver code$arr = array(1, 2, 3, 4, 5, 10, 20, 35);$n = count($arr);echo LCM($arr, $n) . "\n"; // This code is contributed by chandan_jnu?>
<script>// Javascript program to find LCM of array without// using GCD. // Returns LCM of arr[0..n-1]function LCM(arr, n){ // Find the maximum value in arr[] var max_num = 0; for (var i = 0; i < n; i++) if (max_num < arr[i]) max_num = arr[i]; // Initialize result var res = 1; // Find all factors that are present in // two or more array elements. var x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. var indexes = []; for (var j = 0; j < n; j++) if (arr[j] % x == 0) indexes.push(j); // If there are 2 or more array elements // that are divisible by x. if (indexes.length >= 2) { // Reduce all array elements divisible // by x. for (var j = 0; j < indexes.length; j++) arr[indexes[j]] = arr[indexes[j]]/x; res = res * x; } else x++; } // Then multiply all reduced array elements for (var i = 0; i < n; i++) res = res*arr[i]; return res;} // Driver codevar arr = [1, 2, 3, 4, 5, 10, 20, 35];var n = arr.length;document.write( LCM(arr, n) + "<br>"); // This code is contributed by rrrtnx.</script>
Output:
420
This article is contributed by Aditya Kumar. 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.
29AjayKumar
Mithun Kumar
Chandan_Kumar
nidhi_biet
rrrtnx
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
How to swap two numbers without using a temporary variable?
Write a program to reverse digits of a number
|
[
{
"code": null,
"e": 24552,
"s": 24524,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 24643,
"s": 24552,
"text": "Given an array of positive integers, find LCM of the elements present in array.Examples: "
},
{
"code": null,
"e": 24738,
"s": 24643,
"text": "Input : arr[] = {1, 2, 3, 4, 28}\nOutput : 84\n\nInput : arr[] = {4, 6, 12, 24, 30}\nOutput : 120"
},
{
"code": null,
"e": 24888,
"s": 24740,
"text": "We have discussed LCM of array using GCD.In this post a different approach is discussed that doesn’t require computation of GCD. Below are steps. "
},
{
"code": null,
"e": 25190,
"s": 24888,
"text": "Initialize result = 1Find a common factors of two or more array elements.Multiply the result by common factor and divide all the array elements by this common factor.Repeat steps 2 and 3 while there is a common factor of two or more elements.Multiply the result by reduced (or divided) array elements."
},
{
"code": null,
"e": 25212,
"s": 25190,
"text": "Initialize result = 1"
},
{
"code": null,
"e": 25265,
"s": 25212,
"text": "Find a common factors of two or more array elements."
},
{
"code": null,
"e": 25359,
"s": 25265,
"text": "Multiply the result by common factor and divide all the array elements by this common factor."
},
{
"code": null,
"e": 25436,
"s": 25359,
"text": "Repeat steps 2 and 3 while there is a common factor of two or more elements."
},
{
"code": null,
"e": 25496,
"s": 25436,
"text": "Multiply the result by reduced (or divided) array elements."
},
{
"code": null,
"e": 25512,
"s": 25496,
"text": "Illustration : "
},
{
"code": null,
"e": 26091,
"s": 25512,
"text": "Let we have to find the LCM of \narr[] = {1, 2, 3, 4, 28}\n\nWe initialize result = 1.\n\n2 is a common factor that appears in\ntwo or more elements. We divide all\nmultiples by two and multiply result\nwith 2.\narr[] = {1, 1, 3, 2, 14}\nresult = 2\n\n2 is again a common factor that appears \nin two or more elements. We divide all\nmultiples by two and multiply result\nwith 2.\narr[] = {1, 1, 3, 1, 7}\nresult = 4\n\nNow there is no common factor that appears\nin two or more array elements. We multiply\nall modified array elements with result, we\nget.\nresult = 4 * 1 * 1 * 3 * 1 * 7\n = 84"
},
{
"code": null,
"e": 26141,
"s": 26091,
"text": "Below is the implementation of above algorithm. "
},
{
"code": null,
"e": 26145,
"s": 26141,
"text": "C++"
},
{
"code": null,
"e": 26150,
"s": 26145,
"text": "Java"
},
{
"code": null,
"e": 26158,
"s": 26150,
"text": "Python3"
},
{
"code": null,
"e": 26161,
"s": 26158,
"text": "C#"
},
{
"code": null,
"e": 26165,
"s": 26161,
"text": "PHP"
},
{
"code": null,
"e": 26176,
"s": 26165,
"text": "Javascript"
},
{
"code": "// C++ program to find LCM of array without// using GCD.#include<bits/stdc++.h>using namespace std; // Returns LCM of arr[0..n-1]unsigned long long int LCM(int arr[], int n){ // Find the maximum value in arr[] int max_num = 0; for (int i=0; i<n; i++) if (max_num < arr[i]) max_num = arr[i]; // Initialize result unsigned long long int res = 1; // Find all factors that are present in // two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. vector<int> indexes; for (int j=0; j<n; j++) if (arr[j]%x == 0) indexes.push_back(j); // If there are 2 or more array elements // that are divisible by x. if (indexes.size() >= 2) { // Reduce all array elements divisible // by x. for (int j=0; j<indexes.size(); j++) arr[indexes[j]] = arr[indexes[j]]/x; res = res * x; } else x++; } // Then multiply all reduced array elements for (int i=0; i<n; i++) res = res*arr[i]; return res;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 10, 20, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << LCM(arr, n) << \"\\n\"; return 0;}",
"e": 27541,
"s": 26176,
"text": null
},
{
"code": "import java.util.Vector; // Java program to find LCM of array without// using GCD.class GFG { // Returns LCM of arr[0..n-1] static long LCM(int arr[], int n) { // Find the maximum value in arr[] int max_num = 0; for (int i = 0; i < n; i++) { if (max_num < arr[i]) { max_num = arr[i]; } } // Initialize result long res = 1; // Find all factors that are present in // two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. Vector<Integer> indexes = new Vector<>(); for (int j = 0; j < n; j++) { if (arr[j] % x == 0) { indexes.add(indexes.size(), j); } } // If there are 2 or more array elements // that are divisible by x. if (indexes.size() >= 2) { // Reduce all array elements divisible // by x. for (int j = 0; j < indexes.size(); j++) { arr[indexes.get(j)] = arr[indexes.get(j)] / x; } res = res * x; } else { x++; } } // Then multiply all reduced array elements for (int i = 0; i < n; i++) { res = res * arr[i]; } return res; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 10, 20, 35}; int n = arr.length; System.out.println(LCM(arr, n)); }}",
"e": 29181,
"s": 27541,
"text": null
},
{
"code": "# Python3 program to find LCM of array# without using GCD. # Returns LCM of arr[0..n-1]def LCM(arr, n): # Find the maximum value in arr[] max_num = 0; for i in range(n): if (max_num < arr[i]): max_num = arr[i]; # Initialize result res = 1; # Find all factors that are present # in two or more array elements. x = 2; # Current factor. while (x <= max_num): # To store indexes of all array # elements that are divisible by x. indexes = []; for j in range(n): if (arr[j] % x == 0): indexes.append(j); # If there are 2 or more array # elements that are divisible by x. if (len(indexes) >= 2): # Reduce all array elements # divisible by x. for j in range(len(indexes)): arr[indexes[j]] = int(arr[indexes[j]] / x); res = res * x; else: x += 1; # Then multiply all reduced # array elements for i in range(n): res = res * arr[i]; return res; # Driver codearr = [1, 2, 3, 4, 5, 10, 20, 35];n = len(arr);print(LCM(arr, n)); # This code is contributed by chandan_jnu",
"e": 30386,
"s": 29181,
"text": null
},
{
"code": "// C# program to find LCM of array// without using GCD.using System;using System.Collections;class GFG{ // Returns LCM of arr[0..n-1]static long LCM(int []arr, int n){ // Find the maximum value in arr[] int max_num = 0; for (int i = 0; i < n; i++) { if (max_num < arr[i]) { max_num = arr[i]; } } // Initialize result long res = 1; // Find all factors that are present // in two or more array elements. int x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. ArrayList indexes = new ArrayList(); for (int j = 0; j < n; j++) { if (arr[j] % x == 0) { indexes.Add(j); } } // If there are 2 or more array elements // that are divisible by x. if (indexes.Count >= 2) { // Reduce all array elements divisible // by x. for (int j = 0; j < indexes.Count; j++) { arr[(int)indexes[j]] = arr[(int)indexes[j]] / x; } res = res * x; } else { x++; } } // Then multiply all reduced // array elements for (int i = 0; i < n; i++) { res = res * arr[i]; } return res;} // Driver codepublic static void Main(){ int []arr = {1, 2, 3, 4, 5, 10, 20, 35}; int n = arr.Length; Console.WriteLine(LCM(arr, n));}} // This code is contributed by mits",
"e": 31916,
"s": 30386,
"text": null
},
{
"code": "<?php// PHP program to find LCM of array// without using GCD. // Returns LCM of arr[0..n-1]function LCM($arr, $n){ // Find the maximum value in arr[] $max_num = 0; for ($i = 0; $i < $n; $i++) if ($max_num < $arr[$i]) $max_num = $arr[$i]; // Initialize result $res = 1; // Find all factors that are present // in two or more array elements. $x = 2; // Current factor. while ($x <= $max_num) { // To store indexes of all array // elements that are divisible by x. $indexes = array(); for ($j = 0; $j < $n; $j++) if ($arr[$j] % $x == 0) array_push($indexes, $j); // If there are 2 or more array // elements that are divisible by x. if (count($indexes) >= 2) { // Reduce all array elements // divisible by x. for ($j = 0; $j < count($indexes); $j++) $arr[$indexes[$j]] = (int)($arr[$indexes[$j]] / $x); $res = $res * $x; } else $x++; } // Then multiply all reduced // array elements for ($i = 0; $i < $n; $i++) $res = $res * $arr[$i]; return $res;} // Driver code$arr = array(1, 2, 3, 4, 5, 10, 20, 35);$n = count($arr);echo LCM($arr, $n) . \"\\n\"; // This code is contributed by chandan_jnu?>",
"e": 33246,
"s": 31916,
"text": null
},
{
"code": "<script>// Javascript program to find LCM of array without// using GCD. // Returns LCM of arr[0..n-1]function LCM(arr, n){ // Find the maximum value in arr[] var max_num = 0; for (var i = 0; i < n; i++) if (max_num < arr[i]) max_num = arr[i]; // Initialize result var res = 1; // Find all factors that are present in // two or more array elements. var x = 2; // Current factor. while (x <= max_num) { // To store indexes of all array // elements that are divisible by x. var indexes = []; for (var j = 0; j < n; j++) if (arr[j] % x == 0) indexes.push(j); // If there are 2 or more array elements // that are divisible by x. if (indexes.length >= 2) { // Reduce all array elements divisible // by x. for (var j = 0; j < indexes.length; j++) arr[indexes[j]] = arr[indexes[j]]/x; res = res * x; } else x++; } // Then multiply all reduced array elements for (var i = 0; i < n; i++) res = res*arr[i]; return res;} // Driver codevar arr = [1, 2, 3, 4, 5, 10, 20, 35];var n = arr.length;document.write( LCM(arr, n) + \"<br>\"); // This code is contributed by rrrtnx.</script>",
"e": 34553,
"s": 33246,
"text": null
},
{
"code": null,
"e": 34563,
"s": 34553,
"text": "Output: "
},
{
"code": null,
"e": 34567,
"s": 34563,
"text": "420"
},
{
"code": null,
"e": 34992,
"s": 34567,
"text": "This article is contributed by Aditya Kumar. 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": 35004,
"s": 34992,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35017,
"s": 35004,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35031,
"s": 35017,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 35042,
"s": 35031,
"text": "nidhi_biet"
},
{
"code": null,
"e": 35049,
"s": 35042,
"text": "rrrtnx"
},
{
"code": null,
"e": 35057,
"s": 35049,
"text": "GCD-LCM"
},
{
"code": null,
"e": 35070,
"s": 35057,
"text": "Mathematical"
},
{
"code": null,
"e": 35083,
"s": 35070,
"text": "Mathematical"
},
{
"code": null,
"e": 35181,
"s": 35083,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35224,
"s": 35181,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 35273,
"s": 35224,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 35307,
"s": 35273,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 35328,
"s": 35307,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 35371,
"s": 35328,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 35424,
"s": 35371,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 35461,
"s": 35424,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 35493,
"s": 35461,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 35553,
"s": 35493,
"text": "How to swap two numbers without using a temporary variable?"
}
] |
vlcj - Overview
|
The vlcj is an Open Source project which helps to run VLC player within a Java baed application. It provides option to discover the VLC player installed in the sytem and bind it to build a media player client and server software using Java.
Using Java, you can simply play a local media files and even you can create a video on demand streaming server.
vlcj is a quite popular java based library, and it is in used in various java based softwares like oceanographic research vessels and bespoke IPTV and home cinema solutions. Some of the renowned examples are Open Source video camera at Elphel and video mapping for the Open Street Map project.
Create a EmbeddedMediaPlayerComponent Component
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
Playing a video is very easy. Pass the path of the file and it will play the video.
//pass path to media file
mediaPlayerComponent.mediaPlayer().media().play(path);
VLC Media Player is a very popular media player and is available for Linux, MacOS and Windows. It comes bundled with tons of codecs to play any kind of media without any need to install external media codec. It also supports video streaming across networks and allows transcoding of media. Using VLC media player we can play local media files, local network streams, internet based video streams, DVD, Bluray, webcam, digital video and lots more.
VLC Media player is compiled into native platform code and cannot be used by Java programs directly. To overcome this problem, VLC Media Player provides a native API(Application Programming Interface) called LibVLC and is a part of VLC Media Player. vlcj then provides the java layer needed to interact with VLC Media Player using LibVLC.
vlcj is a mature libary. It provides following features which are essential while working with VLC media player.
Java Bindings − vlcj provides Java binding to all native operations of VLC Media Player so that we can program a Media Player functionality using Java programming.
Java Bindings − vlcj provides Java binding to all native operations of VLC Media Player so that we can program a Media Player functionality using Java programming.
Framework − vlcj acts as a framework encapsulating any platform specific behaavior and native code handling by providing a simple high level programming interface for LibVLC.
Framework − vlcj acts as a framework encapsulating any platform specific behaavior and native code handling by providing a simple high level programming interface for LibVLC.
Robust − vlcj ensure the correct usage of LibVLC APIs. As incorrect use may lead to crash or deadlocks.
Robust − vlcj ensure the correct usage of LibVLC APIs. As incorrect use may lead to crash or deadlocks.
Handles Asynchronous native events − vlcj registers callbacks for asynchronous native events which then can be handled in java listener pattern easily. This programming model helps in preventing deadlocks.
Handles Asynchronous native events − vlcj registers callbacks for asynchronous native events which then can be handled in java listener pattern easily. This programming model helps in preventing deadlocks.
Following are few examples where vlcj can be used.
Java Based − Being java based, we can create media player within swing, awt, swt, javafx and openGL programs.
Java Based − Being java based, we can create media player within swing, awt, swt, javafx and openGL programs.
IDE − Eclipse/NetBeans based Rich Client Platform Applications can use vlcj for media based applications.
IDE − Eclipse/NetBeans based Rich Client Platform Applications can use vlcj for media based applications.
Internet Radio Player − Using vlcj, we can create a audio player which can stream internet based radios.
Internet Radio Player − Using vlcj, we can create a audio player which can stream internet based radios.
YouTube Player − Using vlcj, we can create a YouTube player which can stream YouTube videos.
YouTube Player − Using vlcj, we can create a YouTube player which can stream YouTube videos.
Transcoder − Using vlcj, we can transcode any videos.
Transcoder − Using vlcj, we can transcode any videos.
Network streaming server − Using vlcj, we can create a video on demand server.
Network streaming server − Using vlcj, we can create a video on demand server.
Network streaming client − Using vlcj, we can create a video on demand client.
Network streaming client − Using vlcj, we can create a video on demand client.
Video Playing Applet − Using vlcj, we can create an applet which can play a video.
Video Playing Applet − Using vlcj, we can create an applet which can play a video.
WebCam − Using vlcj, we can create webcam application.
WebCam − Using vlcj, we can create webcam application.
CCTV Camera − Using vlcj, we can create CCTV camera application playing videos recorded by CCTV cameras.
CCTV Camera − Using vlcj, we can create CCTV camera application playing videos recorded by CCTV cameras.
vlcj is distributable under GPL licence terms. In case of commercial usage without conditions of GPL license then contact the team at Caprica Software Limited.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 1923,
"text": "The vlcj is an Open Source project which helps to run VLC player within a Java baed application. It provides option to discover the VLC player installed in the sytem and bind it to build a media player client and server software using Java."
},
{
"code": null,
"e": 2276,
"s": 2164,
"text": "Using Java, you can simply play a local media files and even you can create a video on demand streaming server."
},
{
"code": null,
"e": 2570,
"s": 2276,
"text": "vlcj is a quite popular java based library, and it is in used in various java based softwares like oceanographic research vessels and bespoke IPTV and home cinema solutions. Some of the renowned examples are Open Source video camera at Elphel and video mapping for the Open Street Map project."
},
{
"code": null,
"e": 2618,
"s": 2570,
"text": "Create a EmbeddedMediaPlayerComponent Component"
},
{
"code": null,
"e": 2708,
"s": 2618,
"text": "EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();\t\n"
},
{
"code": null,
"e": 2792,
"s": 2708,
"text": "Playing a video is very easy. Pass the path of the file and it will play the video."
},
{
"code": null,
"e": 2878,
"s": 2792,
"text": "//pass path to media file\nmediaPlayerComponent.mediaPlayer().media().play(path); \n"
},
{
"code": null,
"e": 3326,
"s": 2878,
"text": "VLC Media Player is a very popular media player and is available for Linux, MacOS and Windows. It comes bundled with tons of codecs to play any kind of media without any need to install external media codec. It also supports video streaming across networks and allows transcoding of media. Using VLC media player we can play local media files, local network streams, internet based video streams, DVD, Bluray, webcam, digital video and lots more."
},
{
"code": null,
"e": 3665,
"s": 3326,
"text": "VLC Media player is compiled into native platform code and cannot be used by Java programs directly. To overcome this problem, VLC Media Player provides a native API(Application Programming Interface) called LibVLC and is a part of VLC Media Player. vlcj then provides the java layer needed to interact with VLC Media Player using LibVLC."
},
{
"code": null,
"e": 3778,
"s": 3665,
"text": "vlcj is a mature libary. It provides following features which are essential while working with VLC media player."
},
{
"code": null,
"e": 3942,
"s": 3778,
"text": "Java Bindings − vlcj provides Java binding to all native operations of VLC Media Player so that we can program a Media Player functionality using Java programming."
},
{
"code": null,
"e": 4106,
"s": 3942,
"text": "Java Bindings − vlcj provides Java binding to all native operations of VLC Media Player so that we can program a Media Player functionality using Java programming."
},
{
"code": null,
"e": 4281,
"s": 4106,
"text": "Framework − vlcj acts as a framework encapsulating any platform specific behaavior and native code handling by providing a simple high level programming interface for LibVLC."
},
{
"code": null,
"e": 4456,
"s": 4281,
"text": "Framework − vlcj acts as a framework encapsulating any platform specific behaavior and native code handling by providing a simple high level programming interface for LibVLC."
},
{
"code": null,
"e": 4560,
"s": 4456,
"text": "Robust − vlcj ensure the correct usage of LibVLC APIs. As incorrect use may lead to crash or deadlocks."
},
{
"code": null,
"e": 4664,
"s": 4560,
"text": "Robust − vlcj ensure the correct usage of LibVLC APIs. As incorrect use may lead to crash or deadlocks."
},
{
"code": null,
"e": 4870,
"s": 4664,
"text": "Handles Asynchronous native events − vlcj registers callbacks for asynchronous native events which then can be handled in java listener pattern easily. This programming model helps in preventing deadlocks."
},
{
"code": null,
"e": 5076,
"s": 4870,
"text": "Handles Asynchronous native events − vlcj registers callbacks for asynchronous native events which then can be handled in java listener pattern easily. This programming model helps in preventing deadlocks."
},
{
"code": null,
"e": 5127,
"s": 5076,
"text": "Following are few examples where vlcj can be used."
},
{
"code": null,
"e": 5237,
"s": 5127,
"text": "Java Based − Being java based, we can create media player within swing, awt, swt, javafx and openGL programs."
},
{
"code": null,
"e": 5347,
"s": 5237,
"text": "Java Based − Being java based, we can create media player within swing, awt, swt, javafx and openGL programs."
},
{
"code": null,
"e": 5453,
"s": 5347,
"text": "IDE − Eclipse/NetBeans based Rich Client Platform Applications can use vlcj for media based applications."
},
{
"code": null,
"e": 5559,
"s": 5453,
"text": "IDE − Eclipse/NetBeans based Rich Client Platform Applications can use vlcj for media based applications."
},
{
"code": null,
"e": 5664,
"s": 5559,
"text": "Internet Radio Player − Using vlcj, we can create a audio player which can stream internet based radios."
},
{
"code": null,
"e": 5769,
"s": 5664,
"text": "Internet Radio Player − Using vlcj, we can create a audio player which can stream internet based radios."
},
{
"code": null,
"e": 5862,
"s": 5769,
"text": "YouTube Player − Using vlcj, we can create a YouTube player which can stream YouTube videos."
},
{
"code": null,
"e": 5955,
"s": 5862,
"text": "YouTube Player − Using vlcj, we can create a YouTube player which can stream YouTube videos."
},
{
"code": null,
"e": 6009,
"s": 5955,
"text": "Transcoder − Using vlcj, we can transcode any videos."
},
{
"code": null,
"e": 6063,
"s": 6009,
"text": "Transcoder − Using vlcj, we can transcode any videos."
},
{
"code": null,
"e": 6142,
"s": 6063,
"text": "Network streaming server − Using vlcj, we can create a video on demand server."
},
{
"code": null,
"e": 6221,
"s": 6142,
"text": "Network streaming server − Using vlcj, we can create a video on demand server."
},
{
"code": null,
"e": 6300,
"s": 6221,
"text": "Network streaming client − Using vlcj, we can create a video on demand client."
},
{
"code": null,
"e": 6379,
"s": 6300,
"text": "Network streaming client − Using vlcj, we can create a video on demand client."
},
{
"code": null,
"e": 6462,
"s": 6379,
"text": "Video Playing Applet − Using vlcj, we can create an applet which can play a video."
},
{
"code": null,
"e": 6545,
"s": 6462,
"text": "Video Playing Applet − Using vlcj, we can create an applet which can play a video."
},
{
"code": null,
"e": 6600,
"s": 6545,
"text": "WebCam − Using vlcj, we can create webcam application."
},
{
"code": null,
"e": 6655,
"s": 6600,
"text": "WebCam − Using vlcj, we can create webcam application."
},
{
"code": null,
"e": 6760,
"s": 6655,
"text": "CCTV Camera − Using vlcj, we can create CCTV camera application playing videos recorded by CCTV cameras."
},
{
"code": null,
"e": 6865,
"s": 6760,
"text": "CCTV Camera − Using vlcj, we can create CCTV camera application playing videos recorded by CCTV cameras."
},
{
"code": null,
"e": 7025,
"s": 6865,
"text": "vlcj is distributable under GPL licence terms. In case of commercial usage without conditions of GPL license then contact the team at Caprica Software Limited."
},
{
"code": null,
"e": 7032,
"s": 7025,
"text": " Print"
},
{
"code": null,
"e": 7043,
"s": 7032,
"text": " Add Notes"
}
] |
Perl rename Function
|
This function renames the file with OLDNAME to NEWNAME. Uses the system function rename( ), and so it will not rename files across file systems or volumes. If you want to copy or move a file, use the copy or move command supplied in the File::Copy module.
Following is the simple syntax for this function −
rename OLDNAME, NEWNAME
This function returns 0 on failure and 1 on success.
First create test file in /tmp directory and then use following code to change file name.
#!/usr/bin/perl -w
rename("/tmp/test", "/tmp/test2") || die ( "Error in renaming" );
When above code is executed, it produces the following result −
the file gets renamed
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2476,
"s": 2220,
"text": "This function renames the file with OLDNAME to NEWNAME. Uses the system function rename( ), and so it will not rename files across file systems or volumes. If you want to copy or move a file, use the copy or move command supplied in the File::Copy module."
},
{
"code": null,
"e": 2527,
"s": 2476,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2551,
"s": 2527,
"text": "rename OLDNAME, NEWNAME"
},
{
"code": null,
"e": 2604,
"s": 2551,
"text": "This function returns 0 on failure and 1 on success."
},
{
"code": null,
"e": 2694,
"s": 2604,
"text": "First create test file in /tmp directory and then use following code to change file name."
},
{
"code": null,
"e": 2780,
"s": 2694,
"text": "#!/usr/bin/perl -w\n\nrename(\"/tmp/test\", \"/tmp/test2\") || die ( \"Error in renaming\" );"
},
{
"code": null,
"e": 2844,
"s": 2780,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2867,
"s": 2844,
"text": "the file gets renamed\n"
},
{
"code": null,
"e": 2902,
"s": 2867,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2916,
"s": 2902,
"text": " Devi Killada"
},
{
"code": null,
"e": 2951,
"s": 2916,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2971,
"s": 2951,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3004,
"s": 2971,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3020,
"s": 3004,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3053,
"s": 3020,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3070,
"s": 3053,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3103,
"s": 3070,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3126,
"s": 3103,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3161,
"s": 3126,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3184,
"s": 3161,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3191,
"s": 3184,
"text": " Print"
},
{
"code": null,
"e": 3202,
"s": 3191,
"text": " Add Notes"
}
] |
RxJava - PublishSubject
|
PublishSubject emits items to currently subscribed Observers and terminal events to current or late Observers.
Following is the declaration for io.reactivex.subjects.PublishSubject<T> class −
public final class PublishSubject<T>
extends Subject<T>
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import io.reactivex.subjects.PublishSubject;
public class ObservableTester {
public static void main(String[] args) {
final StringBuilder result1 = new StringBuilder();
final StringBuilder result2 = new StringBuilder();
PublishSubject<String> subject = PublishSubject.create();
subject.subscribe(value -> result1.append(value) );
subject.onNext("a");
subject.onNext("b");
subject.onNext("c");
subject.subscribe(value -> result2.append(value));
subject.onNext("d");
subject.onComplete();
//Output will be abcd
System.out.println(result1);
//Output will be d only
//as subscribed after c item emitted.
System.out.println(result2);
}
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java
Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester
It should produce the following output −
abcd
d
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2512,
"s": 2401,
"text": "PublishSubject emits items to currently subscribed Observers and terminal events to current or late Observers."
},
{
"code": null,
"e": 2593,
"s": 2512,
"text": "Following is the declaration for io.reactivex.subjects.PublishSubject<T> class −"
},
{
"code": null,
"e": 2650,
"s": 2593,
"text": "public final class PublishSubject<T>\nextends Subject<T>\n"
},
{
"code": null,
"e": 2738,
"s": 2650,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> RxJava."
},
{
"code": null,
"e": 3490,
"s": 2738,
"text": "import io.reactivex.subjects.PublishSubject;\npublic class ObservableTester {\n public static void main(String[] args) { \n final StringBuilder result1 = new StringBuilder();\n final StringBuilder result2 = new StringBuilder(); \n\n PublishSubject<String> subject = PublishSubject.create(); \n subject.subscribe(value -> result1.append(value) ); \n subject.onNext(\"a\"); \n subject.onNext(\"b\"); \n subject.onNext(\"c\"); \n subject.subscribe(value -> result2.append(value)); \n subject.onNext(\"d\"); \n subject.onComplete();\n\n //Output will be abcd \n System.out.println(result1);\n //Output will be d only\n //as subscribed after c item emitted.\n System.out.println(result2);\n }\n}"
},
{
"code": null,
"e": 3542,
"s": 3490,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 3581,
"s": 3542,
"text": "C:\\RxJava>javac ObservableTester.java\n"
},
{
"code": null,
"e": 3623,
"s": 3581,
"text": "Now run the ObservableTester as follows −"
},
{
"code": null,
"e": 3656,
"s": 3623,
"text": "C:\\RxJava>java ObservableTester\n"
},
{
"code": null,
"e": 3697,
"s": 3656,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 3705,
"s": 3697,
"text": "abcd\nd\n"
},
{
"code": null,
"e": 3712,
"s": 3705,
"text": " Print"
},
{
"code": null,
"e": 3723,
"s": 3712,
"text": " Add Notes"
}
] |
Laravel - Localization
|
Localization feature of Laravel supports different language to be used in application. You need to store all the strings of different language in a file and these files are stored at resources/views directory. You should create a separate directory for each supported language. All the language files should return an array of keyed strings as shown below.
<?php
return [
'welcome' => 'Welcome to the application'
];
Step 1 − Create 3 files for languages − English, French, and German. Save English file at resources/lang/en/lang.php
<?php
return [
'msg' => 'Laravel Internationalization example.'
];
?>
Step 2 − Save French file at resources/lang/fr/lang.php.
<?php
return [
'msg' => 'Exemple Laravel internationalisation.'
];
?>
Step 3 − Save German file at resources/lang/de/lang.php.
<?php
return [
'msg' => 'Laravel Internationalisierung Beispiel.'
];
?>
Step 4 − Create a controller called LocalizationController by executing the following command.
php artisan make:controller LocalizationController --plain
Step 5 − After successful execution, you will receive the following output −
Step 6 − Copy the following code to file
app/Http/Controllers/LocalizationController.php
app/Http/Controllers/LocalizationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class LocalizationController extends Controller {
public function index(Request $request,$locale) {
//set’s application’s locale
app()->setLocale($locale);
//Gets the translated message and displays it
echo trans('lang.msg');
}
}
Step 7 − Add a route for LocalizationController in app/Http/routes.php file. Notice that we are passing {locale} argument after localization/ which we will use to see output in different language.
app/Http/routes.php
Route::get('localization/{locale}','LocalizationController@index');
Step 8 − Now, let us visit the different URLs to see all different languages. Execute the below URL to see output in English language.
http://localhost:8000/localization/en
Step 9 − The output will appear as shown in the following image.
Step 10 − Execute the below URL to see output in French language.
http://localhost:8000/localization/fr
Step 11 − The output will appear as shown in the following image.
Step 12 − Execute the below URL to see output in German language
http://localhost:8000/localization/de
Step 13 − The output will appear as shown in the following image.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2829,
"s": 2472,
"text": "Localization feature of Laravel supports different language to be used in application. You need to store all the strings of different language in a file and these files are stored at resources/views directory. You should create a separate directory for each supported language. All the language files should return an array of keyed strings as shown below."
},
{
"code": null,
"e": 2892,
"s": 2829,
"text": "<?php\nreturn [\n 'welcome' => 'Welcome to the application'\n];"
},
{
"code": null,
"e": 3009,
"s": 2892,
"text": "Step 1 − Create 3 files for languages − English, French, and German. Save English file at resources/lang/en/lang.php"
},
{
"code": null,
"e": 3091,
"s": 3009,
"text": "<?php\n return [\n 'msg' => 'Laravel Internationalization example.'\n ];\n?>"
},
{
"code": null,
"e": 3148,
"s": 3091,
"text": "Step 2 − Save French file at resources/lang/fr/lang.php."
},
{
"code": null,
"e": 3230,
"s": 3148,
"text": "<?php\n return [\n 'msg' => 'Exemple Laravel internationalisation.'\n ];\n?>"
},
{
"code": null,
"e": 3287,
"s": 3230,
"text": "Step 3 − Save German file at resources/lang/de/lang.php."
},
{
"code": null,
"e": 3372,
"s": 3287,
"text": "<?php\n return [\n 'msg' => 'Laravel Internationalisierung Beispiel.' \n ];\n?>"
},
{
"code": null,
"e": 3467,
"s": 3372,
"text": "Step 4 − Create a controller called LocalizationController by executing the following command."
},
{
"code": null,
"e": 3527,
"s": 3467,
"text": "php artisan make:controller LocalizationController --plain\n"
},
{
"code": null,
"e": 3604,
"s": 3527,
"text": "Step 5 − After successful execution, you will receive the following output −"
},
{
"code": null,
"e": 3645,
"s": 3604,
"text": "Step 6 − Copy the following code to file"
},
{
"code": null,
"e": 3693,
"s": 3645,
"text": "app/Http/Controllers/LocalizationController.php"
},
{
"code": null,
"e": 3741,
"s": 3693,
"text": "app/Http/Controllers/LocalizationController.php"
},
{
"code": null,
"e": 4138,
"s": 3741,
"text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass LocalizationController extends Controller {\n public function index(Request $request,$locale) {\n //set’s application’s locale\n app()->setLocale($locale);\n \n //Gets the translated message and displays it\n echo trans('lang.msg');\n }\n}"
},
{
"code": null,
"e": 4335,
"s": 4138,
"text": "Step 7 − Add a route for LocalizationController in app/Http/routes.php file. Notice that we are passing {locale} argument after localization/ which we will use to see output in different language."
},
{
"code": null,
"e": 4355,
"s": 4335,
"text": "app/Http/routes.php"
},
{
"code": null,
"e": 4424,
"s": 4355,
"text": "Route::get('localization/{locale}','LocalizationController@index');\n"
},
{
"code": null,
"e": 4559,
"s": 4424,
"text": "Step 8 − Now, let us visit the different URLs to see all different languages. Execute the below URL to see output in English language."
},
{
"code": null,
"e": 4598,
"s": 4559,
"text": "http://localhost:8000/localization/en\n"
},
{
"code": null,
"e": 4663,
"s": 4598,
"text": "Step 9 − The output will appear as shown in the following image."
},
{
"code": null,
"e": 4729,
"s": 4663,
"text": "Step 10 − Execute the below URL to see output in French language."
},
{
"code": null,
"e": 4768,
"s": 4729,
"text": "http://localhost:8000/localization/fr\n"
},
{
"code": null,
"e": 4834,
"s": 4768,
"text": "Step 11 − The output will appear as shown in the following image."
},
{
"code": null,
"e": 4899,
"s": 4834,
"text": "Step 12 − Execute the below URL to see output in German language"
},
{
"code": null,
"e": 4938,
"s": 4899,
"text": "http://localhost:8000/localization/de\n"
},
{
"code": null,
"e": 5004,
"s": 4938,
"text": "Step 13 − The output will appear as shown in the following image."
},
{
"code": null,
"e": 5037,
"s": 5004,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5057,
"s": 5037,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5092,
"s": 5057,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5106,
"s": 5092,
"text": " Antonio Papa"
},
{
"code": null,
"e": 5140,
"s": 5106,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5160,
"s": 5140,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5193,
"s": 5160,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5213,
"s": 5193,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5248,
"s": 5213,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5271,
"s": 5248,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 5306,
"s": 5271,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5326,
"s": 5306,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 5333,
"s": 5326,
"text": " Print"
},
{
"code": null,
"e": 5344,
"s": 5333,
"text": " Add Notes"
}
] |
Algorithms | Recursion | Question 4 - GeeksforGeeks
|
28 Jun, 2021
What does the following function do?
int fun(int x, int y){ if (y == 0) return 0; return (x + fun(x, y-1));}
(A) x + y(B) x + x*y(C) x*y(D) xyAnswer: (C)Explanation: The function adds x to itself y times which is x*y.Quiz of this Question
Algorithms-Recursion
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Sorting | Question 1
Algorithms | Greedy Algorithms | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Analysis of Algorithms | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
Algorithms | Sorting | Question 23
|
[
{
"code": null,
"e": 24989,
"s": 24961,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25026,
"s": 24989,
"text": "What does the following function do?"
},
{
"code": "int fun(int x, int y){ if (y == 0) return 0; return (x + fun(x, y-1));}",
"e": 25106,
"s": 25026,
"text": null
},
{
"code": null,
"e": 25236,
"s": 25106,
"text": "(A) x + y(B) x + x*y(C) x*y(D) xyAnswer: (C)Explanation: The function adds x to itself y times which is x*y.Quiz of this Question"
},
{
"code": null,
"e": 25257,
"s": 25236,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 25273,
"s": 25257,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 25371,
"s": 25273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25417,
"s": 25371,
"text": "Algorithms | Dynamic Programming | Question 2"
},
{
"code": null,
"e": 25463,
"s": 25417,
"text": "Algorithms | Dynamic Programming | Question 3"
},
{
"code": null,
"e": 25513,
"s": 25463,
"text": "Algorithms | Analysis of Algorithms | Question 17"
},
{
"code": null,
"e": 25547,
"s": 25513,
"text": "Algorithms | Sorting | Question 1"
},
{
"code": null,
"e": 25591,
"s": 25547,
"text": "Algorithms | Greedy Algorithms | Question 1"
},
{
"code": null,
"e": 25642,
"s": 25591,
"text": "Algorithms Quiz | Dynamic Programming | Question 8"
},
{
"code": null,
"e": 25691,
"s": 25642,
"text": "Algorithms | Analysis of Algorithms | Question 8"
},
{
"code": null,
"e": 25736,
"s": 25691,
"text": "Algorithms | Divide and Conquer | Question 6"
},
{
"code": null,
"e": 25780,
"s": 25736,
"text": "Algorithms | Graph Traversals | Question 12"
}
] |
SaltStack - Salt File Server
|
The Salt file server is a stateless ZeroMQ server. It is built into the Salt master. A Salt file server is used for distributing files from master to minions. It contains different modules. Let us understand the salt file server, its configuration, modules related to the salt file server, how to access the salt file server in python, etc., in this chapter.
The file server backend allows the Salt file server to act as a transparent interface to other file server like a local file system, Git version control system, etc.
A Git file server backend can be enabled by using the following configuration in the master file.
fileserver_backend:
- git
To enable multiple backend file system, we can use the following configuration.
fileserver_backend:
- roots
- git
We can also specify the additional option for a different backend server using the specific section of the corresponding backend server.
For using this system, we have to use the following code.
file_roots:
base:
- /srv/salt/prod
For using this system, we have to use the following code.
gitfs_remotes:
- https://github.com/sample/sample1.git
Salt has the option to request files for specific environments.
salt://path/to/file?saltenv = base
Here, the environment is defined using the roots option.
Salt files can be allocated within many root directories and accessed by specifying both the file path and the environment to search. The individual environments can span across multiple directory roots.
The default environment is base. This environment is defined and is used to download files when no other environment is specified.
file_roots:
base:
- /srv/salt/base
You can also use multiple environments as shown in the code below.
file_roots:
base:
- /srv/salt/base
dev:
- /srv/salt/dev
- /srv/salt/base
The CP module is the main module to manipulate the Salt file server. The salt-cp command can also be used to distribute files presented by the Salt file server.
The cp.get_file function can be used on the minion to download a file from the master. It is defined as shown in the following code block.
salt '*' cp.get_file salt://vimrc /etc/vimrc
The above command instructs all Salt minions to download the vimrc file and copy it to /etc/vimrc.
You can enable template option in get_file as follows −
salt '*' cp.get_file "salt://vimrc" /etc/vimrc template = jinja
To use compression, use the gzip named argument. The valid values are integers from 1 to 9, where 1 is the minimum compression and 9 is maximum value.
The command is defined as follows −
salt '*' cp.get_file salt://vimrc /etc/vimrc gzip = 5
The cp.get_dir function can be used on the minion to download an entire directory from the master. It is defined in the following code block.
salt '*' cp.get_dir salt://etc/mysql /etc
The cp.get_dir supports template rendering and gzip compression arguments. If you want, you can assign as well.
Salt provides a python module that helps to access the salt file server. The salt/fileclient.py module is used to set up the communication from the minion to the master.
The sample code to get files is as follows −
import salt.minion
import salt.fileclient
def get_file(path, dest, saltenv = ‘base'):
client = salt.fileclient.get_file_client(__opts__)
return client.get_file(path, dest, true, saltenv)
Here,
opts is available when the module is run in the salt environment. Otherwise, we should provide the configuration path – /etc/salt/minion.
opts is available when the module is run in the salt environment. Otherwise, we should provide the configuration path – /etc/salt/minion.
path refers to the path of the source file in salt file server.
path refers to the path of the source file in salt file server.
dest refers the destination path of the file.
dest refers the destination path of the file.
saltenv refers to the environment
saltenv refers to the environment
In the next chapter, we will understand how to use Git as the file server.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2566,
"s": 2207,
"text": "The Salt file server is a stateless ZeroMQ server. It is built into the Salt master. A Salt file server is used for distributing files from master to minions. It contains different modules. Let us understand the salt file server, its configuration, modules related to the salt file server, how to access the salt file server in python, etc., in this chapter."
},
{
"code": null,
"e": 2732,
"s": 2566,
"text": "The file server backend allows the Salt file server to act as a transparent interface to other file server like a local file system, Git version control system, etc."
},
{
"code": null,
"e": 2830,
"s": 2732,
"text": "A Git file server backend can be enabled by using the following configuration in the master file."
},
{
"code": null,
"e": 2860,
"s": 2830,
"text": "fileserver_backend:\n - git\n"
},
{
"code": null,
"e": 2940,
"s": 2860,
"text": "To enable multiple backend file system, we can use the following configuration."
},
{
"code": null,
"e": 2981,
"s": 2940,
"text": "fileserver_backend:\n - roots\n - git\n"
},
{
"code": null,
"e": 3118,
"s": 2981,
"text": "We can also specify the additional option for a different backend server using the specific section of the corresponding backend server."
},
{
"code": null,
"e": 3176,
"s": 3118,
"text": "For using this system, we have to use the following code."
},
{
"code": null,
"e": 3221,
"s": 3176,
"text": "file_roots:\n base:\n - /srv/salt/prod\n"
},
{
"code": null,
"e": 3279,
"s": 3221,
"text": "For using this system, we have to use the following code."
},
{
"code": null,
"e": 3338,
"s": 3279,
"text": "gitfs_remotes:\n - https://github.com/sample/sample1.git\n"
},
{
"code": null,
"e": 3402,
"s": 3338,
"text": "Salt has the option to request files for specific environments."
},
{
"code": null,
"e": 3438,
"s": 3402,
"text": "salt://path/to/file?saltenv = base\n"
},
{
"code": null,
"e": 3495,
"s": 3438,
"text": "Here, the environment is defined using the roots option."
},
{
"code": null,
"e": 3699,
"s": 3495,
"text": "Salt files can be allocated within many root directories and accessed by specifying both the file path and the environment to search. The individual environments can span across multiple directory roots."
},
{
"code": null,
"e": 3830,
"s": 3699,
"text": "The default environment is base. This environment is defined and is used to download files when no other environment is specified."
},
{
"code": null,
"e": 3875,
"s": 3830,
"text": "file_roots:\n base:\n - /srv/salt/base\n"
},
{
"code": null,
"e": 3942,
"s": 3875,
"text": "You can also use multiple environments as shown in the code below."
},
{
"code": null,
"e": 4040,
"s": 3942,
"text": "file_roots:\n base:\n - /srv/salt/base\n dev:\n - /srv/salt/dev\n - /srv/salt/base\n"
},
{
"code": null,
"e": 4201,
"s": 4040,
"text": "The CP module is the main module to manipulate the Salt file server. The salt-cp command can also be used to distribute files presented by the Salt file server."
},
{
"code": null,
"e": 4340,
"s": 4201,
"text": "The cp.get_file function can be used on the minion to download a file from the master. It is defined as shown in the following code block."
},
{
"code": null,
"e": 4386,
"s": 4340,
"text": "salt '*' cp.get_file salt://vimrc /etc/vimrc\n"
},
{
"code": null,
"e": 4485,
"s": 4386,
"text": "The above command instructs all Salt minions to download the vimrc file and copy it to /etc/vimrc."
},
{
"code": null,
"e": 4541,
"s": 4485,
"text": "You can enable template option in get_file as follows −"
},
{
"code": null,
"e": 4606,
"s": 4541,
"text": "salt '*' cp.get_file \"salt://vimrc\" /etc/vimrc template = jinja\n"
},
{
"code": null,
"e": 4757,
"s": 4606,
"text": "To use compression, use the gzip named argument. The valid values are integers from 1 to 9, where 1 is the minimum compression and 9 is maximum value."
},
{
"code": null,
"e": 4793,
"s": 4757,
"text": "The command is defined as follows −"
},
{
"code": null,
"e": 4848,
"s": 4793,
"text": "salt '*' cp.get_file salt://vimrc /etc/vimrc gzip = 5\n"
},
{
"code": null,
"e": 4990,
"s": 4848,
"text": "The cp.get_dir function can be used on the minion to download an entire directory from the master. It is defined in the following code block."
},
{
"code": null,
"e": 5033,
"s": 4990,
"text": "salt '*' cp.get_dir salt://etc/mysql /etc\n"
},
{
"code": null,
"e": 5145,
"s": 5033,
"text": "The cp.get_dir supports template rendering and gzip compression arguments. If you want, you can assign as well."
},
{
"code": null,
"e": 5315,
"s": 5145,
"text": "Salt provides a python module that helps to access the salt file server. The salt/fileclient.py module is used to set up the communication from the minion to the master."
},
{
"code": null,
"e": 5360,
"s": 5315,
"text": "The sample code to get files is as follows −"
},
{
"code": null,
"e": 5554,
"s": 5360,
"text": "import salt.minion\nimport salt.fileclient\n\ndef get_file(path, dest, saltenv = ‘base'):\n client = salt.fileclient.get_file_client(__opts__)\n return client.get_file(path, dest, true, saltenv)"
},
{
"code": null,
"e": 5560,
"s": 5554,
"text": "Here,"
},
{
"code": null,
"e": 5698,
"s": 5560,
"text": "opts is available when the module is run in the salt environment. Otherwise, we should provide the configuration path – /etc/salt/minion."
},
{
"code": null,
"e": 5836,
"s": 5698,
"text": "opts is available when the module is run in the salt environment. Otherwise, we should provide the configuration path – /etc/salt/minion."
},
{
"code": null,
"e": 5900,
"s": 5836,
"text": "path refers to the path of the source file in salt file server."
},
{
"code": null,
"e": 5964,
"s": 5900,
"text": "path refers to the path of the source file in salt file server."
},
{
"code": null,
"e": 6010,
"s": 5964,
"text": "dest refers the destination path of the file."
},
{
"code": null,
"e": 6056,
"s": 6010,
"text": "dest refers the destination path of the file."
},
{
"code": null,
"e": 6090,
"s": 6056,
"text": "saltenv refers to the environment"
},
{
"code": null,
"e": 6124,
"s": 6090,
"text": "saltenv refers to the environment"
},
{
"code": null,
"e": 6199,
"s": 6124,
"text": "In the next chapter, we will understand how to use Git as the file server."
},
{
"code": null,
"e": 6206,
"s": 6199,
"text": " Print"
},
{
"code": null,
"e": 6217,
"s": 6206,
"text": " Add Notes"
}
] |
C program to trim leading white spaces from String - GeeksforGeeks
|
07 Aug, 2020
Given string str, the task is to write C program to remove leading space from the given string.
Examples :
Input: str = ” geeksforgeeks”Output: geeksforgeeks
Input: str = “gfg”Output: gfg
Approach: The idea is to count the leading spaces in the given string and then from that count index copy the characters from that index to the front of the string. Below are the steps:
Initialize count = 0 to count the number of leading spaces.Iterate through given string and find the index(say idx) at which the leading space character ends.Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.Finally, put ‘\0’ at the last index of the new string to terminate the string.
Initialize count = 0 to count the number of leading spaces.
Iterate through given string and find the index(say idx) at which the leading space character ends.
Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.
Finally, put ‘\0’ at the last index of the new string to terminate the string.
Below is the implementation of the above approach:
C
// C program for the above approach#include <stdio.h> // Function to remove leading// spaces from a given stringchar* removeLeadingSpaces(char* str){ static char str1[99]; int count = 0, j, k; // Iterate String until last // leading space character while (str[count] == ' ') { count++; } // Putting string into another // string variable after // removing leading white spaces for (j = count, k = 0; str[j] != '\0'; j++, k++) { str1[k] = str[j]; } str1[k] = '\0'; return str1;} // Driver Codeint main(){ // Given string char str[] = " geeksforgeeks"; char* ptr; // Function call ptr = removeLeadingSpaces(str); // Print string without leading space printf("%s", ptr); return 0;}
geeksforgeeks
Time Complexity: O(N)Auxiliary Space: O(N)
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24954,
"s": 24926,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 25050,
"s": 24954,
"text": "Given string str, the task is to write C program to remove leading space from the given string."
},
{
"code": null,
"e": 25061,
"s": 25050,
"text": "Examples :"
},
{
"code": null,
"e": 25118,
"s": 25061,
"text": "Input: str = ” geeksforgeeks”Output: geeksforgeeks"
},
{
"code": null,
"e": 25148,
"s": 25118,
"text": "Input: str = “gfg”Output: gfg"
},
{
"code": null,
"e": 25334,
"s": 25148,
"text": "Approach: The idea is to count the leading spaces in the given string and then from that count index copy the characters from that index to the front of the string. Below are the steps:"
},
{
"code": null,
"e": 25696,
"s": 25334,
"text": "Initialize count = 0 to count the number of leading spaces.Iterate through given string and find the index(say idx) at which the leading space character ends.Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.Finally, put ‘\\0’ at the last index of the new string to terminate the string."
},
{
"code": null,
"e": 25756,
"s": 25696,
"text": "Initialize count = 0 to count the number of leading spaces."
},
{
"code": null,
"e": 25856,
"s": 25756,
"text": "Iterate through given string and find the index(say idx) at which the leading space character ends."
},
{
"code": null,
"e": 25982,
"s": 25856,
"text": "Iterate through all the characters from that index idx and copy each character from this index to the end to the front index."
},
{
"code": null,
"e": 26061,
"s": 25982,
"text": "Finally, put ‘\\0’ at the last index of the new string to terminate the string."
},
{
"code": null,
"e": 26112,
"s": 26061,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26114,
"s": 26112,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h> // Function to remove leading// spaces from a given stringchar* removeLeadingSpaces(char* str){ static char str1[99]; int count = 0, j, k; // Iterate String until last // leading space character while (str[count] == ' ') { count++; } // Putting string into another // string variable after // removing leading white spaces for (j = count, k = 0; str[j] != '\\0'; j++, k++) { str1[k] = str[j]; } str1[k] = '\\0'; return str1;} // Driver Codeint main(){ // Given string char str[] = \" geeksforgeeks\"; char* ptr; // Function call ptr = removeLeadingSpaces(str); // Print string without leading space printf(\"%s\", ptr); return 0;}",
"e": 26898,
"s": 26114,
"text": null
},
{
"code": null,
"e": 26913,
"s": 26898,
"text": "geeksforgeeks\n"
},
{
"code": null,
"e": 26956,
"s": 26913,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26967,
"s": 26956,
"text": "C Programs"
},
{
"code": null,
"e": 26975,
"s": 26967,
"text": "Strings"
},
{
"code": null,
"e": 26983,
"s": 26975,
"text": "Strings"
},
{
"code": null,
"e": 27081,
"s": 26983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27122,
"s": 27081,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27153,
"s": 27122,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27194,
"s": 27153,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27228,
"s": 27194,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 27253,
"s": 27228,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 27278,
"s": 27253,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27324,
"s": 27278,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27358,
"s": 27324,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27418,
"s": 27358,
"text": "Write a program to print all permutations of a given string"
}
] |
C# | Type.GetInterface() Method - GeeksforGeeks
|
05 Dec, 2019
Type.GetInterface() Method is used to gets a specific interface implemented or inherited by the current Type.
GetInterface(String) Method
GetInterface(String, Boolean) Method
This method is used to search for the interface with the specified name.
Syntax: public Type GetInterface (string name);Here, it takes the string containing the name of the interface to get. For generic interfaces, this is the mangled name.
Return Value: This method returns an object representing the interface with the specified name, implemented or inherited by the current Type, if found otherwise, null.
Exception: This method throws ArgumentNullException if the name is null .
Below programs illustrate the use of Type.GetInterface(String) Method:
Example 1:
// C# program to demonstrate the// Type.GetInterface(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface("IFormattable"); // Display the Result Console.WriteLine("interface is: {0}", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
interface is: System.IFormattable
Example 2: For ArgumentNullException
// C# program to demonstrate the// Type.GetInterface(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(null); // Display the Result Console.WriteLine("interface is: {0}", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
name is null.
Exception Thrown: System.ArgumentNullException
This method is used to search for the specified interface, specifying whether to do a case-insensitive search for the interface name when overridden in a derived class.
Syntax: public abstract Type GetInterface (string name, bool ignoreCase);
Parameters:
name: The string containing the name of the interface to get. For generic interfaces, this is the mangled name.
ignoreCase: true to ignore the case of that part of the name which specifies the simple interface name (the part that specifies the namespace must be correctly cased) Or false to perform a case-sensitive search for all parts of the name.
Return Value: This method returns n object representing the interface with the specified name, implemented or inherited by the current Type if found otherwise, null.
Exception: This method throws ArgumentNullException if name is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.GetInterface(String, // Boolean) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface("iformattable", true); // Display the Result Console.WriteLine("interface is: {0}", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
interface is: System.IFormattable
Example 2: For ArgumentNullException
// C# program to demonstrate the// Type.GetInterface(String, // Boolean) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(null, true); // Display the Result Console.WriteLine("interface is: {0}", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Output:
name is null.
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.getinterface?view=netframework-4.8
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Delegates
Introduction to .NET Framework
Difference between Ref and Out keywords in C#
HashSet in C# with Examples
C# | Replace() Method
C# | Abstract Classes
|
[
{
"code": null,
"e": 23986,
"s": 23958,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 24096,
"s": 23986,
"text": "Type.GetInterface() Method is used to gets a specific interface implemented or inherited by the current Type."
},
{
"code": null,
"e": 24124,
"s": 24096,
"text": "GetInterface(String) Method"
},
{
"code": null,
"e": 24161,
"s": 24124,
"text": "GetInterface(String, Boolean) Method"
},
{
"code": null,
"e": 24234,
"s": 24161,
"text": "This method is used to search for the interface with the specified name."
},
{
"code": null,
"e": 24402,
"s": 24234,
"text": "Syntax: public Type GetInterface (string name);Here, it takes the string containing the name of the interface to get. For generic interfaces, this is the mangled name."
},
{
"code": null,
"e": 24570,
"s": 24402,
"text": "Return Value: This method returns an object representing the interface with the specified name, implemented or inherited by the current Type, if found otherwise, null."
},
{
"code": null,
"e": 24644,
"s": 24570,
"text": "Exception: This method throws ArgumentNullException if the name is null ."
},
{
"code": null,
"e": 24715,
"s": 24644,
"text": "Below programs illustrate the use of Type.GetInterface(String) Method:"
},
{
"code": null,
"e": 24726,
"s": 24715,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetInterface(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(\"IFormattable\"); // Display the Result Console.WriteLine(\"interface is: {0}\", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25603,
"s": 24726,
"text": null
},
{
"code": null,
"e": 25638,
"s": 25603,
"text": "interface is: System.IFormattable\n"
},
{
"code": null,
"e": 25675,
"s": 25638,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Type.GetInterface(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(null); // Display the Result Console.WriteLine(\"interface is: {0}\", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26546,
"s": 25675,
"text": null
},
{
"code": null,
"e": 26608,
"s": 26546,
"text": "name is null.\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 26777,
"s": 26608,
"text": "This method is used to search for the specified interface, specifying whether to do a case-insensitive search for the interface name when overridden in a derived class."
},
{
"code": null,
"e": 26851,
"s": 26777,
"text": "Syntax: public abstract Type GetInterface (string name, bool ignoreCase);"
},
{
"code": null,
"e": 26863,
"s": 26851,
"text": "Parameters:"
},
{
"code": null,
"e": 26975,
"s": 26863,
"text": "name: The string containing the name of the interface to get. For generic interfaces, this is the mangled name."
},
{
"code": null,
"e": 27213,
"s": 26975,
"text": "ignoreCase: true to ignore the case of that part of the name which specifies the simple interface name (the part that specifies the namespace must be correctly cased) Or false to perform a case-sensitive search for all parts of the name."
},
{
"code": null,
"e": 27379,
"s": 27213,
"text": "Return Value: This method returns n object representing the interface with the specified name, implemented or inherited by the current Type if found otherwise, null."
},
{
"code": null,
"e": 27448,
"s": 27379,
"text": "Exception: This method throws ArgumentNullException if name is null."
},
{
"code": null,
"e": 27513,
"s": 27448,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 27524,
"s": 27513,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetInterface(String, // Boolean) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(\"iformattable\", true); // Display the Result Console.WriteLine(\"interface is: {0}\", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 28415,
"s": 27524,
"text": null
},
{
"code": null,
"e": 28450,
"s": 28415,
"text": "interface is: System.IFormattable\n"
},
{
"code": null,
"e": 28487,
"s": 28450,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Type.GetInterface(String, // Boolean) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting interface of specified name // using GetField(String) Method Type minterface = objType.GetInterface(null, true); // Display the Result Console.WriteLine(\"interface is: {0}\", minterface); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 29376,
"s": 28487,
"text": null
},
{
"code": null,
"e": 29384,
"s": 29376,
"text": "Output:"
},
{
"code": null,
"e": 29446,
"s": 29384,
"text": "name is null.\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 29457,
"s": 29446,
"text": "Reference:"
},
{
"code": null,
"e": 29548,
"s": 29457,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getinterface?view=netframework-4.8"
},
{
"code": null,
"e": 29562,
"s": 29548,
"text": "CSharp-method"
},
{
"code": null,
"e": 29580,
"s": 29562,
"text": "CSharp-Type-Class"
},
{
"code": null,
"e": 29583,
"s": 29580,
"text": "C#"
},
{
"code": null,
"e": 29681,
"s": 29583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29690,
"s": 29681,
"text": "Comments"
},
{
"code": null,
"e": 29703,
"s": 29690,
"text": "Old Comments"
},
{
"code": null,
"e": 29731,
"s": 29703,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29754,
"s": 29731,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29794,
"s": 29754,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29817,
"s": 29794,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29832,
"s": 29817,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29863,
"s": 29832,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29909,
"s": 29863,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29937,
"s": 29909,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29959,
"s": 29937,
"text": "C# | Replace() Method"
}
] |
alsactl command in Linux with Examples - GeeksforGeeks
|
03 Jul, 2020
alsactl is used to control advanced settings for the ALSA(The Advanced Linux Sound Architecture) soundcard drivers. It supports multiple soundcards. It helps to get control over the card features that you can’t seem to control from a mixer application.
Syntax:
alsactl [options] [store|restore|init]
Some of the commands require superuser privilege(sudo) to execute.
1. store: It is used to save the current driver state to the configuration file, for the selected soundcard.Syntax :
sudo alsactl store
2. restore: It loads the driver state from the configuration file,of the selected soundcard. The init action is called in case the restoring fails due to any reason.Syntax :
sudo alsactl restore
3. init: It tries to initialize all devices to a default state. It returns 99 error code if the device is not known.Syntax :
alsactl init
4. –f Option : It is used to select the configuration file which is to be used.The default configuration file is /var/lib/alsa/asound.state.Syntax :
alsactl store -f /tmp/alsa.state
5. -–help Option : It with print the flags and commands of the alsactl command.Syntax :
alsactl -help
6. –version Option : It will print the version details of the alsactl command.Syntax :
alsactl -version
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
Docker - COPY Instruction
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 25787,
"s": 25759,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 26040,
"s": 25787,
"text": "alsactl is used to control advanced settings for the ALSA(The Advanced Linux Sound Architecture) soundcard drivers. It supports multiple soundcards. It helps to get control over the card features that you can’t seem to control from a mixer application."
},
{
"code": null,
"e": 26048,
"s": 26040,
"text": "Syntax:"
},
{
"code": null,
"e": 26089,
"s": 26048,
"text": "alsactl [options] [store|restore|init] \n"
},
{
"code": null,
"e": 26156,
"s": 26089,
"text": "Some of the commands require superuser privilege(sudo) to execute."
},
{
"code": null,
"e": 26273,
"s": 26156,
"text": "1. store: It is used to save the current driver state to the configuration file, for the selected soundcard.Syntax :"
},
{
"code": null,
"e": 26293,
"s": 26273,
"text": "sudo alsactl store\n"
},
{
"code": null,
"e": 26467,
"s": 26293,
"text": "2. restore: It loads the driver state from the configuration file,of the selected soundcard. The init action is called in case the restoring fails due to any reason.Syntax :"
},
{
"code": null,
"e": 26489,
"s": 26467,
"text": "sudo alsactl restore\n"
},
{
"code": null,
"e": 26614,
"s": 26489,
"text": "3. init: It tries to initialize all devices to a default state. It returns 99 error code if the device is not known.Syntax :"
},
{
"code": null,
"e": 26628,
"s": 26614,
"text": "alsactl init\n"
},
{
"code": null,
"e": 26777,
"s": 26628,
"text": "4. –f Option : It is used to select the configuration file which is to be used.The default configuration file is /var/lib/alsa/asound.state.Syntax :"
},
{
"code": null,
"e": 26811,
"s": 26777,
"text": "alsactl store -f /tmp/alsa.state\n"
},
{
"code": null,
"e": 26899,
"s": 26811,
"text": "5. -–help Option : It with print the flags and commands of the alsactl command.Syntax :"
},
{
"code": null,
"e": 26914,
"s": 26899,
"text": "alsactl -help\n"
},
{
"code": null,
"e": 27001,
"s": 26914,
"text": "6. –version Option : It will print the version details of the alsactl command.Syntax :"
},
{
"code": null,
"e": 27019,
"s": 27001,
"text": "alsactl -version\n"
},
{
"code": null,
"e": 27033,
"s": 27019,
"text": "linux-command"
},
{
"code": null,
"e": 27055,
"s": 27033,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 27062,
"s": 27055,
"text": "Picked"
},
{
"code": null,
"e": 27073,
"s": 27062,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27171,
"s": 27073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27206,
"s": 27171,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27235,
"s": 27206,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27269,
"s": 27235,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27295,
"s": 27269,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27332,
"s": 27295,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27369,
"s": 27332,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27411,
"s": 27369,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27437,
"s": 27411,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27473,
"s": 27437,
"text": "uniq Command in LINUX with examples"
}
] |
UUID toString() Method in Java with Examples - GeeksforGeeks
|
27 Dec, 2018
The toString() method of UUID class in Java is generally used to get the string representation of this UUID.
Syntax:
public String toString()
Parameters: This method does not take any parameter.
Return Value: This method returns a String value which is the string representation of this UUID.
Below programs illustrate the working of toString() method:
Program 1:
// Java code to illustrate toString() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "58e0a7d7-eebc-11d8-9669-0800200c9a66"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the string representation System.out.println("The string representation is: " + UUID_1.toString()); }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The string representation is: 58e0a7d7-eebc-11d8-9669-0800200c9a66
Program 2:
// Java code to illustrate toString() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "5fc03087-d265-11e7-b8c6-83e29cd24f4c"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the toString Value System.out.println("The string representation is: " + UUID_1.toString()); }}
UUID: 5fc03087-d265-11e7-b8c6-83e29cd24f4c
The string representation is: 5fc03087-d265-11e7-b8c6-83e29cd24f4c
Java - util package
Java-Functions
Java-UUID
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 24976,
"s": 24948,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 25085,
"s": 24976,
"text": "The toString() method of UUID class in Java is generally used to get the string representation of this UUID."
},
{
"code": null,
"e": 25093,
"s": 25085,
"text": "Syntax:"
},
{
"code": null,
"e": 25118,
"s": 25093,
"text": "public String toString()"
},
{
"code": null,
"e": 25171,
"s": 25118,
"text": "Parameters: This method does not take any parameter."
},
{
"code": null,
"e": 25269,
"s": 25171,
"text": "Return Value: This method returns a String value which is the string representation of this UUID."
},
{
"code": null,
"e": 25329,
"s": 25269,
"text": "Below programs illustrate the working of toString() method:"
},
{
"code": null,
"e": 25340,
"s": 25329,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate toString() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"58e0a7d7-eebc-11d8-9669-0800200c9a66\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the string representation System.out.println(\"The string representation is: \" + UUID_1.toString()); }}",
"e": 25905,
"s": 25340,
"text": null
},
{
"code": null,
"e": 26016,
"s": 25905,
"text": "UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66\nThe string representation is: 58e0a7d7-eebc-11d8-9669-0800200c9a66\n"
},
{
"code": null,
"e": 26027,
"s": 26016,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate toString() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"5fc03087-d265-11e7-b8c6-83e29cd24f4c\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the toString Value System.out.println(\"The string representation is: \" + UUID_1.toString()); }}",
"e": 26585,
"s": 26027,
"text": null
},
{
"code": null,
"e": 26696,
"s": 26585,
"text": "UUID: 5fc03087-d265-11e7-b8c6-83e29cd24f4c\nThe string representation is: 5fc03087-d265-11e7-b8c6-83e29cd24f4c\n"
},
{
"code": null,
"e": 26716,
"s": 26696,
"text": "Java - util package"
},
{
"code": null,
"e": 26731,
"s": 26716,
"text": "Java-Functions"
},
{
"code": null,
"e": 26741,
"s": 26731,
"text": "Java-UUID"
},
{
"code": null,
"e": 26746,
"s": 26741,
"text": "Java"
},
{
"code": null,
"e": 26751,
"s": 26746,
"text": "Java"
},
{
"code": null,
"e": 26849,
"s": 26751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26864,
"s": 26849,
"text": "Stream In Java"
},
{
"code": null,
"e": 26915,
"s": 26864,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26945,
"s": 26915,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26964,
"s": 26945,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26995,
"s": 26964,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27013,
"s": 26995,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27045,
"s": 27013,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27065,
"s": 27045,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27089,
"s": 27065,
"text": "Singleton Class in Java"
}
] |
Add image on a Python Tkinter button
|
Tkinter, which is the GUI library for python programming has a feature to add images to the GUI buttons. This is useful for users to remember the symbols in the GUI rather than the text in the GUI. In the below Tkinter program we show how we can add an image to a GUI button. The photoimage method from the imageKT module is used. We mention the local path to the image file.
from tkinter import *
from PIL import ImageTk ,Image
base = Tk()
base.title('Start Button')
img=ImageTk.PhotoImage(Image.open ("D:\\button.jpg"))
lab=Label(image=img)
lab.pack()
button=Button(base,text='exit',command=base.quit)
button.pack()
base.mainloop()
Running the above code gives us the following result −
|
[
{
"code": null,
"e": 1438,
"s": 1062,
"text": "Tkinter, which is the GUI library for python programming has a feature to add images to the GUI buttons. This is useful for users to remember the symbols in the GUI rather than the text in the GUI. In the below Tkinter program we show how we can add an image to a GUI button. The photoimage method from the imageKT module is used. We mention the local path to the image file."
},
{
"code": null,
"e": 1699,
"s": 1438,
"text": "from tkinter import *\nfrom PIL import ImageTk ,Image\n\nbase = Tk()\nbase.title('Start Button')\n\nimg=ImageTk.PhotoImage(Image.open (\"D:\\\\button.jpg\"))\nlab=Label(image=img)\nlab.pack()\n\nbutton=Button(base,text='exit',command=base.quit)\nbutton.pack()\nbase.mainloop()"
},
{
"code": null,
"e": 1754,
"s": 1699,
"text": "Running the above code gives us the following result −"
}
] |
3 bit Synchronous Down Counter - GeeksforGeeks
|
19 May, 2021
Prerequisite : Counter , Synchronous counter.
3 bit Synchronous Down Counter :
In synchronous counter clock is provided to all the flip-flops simultaneously.
Circuit becomes complex as the number of states increases.
Speed is high.
Design : The steps involves in design are
1. Decide the number of Flip flops –
N number of Flip flop(FF) required for N bit counter.
For 3 bit counter we require 3 FF.
Maximum count = 2n-1, where n is a number of bits.
For n= 3, Maximum count = 7.
Here T FF is used.
2. Write excitation table of FF –
3. Draw State diagram and circuit excitation table – Number of states = 2n, where n is number of bits.
Here T = 1, then there is output state(next state changes from previous state) changes i.e Q changes from 0 to 1 or 1 to 0 T= 0 then, there is no state output state changes i.e Q remains same
4. Find simplified equation using k map –
K map for 3 bit synchronous down counter
5. Create circuit diagram –The clock is provided to every Flip flop at same instant of time. The toggle(T) input is provided to every Flip flop according to the simplified equation of K map.
Timing diagram of 3 bit synchronous Down counter.
Explanation : Here -ve edge triggered clock is used for toggling purpose.
As we see from characteristics table when T = 1, then toggling takes place and T =0 then it stores the output state.
Initially Q3 = 0, Q2= 0, Q1= 0.
In simplified equation of K map we get T1 = 1, therefore Flip flop 1 output Q1 is toggle for every negative edge(because clock is negative edge triggered). Flip-flop(FF) 2 toggle input(T2) is connected to Q’1. Therefore, Flip Flop 2 output state Q2 is toggle only when there is clock falling edge (i.e -ve edge triggering) and Q’1 =1.
Similarly, Flip flop 3 toggle input(T) is connected to Q’2 and Q’1. Therefore, Flip flop 3 output is toggle when there is clock falling edge and Q’2=1 and Q’1 = 1 .(as you can see from timing diagram)
Therefore, we get output(as down counting Q3(MSB) Q2 Q1(LSB) after 8th -ve edge triggered clock the output of the three Flip flops again becomes Q3 = 0, Q2 = 0, Q1 =0.
We get output(state changes) after every -ve edge clock pulse.
By 3 Flip flop we get output as 23-1= 7 to 0.
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
4-bit binary Adder-Subtractor
Full Subtractor in Digital Logic
Encoder in Digital Logic
Carry Look-Ahead Adder
BCD to 7 Segment Decoder
Multiplexers in Digital Logic
Half Adder in Digital Logic
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Magnitude Comparator in Digital Logic
Encoders and Decoders in Digital Logic
|
[
{
"code": null,
"e": 24500,
"s": 24469,
"text": " \n19 May, 2021\n"
},
{
"code": null,
"e": 24546,
"s": 24500,
"text": "Prerequisite : Counter , Synchronous counter."
},
{
"code": null,
"e": 24579,
"s": 24546,
"text": "3 bit Synchronous Down Counter :"
},
{
"code": null,
"e": 24658,
"s": 24579,
"text": "In synchronous counter clock is provided to all the flip-flops simultaneously."
},
{
"code": null,
"e": 24717,
"s": 24658,
"text": "Circuit becomes complex as the number of states increases."
},
{
"code": null,
"e": 24732,
"s": 24717,
"text": "Speed is high."
},
{
"code": null,
"e": 24775,
"s": 24732,
"text": "Design : The steps involves in design are "
},
{
"code": null,
"e": 24815,
"s": 24775,
"text": " 1. Decide the number of Flip flops – "
},
{
"code": null,
"e": 24869,
"s": 24815,
"text": "N number of Flip flop(FF) required for N bit counter."
},
{
"code": null,
"e": 24904,
"s": 24869,
"text": "For 3 bit counter we require 3 FF."
},
{
"code": null,
"e": 24955,
"s": 24904,
"text": "Maximum count = 2n-1, where n is a number of bits."
},
{
"code": null,
"e": 24984,
"s": 24955,
"text": "For n= 3, Maximum count = 7."
},
{
"code": null,
"e": 25003,
"s": 24984,
"text": "Here T FF is used."
},
{
"code": null,
"e": 25040,
"s": 25003,
"text": " 2. Write excitation table of FF –"
},
{
"code": null,
"e": 25149,
"s": 25040,
"text": " 3. Draw State diagram and circuit excitation table – Number of states = 2n, where n is number of bits."
},
{
"code": null,
"e": 25342,
"s": 25149,
"text": "Here T = 1, then there is output state(next state changes from previous state) changes i.e Q changes from 0 to 1 or 1 to 0 T= 0 then, there is no state output state changes i.e Q remains same "
},
{
"code": null,
"e": 25385,
"s": 25342,
"text": " 4. Find simplified equation using k map –"
},
{
"code": null,
"e": 25427,
"s": 25385,
"text": "K map for 3 bit synchronous down counter "
},
{
"code": null,
"e": 25620,
"s": 25427,
"text": " 5. Create circuit diagram –The clock is provided to every Flip flop at same instant of time. The toggle(T) input is provided to every Flip flop according to the simplified equation of K map."
},
{
"code": null,
"e": 25670,
"s": 25620,
"text": "Timing diagram of 3 bit synchronous Down counter."
},
{
"code": null,
"e": 25745,
"s": 25670,
"text": "Explanation : Here -ve edge triggered clock is used for toggling purpose."
},
{
"code": null,
"e": 25862,
"s": 25745,
"text": "As we see from characteristics table when T = 1, then toggling takes place and T =0 then it stores the output state."
},
{
"code": null,
"e": 25894,
"s": 25862,
"text": "Initially Q3 = 0, Q2= 0, Q1= 0."
},
{
"code": null,
"e": 26230,
"s": 25894,
"text": "In simplified equation of K map we get T1 = 1, therefore Flip flop 1 output Q1 is toggle for every negative edge(because clock is negative edge triggered). Flip-flop(FF) 2 toggle input(T2) is connected to Q’1. Therefore, Flip Flop 2 output state Q2 is toggle only when there is clock falling edge (i.e -ve edge triggering) and Q’1 =1."
},
{
"code": null,
"e": 26431,
"s": 26230,
"text": "Similarly, Flip flop 3 toggle input(T) is connected to Q’2 and Q’1. Therefore, Flip flop 3 output is toggle when there is clock falling edge and Q’2=1 and Q’1 = 1 .(as you can see from timing diagram)"
},
{
"code": null,
"e": 26599,
"s": 26431,
"text": "Therefore, we get output(as down counting Q3(MSB) Q2 Q1(LSB) after 8th -ve edge triggered clock the output of the three Flip flops again becomes Q3 = 0, Q2 = 0, Q1 =0."
},
{
"code": null,
"e": 26662,
"s": 26599,
"text": "We get output(state changes) after every -ve edge clock pulse."
},
{
"code": null,
"e": 26708,
"s": 26662,
"text": "By 3 Flip flop we get output as 23-1= 7 to 0."
},
{
"code": null,
"e": 26745,
"s": 26708,
"text": "\nDigital Electronics & Logic Design\n"
},
{
"code": null,
"e": 26950,
"s": 26745,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26980,
"s": 26950,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 27013,
"s": 26980,
"text": "Full Subtractor in Digital Logic"
},
{
"code": null,
"e": 27038,
"s": 27013,
"text": "Encoder in Digital Logic"
},
{
"code": null,
"e": 27061,
"s": 27038,
"text": "Carry Look-Ahead Adder"
},
{
"code": null,
"e": 27086,
"s": 27061,
"text": "BCD to 7 Segment Decoder"
},
{
"code": null,
"e": 27116,
"s": 27086,
"text": "Multiplexers in Digital Logic"
},
{
"code": null,
"e": 27144,
"s": 27116,
"text": "Half Adder in Digital Logic"
},
{
"code": null,
"e": 27211,
"s": 27144,
"text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes"
},
{
"code": null,
"e": 27249,
"s": 27211,
"text": "Magnitude Comparator in Digital Logic"
}
] |
Groovy - equalsIgnoreCase()
|
Compares this String to another String, ignoring case considerations.
Boolean equalsIgnoreCase(String str)
Str - the String to compare this String against
This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
String a = "Hello World";
String b = "HELLO World";
String c = "HELLO WORLD";
println(a.equalsIgnoreCase(b));
println(a.equalsIgnoreCase(c));
println(b.equalsIgnoreCase(c));
}
}
When we run the above program, we will get the following result −
true
true
true
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2308,
"s": 2238,
"text": "Compares this String to another String, ignoring case considerations."
},
{
"code": null,
"e": 2346,
"s": 2308,
"text": "Boolean equalsIgnoreCase(String str)\n"
},
{
"code": null,
"e": 2394,
"s": 2346,
"text": "Str - the String to compare this String against"
},
{
"code": null,
"e": 2506,
"s": 2394,
"text": "This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise."
},
{
"code": null,
"e": 2560,
"s": 2506,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2841,
"s": 2560,
"text": "class Example { \n static void main(String[] args) { \n String a = \"Hello World\"; \n String b = \"HELLO World\"; \n String c = \"HELLO WORLD\";\n\t\t\n println(a.equalsIgnoreCase(b)); \n println(a.equalsIgnoreCase(c)); \n println(b.equalsIgnoreCase(c)); \n } \n}"
},
{
"code": null,
"e": 2907,
"s": 2841,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2925,
"s": 2907,
"text": "true \ntrue \ntrue\n"
},
{
"code": null,
"e": 2958,
"s": 2925,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2976,
"s": 2958,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3011,
"s": 2976,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3029,
"s": 3011,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3036,
"s": 3029,
"text": " Print"
},
{
"code": null,
"e": 3047,
"s": 3036,
"text": " Add Notes"
}
] |
Face Detection Using JavaScript API — face-api.js | by Deepak Gupta | Towards Data Science
|
In this article, we will learn about face detection (Age/Gender/Face Positions/Mood) using face-api.js and the nearby object detection (Person/Phone etc) using coco-ssd model on the web browser.
face-api.jsis a javascript module, built on top of tensorflow.js core, which implements several CNNs (Convolutional Neural Networks) to solve face detection, face recognition and face landmark detection, optimized for the web and for mobile devices.
Let’s start now,
Basic understanding of React.js (You may choose any library or frontend framework of your choice)Basic understanding of p5.js library.Installed create-react-app and Node.js version >= 10.15.1
Basic understanding of React.js (You may choose any library or frontend framework of your choice)
Basic understanding of p5.js library.
Installed create-react-app and Node.js version >= 10.15.1
npx create-react-app object_face_detectioncd object_face_detection
npm install @tensorflow-models/coco-ssdnpm install @tensorflow/tfjs-converternpm install @tensorflow/tfjs-corenpm install face-api.jsnpm install p5npm install react-p5-wrapper
Let’s understand each dependency one by one-
@tensorflow-models/coco-ssd — This will be used for other object detection like phone, wall, etc. around the face.Coco-ssd is a TensorFlow model already trained with a lot of general images and can directly be used inside a browser. You may read here — https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd@tensorflow/tfjs-converter —This convert TensorFlow saved models and keras models to be used by tensorflow.js directly. By that I mean there are a lot of models already made/trained using python or R but the model saved format is different from what the TensorFlow.js use/consume. So this dependency is required to convert other models into TensorFlow's consumable format.@tensorflow/tfjs-core — Tensorflow core javascript library. You may read this — https://www.tensorflow.org/js/tutorials/setup. The face-api.js is made on top of this dependency.face-api.js — This is the core API for this article and will be used for face detection. To learn more — https://github.com/justadudewhohacks/face-api.js?files=1P5 — This is another great library that has evolved in recent times, for our context we will use it for webcam video and for drawing a red color box around the detected face and objects. You may read — https://p5js.orgreact-p5-wrapper — This is just a reactjs wrapper written over p5js functionality. So Instead of writing one, we will use it to save time.
@tensorflow-models/coco-ssd — This will be used for other object detection like phone, wall, etc. around the face.Coco-ssd is a TensorFlow model already trained with a lot of general images and can directly be used inside a browser. You may read here — https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd
@tensorflow/tfjs-converter —This convert TensorFlow saved models and keras models to be used by tensorflow.js directly. By that I mean there are a lot of models already made/trained using python or R but the model saved format is different from what the TensorFlow.js use/consume. So this dependency is required to convert other models into TensorFlow's consumable format.
@tensorflow/tfjs-core — Tensorflow core javascript library. You may read this — https://www.tensorflow.org/js/tutorials/setup. The face-api.js is made on top of this dependency.
face-api.js — This is the core API for this article and will be used for face detection. To learn more — https://github.com/justadudewhohacks/face-api.js?files=1
P5 — This is another great library that has evolved in recent times, for our context we will use it for webcam video and for drawing a red color box around the detected face and objects. You may read — https://p5js.org
react-p5-wrapper — This is just a reactjs wrapper written over p5js functionality. So Instead of writing one, we will use it to save time.
Before we start, we need to download the face-api.js model (already build to do face and mood detection). So let’s create a folder called models inside our public folder and download the file present at — https://github.com/justadudewhohacks/face-api.js/tree/master/weights
The models folder will look like
We will now create a file called ObjectDetectionSketch.js inside our src folder, that will have all our logic.
The file will have some import statements as below
import * as p5 from 'p5'import "p5/lib/addons/p5.dom";import * as cocoSsd from '@tensorflow-models/coco-ssd';import * as faceapi from 'face-api.js';
p5 and p5.dom — needed to work with p5js, bear it with me, after a few paragraphs you will understand the exact usage.cocoSsd and faceapi— You already know it by now.
p5 and p5.dom — needed to work with p5js, bear it with me, after a few paragraphs you will understand the exact usage.
cocoSsd and faceapi— You already know it by now.
Next, we will define our face-API model URL
const MODEL_URL = '/models' // this will pick public folder by default
Now, we will create our function called sketch (the wrapper function that will have all our logic)
export default function sketch (p) {}
Inside the sketch function, we will define a few variables and four functions, two custom and two from p5.js called setup and draw .
Variables
// Variables// save current camera imagelet capture = null;// save cocossd Modellet cocossdModel = null;// to save the result of cocossd and face-api resultslet cocoDrawings = [];let faceDrawings = [];
Custom Functions
// Custom Function// Used to store the result of coco-ssd modelfunction showCocoSSDResults(results) { const id = capture.id(); cocoDrawings = results;}// used to store the result for the face-api.js modelfunction showFaceDetectionData(data) { faceDrawings = data;}
P5.js Functions
// P5.js Functionsp.setup = async function() {}p.draw = function() {}
Let’s understand both p5 functions in detail. 🚀
The p5.js Setup will be called automatically once page loads. We are overriding p5 built-insetup function to initiate some details that we require. Below are the steps that we will do inside our setup function.
1. Load three face-api.js models that we are going to use for face detection.
await faceapi.loadSsdMobilenetv1Model(MODEL_URL);await faceapi.loadAgeGenderModel(MODEL_URL);await faceapi.loadFaceExpressionModel(MODEL_URL);
2. Create a p5.js canvas
p.createCanvas(1280, 720);
3. Implement camera capture ability to canvas.
const constraints = { video: { mandatory: { minWidth: 1280, minHeight: 720 }, optional: [{ maxFrameRate: 10 }] }, audio: false};capture = p.createCapture(constraints, () => {});
4. Set the video Id and size.
capture.id("video_element");capture.size(1280, 720);capture.hide(); // this is require as we don't want to show the deafault video input
5. Load the cocoSsd model and save it locally.
cocoSsd.load().then((model) => { try { cocossdModel = model; } catch(e) { console.log(e); }}).catch((e) => { console.log("Error occured : ", e);});
The draw function of p5js is called if anything is drawn over p5js canvas. Inside our custom draw function, we will do the following steps.
Set the background as white and draw our image over it. Also, add the transparency so that anything drawn further to canvas will be transparent.
Set the background as white and draw our image over it. Also, add the transparency so that anything drawn further to canvas will be transparent.
p.background(255);p.image(capture, 0, 0); p.fill(0,0,0,0);
2. Code to render the coco-ssd model result.
cocoDrawings.map((drawing) => { if (drawing) { p.textSize(20); p.strokeWeight(1); const textX = drawing.bbox[0]+drawing.bbox[2]; const textY = drawing.bbox[1]+drawing.bbox[3]; const confidenetext = "Confidence: "+ drawing.score.toFixed(1); const textWidth = p.textWidth(confidenetext); const itemTextWidth = p.textWidth(drawing.class); p.text(drawing.class, textX-itemTextWidth-10, textY-50);p.text(confidenetext, textX-textWidth-10, textY-10); p.strokeWeight(4); p.stroke('rgb(100%,100%,100%)'); p.rect(drawing.bbox[0], drawing.bbox[1], drawing.bbox[2], drawing.bbox[3]); }});
Here we have a cocoDrawings object that contains current object details detected by coco-ssd model. The shape of the object looks like
{ "bbox": [ 6.165122985839844, 2.656116485595703, 1034.7143936157227, 712.3482799530029 ], "class": "person", "score": 0.9296618103981018}
We use this object data to draw a rectangle that defines the position of the current object with the name of what is detected (person in the above case) and score.
It's a basic p5js code to draw text and rectangle. If you find it hard to understand then give a shot to p5.js docs and within an hour you will have it. — https://p5js.org/
We can have multiple objects that will be drawn on canvas as they will get detected.
3. Code to render the face-api.js model result.
faceDrawings.map((drawing) => { if (drawing) { p.textSize(15); p.strokeWeight(1); const textX = drawing.detection.box._x+drawing.detection.box._width; const textY = drawing.detection.box._y+drawing.detection.box._height; const confidenetext = "Gender: "+ drawing.gender; const textWidth = p.textWidth(confidenetext); p.text(confidenetext, textX-textWidth, textY-60); const agetext = "Age: "+ drawing.age.toFixed(0); const ageTextWidth = p.textWidth(agetext); p.text(agetext, textX-ageTextWidth, textY-30); const copiedExpression = drawing.expressions; const expressions = Object.keys(copiedExpression).map((key) => { const value = copiedExpression[key]; return value; }) const max = Math.max(...expressions); const expression_value = Object.keys(copiedExpression).filter((key) => { return copiedExpression[key] === max; })[0]; const expressiontext = "Mood: "+ expression_value; const expressionWidth = p.textWidth(expressiontext); p.text(expressiontext, textX-expressionWidth, textY-10); p.strokeWeight(4); p.stroke('rgb(100%,0%,10%)'); p.rect(drawing.detection.box._x, drawing.detection.box._y, drawing.detection.box._width, drawing.detection.box._height); }});
Here we are defining text size, drawing the data that we got from face-api.js onto our p5.js canvas.
Now each detected face have below data returned by the face-api.js model
{ "detection": { "_imageDims": { "_width": 1280, "_height": 720 }, "_score": 0.6889822483062744, "_classScore": 0.6889822483062744, "_className": "", "_box": { "_x": 121.50997161865234, "_y": 15.035667419433594, "_width": 507.80059814453125, "_height": 531.7609024047852 } }, "gender": "male", "genderProbability": 0.9683359265327454, "age": 30.109874725341797, "expressions": { "neutral": 0.9950351715087891, "happy": 0.0000017113824242187547, "sad": 0.000005796719960926566, "angry": 0.00000466804613097338, "fearful": 1.3292748013427058e-9, "disgusted": 3.015825145169515e-9, "surprised": 0.004952521994709969 }}
You can see we are getting face as a rectangle coordinate, gender along with age and expressions data
Rectangle coordinates we can pull from detection._box and for expressions, we have all expressions and their corresponding score. So,
const copiedExpression = drawing.expressions;const expressions = Object.keys(copiedExpression).map((key) => { const value = copiedExpression[key]; return value;})const max = Math.max(...expressions);const expression_value = Object.keys(copiedExpression).filter((key) => { return copiedExpression[key] === max; })[0];
With the above code, we will estimate and get height scorer expression and display inside a rectangle
The most difficult part is to fit text inside rectangle, So we did a not so good implementation but it works.
So we remove this width from x coordinate of the box and also 10 more to have some margin from the left border and display text.
const ageTextWidth = p.textWidth(agetext);p.text(agetext, textX-ageTextWidth, textY-30);
But wait 🤔, All this is fine but where is the code that detects the face and the other object.
So here it is👇
4. The code to detect the face and other meta-objects.
faceapi.detectAllFaces(capture.id()) .withAgeAndGender() .withFaceExpressions() .then((data) => { showFaceDetectionData(data);});if(capture.loadedmetadata) { if (cocossdModel) { cocossdModel .detect(document.getElementById("video_element")) .then(showCocoSSDResults) .catch((e) => { console.log("Exception : ", e); }); }}
And we are done 🎢 and ready to test.
Inside the terminal do
cd object_face_detectionnpm start
Here is the output of trying —
https://github.com/overflowjs-com/object_face_detection_webcam_react — is the repository for the code if you find it difficult to flow along with this article.
Note: This implementation is slow as we are loading all models in browser and doing in real-time
Please consider entering your email here if you’d like to be added to my email list and follow me on medium to read more article on javascript and on github to see my crazy code. If anything is not clear or you want to point out something, please comment down below.
You may also like my other articles
Javascript Execution Context and HoistingJavascript — Generator-Yield/Next & Async-Await 🤔Understanding Javascript ‘this’ keyword (Context).Javascript data structure with map, reduce, filterJavascript- Currying VS Partial ApplicationJavascript ES6 — Iterables and IteratorsJavascript — ProxyJavascript — Scopes
Javascript Execution Context and Hoisting
Javascript — Generator-Yield/Next & Async-Await 🤔
Understanding Javascript ‘this’ keyword (Context).
Javascript data structure with map, reduce, filter
Javascript- Currying VS Partial Application
Javascript ES6 — Iterables and Iterators
Javascript — Proxy
Javascript — Scopes
|
[
{
"code": null,
"e": 366,
"s": 171,
"text": "In this article, we will learn about face detection (Age/Gender/Face Positions/Mood) using face-api.js and the nearby object detection (Person/Phone etc) using coco-ssd model on the web browser."
},
{
"code": null,
"e": 616,
"s": 366,
"text": "face-api.jsis a javascript module, built on top of tensorflow.js core, which implements several CNNs (Convolutional Neural Networks) to solve face detection, face recognition and face landmark detection, optimized for the web and for mobile devices."
},
{
"code": null,
"e": 633,
"s": 616,
"text": "Let’s start now,"
},
{
"code": null,
"e": 825,
"s": 633,
"text": "Basic understanding of React.js (You may choose any library or frontend framework of your choice)Basic understanding of p5.js library.Installed create-react-app and Node.js version >= 10.15.1"
},
{
"code": null,
"e": 923,
"s": 825,
"text": "Basic understanding of React.js (You may choose any library or frontend framework of your choice)"
},
{
"code": null,
"e": 961,
"s": 923,
"text": "Basic understanding of p5.js library."
},
{
"code": null,
"e": 1019,
"s": 961,
"text": "Installed create-react-app and Node.js version >= 10.15.1"
},
{
"code": null,
"e": 1086,
"s": 1019,
"text": "npx create-react-app object_face_detectioncd object_face_detection"
},
{
"code": null,
"e": 1262,
"s": 1086,
"text": "npm install @tensorflow-models/coco-ssdnpm install @tensorflow/tfjs-converternpm install @tensorflow/tfjs-corenpm install face-api.jsnpm install p5npm install react-p5-wrapper"
},
{
"code": null,
"e": 1307,
"s": 1262,
"text": "Let’s understand each dependency one by one-"
},
{
"code": null,
"e": 2689,
"s": 1307,
"text": "@tensorflow-models/coco-ssd — This will be used for other object detection like phone, wall, etc. around the face.Coco-ssd is a TensorFlow model already trained with a lot of general images and can directly be used inside a browser. You may read here — https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd@tensorflow/tfjs-converter —This convert TensorFlow saved models and keras models to be used by tensorflow.js directly. By that I mean there are a lot of models already made/trained using python or R but the model saved format is different from what the TensorFlow.js use/consume. So this dependency is required to convert other models into TensorFlow's consumable format.@tensorflow/tfjs-core — Tensorflow core javascript library. You may read this — https://www.tensorflow.org/js/tutorials/setup. The face-api.js is made on top of this dependency.face-api.js — This is the core API for this article and will be used for face detection. To learn more — https://github.com/justadudewhohacks/face-api.js?files=1P5 — This is another great library that has evolved in recent times, for our context we will use it for webcam video and for drawing a red color box around the detected face and objects. You may read — https://p5js.orgreact-p5-wrapper — This is just a reactjs wrapper written over p5js functionality. So Instead of writing one, we will use it to save time."
},
{
"code": null,
"e": 3005,
"s": 2689,
"text": "@tensorflow-models/coco-ssd — This will be used for other object detection like phone, wall, etc. around the face.Coco-ssd is a TensorFlow model already trained with a lot of general images and can directly be used inside a browser. You may read here — https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd"
},
{
"code": null,
"e": 3378,
"s": 3005,
"text": "@tensorflow/tfjs-converter —This convert TensorFlow saved models and keras models to be used by tensorflow.js directly. By that I mean there are a lot of models already made/trained using python or R but the model saved format is different from what the TensorFlow.js use/consume. So this dependency is required to convert other models into TensorFlow's consumable format."
},
{
"code": null,
"e": 3556,
"s": 3378,
"text": "@tensorflow/tfjs-core — Tensorflow core javascript library. You may read this — https://www.tensorflow.org/js/tutorials/setup. The face-api.js is made on top of this dependency."
},
{
"code": null,
"e": 3718,
"s": 3556,
"text": "face-api.js — This is the core API for this article and will be used for face detection. To learn more — https://github.com/justadudewhohacks/face-api.js?files=1"
},
{
"code": null,
"e": 3937,
"s": 3718,
"text": "P5 — This is another great library that has evolved in recent times, for our context we will use it for webcam video and for drawing a red color box around the detected face and objects. You may read — https://p5js.org"
},
{
"code": null,
"e": 4076,
"s": 3937,
"text": "react-p5-wrapper — This is just a reactjs wrapper written over p5js functionality. So Instead of writing one, we will use it to save time."
},
{
"code": null,
"e": 4350,
"s": 4076,
"text": "Before we start, we need to download the face-api.js model (already build to do face and mood detection). So let’s create a folder called models inside our public folder and download the file present at — https://github.com/justadudewhohacks/face-api.js/tree/master/weights"
},
{
"code": null,
"e": 4383,
"s": 4350,
"text": "The models folder will look like"
},
{
"code": null,
"e": 4494,
"s": 4383,
"text": "We will now create a file called ObjectDetectionSketch.js inside our src folder, that will have all our logic."
},
{
"code": null,
"e": 4545,
"s": 4494,
"text": "The file will have some import statements as below"
},
{
"code": null,
"e": 4694,
"s": 4545,
"text": "import * as p5 from 'p5'import \"p5/lib/addons/p5.dom\";import * as cocoSsd from '@tensorflow-models/coco-ssd';import * as faceapi from 'face-api.js';"
},
{
"code": null,
"e": 4861,
"s": 4694,
"text": "p5 and p5.dom — needed to work with p5js, bear it with me, after a few paragraphs you will understand the exact usage.cocoSsd and faceapi— You already know it by now."
},
{
"code": null,
"e": 4980,
"s": 4861,
"text": "p5 and p5.dom — needed to work with p5js, bear it with me, after a few paragraphs you will understand the exact usage."
},
{
"code": null,
"e": 5029,
"s": 4980,
"text": "cocoSsd and faceapi— You already know it by now."
},
{
"code": null,
"e": 5073,
"s": 5029,
"text": "Next, we will define our face-API model URL"
},
{
"code": null,
"e": 5144,
"s": 5073,
"text": "const MODEL_URL = '/models' // this will pick public folder by default"
},
{
"code": null,
"e": 5243,
"s": 5144,
"text": "Now, we will create our function called sketch (the wrapper function that will have all our logic)"
},
{
"code": null,
"e": 5281,
"s": 5243,
"text": "export default function sketch (p) {}"
},
{
"code": null,
"e": 5414,
"s": 5281,
"text": "Inside the sketch function, we will define a few variables and four functions, two custom and two from p5.js called setup and draw ."
},
{
"code": null,
"e": 5424,
"s": 5414,
"text": "Variables"
},
{
"code": null,
"e": 5626,
"s": 5424,
"text": "// Variables// save current camera imagelet capture = null;// save cocossd Modellet cocossdModel = null;// to save the result of cocossd and face-api resultslet cocoDrawings = [];let faceDrawings = [];"
},
{
"code": null,
"e": 5643,
"s": 5626,
"text": "Custom Functions"
},
{
"code": null,
"e": 5917,
"s": 5643,
"text": "// Custom Function// Used to store the result of coco-ssd modelfunction showCocoSSDResults(results) { const id = capture.id(); cocoDrawings = results;}// used to store the result for the face-api.js modelfunction showFaceDetectionData(data) { faceDrawings = data;}"
},
{
"code": null,
"e": 5933,
"s": 5917,
"text": "P5.js Functions"
},
{
"code": null,
"e": 6003,
"s": 5933,
"text": "// P5.js Functionsp.setup = async function() {}p.draw = function() {}"
},
{
"code": null,
"e": 6051,
"s": 6003,
"text": "Let’s understand both p5 functions in detail. 🚀"
},
{
"code": null,
"e": 6262,
"s": 6051,
"text": "The p5.js Setup will be called automatically once page loads. We are overriding p5 built-insetup function to initiate some details that we require. Below are the steps that we will do inside our setup function."
},
{
"code": null,
"e": 6340,
"s": 6262,
"text": "1. Load three face-api.js models that we are going to use for face detection."
},
{
"code": null,
"e": 6483,
"s": 6340,
"text": "await faceapi.loadSsdMobilenetv1Model(MODEL_URL);await faceapi.loadAgeGenderModel(MODEL_URL);await faceapi.loadFaceExpressionModel(MODEL_URL);"
},
{
"code": null,
"e": 6508,
"s": 6483,
"text": "2. Create a p5.js canvas"
},
{
"code": null,
"e": 6535,
"s": 6508,
"text": "p.createCanvas(1280, 720);"
},
{
"code": null,
"e": 6582,
"s": 6535,
"text": "3. Implement camera capture ability to canvas."
},
{
"code": null,
"e": 6788,
"s": 6582,
"text": "const constraints = { video: { mandatory: { minWidth: 1280, minHeight: 720 }, optional: [{ maxFrameRate: 10 }] }, audio: false};capture = p.createCapture(constraints, () => {});"
},
{
"code": null,
"e": 6818,
"s": 6788,
"text": "4. Set the video Id and size."
},
{
"code": null,
"e": 6955,
"s": 6818,
"text": "capture.id(\"video_element\");capture.size(1280, 720);capture.hide(); // this is require as we don't want to show the deafault video input"
},
{
"code": null,
"e": 7002,
"s": 6955,
"text": "5. Load the cocoSsd model and save it locally."
},
{
"code": null,
"e": 7166,
"s": 7002,
"text": "cocoSsd.load().then((model) => { try { cocossdModel = model; } catch(e) { console.log(e); }}).catch((e) => { console.log(\"Error occured : \", e);});"
},
{
"code": null,
"e": 7306,
"s": 7166,
"text": "The draw function of p5js is called if anything is drawn over p5js canvas. Inside our custom draw function, we will do the following steps."
},
{
"code": null,
"e": 7451,
"s": 7306,
"text": "Set the background as white and draw our image over it. Also, add the transparency so that anything drawn further to canvas will be transparent."
},
{
"code": null,
"e": 7596,
"s": 7451,
"text": "Set the background as white and draw our image over it. Also, add the transparency so that anything drawn further to canvas will be transparent."
},
{
"code": null,
"e": 7659,
"s": 7596,
"text": "p.background(255);p.image(capture, 0, 0); p.fill(0,0,0,0);"
},
{
"code": null,
"e": 7704,
"s": 7659,
"text": "2. Code to render the coco-ssd model result."
},
{
"code": null,
"e": 8347,
"s": 7704,
"text": "cocoDrawings.map((drawing) => { if (drawing) { p.textSize(20); p.strokeWeight(1); const textX = drawing.bbox[0]+drawing.bbox[2]; const textY = drawing.bbox[1]+drawing.bbox[3]; const confidenetext = \"Confidence: \"+ drawing.score.toFixed(1); const textWidth = p.textWidth(confidenetext); const itemTextWidth = p.textWidth(drawing.class); p.text(drawing.class, textX-itemTextWidth-10, textY-50);p.text(confidenetext, textX-textWidth-10, textY-10); p.strokeWeight(4); p.stroke('rgb(100%,100%,100%)'); p.rect(drawing.bbox[0], drawing.bbox[1], drawing.bbox[2], drawing.bbox[3]); }});"
},
{
"code": null,
"e": 8482,
"s": 8347,
"text": "Here we have a cocoDrawings object that contains current object details detected by coco-ssd model. The shape of the object looks like"
},
{
"code": null,
"e": 8637,
"s": 8482,
"text": "{ \"bbox\": [ 6.165122985839844, 2.656116485595703, 1034.7143936157227, 712.3482799530029 ], \"class\": \"person\", \"score\": 0.9296618103981018}"
},
{
"code": null,
"e": 8801,
"s": 8637,
"text": "We use this object data to draw a rectangle that defines the position of the current object with the name of what is detected (person in the above case) and score."
},
{
"code": null,
"e": 8974,
"s": 8801,
"text": "It's a basic p5js code to draw text and rectangle. If you find it hard to understand then give a shot to p5.js docs and within an hour you will have it. — https://p5js.org/"
},
{
"code": null,
"e": 9059,
"s": 8974,
"text": "We can have multiple objects that will be drawn on canvas as they will get detected."
},
{
"code": null,
"e": 9107,
"s": 9059,
"text": "3. Code to render the face-api.js model result."
},
{
"code": null,
"e": 10374,
"s": 9107,
"text": "faceDrawings.map((drawing) => { if (drawing) { p.textSize(15); p.strokeWeight(1); const textX = drawing.detection.box._x+drawing.detection.box._width; const textY = drawing.detection.box._y+drawing.detection.box._height; const confidenetext = \"Gender: \"+ drawing.gender; const textWidth = p.textWidth(confidenetext); p.text(confidenetext, textX-textWidth, textY-60); const agetext = \"Age: \"+ drawing.age.toFixed(0); const ageTextWidth = p.textWidth(agetext); p.text(agetext, textX-ageTextWidth, textY-30); const copiedExpression = drawing.expressions; const expressions = Object.keys(copiedExpression).map((key) => { const value = copiedExpression[key]; return value; }) const max = Math.max(...expressions); const expression_value = Object.keys(copiedExpression).filter((key) => { return copiedExpression[key] === max; })[0]; const expressiontext = \"Mood: \"+ expression_value; const expressionWidth = p.textWidth(expressiontext); p.text(expressiontext, textX-expressionWidth, textY-10); p.strokeWeight(4); p.stroke('rgb(100%,0%,10%)'); p.rect(drawing.detection.box._x, drawing.detection.box._y, drawing.detection.box._width, drawing.detection.box._height); }});"
},
{
"code": null,
"e": 10475,
"s": 10374,
"text": "Here we are defining text size, drawing the data that we got from face-api.js onto our p5.js canvas."
},
{
"code": null,
"e": 10548,
"s": 10475,
"text": "Now each detected face have below data returned by the face-api.js model"
},
{
"code": null,
"e": 11243,
"s": 10548,
"text": "{ \"detection\": { \"_imageDims\": { \"_width\": 1280, \"_height\": 720 }, \"_score\": 0.6889822483062744, \"_classScore\": 0.6889822483062744, \"_className\": \"\", \"_box\": { \"_x\": 121.50997161865234, \"_y\": 15.035667419433594, \"_width\": 507.80059814453125, \"_height\": 531.7609024047852 } }, \"gender\": \"male\", \"genderProbability\": 0.9683359265327454, \"age\": 30.109874725341797, \"expressions\": { \"neutral\": 0.9950351715087891, \"happy\": 0.0000017113824242187547, \"sad\": 0.000005796719960926566, \"angry\": 0.00000466804613097338, \"fearful\": 1.3292748013427058e-9, \"disgusted\": 3.015825145169515e-9, \"surprised\": 0.004952521994709969 }}"
},
{
"code": null,
"e": 11345,
"s": 11243,
"text": "You can see we are getting face as a rectangle coordinate, gender along with age and expressions data"
},
{
"code": null,
"e": 11479,
"s": 11345,
"text": "Rectangle coordinates we can pull from detection._box and for expressions, we have all expressions and their corresponding score. So,"
},
{
"code": null,
"e": 11805,
"s": 11479,
"text": "const copiedExpression = drawing.expressions;const expressions = Object.keys(copiedExpression).map((key) => { const value = copiedExpression[key]; return value;})const max = Math.max(...expressions);const expression_value = Object.keys(copiedExpression).filter((key) => { return copiedExpression[key] === max; })[0];"
},
{
"code": null,
"e": 11907,
"s": 11805,
"text": "With the above code, we will estimate and get height scorer expression and display inside a rectangle"
},
{
"code": null,
"e": 12017,
"s": 11907,
"text": "The most difficult part is to fit text inside rectangle, So we did a not so good implementation but it works."
},
{
"code": null,
"e": 12146,
"s": 12017,
"text": "So we remove this width from x coordinate of the box and also 10 more to have some margin from the left border and display text."
},
{
"code": null,
"e": 12235,
"s": 12146,
"text": "const ageTextWidth = p.textWidth(agetext);p.text(agetext, textX-ageTextWidth, textY-30);"
},
{
"code": null,
"e": 12330,
"s": 12235,
"text": "But wait 🤔, All this is fine but where is the code that detects the face and the other object."
},
{
"code": null,
"e": 12345,
"s": 12330,
"text": "So here it is👇"
},
{
"code": null,
"e": 12400,
"s": 12345,
"text": "4. The code to detect the face and other meta-objects."
},
{
"code": null,
"e": 12780,
"s": 12400,
"text": "faceapi.detectAllFaces(capture.id()) .withAgeAndGender() .withFaceExpressions() .then((data) => { showFaceDetectionData(data);});if(capture.loadedmetadata) { if (cocossdModel) { cocossdModel .detect(document.getElementById(\"video_element\")) .then(showCocoSSDResults) .catch((e) => { console.log(\"Exception : \", e); }); }}"
},
{
"code": null,
"e": 12817,
"s": 12780,
"text": "And we are done 🎢 and ready to test."
},
{
"code": null,
"e": 12840,
"s": 12817,
"text": "Inside the terminal do"
},
{
"code": null,
"e": 12874,
"s": 12840,
"text": "cd object_face_detectionnpm start"
},
{
"code": null,
"e": 12905,
"s": 12874,
"text": "Here is the output of trying —"
},
{
"code": null,
"e": 13065,
"s": 12905,
"text": "https://github.com/overflowjs-com/object_face_detection_webcam_react — is the repository for the code if you find it difficult to flow along with this article."
},
{
"code": null,
"e": 13162,
"s": 13065,
"text": "Note: This implementation is slow as we are loading all models in browser and doing in real-time"
},
{
"code": null,
"e": 13429,
"s": 13162,
"text": "Please consider entering your email here if you’d like to be added to my email list and follow me on medium to read more article on javascript and on github to see my crazy code. If anything is not clear or you want to point out something, please comment down below."
},
{
"code": null,
"e": 13465,
"s": 13429,
"text": "You may also like my other articles"
},
{
"code": null,
"e": 13776,
"s": 13465,
"text": "Javascript Execution Context and HoistingJavascript — Generator-Yield/Next & Async-Await 🤔Understanding Javascript ‘this’ keyword (Context).Javascript data structure with map, reduce, filterJavascript- Currying VS Partial ApplicationJavascript ES6 — Iterables and IteratorsJavascript — ProxyJavascript — Scopes"
},
{
"code": null,
"e": 13818,
"s": 13776,
"text": "Javascript Execution Context and Hoisting"
},
{
"code": null,
"e": 13868,
"s": 13818,
"text": "Javascript — Generator-Yield/Next & Async-Await 🤔"
},
{
"code": null,
"e": 13919,
"s": 13868,
"text": "Understanding Javascript ‘this’ keyword (Context)."
},
{
"code": null,
"e": 13970,
"s": 13919,
"text": "Javascript data structure with map, reduce, filter"
},
{
"code": null,
"e": 14014,
"s": 13970,
"text": "Javascript- Currying VS Partial Application"
},
{
"code": null,
"e": 14055,
"s": 14014,
"text": "Javascript ES6 — Iterables and Iterators"
},
{
"code": null,
"e": 14074,
"s": 14055,
"text": "Javascript — Proxy"
}
] |
Adding Image in Existing PDF File using Java - GeeksforGeeks
|
08 Dec, 2020
These days, PDF is frequently used for report generation like to generate In order to make the java program interact with files be it of any type word, excel openCV Apache framework comes into play. External Files Required for Build this Code. The first requirement is to import the following libraries files
Pdfbox-xxx.jarorg.apache.commons.logging-xxx.jar
Pdfbox-xxx.jar
org.apache.commons.logging-xxx.jar
Algorithm:
Linking PDF document and java programCreate PDDocument objectCreate PDPageAdd page to document objectsCreate FileInputStream object for image.Create PDJpeg object by passing PDDocument object and FIleInputStream as its constructorInvoke drawXObject() object and specify coordinates with width and height to draw the image onto PDF file.Close the stream, saving the document object, and close the document.
Linking PDF document and java programCreate PDDocument objectCreate PDPageAdd page to document objectsCreate FileInputStream object for image.
Create PDDocument object
Create PDPage
Add page to document objects
Create FileInputStream object for image.
Create PDJpeg object by passing PDDocument object and FIleInputStream as its constructor
Invoke drawXObject() object and specify coordinates with width and height to draw the image onto PDF file.
Close the stream, saving the document object, and close the document.
Implementation: Considering an input image sample to illustrate the working of a program where in order to illustrate the working PDF document before is as follows:
Processing with the usage of java program to insert text in the above PDF document
Java
// Adding Image in Existing PDF using Java // Importing openCV librariesimport java.io.File;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.graphics.image PDImageXObject;import org.apache.pdfbox.pdmodel.PDPageContentStream;import java.io.IOException; class GFG { // Main driver method public static void main(String[] args) throws IOException { // Loading an already existing pdf document File file = new File("D:\\javong\\pdf1.pdf"); PDDocument doc = new PDDocument.load(file); // Retrieve the page PDPage page = doc.getPage(0); // Creating Object of PDImageXObject for selecting // Image and provide the path of file in argument PDImageXObject pdfimg = PDImageXImage.createFromFile( "D:\\Images\\chloro.jpg", doc); // Creating the PDPageContentStream Object // for Inserting Image PDPageContentStream image = new PDPageContentStream(doc, page); // set the Image inside the Page image.drawImage(pdfImage, 55, 370); System.out.println("Image Inserted"); // Closing the page of PDF by closing // PDPageContentStream Object // && Saving the Document image.close(); doc.save("D:\\javong\\pdf1.pdf"); // Closing the Document doc.close(); }}
Output: Text inserted in the same input image.
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 25547,
"s": 25237,
"text": " These days, PDF is frequently used for report generation like to generate In order to make the java program interact with files be it of any type word, excel openCV Apache framework comes into play. External Files Required for Build this Code. The first requirement is to import the following libraries files"
},
{
"code": null,
"e": 25596,
"s": 25547,
"text": "Pdfbox-xxx.jarorg.apache.commons.logging-xxx.jar"
},
{
"code": null,
"e": 25611,
"s": 25596,
"text": "Pdfbox-xxx.jar"
},
{
"code": null,
"e": 25646,
"s": 25611,
"text": "org.apache.commons.logging-xxx.jar"
},
{
"code": null,
"e": 25657,
"s": 25646,
"text": "Algorithm:"
},
{
"code": null,
"e": 26063,
"s": 25657,
"text": "Linking PDF document and java programCreate PDDocument objectCreate PDPageAdd page to document objectsCreate FileInputStream object for image.Create PDJpeg object by passing PDDocument object and FIleInputStream as its constructorInvoke drawXObject() object and specify coordinates with width and height to draw the image onto PDF file.Close the stream, saving the document object, and close the document."
},
{
"code": null,
"e": 26206,
"s": 26063,
"text": "Linking PDF document and java programCreate PDDocument objectCreate PDPageAdd page to document objectsCreate FileInputStream object for image."
},
{
"code": null,
"e": 26231,
"s": 26206,
"text": "Create PDDocument object"
},
{
"code": null,
"e": 26245,
"s": 26231,
"text": "Create PDPage"
},
{
"code": null,
"e": 26274,
"s": 26245,
"text": "Add page to document objects"
},
{
"code": null,
"e": 26315,
"s": 26274,
"text": "Create FileInputStream object for image."
},
{
"code": null,
"e": 26404,
"s": 26315,
"text": "Create PDJpeg object by passing PDDocument object and FIleInputStream as its constructor"
},
{
"code": null,
"e": 26511,
"s": 26404,
"text": "Invoke drawXObject() object and specify coordinates with width and height to draw the image onto PDF file."
},
{
"code": null,
"e": 26581,
"s": 26511,
"text": "Close the stream, saving the document object, and close the document."
},
{
"code": null,
"e": 26746,
"s": 26581,
"text": "Implementation: Considering an input image sample to illustrate the working of a program where in order to illustrate the working PDF document before is as follows:"
},
{
"code": null,
"e": 26829,
"s": 26746,
"text": "Processing with the usage of java program to insert text in the above PDF document"
},
{
"code": null,
"e": 26834,
"s": 26829,
"text": "Java"
},
{
"code": "// Adding Image in Existing PDF using Java // Importing openCV librariesimport java.io.File;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.graphics.image PDImageXObject;import org.apache.pdfbox.pdmodel.PDPageContentStream;import java.io.IOException; class GFG { // Main driver method public static void main(String[] args) throws IOException { // Loading an already existing pdf document File file = new File(\"D:\\\\javong\\\\pdf1.pdf\"); PDDocument doc = new PDDocument.load(file); // Retrieve the page PDPage page = doc.getPage(0); // Creating Object of PDImageXObject for selecting // Image and provide the path of file in argument PDImageXObject pdfimg = PDImageXImage.createFromFile( \"D:\\\\Images\\\\chloro.jpg\", doc); // Creating the PDPageContentStream Object // for Inserting Image PDPageContentStream image = new PDPageContentStream(doc, page); // set the Image inside the Page image.drawImage(pdfImage, 55, 370); System.out.println(\"Image Inserted\"); // Closing the page of PDF by closing // PDPageContentStream Object // && Saving the Document image.close(); doc.save(\"D:\\\\javong\\\\pdf1.pdf\"); // Closing the Document doc.close(); }}",
"e": 28261,
"s": 26834,
"text": null
},
{
"code": null,
"e": 28308,
"s": 28261,
"text": "Output: Text inserted in the same input image."
},
{
"code": null,
"e": 28313,
"s": 28308,
"text": "Java"
},
{
"code": null,
"e": 28327,
"s": 28313,
"text": "Java Programs"
},
{
"code": null,
"e": 28332,
"s": 28327,
"text": "Java"
},
{
"code": null,
"e": 28430,
"s": 28332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28445,
"s": 28430,
"text": "Stream In Java"
},
{
"code": null,
"e": 28466,
"s": 28445,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28485,
"s": 28466,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28515,
"s": 28485,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28561,
"s": 28515,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28587,
"s": 28561,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28621,
"s": 28587,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28668,
"s": 28621,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28700,
"s": 28668,
"text": "How to Iterate HashMap in Java?"
}
] |
How to Loop Through Column Names in R dataframes? - GeeksforGeeks
|
28 Nov, 2021
In this article, we will discuss how to loop through column names in dataframe in R Programming Language.
Here we are using sapply() function with some functions to get column names. This function will return column names with some results
Syntax:
sapply(dataframe,specific function)
where
dataframe is the inpiut dataframe
specific function is like mean,sum,min ,max etc
Example: R program to get column names in the dataframe by performing some operations
R
# create dataframe with 4 columnsdata = data.frame(column1=c(23, 45), column2=c(50, 39), column3=c(33, 45), column4=c(11, 39)) # displayprint(data) # get mean of all columnsprint(sapply(data, mean)) # get sum of all columnsprint(sapply(data, sum)) # get minimum of all columnsprint(sapply(data, min)) # get maximum of all columnsprint(sapply(data, max))
Output:
column1 column2 column3 column4
1 23 50 33 11
2 45 39 45 39
column1 column2 column3 column4
34.0 44.5 39.0 25.0
column1 column2 column3 column4
68 89 78 50
column1 column2 column3 column4
23 39 33 11
column1 column2 column3 column4
45 50 45 39
By using this function we can get column names. We have to iterate through for loop to get all the column names.
Syntax:
for (iterator in colnames(dataframe)){
print(iterator )
}
where
dataframe is the input dataframe
iterator is a variable is used to iterate the elements
Example:
R
# create dataframe with 4 columnsdata = data.frame(column1=c(23, 45), column2=c(50, 39), column3=c(33, 45), column4=c(11, 39)) # displayprint(data) # display column namesfor (i in colnames(data)){ print(i)}
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 26703,
"s": 26597,
"text": "In this article, we will discuss how to loop through column names in dataframe in R Programming Language."
},
{
"code": null,
"e": 26837,
"s": 26703,
"text": "Here we are using sapply() function with some functions to get column names. This function will return column names with some results"
},
{
"code": null,
"e": 26845,
"s": 26837,
"text": "Syntax:"
},
{
"code": null,
"e": 26881,
"s": 26845,
"text": "sapply(dataframe,specific function)"
},
{
"code": null,
"e": 26887,
"s": 26881,
"text": "where"
},
{
"code": null,
"e": 26921,
"s": 26887,
"text": "dataframe is the inpiut dataframe"
},
{
"code": null,
"e": 26969,
"s": 26921,
"text": "specific function is like mean,sum,min ,max etc"
},
{
"code": null,
"e": 27055,
"s": 26969,
"text": "Example: R program to get column names in the dataframe by performing some operations"
},
{
"code": null,
"e": 27057,
"s": 27055,
"text": "R"
},
{
"code": "# create dataframe with 4 columnsdata = data.frame(column1=c(23, 45), column2=c(50, 39), column3=c(33, 45), column4=c(11, 39)) # displayprint(data) # get mean of all columnsprint(sapply(data, mean)) # get sum of all columnsprint(sapply(data, sum)) # get minimum of all columnsprint(sapply(data, min)) # get maximum of all columnsprint(sapply(data, max))",
"e": 27433,
"s": 27057,
"text": null
},
{
"code": null,
"e": 27441,
"s": 27433,
"text": "Output:"
},
{
"code": null,
"e": 27805,
"s": 27441,
"text": "column1 column2 column3 column4\n1 23 50 33 11\n2 45 39 45 39\ncolumn1 column2 column3 column4 \n 34.0 44.5 39.0 25.0 \ncolumn1 column2 column3 column4 \n 68 89 78 50 \ncolumn1 column2 column3 column4 \n 23 39 33 11 \ncolumn1 column2 column3 column4 \n 45 50 45 39 "
},
{
"code": null,
"e": 27918,
"s": 27805,
"text": "By using this function we can get column names. We have to iterate through for loop to get all the column names."
},
{
"code": null,
"e": 27926,
"s": 27918,
"text": "Syntax:"
},
{
"code": null,
"e": 27988,
"s": 27926,
"text": "for (iterator in colnames(dataframe)){\n print(iterator )\n}"
},
{
"code": null,
"e": 27994,
"s": 27988,
"text": "where"
},
{
"code": null,
"e": 28027,
"s": 27994,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 28082,
"s": 28027,
"text": "iterator is a variable is used to iterate the elements"
},
{
"code": null,
"e": 28091,
"s": 28082,
"text": "Example:"
},
{
"code": null,
"e": 28093,
"s": 28091,
"text": "R"
},
{
"code": "# create dataframe with 4 columnsdata = data.frame(column1=c(23, 45), column2=c(50, 39), column3=c(33, 45), column4=c(11, 39)) # displayprint(data) # display column namesfor (i in colnames(data)){ print(i)}",
"e": 28322,
"s": 28093,
"text": null
},
{
"code": null,
"e": 28330,
"s": 28322,
"text": "Output:"
},
{
"code": null,
"e": 28337,
"s": 28330,
"text": "Picked"
},
{
"code": null,
"e": 28358,
"s": 28337,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28370,
"s": 28358,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28381,
"s": 28370,
"text": "R Language"
},
{
"code": null,
"e": 28479,
"s": 28381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28531,
"s": 28479,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28566,
"s": 28531,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28624,
"s": 28566,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28662,
"s": 28624,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28705,
"s": 28662,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28754,
"s": 28705,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28771,
"s": 28754,
"text": "R - if statement"
},
{
"code": null,
"e": 28821,
"s": 28771,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28873,
"s": 28821,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
C# | CharEnumerator.GetType() Method - GeeksforGeeks
|
30 Apr, 2019
CharEnumerator.GetType() Method is used to get the type of the current instance. This method is inherited from the Object Class.
Syntax:
public Type GetType();
Return Value: This method returns the exact runtime type of the current instance.
Below are the programs to illustrate the use of CharEnumerator.GetType() Method:+
Example 1:
// C# program to illustrate the// use of CharEnumerator.GetType()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = "GeeksforGeeks is Awesome!"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the Type of // the CharEnumerator objects Console.WriteLine(chEnum.GetType()); }}
System.CharEnumerator
Example 2:
// C# program to illustrate the// use of CharEnumerator.GetType()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = "GeeksforGeeks is fun"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Instantiate a clone of CharEnumerator object CharEnumerator chEnumClone = (CharEnumerator)chEnum.Clone(); // Printing the Type of the // CharEnumerator objects and its clone Console.WriteLine("Type of CharEnumerator object: " + chEnum.GetType()); Console.WriteLine("Type of CharEnumerator clone object: " + chEnumClone.GetType()); }}
Type of CharEnumerator object: System.CharEnumerator
Type of CharEnumerator clone object: System.CharEnumerator
CSharp-CharEnumerator-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Replace() Method
C# | Constructors
Introduction to .NET Framework
|
[
{
"code": null,
"e": 25611,
"s": 25583,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 25740,
"s": 25611,
"text": "CharEnumerator.GetType() Method is used to get the type of the current instance. This method is inherited from the Object Class."
},
{
"code": null,
"e": 25748,
"s": 25740,
"text": "Syntax:"
},
{
"code": null,
"e": 25771,
"s": 25748,
"text": "public Type GetType();"
},
{
"code": null,
"e": 25853,
"s": 25771,
"text": "Return Value: This method returns the exact runtime type of the current instance."
},
{
"code": null,
"e": 25935,
"s": 25853,
"text": "Below are the programs to illustrate the use of CharEnumerator.GetType() Method:+"
},
{
"code": null,
"e": 25946,
"s": 25935,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// use of CharEnumerator.GetType()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = \"GeeksforGeeks is Awesome!\"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the Type of // the CharEnumerator objects Console.WriteLine(chEnum.GetType()); }}",
"e": 26407,
"s": 25946,
"text": null
},
{
"code": null,
"e": 26430,
"s": 26407,
"text": "System.CharEnumerator\n"
},
{
"code": null,
"e": 26441,
"s": 26430,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// use of CharEnumerator.GetType()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = \"GeeksforGeeks is fun\"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Instantiate a clone of CharEnumerator object CharEnumerator chEnumClone = (CharEnumerator)chEnum.Clone(); // Printing the Type of the // CharEnumerator objects and its clone Console.WriteLine(\"Type of CharEnumerator object: \" + chEnum.GetType()); Console.WriteLine(\"Type of CharEnumerator clone object: \" + chEnumClone.GetType()); }}",
"e": 27243,
"s": 26441,
"text": null
},
{
"code": null,
"e": 27356,
"s": 27243,
"text": "Type of CharEnumerator object: System.CharEnumerator\nType of CharEnumerator clone object: System.CharEnumerator\n"
},
{
"code": null,
"e": 27384,
"s": 27356,
"text": "CSharp-CharEnumerator-Class"
},
{
"code": null,
"e": 27398,
"s": 27384,
"text": "CSharp-method"
},
{
"code": null,
"e": 27401,
"s": 27398,
"text": "C#"
},
{
"code": null,
"e": 27499,
"s": 27401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27527,
"s": 27499,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27542,
"s": 27527,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27565,
"s": 27542,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27587,
"s": 27565,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27633,
"s": 27587,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27656,
"s": 27633,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27678,
"s": 27656,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27700,
"s": 27678,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27718,
"s": 27700,
"text": "C# | Constructors"
}
] |
MongoDB - limit() Method - GeeksforGeeks
|
28 Jan, 2021
In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return. We can use this method after the find() method and find() will give you all the records or documents in the collection. You can also use some conditions inside find to give you the result that you want.
In this method, we only pass numeric value.
This method is undefined for values which is less than -2131 and greater than 231.
Passing 0 in this method(limit(0)) is equivalent to no limit.
Syntax :
cursor.limit()
Or
db.collectionName.find(<query>).limit(<number>)
Examples:
In the following examples, we are working with:
Database: geeksforgeeks
Collections: gfg
Document: Eight documents contains the content
Limit two documents
db.gfg.find().limit(2)
Here, we only want the first two documents in the result. So, we pass 2 in the limit method.
Limit only two documents that match the given condition
db.gfg.find({"content":/c/i}).limit(2)
Here, we only want the two documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of /c/i, i denotes that it is case-insensitive.
Limit only three documents that match the given condition
db.gfg.find({"content":/c/i}).limit(3)
Here, we only want the three documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of /c/i, i denotes that it is case-insensitive.
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - FindOne() Method
MongoDB - Regex
Export data from MongoDB
Create user and add role in MongoDB
MongoDB Cursor
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - sort() Method
|
[
{
"code": null,
"e": 24202,
"s": 24174,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 24686,
"s": 24202,
"text": "In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return. We can use this method after the find() method and find() will give you all the records or documents in the collection. You can also use some conditions inside find to give you the result that you want."
},
{
"code": null,
"e": 24730,
"s": 24686,
"text": "In this method, we only pass numeric value."
},
{
"code": null,
"e": 24813,
"s": 24730,
"text": "This method is undefined for values which is less than -2131 and greater than 231."
},
{
"code": null,
"e": 24875,
"s": 24813,
"text": "Passing 0 in this method(limit(0)) is equivalent to no limit."
},
{
"code": null,
"e": 24884,
"s": 24875,
"text": "Syntax :"
},
{
"code": null,
"e": 24899,
"s": 24884,
"text": "cursor.limit()"
},
{
"code": null,
"e": 24902,
"s": 24899,
"text": "Or"
},
{
"code": null,
"e": 24950,
"s": 24902,
"text": "db.collectionName.find(<query>).limit(<number>)"
},
{
"code": null,
"e": 24960,
"s": 24950,
"text": "Examples:"
},
{
"code": null,
"e": 25008,
"s": 24960,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 25032,
"s": 25008,
"text": "Database: geeksforgeeks"
},
{
"code": null,
"e": 25049,
"s": 25032,
"text": "Collections: gfg"
},
{
"code": null,
"e": 25096,
"s": 25049,
"text": "Document: Eight documents contains the content"
},
{
"code": null,
"e": 25116,
"s": 25096,
"text": "Limit two documents"
},
{
"code": null,
"e": 25139,
"s": 25116,
"text": "db.gfg.find().limit(2)"
},
{
"code": null,
"e": 25232,
"s": 25139,
"text": "Here, we only want the first two documents in the result. So, we pass 2 in the limit method."
},
{
"code": null,
"e": 25288,
"s": 25232,
"text": "Limit only two documents that match the given condition"
},
{
"code": null,
"e": 25327,
"s": 25288,
"text": "db.gfg.find({\"content\":/c/i}).limit(2)"
},
{
"code": null,
"e": 25680,
"s": 25327,
"text": "Here, we only want the two documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of /c/i, i denotes that it is case-insensitive."
},
{
"code": null,
"e": 25738,
"s": 25680,
"text": "Limit only three documents that match the given condition"
},
{
"code": null,
"e": 25777,
"s": 25738,
"text": "db.gfg.find({\"content\":/c/i}).limit(3)"
},
{
"code": null,
"e": 26132,
"s": 25777,
"text": "Here, we only want the three documents that satisfy the given condition, i.e., {“content”:/c/i}) in the find() method. Here, content is key were we will check whether it contains ‘c’ character in the string or not. /c/ denotes that we are looking for strings that contain this ‘c’ character and in the end of /c/i, i denotes that it is case-insensitive."
},
{
"code": null,
"e": 26147,
"s": 26132,
"text": "MongoDB-method"
},
{
"code": null,
"e": 26154,
"s": 26147,
"text": "Picked"
},
{
"code": null,
"e": 26162,
"s": 26154,
"text": "MongoDB"
},
{
"code": null,
"e": 26260,
"s": 26162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26269,
"s": 26260,
"text": "Comments"
},
{
"code": null,
"e": 26282,
"s": 26269,
"text": "Old Comments"
},
{
"code": null,
"e": 26310,
"s": 26282,
"text": "MongoDB - Distinct() Method"
},
{
"code": null,
"e": 26348,
"s": 26310,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 26375,
"s": 26348,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 26391,
"s": 26375,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 26416,
"s": 26391,
"text": "Export data from MongoDB"
},
{
"code": null,
"e": 26452,
"s": 26416,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 26467,
"s": 26452,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 26522,
"s": 26467,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 26579,
"s": 26522,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
}
] |
Python - Split Numeric String into K digit integers - GeeksforGeeks
|
02 Sep, 2020
Given a String, convert it to K digit integers
Input : test_str = ‘457336’, K = 2Output : [45, 73, 36]Explanation : Divided in 2 digit integers.
Input : test_str = ‘457336’, K = 3Output : [457, 336]Explanation : Divided in 3 digit integers.
Method #1 : Using int() + slice + loop
In this, we iterate for string and perform slicing till K digits and then perform task of conversion to integer using int().
Python3
# Python3 code to demonstrate working of # Split Numeric String into K digit integers# Using int() + slice + loop # initializing stringtest_str = '457336842' # printing original stringprint("The original string is : " + str(test_str)) # initializing substringK = 3 res = []for idx in range(0, len(test_str), K): # converting to int, after slicing res.append(int(test_str[idx : idx + K])) # printing result print("Converted number list : " + str(res))
The original string is : 457336842
Converted number list : [457, 336, 842]
Method #2 : Using list comprehension + int() + slicing
Similar method to above, just a shorthand to solve this problem.
Python3
# Python3 code to demonstrate working of # Split Numeric String into K digit integers# Using list comprehension + int() + slicing # initializing stringtest_str = '457336842' # printing original stringprint("The original string is : " + str(test_str)) # initializing substringK = 3 # one liner to solve problemres = [int(test_str[idx : idx + K]) for idx in range(0, len(test_str), K)] # printing result print("Converted number list : " + str(res))
The original string is : 457336842
Converted number list : [457, 336, 842]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python?
|
[
{
"code": null,
"e": 24408,
"s": 24380,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 24455,
"s": 24408,
"text": "Given a String, convert it to K digit integers"
},
{
"code": null,
"e": 24553,
"s": 24455,
"text": "Input : test_str = ‘457336’, K = 2Output : [45, 73, 36]Explanation : Divided in 2 digit integers."
},
{
"code": null,
"e": 24649,
"s": 24553,
"text": "Input : test_str = ‘457336’, K = 3Output : [457, 336]Explanation : Divided in 3 digit integers."
},
{
"code": null,
"e": 24688,
"s": 24649,
"text": "Method #1 : Using int() + slice + loop"
},
{
"code": null,
"e": 24813,
"s": 24688,
"text": "In this, we iterate for string and perform slicing till K digits and then perform task of conversion to integer using int()."
},
{
"code": null,
"e": 24821,
"s": 24813,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Split Numeric String into K digit integers# Using int() + slice + loop # initializing stringtest_str = '457336842' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing substringK = 3 res = []for idx in range(0, len(test_str), K): # converting to int, after slicing res.append(int(test_str[idx : idx + K])) # printing result print(\"Converted number list : \" + str(res)) ",
"e": 25290,
"s": 24821,
"text": null
},
{
"code": null,
"e": 25366,
"s": 25290,
"text": "The original string is : 457336842\nConverted number list : [457, 336, 842]\n"
},
{
"code": null,
"e": 25421,
"s": 25366,
"text": "Method #2 : Using list comprehension + int() + slicing"
},
{
"code": null,
"e": 25486,
"s": 25421,
"text": "Similar method to above, just a shorthand to solve this problem."
},
{
"code": null,
"e": 25494,
"s": 25486,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Split Numeric String into K digit integers# Using list comprehension + int() + slicing # initializing stringtest_str = '457336842' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing substringK = 3 # one liner to solve problemres = [int(test_str[idx : idx + K]) for idx in range(0, len(test_str), K)] # printing result print(\"Converted number list : \" + str(res)) ",
"e": 25947,
"s": 25494,
"text": null
},
{
"code": null,
"e": 26023,
"s": 25947,
"text": "The original string is : 457336842\nConverted number list : [457, 336, 842]\n"
},
{
"code": null,
"e": 26044,
"s": 26023,
"text": "Python list-programs"
},
{
"code": null,
"e": 26067,
"s": 26044,
"text": "Python string-programs"
},
{
"code": null,
"e": 26074,
"s": 26067,
"text": "Python"
},
{
"code": null,
"e": 26090,
"s": 26074,
"text": "Python Programs"
},
{
"code": null,
"e": 26188,
"s": 26090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26197,
"s": 26188,
"text": "Comments"
},
{
"code": null,
"e": 26210,
"s": 26197,
"text": "Old Comments"
},
{
"code": null,
"e": 26228,
"s": 26210,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26260,
"s": 26228,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26282,
"s": 26260,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26324,
"s": 26282,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26361,
"s": 26324,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26383,
"s": 26361,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26422,
"s": 26383,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26460,
"s": 26422,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 26517,
"s": 26460,
"text": "Python program to check whether a number is Prime or not"
}
] |
How to plot a Bar Chart with multiple labels in Matplotlib?
|
To plot a bar chart with multiple labels in Matplotlib, we can take the following steps −
Make some data set for men_means, men_std, women_means, and women_std.
Make some data set for men_means, men_std, women_means, and women_std.
Make index data points using numpy.
Make index data points using numpy.
Initialize the width of the bars.
Initialize the width of the bars.
Use subplots() method to create a figure and a set of subplots.
Use subplots() method to create a figure and a set of subplots.
Create rects1 and rects2 bars rectangle using bar() method.
Create rects1 and rects2 bars rectangle using bar() method.
Use set_ylabel(),
set_title(), set_xticks() and set_xticklabels() methods.
Use set_ylabel(),
set_title(), set_xticks() and set_xticklabels() methods.
Place a legend on the plot.
Place a legend on the plot.
Add multiple labels for bar chart using autolabel() method.
Add multiple labels for bar chart using autolabel() method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # use 3 points offset
textcoords="offset points", # in both directions
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show()
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To plot a bar chart with multiple labels in Matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1223,
"s": 1152,
"text": "Make some data set for men_means, men_std, women_means, and women_std."
},
{
"code": null,
"e": 1294,
"s": 1223,
"text": "Make some data set for men_means, men_std, women_means, and women_std."
},
{
"code": null,
"e": 1330,
"s": 1294,
"text": "Make index data points using numpy."
},
{
"code": null,
"e": 1366,
"s": 1330,
"text": "Make index data points using numpy."
},
{
"code": null,
"e": 1400,
"s": 1366,
"text": "Initialize the width of the bars."
},
{
"code": null,
"e": 1434,
"s": 1400,
"text": "Initialize the width of the bars."
},
{
"code": null,
"e": 1498,
"s": 1434,
"text": "Use subplots() method to create a figure and a set of subplots."
},
{
"code": null,
"e": 1562,
"s": 1498,
"text": "Use subplots() method to create a figure and a set of subplots."
},
{
"code": null,
"e": 1622,
"s": 1562,
"text": "Create rects1 and rects2 bars rectangle using bar() method."
},
{
"code": null,
"e": 1682,
"s": 1622,
"text": "Create rects1 and rects2 bars rectangle using bar() method."
},
{
"code": null,
"e": 1757,
"s": 1682,
"text": "Use set_ylabel(),\nset_title(), set_xticks() and set_xticklabels() methods."
},
{
"code": null,
"e": 1832,
"s": 1757,
"text": "Use set_ylabel(),\nset_title(), set_xticks() and set_xticklabels() methods."
},
{
"code": null,
"e": 1860,
"s": 1832,
"text": "Place a legend on the plot."
},
{
"code": null,
"e": 1888,
"s": 1860,
"text": "Place a legend on the plot."
},
{
"code": null,
"e": 1948,
"s": 1888,
"text": "Add multiple labels for bar chart using autolabel() method."
},
{
"code": null,
"e": 2008,
"s": 1948,
"text": "Add multiple labels for bar chart using autolabel() method."
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2092,
"s": 2050,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 3312,
"s": 2092,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nmen_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)\nwomen_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)\n\nind = np.arange(len(men_means)) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')\nrects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')\n\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(ind)\nax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))\nax.legend()\n\ndef autolabel(rects, xpos='center'):\n ha = {'center': 'center', 'right': 'left', 'left': 'right'}\n offset = {'center': 0, 'right': 1, 'left': -1}\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(offset[xpos]*3, 3), # use 3 points offset\n textcoords=\"offset points\", # in both directions\n ha=ha[xpos], va='bottom')\n\nautolabel(rects1, \"left\")\nautolabel(rects2, \"right\")\nplt.show()"
}
] |
String Buffer and String Builder Classes
|
The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
Unlike Strings, objects of type StringBuffer and String builder can be modified over and over again without leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe (not synchronised).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.
public class Test {
public static void main(String args[]) {
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}
This will produce the following result −
test String Buffer
Here is the list of important methods supported by StringBuffer class −
Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings, etc.
The method reverses the value of the StringBuffer object that invoked the method.
Deletes the string starting from the start index until the end index.
This method inserts a string s at the position mentioned by the offset.
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.
Here is the list of other methods (except set methods) which are very similar to String class −
int capacity()
Returns the current capacity of the String buffer.
char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
int length()
Returns the length (character count) of this string buffer.
void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
void setLength(int newLength)
Sets the length of this String buffer.
CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. The substring begins at the specified index and extends to the end of the StringBuffer.
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.
String toString()
Converts to a string representing the data in this string buffer.
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": 2512,
"s": 2377,
"text": "The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters."
},
{
"code": null,
"e": 2664,
"s": 2512,
"text": "Unlike Strings, objects of type StringBuffer and String builder can be modified over and over again without leaving behind a lot of new unused objects."
},
{
"code": null,
"e": 2854,
"s": 2664,
"text": "The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe (not synchronised)."
},
{
"code": null,
"e": 3036,
"s": 2854,
"text": "It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects."
},
{
"code": null,
"e": 3240,
"s": 3036,
"text": "public class Test {\n\n public static void main(String args[]) {\n StringBuffer sBuffer = new StringBuffer(\"test\");\n sBuffer.append(\" String Buffer\");\n System.out.println(sBuffer); \n }\n}"
},
{
"code": null,
"e": 3281,
"s": 3240,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3301,
"s": 3281,
"text": "test String Buffer\n"
},
{
"code": null,
"e": 3373,
"s": 3301,
"text": "Here is the list of important methods supported by StringBuffer class −"
},
{
"code": null,
"e": 3487,
"s": 3373,
"text": "Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings, etc."
},
{
"code": null,
"e": 3569,
"s": 3487,
"text": "The method reverses the value of the StringBuffer object that invoked the method."
},
{
"code": null,
"e": 3639,
"s": 3569,
"text": "Deletes the string starting from the start index until the end index."
},
{
"code": null,
"e": 3711,
"s": 3639,
"text": "This method inserts a string s at the position mentioned by the offset."
},
{
"code": null,
"e": 3824,
"s": 3711,
"text": "This method replaces the characters in a substring of this StringBuffer with characters in the specified String."
},
{
"code": null,
"e": 3920,
"s": 3824,
"text": "Here is the list of other methods (except set methods) which are very similar to String class −"
},
{
"code": null,
"e": 3935,
"s": 3920,
"text": "int capacity()"
},
{
"code": null,
"e": 3986,
"s": 3935,
"text": "Returns the current capacity of the String buffer."
},
{
"code": null,
"e": 4009,
"s": 3986,
"text": "char charAt(int index)"
},
{
"code": null,
"e": 4142,
"s": 4009,
"text": "The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned."
},
{
"code": null,
"e": 4183,
"s": 4142,
"text": "void ensureCapacity(int minimumCapacity)"
},
{
"code": null,
"e": 4267,
"s": 4183,
"text": "Ensures that the capacity of the buffer is at least equal to the specified minimum."
},
{
"code": null,
"e": 4333,
"s": 4267,
"text": "void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)"
},
{
"code": null,
"e": 4421,
"s": 4333,
"text": "Characters are copied from this string buffer into the destination character array dst."
},
{
"code": null,
"e": 4445,
"s": 4421,
"text": "int indexOf(String str)"
},
{
"code": null,
"e": 4534,
"s": 4445,
"text": "Returns the index within this string of the first occurrence of the specified substring."
},
{
"code": null,
"e": 4573,
"s": 4534,
"text": "int indexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 4695,
"s": 4573,
"text": "Returns the index within this string of the first occurrence of the specified substring, starting at the specified index."
},
{
"code": null,
"e": 4723,
"s": 4695,
"text": "int lastIndexOf(String str)"
},
{
"code": null,
"e": 4816,
"s": 4723,
"text": "Returns the index within this string of the rightmost occurrence of the specified substring."
},
{
"code": null,
"e": 4859,
"s": 4816,
"text": "int lastIndexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 4947,
"s": 4859,
"text": "Returns the index within this string of the last occurrence of the specified substring."
},
{
"code": null,
"e": 4960,
"s": 4947,
"text": "int length()"
},
{
"code": null,
"e": 5020,
"s": 4960,
"text": "Returns the length (character count) of this string buffer."
},
{
"code": null,
"e": 5055,
"s": 5020,
"text": "void setCharAt(int index, char ch)"
},
{
"code": null,
"e": 5128,
"s": 5055,
"text": "The character at the specified index of this string buffer is set to ch."
},
{
"code": null,
"e": 5158,
"s": 5128,
"text": "void setLength(int newLength)"
},
{
"code": null,
"e": 5197,
"s": 5158,
"text": "Sets the length of this String buffer."
},
{
"code": null,
"e": 5242,
"s": 5197,
"text": "CharSequence subSequence(int start, int end)"
},
{
"code": null,
"e": 5315,
"s": 5242,
"text": "Returns a new character sequence that is a subsequence of this sequence."
},
{
"code": null,
"e": 5343,
"s": 5315,
"text": "String substring(int start)"
},
{
"code": null,
"e": 5536,
"s": 5343,
"text": "Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. The substring begins at the specified index and extends to the end of the StringBuffer."
},
{
"code": null,
"e": 5573,
"s": 5536,
"text": "String substring(int start, int end)"
},
{
"code": null,
"e": 5678,
"s": 5573,
"text": "Returns a new String that contains a subsequence of characters currently contained in this StringBuffer."
},
{
"code": null,
"e": 5696,
"s": 5678,
"text": "String toString()"
},
{
"code": null,
"e": 5762,
"s": 5696,
"text": "Converts to a string representing the data in this string buffer."
},
{
"code": null,
"e": 5795,
"s": 5762,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5811,
"s": 5795,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5844,
"s": 5811,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5860,
"s": 5844,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5895,
"s": 5860,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5909,
"s": 5895,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5943,
"s": 5909,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5957,
"s": 5943,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5994,
"s": 5957,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6009,
"s": 5994,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6042,
"s": 6009,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6061,
"s": 6042,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6068,
"s": 6061,
"text": " Print"
},
{
"code": null,
"e": 6079,
"s": 6068,
"text": " Add Notes"
}
] |
Check the quality of your code with Pylint | by Amanda Iglesias Moreno | Towards Data Science
|
Pylint is a quality checker for Python programming language that follows the style recommended by PEP 8. This document provides guidelines to write clear code in Python with the main goal of improving readability and consistency of the code. Code is read much more often than is written that is why is so important to stick to conventions that will help us or other people to understand more easily the available code. In this article, we explain 10 rules of PEP 8 that can make your Python code easier for others to read and how we can check them with Pylint. Let’s get started! 💪
Pylint is a third party library that is not available by default in Python. Since Pylint is not part of the Python Standard Library, we need to install it separately. This can easily be achieved by using the pip package. Pip is a standard package manager for Python, allowing to install and manage packages that are not included in the Python Standard Library. To check if pip is installed, you can execute the following command in your Windows Terminal:
pip --version
As shown above, the version 10.0.1 is already available in our system. Now, we can install pylint, running in the command prompt:
pip install pylint
All dependencies required for pylint are also installed. Notice that pip downloads the most recent version of the package.
Once we have installed pylint, we can easily use it by running the command pylint with the name of the file as follows:
pylint filename.py
Now! We are ready to see some code examples💪. In this article, we will explain in detail 10 coding conventions while coding in Python. In addition, we will prove how pylint can detect them.
PEP 8 is a style guide that defines how your python code should be formatted to maximize its readability. In this post, we will only cover some key points; therefore, if you want to study the topic in greater detail, I recommend you take a look at the guide.
www.python.org
In Python, we use implicit continuation line inside parethesis (()), brackets ([]),and braces ({}). Implicit means that we do not write the line continuation character (\) to indicate that we extend a statement over multiple lines.
When using implicit continuation lines, the wrapped element should be aligned vertically, or using hanging indentation. In the context of Python, hanging indentation means that the opening parenthesis of a parenthesized statement is the last non-whitespace character of the line, with subsequent lines being indented until the closing parenthesis.
Arguments inside the parenthesis are not aligned vertically, or using hanging indentation.
Pylint detects a wrong indentation.
Arguments inside the parenthesis are aligned vertically.
Arguments inside the parenthesis are aligned using hanging indentation.
Always surround these operators with a single space on either side:
Assignment (=)
Augmented assignment (+=, -=, etc)
Comparison operators (<, >, <=, >=, ==, !=)
Logical operators (and, or, not)
Membership operators (in, not in)
Identity operators (is, not is)
Operators are not surrounded by spaces.
We can easily disabled a warning in pylint adding a comment at the top of the code as shown above (#pylint: disable=C0114)
The C0114 warning indicates that a module docstring is missing. A docstring is a string that occurs as the first statement in a module, function, class, or method definition. According to PEP 257 (guide containing docstring conventions), all modules should have a docstring at the beginning, describing what the module does.
In this article, we are not going to add a docstring at the top of each module for simplicity. However, it is highly recommended to write doctrings in practice. As before, if you want to know more about how to use doctrings in Python, I recommend you take a closer look at PEP 257 guidelines.
www.python.org
As shown below, pylint detects that the comparison operator < should be surrounded with a single space on either side.
However, pylint does not detect that the membership operator in the if statement should be surrounded by spaces as well. Pylint is not perfect! 😢
Operators are surrounded with a single space on either side.
After a comma, semicolon, or colon, we have to use a whitespace. However, PEP 8 recommends to avoid them immediately before.
In the following code, we can observe the following bad practices:
A whitespace is missing after the comma that separates each element of the list.A whitespace is missing after the colon (:) that separates each key-value pair in the dictionary.A whitespace is present immediately before the comma that separates each element of the tuple.
A whitespace is missing after the comma that separates each element of the list.
A whitespace is missing after the colon (:) that separates each key-value pair in the dictionary.
A whitespace is present immediately before the comma that separates each element of the tuple.
As shown above, pylint detects that a whitespace is required after each comma that separates the elements of the list (numbers). In addition, pylint detects that there is an space before the comma in the tuple (coordinates). However, it fails to detect the missing space after the colon that separates each key-value pair.
I would like to clarify that PEP8 guideline does not mention that a whitespace is required after a comma, colon, or semicolon. However, it is a widespread practice detected by most style checkers as pylint.
There are spaces after, but not before, each comma, colon, and semicolon.
Whitespaces are used immediately inside parentheses, brackets, or braces.
Pylint detects that no spaces are allowed before and after parentheses, brackets, or braces.
No whitespaces are used immediately inside parentheses, brackets, or braces.
An argument is a value passed to a function when calling it. Python functions accept two types of arguments: (1) positional arguments, and (2) keyword arguments. When calling a function using positional arguments, the arguments must be included in the proper order. On the contrary, the keyword arguments can be provided in an arbitrary order, since these arguments are preceded by an identifier (keyword=value). According to PEP8, we do not have to use spaces around the = sign when calling a function using keyword arguments.
Function arguments can have default values. In case the argument is not provided when calling a function, the argument takes its default value. As before, spaces are not used around the = sign when defining default arguments.
Spaces are used around the = sign when using keyword and default arguments.
Pylint detects that spaces are not allowed around keyword arguments.
Spaces are not employed around the = sign.
Error messages in Python can be separated into two types: syntax errors and exceptions. Syntax errors occur when Python can not interpret the code, indicating that something is wrong with the syntax of the program. On the other hand, exceptions occur when unexpected things happen during the execution of the code.
In the following block code, Python provides a message indicating we ran into a TypeError when trying to convert a string to a hexadecimal number, since the hex function expects an integer as input.
To handle exceptions in Python, we use the try and except statements. The try clause contains the operation that can raise an exception, and the except clause includes the code that handles the exception. The try clause is executed statement by statement. However, if an exception occurs, the execution of the try statement stops, and then the except statement is executed.
Here, the code in the except block is executed when any kind of exception occurs during the execution of the try block. According to PEP8 guidelines, it is not recommended to use bare except clauses, since they will catch all exceptions, including SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C.
Pylint detects that a bare except clause is used.
We should specify which error we want to handle in the except block as follows:
Now, the program catches the TypeError exception, but not other exceptions.
In if statements, it is not correct to compare boolean variables to True or False using == or is.
Pylint detect that the comparison to True should be just the expression (is_raining).
We have to use the boolean variable directly in the if statement as follows:
It is a bad practice to use string slicing to check for prefixes or suffixes.
However, pylint does not detect this style problem, although it is contained in PEP 8 guide.
According to the style guide PEP8, we have to use str.startswith() and str.endswith() to check for prefixes or suffixes.
The str.startswith(prefix, start, end) function checks whether a string starts with a given prefix. The function returns True if the string starts with the specified prefix; otherwise, returns False. Start and end are optional parameters to specify the index from where the check begins and ends.
The str.endswith(suffix, start, end) function returns True if the string (str) ends with a specified suffix. If not, it returns False. As before, the function has two optional parameters start and end to specify the indexes from where the test starts and ends.
A module is a file consisting of Python code. If you are working on big projects, it makes sense to organize your code into multiple files, and import them into other Python files when necessary. To import a Python module, we just type the statement import followed by the name of the file. Besides importing our own modules, we can also import built-in modules available in the python standard library as well as in third-party libraries. According to PEP8 guidelines, imports are written at the top of the Python script, each one on a separated line. In addition, imports should be grouped in the following order:
Standard library importsThird-party importsLocal scripts imports
Standard library imports
Third-party imports
Local scripts imports
Imports are not written in separated lines, and are not grouped in the correct order.
Pylint detects that the modules pandas and matplotlib are not written on separated lines. In addition, Pylint detects that the Python standard library module (csv) should be placed before the third-party imports (pandas and matplotlib). As we can observe below, Pylint also recognizes that all imports are unused, since, for simplicity, we did not add more code.
Imports are written in separated lines, and are grouped in the correct order.
Lambda expressions are anonymous short-term functions with the following syntax:
lambda arguments: expression
These functions can have multiple arguments, returning the value provided by expression. We can find them not only in Python; other programming languages support lambda functions as well.
According to PEP8 guidelines, it is not recommended to assign a lambda function directly to an identifier. In this case, it is advisable to use regular functions (defined with def keyword).
A lambda expression is assigned directly to an identifier (multiply).
Pylint does not detect this problem, although it is contained in PEP 8 guide.
We create the function with the def keyword.
Pylint is not perfect, but it can really help to improve the quality of your code! Remember that code is read much more often than is written that is why is so important to stick to conventions that will help others to understand your code. In addition, a clear code shows professionalism 😉. That’s why I encourage you to use quality checkers such as Pylint (there are plenty more!) to check your code. It will look more clear and professional 👌
|
[
{
"code": null,
"e": 754,
"s": 172,
"text": "Pylint is a quality checker for Python programming language that follows the style recommended by PEP 8. This document provides guidelines to write clear code in Python with the main goal of improving readability and consistency of the code. Code is read much more often than is written that is why is so important to stick to conventions that will help us or other people to understand more easily the available code. In this article, we explain 10 rules of PEP 8 that can make your Python code easier for others to read and how we can check them with Pylint. Let’s get started! 💪"
},
{
"code": null,
"e": 1209,
"s": 754,
"text": "Pylint is a third party library that is not available by default in Python. Since Pylint is not part of the Python Standard Library, we need to install it separately. This can easily be achieved by using the pip package. Pip is a standard package manager for Python, allowing to install and manage packages that are not included in the Python Standard Library. To check if pip is installed, you can execute the following command in your Windows Terminal:"
},
{
"code": null,
"e": 1223,
"s": 1209,
"text": "pip --version"
},
{
"code": null,
"e": 1353,
"s": 1223,
"text": "As shown above, the version 10.0.1 is already available in our system. Now, we can install pylint, running in the command prompt:"
},
{
"code": null,
"e": 1372,
"s": 1353,
"text": "pip install pylint"
},
{
"code": null,
"e": 1495,
"s": 1372,
"text": "All dependencies required for pylint are also installed. Notice that pip downloads the most recent version of the package."
},
{
"code": null,
"e": 1615,
"s": 1495,
"text": "Once we have installed pylint, we can easily use it by running the command pylint with the name of the file as follows:"
},
{
"code": null,
"e": 1634,
"s": 1615,
"text": "pylint filename.py"
},
{
"code": null,
"e": 1824,
"s": 1634,
"text": "Now! We are ready to see some code examples💪. In this article, we will explain in detail 10 coding conventions while coding in Python. In addition, we will prove how pylint can detect them."
},
{
"code": null,
"e": 2083,
"s": 1824,
"text": "PEP 8 is a style guide that defines how your python code should be formatted to maximize its readability. In this post, we will only cover some key points; therefore, if you want to study the topic in greater detail, I recommend you take a look at the guide."
},
{
"code": null,
"e": 2098,
"s": 2083,
"text": "www.python.org"
},
{
"code": null,
"e": 2330,
"s": 2098,
"text": "In Python, we use implicit continuation line inside parethesis (()), brackets ([]),and braces ({}). Implicit means that we do not write the line continuation character (\\) to indicate that we extend a statement over multiple lines."
},
{
"code": null,
"e": 2678,
"s": 2330,
"text": "When using implicit continuation lines, the wrapped element should be aligned vertically, or using hanging indentation. In the context of Python, hanging indentation means that the opening parenthesis of a parenthesized statement is the last non-whitespace character of the line, with subsequent lines being indented until the closing parenthesis."
},
{
"code": null,
"e": 2769,
"s": 2678,
"text": "Arguments inside the parenthesis are not aligned vertically, or using hanging indentation."
},
{
"code": null,
"e": 2805,
"s": 2769,
"text": "Pylint detects a wrong indentation."
},
{
"code": null,
"e": 2862,
"s": 2805,
"text": "Arguments inside the parenthesis are aligned vertically."
},
{
"code": null,
"e": 2934,
"s": 2862,
"text": "Arguments inside the parenthesis are aligned using hanging indentation."
},
{
"code": null,
"e": 3002,
"s": 2934,
"text": "Always surround these operators with a single space on either side:"
},
{
"code": null,
"e": 3017,
"s": 3002,
"text": "Assignment (=)"
},
{
"code": null,
"e": 3052,
"s": 3017,
"text": "Augmented assignment (+=, -=, etc)"
},
{
"code": null,
"e": 3096,
"s": 3052,
"text": "Comparison operators (<, >, <=, >=, ==, !=)"
},
{
"code": null,
"e": 3129,
"s": 3096,
"text": "Logical operators (and, or, not)"
},
{
"code": null,
"e": 3163,
"s": 3129,
"text": "Membership operators (in, not in)"
},
{
"code": null,
"e": 3195,
"s": 3163,
"text": "Identity operators (is, not is)"
},
{
"code": null,
"e": 3235,
"s": 3195,
"text": "Operators are not surrounded by spaces."
},
{
"code": null,
"e": 3358,
"s": 3235,
"text": "We can easily disabled a warning in pylint adding a comment at the top of the code as shown above (#pylint: disable=C0114)"
},
{
"code": null,
"e": 3683,
"s": 3358,
"text": "The C0114 warning indicates that a module docstring is missing. A docstring is a string that occurs as the first statement in a module, function, class, or method definition. According to PEP 257 (guide containing docstring conventions), all modules should have a docstring at the beginning, describing what the module does."
},
{
"code": null,
"e": 3976,
"s": 3683,
"text": "In this article, we are not going to add a docstring at the top of each module for simplicity. However, it is highly recommended to write doctrings in practice. As before, if you want to know more about how to use doctrings in Python, I recommend you take a closer look at PEP 257 guidelines."
},
{
"code": null,
"e": 3991,
"s": 3976,
"text": "www.python.org"
},
{
"code": null,
"e": 4110,
"s": 3991,
"text": "As shown below, pylint detects that the comparison operator < should be surrounded with a single space on either side."
},
{
"code": null,
"e": 4256,
"s": 4110,
"text": "However, pylint does not detect that the membership operator in the if statement should be surrounded by spaces as well. Pylint is not perfect! 😢"
},
{
"code": null,
"e": 4317,
"s": 4256,
"text": "Operators are surrounded with a single space on either side."
},
{
"code": null,
"e": 4442,
"s": 4317,
"text": "After a comma, semicolon, or colon, we have to use a whitespace. However, PEP 8 recommends to avoid them immediately before."
},
{
"code": null,
"e": 4509,
"s": 4442,
"text": "In the following code, we can observe the following bad practices:"
},
{
"code": null,
"e": 4781,
"s": 4509,
"text": "A whitespace is missing after the comma that separates each element of the list.A whitespace is missing after the colon (:) that separates each key-value pair in the dictionary.A whitespace is present immediately before the comma that separates each element of the tuple."
},
{
"code": null,
"e": 4862,
"s": 4781,
"text": "A whitespace is missing after the comma that separates each element of the list."
},
{
"code": null,
"e": 4960,
"s": 4862,
"text": "A whitespace is missing after the colon (:) that separates each key-value pair in the dictionary."
},
{
"code": null,
"e": 5055,
"s": 4960,
"text": "A whitespace is present immediately before the comma that separates each element of the tuple."
},
{
"code": null,
"e": 5378,
"s": 5055,
"text": "As shown above, pylint detects that a whitespace is required after each comma that separates the elements of the list (numbers). In addition, pylint detects that there is an space before the comma in the tuple (coordinates). However, it fails to detect the missing space after the colon that separates each key-value pair."
},
{
"code": null,
"e": 5585,
"s": 5378,
"text": "I would like to clarify that PEP8 guideline does not mention that a whitespace is required after a comma, colon, or semicolon. However, it is a widespread practice detected by most style checkers as pylint."
},
{
"code": null,
"e": 5659,
"s": 5585,
"text": "There are spaces after, but not before, each comma, colon, and semicolon."
},
{
"code": null,
"e": 5733,
"s": 5659,
"text": "Whitespaces are used immediately inside parentheses, brackets, or braces."
},
{
"code": null,
"e": 5826,
"s": 5733,
"text": "Pylint detects that no spaces are allowed before and after parentheses, brackets, or braces."
},
{
"code": null,
"e": 5903,
"s": 5826,
"text": "No whitespaces are used immediately inside parentheses, brackets, or braces."
},
{
"code": null,
"e": 6431,
"s": 5903,
"text": "An argument is a value passed to a function when calling it. Python functions accept two types of arguments: (1) positional arguments, and (2) keyword arguments. When calling a function using positional arguments, the arguments must be included in the proper order. On the contrary, the keyword arguments can be provided in an arbitrary order, since these arguments are preceded by an identifier (keyword=value). According to PEP8, we do not have to use spaces around the = sign when calling a function using keyword arguments."
},
{
"code": null,
"e": 6657,
"s": 6431,
"text": "Function arguments can have default values. In case the argument is not provided when calling a function, the argument takes its default value. As before, spaces are not used around the = sign when defining default arguments."
},
{
"code": null,
"e": 6733,
"s": 6657,
"text": "Spaces are used around the = sign when using keyword and default arguments."
},
{
"code": null,
"e": 6802,
"s": 6733,
"text": "Pylint detects that spaces are not allowed around keyword arguments."
},
{
"code": null,
"e": 6845,
"s": 6802,
"text": "Spaces are not employed around the = sign."
},
{
"code": null,
"e": 7160,
"s": 6845,
"text": "Error messages in Python can be separated into two types: syntax errors and exceptions. Syntax errors occur when Python can not interpret the code, indicating that something is wrong with the syntax of the program. On the other hand, exceptions occur when unexpected things happen during the execution of the code."
},
{
"code": null,
"e": 7359,
"s": 7160,
"text": "In the following block code, Python provides a message indicating we ran into a TypeError when trying to convert a string to a hexadecimal number, since the hex function expects an integer as input."
},
{
"code": null,
"e": 7733,
"s": 7359,
"text": "To handle exceptions in Python, we use the try and except statements. The try clause contains the operation that can raise an exception, and the except clause includes the code that handles the exception. The try clause is executed statement by statement. However, if an exception occurs, the execution of the try statement stops, and then the except statement is executed."
},
{
"code": null,
"e": 8082,
"s": 7733,
"text": "Here, the code in the except block is executed when any kind of exception occurs during the execution of the try block. According to PEP8 guidelines, it is not recommended to use bare except clauses, since they will catch all exceptions, including SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C."
},
{
"code": null,
"e": 8132,
"s": 8082,
"text": "Pylint detects that a bare except clause is used."
},
{
"code": null,
"e": 8212,
"s": 8132,
"text": "We should specify which error we want to handle in the except block as follows:"
},
{
"code": null,
"e": 8288,
"s": 8212,
"text": "Now, the program catches the TypeError exception, but not other exceptions."
},
{
"code": null,
"e": 8386,
"s": 8288,
"text": "In if statements, it is not correct to compare boolean variables to True or False using == or is."
},
{
"code": null,
"e": 8472,
"s": 8386,
"text": "Pylint detect that the comparison to True should be just the expression (is_raining)."
},
{
"code": null,
"e": 8549,
"s": 8472,
"text": "We have to use the boolean variable directly in the if statement as follows:"
},
{
"code": null,
"e": 8627,
"s": 8549,
"text": "It is a bad practice to use string slicing to check for prefixes or suffixes."
},
{
"code": null,
"e": 8720,
"s": 8627,
"text": "However, pylint does not detect this style problem, although it is contained in PEP 8 guide."
},
{
"code": null,
"e": 8841,
"s": 8720,
"text": "According to the style guide PEP8, we have to use str.startswith() and str.endswith() to check for prefixes or suffixes."
},
{
"code": null,
"e": 9138,
"s": 8841,
"text": "The str.startswith(prefix, start, end) function checks whether a string starts with a given prefix. The function returns True if the string starts with the specified prefix; otherwise, returns False. Start and end are optional parameters to specify the index from where the check begins and ends."
},
{
"code": null,
"e": 9399,
"s": 9138,
"text": "The str.endswith(suffix, start, end) function returns True if the string (str) ends with a specified suffix. If not, it returns False. As before, the function has two optional parameters start and end to specify the indexes from where the test starts and ends."
},
{
"code": null,
"e": 10015,
"s": 9399,
"text": "A module is a file consisting of Python code. If you are working on big projects, it makes sense to organize your code into multiple files, and import them into other Python files when necessary. To import a Python module, we just type the statement import followed by the name of the file. Besides importing our own modules, we can also import built-in modules available in the python standard library as well as in third-party libraries. According to PEP8 guidelines, imports are written at the top of the Python script, each one on a separated line. In addition, imports should be grouped in the following order:"
},
{
"code": null,
"e": 10080,
"s": 10015,
"text": "Standard library importsThird-party importsLocal scripts imports"
},
{
"code": null,
"e": 10105,
"s": 10080,
"text": "Standard library imports"
},
{
"code": null,
"e": 10125,
"s": 10105,
"text": "Third-party imports"
},
{
"code": null,
"e": 10147,
"s": 10125,
"text": "Local scripts imports"
},
{
"code": null,
"e": 10233,
"s": 10147,
"text": "Imports are not written in separated lines, and are not grouped in the correct order."
},
{
"code": null,
"e": 10596,
"s": 10233,
"text": "Pylint detects that the modules pandas and matplotlib are not written on separated lines. In addition, Pylint detects that the Python standard library module (csv) should be placed before the third-party imports (pandas and matplotlib). As we can observe below, Pylint also recognizes that all imports are unused, since, for simplicity, we did not add more code."
},
{
"code": null,
"e": 10674,
"s": 10596,
"text": "Imports are written in separated lines, and are grouped in the correct order."
},
{
"code": null,
"e": 10755,
"s": 10674,
"text": "Lambda expressions are anonymous short-term functions with the following syntax:"
},
{
"code": null,
"e": 10784,
"s": 10755,
"text": "lambda arguments: expression"
},
{
"code": null,
"e": 10972,
"s": 10784,
"text": "These functions can have multiple arguments, returning the value provided by expression. We can find them not only in Python; other programming languages support lambda functions as well."
},
{
"code": null,
"e": 11162,
"s": 10972,
"text": "According to PEP8 guidelines, it is not recommended to assign a lambda function directly to an identifier. In this case, it is advisable to use regular functions (defined with def keyword)."
},
{
"code": null,
"e": 11232,
"s": 11162,
"text": "A lambda expression is assigned directly to an identifier (multiply)."
},
{
"code": null,
"e": 11310,
"s": 11232,
"text": "Pylint does not detect this problem, although it is contained in PEP 8 guide."
},
{
"code": null,
"e": 11355,
"s": 11310,
"text": "We create the function with the def keyword."
}
] |
What is the difference between $(window).load() and $(document).ready() functions in jQuery?
|
Both the methods are used in jQuery. Let’s see what purpose they fulfill.
$(window).load()
The code which gets included inside $( window ).on( "load", function() { ... }) runs only once the entire page is ready (not only DOM).
Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.
$(document).ready()
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $( document ).ready() method will run once the page DOM is ready to execute JavaScript code.
You can try to run the following code to learn how to use to use $(document).ready() in jQuery:
Live Demo
<html>
<head>
<title>jQuery Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {
alert("Hi!");
});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
You can try to run the following code to learn how to use $(window).load() in jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("Image successfully loaded.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor Connect" width="310" height="220">
<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "Both the methods are used in jQuery. Let’s see what purpose they fulfill."
},
{
"code": null,
"e": 1153,
"s": 1136,
"text": "$(window).load()"
},
{
"code": null,
"e": 1289,
"s": 1153,
"text": "The code which gets included inside $( window ).on( \"load\", function() { ... }) runs only once the entire page is ready (not only DOM)."
},
{
"code": null,
"e": 1448,
"s": 1289,
"text": "Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0."
},
{
"code": null,
"e": 1468,
"s": 1448,
"text": "$(document).ready()"
},
{
"code": null,
"e": 1682,
"s": 1468,
"text": "The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $( document ).ready() method will run once the page DOM is ready to execute JavaScript code."
},
{
"code": null,
"e": 1778,
"s": 1682,
"text": "You can try to run the following code to learn how to use to use $(document).ready() in jQuery:"
},
{
"code": null,
"e": 1788,
"s": 1778,
"text": "Live Demo"
},
{
"code": null,
"e": 2235,
"s": 1788,
"text": "<html>\n\n <head>\n <title>jQuery Function</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n\n <script>\n $(document).ready(function() {\n $(\"div\").click(function() {\n alert(\"Hi!\");\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"mydiv\">\n Click on this to see a dialogue box.\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 2321,
"s": 2235,
"text": "You can try to run the following code to learn how to use $(window).load() in jQuery:"
},
{
"code": null,
"e": 2331,
"s": 2321,
"text": "Live Demo"
},
{
"code": null,
"e": 2904,
"s": 2331,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"img\").load(function(){\n alert(\"Image successfully loaded.\");\n });\n});\n</script>\n</head>\n<body>\n\n<img src=\"/videotutorials/images/tutor_connect_home.jpg\" alt=\"Tutor Connect\" width=\"310\" height=\"220\">\n\n<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>\n\n</body>\n</html>"
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 51 - GeeksforGeeks
|
28 Jun, 2021
Let R be a relation on the set of ordered pairs of positive integers such that ((p, q), (r, s)) ∈ R if and only if p–s = q–r. Which one of the following is true about R?(A) Both reflexive and symmetric(B) Reflexive but not symmetric(C) Not reflexive but symmetric(D) Neither reflexive nor symmetricAnswer: (C)Explanation:
((p, q), (r, s)) ∈ R if and only if p–s = q–r
(p, q) is not related to (p, q)
as p-q is not same as q-p.
The relation is symmetric because if p–s = q–r, then s-q = s-p.
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25959,
"s": 25931,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26281,
"s": 25959,
"text": "Let R be a relation on the set of ordered pairs of positive integers such that ((p, q), (r, s)) ∈ R if and only if p–s = q–r. Which one of the following is true about R?(A) Both reflexive and symmetric(B) Reflexive but not symmetric(C) Not reflexive but symmetric(D) Neither reflexive nor symmetricAnswer: (C)Explanation:"
},
{
"code": null,
"e": 26454,
"s": 26281,
"text": "((p, q), (r, s)) ∈ R if and only if p–s = q–r\n\n(p, q) is not related to (p, q)\n\nas p-q is not same as q-p.\n\nThe relation is symmetric because if p–s = q–r, then s-q = s-p. "
},
{
"code": null,
"e": 26476,
"s": 26454,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26497,
"s": 26476,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 26523,
"s": 26497,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 26528,
"s": 26523,
"text": "GATE"
},
{
"code": null,
"e": 26626,
"s": 26528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26660,
"s": 26626,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26694,
"s": 26660,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26728,
"s": 26694,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26761,
"s": 26728,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26797,
"s": 26761,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26831,
"s": 26797,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26867,
"s": 26831,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26901,
"s": 26867,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26935,
"s": 26901,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
C++ | Operator Overloading | Question 4 - GeeksforGeeks
|
28 Jun, 2021
Which of the following operators should be preferred to overload as a global function rather than a member method?(A) Postfix ++(B) Comparison Operator(C) Insertion Operator <<(D) Prefix++Answer: (C)Explanation: cout is an object of ostream class which is a compiler defined class.
When we do “cout << obj" where obj is an object of our class, the compiler first looks for an operator function in ostream, then it looks for a global function.One way to overload insertion operator is to modify ostream class which may not be a good idea. So we make a global method. Following is an example.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(int r = 0, int i =0)
{
real = r;
imag = i;
}
friend ostream & operator << (ostream &out, const Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag;
return out;
}
int main()
{
Complex c1(10, 15);
cout << c1;
return 0;
}
Quiz of this Question
C++-Operator Overloading
Operator Overloading
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
fork() in C
std::string class in C++
C++ | new and delete | Question 4
C++ | new and delete | Question 1
C++ | Inheritance | Question 3
C++ | References | Question 4
C++ | Inheritance | Question 7
|
[
{
"code": null,
"e": 26113,
"s": 26085,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26395,
"s": 26113,
"text": "Which of the following operators should be preferred to overload as a global function rather than a member method?(A) Postfix ++(B) Comparison Operator(C) Insertion Operator <<(D) Prefix++Answer: (C)Explanation: cout is an object of ostream class which is a compiler defined class."
},
{
"code": null,
"e": 26704,
"s": 26395,
"text": "When we do “cout << obj\" where obj is an object of our class, the compiler first looks for an operator function in ostream, then it looks for a global function.One way to overload insertion operator is to modify ostream class which may not be a good idea. So we make a global method. Following is an example."
},
{
"code": null,
"e": 27151,
"s": 26704,
"text": "#include <iostream>\nusing namespace std;\n\nclass Complex\n{\nprivate:\n int real;\n int imag;\npublic:\n Complex(int r = 0, int i =0)\n {\n real = r;\n imag = i;\n }\n friend ostream & operator << (ostream &out, const Complex &c);\n};\n\nostream & operator << (ostream &out, const Complex &c)\n{\n out << c.real;\n out << \"+i\" << c.imag;\n return out;\n}\n\nint main()\n{\n Complex c1(10, 15);\n cout << c1;\n return 0;\n}\n"
},
{
"code": null,
"e": 27173,
"s": 27151,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 27198,
"s": 27173,
"text": "C++-Operator Overloading"
},
{
"code": null,
"e": 27219,
"s": 27198,
"text": "Operator Overloading"
},
{
"code": null,
"e": 27230,
"s": 27219,
"text": "C Language"
},
{
"code": null,
"e": 27239,
"s": 27230,
"text": "C++ Quiz"
},
{
"code": null,
"e": 27337,
"s": 27239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27359,
"s": 27337,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27387,
"s": 27359,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27404,
"s": 27387,
"text": "Substring in C++"
},
{
"code": null,
"e": 27416,
"s": 27404,
"text": "fork() in C"
},
{
"code": null,
"e": 27441,
"s": 27416,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27475,
"s": 27441,
"text": "C++ | new and delete | Question 4"
},
{
"code": null,
"e": 27509,
"s": 27475,
"text": "C++ | new and delete | Question 1"
},
{
"code": null,
"e": 27540,
"s": 27509,
"text": "C++ | Inheritance | Question 3"
},
{
"code": null,
"e": 27570,
"s": 27540,
"text": "C++ | References | Question 4"
}
] |
Output of C++ Program | Set 3
|
24 Sep, 2021
Predict the output of below C++ programs.Question 1
C++
#include<iostream> using namespace std;class P {public: void print() { cout <<" Inside P::"; }}; class Q : public P {public: void print() { cout <<" Inside Q"; }}; class R: public Q {}; int main(void){ R r; r.print(); return 0;}
Output: Inside Q
The print function is not defined in class R. So it is looked up in the inheritance hierarchy. print() is present in both classes P and Q, which of them should be called? The idea is, if there is multilevel inheritance, then function is linearly searched up in the inheritance hierarchy until a matching function is found.
Question 2
C++
#include<iostream>#include<stdio.h> using namespace std; class Base{public: Base() { fun(); //note: fun() is virtual } virtual void fun() { cout<<"\nBase Function"; }}; class Derived: public Base{public: Derived(){} virtual void fun() { cout<<"\nDerived Function"; }}; int main(){ Base* pBase = new Derived(); delete pBase; return 0;}
Output: Base Function
See following excerpt from C++ standard for explanation.
When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object.
Because of this difference in behavior, it is recommended that object’s virtual function is not invoked while it is being constructed or destroyed. See this for more details.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
sagartomar9927
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 106,
"s": 54,
"text": "Predict the output of below C++ programs.Question 1"
},
{
"code": null,
"e": 110,
"s": 106,
"text": "C++"
},
{
"code": "#include<iostream> using namespace std;class P {public: void print() { cout <<\" Inside P::\"; }}; class Q : public P {public: void print() { cout <<\" Inside Q\"; }}; class R: public Q {}; int main(void){ R r; r.print(); return 0;}",
"e": 351,
"s": 110,
"text": null
},
{
"code": null,
"e": 368,
"s": 351,
"text": "Output: Inside Q"
},
{
"code": null,
"e": 691,
"s": 368,
"text": "The print function is not defined in class R. So it is looked up in the inheritance hierarchy. print() is present in both classes P and Q, which of them should be called? The idea is, if there is multilevel inheritance, then function is linearly searched up in the inheritance hierarchy until a matching function is found."
},
{
"code": null,
"e": 703,
"s": 691,
"text": "Question 2 "
},
{
"code": null,
"e": 707,
"s": 703,
"text": "C++"
},
{
"code": "#include<iostream>#include<stdio.h> using namespace std; class Base{public: Base() { fun(); //note: fun() is virtual } virtual void fun() { cout<<\"\\nBase Function\"; }}; class Derived: public Base{public: Derived(){} virtual void fun() { cout<<\"\\nDerived Function\"; }}; int main(){ Base* pBase = new Derived(); delete pBase; return 0;}",
"e": 1064,
"s": 707,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1064,
"text": "Output: Base Function"
},
{
"code": null,
"e": 1143,
"s": 1086,
"text": "See following excerpt from C++ standard for explanation."
},
{
"code": null,
"e": 1668,
"s": 1143,
"text": "When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object."
},
{
"code": null,
"e": 1992,
"s": 1668,
"text": "Because of this difference in behavior, it is recommended that object’s virtual function is not invoked while it is being constructed or destroyed. See this for more details.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. "
},
{
"code": null,
"e": 2007,
"s": 1992,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2018,
"s": 2007,
"text": "CPP-Output"
},
{
"code": null,
"e": 2033,
"s": 2018,
"text": "Program Output"
}
] |
ReactJS Pure Components
|
07 Aug, 2020
Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to customize the default behavior and implement it when the React component should re-render or update itself.
Prerequisite:
ReactJS Components
ReactJS Components – Set 2
Now, ReactJS has provided us a Pure Component. If we extend a class with Pure Component, there is no need for shouldComponentUpdate() Lifecycle Method. ReactJS Pure Component Class compares current state and props with new props and states to decide whether the React component should re-render itself or Not.
In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself. Since Pure Components restricts the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends React.PureComponent.
Example: Program to demonstrate the creation of Pure Components.
javascript
import React from ‘react’; export default class Test extends React.PureComponent{ render(){ return <h1>Welcome to GeeksforGeeks</h1>; }}
Output :
Extending React Class Components with Pure Components ensures the higher performance of the Component and ultimately makes your application faster, While in the case of Regular Component, it will always re-render either value of State and Props changes or not.
While using Pure Components, Things to be noted are that, In these components, the Value of State and Props are Shallow Compared (Shallow Comparison) and It also takes care of “shouldComponentUpdate” Lifecycle method implicitly.So there is a possibility that if these State and Props Objects contain nested data structure then Pure Component’s implemented shouldComponentUpdate will return false and will not update the whole subtree of Children of this Class Component. So in Pure Component, the nested data structure doesn’t work properly.
In this case, State and Props Objects should be simple objects and Child Elements should also be Pure, means to return the same output for the same input values at any instance.
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 236,
"s": 54,
"text": "Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to customize the default behavior and implement it when the React component should re-render or update itself."
},
{
"code": null,
"e": 251,
"s": 236,
"text": "Prerequisite: "
},
{
"code": null,
"e": 270,
"s": 251,
"text": "ReactJS Components"
},
{
"code": null,
"e": 297,
"s": 270,
"text": "ReactJS Components – Set 2"
},
{
"code": null,
"e": 608,
"s": 297,
"text": "Now, ReactJS has provided us a Pure Component. If we extend a class with Pure Component, there is no need for shouldComponentUpdate() Lifecycle Method. ReactJS Pure Component Class compares current state and props with new props and states to decide whether the React component should re-render itself or Not."
},
{
"code": null,
"e": 932,
"s": 608,
"text": "In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself. Since Pure Components restricts the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends React.PureComponent. "
},
{
"code": null,
"e": 999,
"s": 932,
"text": "Example: Program to demonstrate the creation of Pure Components. "
},
{
"code": null,
"e": 1010,
"s": 999,
"text": "javascript"
},
{
"code": "import React from ‘react’; export default class Test extends React.PureComponent{ render(){ return <h1>Welcome to GeeksforGeeks</h1>; }}",
"e": 1157,
"s": 1010,
"text": null
},
{
"code": null,
"e": 1166,
"s": 1157,
"text": "Output :"
},
{
"code": null,
"e": 1427,
"s": 1166,
"text": "Extending React Class Components with Pure Components ensures the higher performance of the Component and ultimately makes your application faster, While in the case of Regular Component, it will always re-render either value of State and Props changes or not."
},
{
"code": null,
"e": 1969,
"s": 1427,
"text": "While using Pure Components, Things to be noted are that, In these components, the Value of State and Props are Shallow Compared (Shallow Comparison) and It also takes care of “shouldComponentUpdate” Lifecycle method implicitly.So there is a possibility that if these State and Props Objects contain nested data structure then Pure Component’s implemented shouldComponentUpdate will return false and will not update the whole subtree of Children of this Class Component. So in Pure Component, the nested data structure doesn’t work properly."
},
{
"code": null,
"e": 2147,
"s": 1969,
"text": "In this case, State and Props Objects should be simple objects and Child Elements should also be Pure, means to return the same output for the same input values at any instance."
},
{
"code": null,
"e": 2156,
"s": 2147,
"text": "react-js"
},
{
"code": null,
"e": 2167,
"s": 2156,
"text": "JavaScript"
},
{
"code": null,
"e": 2184,
"s": 2167,
"text": "Web Technologies"
}
] |
Number of arrays of size N whose elements are positive integers and sum is K
|
05 May, 2021
Given two positive integers N and K. The task is to find the number of arrays of size N that can be formed such that elements of the array should be positive integers and the sum of elements is equal to K.Examples:
Input : N = 2, K = 3
Output : 2
Explanation: [1, 2] and [2, 1] are the only arrays of size 2 whose sum is 3.
Input : n = 3, k = 7
Output : 15
Prerequisite: Stars and Bars
Suppose there are K identical objects which needs to be placed in N bins (N indices of the array) such that each bin have at least one object. Instead of starting to place objects into bins, we start placing the objects on a line, where the object for the first bin will be taken from the left, followed by the objects for the second bin, and so forth. Thus, the configuration will be determined once one knows what is the first object going to the second bin, and the first object going to the third bin, and so on. We can indicate this by placing N X 1 separating bars at some places between two objects; since no bin is allowed to be empty, there can be at most one bar between a given pair of objects. So, we have K objects in a line with K – 1 gaps. Now we have to choose N – 1 gaps to place bars from K – 1 gaps. This can be chosen by K – 1CN – 1.Below is implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the number of arrays of// size N whose elements are positive integers// and sum is K#include <bits/stdc++.h>using namespace std; // Return nCrint binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of array that can be// formed of size n and sum equals to k.int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codeint main(){ int N = 2, K = 3; cout << countArray(N, K) << endl; return 0;}
// Java Program to find the// number of arrays of size// N whose elements are positive// integers and sum is Kimport java.io.*; class GFG{ // Return nCrstatic int binomialCoeff(int n, int k){ int []C = new int[k + 1]; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of// array that can be// formed of size n and// sum equals to k.static int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codepublic static void main (String[] args){ int N = 2, K = 3; System.out.println( countArray(N, K));}} // This code is contributed by anuj_67.
# Python3 Program to find the number# of arrays of size N whose elements# are positive integers and sum is K # Return nCrdef binomialCoeff(n, k): C = [0] * (k + 1); C[0] = 1; # nC0 is 1 for i in range(1, n + 1): # Compute next row of pascal # triangle using the previous row for j in range(min(i, k), 0, -1): C[j] = C[j] + C[j - 1]; return C[k]; # Return the number of array that# can be formed of size n and# sum equals to k.def countArray(N, K): return binomialCoeff(K - 1, N - 1); # Driver CodeN = 2;K = 3; print(countArray(N, K)); # This code is contributed by mits
// C# Program to find the// number of arrays of size// N whose elements are positive// integers and sum is Kusing System; class GFG{// Return nCrstatic int binomialCoeff(int n, int k){ int []C = new int[k + 1]; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of // pascal triangle using // the previous row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of// array that can be// formed of size n and// sum equals to k.static int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codestatic public void Main (){ int N = 2, K = 3; Console.WriteLine( countArray(N, K));}} // This code is contributed by ajit
<?php// PHP Program to find the// number of arrays of size// N whose elements are// positive integers and// sum is K // Return nCrfunction binomialCoeff($n, $k){ $C = array_fill(0, ($k + 1), 0); $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row // of pascal triangle // using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} // Return the number of// array that can be// formed of size n and// sum equals to k.function countArray($N, $K){ return binomialCoeff($K - 1, $N - 1);} // Driver Code$N = 2;$K = 3; echo countArray($N, $K); // This code is contributed by mits?>
<script> // Javascript Program to find the number of arrays of// size N whose elements are positive integers// and sum is K // Return nCrfunction binomialCoeff(n, k){ var C = Array(k+1).fill(0); C[0] = 1; // nC0 is 1 for (var i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (var j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of array that can be// formed of size n and sum equals to k.function countArray(N, K){ return binomialCoeff(K - 1, N - 1);} // Driver Codevar N = 2, K = 3;document.write( countArray(N, K)); </script>
Output:
2
vt_m
jit_t
Mithun Kumar
rutvik_56
Permutation and Combination
Arrays
Combinatorial
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "Given two positive integers N and K. The task is to find the number of arrays of size N that can be formed such that elements of the array should be positive integers and the sum of elements is equal to K.Examples: "
},
{
"code": null,
"e": 412,
"s": 269,
"text": "Input : N = 2, K = 3\nOutput : 2\nExplanation: [1, 2] and [2, 1] are the only arrays of size 2 whose sum is 3.\n\nInput : n = 3, k = 7\nOutput : 15"
},
{
"code": null,
"e": 443,
"s": 412,
"text": "Prerequisite: Stars and Bars "
},
{
"code": null,
"e": 1340,
"s": 443,
"text": "Suppose there are K identical objects which needs to be placed in N bins (N indices of the array) such that each bin have at least one object. Instead of starting to place objects into bins, we start placing the objects on a line, where the object for the first bin will be taken from the left, followed by the objects for the second bin, and so forth. Thus, the configuration will be determined once one knows what is the first object going to the second bin, and the first object going to the third bin, and so on. We can indicate this by placing N X 1 separating bars at some places between two objects; since no bin is allowed to be empty, there can be at most one bar between a given pair of objects. So, we have K objects in a line with K – 1 gaps. Now we have to choose N – 1 gaps to place bars from K – 1 gaps. This can be chosen by K – 1CN – 1.Below is implementation of this approach: "
},
{
"code": null,
"e": 1344,
"s": 1340,
"text": "C++"
},
{
"code": null,
"e": 1349,
"s": 1344,
"text": "Java"
},
{
"code": null,
"e": 1357,
"s": 1349,
"text": "Python3"
},
{
"code": null,
"e": 1360,
"s": 1357,
"text": "C#"
},
{
"code": null,
"e": 1364,
"s": 1360,
"text": "PHP"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": "Javascript"
},
{
"code": "// CPP Program to find the number of arrays of// size N whose elements are positive integers// and sum is K#include <bits/stdc++.h>using namespace std; // Return nCrint binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of array that can be// formed of size n and sum equals to k.int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codeint main(){ int N = 2, K = 3; cout << countArray(N, K) << endl; return 0;}",
"e": 2109,
"s": 1375,
"text": null
},
{
"code": "// Java Program to find the// number of arrays of size// N whose elements are positive// integers and sum is Kimport java.io.*; class GFG{ // Return nCrstatic int binomialCoeff(int n, int k){ int []C = new int[k + 1]; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of// array that can be// formed of size n and// sum equals to k.static int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codepublic static void main (String[] args){ int N = 2, K = 3; System.out.println( countArray(N, K));}} // This code is contributed by anuj_67.",
"e": 2930,
"s": 2109,
"text": null
},
{
"code": "# Python3 Program to find the number# of arrays of size N whose elements# are positive integers and sum is K # Return nCrdef binomialCoeff(n, k): C = [0] * (k + 1); C[0] = 1; # nC0 is 1 for i in range(1, n + 1): # Compute next row of pascal # triangle using the previous row for j in range(min(i, k), 0, -1): C[j] = C[j] + C[j - 1]; return C[k]; # Return the number of array that# can be formed of size n and# sum equals to k.def countArray(N, K): return binomialCoeff(K - 1, N - 1); # Driver CodeN = 2;K = 3; print(countArray(N, K)); # This code is contributed by mits",
"e": 3556,
"s": 2930,
"text": null
},
{
"code": "// C# Program to find the// number of arrays of size// N whose elements are positive// integers and sum is Kusing System; class GFG{// Return nCrstatic int binomialCoeff(int n, int k){ int []C = new int[k + 1]; C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of // pascal triangle using // the previous row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of// array that can be// formed of size n and// sum equals to k.static int countArray(int N, int K){ return binomialCoeff(K - 1, N - 1);} // Driver Codestatic public void Main (){ int N = 2, K = 3; Console.WriteLine( countArray(N, K));}} // This code is contributed by ajit",
"e": 4438,
"s": 3556,
"text": null
},
{
"code": "<?php// PHP Program to find the// number of arrays of size// N whose elements are// positive integers and// sum is K // Return nCrfunction binomialCoeff($n, $k){ $C = array_fill(0, ($k + 1), 0); $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row // of pascal triangle // using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} // Return the number of// array that can be// formed of size n and// sum equals to k.function countArray($N, $K){ return binomialCoeff($K - 1, $N - 1);} // Driver Code$N = 2;$K = 3; echo countArray($N, $K); // This code is contributed by mits?>",
"e": 5207,
"s": 4438,
"text": null
},
{
"code": "<script> // Javascript Program to find the number of arrays of// size N whose elements are positive integers// and sum is K // Return nCrfunction binomialCoeff(n, k){ var C = Array(k+1).fill(0); C[0] = 1; // nC0 is 1 for (var i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (var j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Return the number of array that can be// formed of size n and sum equals to k.function countArray(N, K){ return binomialCoeff(K - 1, N - 1);} // Driver Codevar N = 2, K = 3;document.write( countArray(N, K)); </script>",
"e": 5874,
"s": 5207,
"text": null
},
{
"code": null,
"e": 5884,
"s": 5874,
"text": "Output: "
},
{
"code": null,
"e": 5886,
"s": 5884,
"text": "2"
},
{
"code": null,
"e": 5893,
"s": 5888,
"text": "vt_m"
},
{
"code": null,
"e": 5899,
"s": 5893,
"text": "jit_t"
},
{
"code": null,
"e": 5912,
"s": 5899,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5922,
"s": 5912,
"text": "rutvik_56"
},
{
"code": null,
"e": 5950,
"s": 5922,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 5957,
"s": 5950,
"text": "Arrays"
},
{
"code": null,
"e": 5971,
"s": 5957,
"text": "Combinatorial"
},
{
"code": null,
"e": 5991,
"s": 5971,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6004,
"s": 5991,
"text": "Mathematical"
},
{
"code": null,
"e": 6011,
"s": 6004,
"text": "Arrays"
},
{
"code": null,
"e": 6031,
"s": 6011,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6044,
"s": 6031,
"text": "Mathematical"
},
{
"code": null,
"e": 6058,
"s": 6044,
"text": "Combinatorial"
}
] |
Peterson’s Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
|
03 Mar, 2022
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support.
Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson’s Algorithm for mutual Exclusion. It was developed by Peterson in 1981 though the initial work in this direction was done by Theodorus Jozef Dekker who came up with Dekker’s algorithm in 1960, which was later refined by Peterson and came to be known as Peterson’s Algorithm.
Basically, Peterson’s algorithm provides guaranteed mutual exclusion by using only the shared memory. It uses two ideas in the algorithm:
Willingness to acquire lock.Turn to acquire lock.
Willingness to acquire lock.
Turn to acquire lock.
Prerequisite: Multithreading in C
The idea is that first a thread expresses its desire to acquire a lock and sets flag[self] = 1 and then gives the other thread a chance to acquire the lock. If the thread desires to acquire the lock, then, it gets the lock and passes the chance to the 1st thread. If it does not desire to get the lock then the while loop breaks and the 1st thread gets the chance.
Implementation in C language
C
// Filename: peterson_spinlock.c// Use below command to compile:// gcc -pthread peterson_spinlock.c -o peterson_spinlock #include <stdio.h>#include <pthread.h>#include"mythreads.h" int flag[2];int turn;const int MAX = 1e9;int ans = 0; void lock_init(){ // Initialize lock by resetting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0;} // Executed before entering critical sectionvoid lock(int self){ // Set flag[self] = 1 saying you want to acquire lock flag[self] = 1; // But, first give the other thread the chance to // acquire lock turn = 1-self; // Wait until the other thread looses the desire // to acquire lock or it is your turn to get the lock. while (flag[1-self]==1 && turn==1-self) ;} // Executed after leaving critical sectionvoid unlock(int self){ // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self] = 0;} // A Sample function run by two threads created// in main()void* func(void *s){ int i = 0; int self = (int *)s; printf("Thread Entered: %d\n", self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i=0; i<MAX; i++) ans++; unlock(self);} // Driver codeint main(){ // Initialized the lock then fork 2 threads pthread_t p1, p2; lock_init(); // Create two threads (both run func) pthread_create(&p1, NULL, func, (void*)0); pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. pthread_join(p1, NULL); pthread_join(p2, NULL); printf("Actual Count: %d | Expected Count: %d\n", ans, MAX*2); return 0;}
C
// mythread.h (A wrapper header file with assert// statements)#ifndef __MYTHREADS_h__#define __MYTHREADS_h__ #include <pthread.h>#include <assert.h>#include <sched.h> void Pthread_mutex_lock(pthread_mutex_t *m){ int rc = pthread_mutex_lock(m); assert(rc == 0);} void Pthread_mutex_unlock(pthread_mutex_t *m){ int rc = pthread_mutex_unlock(m); assert(rc == 0);} void Pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg){ int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0);} void Pthread_join(pthread_t thread, void **value_ptr){ int rc = pthread_join(thread, value_ptr); assert(rc == 0);} #endif // __MYTHREADS_h__
Output:
Thread Entered: 1
Thread Entered: 0
Actual Count: 2000000000 | Expected Count: 2000000000
The produced output is 2*109 where 109 is incremented by both threads.
This article is contributed by Pinkesh Badjatiya . 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.
pigeonlord01
surinderdawra388
Process Synchronization
system-programming
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
File Allocation Methods
Paging in Operating System
Inter Process Communication (IPC)
Introduction of Operating System - Set 1
Semaphores in Process Synchronization
CPU Scheduling in Operating Systems
Difference between Process and Thread
Introduction of Process Synchronization
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 211,
"s": 54,
"text": "Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support."
},
{
"code": null,
"e": 670,
"s": 211,
"text": "Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson’s Algorithm for mutual Exclusion. It was developed by Peterson in 1981 though the initial work in this direction was done by Theodorus Jozef Dekker who came up with Dekker’s algorithm in 1960, which was later refined by Peterson and came to be known as Peterson’s Algorithm."
},
{
"code": null,
"e": 808,
"s": 670,
"text": "Basically, Peterson’s algorithm provides guaranteed mutual exclusion by using only the shared memory. It uses two ideas in the algorithm:"
},
{
"code": null,
"e": 858,
"s": 808,
"text": "Willingness to acquire lock.Turn to acquire lock."
},
{
"code": null,
"e": 887,
"s": 858,
"text": "Willingness to acquire lock."
},
{
"code": null,
"e": 909,
"s": 887,
"text": "Turn to acquire lock."
},
{
"code": null,
"e": 943,
"s": 909,
"text": "Prerequisite: Multithreading in C"
},
{
"code": null,
"e": 1308,
"s": 943,
"text": "The idea is that first a thread expresses its desire to acquire a lock and sets flag[self] = 1 and then gives the other thread a chance to acquire the lock. If the thread desires to acquire the lock, then, it gets the lock and passes the chance to the 1st thread. If it does not desire to get the lock then the while loop breaks and the 1st thread gets the chance."
},
{
"code": null,
"e": 1338,
"s": 1308,
"text": "Implementation in C language "
},
{
"code": null,
"e": 1340,
"s": 1338,
"text": "C"
},
{
"code": "// Filename: peterson_spinlock.c// Use below command to compile:// gcc -pthread peterson_spinlock.c -o peterson_spinlock #include <stdio.h>#include <pthread.h>#include\"mythreads.h\" int flag[2];int turn;const int MAX = 1e9;int ans = 0; void lock_init(){ // Initialize lock by resetting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0;} // Executed before entering critical sectionvoid lock(int self){ // Set flag[self] = 1 saying you want to acquire lock flag[self] = 1; // But, first give the other thread the chance to // acquire lock turn = 1-self; // Wait until the other thread looses the desire // to acquire lock or it is your turn to get the lock. while (flag[1-self]==1 && turn==1-self) ;} // Executed after leaving critical sectionvoid unlock(int self){ // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self] = 0;} // A Sample function run by two threads created// in main()void* func(void *s){ int i = 0; int self = (int *)s; printf(\"Thread Entered: %d\\n\", self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i=0; i<MAX; i++) ans++; unlock(self);} // Driver codeint main(){ // Initialized the lock then fork 2 threads pthread_t p1, p2; lock_init(); // Create two threads (both run func) pthread_create(&p1, NULL, func, (void*)0); pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. pthread_join(p1, NULL); pthread_join(p2, NULL); printf(\"Actual Count: %d | Expected Count: %d\\n\", ans, MAX*2); return 0;}",
"e": 3118,
"s": 1340,
"text": null
},
{
"code": null,
"e": 3120,
"s": 3118,
"text": "C"
},
{
"code": "// mythread.h (A wrapper header file with assert// statements)#ifndef __MYTHREADS_h__#define __MYTHREADS_h__ #include <pthread.h>#include <assert.h>#include <sched.h> void Pthread_mutex_lock(pthread_mutex_t *m){ int rc = pthread_mutex_lock(m); assert(rc == 0);} void Pthread_mutex_unlock(pthread_mutex_t *m){ int rc = pthread_mutex_unlock(m); assert(rc == 0);} void Pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg){ int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0);} void Pthread_join(pthread_t thread, void **value_ptr){ int rc = pthread_join(thread, value_ptr); assert(rc == 0);} #endif // __MYTHREADS_h__",
"e": 4007,
"s": 3120,
"text": null
},
{
"code": null,
"e": 4016,
"s": 4007,
"text": "Output: "
},
{
"code": null,
"e": 4106,
"s": 4016,
"text": "Thread Entered: 1\nThread Entered: 0\nActual Count: 2000000000 | Expected Count: 2000000000"
},
{
"code": null,
"e": 4177,
"s": 4106,
"text": "The produced output is 2*109 where 109 is incremented by both threads."
},
{
"code": null,
"e": 4604,
"s": 4177,
"text": "This article is contributed by Pinkesh Badjatiya . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4617,
"s": 4604,
"text": "pigeonlord01"
},
{
"code": null,
"e": 4634,
"s": 4617,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4658,
"s": 4634,
"text": "Process Synchronization"
},
{
"code": null,
"e": 4677,
"s": 4658,
"text": "system-programming"
},
{
"code": null,
"e": 4695,
"s": 4677,
"text": "Operating Systems"
},
{
"code": null,
"e": 4713,
"s": 4695,
"text": "Operating Systems"
},
{
"code": null,
"e": 4811,
"s": 4713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4860,
"s": 4811,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 4887,
"s": 4860,
"text": "Disk Scheduling Algorithms"
},
{
"code": null,
"e": 4911,
"s": 4887,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 4938,
"s": 4911,
"text": "Paging in Operating System"
},
{
"code": null,
"e": 4972,
"s": 4938,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 5013,
"s": 4972,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 5051,
"s": 5013,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 5087,
"s": 5051,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 5125,
"s": 5087,
"text": "Difference between Process and Thread"
}
] |
Map vs Object in JavaScript
|
01 Feb, 2022
Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations.
Few basic differences are as follows:
In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!)In the Map, the original order of elements is preserved. This is not true in case of objects.The Map is an instance of an object but the vice-versa is not true.
In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!)
In the Map, the original order of elements is preserved. This is not true in case of objects.
The Map is an instance of an object but the vice-versa is not true.
Example:
<script> var map = new Map([ [5, 4], [7, 9] ]); //output:true console.log(map instanceof Object); //output:false var obj = new Object(); console.log(obj instanceof Map); </script>
Output:
true
false
Let’s dive deep into some more concepts which makes Object different than Map.
Declaration:In JavaScript, there are many ways to create an object. For example:By using direct literal:var obj = {};var obj = {1:"Object Name", 2:"Test"};console.log(obj);Output:ObjectUse of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:ObjectUsing object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1
summerOn the other hand, the Map has only one way of creation.var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, "Sam"], [2, "John"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)
Map(2)Accessing Element:Map uses its inbuilt get() method for accessing its elements.map.get(1);Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;
obj[id];Check if a key already exists:Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false.Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value.Adding new Element:Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}In object, it is done directly.obj["Demo"]="Map vs Object"; //{1->Object Name, 2->Test, Demo->Map vs Object}Getting the size:Map automatically updates its size and get the easiest.console.log(map.size);In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);
Declaration:In JavaScript, there are many ways to create an object. For example:By using direct literal:var obj = {};var obj = {1:"Object Name", 2:"Test"};console.log(obj);Output:ObjectUse of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:ObjectUsing object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1
summerOn the other hand, the Map has only one way of creation.var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, "Sam"], [2, "John"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)
Map(2)
By using direct literal:var obj = {};var obj = {1:"Object Name", 2:"Test"};console.log(obj);Output:Object
var obj = {};var obj = {1:"Object Name", 2:"Test"};console.log(obj);
Output:
Object
Use of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:Object
var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);
Output:
Object
Using object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1
summer
function fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);
fruit 1
summer
On the other hand, the Map has only one way of creation.
var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, "Sam"], [2, "John"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)
Map(2)
var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, "Sam"], [2, "John"]]); // 1-> Sam, 2->Johnconsole.log(map);
Output:
Map(0)
Map(2)
Accessing Element:Map uses its inbuilt get() method for accessing its elements.map.get(1);Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;
obj[id];
Map uses its inbuilt get() method for accessing its elements.map.get(1);
map.get(1);
Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;
obj[id];
obj.id;
obj[id];
Check if a key already exists:Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false.Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value.
Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false.
map.has(1);//returns boolean value true or false.
Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value.
var doExist = obj.1 === undefined; //returns boolean value.
Adding new Element:Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}In object, it is done directly.obj["Demo"]="Map vs Object"; //{1->Object Name, 2->Test, Demo->Map vs Object}
Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}
map.set(4, 5); //{5->4, 7->9, 4->5}
In object, it is done directly.obj["Demo"]="Map vs Object"; //{1->Object Name, 2->Test, Demo->Map vs Object}
obj["Demo"]="Map vs Object"; //{1->Object Name, 2->Test, Demo->Map vs Object}
Getting the size:Map automatically updates its size and get the easiest.console.log(map.size);In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);
Map automatically updates its size and get the easiest.console.log(map.size);
console.log(map.size);
In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);
console.log(Object.keys(obj).length);
Hence we can see Map is having better performance and less to write code structure which gives it an edge over Object. However, there are some scenarios which requires object to be used. Let us see.WHEN AND WHERE TO USE OBJECT:
Objects are a great choice for situations where we need simple structure to store data and the type of keys needed is either an integer, strings or symbols.
Scenarios which needs the application of separate logic to individual property element, the object is definitely the choice.
JSON gives direct support for object but not with map(yet).
Map is completely hash whereas Object is more than that.
Although Map tends to have more advantages over objects, at the end the day it depends on the kind of data being used and the operation needs to be performed.However, of all the advantages of map over object, map cannot replace object in JavaScript because Object is much more than a hash table. It shouldn’t be used just for the purpose of hashing if there exists another choice.
shivamnayak
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 406,
"s": 54,
"text": "Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations."
},
{
"code": null,
"e": 444,
"s": 406,
"text": "Few basic differences are as follows:"
},
{
"code": null,
"e": 785,
"s": 444,
"text": "In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!)In the Map, the original order of elements is preserved. This is not true in case of objects.The Map is an instance of an object but the vice-versa is not true."
},
{
"code": null,
"e": 966,
"s": 785,
"text": "In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!)"
},
{
"code": null,
"e": 1060,
"s": 966,
"text": "In the Map, the original order of elements is preserved. This is not true in case of objects."
},
{
"code": null,
"e": 1128,
"s": 1060,
"text": "The Map is an instance of an object but the vice-versa is not true."
},
{
"code": null,
"e": 1137,
"s": 1128,
"text": "Example:"
},
{
"code": "<script> var map = new Map([ [5, 4], [7, 9] ]); //output:true console.log(map instanceof Object); //output:false var obj = new Object(); console.log(obj instanceof Map); </script>",
"e": 1357,
"s": 1137,
"text": null
},
{
"code": null,
"e": 1365,
"s": 1357,
"text": "Output:"
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": "true\nfalse"
},
{
"code": null,
"e": 1455,
"s": 1376,
"text": "Let’s dive deep into some more concepts which makes Object different than Map."
},
{
"code": null,
"e": 3122,
"s": 1455,
"text": "Declaration:In JavaScript, there are many ways to create an object. For example:By using direct literal:var obj = {};var obj = {1:\"Object Name\", 2:\"Test\"};console.log(obj);Output:ObjectUse of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:ObjectUsing object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1\nsummerOn the other hand, the Map has only one way of creation.var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, \"Sam\"], [2, \"John\"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)\nMap(2)Accessing Element:Map uses its inbuilt get() method for accessing its elements.map.get(1);Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;\nobj[id];Check if a key already exists:Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false.Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value.Adding new Element:Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}In object, it is done directly.obj[\"Demo\"]=\"Map vs Object\"; //{1->Object Name, 2->Test, Demo->Map vs Object}Getting the size:Map automatically updates its size and get the easiest.console.log(map.size);In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);"
},
{
"code": null,
"e": 3957,
"s": 3122,
"text": "Declaration:In JavaScript, there are many ways to create an object. For example:By using direct literal:var obj = {};var obj = {1:\"Object Name\", 2:\"Test\"};console.log(obj);Output:ObjectUse of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:ObjectUsing object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1\nsummerOn the other hand, the Map has only one way of creation.var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, \"Sam\"], [2, \"John\"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)\nMap(2)"
},
{
"code": null,
"e": 4063,
"s": 3957,
"text": "By using direct literal:var obj = {};var obj = {1:\"Object Name\", 2:\"Test\"};console.log(obj);Output:Object"
},
{
"code": "var obj = {};var obj = {1:\"Object Name\", 2:\"Test\"};console.log(obj);",
"e": 4132,
"s": 4063,
"text": null
},
{
"code": null,
"e": 4140,
"s": 4132,
"text": "Output:"
},
{
"code": null,
"e": 4147,
"s": 4140,
"text": "Object"
},
{
"code": null,
"e": 4256,
"s": 4147,
"text": "Use of constructor:var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);Output:Object"
},
{
"code": "var obj = new Object(); //Empty objectvar obj = new Object;console.log(obj);",
"e": 4333,
"s": 4256,
"text": null
},
{
"code": null,
"e": 4341,
"s": 4333,
"text": "Output:"
},
{
"code": null,
"e": 4348,
"s": 4341,
"text": "Object"
},
{
"code": null,
"e": 4688,
"s": 4348,
"text": "Using object.createfunction fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);fruit 1\nsummer"
},
{
"code": "function fruits() { this.name = 'fruit 1'; this.season = 'summer'; } function apple() { fruits.call(this); } apple.prototype = Object.create(fruits.prototype); const app = new apple(); console.log(app.name); console.log(app.season);",
"e": 4995,
"s": 4688,
"text": null
},
{
"code": null,
"e": 5010,
"s": 4995,
"text": "fruit 1\nsummer"
},
{
"code": null,
"e": 5067,
"s": 5010,
"text": "On the other hand, the Map has only one way of creation."
},
{
"code": null,
"e": 5214,
"s": 5067,
"text": "var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, \"Sam\"], [2, \"John\"]]); // 1-> Sam, 2->Johnconsole.log(map);Output:Map(0)\nMap(2)"
},
{
"code": "var map = new Map();//Emptyconsole.log(map);var map = new Map([[1, \"Sam\"], [2, \"John\"]]); // 1-> Sam, 2->Johnconsole.log(map);",
"e": 5341,
"s": 5214,
"text": null
},
{
"code": null,
"e": 5349,
"s": 5341,
"text": "Output:"
},
{
"code": null,
"e": 5363,
"s": 5349,
"text": "Map(0)\nMap(2)"
},
{
"code": null,
"e": 5547,
"s": 5363,
"text": "Accessing Element:Map uses its inbuilt get() method for accessing its elements.map.get(1);Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;\nobj[id];"
},
{
"code": null,
"e": 5620,
"s": 5547,
"text": "Map uses its inbuilt get() method for accessing its elements.map.get(1);"
},
{
"code": null,
"e": 5632,
"s": 5620,
"text": "map.get(1);"
},
{
"code": null,
"e": 5726,
"s": 5632,
"text": "Object simply uses the ‘key’ name with a dot operator to access its elements.obj.id;\nobj[id];"
},
{
"code": null,
"e": 5743,
"s": 5726,
"text": "obj.id;\nobj[id];"
},
{
"code": null,
"e": 5979,
"s": 5743,
"text": "Check if a key already exists:Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false.Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value."
},
{
"code": null,
"e": 6075,
"s": 5979,
"text": "Map uses it’s inbuilt has() function for this.map.has(1);//returns boolean value true or false."
},
{
"code": null,
"e": 6125,
"s": 6075,
"text": "map.has(1);//returns boolean value true or false."
},
{
"code": null,
"e": 6236,
"s": 6125,
"text": "Object uses ‘===’ operator for performing the task.var doExist = obj.1 === undefined; //returns boolean value."
},
{
"code": null,
"e": 6296,
"s": 6236,
"text": "var doExist = obj.1 === undefined; //returns boolean value."
},
{
"code": null,
"e": 6500,
"s": 6296,
"text": "Adding new Element:Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}In object, it is done directly.obj[\"Demo\"]=\"Map vs Object\"; //{1->Object Name, 2->Test, Demo->Map vs Object}"
},
{
"code": null,
"e": 6577,
"s": 6500,
"text": "Map uses set() method to add new element.map.set(4, 5); //{5->4, 7->9, 4->5}"
},
{
"code": null,
"e": 6613,
"s": 6577,
"text": "map.set(4, 5); //{5->4, 7->9, 4->5}"
},
{
"code": null,
"e": 6722,
"s": 6613,
"text": "In object, it is done directly.obj[\"Demo\"]=\"Map vs Object\"; //{1->Object Name, 2->Test, Demo->Map vs Object}"
},
{
"code": null,
"e": 6800,
"s": 6722,
"text": "obj[\"Demo\"]=\"Map vs Object\"; //{1->Object Name, 2->Test, Demo->Map vs Object}"
},
{
"code": null,
"e": 7012,
"s": 6800,
"text": "Getting the size:Map automatically updates its size and get the easiest.console.log(map.size);In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);"
},
{
"code": null,
"e": 7090,
"s": 7012,
"text": "Map automatically updates its size and get the easiest.console.log(map.size);"
},
{
"code": null,
"e": 7113,
"s": 7090,
"text": "console.log(map.size);"
},
{
"code": null,
"e": 7231,
"s": 7113,
"text": "In object, the size needs to be calculated manually with the help Object.keys().console.log(Object.keys(obj).length);"
},
{
"code": null,
"e": 7269,
"s": 7231,
"text": "console.log(Object.keys(obj).length);"
},
{
"code": null,
"e": 7497,
"s": 7269,
"text": "Hence we can see Map is having better performance and less to write code structure which gives it an edge over Object. However, there are some scenarios which requires object to be used. Let us see.WHEN AND WHERE TO USE OBJECT:"
},
{
"code": null,
"e": 7654,
"s": 7497,
"text": "Objects are a great choice for situations where we need simple structure to store data and the type of keys needed is either an integer, strings or symbols."
},
{
"code": null,
"e": 7779,
"s": 7654,
"text": "Scenarios which needs the application of separate logic to individual property element, the object is definitely the choice."
},
{
"code": null,
"e": 7839,
"s": 7779,
"text": "JSON gives direct support for object but not with map(yet)."
},
{
"code": null,
"e": 7896,
"s": 7839,
"text": "Map is completely hash whereas Object is more than that."
},
{
"code": null,
"e": 8277,
"s": 7896,
"text": "Although Map tends to have more advantages over objects, at the end the day it depends on the kind of data being used and the operation needs to be performed.However, of all the advantages of map over object, map cannot replace object in JavaScript because Object is much more than a hash table. It shouldn’t be used just for the purpose of hashing if there exists another choice."
},
{
"code": null,
"e": 8289,
"s": 8277,
"text": "shivamnayak"
},
{
"code": null,
"e": 8305,
"s": 8289,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 8312,
"s": 8305,
"text": "Picked"
},
{
"code": null,
"e": 8323,
"s": 8312,
"text": "JavaScript"
},
{
"code": null,
"e": 8340,
"s": 8323,
"text": "Web Technologies"
},
{
"code": null,
"e": 8367,
"s": 8340,
"text": "Web technologies Questions"
}
] |
Find the minimum value to be added so that array becomes balanced
|
12 Jul, 2022
Given an array of even size, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. Suppose, we have an array 1 3 1 2 4 3. The Sum of first three elements is 1 + 3 + 1 = 5 and sum of last three elements is 2 + 4 + 3 = 9 So this is unbalanced, to make it balanced the minimum number we can add is 4 to any element in first half.
Examples :
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Input : 1 2 1 2 1 3
Output : 2
Sum of first 3 elements is 1 + 2 + 1 = 4,
sum of last three elements is 2 + 1 + 3 = 6
To make the array balanced you can add 2.
Input : 20 10
Output : 10
The idea is simple, we compute sums of first and second halves. Once these sums are computed, we return absolute difference of these two values.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Returns minimum value that need to be added// to make array balanced.int minValueToBalance(int a[], int n){ // Calculating sum of first half elements // of an array int sum1 = 0; for (int i = 0; i < n/2; i++) sum1 += a[i]; // Calculating sum of other half elements // of an array int sum2 = 0; for (int i = n/2; i < n; i++) sum2 += a[i]; // calculating difference return abs(sum1 - sum2);} // Driver codeint main(){ int arr[] = {1, 7, 1, 1, 3, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << minValueToBalance(arr, n)<<endl; return 0;}
// Java program to Find the minimum value// to be added so that array becomes balanced class Minimum{ // Returns minimum value that need to // be added to make array balanced. public static int minValueToBalance(int a[], int n) { // Calculating sum of first half // elements of an array int sum1 = 0; for (int i = 0; i < n / 2; i++) sum1 += a[i]; // Calculating sum of other half // elements of an array int sum2 = 0; for (int i = n/2; i < n; i++) sum2 += a[i]; // calculating difference return Math.abs(sum1 - sum2); } // driver code public static void main(String[] args) { int arr[] = {1, 7, 1, 1, 3, 1}; int n = 6; System.out.print(minValueToBalance(arr, n)); }} // This code is contributed by rishabh_jain
# Python3 program to Find the# minimum value to be added so that# array becomes balanced # Returns minimum value that need to# be added to make array balanced.def minValueToBalance(a, n): # Calculating sum of first # half elements of an array sum1 = 0 for i in range( int(n / 2)): sum1 += a[i] # Calculating sum of other # half elements of an array sum2 = 0; i = int(n / 2) while i < n: sum2 += a[i] i = i + 1 # calculating difference return abs(sum1 - sum2) # Driver codearr = [1, 7, 1, 1, 3, 1]n = len(arr)print(minValueToBalance(arr, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to Find the minimum value// to be added so that array becomes balancedusing System; class Minimum { // Returns minimum value that need to // be added to make array balanced. public static int minValueToBalance(int []a, int n) { // Calculating sum of first half // elements of an array int sum1 = 0; for (int i = 0; i < n / 2; i++) sum1 += a[i]; // Calculating sum of other half // elements of an array int sum2 = 0; for (int i = n / 2; i < n; i++) sum2 += a[i]; // calculating difference return Math.Abs(sum1 - sum2); } // Driver Code public static void Main() { int []arr = {1, 7, 1, 1, 3, 1}; int n = 6; Console.Write(minValueToBalance(arr, n)); }} // This code is contributed by Nitin Mittal.
<?php// Returns minimum value// that need to be added// to make array balanced.function minValueToBalance($a, $n){ // Calculating sum of first // half elements of an array $sum1 = 0; for ($i = 0; $i < $n / 2; $i++) $sum1 += $a[$i]; // Calculating sum of other // half elements of an array $sum2 = 0; for ( $i = $n / 2; $i < $n; $i++) $sum2 += $a[$i]; // calculating difference return abs($sum1 - $sum2);} // Driver code$arr = array(1, 7, 1, 1, 3, 1);$n = sizeof($arr) / sizeof($arr[0]);echo minValueToBalance($arr, $n); // This code is contributed// by nitin mittal.?>
<script> // Returns minimum value that need to be added// to make array balanced.function minValueToBalance(a, n){ // Calculating sum of first half elements // of an array let sum1 = 0; for (let i = 0; i < Math.floor(n/2); i++) sum1 += a[i]; // Calculating sum of other half elements // of an array let sum2 = 0; for (let i = Math.floor(n/2); i < n; i++) sum2 += a[i]; // calculating difference return Math.abs(sum1 - sum2);} // Driver code let arr = [1, 7, 1, 1, 3, 1]; let n = arr.length; document.write(minValueToBalance(arr, n) + "<br>"); // This code is contributed by Surbhi Tyagi. </script>
4
Find the minimum value to be added so that array becomes balanced | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind the minimum value to be added so that array becomes balanced | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Zq1XLf5DTSo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Rajput. 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.
nitin mittal
surbhityagi15
hardikkoriintern
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 525,
"s": 53,
"text": "Given an array of even size, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. Suppose, we have an array 1 3 1 2 4 3. The Sum of first three elements is 1 + 3 + 1 = 5 and sum of last three elements is 2 + 4 + 3 = 9 So this is unbalanced, to make it balanced the minimum number we can add is 4 to any element in first half."
},
{
"code": null,
"e": 537,
"s": 525,
"text": "Examples : "
},
{
"code": null,
"e": 546,
"s": 537,
"text": "Chapters"
},
{
"code": null,
"e": 573,
"s": 546,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 623,
"s": 573,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 646,
"s": 623,
"text": "captions off, selected"
},
{
"code": null,
"e": 654,
"s": 646,
"text": "English"
},
{
"code": null,
"e": 678,
"s": 654,
"text": "This is a modal window."
},
{
"code": null,
"e": 747,
"s": 678,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 769,
"s": 747,
"text": "End of dialog window."
},
{
"code": null,
"e": 956,
"s": 769,
"text": "Input : 1 2 1 2 1 3\nOutput : 2\nSum of first 3 elements is 1 + 2 + 1 = 4, \nsum of last three elements is 2 + 1 + 3 = 6\nTo make the array balanced you can add 2.\n\nInput : 20 10\nOutput : 10"
},
{
"code": null,
"e": 1102,
"s": 956,
"text": "The idea is simple, we compute sums of first and second halves. Once these sums are computed, we return absolute difference of these two values. "
},
{
"code": null,
"e": 1118,
"s": 1102,
"text": "Implementation:"
},
{
"code": null,
"e": 1122,
"s": 1118,
"text": "C++"
},
{
"code": null,
"e": 1127,
"s": 1122,
"text": "Java"
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "Python3"
},
{
"code": null,
"e": 1138,
"s": 1135,
"text": "C#"
},
{
"code": null,
"e": 1142,
"s": 1138,
"text": "PHP"
},
{
"code": null,
"e": 1153,
"s": 1142,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Returns minimum value that need to be added// to make array balanced.int minValueToBalance(int a[], int n){ // Calculating sum of first half elements // of an array int sum1 = 0; for (int i = 0; i < n/2; i++) sum1 += a[i]; // Calculating sum of other half elements // of an array int sum2 = 0; for (int i = n/2; i < n; i++) sum2 += a[i]; // calculating difference return abs(sum1 - sum2);} // Driver codeint main(){ int arr[] = {1, 7, 1, 1, 3, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << minValueToBalance(arr, n)<<endl; return 0;}",
"e": 1795,
"s": 1153,
"text": null
},
{
"code": "// Java program to Find the minimum value// to be added so that array becomes balanced class Minimum{ // Returns minimum value that need to // be added to make array balanced. public static int minValueToBalance(int a[], int n) { // Calculating sum of first half // elements of an array int sum1 = 0; for (int i = 0; i < n / 2; i++) sum1 += a[i]; // Calculating sum of other half // elements of an array int sum2 = 0; for (int i = n/2; i < n; i++) sum2 += a[i]; // calculating difference return Math.abs(sum1 - sum2); } // driver code public static void main(String[] args) { int arr[] = {1, 7, 1, 1, 3, 1}; int n = 6; System.out.print(minValueToBalance(arr, n)); }} // This code is contributed by rishabh_jain",
"e": 2692,
"s": 1795,
"text": null
},
{
"code": "# Python3 program to Find the# minimum value to be added so that# array becomes balanced # Returns minimum value that need to# be added to make array balanced.def minValueToBalance(a, n): # Calculating sum of first # half elements of an array sum1 = 0 for i in range( int(n / 2)): sum1 += a[i] # Calculating sum of other # half elements of an array sum2 = 0; i = int(n / 2) while i < n: sum2 += a[i] i = i + 1 # calculating difference return abs(sum1 - sum2) # Driver codearr = [1, 7, 1, 1, 3, 1]n = len(arr)print(minValueToBalance(arr, n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3355,
"s": 2692,
"text": null
},
{
"code": "// C# program to Find the minimum value// to be added so that array becomes balancedusing System; class Minimum { // Returns minimum value that need to // be added to make array balanced. public static int minValueToBalance(int []a, int n) { // Calculating sum of first half // elements of an array int sum1 = 0; for (int i = 0; i < n / 2; i++) sum1 += a[i]; // Calculating sum of other half // elements of an array int sum2 = 0; for (int i = n / 2; i < n; i++) sum2 += a[i]; // calculating difference return Math.Abs(sum1 - sum2); } // Driver Code public static void Main() { int []arr = {1, 7, 1, 1, 3, 1}; int n = 6; Console.Write(minValueToBalance(arr, n)); }} // This code is contributed by Nitin Mittal.",
"e": 4265,
"s": 3355,
"text": null
},
{
"code": "<?php// Returns minimum value// that need to be added// to make array balanced.function minValueToBalance($a, $n){ // Calculating sum of first // half elements of an array $sum1 = 0; for ($i = 0; $i < $n / 2; $i++) $sum1 += $a[$i]; // Calculating sum of other // half elements of an array $sum2 = 0; for ( $i = $n / 2; $i < $n; $i++) $sum2 += $a[$i]; // calculating difference return abs($sum1 - $sum2);} // Driver code$arr = array(1, 7, 1, 1, 3, 1);$n = sizeof($arr) / sizeof($arr[0]);echo minValueToBalance($arr, $n); // This code is contributed// by nitin mittal.?>",
"e": 4880,
"s": 4265,
"text": null
},
{
"code": "<script> // Returns minimum value that need to be added// to make array balanced.function minValueToBalance(a, n){ // Calculating sum of first half elements // of an array let sum1 = 0; for (let i = 0; i < Math.floor(n/2); i++) sum1 += a[i]; // Calculating sum of other half elements // of an array let sum2 = 0; for (let i = Math.floor(n/2); i < n; i++) sum2 += a[i]; // calculating difference return Math.abs(sum1 - sum2);} // Driver code let arr = [1, 7, 1, 1, 3, 1]; let n = arr.length; document.write(minValueToBalance(arr, n) + \"<br>\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 5533,
"s": 4880,
"text": null
},
{
"code": null,
"e": 5535,
"s": 5533,
"text": "4"
},
{
"code": null,
"e": 6483,
"s": 5535,
"text": "Find the minimum value to be added so that array becomes balanced | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind the minimum value to be added so that array becomes balanced | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Zq1XLf5DTSo\" 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": 6780,
"s": 6483,
"text": "This article is contributed by Sahil Rajput. 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": 6793,
"s": 6780,
"text": "nitin mittal"
},
{
"code": null,
"e": 6807,
"s": 6793,
"text": "surbhityagi15"
},
{
"code": null,
"e": 6824,
"s": 6807,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6831,
"s": 6824,
"text": "Arrays"
},
{
"code": null,
"e": 6838,
"s": 6831,
"text": "Arrays"
}
] |
Python | sympy.simplify() method
|
25 Jun, 2019
With the help of sympy.simplify() method, we can simplify any mathematical expression.
Syntax: simplify(expression)
Parameters:expression – It is the mathematical expression which needs to be simplified.
Returns: Returns a simplified mathematical expression corresponding to the input expression.
Example #1:In this example we can see that by using sympy.lambdify() method, we can simplify any mathematical expression.
# import sympyfrom sympy import * x = symbols('x')expr = sin(x)**2 + cos(x)**2 print("Before Simplification : {}".format(expr)) # Use sympy.simplify() methodsmpl = simplify(expr) print("After Simplification : {}".format(smpl))
Output:
Before Simplification : sin(x)**2 + cos(x)**2
After Simplification : 1
Example #2:
# import sympyfrom sympy import * x = symbols('x')expr = (x**3 + x**2 - x - 1)/(x**2 + 2 * x + 1) print("Before Simplification : {}".format(expr)) # Use sympy.simplify() methodsmpl = simplify(expr) print("After Simplification : {}".format(smpl))
Output:
Before Simplification : (x**3 + x**2 - x - 1)/(x**2 + 2*x + 1)
After Simplification : After Simplification : x - 1
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "With the help of sympy.simplify() method, we can simplify any mathematical expression."
},
{
"code": null,
"e": 144,
"s": 115,
"text": "Syntax: simplify(expression)"
},
{
"code": null,
"e": 232,
"s": 144,
"text": "Parameters:expression – It is the mathematical expression which needs to be simplified."
},
{
"code": null,
"e": 325,
"s": 232,
"text": "Returns: Returns a simplified mathematical expression corresponding to the input expression."
},
{
"code": null,
"e": 447,
"s": 325,
"text": "Example #1:In this example we can see that by using sympy.lambdify() method, we can simplify any mathematical expression."
},
{
"code": "# import sympyfrom sympy import * x = symbols('x')expr = sin(x)**2 + cos(x)**2 print(\"Before Simplification : {}\".format(expr)) # Use sympy.simplify() methodsmpl = simplify(expr) print(\"After Simplification : {}\".format(smpl)) ",
"e": 685,
"s": 447,
"text": null
},
{
"code": null,
"e": 693,
"s": 685,
"text": "Output:"
},
{
"code": null,
"e": 765,
"s": 693,
"text": "Before Simplification : sin(x)**2 + cos(x)**2\nAfter Simplification : 1\n"
},
{
"code": null,
"e": 777,
"s": 765,
"text": "Example #2:"
},
{
"code": "# import sympyfrom sympy import * x = symbols('x')expr = (x**3 + x**2 - x - 1)/(x**2 + 2 * x + 1) print(\"Before Simplification : {}\".format(expr)) # Use sympy.simplify() methodsmpl = simplify(expr) print(\"After Simplification : {}\".format(smpl)) ",
"e": 1034,
"s": 777,
"text": null
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Output:"
},
{
"code": null,
"e": 1158,
"s": 1042,
"text": "Before Simplification : (x**3 + x**2 - x - 1)/(x**2 + 2*x + 1)\nAfter Simplification : After Simplification : x - 1\n"
},
{
"code": null,
"e": 1164,
"s": 1158,
"text": "SymPy"
},
{
"code": null,
"e": 1171,
"s": 1164,
"text": "Python"
}
] |
MongoDB query to return specific fields from an array?
|
To return specific fields, use aggregate $project. Let us first create a collection with documents −
> db.returnSpecificFieldDemo.insertOne(
{
"StudentId":1,
"StudentDetails": [
{
"StudentName":"Larry",
"StudentAge":21,
"StudentCountryName":"US"
},
{
"StudentName":"Chris",
"StudentAge":23,
"StudentCountryName":"AUS"
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce23d3236e8b255a5eee943")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.returnSpecificFieldDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce23d3236e8b255a5eee943"),
"StudentId" : 1,
"StudentDetails" : [
{
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 23,
"StudentCountryName" : "AUS"
}
]
}
Following is the query to return specific fields from an array −
> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]);
This will produce the following output −
{ "StudentId" : 1, "StudentCountryName" : "AUS" }
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To return specific fields, use aggregate $project. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1606,
"s": 1163,
"text": "> db.returnSpecificFieldDemo.insertOne(\n {\n \"StudentId\":1,\n \"StudentDetails\": [\n {\n \"StudentName\":\"Larry\",\n \"StudentAge\":21,\n \"StudentCountryName\":\"US\"\n },\n {\n \"StudentName\":\"Chris\",\n \"StudentAge\":23,\n \"StudentCountryName\":\"AUS\"\n }\n ]\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce23d3236e8b255a5eee943\")\n}"
},
{
"code": null,
"e": 1705,
"s": 1606,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1751,
"s": 1705,
"text": "> db.returnSpecificFieldDemo.find().pretty();"
},
{
"code": null,
"e": 1792,
"s": 1751,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2126,
"s": 1792,
"text": "{\n \"_id\" : ObjectId(\"5ce23d3236e8b255a5eee943\"),\n \"StudentId\" : 1,\n \"StudentDetails\" : [\n {\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 21,\n \"StudentCountryName\" : \"US\"\n },\n {\n \"StudentName\" : \"Chris\",\n \"StudentAge\" : 23,\n \"StudentCountryName\" : \"AUS\"\n }\n ]\n}"
},
{
"code": null,
"e": 2191,
"s": 2126,
"text": "Following is the query to return specific fields from an array −"
},
{
"code": null,
"e": 2356,
"s": 2191,
"text": "> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]);"
},
{
"code": null,
"e": 2397,
"s": 2356,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2447,
"s": 2397,
"text": "{ \"StudentId\" : 1, \"StudentCountryName\" : \"AUS\" }"
}
] |
Python Pandas - Check if the index has duplicate values
|
To check if the index has duplicate values, use the index.has_duplicates property in Pandas.
At first, import the required libraries −
import pandas as pd
Creating the index −
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])
Display the index −
print("Pandas Index...\n",index)
Check if the index is having duplicate values −
print("\nIs the Pandas index having duplicate values?\n",index.has_duplicates)
Following is the code −
import pandas as pd
# Creating the index
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])
# Display the index
print("Pandas Index...\n",index)
# Return an array representing the data in the Index
print("\nArray...\n",index.values)
# Check if the index is having duplicate values
print("\nIs the Pandas index having duplicate values?\n",index.has_duplicates)
This will produce the following code −
Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')
Array...
['Car' 'Bike' 'Truck' 'Car' 'Airplane']
Is the Pandas index having duplicate values?
True
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To check if the index has duplicate values, use the index.has_duplicates property in Pandas."
},
{
"code": null,
"e": 1197,
"s": 1155,
"text": "At first, import the required libraries −"
},
{
"code": null,
"e": 1217,
"s": 1197,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1238,
"s": 1217,
"text": "Creating the index −"
},
{
"code": null,
"e": 1297,
"s": 1238,
"text": "index = pd.Index(['Car','Bike','Truck','Car','Airplane'])\n"
},
{
"code": null,
"e": 1317,
"s": 1297,
"text": "Display the index −"
},
{
"code": null,
"e": 1350,
"s": 1317,
"text": "print(\"Pandas Index...\\n\",index)"
},
{
"code": null,
"e": 1398,
"s": 1350,
"text": "Check if the index is having duplicate values −"
},
{
"code": null,
"e": 1478,
"s": 1398,
"text": "print(\"\\nIs the Pandas index having duplicate values?\\n\",index.has_duplicates)\n"
},
{
"code": null,
"e": 1502,
"s": 1478,
"text": "Following is the code −"
},
{
"code": null,
"e": 1873,
"s": 1502,
"text": "import pandas as pd\n\n# Creating the index\nindex = pd.Index(['Car','Bike','Truck','Car','Airplane'])\n\n# Display the index\nprint(\"Pandas Index...\\n\",index)\n\n# Return an array representing the data in the Index\nprint(\"\\nArray...\\n\",index.values)\n\n# Check if the index is having duplicate values\nprint(\"\\nIs the Pandas index having duplicate values?\\n\",index.has_duplicates)"
},
{
"code": null,
"e": 1912,
"s": 1873,
"text": "This will produce the following code −"
},
{
"code": null,
"e": 2096,
"s": 1912,
"text": "Pandas Index...\nIndex(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')\n\nArray...\n['Car' 'Bike' 'Truck' 'Car' 'Airplane']\n\nIs the Pandas index having duplicate values?\nTrue"
}
] |
Zygodrome Number - GeeksforGeeks
|
12 Apr, 2022
Given an integer N, the task is to check if N is an zygodrome Number.
Zygodrome Number is a numbers if it is made of nontrivial runs of identical digits. For example: 112233, 7777333 and 1100 are all zygodromes in base 10.
Examples:
Input: N = 1122 Output: Yes Input: N = 26 Output: No
Approach: The idea is to convert the number to string and return false if any character is not equal to previous character and next character. Since the first character does not have a previous character and the last character doesn’t not have the next character so we will add a space at the beginning and end of the string.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check if N// is an zygodrome number #include <bits/stdc++.h>using namespace std; // Function to check if N// is an zygodrome numberbool iszygodromeNum(int N){ // convert N to string string s = to_string(N); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.size() - 1; i++) { // If any character is not same as // prev and next then return false if (s[i] != s[i - 1] && s[i] != s[i + 1]) { return false; } } return true;} // Driver codeint main(){ int n = 1122; if (iszygodromeNum(n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation to check if N// is a zygodrome numberclass GFG{ // Function to check if N// is an zygodrome numberstatic boolean iszygodromeNum(int N){ // convert N to string String s = Integer.toString(N); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.length() - 1; i++) { // If any character is not same as // prev and next then return false if (s.charAt(i) != s.charAt(i - 1) && s.charAt(i) != s.charAt(i + 1)) { return false; } } return true;} // Driver codepublic static void main(String[] args){ int n = 1122; if (iszygodromeNum(n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by shubham
# Python3 program implementation to check# if N is an zygodrome number # Function to check if N# is an zygodrome numberdef iszygodromeNum(N): # Convert N to string s = str(N); # Adding a space at the # beginning and # end of the string s = ' ' + s + ' '; # Traverse the string i = 1 while i < len(s) - 1: # If any character is not same as # prev and next then return false if ((s[i] != s[i - 1]) and (s[i] != s[i + 1])): return False; i += 1 return True; # Driver codeif __name__ == '__main__': n = 1122; if iszygodromeNum(n): print("Yes") else: print("No") # This code is contributed by jana_sayantan
// C# implementation to check if N// is a zygodrome numberusing System;class GFG{ // Function to check if N// is an zygodrome numberstatic bool iszygodromeNum(int N){ // convert N to string String s = N.ToString(); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.Length - 1; i++) { // If any character is not same as // prev and next then return false if (s[i] != s[i - 1] && s[i] != s[i + 1]) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ int n = 1122; if (iszygodromeNum(n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Princi Singh
<script>// Javascript implementation to check if N// is a zygodrome number // Function to check if N // is an zygodrome number function iszygodromeNum( N) { // convert N to string let s = N.toString(); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for ( i = 1; i < s.length - 1; i++) { // If any letacter is not same as // prev and next then return false if (s[i] != s[i-1] && s[i] != s[i + 1]) { return false; } } return true; } // Driver code let n = 1122; if (iszygodromeNum(n)) document.write("Yes"); else document.write("No"); // This code is contributed by todaysgaurav</script>
Yes
Time Complexity: O(log10n)
shubham prakash 1
princi singh
jana_sayantan
todaysgaurav
souravmahato348
rkbhola5
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
Fizz Buzz Implementation
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 24371,
"s": 24301,
"text": "Given an integer N, the task is to check if N is an zygodrome Number."
},
{
"code": null,
"e": 24524,
"s": 24371,
"text": "Zygodrome Number is a numbers if it is made of nontrivial runs of identical digits. For example: 112233, 7777333 and 1100 are all zygodromes in base 10."
},
{
"code": null,
"e": 24534,
"s": 24524,
"text": "Examples:"
},
{
"code": null,
"e": 24587,
"s": 24534,
"text": "Input: N = 1122 Output: Yes Input: N = 26 Output: No"
},
{
"code": null,
"e": 24963,
"s": 24587,
"text": "Approach: The idea is to convert the number to string and return false if any character is not equal to previous character and next character. Since the first character does not have a previous character and the last character doesn’t not have the next character so we will add a space at the beginning and end of the string.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24967,
"s": 24963,
"text": "C++"
},
{
"code": null,
"e": 24972,
"s": 24967,
"text": "Java"
},
{
"code": null,
"e": 24980,
"s": 24972,
"text": "Python3"
},
{
"code": null,
"e": 24983,
"s": 24980,
"text": "C#"
},
{
"code": null,
"e": 24994,
"s": 24983,
"text": "Javascript"
},
{
"code": "// C++ implementation to check if N// is an zygodrome number #include <bits/stdc++.h>using namespace std; // Function to check if N// is an zygodrome numberbool iszygodromeNum(int N){ // convert N to string string s = to_string(N); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.size() - 1; i++) { // If any character is not same as // prev and next then return false if (s[i] != s[i - 1] && s[i] != s[i + 1]) { return false; } } return true;} // Driver codeint main(){ int n = 1122; if (iszygodromeNum(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 25733,
"s": 24994,
"text": null
},
{
"code": "// Java implementation to check if N// is a zygodrome numberclass GFG{ // Function to check if N// is an zygodrome numberstatic boolean iszygodromeNum(int N){ // convert N to string String s = Integer.toString(N); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.length() - 1; i++) { // If any character is not same as // prev and next then return false if (s.charAt(i) != s.charAt(i - 1) && s.charAt(i) != s.charAt(i + 1)) { return false; } } return true;} // Driver codepublic static void main(String[] args){ int n = 1122; if (iszygodromeNum(n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by shubham",
"e": 26578,
"s": 25733,
"text": null
},
{
"code": "# Python3 program implementation to check# if N is an zygodrome number # Function to check if N# is an zygodrome numberdef iszygodromeNum(N): # Convert N to string s = str(N); # Adding a space at the # beginning and # end of the string s = ' ' + s + ' '; # Traverse the string i = 1 while i < len(s) - 1: # If any character is not same as # prev and next then return false if ((s[i] != s[i - 1]) and (s[i] != s[i + 1])): return False; i += 1 return True; # Driver codeif __name__ == '__main__': n = 1122; if iszygodromeNum(n): print(\"Yes\") else: print(\"No\") # This code is contributed by jana_sayantan",
"e": 27331,
"s": 26578,
"text": null
},
{
"code": "// C# implementation to check if N// is a zygodrome numberusing System;class GFG{ // Function to check if N// is an zygodrome numberstatic bool iszygodromeNum(int N){ // convert N to string String s = N.ToString(); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for (int i = 1; i < s.Length - 1; i++) { // If any character is not same as // prev and next then return false if (s[i] != s[i - 1] && s[i] != s[i + 1]) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ int n = 1122; if (iszygodromeNum(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Princi Singh",
"e": 28150,
"s": 27331,
"text": null
},
{
"code": "<script>// Javascript implementation to check if N// is a zygodrome number // Function to check if N // is an zygodrome number function iszygodromeNum( N) { // convert N to string let s = N.toString(); // Adding a space at the // beginning and // end of the string s = ' ' + s + ' '; // Traverse the string for ( i = 1; i < s.length - 1; i++) { // If any letacter is not same as // prev and next then return false if (s[i] != s[i-1] && s[i] != s[i + 1]) { return false; } } return true; } // Driver code let n = 1122; if (iszygodromeNum(n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by todaysgaurav</script>",
"e": 29000,
"s": 28150,
"text": null
},
{
"code": null,
"e": 29004,
"s": 29000,
"text": "Yes"
},
{
"code": null,
"e": 29031,
"s": 29004,
"text": "Time Complexity: O(log10n)"
},
{
"code": null,
"e": 29049,
"s": 29031,
"text": "shubham prakash 1"
},
{
"code": null,
"e": 29062,
"s": 29049,
"text": "princi singh"
},
{
"code": null,
"e": 29076,
"s": 29062,
"text": "jana_sayantan"
},
{
"code": null,
"e": 29089,
"s": 29076,
"text": "todaysgaurav"
},
{
"code": null,
"e": 29105,
"s": 29089,
"text": "souravmahato348"
},
{
"code": null,
"e": 29114,
"s": 29105,
"text": "rkbhola5"
},
{
"code": null,
"e": 29121,
"s": 29114,
"text": "series"
},
{
"code": null,
"e": 29134,
"s": 29121,
"text": "Mathematical"
},
{
"code": null,
"e": 29147,
"s": 29134,
"text": "Mathematical"
},
{
"code": null,
"e": 29154,
"s": 29147,
"text": "series"
},
{
"code": null,
"e": 29252,
"s": 29154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29261,
"s": 29252,
"text": "Comments"
},
{
"code": null,
"e": 29274,
"s": 29261,
"text": "Old Comments"
},
{
"code": null,
"e": 29319,
"s": 29274,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 29351,
"s": 29319,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29395,
"s": 29351,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29429,
"s": 29395,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 29462,
"s": 29429,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29487,
"s": 29462,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 29526,
"s": 29487,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 29577,
"s": 29526,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 29648,
"s": 29577,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Bridges in a Graph
|
An edge in an undirected graph is said to be a bridge, if and only if by removing it, disconnects the graph, or make different components of the graph.
In a practical approach, if some bridges are present in a network when the connection of bridges is broken, it can break the whole network.
Input:
The adjacency matrix of the graph.
0 1 1 1 0
1 0 1 0 0
1 1 0 0 0
1 0 0 0 1
0 0 0 1 0
Output:
Bridges in given graph:
Bridge 3--4
Bridge 0--3
bridgeFind(start, visited, disc, low, parent)
Input − The start vertex, the visited array to mark when a node is visited, the disc will hold the discovery time of the vertex, and low will hold information about subtrees. The parent will hold the parent of the current vertex.
Output − print if any bridge is found.
Begin
time := 0 //the value of time will not be initialized for next function calls
mark start as visited
set disc[start] := time+1 and low[start] := time + 1
time := time + 1
for all vertex v in the graph G, do
if there is an edge between (start, v), then
if v is visited, then
parent[v] := start
bridgeFind(v, visited, disc, low, parent)
low[start] := minimum of low[start] and low[v]
if low[v] > disc[start], then
display bridges from start to v
else if v is not the parent of start, then
low[start] := minimum of low[start] and disc[v]
done
End
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}
};
int min(int a, int b) {
return (a<b)?a:b;
}
void bridgeFind(int start, bool visited[], int disc[], int low[], int parent[]) {
static int time = 0;
visited[start] = true; //make the first vertex is visited
disc[start] = low[start] = ++time; //initialize discovery time and the low time
for(int v = 0; v<NODE; v++) {
if(graph[start][v]) { //for all vertex v, which is connected with start
if(!visited[v]) {
parent[v] = start; //make start node as parent
bridgeFind(v, visited, disc, low, parent);
low[start] = min(low[start], low[v]); //when subtree from v is connected to one of parent of start node
if(low[v] > disc[start])
cout << "Bridge " << start << "--"<<v<<endl;
} else if(v != parent[start]) //update low of start for previous call
low[start] = min(low[start], disc[v]);
}
}
}
bool bridges() {
bool *vis = new bool[NODE];
int *disc = new int[NODE];
int *low = new int[NODE];
int *parent = new int[NODE];
for(int i = 0; i<NODE; i++) {
vis[i] = false; //no node is visited
parent[i] = -1; //initially there is no parent for any node
}
for(int i = 0; i<NODE; i++)
if(!vis[i]) //if any node is unvisited, the graph is not connected
bridgeFind(i, vis, disc, low, parent);
}
int main() {
cout << "Bridges in given graph:"<<endl;
bridges();
}
Bridges in given graph:
Bridge 3--4
Bridge 0--3
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "An edge in an undirected graph is said to be a bridge, if and only if by removing it, disconnects the graph, or make different components of the graph. "
},
{
"code": null,
"e": 1355,
"s": 1215,
"text": "In a practical approach, if some bridges are present in a network when the connection of bridges is broken, it can break the whole network."
},
{
"code": null,
"e": 1505,
"s": 1355,
"text": "Input:\nThe adjacency matrix of the graph.\n\n0 1 1 1 0\n1 0 1 0 0\n1 1 0 0 0\n1 0 0 0 1\n0 0 0 1 0\n\nOutput:\nBridges in given graph:\nBridge 3--4\nBridge 0--3"
},
{
"code": null,
"e": 1551,
"s": 1505,
"text": "bridgeFind(start, visited, disc, low, parent)"
},
{
"code": null,
"e": 1781,
"s": 1551,
"text": "Input − The start vertex, the visited array to mark when a node is visited, the disc will hold the discovery time of the vertex, and low will hold information about subtrees. The parent will hold the parent of the current vertex."
},
{
"code": null,
"e": 1820,
"s": 1781,
"text": "Output − print if any bridge is found."
},
{
"code": null,
"e": 2494,
"s": 1820,
"text": "Begin\n time := 0 //the value of time will not be initialized for next function calls\n mark start as visited\n set disc[start] := time+1 and low[start] := time + 1\n time := time + 1\n\n for all vertex v in the graph G, do\n if there is an edge between (start, v), then\n if v is visited, then\n parent[v] := start\n bridgeFind(v, visited, disc, low, parent)\n low[start] := minimum of low[start] and low[v]\n\n if low[v] > disc[start], then\n display bridges from start to v\n else if v is not the parent of start, then\n low[start] := minimum of low[start] and disc[v]\n done\nEnd"
},
{
"code": null,
"e": 4228,
"s": 2494,
"text": "#include<iostream>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 1, 1, 0},\n {1, 0, 1, 0, 0},\n {1, 1, 0, 0, 0},\n {1, 0, 0, 0, 1},\n {0, 0, 0, 1, 0}\n};\n \nint min(int a, int b) {\n return (a<b)?a:b;\n}\n \nvoid bridgeFind(int start, bool visited[], int disc[], int low[], int parent[]) {\n static int time = 0;\n visited[start] = true; //make the first vertex is visited\n disc[start] = low[start] = ++time; //initialize discovery time and the low time\n\n for(int v = 0; v<NODE; v++) {\n if(graph[start][v]) { //for all vertex v, which is connected with start\n if(!visited[v]) {\n parent[v] = start; //make start node as parent\n bridgeFind(v, visited, disc, low, parent);\n \n low[start] = min(low[start], low[v]); //when subtree from v is connected to one of parent of start node\n if(low[v] > disc[start])\n cout << \"Bridge \" << start << \"--\"<<v<<endl;\n } else if(v != parent[start]) //update low of start for previous call\n low[start] = min(low[start], disc[v]);\n }\n }\n}\n\nbool bridges() {\n bool *vis = new bool[NODE];\n int *disc = new int[NODE];\n int *low = new int[NODE];\n int *parent = new int[NODE];\n \n for(int i = 0; i<NODE; i++) {\n vis[i] = false; //no node is visited\n parent[i] = -1; //initially there is no parent for any node\n }\n \n for(int i = 0; i<NODE; i++)\n if(!vis[i]) //if any node is unvisited, the graph is not connected\n bridgeFind(i, vis, disc, low, parent);\n}\n\nint main() {\n cout << \"Bridges in given graph:\"<<endl;\n bridges();\n}"
},
{
"code": null,
"e": 4276,
"s": 4228,
"text": "Bridges in given graph:\nBridge 3--4\nBridge 0--3"
}
] |
Count numbers in the range [L, R] having only three set bits - GeeksforGeeks
|
24 Jun, 2021
Given an array arr[] of N pairs, where each array element denotes a query of the form {L, R}, the task is to find the count of numbers in the range [L, R], having only 3-set bits for each query {L, R}.
Examples:
Input: arr[] = {{11, 19}, {14, 19}}Output: 4 2Explanation:
Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13, 14, 19}.Query(14, 19): Numbers in the range [14, 19] having three set bits are {14, 19}.
Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13, 14, 19}.
Query(14, 19): Numbers in the range [14, 19] having three set bits are {14, 19}.
Input: arr[] = {{1, 10}, {6, 12}}Output: 1 2Explanation:
Query(1, 10): Numbers in the range [1, 10] having three set bits are {7}.Query(6, 12): Numbers in the range [6, 12] having three set bits are {7, 12}.
Query(1, 10): Numbers in the range [1, 10] having three set bits are {7}.
Query(6, 12): Numbers in the range [6, 12] having three set bits are {7, 12}.
Approach: The idea to solve this problem is to do a pre-computation and store all the numbers with only 3 bits set in the range [1, 1018], and then use binary search to find the position of lowerbound of L and upperbound of R and return the answer as there difference. Follow the steps below to solve the given problem:
Initialize a vector, say V, to store all the numbers in the range [1, 1018] with only three bits set.
Iterate over every triplet formed of the relation [0, 63]×[0, 63]×[0, 63] using variables i, j, and k and perform the following steps:If i, j, and k are distinct, then compute the number with the ith, jth, and kth bit set, and if the number is less than 1018, push the number in the vector V.
If i, j, and k are distinct, then compute the number with the ith, jth, and kth bit set, and if the number is less than 1018, push the number in the vector V.
Sort the vector V in ascending order.
Traverse the array arr[], using the variable i, and perform the following steps:Store the boundaries of the query in the variables, say L and R, respectively.Find the position of the lowerbound of L and upperbound of R in the vector V.Print the difference between the positions of the upper bound of R and the lower bound of L, as the result.
Store the boundaries of the query in the variables, say L and R, respectively.
Find the position of the lowerbound of L and upperbound of R in the vector V.
Print the difference between the positions of the upper bound of R and the lower bound of L, as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to precomputevoid precompute(vector<long long>& v){ // Iterate over the range [0, 64] for (long long i = 0; i < 64; i++) { // Iterate over the range [0, 64] for (long long j = i + 1; j < 64; j++) { // Iterate over the range [0, 64] for (long long k = j + 1; k < 64; k++) { // Stores the number with set bits // i, j, and k long long int x = (1LL << i) | (1LL << j) | (1LL << k); // Check if the number is less // than 1e18 if (x <= 1e18 && x > 0) v.push_back(x); } } } // Sort the computed vector sort(v.begin(), v.end());} // Function to count number in the range// [l, r] having three set bitslong long query(long long l, long long r, vector<long long>& v){ // Find the lowerbound of l in v auto X = lower_bound(v.begin(), v.end(), l); // Find the upperbound of l in v auto Y = upper_bound(v.begin(), v.end(), r); // Return the difference // in their positions return (Y - X);}void PerformQuery(vector<pair<long long, long long> > arr, int N){ // Stores all the numbers in the range // [1, 1e18] having three set bits vector<long long> V; // Function call to perform the // precomputation precompute(V); // Iterate through each query for (auto it : arr) { long long L = it.first; long long R = it.second; // Print the answer cout << query(L, R, V) << "\n"; }} // Driver Codeint main(){ // Input vector<pair<long long, long long> > arr = { { 11, 19 }, { 14, 19 } }; int N = arr.size(); // Function call PerformQuery(arr, N); return 0;}
4
2
Time Complexity: O(N*log(633)+ 633)Auxiliary Space: O(633)
Bit Algorithms
setBitCount
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Hamming code Implementation in C/C++
Write an Efficient Method to Check if a Number is Multiple of 3
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24988,
"s": 24960,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 25190,
"s": 24988,
"text": "Given an array arr[] of N pairs, where each array element denotes a query of the form {L, R}, the task is to find the count of numbers in the range [L, R], having only 3-set bits for each query {L, R}."
},
{
"code": null,
"e": 25200,
"s": 25190,
"text": "Examples:"
},
{
"code": null,
"e": 25272,
"s": 25200,
"text": "Input: arr[] = {{11, 19}, {14, 19}}Output: 4 2Explanation: "
},
{
"code": null,
"e": 25441,
"s": 25272,
"text": "Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13, 14, 19}.Query(14, 19): Numbers in the range [14, 19] having three set bits are {14, 19}."
},
{
"code": null,
"e": 25530,
"s": 25441,
"text": "Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13, 14, 19}."
},
{
"code": null,
"e": 25611,
"s": 25530,
"text": "Query(14, 19): Numbers in the range [14, 19] having three set bits are {14, 19}."
},
{
"code": null,
"e": 25682,
"s": 25611,
"text": "Input: arr[] = {{1, 10}, {6, 12}}Output: 1 2Explanation: "
},
{
"code": null,
"e": 25833,
"s": 25682,
"text": "Query(1, 10): Numbers in the range [1, 10] having three set bits are {7}.Query(6, 12): Numbers in the range [6, 12] having three set bits are {7, 12}."
},
{
"code": null,
"e": 25907,
"s": 25833,
"text": "Query(1, 10): Numbers in the range [1, 10] having three set bits are {7}."
},
{
"code": null,
"e": 25985,
"s": 25907,
"text": "Query(6, 12): Numbers in the range [6, 12] having three set bits are {7, 12}."
},
{
"code": null,
"e": 26305,
"s": 25985,
"text": "Approach: The idea to solve this problem is to do a pre-computation and store all the numbers with only 3 bits set in the range [1, 1018], and then use binary search to find the position of lowerbound of L and upperbound of R and return the answer as there difference. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 26407,
"s": 26305,
"text": "Initialize a vector, say V, to store all the numbers in the range [1, 1018] with only three bits set."
},
{
"code": null,
"e": 26700,
"s": 26407,
"text": "Iterate over every triplet formed of the relation [0, 63]×[0, 63]×[0, 63] using variables i, j, and k and perform the following steps:If i, j, and k are distinct, then compute the number with the ith, jth, and kth bit set, and if the number is less than 1018, push the number in the vector V."
},
{
"code": null,
"e": 26859,
"s": 26700,
"text": "If i, j, and k are distinct, then compute the number with the ith, jth, and kth bit set, and if the number is less than 1018, push the number in the vector V."
},
{
"code": null,
"e": 26897,
"s": 26859,
"text": "Sort the vector V in ascending order."
},
{
"code": null,
"e": 27240,
"s": 26897,
"text": "Traverse the array arr[], using the variable i, and perform the following steps:Store the boundaries of the query in the variables, say L and R, respectively.Find the position of the lowerbound of L and upperbound of R in the vector V.Print the difference between the positions of the upper bound of R and the lower bound of L, as the result."
},
{
"code": null,
"e": 27319,
"s": 27240,
"text": "Store the boundaries of the query in the variables, say L and R, respectively."
},
{
"code": null,
"e": 27397,
"s": 27319,
"text": "Find the position of the lowerbound of L and upperbound of R in the vector V."
},
{
"code": null,
"e": 27505,
"s": 27397,
"text": "Print the difference between the positions of the upper bound of R and the lower bound of L, as the result."
},
{
"code": null,
"e": 27556,
"s": 27505,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27560,
"s": 27556,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to precomputevoid precompute(vector<long long>& v){ // Iterate over the range [0, 64] for (long long i = 0; i < 64; i++) { // Iterate over the range [0, 64] for (long long j = i + 1; j < 64; j++) { // Iterate over the range [0, 64] for (long long k = j + 1; k < 64; k++) { // Stores the number with set bits // i, j, and k long long int x = (1LL << i) | (1LL << j) | (1LL << k); // Check if the number is less // than 1e18 if (x <= 1e18 && x > 0) v.push_back(x); } } } // Sort the computed vector sort(v.begin(), v.end());} // Function to count number in the range// [l, r] having three set bitslong long query(long long l, long long r, vector<long long>& v){ // Find the lowerbound of l in v auto X = lower_bound(v.begin(), v.end(), l); // Find the upperbound of l in v auto Y = upper_bound(v.begin(), v.end(), r); // Return the difference // in their positions return (Y - X);}void PerformQuery(vector<pair<long long, long long> > arr, int N){ // Stores all the numbers in the range // [1, 1e18] having three set bits vector<long long> V; // Function call to perform the // precomputation precompute(V); // Iterate through each query for (auto it : arr) { long long L = it.first; long long R = it.second; // Print the answer cout << query(L, R, V) << \"\\n\"; }} // Driver Codeint main(){ // Input vector<pair<long long, long long> > arr = { { 11, 19 }, { 14, 19 } }; int N = arr.size(); // Function call PerformQuery(arr, N); return 0;}",
"e": 29448,
"s": 27560,
"text": null
},
{
"code": null,
"e": 29452,
"s": 29448,
"text": "4\n2"
},
{
"code": null,
"e": 29511,
"s": 29452,
"text": "Time Complexity: O(N*log(633)+ 633)Auxiliary Space: O(633)"
},
{
"code": null,
"e": 29526,
"s": 29511,
"text": "Bit Algorithms"
},
{
"code": null,
"e": 29538,
"s": 29526,
"text": "setBitCount"
},
{
"code": null,
"e": 29548,
"s": 29538,
"text": "Bit Magic"
},
{
"code": null,
"e": 29561,
"s": 29548,
"text": "Mathematical"
},
{
"code": null,
"e": 29574,
"s": 29561,
"text": "Mathematical"
},
{
"code": null,
"e": 29584,
"s": 29574,
"text": "Bit Magic"
},
{
"code": null,
"e": 29682,
"s": 29584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29733,
"s": 29682,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29770,
"s": 29733,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 29793,
"s": 29770,
"text": "Program to find parity"
},
{
"code": null,
"e": 29830,
"s": 29793,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 29894,
"s": 29830,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 29924,
"s": 29894,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29984,
"s": 29924,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29999,
"s": 29984,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30042,
"s": 29999,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to query MySQL on the current week?
|
To query MySQL on the current week, you can use YEARWEEK() function.
The syntax is as follows
SELECT *FROM yourTableName WHERE YEARWEEK(yourDateColumnName) = YEARWEEK(NOW());
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table currentWeekDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(20),
-> UserPostDate date
-> );
Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into currentWeekDemo(UserName,UserPostDate) values('Carol','2010-01-06');
Query OK, 1 row affected (0.20 sec)
mysql> insert into currentWeekDemo(UserName,UserPostDate) values('Bob','2019-06-04');
Query OK, 1 row affected (0.17 sec)
mysql> insert into currentWeekDemo(UserName,UserPostDate) values('David','2019-03-06');
Query OK, 1 row affected (0.16 sec)
mysql> insert into currentWeekDemo(UserName,UserPostDate) values('Maxwell','2018-04-21');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from currentWeekDemo;
The following is the output
+--------+----------+--------------+
| UserId | UserName | UserPostDate |
+--------+----------+--------------+
| 1 | Carol | 2010-01-06 |
| 2 | Bob | 2019-06-04 |
| 3 | David | 2019-03-06 |
| 4 | Maxwell | 2018-04-21 |
+--------+----------+--------------+
4 rows in set (0.00 sec)
The following is how you can query MySQL on the current week
mysql> select *from currentWeekDemo WHERE YEARWEEK(UserPostDate) = YEARWEEK(NOW());
The following is the output
+--------+----------+--------------+
| UserId | UserName | UserPostDate |
+--------+----------+--------------+
| 3 | David | 2019-03-06 |
+--------+----------+--------------+
1 row in set (0.05 sec)
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To query MySQL on the current week, you can use YEARWEEK() function."
},
{
"code": null,
"e": 1156,
"s": 1131,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1237,
"s": 1156,
"text": "SELECT *FROM yourTableName WHERE YEARWEEK(yourDateColumnName) = YEARWEEK(NOW());"
},
{
"code": null,
"e": 1334,
"s": 1237,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1530,
"s": 1334,
"text": "mysql> create table currentWeekDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserName varchar(20),\n -> UserPostDate date\n -> );\nQuery OK, 0 rows affected (0.68 sec)"
},
{
"code": null,
"e": 1611,
"s": 1530,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2107,
"s": 1611,
"text": "mysql> insert into currentWeekDemo(UserName,UserPostDate) values('Carol','2010-01-06');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into currentWeekDemo(UserName,UserPostDate) values('Bob','2019-06-04');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into currentWeekDemo(UserName,UserPostDate) values('David','2019-03-06');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into currentWeekDemo(UserName,UserPostDate) values('Maxwell','2018-04-21');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2192,
"s": 2107,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2229,
"s": 2192,
"text": "mysql> select *from currentWeekDemo;"
},
{
"code": null,
"e": 2257,
"s": 2229,
"text": "The following is the output"
},
{
"code": null,
"e": 2578,
"s": 2257,
"text": "+--------+----------+--------------+\n| UserId | UserName | UserPostDate |\n+--------+----------+--------------+\n| 1 | Carol | 2010-01-06 |\n| 2 | Bob | 2019-06-04 |\n| 3 | David | 2019-03-06 |\n| 4 | Maxwell | 2018-04-21 |\n+--------+----------+--------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2639,
"s": 2578,
"text": "The following is how you can query MySQL on the current week"
},
{
"code": null,
"e": 2723,
"s": 2639,
"text": "mysql> select *from currentWeekDemo WHERE YEARWEEK(UserPostDate) = YEARWEEK(NOW());"
},
{
"code": null,
"e": 2751,
"s": 2723,
"text": "The following is the output"
},
{
"code": null,
"e": 2960,
"s": 2751,
"text": "+--------+----------+--------------+\n| UserId | UserName | UserPostDate |\n+--------+----------+--------------+\n| 3 | David | 2019-03-06 |\n+--------+----------+--------------+\n1 row in set (0.05 sec)"
}
] |
C/C++ while loop with Examples - GeeksforGeeks
|
22 Nov, 2019
Loops in C/C++ come into use when we need to repeatedly execute a block of statements.
During the study of ‘for’ loop in C or C++, we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. The while loop in C/C++ is used in situations where we do not know the exact number of iterations of loop beforehand. The loop execution is terminated on the basis of the test condition.
Syntax:
while (test_expression)
{
// statements
update_expression;
}
The various parts of the While loop are:
Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop.Example:i <= 10Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;
Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop.Example:i <= 10
i <= 10
Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;
i++;
How does a While loop executes?
Control falls into the while loop.The flow jumps to ConditionCondition is tested.If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.Updation takes place.Control flows back to Step 2.The do-while loop has ended and the flow has gone outside.
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The do-while loop has ended and the flow has gone outside.
Flowchart while loop (for Control Flow):
Example 1: This program will try to print “Hello World” 5 times.
C
C++
// C program to illustrate while loop #include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i < 6) { printf("Hello World\n"); // update expression i++; } return 0;}
// C++ program to illustrate while loop #include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i < 6) { cout << "Hello World\n"; // update expression i++; } return 0;}
Hello World
Hello World
Hello World
Hello World
Hello World
Dry-Running Example 1: The program will execute in the following manner.
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop to return 0.
Example 2:
C
C++
// C program to illustrate while loop #include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i > -5) { printf("%d\n", i); // update expression i--; } return 0;}
// C++ program to illustrate while loop #include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i > -5) { cout << i << "\n"; // update expression i--; } return 0;}
1
0
-1
-2
-3
-4
Related Articles:
Loops in C and C++C/C++ For loop with ExamplesC/C++ do while loop with ExamplesDifference between while and do-while loop in C, C++, JavaDifference between for and while loop in C, C++, Java
Loops in C and C++
C/C++ For loop with Examples
C/C++ do while loop with Examples
Difference between while and do-while loop in C, C++, Java
Difference between for and while loop in C, C++, Java
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 23908,
"s": 23880,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 23995,
"s": 23908,
"text": "Loops in C/C++ come into use when we need to repeatedly execute a block of statements."
},
{
"code": null,
"e": 24370,
"s": 23995,
"text": "During the study of ‘for’ loop in C or C++, we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. The while loop in C/C++ is used in situations where we do not know the exact number of iterations of loop beforehand. The loop execution is terminated on the basis of the test condition."
},
{
"code": null,
"e": 24378,
"s": 24370,
"text": "Syntax:"
},
{
"code": null,
"e": 24446,
"s": 24378,
"text": "while (test_expression)\n{\n // statements\n \n update_expression;\n}"
},
{
"code": null,
"e": 24487,
"s": 24446,
"text": "The various parts of the While loop are:"
},
{
"code": null,
"e": 24852,
"s": 24487,
"text": "Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop.Example:i <= 10Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;"
},
{
"code": null,
"e": 25085,
"s": 24852,
"text": "Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop.Example:i <= 10"
},
{
"code": null,
"e": 25093,
"s": 25085,
"text": "i <= 10"
},
{
"code": null,
"e": 25226,
"s": 25093,
"text": "Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;"
},
{
"code": null,
"e": 25231,
"s": 25226,
"text": "i++;"
},
{
"code": null,
"e": 25263,
"s": 25231,
"text": "How does a While loop executes?"
},
{
"code": null,
"e": 25620,
"s": 25263,
"text": "Control falls into the while loop.The flow jumps to ConditionCondition is tested.If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.Updation takes place.Control flows back to Step 2.The do-while loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 25655,
"s": 25620,
"text": "Control falls into the while loop."
},
{
"code": null,
"e": 25683,
"s": 25655,
"text": "The flow jumps to Condition"
},
{
"code": null,
"e": 25815,
"s": 25683,
"text": "Condition is tested.If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 25927,
"s": 25815,
"text": "If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 25982,
"s": 25927,
"text": "If Condition yields true, the flow goes into the Body."
},
{
"code": null,
"e": 26040,
"s": 25982,
"text": "If Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 26097,
"s": 26040,
"text": "The statements inside the body of the loop get executed."
},
{
"code": null,
"e": 26119,
"s": 26097,
"text": "Updation takes place."
},
{
"code": null,
"e": 26149,
"s": 26119,
"text": "Control flows back to Step 2."
},
{
"code": null,
"e": 26208,
"s": 26149,
"text": "The do-while loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 26249,
"s": 26208,
"text": "Flowchart while loop (for Control Flow):"
},
{
"code": null,
"e": 26314,
"s": 26249,
"text": "Example 1: This program will try to print “Hello World” 5 times."
},
{
"code": null,
"e": 26316,
"s": 26314,
"text": "C"
},
{
"code": null,
"e": 26320,
"s": 26316,
"text": "C++"
},
{
"code": "// C program to illustrate while loop #include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i < 6) { printf(\"Hello World\\n\"); // update expression i++; } return 0;}",
"e": 26575,
"s": 26320,
"text": null
},
{
"code": "// C++ program to illustrate while loop #include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i < 6) { cout << \"Hello World\\n\"; // update expression i++; } return 0;}",
"e": 26853,
"s": 26575,
"text": null
},
{
"code": null,
"e": 26914,
"s": 26853,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World\n"
},
{
"code": null,
"e": 26987,
"s": 26914,
"text": "Dry-Running Example 1: The program will execute in the following manner."
},
{
"code": null,
"e": 27746,
"s": 26987,
"text": "1. Program starts.\n2. i is initialized with value 1.\n3. Condition is checked. 1 < 6 yields true.\n 3.a) \"Hello World\" gets printed 1st time.\n 3.b) Updation is done. Now i = 2.\n4. Condition is checked. 2 < 6 yields true.\n 4.a) \"Hello World\" gets printed 2nd time.\n 4.b) Updation is done. Now i = 3.\n5. Condition is checked. 3 < 6 yields true.\n 5.a) \"Hello World\" gets printed 3rd time\n 5.b) Updation is done. Now i = 4.\n6. Condition is checked. 4 < 6 yields true.\n 6.a) \"Hello World\" gets printed 4th time\n 6.b) Updation is done. Now i = 5.\n7. Condition is checked. 5 < 6 yields true.\n 7.a) \"Hello World\" gets printed 5th time\n 7.b) Updation is done. Now i = 6.\n8. Condition is checked. 6 < 6 yields false.\n9. Flow goes outside the loop to return 0.\n"
},
{
"code": null,
"e": 27757,
"s": 27746,
"text": "Example 2:"
},
{
"code": null,
"e": 27759,
"s": 27757,
"text": "C"
},
{
"code": null,
"e": 27763,
"s": 27759,
"text": "C++"
},
{
"code": "// C program to illustrate while loop #include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i > -5) { printf(\"%d\\n\", i); // update expression i--; } return 0;}",
"e": 28011,
"s": 27763,
"text": null
},
{
"code": "// C++ program to illustrate while loop #include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i > -5) { cout << i << \"\\n\"; // update expression i--; } return 0;}",
"e": 28284,
"s": 28011,
"text": null
},
{
"code": null,
"e": 28301,
"s": 28284,
"text": "1\n0\n-1\n-2\n-3\n-4\n"
},
{
"code": null,
"e": 28319,
"s": 28301,
"text": "Related Articles:"
},
{
"code": null,
"e": 28510,
"s": 28319,
"text": "Loops in C and C++C/C++ For loop with ExamplesC/C++ do while loop with ExamplesDifference between while and do-while loop in C, C++, JavaDifference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 28529,
"s": 28510,
"text": "Loops in C and C++"
},
{
"code": null,
"e": 28558,
"s": 28529,
"text": "C/C++ For loop with Examples"
},
{
"code": null,
"e": 28592,
"s": 28558,
"text": "C/C++ do while loop with Examples"
},
{
"code": null,
"e": 28651,
"s": 28592,
"text": "Difference between while and do-while loop in C, C++, Java"
},
{
"code": null,
"e": 28705,
"s": 28651,
"text": "Difference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 28716,
"s": 28705,
"text": "C Language"
},
{
"code": null,
"e": 28720,
"s": 28716,
"text": "C++"
},
{
"code": null,
"e": 28739,
"s": 28720,
"text": "School Programming"
},
{
"code": null,
"e": 28743,
"s": 28739,
"text": "CPP"
},
{
"code": null,
"e": 28841,
"s": 28743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28850,
"s": 28841,
"text": "Comments"
},
{
"code": null,
"e": 28863,
"s": 28850,
"text": "Old Comments"
},
{
"code": null,
"e": 28898,
"s": 28863,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28926,
"s": 28898,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28972,
"s": 28926,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28984,
"s": 28972,
"text": "fork() in C"
},
{
"code": null,
"e": 29024,
"s": 28984,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29042,
"s": 29024,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29088,
"s": 29042,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29131,
"s": 29088,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29150,
"s": 29131,
"text": "Inheritance in C++"
}
] |
\small - Tex Command
|
\small - Used to turn on small size.
{ \small ...}
\small command turn on small size.
\rm\tiny tiny \Tiny Tiny
\small small \normalsize normal
\large lg \Large Lg \LARGE LG
\huge hg \Huge Hg
tinyTinysmallnormallgLgLGhgHg
\def\myExp{\alpha\frac xy}
\tiny\myExp \Tiny\myExp
\small\myExp \normalsize\myExp
\large\myExp \Large\myExp \LARGE\myExp
\huge\myExp \Huge\myExp
αxyαxyαxyαxyαxyαxyαxyαxyαxy
ab{\small cd} cd
abcdcd
ab\small{cd} cd
abcdcd
\rm\tiny tiny \Tiny Tiny
\small small \normalsize normal
\large lg \Large Lg \LARGE LG
\huge hg \Huge Hg
tinyTinysmallnormallgLgLGhgHg
\rm\tiny tiny \Tiny Tiny
\small small \normalsize normal
\large lg \Large Lg \LARGE LG
\huge hg \Huge Hg
\def\myExp{\alpha\frac xy}
\tiny\myExp \Tiny\myExp
\small\myExp \normalsize\myExp
\large\myExp \Large\myExp \LARGE\myExp
\huge\myExp \Huge\myExp
αxyαxyαxyαxyαxyαxyαxyαxyαxy
\def\myExp{\alpha\frac xy}
\tiny\myExp \Tiny\myExp
\small\myExp \normalsize\myExp
\large\myExp \Large\myExp \LARGE\myExp
\huge\myExp \Huge\myExp
ab{\small cd} cd
abcdcd
ab{\small cd} cd
ab\small{cd} cd
abcdcd
ab\small{cd} cd
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": 8023,
"s": 7986,
"text": "\\small - Used to turn on small size."
},
{
"code": null,
"e": 8037,
"s": 8023,
"text": "{ \\small ...}"
},
{
"code": null,
"e": 8072,
"s": 8037,
"text": "\\small command turn on small size."
},
{
"code": null,
"e": 8441,
"s": 8072,
"text": "\n\\rm\\tiny tiny \\Tiny Tiny\n\\small small \\normalsize normal\n\\large lg \\Large Lg \\LARGE LG\n\\huge hg \\Huge Hg\n\ntinyTinysmallnormallgLgLGhgHg\n\n\n\\def\\myExp{\\alpha\\frac xy}\n\\tiny\\myExp \\Tiny\\myExp\n\\small\\myExp \\normalsize\\myExp\n\\large\\myExp \\Large\\myExp \\LARGE\\myExp\n\\huge\\myExp \\Huge\\myExp\n\nαxyαxyαxyαxyαxyαxyαxyαxyαxy\n\n\nab{\\small cd} cd\n\nabcdcd\n\n\nab\\small{cd} cd\n\nabcdcd\n\n\n"
},
{
"code": null,
"e": 8579,
"s": 8441,
"text": "\\rm\\tiny tiny \\Tiny Tiny\n\\small small \\normalsize normal\n\\large lg \\Large Lg \\LARGE LG\n\\huge hg \\Huge Hg\n\ntinyTinysmallnormallgLgLGhgHg\n\n"
},
{
"code": null,
"e": 8684,
"s": 8579,
"text": "\\rm\\tiny tiny \\Tiny Tiny\n\\small small \\normalsize normal\n\\large lg \\Large Lg \\LARGE LG\n\\huge hg \\Huge Hg"
},
{
"code": null,
"e": 8860,
"s": 8684,
"text": "\\def\\myExp{\\alpha\\frac xy}\n\\tiny\\myExp \\Tiny\\myExp\n\\small\\myExp \\normalsize\\myExp\n\\large\\myExp \\Large\\myExp \\LARGE\\myExp\n\\huge\\myExp \\Huge\\myExp\n\nαxyαxyαxyαxyαxyαxyαxyαxyαxy\n\n"
},
{
"code": null,
"e": 9005,
"s": 8860,
"text": "\\def\\myExp{\\alpha\\frac xy}\n\\tiny\\myExp \\Tiny\\myExp\n\\small\\myExp \\normalsize\\myExp\n\\large\\myExp \\Large\\myExp \\LARGE\\myExp\n\\huge\\myExp \\Huge\\myExp"
},
{
"code": null,
"e": 9032,
"s": 9005,
"text": "ab{\\small cd} cd\n\nabcdcd\n\n"
},
{
"code": null,
"e": 9049,
"s": 9032,
"text": "ab{\\small cd} cd"
},
{
"code": null,
"e": 9075,
"s": 9049,
"text": "ab\\small{cd} cd\n\nabcdcd\n\n"
},
{
"code": null,
"e": 9091,
"s": 9075,
"text": "ab\\small{cd} cd"
},
{
"code": null,
"e": 9123,
"s": 9091,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 9136,
"s": 9123,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9169,
"s": 9136,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9182,
"s": 9169,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9214,
"s": 9182,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9250,
"s": 9214,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 9285,
"s": 9250,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9302,
"s": 9285,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 9335,
"s": 9302,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9349,
"s": 9335,
"text": " Daniel Stern"
},
{
"code": null,
"e": 9381,
"s": 9349,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 9396,
"s": 9381,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 9403,
"s": 9396,
"text": " Print"
},
{
"code": null,
"e": 9414,
"s": 9403,
"text": " Add Notes"
}
] |
How to Publish a Python Package to PyPI using Poetry | by Edward Krueger | Towards Data Science
|
By: Edward Krueger and Dylan Rossi
Have you ever wanted to create a python package for the world to use but thought it was too difficult to get published? Poetry can alleviate your worries with how simple they make the process.
Once you have your package created, Poetry will take the wheel (yes, that is a pun) and do the publishing work for you.
Note: This article will assume you have already built a python package with Poetry that is ready for publishing. If you do not have a package already created, please download our example and follow along.
To publish a python package to PyPI, you must first have a PyPI account.
If you do not have one created, head over to PyPI and click on the Register link.
They will ask for the usual information (email, username, password) and register your account.
You should also receive an email from them asking you to confirm your account registration.
Once you are fully registered, sign in and head over to your account page.
You now need to create an API token to connect to Poetry. This token will allow Poetry to know where to publish your package and also give it access/permission to publish to your account.
From your account page, click on the “Account Settings” link on the left-hand side.
Scroll down until you see the “API Tokens” section and click the “Add API Token” button.
You will then give your token a name and scope.
For this example, we are naming the token “poetrypackagetemplate.”
You will also set the scope to “Entire Account (all projects),” but in practice, it is better to select one token per project instead (which is why it will notify you with a cautionary message).
After this is filled in, create the API token by clicking the “Add Token” button.
PyPI will generate your API token and display it on your screen, but only for now, so be sure to copy it or leave this page open until we connect it to Poetry.
Now that you have an API token connected to your PyPI account, we can give this token to Poetry, so it knows where to publish your package. We can do this by creating environment variables that will save your credentials which we can then pass to Poetry’s publish command.
Go ahead and open up Terminal (git-bash on Windows) and make sure you are in the directory of either your python package or our example one.
Then run these commands on macOS or Linux:
export PYPI_USERNAME=__token__export PYPI_PASSWORD=<Your API Token>
Run these commands (on Windows):
set PYPI_USERNAME=__token__set PYPI_PASSWORD=<Your API Token>
That is it! Poetry is now ready to publish your python package to PyPI.
To finalize your publication, you will need to run one more command.
poetry publish --build --username $PYPI_USERNAME --password $PYPI_PASSWORD
Poetry will then begin the process to build and publish your python package to PyPI.
Once it finishes, your package will be on your PyPI account and available to install via pip!
As you can see from this brief article, publishing your python package to PyPI is a breeze with Poetry.
If you want, you can test out installing your newly published package by simply running
pip install <Your Package Name>
Congratulations on publishing your python package!
Check out this article by Christopher Sidebottom if you want some more information on Poetry:
|
[
{
"code": null,
"e": 207,
"s": 172,
"text": "By: Edward Krueger and Dylan Rossi"
},
{
"code": null,
"e": 400,
"s": 207,
"text": "Have you ever wanted to create a python package for the world to use but thought it was too difficult to get published? Poetry can alleviate your worries with how simple they make the process."
},
{
"code": null,
"e": 520,
"s": 400,
"text": "Once you have your package created, Poetry will take the wheel (yes, that is a pun) and do the publishing work for you."
},
{
"code": null,
"e": 725,
"s": 520,
"text": "Note: This article will assume you have already built a python package with Poetry that is ready for publishing. If you do not have a package already created, please download our example and follow along."
},
{
"code": null,
"e": 798,
"s": 725,
"text": "To publish a python package to PyPI, you must first have a PyPI account."
},
{
"code": null,
"e": 880,
"s": 798,
"text": "If you do not have one created, head over to PyPI and click on the Register link."
},
{
"code": null,
"e": 975,
"s": 880,
"text": "They will ask for the usual information (email, username, password) and register your account."
},
{
"code": null,
"e": 1067,
"s": 975,
"text": "You should also receive an email from them asking you to confirm your account registration."
},
{
"code": null,
"e": 1142,
"s": 1067,
"text": "Once you are fully registered, sign in and head over to your account page."
},
{
"code": null,
"e": 1330,
"s": 1142,
"text": "You now need to create an API token to connect to Poetry. This token will allow Poetry to know where to publish your package and also give it access/permission to publish to your account."
},
{
"code": null,
"e": 1414,
"s": 1330,
"text": "From your account page, click on the “Account Settings” link on the left-hand side."
},
{
"code": null,
"e": 1503,
"s": 1414,
"text": "Scroll down until you see the “API Tokens” section and click the “Add API Token” button."
},
{
"code": null,
"e": 1551,
"s": 1503,
"text": "You will then give your token a name and scope."
},
{
"code": null,
"e": 1618,
"s": 1551,
"text": "For this example, we are naming the token “poetrypackagetemplate.”"
},
{
"code": null,
"e": 1813,
"s": 1618,
"text": "You will also set the scope to “Entire Account (all projects),” but in practice, it is better to select one token per project instead (which is why it will notify you with a cautionary message)."
},
{
"code": null,
"e": 1895,
"s": 1813,
"text": "After this is filled in, create the API token by clicking the “Add Token” button."
},
{
"code": null,
"e": 2055,
"s": 1895,
"text": "PyPI will generate your API token and display it on your screen, but only for now, so be sure to copy it or leave this page open until we connect it to Poetry."
},
{
"code": null,
"e": 2328,
"s": 2055,
"text": "Now that you have an API token connected to your PyPI account, we can give this token to Poetry, so it knows where to publish your package. We can do this by creating environment variables that will save your credentials which we can then pass to Poetry’s publish command."
},
{
"code": null,
"e": 2469,
"s": 2328,
"text": "Go ahead and open up Terminal (git-bash on Windows) and make sure you are in the directory of either your python package or our example one."
},
{
"code": null,
"e": 2512,
"s": 2469,
"text": "Then run these commands on macOS or Linux:"
},
{
"code": null,
"e": 2580,
"s": 2512,
"text": "export PYPI_USERNAME=__token__export PYPI_PASSWORD=<Your API Token>"
},
{
"code": null,
"e": 2613,
"s": 2580,
"text": "Run these commands (on Windows):"
},
{
"code": null,
"e": 2675,
"s": 2613,
"text": "set PYPI_USERNAME=__token__set PYPI_PASSWORD=<Your API Token>"
},
{
"code": null,
"e": 2747,
"s": 2675,
"text": "That is it! Poetry is now ready to publish your python package to PyPI."
},
{
"code": null,
"e": 2816,
"s": 2747,
"text": "To finalize your publication, you will need to run one more command."
},
{
"code": null,
"e": 2891,
"s": 2816,
"text": "poetry publish --build --username $PYPI_USERNAME --password $PYPI_PASSWORD"
},
{
"code": null,
"e": 2976,
"s": 2891,
"text": "Poetry will then begin the process to build and publish your python package to PyPI."
},
{
"code": null,
"e": 3070,
"s": 2976,
"text": "Once it finishes, your package will be on your PyPI account and available to install via pip!"
},
{
"code": null,
"e": 3174,
"s": 3070,
"text": "As you can see from this brief article, publishing your python package to PyPI is a breeze with Poetry."
},
{
"code": null,
"e": 3262,
"s": 3174,
"text": "If you want, you can test out installing your newly published package by simply running"
},
{
"code": null,
"e": 3294,
"s": 3262,
"text": "pip install <Your Package Name>"
},
{
"code": null,
"e": 3345,
"s": 3294,
"text": "Congratulations on publishing your python package!"
}
] |
Ways to concatenate tuples in Python
|
When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.
The '+' operator can be used to add numeric values or concatenate strings.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = (11, 14, 0, 78, 33, 11)
my_tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)
my_result = my_tuple_1 + my_tuple_2
print("The tuple after concatenation is : " )
print(my_result)
The first tuple is :
(11, 14, 0, 78, 33, 11)
The second tuple is :
(10, 78, 0, 56, 8, 34)
The tuple after concatenation is :
(11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)
Two tuples are defined and are displayed on the console.
They are concatenated using the '+' operator.
This is assigned to a value.
It is displayed on the console.
|
[
{
"code": null,
"e": 1383,
"s": 1062,
"text": "When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access."
},
{
"code": null,
"e": 1458,
"s": 1383,
"text": "The '+' operator can be used to add numeric values or concatenate strings."
},
{
"code": null,
"e": 1497,
"s": 1458,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1507,
"s": 1497,
"text": "Live Demo"
},
{
"code": null,
"e": 1781,
"s": 1507,
"text": "my_tuple_1 = (11, 14, 0, 78, 33, 11)\nmy_tuple_2 = (10, 78, 0, 56, 8, 34)\n\nprint(\"The first tuple is : \")\nprint(my_tuple_1)\nprint(\"The second tuple is : \")\nprint(my_tuple_2)\n\nmy_result = my_tuple_1 + my_tuple_2\n\nprint(\"The tuple after concatenation is : \" )\nprint(my_result)"
},
{
"code": null,
"e": 1952,
"s": 1781,
"text": "The first tuple is :\n(11, 14, 0, 78, 33, 11)\nThe second tuple is :\n(10, 78, 0, 56, 8, 34)\nThe tuple after concatenation is :\n(11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)"
},
{
"code": null,
"e": 2009,
"s": 1952,
"text": "Two tuples are defined and are displayed on the console."
},
{
"code": null,
"e": 2055,
"s": 2009,
"text": "They are concatenated using the '+' operator."
},
{
"code": null,
"e": 2084,
"s": 2055,
"text": "This is assigned to a value."
},
{
"code": null,
"e": 2116,
"s": 2084,
"text": "It is displayed on the console."
}
] |
How to Add Labels in a Plot using Python? - GeeksforGeeks
|
20 Oct, 2021
Prerequisites: Python Matplotlib
In this article, we will discuss adding labels to the plot using Matplotlib in Python. But first, understand what are labels in a plot. The heading or sub-heading written at the vertical axis (say Y-axis) and the horizontal axis(say X-axis) improves the quality of understanding of plotted stats.
Example: Let’s create a simple plot
Python
# python program to plot graph without labels
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# it will take x coordinates by default
# starting from 0,1,2,3,4...
y = np.array([3, 8, 1, 10])
plt.plot(y)
plt.show()
Output:
Plot without Labels or Title
By using pyplot() function of library we can add xlabel() and ylabel() to set x and y labels.
Example: Let’s add Label in the above Plot
Python
# python program for plots with label
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Number of children it was default in earlier case
x = np.array([0, 1, 2, 3])
# Number of families
y = np.array([3, 8, 1, 10])
plt.plot(x, y)
# Label for x-axis
plt.xlabel("Number of Childerns")
# Label for y-axis
plt.ylabel("Number of Families")
plt.show() # for display
Output:
Plot with Labels
If you would like to make it more understandable, add a Title to the plot, by just adding a single line of code.
plt.title("Survey Of Colony")
Example:
Python3
# python program for plots with label
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Number of children it was default in earlier case
x = np.array([0, 1, 2, 3])
# Number of families
y = np.array([3, 8, 1, 10])
plt.plot(x, y)
# Label for x-axis
plt.xlabel("Number of Childerns")
# Label for y-axis
plt.ylabel("Number of Families")
# title of the plot
plt.title("Survey Of Colony")
plt.show() # for display
Output:
Plot with Title
In order to make the Plot more attractive use the fontdict parameter in xlabel(), ylabel(), and title() to apply the font properties.
Python
# Adding font properties to labels and titles
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Number of Children
x = np.array([0, 1, 2, 3])
# Number of Families
y = np.array([3, 8, 1, 10])
# label including this form1 will have these properties
form1 = {'family': 'serif', 'color': 'blue', 'size': 20}
# label including this form2 will have these properties
form2 = {'family': 'serif', 'color': 'darkred', 'size': 15}
plt.plot(x, y)
plt.xlabel("Number of Childerns", fontdict=form1)
plt.ylabel("Number of Families", fontdict=form1)
plt.title("Survey Of Colony", fontdict=form2)
plt.show()
Output:
Plot with Font Properties
surindertarika1234
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
|
[
{
"code": null,
"e": 25655,
"s": 25624,
"text": " \n20 Oct, 2021\n"
},
{
"code": null,
"e": 25689,
"s": 25655,
"text": "Prerequisites: Python Matplotlib "
},
{
"code": null,
"e": 25986,
"s": 25689,
"text": "In this article, we will discuss adding labels to the plot using Matplotlib in Python. But first, understand what are labels in a plot. The heading or sub-heading written at the vertical axis (say Y-axis) and the horizontal axis(say X-axis) improves the quality of understanding of plotted stats."
},
{
"code": null,
"e": 26022,
"s": 25986,
"text": "Example: Let’s create a simple plot"
},
{
"code": null,
"e": 26029,
"s": 26022,
"text": "Python"
},
{
"code": "\n\n\n\n\n\n\n# python program to plot graph without labels\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n \n \n# it will take x coordinates by default \n# starting from 0,1,2,3,4...\ny = np.array([3, 8, 1, 10])\n \nplt.plot(y)\nplt.show()\n\n\n\n\n\n",
"e": 26294,
"s": 26039,
"text": null
},
{
"code": null,
"e": 26302,
"s": 26294,
"text": "Output:"
},
{
"code": null,
"e": 26331,
"s": 26302,
"text": "Plot without Labels or Title"
},
{
"code": null,
"e": 26426,
"s": 26331,
"text": "By using pyplot() function of library we can add xlabel() and ylabel() to set x and y labels. "
},
{
"code": null,
"e": 26469,
"s": 26426,
"text": "Example: Let’s add Label in the above Plot"
},
{
"code": null,
"e": 26476,
"s": 26469,
"text": "Python"
},
{
"code": "\n\n\n\n\n\n\n# python program for plots with label\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n \n \n# Number of children it was default in earlier case\nx = np.array([0, 1, 2, 3])\n \n# Number of families\ny = np.array([3, 8, 1, 10])\n \nplt.plot(x, y)\n \n# Label for x-axis\nplt.xlabel(\"Number of Childerns\")\n \n# Label for y-axis\nplt.ylabel(\"Number of Families\")\n \nplt.show() # for display\n\n\n\n\n\n",
"e": 26894,
"s": 26486,
"text": null
},
{
"code": null,
"e": 26902,
"s": 26894,
"text": "Output:"
},
{
"code": null,
"e": 26919,
"s": 26902,
"text": "Plot with Labels"
},
{
"code": null,
"e": 27032,
"s": 26919,
"text": "If you would like to make it more understandable, add a Title to the plot, by just adding a single line of code."
},
{
"code": null,
"e": 27062,
"s": 27032,
"text": "plt.title(\"Survey Of Colony\")"
},
{
"code": null,
"e": 27071,
"s": 27062,
"text": "Example:"
},
{
"code": null,
"e": 27079,
"s": 27071,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# python program for plots with label\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n \n \n# Number of children it was default in earlier case\nx = np.array([0, 1, 2, 3])\n \n# Number of families\ny = np.array([3, 8, 1, 10])\n \nplt.plot(x, y)\n \n# Label for x-axis\nplt.xlabel(\"Number of Childerns\")\n \n# Label for y-axis\nplt.ylabel(\"Number of Families\")\n \n# title of the plot\nplt.title(\"Survey Of Colony\")\n \nplt.show() # for display\n\n\n\n\n\n",
"e": 27549,
"s": 27089,
"text": null
},
{
"code": null,
"e": 27561,
"s": 27553,
"text": "Output:"
},
{
"code": null,
"e": 27579,
"s": 27563,
"text": "Plot with Title"
},
{
"code": null,
"e": 27715,
"s": 27581,
"text": "In order to make the Plot more attractive use the fontdict parameter in xlabel(), ylabel(), and title() to apply the font properties."
},
{
"code": null,
"e": 27724,
"s": 27717,
"text": "Python"
},
{
"code": "\n\n\n\n\n\n\n# Adding font properties to labels and titles\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n \n \n# Number of Children\nx = np.array([0, 1, 2, 3])\n \n# Number of Families\ny = np.array([3, 8, 1, 10])\n \n# label including this form1 will have these properties\nform1 = {'family': 'serif', 'color': 'blue', 'size': 20}\n \n# label including this form2 will have these properties\nform2 = {'family': 'serif', 'color': 'darkred', 'size': 15}\n \nplt.plot(x, y)\nplt.xlabel(\"Number of Childerns\", fontdict=form1)\nplt.ylabel(\"Number of Families\", fontdict=form1)\nplt.title(\"Survey Of Colony\", fontdict=form2)\nplt.show()\n\n\n\n\n\n",
"e": 28371,
"s": 27734,
"text": null
},
{
"code": null,
"e": 28379,
"s": 28371,
"text": "Output:"
},
{
"code": null,
"e": 28405,
"s": 28379,
"text": "Plot with Font Properties"
},
{
"code": null,
"e": 28424,
"s": 28405,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28444,
"s": 28424,
"text": "\nPython-matplotlib\n"
},
{
"code": null,
"e": 28470,
"s": 28444,
"text": "\nTechnical Scripter 2020\n"
},
{
"code": null,
"e": 28479,
"s": 28470,
"text": "\nPython\n"
},
{
"code": null,
"e": 28500,
"s": 28479,
"text": "\nTechnical Scripter\n"
},
{
"code": null,
"e": 28705,
"s": 28500,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28737,
"s": 28705,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28779,
"s": 28737,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28821,
"s": 28779,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28877,
"s": 28821,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28904,
"s": 28877,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28935,
"s": 28904,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28964,
"s": 28935,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29003,
"s": 28964,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29039,
"s": 29003,
"text": "Python | Pandas dataframe.groupby()"
}
] |
arg() function for Complex Number in C++ - GeeksforGeeks
|
11 Oct, 2018
The arg() function for complex number is defined in the complex header file. This function is used to return the argument of the complex number z.
Syntax:
template<class T> T arg (const complex<T>& z);
Parameter:
z: It represents the given complex number.
Return: It returns the argument of the complex number.
Below programs illustrate the above function:-
Example 1:
// C++ program to demonstrate// example of arg() function. #include <bits/stdc++.h>using namespace std; int main (){ // defines the complex number: (5.0 + 12.0i) complex<double> complexnumber (5.0, 12.0); // prints the argument of the complex number cout << "The argument of " << complexnumber << " is: "; cout << arg(complexnumber) << endl; return 0;}
The argument of (5,12) is: 1.17601
Example 2:
// C++ program to demonstrate// example of arg() function #include <bits/stdc++.h>using namespace std; int main (){ // defines the complex number: (4.0+3.0i) complex<double> complexnumber (4.0, 3.0); // prints the argument of the complex number cout << "The argument of " << complexnumber << " is: "; cout << arg(complexnumber) << endl; return 0;}
The argument of (4,3) is: 0.643501
CPP-complex
CPP-Functions
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Destructors in C++
|
[
{
"code": null,
"e": 24196,
"s": 24168,
"text": "\n11 Oct, 2018"
},
{
"code": null,
"e": 24343,
"s": 24196,
"text": "The arg() function for complex number is defined in the complex header file. This function is used to return the argument of the complex number z."
},
{
"code": null,
"e": 24351,
"s": 24343,
"text": "Syntax:"
},
{
"code": null,
"e": 24399,
"s": 24351,
"text": "template<class T> T arg (const complex<T>& z);\n"
},
{
"code": null,
"e": 24410,
"s": 24399,
"text": "Parameter:"
},
{
"code": null,
"e": 24453,
"s": 24410,
"text": "z: It represents the given complex number."
},
{
"code": null,
"e": 24508,
"s": 24453,
"text": "Return: It returns the argument of the complex number."
},
{
"code": null,
"e": 24555,
"s": 24508,
"text": "Below programs illustrate the above function:-"
},
{
"code": null,
"e": 24566,
"s": 24555,
"text": "Example 1:"
},
{
"code": "// C++ program to demonstrate// example of arg() function. #include <bits/stdc++.h>using namespace std; int main (){ // defines the complex number: (5.0 + 12.0i) complex<double> complexnumber (5.0, 12.0); // prints the argument of the complex number cout << \"The argument of \" << complexnumber << \" is: \"; cout << arg(complexnumber) << endl; return 0;}",
"e": 24931,
"s": 24566,
"text": null
},
{
"code": null,
"e": 24967,
"s": 24931,
"text": "The argument of (5,12) is: 1.17601\n"
},
{
"code": null,
"e": 24978,
"s": 24967,
"text": "Example 2:"
},
{
"code": "// C++ program to demonstrate// example of arg() function #include <bits/stdc++.h>using namespace std; int main (){ // defines the complex number: (4.0+3.0i) complex<double> complexnumber (4.0, 3.0); // prints the argument of the complex number cout << \"The argument of \" << complexnumber << \" is: \"; cout << arg(complexnumber) << endl; return 0;}",
"e": 25338,
"s": 24978,
"text": null
},
{
"code": null,
"e": 25374,
"s": 25338,
"text": "The argument of (4,3) is: 0.643501\n"
},
{
"code": null,
"e": 25386,
"s": 25374,
"text": "CPP-complex"
},
{
"code": null,
"e": 25400,
"s": 25386,
"text": "CPP-Functions"
},
{
"code": null,
"e": 25412,
"s": 25400,
"text": "CPP-Library"
},
{
"code": null,
"e": 25416,
"s": 25412,
"text": "C++"
},
{
"code": null,
"e": 25420,
"s": 25416,
"text": "CPP"
},
{
"code": null,
"e": 25518,
"s": 25420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25546,
"s": 25518,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25566,
"s": 25546,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25599,
"s": 25566,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25623,
"s": 25599,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25648,
"s": 25623,
"text": "std::string class in C++"
},
{
"code": null,
"e": 25692,
"s": 25648,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25716,
"s": 25692,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 25769,
"s": 25716,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 25805,
"s": 25769,
"text": "Convert string to char array in C++"
}
] |
Dart Programming - HTML DOM
|
Every webpage resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
Window − Top of the hierarchy. It is the outmost element of the object hierarchy.
Window − Top of the hierarchy. It is the outmost element of the object hierarchy.
Document − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
Document − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
Elements − represent the content on a web page. Examples include the text boxes, page title etc.
Elements − represent the content on a web page. Examples include the text boxes, page title etc.
Nodes − are often elements, but they can also be attributes, text, comments, and other DOM types.
Nodes − are often elements, but they can also be attributes, text, comments, and other DOM types.
Here is a simple hierarchy of a few important DOM objects −
Dart provides the dart:html library to manipulate objects and elements in the DOM. Console-based applications cannot use the dart:html library. To use the HTML library in the web applications, import dart:html −
import 'dart:html';
Moving on, we will discuss some DOM Operations in the next section.
The dart:html library provides the querySelector function to search for elements in the DOM.
Element querySelector(String selectors);
The querySelector() function returns the first element that matches the specified group of selectors. "selectors should be string using CSS selector syntax as given below
var element1 = document.querySelector('.className');
var element2 = document.querySelector('#id');
Follow the steps given below, in the Webstorm IDE −
Step 1 − File NewProject → In the location, provide the project name as DemoWebApp.
Step 1 − In the section "Generate sample content", select SimpleWebApplication.
It will create a sample project, DemoWebApp. There is a pubspec.yaml file containing the dependencies which need to be downloaded.
name: 'DemoWebApp'
version: 0.0.1
description: An absolute bare-bones web app.
#author: Your Name <email@example.com>
#homepage: https://www.example.com
environment:
sdk: '>=1.0.0 <2.0.0'
dependencies:
browser: '>=0.10.0 <0.11.0' dart_to_js_script_rewriter: '^1.0.1'
transformers:
- dart_to_js_script_rewriter
If you are connected to Web, then these will be downloaded automatically, else you can right-click on the pubspec.yaml and get dependencies.
In the web folder, you will find three files: Index.html, main.dart, and style.css
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<meta name = "scaffolded-by" content = "https://github.com/google/stagehand">
<title>DemoWebApp</title>
<link rel = "stylesheet" href = "styles.css">
<script defer src = "main.dart" type = "application/dart"></script>
<script defer src = "packages/browser/dart.js"></script>
</head>
<body>
<h1>
<div id = "output"></div>
</h1>
</body>
</html>
import 'dart:html';
void main() {
querySelector('#output').text = 'Your Dart web dom app is running!!!.';
}
Run the index.html file; you will see the following output on your screen.
The dart:html library provides the onClick event for DOM Elements. The syntax shows how an element could handle a stream of click events.
querySelector('#Id').onClick.listen(eventHanlderFunction);
The querySelector() function returns the element from the given DOM and onClick.listen() will take an eventHandler method which will be invoked when a click event is raised. The syntax of eventHandler is given below −
void eventHanlderFunction (MouseEvent event){ }
Let us now take an example to understand the concept of Event Handling in Dart.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<meta name = "scaffolded-by" content ="https://github.com/google/stagehand">
<title>DemoWebApp</title>
<link rel = "stylesheet" href = "styles.css">
<script defer src = "TestEvent.dart" type="application/dart"></script>
<script defer src = "packages/browser/dart.js"></script>
</head>
<body>
<div id = "output"></div>
<h1>
<div>
Enter you name : <input type = "text" id = "txtName">
<input type = "button" id = "btnWish" value="Wish">
</div>
</h1>
<h2 id = "display"></h2>
</body>
</html>
import 'dart:html';
void main() {
querySelector('#btnWish').onClick.listen(wishHandler);
}
void wishHandler(MouseEvent event){
String name = (querySelector('#txtName') as InputElement).value;
querySelector('#display').text = 'Hello Mr.'+ name;
}
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2609,
"s": 2525,
"text": "Every webpage resides inside a browser window which can be considered as an object."
},
{
"code": null,
"e": 2821,
"s": 2609,
"text": "A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content."
},
{
"code": null,
"e": 3046,
"s": 2821,
"text": "The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document."
},
{
"code": null,
"e": 3128,
"s": 3046,
"text": "Window − Top of the hierarchy. It is the outmost element of the object hierarchy."
},
{
"code": null,
"e": 3210,
"s": 3128,
"text": "Window − Top of the hierarchy. It is the outmost element of the object hierarchy."
},
{
"code": null,
"e": 3346,
"s": 3210,
"text": "Document − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page."
},
{
"code": null,
"e": 3482,
"s": 3346,
"text": "Document − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page."
},
{
"code": null,
"e": 3579,
"s": 3482,
"text": "Elements − represent the content on a web page. Examples include the text boxes, page title etc."
},
{
"code": null,
"e": 3676,
"s": 3579,
"text": "Elements − represent the content on a web page. Examples include the text boxes, page title etc."
},
{
"code": null,
"e": 3774,
"s": 3676,
"text": "Nodes − are often elements, but they can also be attributes, text, comments, and other DOM types."
},
{
"code": null,
"e": 3872,
"s": 3774,
"text": "Nodes − are often elements, but they can also be attributes, text, comments, and other DOM types."
},
{
"code": null,
"e": 3932,
"s": 3872,
"text": "Here is a simple hierarchy of a few important DOM objects −"
},
{
"code": null,
"e": 4144,
"s": 3932,
"text": "Dart provides the dart:html library to manipulate objects and elements in the DOM. Console-based applications cannot use the dart:html library. To use the HTML library in the web applications, import dart:html −"
},
{
"code": null,
"e": 4165,
"s": 4144,
"text": "import 'dart:html';\n"
},
{
"code": null,
"e": 4233,
"s": 4165,
"text": "Moving on, we will discuss some DOM Operations in the next section."
},
{
"code": null,
"e": 4326,
"s": 4233,
"text": "The dart:html library provides the querySelector function to search for elements in the DOM."
},
{
"code": null,
"e": 4368,
"s": 4326,
"text": "Element querySelector(String selectors);\n"
},
{
"code": null,
"e": 4539,
"s": 4368,
"text": "The querySelector() function returns the first element that matches the specified group of selectors. \"selectors should be string using CSS selector syntax as given below"
},
{
"code": null,
"e": 4641,
"s": 4539,
"text": "var element1 = document.querySelector('.className'); \nvar element2 = document.querySelector('#id'); \n"
},
{
"code": null,
"e": 4693,
"s": 4641,
"text": "Follow the steps given below, in the Webstorm IDE −"
},
{
"code": null,
"e": 4777,
"s": 4693,
"text": "Step 1 − File NewProject → In the location, provide the project name as DemoWebApp."
},
{
"code": null,
"e": 4857,
"s": 4777,
"text": "Step 1 − In the section \"Generate sample content\", select SimpleWebApplication."
},
{
"code": null,
"e": 4988,
"s": 4857,
"text": "It will create a sample project, DemoWebApp. There is a pubspec.yaml file containing the dependencies which need to be downloaded."
},
{
"code": null,
"e": 5325,
"s": 4988,
"text": "name: 'DemoWebApp' \nversion: 0.0.1 \ndescription: An absolute bare-bones web app. \n\n#author: Your Name <email@example.com> \n#homepage: https://www.example.com \nenvironment: \n sdk: '>=1.0.0 <2.0.0' \ndependencies: \n browser: '>=0.10.0 <0.11.0' dart_to_js_script_rewriter: '^1.0.1' \ntransformers: \n- dart_to_js_script_rewriter "
},
{
"code": null,
"e": 5466,
"s": 5325,
"text": "If you are connected to Web, then these will be downloaded automatically, else you can right-click on the pubspec.yaml and get dependencies."
},
{
"code": null,
"e": 5549,
"s": 5466,
"text": "In the web folder, you will find three files: Index.html, main.dart, and style.css"
},
{
"code": null,
"e": 6209,
"s": 5549,
"text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset = \"utf-8\"> \n <meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\"> \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <meta name = \"scaffolded-by\" content = \"https://github.com/google/stagehand\">\n <title>DemoWebApp</title> \n <link rel = \"stylesheet\" href = \"styles.css\"> \n <script defer src = \"main.dart\" type = \"application/dart\"></script>\n <script defer src = \"packages/browser/dart.js\"></script> \n </head>\n \n <body> \n <h1>\n <div id = \"output\"></div> \n </h1> \n </body> \n</html> "
},
{
"code": null,
"e": 6327,
"s": 6209,
"text": "import 'dart:html'; \nvoid main() { \n querySelector('#output').text = 'Your Dart web dom app is running!!!.'; \n} "
},
{
"code": null,
"e": 6402,
"s": 6327,
"text": "Run the index.html file; you will see the following output on your screen."
},
{
"code": null,
"e": 6540,
"s": 6402,
"text": "The dart:html library provides the onClick event for DOM Elements. The syntax shows how an element could handle a stream of click events."
},
{
"code": null,
"e": 6601,
"s": 6540,
"text": "querySelector('#Id').onClick.listen(eventHanlderFunction); \n"
},
{
"code": null,
"e": 6819,
"s": 6601,
"text": "The querySelector() function returns the element from the given DOM and onClick.listen() will take an eventHandler method which will be invoked when a click event is raised. The syntax of eventHandler is given below −"
},
{
"code": null,
"e": 6869,
"s": 6819,
"text": "void eventHanlderFunction (MouseEvent event){ } \n"
},
{
"code": null,
"e": 6949,
"s": 6869,
"text": "Let us now take an example to understand the concept of Event Handling in Dart."
},
{
"code": null,
"e": 7787,
"s": 6949,
"text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset = \"utf-8\"> \n <meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\"> \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\"> \n <meta name = \"scaffolded-by\" content =\"https://github.com/google/stagehand\"> \n <title>DemoWebApp</title> \n <link rel = \"stylesheet\" href = \"styles.css\"> \n <script defer src = \"TestEvent.dart\" type=\"application/dart\"></script> \n <script defer src = \"packages/browser/dart.js\"></script> \n </head> \n \n <body> \n <div id = \"output\"></div> \n <h1> \n <div> \n Enter you name : <input type = \"text\" id = \"txtName\"> \n <input type = \"button\" id = \"btnWish\" value=\"Wish\"> \n </div> \n </h1> \n <h2 id = \"display\"></h2> \n </body>\n \n</html>"
},
{
"code": null,
"e": 8051,
"s": 7787,
"text": "import 'dart:html'; \nvoid main() { \n querySelector('#btnWish').onClick.listen(wishHandler); \n} \nvoid wishHandler(MouseEvent event){ \n String name = (querySelector('#txtName') as InputElement).value; \n querySelector('#display').text = 'Hello Mr.'+ name; \n}"
},
{
"code": null,
"e": 8086,
"s": 8051,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8106,
"s": 8086,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 8139,
"s": 8106,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8159,
"s": 8139,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 8192,
"s": 8159,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8209,
"s": 8192,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8244,
"s": 8209,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 8261,
"s": 8244,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8296,
"s": 8261,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8316,
"s": 8296,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8349,
"s": 8316,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8369,
"s": 8349,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8376,
"s": 8369,
"text": " Print"
},
{
"code": null,
"e": 8387,
"s": 8376,
"text": " Add Notes"
}
] |
Create DATETIME from DATE and TIME in MySQL?
|
You can create DATETIME from DATE and TIME with the help of ADDTIME() function in MySQL. The syntax is as follows −
SELECT ADDTIME(CONVERT(yourDateColumnName,datetime),yourTimeColumnName) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DateTime
−> (
−> DueDate date,
−> DueTime time
−> );
Query OK, 0 rows affected (1.19 sec)
Now you can insert date and time separately. The query to insert is as follows −
mysql> insert into DateTime values(curdate(),now());
Query OK, 1 row affected (0.08 sec)
Display all records from the table with the help of select statement −
mysql> select *from DateTime;
The following is the output −
+------------+----------+
| DueDate | DueTime |
+------------+----------+
| 2018-12-11 | 09:59:07 |
+------------+----------+
1 row in set (0.00 sec)
Now you can implement the syntax we discussed in the beginning to create a datetime from date and time. The query is as follows −
mysql> select addtime(convert(DueDate,datetime),DueTime) as DATETimeDemo from DateTime;
The following is the output displaying datetime created from date and time −
+---------------------+
| DATETimeDemo |
+---------------------+
| 2018-12-11 09:59:07 |
+---------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "You can create DATETIME from DATE and TIME with the help of ADDTIME() function in MySQL. The syntax is as follows −"
},
{
"code": null,
"e": 1289,
"s": 1178,
"text": "SELECT ADDTIME(CONVERT(yourDateColumnName,datetime),yourTimeColumnName) as anyVariableName from yourTableName;"
},
{
"code": null,
"e": 1389,
"s": 1289,
"text": "To understand the above concept, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1511,
"s": 1389,
"text": "mysql> create table DateTime\n −> (\n −> DueDate date,\n −> DueTime time\n −> );\nQuery OK, 0 rows affected (1.19 sec)"
},
{
"code": null,
"e": 1592,
"s": 1511,
"text": "Now you can insert date and time separately. The query to insert is as follows −"
},
{
"code": null,
"e": 1681,
"s": 1592,
"text": "mysql> insert into DateTime values(curdate(),now());\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1752,
"s": 1681,
"text": "Display all records from the table with the help of select statement −"
},
{
"code": null,
"e": 1782,
"s": 1752,
"text": "mysql> select *from DateTime;"
},
{
"code": null,
"e": 1812,
"s": 1782,
"text": "The following is the output −"
},
{
"code": null,
"e": 1966,
"s": 1812,
"text": "+------------+----------+\n| DueDate | DueTime |\n+------------+----------+\n| 2018-12-11 | 09:59:07 |\n+------------+----------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2096,
"s": 1966,
"text": "Now you can implement the syntax we discussed in the beginning to create a datetime from date and time. The query is as follows −"
},
{
"code": null,
"e": 2184,
"s": 2096,
"text": "mysql> select addtime(convert(DueDate,datetime),DueTime) as DATETimeDemo from DateTime;"
},
{
"code": null,
"e": 2261,
"s": 2184,
"text": "The following is the output displaying datetime created from date and time −"
},
{
"code": null,
"e": 2405,
"s": 2261,
"text": "+---------------------+\n| DATETimeDemo |\n+---------------------+\n| 2018-12-11 09:59:07 |\n+---------------------+\n1 row in set (0.00 sec)"
}
] |
Removing stop words with NLTK in Python
|
When computers process natural language, some extremely common words which would appear to be of little value in helping select documents matching a user need are excluded from the vocabulary entirely. These words are called stop words.
For example, if you give the input sentence as −
John is a person who takes care of the people around him.
After stop word removal, you'll get the output −
['John', 'person', 'takes', 'care', 'people', 'around', '.']
NLTK has a collection of these stopwords which we can use to remove these from any given sentence. This is inside the NLTK.corpus module. We can use that to filter out stop words from out sentence. For example,
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
my_sent = "John is a person who takes care of people around him."
tokens = word_tokenize(my_sent)
filtered_sentence = [w for w in tokens if not w in stopwords.words()]
print(filtered_sentence)
This will give the output −
['John', 'person', 'takes', 'care', 'people', 'around', '.']
|
[
{
"code": null,
"e": 1299,
"s": 1062,
"text": "When computers process natural language, some extremely common words which would appear to be of little value in helping select documents matching a user need are excluded from the vocabulary entirely. These words are called stop words."
},
{
"code": null,
"e": 1348,
"s": 1299,
"text": "For example, if you give the input sentence as −"
},
{
"code": null,
"e": 1406,
"s": 1348,
"text": "John is a person who takes care of the people around him."
},
{
"code": null,
"e": 1455,
"s": 1406,
"text": "After stop word removal, you'll get the output −"
},
{
"code": null,
"e": 1516,
"s": 1455,
"text": "['John', 'person', 'takes', 'care', 'people', 'around', '.']"
},
{
"code": null,
"e": 1727,
"s": 1516,
"text": "NLTK has a collection of these stopwords which we can use to remove these from any given sentence. This is inside the NLTK.corpus module. We can use that to filter out stop words from out sentence. For example,"
},
{
"code": null,
"e": 1997,
"s": 1727,
"text": "from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nmy_sent = \"John is a person who takes care of people around him.\"\ntokens = word_tokenize(my_sent)\n\nfiltered_sentence = [w for w in tokens if not w in stopwords.words()]\n\nprint(filtered_sentence)"
},
{
"code": null,
"e": 2025,
"s": 1997,
"text": "This will give the output −"
},
{
"code": null,
"e": 2086,
"s": 2025,
"text": "['John', 'person', 'takes', 'care', 'people', 'around', '.']"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.