title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What is the difference between UNIX TIMESTAMPS and MySQL TIMESTAMPS?
In MySQL, UNIX TIMESTAMPS are stored as 32-bit integers. On the other hand MySQL TIMESTAMPS are also stored in similar manner but represented in readable YYYY-MM-DD HH:MM:SS format. mysql> Select UNIX_TIMESTAMP('2017-09-25 02:05:45') AS 'UNIXTIMESTAMP VALUE'; +---------------------+ | UNIXTIMESTAMP VALUE | +---------------------+ | 1506285345 | +---------------------+ 1 row in set (0.00 sec) The query above shows that UNIX TIMESTAMPS values are stored as 32 bit integers whose range is same as MySQL INTEGER data type range. mysql> Select FROM_UNIXTIME(1506283345) AS 'MySQLTIMESTAMP VALUE'; +----------------------+ | MySQLTIMESTAMP VALUE | +----------------------+ | 2017-09-25 01:32:25 | +----------------------+ 1 row in set (0.00 sec) The query above shows that MySQL TIMESTAMPS values are also stored as 32 bit integers, but in a readable format, whose range is same as MySQL TIMESTAMP data type range.
[ { "code": null, "e": 1244, "s": 1062, "text": "In MySQL, UNIX TIMESTAMPS are stored as 32-bit integers. On the other hand MySQL TIMESTAMPS are also stored in similar manner but represented in readable YYYY-MM-DD HH:MM:SS format." }, { "code": null, "e": 1466, "s": 1244, "text": "mysql> Select UNIX_TIMESTAMP('2017-09-25 02:05:45') AS 'UNIXTIMESTAMP VALUE';\n+---------------------+\n| UNIXTIMESTAMP VALUE |\n+---------------------+\n| 1506285345 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1600, "s": 1466, "text": "The query above shows that UNIX TIMESTAMPS values are stored as 32 bit integers whose range is same as MySQL INTEGER data type range." }, { "code": null, "e": 1816, "s": 1600, "text": "mysql> Select FROM_UNIXTIME(1506283345) AS 'MySQLTIMESTAMP VALUE';\n+----------------------+\n| MySQLTIMESTAMP VALUE |\n+----------------------+\n| 2017-09-25 01:32:25 |\n+----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1985, "s": 1816, "text": "The query above shows that MySQL TIMESTAMPS values are also stored as 32 bit integers, but in a readable format, whose range is same as MySQL TIMESTAMP data type range." } ]
How do I display the current date and time in an Android application?
This example demonstrates about How do I display the current date and time in an Android application Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project. Step 2 βˆ’ Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tvDateTime" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="16dp" android:gravity="center" android:padding="16dp" android:textSize="24sp" /> </RelativeLayout> Step 3 βˆ’ Add the following code to src/MainActivity.java package app.com.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.text.DateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tvDateTime = findViewById(R.id.tvDateTime); String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()); tvDateTime.setText(currentDateTimeString); } } Step 4 βˆ’ Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen βˆ’ Click here to download the project code.
[ { "code": null, "e": 1163, "s": 1062, "text": "This example demonstrates about How do I display the current date and time in an Android application" }, { "code": null, "e": 1292, "s": 1163, "text": "Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project." }, { "code": null, "e": 1357, "s": 1292, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1956, "s": 1357, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/tvDateTime\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_margin=\"16dp\"\n android:gravity=\"center\"\n android:padding=\"16dp\"\n android:textSize=\"24sp\" />\n</RelativeLayout>" }, { "code": null, "e": 2013, "s": 1956, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 2612, "s": 2013, "text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.text.DateFormat;\nimport java.util.Date;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView tvDateTime = findViewById(R.id.tvDateTime);\n String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());\n tvDateTime.setText(currentDateTimeString);\n }\n}" }, { "code": null, "e": 2667, "s": 2612, "text": "Step 4 βˆ’ Add the following code to androidManifest.xml" }, { "code": null, "e": 3337, "s": 2667, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3684, "s": 3337, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen βˆ’" }, { "code": null, "e": 3725, "s": 3684, "text": "Click here to download the project code." } ]
Kotlin Get Started
The easiest way to get started with Kotlin, is to use an IDE. An IDE (Integrated Development Environment) is used to edit and compile code. In this chapter, we will use IntelliJ (developed by the same people that created Kotlin) which is free to download from https://www.jetbrains.com/idea/download/. Once IntelliJ is downloaded and installed, click on the New Project button to get started with IntelliJ: Then click on "Kotlin" in the left side menu, and enter a name for your project: Next, we need to install something called JDK (Java Development Kit) to get our Kotlin project up and going. Click on the "Project JDK" menu, select "Download JDK" and select a version and vendor (e.g. AdoptOpenJDK 11) and click on the "Download" button: When the JDK is downloaded and installed, choose it from the select menu and then click on the "Next" button and at last "Finish": Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in IntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a kotlin file: Select the "File" option and add a name to your Kotlin file, for example "Main": You have now created your first Kotlin file (Main.kt). Let's add some Kotlin code to it, and run the program to see how it works. Inside the Main.kt file, add the following code: Main.kt fun main() { println("Hello World") } Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, lets focus on how to run the code. Click on the Run button at the top navigation bar, then click "Run", and select "Mainkt". Next, IntelliJ will build your project, and run the Kotlin file. The output will look something like this: As you can see, the output of the code was "Hello World", meaning that you have now written and executed your first Kotlin program! When learning Kotlin at w3schools.com, you can use our "Try it Yourself" tool, which shows both the code and the result. This will make it easier for you to understand every part as we move forward: Code: fun main() { println("Hello World") } Result: We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 62, "s": 0, "text": "The easiest way to get started with Kotlin, is to use an IDE." }, { "code": null, "e": 140, "s": 62, "text": "An IDE (Integrated Development Environment) is used to edit and compile code." }, { "code": null, "e": 302, "s": 140, "text": "In this chapter, we will use IntelliJ (developed by the same people that created Kotlin) which is free to download from https://www.jetbrains.com/idea/download/." }, { "code": null, "e": 408, "s": 302, "text": "Once IntelliJ is downloaded and installed, click on the \nNew Project button to get started with IntelliJ:" }, { "code": null, "e": 489, "s": 408, "text": "Then click on \"Kotlin\" in the left side menu, and enter a name for your project:" }, { "code": null, "e": 745, "s": 489, "text": "Next, we need to install something called JDK (Java Development Kit) to get \nour Kotlin project up and going. Click on the \"Project JDK\" menu, select \"Download JDK\" and select a version and vendor (e.g. AdoptOpenJDK 11)\nand click on the \"Download\" button:" }, { "code": null, "e": 877, "s": 745, "text": "When the JDK is downloaded and installed, choose it from the select menu and \nthen click on the \"Next\" button and at last \"Finish\":" }, { "code": null, "e": 1121, "s": 877, "text": "Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in \nIntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a kotlin file:" }, { "code": null, "e": 1202, "s": 1121, "text": "Select the \"File\" option and add a name to your Kotlin file, for example \"Main\":" }, { "code": null, "e": 1381, "s": 1202, "text": "You have now created your first Kotlin file (Main.kt). Let's add some Kotlin code to it, and run the program to see how it works. Inside the Main.kt file, add the following code:" }, { "code": null, "e": 1389, "s": 1381, "text": "Main.kt" }, { "code": null, "e": 1429, "s": 1389, "text": "fun main() {\n println(\"Hello World\")\n}" }, { "code": null, "e": 1666, "s": 1429, "text": "Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, lets focus on how to run the code. Click on the Run button \nat the top navigation bar, then click \"Run\", and select \"Mainkt\". " }, { "code": null, "e": 1774, "s": 1666, "text": "Next, IntelliJ will build your project, and run the Kotlin file. The output \nwill look something like this:" }, { "code": null, "e": 1906, "s": 1774, "text": "As you can see, the output of the code was \"Hello World\", meaning that you have now written and executed your first Kotlin program!" }, { "code": null, "e": 2106, "s": 1906, "text": "When learning Kotlin at w3schools.com, you can use our \"Try it Yourself\" tool, which shows both the code and the result. This will make it easier for \nyou to understand every part as we move forward:" }, { "code": null, "e": 2112, "s": 2106, "text": "Code:" }, { "code": null, "e": 2152, "s": 2112, "text": "fun main() {\n println(\"Hello World\")\n}" }, { "code": null, "e": 2160, "s": 2152, "text": "Result:" }, { "code": null, "e": 2193, "s": 2160, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2235, "s": 2193, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2342, "s": 2235, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2361, "s": 2342, "text": "help@w3schools.com" } ]
What MySQL COALESCE() function returns if all the arguments provided to it are NULL?
If all the values in MySQL COALESCE() function are NULL then it returns NULL as the output. It means that this function does not find any non-NULL value in the list. mysql> Select COALESCE(NULL, NULL, NULL, NULL); +----------------------------------+ | COALESCE(NULL, NULL, NULL, NULL) | +----------------------------------+ | NULL | +----------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1228, "s": 1062, "text": "If all the values in MySQL COALESCE() function are NULL then it returns NULL as the output. It means that this function does not find any non-NULL value in the list." }, { "code": null, "e": 1486, "s": 1228, "text": "mysql> Select COALESCE(NULL, NULL, NULL, NULL);\n+----------------------------------+\n| COALESCE(NULL, NULL, NULL, NULL) |\n+----------------------------------+\n| NULL |\n+----------------------------------+\n\n1 row in set (0.00 sec)" } ]
java.time.LocalDate.atTime() Method Example
The java.time.LocalDate.atTime(OffsetTime time) method combines this date with an offset time to create an OffsetDateTime. Following is the declaration for java.time.LocalDate.atTime(OffsetTime time) method. public OffsetDateTime atTime(OffsetTime time) time βˆ’ the time to combine with, not null. the offset date-time formed from this date and the specified time, not null. The following example shows the usage of java.time.LocalDate.atTime(OffsetTime time) method. package com.tutorialspoint; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.OffsetTime; public class LocalDateDemo { public static void main(String[] args) { LocalDate date = LocalDate.parse("2017-02-03"); System.out.println(date); OffsetTime time = OffsetTime.now(); OffsetDateTime date1 = date.atTime(time); System.out.println(date1); } } Let us compile and run the above program, this will produce the following result βˆ’ 2017-02-03 2017-02-03T11:47:42.530+05:30 Print Add Notes Bookmark this page
[ { "code": null, "e": 2038, "s": 1915, "text": "The java.time.LocalDate.atTime(OffsetTime time) method combines this date with an offset time to create an OffsetDateTime." }, { "code": null, "e": 2123, "s": 2038, "text": "Following is the declaration for java.time.LocalDate.atTime(OffsetTime time) method." }, { "code": null, "e": 2170, "s": 2123, "text": "public OffsetDateTime atTime(OffsetTime time)\n" }, { "code": null, "e": 2213, "s": 2170, "text": "time βˆ’ the time to combine with, not null." }, { "code": null, "e": 2290, "s": 2213, "text": "the offset date-time formed from this date and the specified time, not null." }, { "code": null, "e": 2383, "s": 2290, "text": "The following example shows the usage of java.time.LocalDate.atTime(OffsetTime time) method." }, { "code": null, "e": 2797, "s": 2383, "text": "package com.tutorialspoint;\n\nimport java.time.LocalDate;\nimport java.time.OffsetDateTime;\nimport java.time.OffsetTime;\n\npublic class LocalDateDemo {\n public static void main(String[] args) {\n\n LocalDate date = LocalDate.parse(\"2017-02-03\");\n System.out.println(date); \n OffsetTime time = OffsetTime.now();\n OffsetDateTime date1 = date.atTime(time);\n System.out.println(date1); \n }\n}" }, { "code": null, "e": 2880, "s": 2797, "text": "Let us compile and run the above program, this will produce the following result βˆ’" }, { "code": null, "e": 2922, "s": 2880, "text": "2017-02-03\n2017-02-03T11:47:42.530+05:30\n" }, { "code": null, "e": 2929, "s": 2922, "text": " Print" }, { "code": null, "e": 2940, "s": 2929, "text": " Add Notes" } ]
Vim - Using Vim As Ide
We can configure Vim to use it as an IDE. In this section, we will discuss following items Syntax highlighting Smart indentation Bounce Execute shell commands Configuring ctags and csope Auto-completion and auto-suggestion Syntax highlighting is one of the important features of IDE. To enable syntax highlighting use βˆ’ :syntax on For instance, below image show syntax highlighting for C code βˆ’ To disable syntax highlighting use βˆ’ :syntax off When syntax highlighting is disabled, it will show following output βˆ’ To perform auto and smart indentation use following commands βˆ’ : set autoindent : set smartindent In addition to this you can use below command to auto-indent C code βˆ’ : set cindent If you are using programming language which uses curly braces to combine multiple statements then % key will be your friend. This key will jump between start and end of curly braces quickly. For instance, you are at line 11 and execute % command then it will move cursor the line 4. Below image shows this βˆ’ To execute single command from Vim editor user βˆ’ :!<command> For instance, to execute pwd command use following syntax βˆ’ :!pwd However, if you want to multiple shell commands then execute following command βˆ’ :shell Above command will give you terminal access, where you can execute multiple commands. Once you are done with it, just type exit command which will return back to Vim session. Combination of ctags and csope provides many useful features like go to function definition, go to function declaration, find function calls, search file, and many more. Perform below steps to configure these tool βˆ’ Generate tags using following command βˆ’ $ ctags <file> This command will generate new file namely tags Provide tag file to vim using following command βˆ’ :set tags = tag Now move your cursor under function name and press Ctrl + ] to go to function definition. Use Ctrl + t to come back to previous position. To install and configure cscope perform following steps βˆ’ Install cscope $ sudo apt-get install cscope Generate ctags and launch main window $ cscope –R User Ctrl + d to close cscope window We can use following commands for auto-completion βˆ’ Word completion Line completion File name completion Note that we have to use these commands in insert mode. 46 Lectures 5.5 hours Jason Cannon Print Add Notes Bookmark this page
[ { "code": null, "e": 2061, "s": 1970, "text": "We can configure Vim to use it as an IDE. In this section, we will discuss following items" }, { "code": null, "e": 2081, "s": 2061, "text": "Syntax highlighting" }, { "code": null, "e": 2099, "s": 2081, "text": "Smart indentation" }, { "code": null, "e": 2106, "s": 2099, "text": "Bounce" }, { "code": null, "e": 2129, "s": 2106, "text": "Execute shell commands" }, { "code": null, "e": 2157, "s": 2129, "text": "Configuring ctags and csope" }, { "code": null, "e": 2193, "s": 2157, "text": "Auto-completion and auto-suggestion" }, { "code": null, "e": 2290, "s": 2193, "text": "Syntax highlighting is one of the important features of IDE. To enable syntax highlighting use βˆ’" }, { "code": null, "e": 2302, "s": 2290, "text": ":syntax on\n" }, { "code": null, "e": 2366, "s": 2302, "text": "For instance, below image show syntax highlighting for C code βˆ’" }, { "code": null, "e": 2403, "s": 2366, "text": "To disable syntax highlighting use βˆ’" }, { "code": null, "e": 2416, "s": 2403, "text": ":syntax off\n" }, { "code": null, "e": 2486, "s": 2416, "text": "When syntax highlighting is disabled, it will show following output βˆ’" }, { "code": null, "e": 2549, "s": 2486, "text": "To perform auto and smart indentation use following commands βˆ’" }, { "code": null, "e": 2586, "s": 2549, "text": ": set autoindent \n: set smartindent\n" }, { "code": null, "e": 2656, "s": 2586, "text": "In addition to this you can use below command to auto-indent C code βˆ’" }, { "code": null, "e": 2671, "s": 2656, "text": ": set cindent\n" }, { "code": null, "e": 2862, "s": 2671, "text": "If you are using programming language which uses curly braces to combine multiple statements then % key will be your friend. This key will jump between start and end of curly braces quickly." }, { "code": null, "e": 2979, "s": 2862, "text": "For instance, you are at line 11 and execute % command then it will move cursor the line 4. Below image shows this βˆ’" }, { "code": null, "e": 3028, "s": 2979, "text": "To execute single command from Vim editor user βˆ’" }, { "code": null, "e": 3041, "s": 3028, "text": ":!<command>\n" }, { "code": null, "e": 3101, "s": 3041, "text": "For instance, to execute pwd command use following syntax βˆ’" }, { "code": null, "e": 3108, "s": 3101, "text": ":!pwd\n" }, { "code": null, "e": 3189, "s": 3108, "text": "However, if you want to multiple shell commands then execute following command βˆ’" }, { "code": null, "e": 3197, "s": 3189, "text": ":shell\n" }, { "code": null, "e": 3372, "s": 3197, "text": "Above command will give you terminal access, where you can execute multiple commands. Once you are done with it, just type exit command which will return back to Vim session." }, { "code": null, "e": 3588, "s": 3372, "text": "Combination of ctags and csope provides many useful features like go to function definition, go to function declaration, find function calls, search file, and many more. Perform below steps to configure these tool βˆ’" }, { "code": null, "e": 3628, "s": 3588, "text": "Generate tags using following command βˆ’" }, { "code": null, "e": 3644, "s": 3628, "text": "$ ctags <file>\n" }, { "code": null, "e": 3692, "s": 3644, "text": "This command will generate new file namely tags" }, { "code": null, "e": 3742, "s": 3692, "text": "Provide tag file to vim using following command βˆ’" }, { "code": null, "e": 3759, "s": 3742, "text": ":set tags = tag\n" }, { "code": null, "e": 3849, "s": 3759, "text": "Now move your cursor under function name and press Ctrl + ] to go to function definition." }, { "code": null, "e": 3897, "s": 3849, "text": "Use Ctrl + t to come back to previous position." }, { "code": null, "e": 3955, "s": 3897, "text": "To install and configure cscope perform following steps βˆ’" }, { "code": null, "e": 3970, "s": 3955, "text": "Install cscope" }, { "code": null, "e": 4001, "s": 3970, "text": "$ sudo apt-get install cscope\n" }, { "code": null, "e": 4039, "s": 4001, "text": "Generate ctags and launch main window" }, { "code": null, "e": 4052, "s": 4039, "text": "$ cscope –R\n" }, { "code": null, "e": 4089, "s": 4052, "text": "User Ctrl + d to close cscope window" }, { "code": null, "e": 4141, "s": 4089, "text": "We can use following commands for auto-completion βˆ’" }, { "code": null, "e": 4157, "s": 4141, "text": "Word completion" }, { "code": null, "e": 4173, "s": 4157, "text": "Line completion" }, { "code": null, "e": 4194, "s": 4173, "text": "File name completion" }, { "code": null, "e": 4250, "s": 4194, "text": "Note that we have to use these commands in insert mode." }, { "code": null, "e": 4285, "s": 4250, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4299, "s": 4285, "text": " Jason Cannon" }, { "code": null, "e": 4306, "s": 4299, "text": " Print" }, { "code": null, "e": 4317, "s": 4306, "text": " Add Notes" } ]
C# | Char.ToString() Method - GeeksforGeeks
01 Feb, 2019 In C#, Char.ToString() is a System.Char struct method which is used to convert the value of this instance to its equivalent string representation. This method can be overloaded by passing different type of arguments to it. Char.ToString(IFormatProvider) MethodChar.ToString(Char) MethodChar.ToString() Method Char.ToString(IFormatProvider) Method Char.ToString(Char) Method Char.ToString() Method This method is used to convert the value of the current instance to its equivalent string representation by using the specified culture-specific format information. The culture-specific format is a type of formatting, it is a process in which an instance value of class, structure, or enum is converted to the string representation and the result displayed to the user. Syntax: public string ToString(IFormatProvider provider); Parameter: provider: It is the required object which supplies culture-specific formatting information and it is reserved. Return Type: It returns the string representation of the value of current instance which is specified by parameter provider. The return type of this method is System.String. Example: // C# program to illustrate the// Char.ToString(IFormatProvider) Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // converting into string Console.WriteLine(Char.ToString('G')); }} G Note: Here, the parameter provider, is ignored as it does not participate in this operation. This method is used to convert a specified Unicode character into a string representation. Syntax: public static string ToString(Char ch); Parameter: ch: It is the Unicode character which is to be converted. Return Type: It returns a string representation of parameter ch. The return type of this method is System.String. Example: // C# program to illustrate the// Char.ToString(Char) Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // using ToString(Char) method // for converting char into string Console.WriteLine(Char.ToString('A')); }} A This method is used to convert the value of this instance to its equivalent string representation. Syntax: public override string ToString(); Return Type: It returns a string representation of the value of this instance. The return type of this method is System.String. Example: // C# program to illustrate the// Char.ToString() Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // declaration of data type char ch1 = 'P'; string output; // convert into a string output = ch1.ToString(); Console.WriteLine(output); }} P Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.tostring?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | IsNullOrEmpty() Method C# | How to check whether a List contains a specified element C# Dictionary with examples C# | Arrays of Strings String.Split() Method in C# with Examples C# | Method Overriding C# | Constructors C# | Class and Object Extension Method in C#
[ { "code": null, "e": 23192, "s": 23164, "text": "\n01 Feb, 2019" }, { "code": null, "e": 23415, "s": 23192, "text": "In C#, Char.ToString() is a System.Char struct method which is used to convert the value of this instance to its equivalent string representation. This method can be overloaded by passing different type of arguments to it." }, { "code": null, "e": 23501, "s": 23415, "text": "Char.ToString(IFormatProvider) MethodChar.ToString(Char) MethodChar.ToString() Method" }, { "code": null, "e": 23539, "s": 23501, "text": "Char.ToString(IFormatProvider) Method" }, { "code": null, "e": 23566, "s": 23539, "text": "Char.ToString(Char) Method" }, { "code": null, "e": 23589, "s": 23566, "text": "Char.ToString() Method" }, { "code": null, "e": 23959, "s": 23589, "text": "This method is used to convert the value of the current instance to its equivalent string representation by using the specified culture-specific format information. The culture-specific format is a type of formatting, it is a process in which an instance value of class, structure, or enum is converted to the string representation and the result displayed to the user." }, { "code": null, "e": 23967, "s": 23959, "text": "Syntax:" }, { "code": null, "e": 24017, "s": 23967, "text": "public string ToString(IFormatProvider provider);" }, { "code": null, "e": 24028, "s": 24017, "text": "Parameter:" }, { "code": null, "e": 24139, "s": 24028, "text": "provider: It is the required object which supplies culture-specific formatting information and it is reserved." }, { "code": null, "e": 24313, "s": 24139, "text": "Return Type: It returns the string representation of the value of current instance which is specified by parameter provider. The return type of this method is System.String." }, { "code": null, "e": 24322, "s": 24313, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.ToString(IFormatProvider) Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // converting into string Console.WriteLine(Char.ToString('G')); }}", "e": 24568, "s": 24322, "text": null }, { "code": null, "e": 24571, "s": 24568, "text": "G\n" }, { "code": null, "e": 24664, "s": 24571, "text": "Note: Here, the parameter provider, is ignored as it does not participate in this operation." }, { "code": null, "e": 24755, "s": 24664, "text": "This method is used to convert a specified Unicode character into a string representation." }, { "code": null, "e": 24763, "s": 24755, "text": "Syntax:" }, { "code": null, "e": 24803, "s": 24763, "text": "public static string ToString(Char ch);" }, { "code": null, "e": 24814, "s": 24803, "text": "Parameter:" }, { "code": null, "e": 24872, "s": 24814, "text": "ch: It is the Unicode character which is to be converted." }, { "code": null, "e": 24986, "s": 24872, "text": "Return Type: It returns a string representation of parameter ch. The return type of this method is System.String." }, { "code": null, "e": 24995, "s": 24986, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.ToString(Char) Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // using ToString(Char) method // for converting char into string Console.WriteLine(Char.ToString('A')); }}", "e": 25276, "s": 24995, "text": null }, { "code": null, "e": 25279, "s": 25276, "text": "A\n" }, { "code": null, "e": 25378, "s": 25279, "text": "This method is used to convert the value of this instance to its equivalent string representation." }, { "code": null, "e": 25386, "s": 25378, "text": "Syntax:" }, { "code": null, "e": 25421, "s": 25386, "text": "public override string ToString();" }, { "code": null, "e": 25549, "s": 25421, "text": "Return Type: It returns a string representation of the value of this instance. The return type of this method is System.String." }, { "code": null, "e": 25558, "s": 25549, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.ToString() Methodusing System; class GeeksforGeeks{ // Main method public static void Main() { // declaration of data type char ch1 = 'P'; string output; // convert into a string output = ch1.ToString(); Console.WriteLine(output); }}", "e": 25892, "s": 25558, "text": null }, { "code": null, "e": 25895, "s": 25892, "text": "P\n" }, { "code": null, "e": 25995, "s": 25895, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.tostring?view=netframework-4.7.2" }, { "code": null, "e": 26014, "s": 25995, "text": "CSharp-Char-Struct" }, { "code": null, "e": 26028, "s": 26014, "text": "CSharp-method" }, { "code": null, "e": 26031, "s": 26028, "text": "C#" }, { "code": null, "e": 26129, "s": 26031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26138, "s": 26129, "text": "Comments" }, { "code": null, "e": 26151, "s": 26138, "text": "Old Comments" }, { "code": null, "e": 26205, "s": 26151, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 26233, "s": 26205, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 26295, "s": 26233, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 26323, "s": 26295, "text": "C# Dictionary with examples" }, { "code": null, "e": 26346, "s": 26323, "text": "C# | Arrays of Strings" }, { "code": null, "e": 26388, "s": 26346, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 26411, "s": 26388, "text": "C# | Method Overriding" }, { "code": null, "e": 26429, "s": 26411, "text": "C# | Constructors" }, { "code": null, "e": 26451, "s": 26429, "text": "C# | Class and Object" } ]
NLP: Contextualized word embeddings from BERT | by Andreas Pogiatzis | Towards Data Science
Undoubtedly, Natural Language Processing (NLP) research has taken enormous leaps after being relatively stationary for a couple of years. Firstly, Google’s Bidirectional Encoder Representations from Transformer (BERT) [1] becoming the highlight by the end of 2018 for achieving state-of-the-art performance in many NLP tasks and not much later, OpenAI’s GPT-2 stealing the thunder by promising even more astonishing results which reportedly rendering it too dangerous to publish! Considering the time frame and the players behind these publications, it takes no effort to realize that there is a lot of activity in the space at the moment. That being said, we will focus on BERT for this post and attempt to have a small piece of this pie by extracting pre-trained contextualized word embeddings like ELMo [3]. To give you a brief outline, I will first give a little bit of background context, then a take a high-level overview of BERT’s architecture, and lastly jump into the code while explaining some tricky parts here and there. Just for more convenience, I will be using Google’s Colab for the coding but the same code can as well run on your local environment without many modifications. If you came just for the coding part, skip to the β€œBERT Word Embedding Extraction” section. Find the finished notebook code here. To start off, embeddings are simply (moderately) low dimensional representations of a point in a higher dimensional vector space. In the same manner, word embeddings are dense vector representations of words in lower dimensional space. The first, word embedding model utilizing neural networks was published in 2013 [4] by research at Google. Since then, word embeddings are encountered in almost every NLP model used in practice today. Of course, the reason for such mass adoption is quite frankly their effectiveness. By translating a word to an embedding it becomes possible to model the semantic importance of a word in a numeric form and thus perform mathematical operations on it. To make this more clear I will give you the most common example that you can find in the context of word embeddings When this was first possible by the word2vec model it was an amazing breakthrough. From there, many more advanced models surfaced which not only captured a static semantic meaning but also a contextualized meaning. For instance, consider the two sentences below: I like apples. I like Apple macbooks Note that the word apple has a different semantic meaning in each sentence. Now with a contextualized language model, the embedding of the word apple would have a different vector representation which makes it even more powerful for NLP tasks. However, I will leave the details of how that works, out of the scope of this post just to keep it short and on point. To be frank, much of the progress in the NLP space can be attributed to the advancements of general deep learning research. More particularly, Google (again!) presented a novel neural network architecture called a transformer in a seminal paper [5] which had many benefits over the conventional sequential models (LSTM, RNN, GRU etc). Advantages included but were not limited to, the more effective modeling of long term dependencies among tokens in a temporal sequence, and the more efficient training of the model in general by eliminating the sequential dependency on previous tokens. In a nutshell, a transformer is an encoder-decoder architecture model which uses attention mechanisms to forward a more complete picture of the whole sequence to the decoder at once rather than sequentially as illustrated in the figures below. Again, I won’t be describing details about how attention works as it will make the topic way more confusing and harder to digest. Feel free to follow the relevant paper in the references. OpenAI’s GPT was the first to create a transformer based language model with fine tuning but to be more precise, it was only using the decoder of the transformer. Therefore, making the language modeling uni-directional. The technical reason for dropping out the encoder was that language modeling would become a trivial task as the word to be predicted could have ultimately seen itself. By now, the name of the model should probably make more sense and give you a rough idea of what it is. BERT brought everything together to build a bidirectional transformer-based language model using encoders rather than decoders! To overcome the β€œsee itself” issue, the guys at Google had an ingenious idea. They employed masked language modeling. In other words, they hid 15% of the words and used their position information to infer them. Finally, they also mixed it up a little bit to make the learning process more effective. Although this methodology had a negative impact on convergence time, it outperformed state-of-the-art models even before convergence which sealed the success of the model. Normally, BERT represents a general language modeling which supports transfer learning and fine-tuning on specific tasks, however, in this post we will only touch the feature extraction side of BERT by just obtaining ELMo-like word embeddings from it, using Keras and TensorFlow. But hold your horses! Before we jump into the code let’s explore BERT’s architecture really quick so that we have a bit of background at implementation time. Believe me, it will make things a lot easier to understand. In fact, BERT developers created two main models: The BASE: Number of transformer blocks (L): 12, Hidden layer size (H): 768 and Attention heads(A): 12The LARGE: Number of transformer blocks (L): 24, Hidden layer size (H): 1024 and Attention heads(A): 16 The BASE: Number of transformer blocks (L): 12, Hidden layer size (H): 768 and Attention heads(A): 12 The LARGE: Number of transformer blocks (L): 24, Hidden layer size (H): 1024 and Attention heads(A): 16 In this post, I will be using the BASE model as it is more than enough ( and way smaller!). From a very high-level perspective, BERT’s architecture looks like this: It may seem simple but remember that each encoder block encapsulates a more sophisticated model architecture. At this point, to make things clearer it is important to understand the special tokens that BERT authors used for fine-tuning and specific task training. These are the following: [CLS] : The first token of every sequence. A classification token which is normally used in conjunction with a softmax layer for classification tasks. For anything else, it can be safely ignored.[SEP] : A sequence delimiter token which was used at pre-training for sequence-pair tasks (i.e. Next sentence prediction). Must be used when sequence pair tasks are required. When a single sequence is used it is just appended at the end.[MASK] : Token used for masked words. Only used for pre-training. [CLS] : The first token of every sequence. A classification token which is normally used in conjunction with a softmax layer for classification tasks. For anything else, it can be safely ignored. [SEP] : A sequence delimiter token which was used at pre-training for sequence-pair tasks (i.e. Next sentence prediction). Must be used when sequence pair tasks are required. When a single sequence is used it is just appended at the end. [MASK] : Token used for masked words. Only used for pre-training. Moving on, the input format that BERT expects is illustrated below: As such, any input to be used with BERT must be formatted to match the above. The input layer is simply the vector of the sequence tokens along with the special tokens. The β€œ##ing” token in the example above may raise some eyebrows so to clarify, BERT utilizes WordPiece [6] for tokenization which in effect, splits token like β€œplaying” to β€œplay” and β€œ##ing”. This is mainly to cover a wider spectrum of Out-Of-Vocabulary (OOV) words. Token embeddings are the vocabulary IDs for each of the tokens. Sentence Embeddings is just a numeric class to distinguish between sentence A and B. And lastly, Transformer positional embeddings indicate the position of each word in the sequence. More details on this one can be found in [5]. Finally, there is one last thing. Everything is great is sofar, but how can I get word embeddings from this?!? As discussed, BERT base model uses 12 layers of transformer encoders, each output per token from each layer of these can be used as a word embedding! You probably wonder, which one is the best though? Well, I guess this depends on the task but empirically, the authors identified that one of the best performing choices was to sum the last 4 layers, which is what we will be doing. As illustrated the best performing option is to concatenate the last 4 layers but in this post, the summing approach is used for convenience. More particularly, the performance difference is not that much, and also there is more flexibility for truncating the dimensions further, without losing much information. Enough with the theory. Let’s move on to the practice. Firstly, create a new Google Colab notebook. Go to Edit->Notebook Settings and make sure hardware accelerator is set to TPU. Now, the first task is to clone the official BERT repository, add its directory to the path and import the appropriate modules from there. !rm -rf bert!git clone https://github.com/google-research/bertimport syssys.path.append('bert/')from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport codecsimport collectionsimport jsonimport reimport osimport pprintimport numpy as npimport tensorflow as tfimport modelingimport tokenization The two modules imported from BERT are modeling and tokenization. Modeling includes the BERT model implementation and tokenization is obviously for tokenizing the sequences. Adding to this, we fetch our TPU address from colab and initialize a new tensorflow session. (Note that this only applies for Colab. When running locally, it is not needed). If you see any errors on when running the block below make sure you are using a TPU as hardware accelerator (see above) Moving on, we select which BERT model we want to use. As you can see there are three available models that we can choose, but in reality, there are even more pre-trained models available for download in the official BERT GitHub repository. Those are just the models that have already been downloaded and hosted by Google in an open bucket so that can be accessed from Colaboratory. (For local use you need to download and extract a pre-trained model). Recall the parameters from before: 12 L (transformer blocks) 768 H (hidden layer size) 12 A (attention heads) . β€œUncased” is just for lowercase sequences. In this example, we will use the uncased BERT BASE model. Furthermore, we define some global parameters for the model: Most of the parameters above are pretty self-explanatory. In my opinion, the only one that may be a little bit tricky is the LAYERS array. Recall that we are using on the last 4 layers from the 12 hidden encoders. Hence, LAYERS keeps their indices. The next part is solely to define wrapper classes for the input before processing and after processing (Features). In the InputExample class, we have set text_b to None by default since we aim to use single sequences rather than a sequence-pairs. Moreover, the InputFeatures class encapsulates the features that BERT needs for input (See input diagram above). The tokens property is clearly a vector of input tokens, input_ids are the ids that correspond to the token from the vocabulary, input_mask annotates real token sequence from padding and lastly, input_type_ids separates segment A from segment B so it is not really relevant here. Now, add the following code: This is to set up our Estimator. An Estimator is just an abstraction for a model that tensorflow provides along with an API for training, evaluation, and prediction. Our custom estimator is, therefore, a wrapper around the BertModel. Admittedly there are parts of the code that can be removed from the above but I am sticking to the example that Google provided just for consistency. The important parts there is line 60 β€” where the bert model is defined β€” , and line 100 where the predictions from the top 4 layers are extracted. Continue along by also adding the following: This is the function that takes care of the input processing. In other words, it transforms InputExamples to InputFeatures. Adding to these, we create a function for converting a normal string sequence to InputExample: Now for the last bit of the code, we define a function which accepts an array of strings as a parameter and the desired dimension (max 768) of the embedding output and returns a dictionary with the token as key and the embedding vector as value. The above code snippet simply builds the estimator and invokes a prediction based on the given inputs. Let’s go ahead and test our model by running this: embeddings = get_features([β€œThis is a test sentence”], dim=50)print(embeddings) If everything goes well, you will have a dictionary containing the embeddings of size 50 per token. Remember that these are contextualized embeddings, so if you have duplicate tokens on different sequences only the embedding of the last token will be kept in the dictionary. To keep both, replace the dictionary with a different data structure. You can find the complete notebook here. Now, these embeddings can be used as input features for other models built for custom tasks. Nevertheless, I will save that for another post. Or even maybe implement a BERT Keras Layer for seamless embedding integration. That’s all from me folks. I hope you enjoyed the post and hopefully got a clearer picture around BERT. Feel free to post your feedback or questions in the comments section. [1] J.Devlin, M. Chang, K. Lee and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (2018) [2] Radford, Alec, Wu, Jeff, Child, Rewon, Luan, David, Amodei, Dario, Sutskever, Ilya, Language Models are Unsupervised Multitask Learners (2019) [3] M. Peters, M. Neumann, M. Iyyer, M. Gardner, C. Clark, K.Lee and L.Zettlemoyer, Deep contextualized word representations (2018), North American Chapter of the Association for Computational Linguistics [4] T.Mikolov, I. Sutskever, K. Chen, G. Corrado and J. Dean, Distributed Representations of Words and Phrases and their Compositionality (2013) [5]A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A.Gomez, L. Kaiser and I. Polosukhin, Attention Is All You Need (2017) [6] Y. Wu, M. Schuster, Z. Chen, Q. Le, M. Norouzi, W. Macherey, M. Krikun, Y. Cao, Q. Gao, K. Macherey, J. Klingner, A. Shah, M. Johnson, X. Liu, Ł. Kaiser, S. Gouws, Y. Kato, T. Kudo, H. Kazawa, K. Stevens, G. Kurian, N. Patil, W. Wang, C. Young, J. Smith, J. Riesa, A. Rudnick, O. Vinyals, G. Corrado, M. Hughes and J. Dean Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation (2016)
[ { "code": null, "e": 812, "s": 172, "text": "Undoubtedly, Natural Language Processing (NLP) research has taken enormous leaps after being relatively stationary for a couple of years. Firstly, Google’s Bidirectional Encoder Representations from Transformer (BERT) [1] becoming the highlight by the end of 2018 for achieving state-of-the-art performance in many NLP tasks and not much later, OpenAI’s GPT-2 stealing the thunder by promising even more astonishing results which reportedly rendering it too dangerous to publish! Considering the time frame and the players behind these publications, it takes no effort to realize that there is a lot of activity in the space at the moment." }, { "code": null, "e": 983, "s": 812, "text": "That being said, we will focus on BERT for this post and attempt to have a small piece of this pie by extracting pre-trained contextualized word embeddings like ELMo [3]." }, { "code": null, "e": 1205, "s": 983, "text": "To give you a brief outline, I will first give a little bit of background context, then a take a high-level overview of BERT’s architecture, and lastly jump into the code while explaining some tricky parts here and there." }, { "code": null, "e": 1366, "s": 1205, "text": "Just for more convenience, I will be using Google’s Colab for the coding but the same code can as well run on your local environment without many modifications." }, { "code": null, "e": 1496, "s": 1366, "text": "If you came just for the coding part, skip to the β€œBERT Word Embedding Extraction” section. Find the finished notebook code here." }, { "code": null, "e": 2299, "s": 1496, "text": "To start off, embeddings are simply (moderately) low dimensional representations of a point in a higher dimensional vector space. In the same manner, word embeddings are dense vector representations of words in lower dimensional space. The first, word embedding model utilizing neural networks was published in 2013 [4] by research at Google. Since then, word embeddings are encountered in almost every NLP model used in practice today. Of course, the reason for such mass adoption is quite frankly their effectiveness. By translating a word to an embedding it becomes possible to model the semantic importance of a word in a numeric form and thus perform mathematical operations on it. To make this more clear I will give you the most common example that you can find in the context of word embeddings" }, { "code": null, "e": 2562, "s": 2299, "text": "When this was first possible by the word2vec model it was an amazing breakthrough. From there, many more advanced models surfaced which not only captured a static semantic meaning but also a contextualized meaning. For instance, consider the two sentences below:" }, { "code": null, "e": 2577, "s": 2562, "text": "I like apples." }, { "code": null, "e": 2599, "s": 2577, "text": "I like Apple macbooks" }, { "code": null, "e": 2843, "s": 2599, "text": "Note that the word apple has a different semantic meaning in each sentence. Now with a contextualized language model, the embedding of the word apple would have a different vector representation which makes it even more powerful for NLP tasks." }, { "code": null, "e": 2962, "s": 2843, "text": "However, I will leave the details of how that works, out of the scope of this post just to keep it short and on point." }, { "code": null, "e": 3550, "s": 2962, "text": "To be frank, much of the progress in the NLP space can be attributed to the advancements of general deep learning research. More particularly, Google (again!) presented a novel neural network architecture called a transformer in a seminal paper [5] which had many benefits over the conventional sequential models (LSTM, RNN, GRU etc). Advantages included but were not limited to, the more effective modeling of long term dependencies among tokens in a temporal sequence, and the more efficient training of the model in general by eliminating the sequential dependency on previous tokens." }, { "code": null, "e": 3794, "s": 3550, "text": "In a nutshell, a transformer is an encoder-decoder architecture model which uses attention mechanisms to forward a more complete picture of the whole sequence to the decoder at once rather than sequentially as illustrated in the figures below." }, { "code": null, "e": 3982, "s": 3794, "text": "Again, I won’t be describing details about how attention works as it will make the topic way more confusing and harder to digest. Feel free to follow the relevant paper in the references." }, { "code": null, "e": 4370, "s": 3982, "text": "OpenAI’s GPT was the first to create a transformer based language model with fine tuning but to be more precise, it was only using the decoder of the transformer. Therefore, making the language modeling uni-directional. The technical reason for dropping out the encoder was that language modeling would become a trivial task as the word to be predicted could have ultimately seen itself." }, { "code": null, "e": 4901, "s": 4370, "text": "By now, the name of the model should probably make more sense and give you a rough idea of what it is. BERT brought everything together to build a bidirectional transformer-based language model using encoders rather than decoders! To overcome the β€œsee itself” issue, the guys at Google had an ingenious idea. They employed masked language modeling. In other words, they hid 15% of the words and used their position information to infer them. Finally, they also mixed it up a little bit to make the learning process more effective." }, { "code": null, "e": 5073, "s": 4901, "text": "Although this methodology had a negative impact on convergence time, it outperformed state-of-the-art models even before convergence which sealed the success of the model." }, { "code": null, "e": 5353, "s": 5073, "text": "Normally, BERT represents a general language modeling which supports transfer learning and fine-tuning on specific tasks, however, in this post we will only touch the feature extraction side of BERT by just obtaining ELMo-like word embeddings from it, using Keras and TensorFlow." }, { "code": null, "e": 5571, "s": 5353, "text": "But hold your horses! Before we jump into the code let’s explore BERT’s architecture really quick so that we have a bit of background at implementation time. Believe me, it will make things a lot easier to understand." }, { "code": null, "e": 5621, "s": 5571, "text": "In fact, BERT developers created two main models:" }, { "code": null, "e": 5826, "s": 5621, "text": "The BASE: Number of transformer blocks (L): 12, Hidden layer size (H): 768 and Attention heads(A): 12The LARGE: Number of transformer blocks (L): 24, Hidden layer size (H): 1024 and Attention heads(A): 16" }, { "code": null, "e": 5928, "s": 5826, "text": "The BASE: Number of transformer blocks (L): 12, Hidden layer size (H): 768 and Attention heads(A): 12" }, { "code": null, "e": 6032, "s": 5928, "text": "The LARGE: Number of transformer blocks (L): 24, Hidden layer size (H): 1024 and Attention heads(A): 16" }, { "code": null, "e": 6124, "s": 6032, "text": "In this post, I will be using the BASE model as it is more than enough ( and way smaller!)." }, { "code": null, "e": 6197, "s": 6124, "text": "From a very high-level perspective, BERT’s architecture looks like this:" }, { "code": null, "e": 6307, "s": 6197, "text": "It may seem simple but remember that each encoder block encapsulates a more sophisticated model architecture." }, { "code": null, "e": 6486, "s": 6307, "text": "At this point, to make things clearer it is important to understand the special tokens that BERT authors used for fine-tuning and specific task training. These are the following:" }, { "code": null, "e": 6984, "s": 6486, "text": "[CLS] : The first token of every sequence. A classification token which is normally used in conjunction with a softmax layer for classification tasks. For anything else, it can be safely ignored.[SEP] : A sequence delimiter token which was used at pre-training for sequence-pair tasks (i.e. Next sentence prediction). Must be used when sequence pair tasks are required. When a single sequence is used it is just appended at the end.[MASK] : Token used for masked words. Only used for pre-training." }, { "code": null, "e": 7180, "s": 6984, "text": "[CLS] : The first token of every sequence. A classification token which is normally used in conjunction with a softmax layer for classification tasks. For anything else, it can be safely ignored." }, { "code": null, "e": 7418, "s": 7180, "text": "[SEP] : A sequence delimiter token which was used at pre-training for sequence-pair tasks (i.e. Next sentence prediction). Must be used when sequence pair tasks are required. When a single sequence is used it is just appended at the end." }, { "code": null, "e": 7484, "s": 7418, "text": "[MASK] : Token used for masked words. Only used for pre-training." }, { "code": null, "e": 7552, "s": 7484, "text": "Moving on, the input format that BERT expects is illustrated below:" }, { "code": null, "e": 7630, "s": 7552, "text": "As such, any input to be used with BERT must be formatted to match the above." }, { "code": null, "e": 7987, "s": 7630, "text": "The input layer is simply the vector of the sequence tokens along with the special tokens. The β€œ##ing” token in the example above may raise some eyebrows so to clarify, BERT utilizes WordPiece [6] for tokenization which in effect, splits token like β€œplaying” to β€œplay” and β€œ##ing”. This is mainly to cover a wider spectrum of Out-Of-Vocabulary (OOV) words." }, { "code": null, "e": 8051, "s": 7987, "text": "Token embeddings are the vocabulary IDs for each of the tokens." }, { "code": null, "e": 8136, "s": 8051, "text": "Sentence Embeddings is just a numeric class to distinguish between sentence A and B." }, { "code": null, "e": 8280, "s": 8136, "text": "And lastly, Transformer positional embeddings indicate the position of each word in the sequence. More details on this one can be found in [5]." }, { "code": null, "e": 8773, "s": 8280, "text": "Finally, there is one last thing. Everything is great is sofar, but how can I get word embeddings from this?!? As discussed, BERT base model uses 12 layers of transformer encoders, each output per token from each layer of these can be used as a word embedding! You probably wonder, which one is the best though? Well, I guess this depends on the task but empirically, the authors identified that one of the best performing choices was to sum the last 4 layers, which is what we will be doing." }, { "code": null, "e": 9086, "s": 8773, "text": "As illustrated the best performing option is to concatenate the last 4 layers but in this post, the summing approach is used for convenience. More particularly, the performance difference is not that much, and also there is more flexibility for truncating the dimensions further, without losing much information." }, { "code": null, "e": 9141, "s": 9086, "text": "Enough with the theory. Let’s move on to the practice." }, { "code": null, "e": 9266, "s": 9141, "text": "Firstly, create a new Google Colab notebook. Go to Edit->Notebook Settings and make sure hardware accelerator is set to TPU." }, { "code": null, "e": 9405, "s": 9266, "text": "Now, the first task is to clone the official BERT repository, add its directory to the path and import the appropriate modules from there." }, { "code": null, "e": 9756, "s": 9405, "text": "!rm -rf bert!git clone https://github.com/google-research/bertimport syssys.path.append('bert/')from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport codecsimport collectionsimport jsonimport reimport osimport pprintimport numpy as npimport tensorflow as tfimport modelingimport tokenization" }, { "code": null, "e": 9930, "s": 9756, "text": "The two modules imported from BERT are modeling and tokenization. Modeling includes the BERT model implementation and tokenization is obviously for tokenizing the sequences." }, { "code": null, "e": 10224, "s": 9930, "text": "Adding to this, we fetch our TPU address from colab and initialize a new tensorflow session. (Note that this only applies for Colab. When running locally, it is not needed). If you see any errors on when running the block below make sure you are using a TPU as hardware accelerator (see above)" }, { "code": null, "e": 10278, "s": 10224, "text": "Moving on, we select which BERT model we want to use." }, { "code": null, "e": 10676, "s": 10278, "text": "As you can see there are three available models that we can choose, but in reality, there are even more pre-trained models available for download in the official BERT GitHub repository. Those are just the models that have already been downloaded and hosted by Google in an open bucket so that can be accessed from Colaboratory. (For local use you need to download and extract a pre-trained model)." }, { "code": null, "e": 10889, "s": 10676, "text": "Recall the parameters from before: 12 L (transformer blocks) 768 H (hidden layer size) 12 A (attention heads) . β€œUncased” is just for lowercase sequences. In this example, we will use the uncased BERT BASE model." }, { "code": null, "e": 10950, "s": 10889, "text": "Furthermore, we define some global parameters for the model:" }, { "code": null, "e": 11199, "s": 10950, "text": "Most of the parameters above are pretty self-explanatory. In my opinion, the only one that may be a little bit tricky is the LAYERS array. Recall that we are using on the last 4 layers from the 12 hidden encoders. Hence, LAYERS keeps their indices." }, { "code": null, "e": 11314, "s": 11199, "text": "The next part is solely to define wrapper classes for the input before processing and after processing (Features)." }, { "code": null, "e": 11446, "s": 11314, "text": "In the InputExample class, we have set text_b to None by default since we aim to use single sequences rather than a sequence-pairs." }, { "code": null, "e": 11839, "s": 11446, "text": "Moreover, the InputFeatures class encapsulates the features that BERT needs for input (See input diagram above). The tokens property is clearly a vector of input tokens, input_ids are the ids that correspond to the token from the vocabulary, input_mask annotates real token sequence from padding and lastly, input_type_ids separates segment A from segment B so it is not really relevant here." }, { "code": null, "e": 11868, "s": 11839, "text": "Now, add the following code:" }, { "code": null, "e": 12399, "s": 11868, "text": "This is to set up our Estimator. An Estimator is just an abstraction for a model that tensorflow provides along with an API for training, evaluation, and prediction. Our custom estimator is, therefore, a wrapper around the BertModel. Admittedly there are parts of the code that can be removed from the above but I am sticking to the example that Google provided just for consistency. The important parts there is line 60 β€” where the bert model is defined β€” , and line 100 where the predictions from the top 4 layers are extracted." }, { "code": null, "e": 12444, "s": 12399, "text": "Continue along by also adding the following:" }, { "code": null, "e": 12568, "s": 12444, "text": "This is the function that takes care of the input processing. In other words, it transforms InputExamples to InputFeatures." }, { "code": null, "e": 12663, "s": 12568, "text": "Adding to these, we create a function for converting a normal string sequence to InputExample:" }, { "code": null, "e": 12909, "s": 12663, "text": "Now for the last bit of the code, we define a function which accepts an array of strings as a parameter and the desired dimension (max 768) of the embedding output and returns a dictionary with the token as key and the embedding vector as value." }, { "code": null, "e": 13012, "s": 12909, "text": "The above code snippet simply builds the estimator and invokes a prediction based on the given inputs." }, { "code": null, "e": 13063, "s": 13012, "text": "Let’s go ahead and test our model by running this:" }, { "code": null, "e": 13143, "s": 13063, "text": "embeddings = get_features([β€œThis is a test sentence”], dim=50)print(embeddings)" }, { "code": null, "e": 13488, "s": 13143, "text": "If everything goes well, you will have a dictionary containing the embeddings of size 50 per token. Remember that these are contextualized embeddings, so if you have duplicate tokens on different sequences only the embedding of the last token will be kept in the dictionary. To keep both, replace the dictionary with a different data structure." }, { "code": null, "e": 13529, "s": 13488, "text": "You can find the complete notebook here." }, { "code": null, "e": 13750, "s": 13529, "text": "Now, these embeddings can be used as input features for other models built for custom tasks. Nevertheless, I will save that for another post. Or even maybe implement a BERT Keras Layer for seamless embedding integration." }, { "code": null, "e": 13923, "s": 13750, "text": "That’s all from me folks. I hope you enjoyed the post and hopefully got a clearer picture around BERT. Feel free to post your feedback or questions in the comments section." }, { "code": null, "e": 14060, "s": 13923, "text": "[1] J.Devlin, M. Chang, K. Lee and K. Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (2018)" }, { "code": null, "e": 14207, "s": 14060, "text": "[2] Radford, Alec, Wu, Jeff, Child, Rewon, Luan, David, Amodei, Dario, Sutskever, Ilya, Language Models are Unsupervised Multitask Learners (2019)" }, { "code": null, "e": 14412, "s": 14207, "text": "[3] M. Peters, M. Neumann, M. Iyyer, M. Gardner, C. Clark, K.Lee and L.Zettlemoyer, Deep contextualized word representations (2018), North American Chapter of the Association for Computational Linguistics" }, { "code": null, "e": 14557, "s": 14412, "text": "[4] T.Mikolov, I. Sutskever, K. Chen, G. Corrado and J. Dean, Distributed Representations of Words and Phrases and their Compositionality (2013)" }, { "code": null, "e": 14690, "s": 14557, "text": "[5]A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A.Gomez, L. Kaiser and I. Polosukhin, Attention Is All You Need (2017)" } ]
C++ File Writer-Reader application using Windows Threads - GeeksforGeeks
01 May, 2020 In this article, we will create a simple Writer-Reader application, which uses two threads, one for Writing into the file and another for Reading from the file. Here we will discuss the approach using Win32 Threads in C/C++. A windows thread can be created using the CreateThread() method. Approach: Create a Thread function for Reading data from the file// Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open("sample.txt"); // Reading the data into the buffer cout << "Reading data from the file:"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;}Create a Thread function for Writing data into the file// Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open("sample.txt"); cout << "Enter data to write into the file:"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;}Create two threads using CreateThread function for both Writing and Reading data from the fileUse WaitForSingleObject to wait until the specified object is in the signaled state or time out interval elapses. Create a Thread function for Reading data from the file// Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open("sample.txt"); // Reading the data into the buffer cout << "Reading data from the file:"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;} // Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open("sample.txt"); // Reading the data into the buffer cout << "Reading data from the file:"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;} Create a Thread function for Writing data into the file// Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open("sample.txt"); cout << "Enter data to write into the file:"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;} // Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open("sample.txt"); cout << "Enter data to write into the file:"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;} Create two threads using CreateThread function for both Writing and Reading data from the file Use WaitForSingleObject to wait until the specified object is in the signaled state or time out interval elapses. Below is the implementation of the above program: // C++ program for File Writer-Reader// application using Windows Threads #include <fstream>#include <iostream>#include <string.h>#include <winsock2.h> using namespace std; // Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open("sample.txt"); // Reading the data into the buffer cout << "Reading data from the file:" << endl; fileReader >> buffer; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;} // Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open("sample.txt"); cout << "Enter data to write " << "into the file:" << endl; cin >> buffer; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;} // Driver codeint main(){ WSADATA WSAData; char buffer[1024]; DWORD tid; ofstream fileWriter; ifstream fileReader; HANDLE t1, t2; int choice, flag = 1; while (flag) { cout << "================================" << "========================" << "==================" << endl; cout << "Select your option" << "\t1.Run the application " << "\t2.Exit" << endl; cin >> choice; switch (choice) { case 1: // Create the first thread for Writing t1 = CreateThread(NULL, 0, WriteIntoAFile, &fileWriter, 0, &tid); WaitForSingleObject(t1, INFINITE); // Create the second thread for Reading t2 = CreateThread(NULL, 0, ReadFromAFile, &fileReader, 0, &tid); WaitForSingleObject(t2, INFINITE); break; case 2: // Exiting the application cout << "Thank you for using" << " the application" << endl; flag = 0; break; default: // For any query other than 1 and 2 cout << "Enter a valid query!!" << endl; } } return 0;} Run the application in the cmd using the command: g++ MultiThreading.cpp -lws2_32 Output: cpp-multithreading Articles C++ Programs Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction SQL | Date functions Time complexities of different data structures Difference between Class and Object Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character CSV file management using C++
[ { "code": null, "e": 24396, "s": 24368, "text": "\n01 May, 2020" }, { "code": null, "e": 24686, "s": 24396, "text": "In this article, we will create a simple Writer-Reader application, which uses two threads, one for Writing into the file and another for Reading from the file. Here we will discuss the approach using Win32 Threads in C/C++. A windows thread can be created using the CreateThread() method." }, { "code": null, "e": 24696, "s": 24686, "text": "Approach:" }, { "code": null, "e": 25984, "s": 24696, "text": "Create a Thread function for Reading data from the file// Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open(\"sample.txt\"); // Reading the data into the buffer cout << \"Reading data from the file:\"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;}Create a Thread function for Writing data into the file// Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open(\"sample.txt\"); cout << \"Enter data to write into the file:\"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;}Create two threads using CreateThread function for both Writing and Reading data from the fileUse WaitForSingleObject to wait until the specified object is in the signaled state or time out interval elapses." }, { "code": null, "e": 26537, "s": 25984, "text": "Create a Thread function for Reading data from the file// Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open(\"sample.txt\"); // Reading the data into the buffer cout << \"Reading data from the file:\"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;}" }, { "code": "// Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open(\"sample.txt\"); // Reading the data into the buffer cout << \"Reading data from the file:\"; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;}", "e": 27035, "s": 26537, "text": null }, { "code": null, "e": 27564, "s": 27035, "text": "Create a Thread function for Writing data into the file// Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open(\"sample.txt\"); cout << \"Enter data to write into the file:\"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;}" }, { "code": "// Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open(\"sample.txt\"); cout << \"Enter data to write into the file:\"; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;}", "e": 28038, "s": 27564, "text": null }, { "code": null, "e": 28133, "s": 28038, "text": "Create two threads using CreateThread function for both Writing and Reading data from the file" }, { "code": null, "e": 28247, "s": 28133, "text": "Use WaitForSingleObject to wait until the specified object is in the signaled state or time out interval elapses." }, { "code": null, "e": 28297, "s": 28247, "text": "Below is the implementation of the above program:" }, { "code": "// C++ program for File Writer-Reader// application using Windows Threads #include <fstream>#include <iostream>#include <string.h>#include <winsock2.h> using namespace std; // Thread function used to Read data from the fileDWORD WINAPI ReadFromAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ifstream object ifstream fileReader; // Opening the file in read mode fileReader.open(\"sample.txt\"); // Reading the data into the buffer cout << \"Reading data from the file:\" << endl; fileReader >> buffer; // Printing the data onto the console cout << buffer << endl; // Closing the opened file fileReader.close(); return 1;} // Thread function used to Write data into the fileDWORD WINAPI WriteIntoAFile(PVOID lpParam){ // Create a buffer char buffer[1024] = { 0 }; // Creating ofstream object ofstream fileWriter; // Opening the file in write mode fileWriter.open(\"sample.txt\"); cout << \"Enter data to write \" << \"into the file:\" << endl; cin >> buffer; // Write the given input into the file fileWriter << buffer << endl; // Closing the opened file fileWriter.close(); return 1;} // Driver codeint main(){ WSADATA WSAData; char buffer[1024]; DWORD tid; ofstream fileWriter; ifstream fileReader; HANDLE t1, t2; int choice, flag = 1; while (flag) { cout << \"================================\" << \"========================\" << \"==================\" << endl; cout << \"Select your option\" << \"\\t1.Run the application \" << \"\\t2.Exit\" << endl; cin >> choice; switch (choice) { case 1: // Create the first thread for Writing t1 = CreateThread(NULL, 0, WriteIntoAFile, &fileWriter, 0, &tid); WaitForSingleObject(t1, INFINITE); // Create the second thread for Reading t2 = CreateThread(NULL, 0, ReadFromAFile, &fileReader, 0, &tid); WaitForSingleObject(t2, INFINITE); break; case 2: // Exiting the application cout << \"Thank you for using\" << \" the application\" << endl; flag = 0; break; default: // For any query other than 1 and 2 cout << \"Enter a valid query!!\" << endl; } } return 0;}", "e": 30934, "s": 28297, "text": null }, { "code": null, "e": 30984, "s": 30934, "text": "Run the application in the cmd using the command:" }, { "code": null, "e": 31016, "s": 30984, "text": "g++ MultiThreading.cpp -lws2_32" }, { "code": null, "e": 31024, "s": 31016, "text": "Output:" }, { "code": null, "e": 31043, "s": 31024, "text": "cpp-multithreading" }, { "code": null, "e": 31052, "s": 31043, "text": "Articles" }, { "code": null, "e": 31065, "s": 31052, "text": "C++ Programs" }, { "code": null, "e": 31083, "s": 31065, "text": "Operating Systems" }, { "code": null, "e": 31101, "s": 31083, "text": "Operating Systems" }, { "code": null, "e": 31199, "s": 31101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31208, "s": 31199, "text": "Comments" }, { "code": null, "e": 31221, "s": 31208, "text": "Old Comments" }, { "code": null, "e": 31258, "s": 31221, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 31284, "s": 31258, "text": "Docker - COPY Instruction" }, { "code": null, "e": 31305, "s": 31284, "text": "SQL | Date functions" }, { "code": null, "e": 31352, "s": 31305, "text": "Time complexities of different data structures" }, { "code": null, "e": 31388, "s": 31352, "text": "Difference between Class and Object" }, { "code": null, "e": 31423, "s": 31388, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31482, "s": 31423, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 31508, "s": 31482, "text": "C++ Program for QuickSort" }, { "code": null, "e": 31552, "s": 31508, "text": "Program to print ASCII Value of a character" } ]
How to print Superscript and Subscript in Python? - GeeksforGeeks
24 Jan, 2021 Whenever we are working with formulas there may be a need of writing the given formula in a given format which may require subscripts or superscripts. There are several methods available to print subscripts and superscripts in Python. We will be discussing two of them below – Using maketrans() and translate() : We can make two strings one for the normal characters and the other for the subscript/superscript characters. After this, we can use the maketrans() method which returns a mapping that can be used with the translate() method to replace the specified characters. It can be implemented for superscripts as Python3 # function to convert to superscriptdef get_super(x): normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()" super_s = "ABcDEfGHIJKLMNOPQRsTUVWxyzabcdefghΙͺjklmnopΫΉrstuvwxyz0123456789+βˆ’=()" res = x.maketrans(''.join(normal), ''.join(super_s)) return x.translate(res) # display supersciptprint(get_super('GeeksforGeeks')) #GeeksforGeeks Output: GeeksforGeeks And for subscripts, we can implement it as Python3 # function to convert to subscriptdef get_sub(x): normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()" sub_s = "a8CDeΥ’GhijklmnopQrstuvwxΞ³Zaβ™­κœ€α‘―eΥ’9hijklmnop૧rstuvwxΞ³20123456789+βˆ’=()" res = x.maketrans(''.join(normal), ''.join(sub_s)) return x.translate(res) # display subscriptprint('H{}SO{}'.format(get_sub('2'),get_sub('4'))) #H2SO4 Output: H2SO4 Using Unicode subscripts and superscripts: The following table gives the subscripts and superscripts of the Unicode characters: With the help of the Unicode character, we can implement this in our codes as – Python3 # subscriptprint(u'H\u2082SO\u2084') # H2SO4 # superscriptprint("x\u00b2 + y\u00b2 = 2") # x2 + y2 = 2 Output: H2SO4 x2 + y2 = 2 Picked python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24489, "s": 24212, "text": "Whenever we are working with formulas there may be a need of writing the given formula in a given format which may require subscripts or superscripts. There are several methods available to print subscripts and superscripts in Python. We will be discussing two of them below –" }, { "code": null, "e": 24525, "s": 24489, "text": "Using maketrans() and translate() :" }, { "code": null, "e": 24830, "s": 24525, "text": "We can make two strings one for the normal characters and the other for the subscript/superscript characters. After this, we can use the maketrans() method which returns a mapping that can be used with the translate() method to replace the specified characters. It can be implemented for superscripts as " }, { "code": null, "e": 24838, "s": 24830, "text": "Python3" }, { "code": "# function to convert to superscriptdef get_super(x): normal = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()\" super_s = \"ABcDEfGHIJKLMNOPQRsTUVWxyzabcdefghΙͺjklmnopΫΉrstuvwxyz0123456789+βˆ’=()\" res = x.maketrans(''.join(normal), ''.join(super_s)) return x.translate(res) # display supersciptprint(get_super('GeeksforGeeks')) #GeeksforGeeks", "e": 25210, "s": 24838, "text": null }, { "code": null, "e": 25218, "s": 25210, "text": "Output:" }, { "code": null, "e": 25232, "s": 25218, "text": "GeeksforGeeks" }, { "code": null, "e": 25275, "s": 25232, "text": "And for subscripts, we can implement it as" }, { "code": null, "e": 25283, "s": 25275, "text": "Python3" }, { "code": "# function to convert to subscriptdef get_sub(x): normal = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()\" sub_s = \"a8CDeΥ’GhijklmnopQrstuvwxΞ³Zaβ™­κœ€α‘―eΥ’9hijklmnop૧rstuvwxΞ³20123456789+βˆ’=()\" res = x.maketrans(''.join(normal), ''.join(sub_s)) return x.translate(res) # display subscriptprint('H{}SO{}'.format(get_sub('2'),get_sub('4'))) #H2SO4", "e": 25655, "s": 25283, "text": null }, { "code": null, "e": 25663, "s": 25655, "text": "Output:" }, { "code": null, "e": 25669, "s": 25663, "text": "H2SO4" }, { "code": null, "e": 25712, "s": 25669, "text": "Using Unicode subscripts and superscripts:" }, { "code": null, "e": 25797, "s": 25712, "text": "The following table gives the subscripts and superscripts of the Unicode characters:" }, { "code": null, "e": 25877, "s": 25797, "text": "With the help of the Unicode character, we can implement this in our codes as –" }, { "code": null, "e": 25885, "s": 25877, "text": "Python3" }, { "code": "# subscriptprint(u'H\\u2082SO\\u2084') # H2SO4 # superscriptprint(\"x\\u00b2 + y\\u00b2 = 2\") # x2 + y2 = 2", "e": 25991, "s": 25885, "text": null }, { "code": null, "e": 25999, "s": 25991, "text": "Output:" }, { "code": null, "e": 26017, "s": 25999, "text": "H2SO4\nx2 + y2 = 2" }, { "code": null, "e": 26024, "s": 26017, "text": "Picked" }, { "code": null, "e": 26038, "s": 26024, "text": "python-string" }, { "code": null, "e": 26045, "s": 26038, "text": "Python" }, { "code": null, "e": 26143, "s": 26045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26152, "s": 26143, "text": "Comments" }, { "code": null, "e": 26165, "s": 26152, "text": "Old Comments" }, { "code": null, "e": 26197, "s": 26165, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26252, "s": 26197, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26308, "s": 26252, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26347, "s": 26308, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26389, "s": 26347, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26431, "s": 26389, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26453, "s": 26431, "text": "Defaultdict in Python" }, { "code": null, "e": 26484, "s": 26453, "text": "Python | os.path.join() method" }, { "code": null, "e": 26513, "s": 26484, "text": "Create a directory in Python" } ]
How to display PDF file in web page from Database in PHP
Theory of Computation In this article, you will learn how to display the PDF file on a webpage using PHP. PDF is one of the most trusted document format. PHP provides simple functionality to embed PDF files. It has a very simple implementation. Here, we have mentioned two ways to display PDF in a web page. It demands on how you want to show. If you want to include PDF as a sub part of a web page, then display them in an iframe as we mentioned in method1. If you want to make the PDF as a whole web content, then use the header() function as we mentioned in method2. Suppose we have a 'infopdf' TABLE in the Database as follows. You can use your existing database or copy and paste this in MySQL. CREATE TABLE IF NOT EXISTS `infopdf` ( `fileid` int(11) NOT NULL AUTO_INCREMENT, `filename` varchar(150) NOT NULL, `directory` varchar(150) NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`fileid`) ) INSERT INTO `infopdf` (`fileid`, `filename`, `directory`, `created_date`) VALUES (1, 'etp.pdf', '/document/', '2019-07-12'); Now, create a PHP file 'index.php' and write the database connection code at the top. For this, we are using Object Oriented PHP MySQLi connection code. Then, fetch the pdf file name and directory using select statement. To embed the PDF in a web page, we use the iframe element. <?php // Database Connection $conn = new mysqli('hostname', 'username', 'password', 'database'); //Check for connection error $select = "SELECT * FROM `infopdf`"; $result = $conn->query($select); while($row = $result->fetch_object()){ $pdf = $row->filename; $path = $row->directory; $date = $row->created_date; } echo '<h1>Here is the information PDF</h1>'; echo '<strong>Created Date : </strong>'.$date; echo '<strong>File Name : </strong>'.$pdf; ?> <br/><br/> <iframe src="<?php echo $path.$pdf; ?>" width="90%" height="500px"> </iframe> Here is the PDF file displayed on the webpage that is fetched from the MySQL database table using the PHP code: In the above method, we have embedded PDF in an iframe. This is basically used when we have to show a pdf in addition to the web contents. But if you want to display PDF as the whole content of webpage, then it's better to use header() function. In this below example, we have added header() function and set the file 'Content-type', 'Content-Disposition', 'Content-Transfer-Encoding'. We have used PHP predefined readfile() function to read the file and added error control operator (@) in front of it. When this operator pretended to an expression, any error or warning might be generated by this expression will be ignored. <?php // Database Connection $conn = new mysqli('hostname', 'username', 'password', 'database'); //Check for connection error $select = "SELECT * FROM `infopdf`"; $result = $conn->query($select); while($row = $result->fetch_object()){ $pdf = $row->filename; $path = $row->directory; $date = $row->created_date; $file = $path.$pdf; } // Add header to load pdf file header('Content-type: application/pdf'); header('Content-Disposition: inline; filename="' .$file. '"'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); @readfile($file); ?> Here is the PDF file displayed on the webpage that is fetched from the MySQL database table using the PHP code: Jan 3 Stateful vs Stateless A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... Dec 29 Best programming language to learn in 2021 In this article, we have mentioned the analyzed results of the best programming language for 2021... In this article, we have mentioned the analyzed results of the best programming language for 2021... Dec 20 How is Python best for mobile app development? Python has a set of useful Libraries and Packages that minimize the use of code... Python has a set of useful Libraries and Packages that minimize the use of code... July 18 Learn all about Emoji In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... Jan 10 Data Science Recruitment of Freshers In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... eTutorialsPointΒ©Copyright 2016-2022. All Rights Reserved.
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 197, "s": 112, "text": "In this article, you will learn how to display the PDF file on a webpage using PHP.\n" }, { "code": null, "e": 661, "s": 197, "text": "PDF is one of the most trusted document format. PHP provides simple functionality to embed PDF files. It has a very simple implementation. Here, we have mentioned two ways to display PDF in a web page. It demands on how you want to show. If you want to include PDF as a sub part of a web page, then display them in an iframe as we mentioned in method1. If you want to make the PDF as a whole web content, then use the header() function as we mentioned in method2." }, { "code": null, "e": 791, "s": 661, "text": "Suppose we have a 'infopdf' TABLE in the Database as follows. You can use your existing database or copy and paste this in MySQL." }, { "code": null, "e": 1006, "s": 791, "text": "CREATE TABLE IF NOT EXISTS `infopdf` (\n `fileid` int(11) NOT NULL AUTO_INCREMENT,\n `filename` varchar(150) NOT NULL,\n `directory` varchar(150) NOT NULL,\n `created_date` date NOT NULL,\n PRIMARY KEY (`fileid`)\n)" }, { "code": null, "e": 1131, "s": 1006, "text": "INSERT INTO `infopdf` (`fileid`, `filename`, `directory`, `created_date`) VALUES\n(1, 'etp.pdf', '/document/', '2019-07-12');" }, { "code": null, "e": 1411, "s": 1131, "text": "Now, create a PHP file 'index.php' and write the database connection code at the top. For this, we are using Object Oriented PHP MySQLi connection code. Then, fetch the pdf file name and directory using select statement. To embed the PDF in a web page, we use the iframe element." }, { "code": null, "e": 1960, "s": 1411, "text": "<?php\n// Database Connection \n$conn = new mysqli('hostname', 'username', 'password', 'database');\n//Check for connection error\n$select = \"SELECT * FROM `infopdf`\";\n$result = $conn->query($select);\nwhile($row = $result->fetch_object()){\n $pdf = $row->filename;\n $path = $row->directory;\n $date = $row->created_date;\n}\n\necho '<h1>Here is the information PDF</h1>';\necho '<strong>Created Date : </strong>'.$date;\necho '<strong>File Name : </strong>'.$pdf;\n?>\n<br/><br/>\n<iframe src=\"<?php echo $path.$pdf; ?>\" width=\"90%\" height=\"500px\">\n</iframe>\n" }, { "code": null, "e": 2072, "s": 1960, "text": "Here is the PDF file displayed on the webpage that is fetched from the MySQL database table using the PHP code:" }, { "code": null, "e": 2699, "s": 2072, "text": "In the above method, we have embedded PDF in an iframe. This is basically used when we have to show a pdf in addition to the web contents. But if you want to display PDF as the whole content of webpage, then it's better to use header() function. In this below example, we have added header() function and set the file 'Content-type', 'Content-Disposition', 'Content-Transfer-Encoding'. We have used PHP predefined readfile() function to read the file and added error control operator (@) in front of it. When this operator pretended to an expression, any error or warning might be generated by this expression will be ignored." }, { "code": null, "e": 3280, "s": 2699, "text": "<?php\n// Database Connection \n$conn = new mysqli('hostname', 'username', 'password', 'database');\n//Check for connection error\n$select = \"SELECT * FROM `infopdf`\";\n$result = $conn->query($select);\nwhile($row = $result->fetch_object()){\n $pdf = $row->filename;\n $path = $row->directory;\n $date = $row->created_date;\n $file = $path.$pdf;\n}\n// Add header to load pdf file\nheader('Content-type: application/pdf'); \nheader('Content-Disposition: inline; filename=\"' .$file. '\"'); \nheader('Content-Transfer-Encoding: binary'); \nheader('Accept-Ranges: bytes'); \n@readfile($file); \n?>" }, { "code": null, "e": 3392, "s": 3280, "text": "Here is the PDF file displayed on the webpage that is fetched from the MySQL database table using the PHP code:" }, { "code": null, "e": 3538, "s": 3392, "text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n" }, { "code": null, "e": 3654, "s": 3538, "text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..." }, { "code": null, "e": 3807, "s": 3654, "text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n" }, { "code": null, "e": 3908, "s": 3807, "text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..." }, { "code": null, "e": 4047, "s": 3908, "text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n" }, { "code": null, "e": 4130, "s": 4047, "text": "Python has a set of useful Libraries and Packages that minimize the use of code..." }, { "code": null, "e": 4296, "s": 4130, "text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n" }, { "code": null, "e": 4430, "s": 4296, "text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..." }, { "code": null, "e": 4597, "s": 4430, "text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n" }, { "code": null, "e": 4718, "s": 4597, "text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..." } ]
DB2 - Backup and Recovery
This chapter describes backup and restore methods of database. Backup and recovery methods are designed to keep our information safe. In Command Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery utilities you can take backup or restore the data of databases in DB2 UDB. Log files consist of error logs, which are used to recover from application errors. The logs keep the record of changes in the database. There are two types of logging as described below: It is a method where the old transaction logs are overwritten when there is a need to allocate a new transaction log file, thus erasing the sequences of log files and reusing them. You are permitted to take only full back-up in offline mode. i.e., the database must be offline to take the full backup. This mode supports for Online Backup and database recovery using log files called roll forward recovery. The mode of backup can be changed from circular to archive by setting logretain or userexit to ON. For archive logging, backup setting database require a directory that is writable for DB2 process. Using Backup command you can take copy of entire database. This backup copy includes database system files, data files, log files, control information and so on. You can take backup while working offline as well as online. Syntax: [To list the active applications/databases] db2 list application Output: Auth Id Application Appl. Application Id DB # of Name Handle Name Agents -------- -------------- ---------- --------------------- ----------------------------------------- -------- ----- DB2INST1 db2bp 39 *LOCAL.db2inst1.140722043938 ONE 1 Syntax: [To force application using app. Handled id] db2 "force application (39)" Output: DB20000I The FORCE APPLICATION command completed successfully. DB21024I This command is asynchronous and may not be effective immediately. Syntax: [To terminate Database Connection] db2 terminate Syntax: [To deactivate Database] db2 deactivate database one Syntax: [To take the backup file] db2 backup database <db_name> to <location> Example: db2 backup database one to /home/db2inst1/ Output: Backup successful. The timestamp for this backup image is : 20140722105345 To start, you need to change the mode from Circular logging to Archive Logging. Syntax: [To check if the database is using circular or archive logging] db2 get db cfg for one | grep LOGARCH Output: First log archive method (LOGARCHMETH1) = OFF Archive compression for logarchmeth1 (LOGARCHCOMPR1) = OFF Options for logarchmeth1 (LOGARCHOPT1) = Second log archive method (LOGARCHMETH2) = OFF Archive compression for logarchmeth2 (LOGARCHCOMPR2) = OFF Options for logarchmeth2 (LOGARCHOPT2) = In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in off mode, which implies that the current database in β€œCIRCULLAR LOGGING” mode. If you need to work with β€˜ARCHIVE LOGGING’ mode, you need to change or add path in the variables logarchmeth1 and logarchmeth2 present in the configuration file. Syntax: [To make directories] mkdir backup mkdir backup/ArchiveDest Syntax: [To provide user permissions for folder] chown db2inst1:db2iadm1 backup/ArchiveDest Syntax: [To update configuration LOGARCHMETH1] db2 update database configuration for one using LOGARCHMETH1 'DISK:/home/db2inst1/backup/ArchiveDest' You can take offline backup for safety, activate the database and connect to it. Syntax: [To take online backup] db2 backup database one online to /home/db2inst1/onlinebackup/ compress include logs Output: db2 backup database one online to /home/db2inst1/onlinebackup/ compress include logs Verify Backup file using following command: Syntax: db2ckbkp <location/backup file> Example: db2ckbkp /home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001 Listing the history of backup files Syntax: db2 list history backup all for one Output: List History File for one Number of matching file entries = 4 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID -- --- ------------------ ---- --- ------------ ------------ -------------- B D 20140722105345001 F D S0000000.LOG S0000000.LOG ------------------------------------------------------------ ---------------- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ------------------------------------------------------------ ---------------- Comment: DB2 BACKUP ONE OFFLINE Start Time: 20140722105345 End Time: 20140722105347 Status: A ------------------------------------------------------------ ---------------- EID: 3 Location: /home/db2inst1 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID -- --- ------------------ ---- --- ------------ ------------ -------------- B D 20140722112239000 N S0000000.LOG S0000000.LOG ------------------------------------------------------------ ------------------------------------------------------------- ------------------------------- Comment: DB2 BACKUP ONE ONLINE Start Time: 20140722112239 End Time: 20140722112240 Status: A ------------------------------------------------------------ ---------------- EID: 4 Location: SQLCA Information sqlcaid : SQLCA sqlcabc: 136 sqlcode: -2413 sqlerrml: 0 sqlerrmc: sqlerrp : sqlubIni sqlerrd : (1) 0 (2) 0 (3) 0 (4) 0 (5) 0 (6) 0 sqlwarn : (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) sqlstate: Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID -- --- ------------------ ---- --- ------------ ------------ -------------- B D 20140722112743001 F D S0000000.LOG S0000000.LOG ------------------------------------------------------------ ---------------- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ------------------------------------------------------------- ---------------- Comment: DB2 BACKUP ONE OFFLINE Start Time: 20140722112743 End Time: 20140722112743 Status: A ------------------------------------------------------------- ---------------- EID: 5 Location: /home/db2inst1 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID ------------------------------------------------------------- ---------------- R D 20140722114519001 F 20140722112743 ------------------------------------------------------------ ---------------- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ------------------------------------------------------------ ---------------- Comment: RESTORE ONE WITH RF Start Time: 20140722114519 End Time: 20140722115015 Status: A ------------------------------------------------------------ ---------------- EID: 6 Location: To restore the database from backup file, you need to follow the given syntax: Syntax: db2 restore database <db_name> from <location> taken at <timestamp> Example: db2 restore database one from /home/db2inst1/ taken at 20140722112743 Output: SQL2523W Warning! Restoring to an existing database that is different from the database on the backup image, but have matching names. The target database will be overwritten by the backup version. The Roll-forward recovery logs associated with the target database will be deleted. Do you want to continue ? (y/n) y DB20000I The RESTORE DATABASE command completed successfully. Roll forward all the logs located in the log directory, including latest changes just before the disk drive failure. Syntax: db2 rollforward db <db_name> to end of logs and stop Example: db2 rollforward db one to end of logs and stop Output: Rollforward Status Input database alias = one Number of members have returned status = 1 Member ID = 0 Rollforward status = not pending Next log file to be read = Log files processed = S0000000.LOG - S0000001.LOG Last committed transaction = 2014-07-22- 06.00.33.000000 UTC DB20000I The ROLLFORWARD command completed successfully. 10 Lectures 1.5 hours Nishant Malik 41 Lectures 8.5 hours Parth Panjabi 53 Lectures 11.5 hours Parth Panjabi 33 Lectures 7 hours Parth Panjabi 44 Lectures 3 hours Arnab Chakraborty 178 Lectures 14.5 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 1991, "s": 1928, "text": "This chapter describes backup and restore methods of database." }, { "code": null, "e": 2229, "s": 1991, "text": "Backup and recovery methods are designed to keep our information safe. In Command Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery utilities you can take backup or restore the data of databases in DB2 UDB." }, { "code": null, "e": 2418, "s": 2229, "text": "Log files consist of error logs, which are used to recover from application errors. The logs keep the record of changes in the database. There are two types of logging as described below:" }, { "code": null, "e": 2720, "s": 2418, "text": "It is a method where the old transaction logs are overwritten when there is a need to allocate a new transaction log file, thus erasing the sequences of log files and reusing them. You are permitted to take only full back-up in offline mode. i.e., the database must be offline to take the full backup." }, { "code": null, "e": 3023, "s": 2720, "text": "This mode supports for Online Backup and database recovery using log files called roll forward recovery. The mode of backup can be changed from circular to archive by setting logretain or userexit to ON. For archive logging, backup setting database require a directory that is writable for DB2 process." }, { "code": null, "e": 3185, "s": 3023, "text": "Using Backup command you can take copy of entire database. This backup copy includes database system files, data files, log files, control information and so on." }, { "code": null, "e": 3246, "s": 3185, "text": "You can take backup while working offline as well as online." }, { "code": null, "e": 3298, "s": 3246, "text": "Syntax: [To list the active applications/databases]" }, { "code": null, "e": 3321, "s": 3298, "text": "db2 list application " }, { "code": null, "e": 3329, "s": 3321, "text": "Output:" }, { "code": null, "e": 3735, "s": 3329, "text": "Auth Id Application Appl. Application Id \nDB # of \n Name Handle \nName Agents \n-------- -------------- ---------- ---------------------\n----------------------------------------- -------- ----- \nDB2INST1 db2bp 39 \n*LOCAL.db2inst1.140722043938 \nONE 1 " }, { "code": null, "e": 3788, "s": 3735, "text": "Syntax: [To force application using app. Handled id]" }, { "code": null, "e": 3820, "s": 3788, "text": "db2 \"force application (39)\" " }, { "code": null, "e": 3828, "s": 3820, "text": "Output:" }, { "code": null, "e": 3975, "s": 3828, "text": "DB20000I The FORCE APPLICATION command completed \nsuccessfully. \n\nDB21024I This command is asynchronous and may not \nbe effective immediately. " }, { "code": null, "e": 4018, "s": 3975, "text": "Syntax: [To terminate Database Connection]" }, { "code": null, "e": 4034, "s": 4018, "text": "db2 terminate " }, { "code": null, "e": 4067, "s": 4034, "text": "Syntax: [To deactivate Database]" }, { "code": null, "e": 4098, "s": 4067, "text": "db2 deactivate database one " }, { "code": null, "e": 4132, "s": 4098, "text": "Syntax: [To take the backup file]" }, { "code": null, "e": 4179, "s": 4132, "text": "db2 backup database <db_name> to <location> " }, { "code": null, "e": 4188, "s": 4179, "text": "Example:" }, { "code": null, "e": 4232, "s": 4188, "text": "db2 backup database one to /home/db2inst1/ " }, { "code": null, "e": 4240, "s": 4232, "text": "Output:" }, { "code": null, "e": 4318, "s": 4240, "text": "Backup successful. The timestamp for this backup image is : \n20140722105345 " }, { "code": null, "e": 4398, "s": 4318, "text": "To start, you need to change the mode from Circular logging to Archive Logging." }, { "code": null, "e": 4470, "s": 4398, "text": "Syntax: [To check if the database is using circular or archive logging]" }, { "code": null, "e": 4511, "s": 4470, "text": "db2 get db cfg for one | grep LOGARCH " }, { "code": null, "e": 4519, "s": 4511, "text": "Output:" }, { "code": null, "e": 4870, "s": 4519, "text": "First log archive method (LOGARCHMETH1) = OFF \n Archive compression for logarchmeth1 (LOGARCHCOMPR1) = OFF \n Options for logarchmeth1 (LOGARCHOPT1) = \n Second log archive method (LOGARCHMETH2) = OFF \n Archive compression for logarchmeth2 (LOGARCHCOMPR2) = OFF \n Options for logarchmeth2 (LOGARCHOPT2) = " }, { "code": null, "e": 5194, "s": 4870, "text": "In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in off mode, which implies that the current database in β€œCIRCULLAR LOGGING” mode. If you need to work with β€˜ARCHIVE LOGGING’ mode, you need to change or add path in the variables logarchmeth1 and logarchmeth2 present in the configuration file." }, { "code": null, "e": 5224, "s": 5194, "text": "Syntax: [To make directories]" }, { "code": null, "e": 5267, "s": 5224, "text": "mkdir backup \nmkdir backup/ArchiveDest " }, { "code": null, "e": 5316, "s": 5267, "text": "Syntax: [To provide user permissions for folder]" }, { "code": null, "e": 5360, "s": 5316, "text": "chown db2inst1:db2iadm1 backup/ArchiveDest " }, { "code": null, "e": 5407, "s": 5360, "text": "Syntax: [To update configuration LOGARCHMETH1]" }, { "code": null, "e": 5510, "s": 5407, "text": "db2 update database configuration for one using LOGARCHMETH1 \n'DISK:/home/db2inst1/backup/ArchiveDest'" }, { "code": null, "e": 5591, "s": 5510, "text": "You can take offline backup for safety, activate the database and connect to it." }, { "code": null, "e": 5623, "s": 5591, "text": "Syntax: [To take online backup]" }, { "code": null, "e": 5712, "s": 5623, "text": "db2 backup database one online to \n/home/db2inst1/onlinebackup/ compress include logs " }, { "code": null, "e": 5720, "s": 5712, "text": "Output:" }, { "code": null, "e": 5810, "s": 5720, "text": "db2 backup database one online to \n/home/db2inst1/onlinebackup/ compress include logs " }, { "code": null, "e": 5854, "s": 5810, "text": "Verify Backup file using following command:" }, { "code": null, "e": 5862, "s": 5854, "text": "Syntax:" }, { "code": null, "e": 5897, "s": 5862, "text": "db2ckbkp <location/backup file> " }, { "code": null, "e": 5906, "s": 5897, "text": "Example:" }, { "code": null, "e": 5976, "s": 5906, "text": "db2ckbkp \n/home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001 " }, { "code": null, "e": 6012, "s": 5976, "text": "Listing the history of backup files" }, { "code": null, "e": 6020, "s": 6012, "text": "Syntax:" }, { "code": null, "e": 6060, "s": 6020, "text": "db2 list history backup all for one " }, { "code": null, "e": 6068, "s": 6060, "text": "Output:" }, { "code": null, "e": 9351, "s": 6068, "text": " List History File for one \n \nNumber of matching file entries = 4 \n \nOp Obj Timestamp+Sequence Type Dev Earliest Log Current Log \nBackup ID \n -- --- ------------------ ---- --- ------------ ------------ \n --------------\n B D 20140722105345001 F D S0000000.LOG S0000000.LOG \n\n ------------------------------------------------------------ \n ---------------- \n \n Contains 4 tablespace(s): \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1\n \n 00003 SYSTOOLSPACE \n \n 00004 TS1 \n ------------------------------------------------------------ \n ---------------- \n Comment: DB2 BACKUP ONE OFFLINE \n \n Start Time: 20140722105345 \n \n End Time: 20140722105347\n \n Status: A\n ------------------------------------------------------------ \n ---------------- \n EID: 3 Location: /home/db2inst1 \n\n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID\n -- --- ------------------ ---- --- ------------ ------------ \n -------------- \n B D 20140722112239000 N S0000000.LOG S0000000.LOG \n ------------------------------------------------------------ \n ------------------------------------------------------------- \n ------------------------------- \n \n Comment: DB2 BACKUP ONE ONLINE \n \n Start Time: 20140722112239 \n \n End Time: 20140722112240 \n \n Status: A \n ------------------------------------------------------------ \n ---------------- \n EID: 4 Location: \nSQLCA Information \n \n sqlcaid : SQLCA sqlcabc: 136 sqlcode: -2413 sqlerrml: 0 \n \n sqlerrmc: \n sqlerrp : sqlubIni \n sqlerrd : (1) 0 (2) 0 (3) 0 \n \n (4) 0 (5) 0 (6) 0 \n\t\t \n sqlwarn : (1) (2) (3) (4) (5) (6) \n \n (7) (8) (9) (10) (11) \n sqlstate: \n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID\n -- --- ------------------ ---- --- ------------ ------------ \n -------------- \n B D 20140722112743001 F D S0000000.LOG S0000000.LOG \n \n ------------------------------------------------------------ \n ---------------- \n Contains 4 tablespace(s): \n \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1 \n \n 00003 SYSTOOLSPACE \n \n 00004 TS1\n ------------------------------------------------------------- \n ---------------- \n Comment: DB2 BACKUP ONE OFFLINE \n \n Start Time: 20140722112743 \n \n End Time: 20140722112743 \n \n Status: A \n ------------------------------------------------------------- \n ---------------- \n EID: 5 Location: /home/db2inst1 \n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID \n ------------------------------------------------------------- \n ----------------\n \nR D 20140722114519001 F \n20140722112743 \n\n ------------------------------------------------------------ \n ---------------- \n Contains 4 tablespace(s): \n \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1 \n \n 00003 SYSTOOLSPACE \n \n 00004 TS1\n ------------------------------------------------------------ \n ---------------- \nComment: RESTORE ONE WITH RF\n \n Start Time: 20140722114519 \n \n End Time: 20140722115015 \n Status: A \n\t \n ------------------------------------------------------------ \n ---------------- \n EID: 6 Location: " }, { "code": null, "e": 9430, "s": 9351, "text": "To restore the database from backup file, you need to follow the given syntax:" }, { "code": null, "e": 9438, "s": 9430, "text": "Syntax:" }, { "code": null, "e": 9511, "s": 9438, "text": "db2 restore database <db_name> from <location> \ntaken at <timestamp> " }, { "code": null, "e": 9520, "s": 9511, "text": "Example:" }, { "code": null, "e": 9593, "s": 9520, "text": "db2 restore database one from /home/db2inst1/ taken at \n20140722112743 " }, { "code": null, "e": 9601, "s": 9593, "text": "Output:" }, { "code": null, "e": 10003, "s": 9601, "text": "SQL2523W Warning! Restoring to an existing database that is \ndifferent from \n \nthe database on the backup image, but have matching names. \nThe target database \n \nwill be overwritten by the backup version. The Roll-forward \nrecovery logs\n\nassociated with the target database will be deleted. \n\nDo you want to continue ? (y/n) y \n \nDB20000I The RESTORE DATABASE command completed successfully. " }, { "code": null, "e": 10120, "s": 10003, "text": "Roll forward all the logs located in the log directory, including latest changes just before the disk drive failure." }, { "code": null, "e": 10128, "s": 10120, "text": "Syntax:" }, { "code": null, "e": 10184, "s": 10128, "text": "db2 rollforward db <db_name> to end of logs and stop " }, { "code": null, "e": 10193, "s": 10184, "text": "Example:" }, { "code": null, "e": 10242, "s": 10193, "text": "db2 rollforward db one to end of logs and stop " }, { "code": null, "e": 10250, "s": 10242, "text": "Output:" }, { "code": null, "e": 10754, "s": 10250, "text": " Rollforward Status \n Input database alias = one \n Number of members have returned status = 1 \n Member ID = 0 \n Rollforward status = not pending \n Next log file to be read = \n Log files processed = S0000000.LOG - \n S0000001.LOG \n Last committed transaction = 2014-07-22- \n 06.00.33.000000 UTC \nDB20000I The ROLLFORWARD command completed successfully. " }, { "code": null, "e": 10789, "s": 10754, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10804, "s": 10789, "text": " Nishant Malik" }, { "code": null, "e": 10839, "s": 10804, "text": "\n 41 Lectures \n 8.5 hours \n" }, { "code": null, "e": 10854, "s": 10839, "text": " Parth Panjabi" }, { "code": null, "e": 10890, "s": 10854, "text": "\n 53 Lectures \n 11.5 hours \n" }, { "code": null, "e": 10905, "s": 10890, "text": " Parth Panjabi" }, { "code": null, "e": 10938, "s": 10905, "text": "\n 33 Lectures \n 7 hours \n" }, { "code": null, "e": 10953, "s": 10938, "text": " Parth Panjabi" }, { "code": null, "e": 10986, "s": 10953, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 11005, "s": 10986, "text": " Arnab Chakraborty" }, { "code": null, "e": 11042, "s": 11005, "text": "\n 178 Lectures \n 14.5 hours \n" }, { "code": null, "e": 11061, "s": 11042, "text": " Arnab Chakraborty" }, { "code": null, "e": 11068, "s": 11061, "text": " Print" }, { "code": null, "e": 11079, "s": 11068, "text": " Add Notes" } ]
Handle missing data with R: 10 daily used idioms | by Pavlo Horbonos | Towards Data Science
Data cleaning is one of the most time-consuming stages of the Data Analysis process. Many of its steps include acquainting the dataset, search of the missing values, their imputation or removing, and possibly a lot of repetitions of the same code lines but for different variables or their combinations. So, we have to search and accept any possibilities to speed the process up. Some time ago I have presented the article about short Python idioms for missing values in datasets. Today I have prepared the compilation of similar scripts but in R language. Also, we will work again with the wines reviews dataset from Kaggle. Yes, vectors in R start with 1, but before handling missing values we should have a dataset with missing values. Sometimes empty records are filled with substitutional strings like spaces (β€œ β€œ), β€œempty”, β€œnan”, or some garbage. To start the work we should substitute them with β€œreal” NA values. Lucky for us, we can do it at the stage of dataset opening: wine_data <- read.csv(β€˜winemag-data-130k-v2.csv’, na.string = c(β€˜β€™, β€˜i’, β€˜P’)) na.string accepts a vector of substitutional values. In the beginning, we need to check the presence of missing values. We have is.na() for these purposes. It receives data and returns a boolean vector. Check if a single value missing:is.na(wine_data$region_1[2]) Get rows with missing elements in some columns:wine_data[is.na(wine_data$country),] Check if there are NO missing values in a column:all(!is.na(wine_data$points)) Check if there is ANY missing value in a column:any(is.na(wine_data$country)) Previous scripts require some knowledge about the dataset and access to separate elements. But what if we want to see the whole picture? The answer is na.fail() function. It throws an exception if there is any missing value in whole data: na.fail(wine_data) There is a special function, which replaces a bunch of filters and indexes. It is mostly used with data frames and may be used to show all the rows with any missing value (in any column): complete.cases(). It returns a boolean vector and is very convenient for indexing. Get the number of rows with missing datasum(!complete.cases(wine_data)) Get THE rows with missing datawine_data[!complete.cases(wine_data), ] All previous scripts are mostly used for exploratory tasks: to show, to acquire, etc.. But what if we need to get the indexes of missing values? In this case, we should use which() function: which(is.na(wine_data$country))#returns indexes of rows with missing data It seems, that the only purpose of NA values existence is to be removed. Though, we may use them in some very interesting combinations. For example, we have a vector of mixed data: test_vec <- c( 'ten', '5', 'n', '25', '10') And we want to separate β€œconvertible” strings (like β€˜5’ or β€˜25’) from the others. We can do it together with is.na() function: test_vec[!is.na(as.numeric(test_vec))]# returns ( '5', '25', '10' ) NAs presence has some side effects β€” it turns the resulting value of almost any operation into NA. But there is a solution β€” a lot of R functions have built-in na.rm argument, which allows skipping missing values. mean(wine_data$price)# returns NAmean(wine_data$price, na.rm = T)# returns the result You can take a look at the previous scripts and think, that omitting of missing values is a very tedious job. Well, yes, it is. But in case if need to remove all NA at once and forget them as a nightmare β€” R has the next functions for us: wine_data_totally_cleared_1 <- na.omit(wine_data)wine_data_totally_cleared_2 <- wine_data[complete.cases(wine_data),] As you see β€” we can use as special function na.omit() as already known complete.cases(). The result is the same: there will be no more missing values in the dataset. When we build some filters, we expect the result to have only matching values. It becomes especially valuable while working with data frames. But if you run, for example, this command: wine_data_condition_NA <- wine_data[wine_data$price > 20,] you will get not the correct subset only, but all the missing values too. It is the result of R data frame indexing, boolean arrays, and NA nature: missing value turns the condition result into NA which is treated as not FALSE. And we still have the pain of missing values search. The solution is subset() function: wine_data_condition <- subset(wine_data, wine_data$price > 20) It returns the correct subset, but without NAs, which are filtered away. Let’s return to the step when we looked at the whole picture of the dataset. We want to see the distribution of missing values, maybe some patterns, or dependency between variables. And we have another R package with the desired function β€” β€œmice” package. It contains functions, which walk through the dataset, count all the omissions, and build the picture of the dataset. For example, let’s take the sample: wine_data[1:5, 4:8]. It contains the next data: As we see, there are some missing values. Let’s apply md.pattern() function from the mentioned package: require(mice)md.pattern(wine_data[1:5, 4:8], plot = F) And we get the table of patterns: The leftmost index shows the number of rows. The rightmost index shows the number of missing features. The central matrix shows the patterns: which features combination is absent in the counted rows. So the first line tells us, that there are 2 rows with no absent data (0 missing features). And the third line shows, that there is 1 row in the data fragment with 1 missing feature β€” with price missing. Now we are ready to visualize the distribution of missing values. We have another R package for this job β€” VIM library. Among many other functions it plots the distribution histogram of empty records and builds a visual representation of patterns table from the previous step: require(VIM)aggr_plot <- aggr(wine_data, col=c(β€˜navyblue’,’red’), numbers=TRUE, labels=colnames(wine_data), ylab=c(β€œHistogram of missing data”,”Pattern”)) We have got a beautiful picture: Now we can see, for example, that almost 60% of the rows have no region_2 value. As for me, you should bring these code snippets to automatism. And you will gather significant analysis speeding. Also, as always, you may find the code with working examples on my GitHub: github.com Make sure, that you have seen my previous article about Python idioms:
[ { "code": null, "e": 551, "s": 171, "text": "Data cleaning is one of the most time-consuming stages of the Data Analysis process. Many of its steps include acquainting the dataset, search of the missing values, their imputation or removing, and possibly a lot of repetitions of the same code lines but for different variables or their combinations. So, we have to search and accept any possibilities to speed the process up." }, { "code": null, "e": 797, "s": 551, "text": "Some time ago I have presented the article about short Python idioms for missing values in datasets. Today I have prepared the compilation of similar scripts but in R language. Also, we will work again with the wines reviews dataset from Kaggle." }, { "code": null, "e": 1152, "s": 797, "text": "Yes, vectors in R start with 1, but before handling missing values we should have a dataset with missing values. Sometimes empty records are filled with substitutional strings like spaces (β€œ β€œ), β€œempty”, β€œnan”, or some garbage. To start the work we should substitute them with β€œreal” NA values. Lucky for us, we can do it at the stage of dataset opening:" }, { "code": null, "e": 1253, "s": 1152, "text": "wine_data <- read.csv(β€˜winemag-data-130k-v2.csv’, na.string = c(β€˜β€™, β€˜i’, β€˜P’))" }, { "code": null, "e": 1306, "s": 1253, "text": "na.string accepts a vector of substitutional values." }, { "code": null, "e": 1456, "s": 1306, "text": "In the beginning, we need to check the presence of missing values. We have is.na() for these purposes. It receives data and returns a boolean vector." }, { "code": null, "e": 1517, "s": 1456, "text": "Check if a single value missing:is.na(wine_data$region_1[2])" }, { "code": null, "e": 1601, "s": 1517, "text": "Get rows with missing elements in some columns:wine_data[is.na(wine_data$country),]" }, { "code": null, "e": 1680, "s": 1601, "text": "Check if there are NO missing values in a column:all(!is.na(wine_data$points))" }, { "code": null, "e": 1758, "s": 1680, "text": "Check if there is ANY missing value in a column:any(is.na(wine_data$country))" }, { "code": null, "e": 1997, "s": 1758, "text": "Previous scripts require some knowledge about the dataset and access to separate elements. But what if we want to see the whole picture? The answer is na.fail() function. It throws an exception if there is any missing value in whole data:" }, { "code": null, "e": 2016, "s": 1997, "text": "na.fail(wine_data)" }, { "code": null, "e": 2287, "s": 2016, "text": "There is a special function, which replaces a bunch of filters and indexes. It is mostly used with data frames and may be used to show all the rows with any missing value (in any column): complete.cases(). It returns a boolean vector and is very convenient for indexing." }, { "code": null, "e": 2359, "s": 2287, "text": "Get the number of rows with missing datasum(!complete.cases(wine_data))" }, { "code": null, "e": 2429, "s": 2359, "text": "Get THE rows with missing datawine_data[!complete.cases(wine_data), ]" }, { "code": null, "e": 2620, "s": 2429, "text": "All previous scripts are mostly used for exploratory tasks: to show, to acquire, etc.. But what if we need to get the indexes of missing values? In this case, we should use which() function:" }, { "code": null, "e": 2694, "s": 2620, "text": "which(is.na(wine_data$country))#returns indexes of rows with missing data" }, { "code": null, "e": 2875, "s": 2694, "text": "It seems, that the only purpose of NA values existence is to be removed. Though, we may use them in some very interesting combinations. For example, we have a vector of mixed data:" }, { "code": null, "e": 2919, "s": 2875, "text": "test_vec <- c( 'ten', '5', 'n', '25', '10')" }, { "code": null, "e": 3046, "s": 2919, "text": "And we want to separate β€œconvertible” strings (like β€˜5’ or β€˜25’) from the others. We can do it together with is.na() function:" }, { "code": null, "e": 3114, "s": 3046, "text": "test_vec[!is.na(as.numeric(test_vec))]# returns ( '5', '25', '10' )" }, { "code": null, "e": 3328, "s": 3114, "text": "NAs presence has some side effects β€” it turns the resulting value of almost any operation into NA. But there is a solution β€” a lot of R functions have built-in na.rm argument, which allows skipping missing values." }, { "code": null, "e": 3414, "s": 3328, "text": "mean(wine_data$price)# returns NAmean(wine_data$price, na.rm = T)# returns the result" }, { "code": null, "e": 3653, "s": 3414, "text": "You can take a look at the previous scripts and think, that omitting of missing values is a very tedious job. Well, yes, it is. But in case if need to remove all NA at once and forget them as a nightmare β€” R has the next functions for us:" }, { "code": null, "e": 3771, "s": 3653, "text": "wine_data_totally_cleared_1 <- na.omit(wine_data)wine_data_totally_cleared_2 <- wine_data[complete.cases(wine_data),]" }, { "code": null, "e": 3937, "s": 3771, "text": "As you see β€” we can use as special function na.omit() as already known complete.cases(). The result is the same: there will be no more missing values in the dataset." }, { "code": null, "e": 4122, "s": 3937, "text": "When we build some filters, we expect the result to have only matching values. It becomes especially valuable while working with data frames. But if you run, for example, this command:" }, { "code": null, "e": 4181, "s": 4122, "text": "wine_data_condition_NA <- wine_data[wine_data$price > 20,]" }, { "code": null, "e": 4462, "s": 4181, "text": "you will get not the correct subset only, but all the missing values too. It is the result of R data frame indexing, boolean arrays, and NA nature: missing value turns the condition result into NA which is treated as not FALSE. And we still have the pain of missing values search." }, { "code": null, "e": 4497, "s": 4462, "text": "The solution is subset() function:" }, { "code": null, "e": 4560, "s": 4497, "text": "wine_data_condition <- subset(wine_data, wine_data$price > 20)" }, { "code": null, "e": 4633, "s": 4560, "text": "It returns the correct subset, but without NAs, which are filtered away." }, { "code": null, "e": 5091, "s": 4633, "text": "Let’s return to the step when we looked at the whole picture of the dataset. We want to see the distribution of missing values, maybe some patterns, or dependency between variables. And we have another R package with the desired function β€” β€œmice” package. It contains functions, which walk through the dataset, count all the omissions, and build the picture of the dataset. For example, let’s take the sample: wine_data[1:5, 4:8]. It contains the next data:" }, { "code": null, "e": 5195, "s": 5091, "text": "As we see, there are some missing values. Let’s apply md.pattern() function from the mentioned package:" }, { "code": null, "e": 5250, "s": 5195, "text": "require(mice)md.pattern(wine_data[1:5, 4:8], plot = F)" }, { "code": null, "e": 5284, "s": 5250, "text": "And we get the table of patterns:" }, { "code": null, "e": 5688, "s": 5284, "text": "The leftmost index shows the number of rows. The rightmost index shows the number of missing features. The central matrix shows the patterns: which features combination is absent in the counted rows. So the first line tells us, that there are 2 rows with no absent data (0 missing features). And the third line shows, that there is 1 row in the data fragment with 1 missing feature β€” with price missing." }, { "code": null, "e": 5965, "s": 5688, "text": "Now we are ready to visualize the distribution of missing values. We have another R package for this job β€” VIM library. Among many other functions it plots the distribution histogram of empty records and builds a visual representation of patterns table from the previous step:" }, { "code": null, "e": 6120, "s": 5965, "text": "require(VIM)aggr_plot <- aggr(wine_data, col=c(β€˜navyblue’,’red’), numbers=TRUE, labels=colnames(wine_data), ylab=c(β€œHistogram of missing data”,”Pattern”))" }, { "code": null, "e": 6153, "s": 6120, "text": "We have got a beautiful picture:" }, { "code": null, "e": 6234, "s": 6153, "text": "Now we can see, for example, that almost 60% of the rows have no region_2 value." }, { "code": null, "e": 6423, "s": 6234, "text": "As for me, you should bring these code snippets to automatism. And you will gather significant analysis speeding. Also, as always, you may find the code with working examples on my GitHub:" }, { "code": null, "e": 6434, "s": 6423, "text": "github.com" } ]
Tryit Editor v3.7
Tryit: HTML image map - execute a function
[]
Object Detection Using YOLOv3 on Colab with questions for interview preparation | by Manish Sharma | Towards Data Science
This blog will help you to train a model which can identify different objects in an image. It’s fun and exciting to observe how the model can behave better than humans in certain conditions. It can differentiate between car and pickup truck even if the rear of the truck is not clear in an image, personally, I wasn’t able to make that difference. In case you have already used YOLO as a black box this blog will help you to understand the model and its nuances. Finally, there are some questions that can help you to gauge your understanding of the model. Try to answer the questions in the comment section and don’t hesitate to ask me if you need an answer. Requirements: A pc with an internet connection and a Google account. Learnings: An hands-on experience of object detection using YOLOv3 to deepen the understanding of YOLO algorithm. Setup: Set up a Colab notebook account through your google drive (My Drive > New > More > Connect More apps > Colab). To perform the object detection on images in your pc install β€˜Drive Backup and Sync’. Allow one folder on your pc to sync on google drive. The files (images or videos) from this folder will be accessed by Colab (via google drive). Object detection The object detection part is divided into 9 easy steps. It will allow you to apply object detection on the images clicked by you. So let’s begin the object detection first and later on I will explain the algorithm (YOLO) behind it. STEP1: Connect your Colab notebook with google drive. Once you import and mount the drive, you need to click on the link which appears below your code. You need to allow the Colab to access the drive by permitting it. from google.colab import drivedrive.mount('/content.gdrive') Step2: Change the hardware accelerator to GPU (Runtime > Change Runtime type > Hardware accelerator = GPU). To make sure you are connected to GPU, type !nvidia-smi, if you are connected you should get the details of GPU you are connected (as shown below). !nvidia-smi Step3: Darknet is an open-source neural network written by Joseph Redmon. It is written in C and CUDA. It supports both CPU and GPU computation. The official implementation of the darknet is available at: https://pjreddie.com/darknet/ . We will use a slightly modified version of the darknet available at AlexyAB/darknet. This neural network framework can be used for object detection using YOLO. #clone darknet repositoryimport osos.environ['PATH'] += ':/usr/local/cuda/bin'!rm -fr darknet!git clone https://github.com/AlexeyAB/darknet Step4: Check the current directory using !pwd. We should be in /content/darknet folder. Or else change to darknet folder (%cd /darknet). Once in this folder, we using stream editor (sed) to edit the make files of GPU and OpenCV (in, in-place mode, i.e, sed -i). We change all the instances of GPU=0 to GPU =1, to enable GPU and OpenCV. #go to the darknet folder, edit and remake Makefiles of GPU and OPENCV!sed -i 's/GPU=0/GPU=1/g' Makefile!sed -i 's/OPENCV=0/OPENCV=1/g' Makefile!make Step5: Loading the pre-trained weights for YOLO object detection. We get the pre-trained weights for YOLOv3 from pjreddie.com. This website belongs to Joseph Redmon the man behind YOLO and darknet. # get yolov3 weights!wget https://pjreddie.com/media/files/yolov3.weights!chmod a+x ./darknet Step6: Make sure that you are in the correct directory (/content/darknet) using !pwd. If yes, then install the required packages. For the complete list, I will encourage you to have a look at my jupyter file on github. !apt install ffmpeg libopencv-dev libgtk-3-dev python-numpy python3-numpy libdc1394-22 libdc1394-22-dev libjpeg-dev libtiff5-dev libavcodec-dev libavformat-dev libswscale-dev libxine2-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libv4l-dev libtbb-dev qtbase5-dev libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev x264 v4l-utils unzip Step7: Loading the image from your drive to Colab and running YOLO on it. You can transfer any image from your pc to the folder you shared with google drive in step 1. That image will appear in the same folder in the drive. In my case, I named the folder β€˜darknet’ and the name of the image is β€˜test2.jpg’. The address of the folder will be: /content.gdrive/My Drive/darknet/test2.jpg but since space is not allowed in the address path you can use: /content.gdrive/My\ Drive/darknet/test2.jpg. !./darknet detect cfg/yolov3.cfg yolov3.weights /content.gdrive/My\ Drive/darknet/test2.jpg Step8: You need OpenCV and matplotlib to view your result. If you are on this step first of all congratulations that you have run your very first YOLO object detection using your image. import cv2import matplotlib.pyplot as pltimport os.pathfig,ax = plt.subplots()ax.tick_params(labelbottom="off",bottom="off")ax.tick_params(labelleft="off",left="off")ax.set_xticklabels([])ax.axis('off')file = './predictions.jpg'if os.path.exists(file):img = cv2.imread(file)show_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)#show_img(show_img)plt.imshow(show_img)plt.show()#cv2.imshow(img) Step9: Result analysis. Here you can see that algorithm can correctly detect a baby as a person, cell phone, and hairbrush (as a toothbrush). While several other items (hairdryer, small purse, makeup items)can’t be detected. Can you guess the reason? Maybe you should check the weights we used were trained on which all objects. Here I have presented an exercise to help new users to start object detection by just using their pc. Moreover, users can use their images so it will further add to their fun. Once you are done with this fun part it will be intriguing to know how YOLO can detect the objects. Let’s try to learn how does the algorithm works. YOLO (link to original paper ): You Only Look Once is an object detection network. It localizes and classifies an object. It does both these tasks in a single step. The backbone of YOLO in the darknet-53 neural network, there are 53 convolutional layers in the network for feature extraction. YOLO divides the input image in m x m grid. Each cell of the grid contains some (B) anchor boxes to localize the object. For an object, the cell in which the center of the object lies is responsible for detecting the object. Let’s try to understand the output vector which will give insights into different aspects of this algorithm. The output vector will consist of B * (5 + C) elements. B is the number of anchor boxes that are present in each cell. Each box will give a probability element showing what’s the probability of an object being present in the cell, 4 elements describing the bounding box (2 for center coordinates bx, by and other two to describe height and width of the box bh and bw). C is the number of classes. If there are 6 classes then there will be 11 elements per box, and if there are 3 boxes then in totality there will be 33 elements in the output. YOLOv3 is among the fastest object detection algorithm currently present. The speed comes at the cost of accuracy. It makes a high error in object localization compared to fast R-CNN but still, it makes less background error compared to later. To detect multiple objects per cell, it makes use of multiple anchor boxes per cell. Of course, these anchors would be of a different dimension. Let’s say one is a wider rectangle (lengthwise) other being a longer rectangle (width-wise). One other aspect to mention is to get rid of multiple bounding boxes per object it uses standard non-max suppression. You may comment on your answers in the comment section or ask me in case you want me to answer any of these. I will highly appreciate it if you could answer the questions for which you know the answers, other readers will definitely get benefitted because of your comments. Q1. An n x n image convolved with a filter of size f x f, padding of p and stride of s, what will be the size of output? Do check what happens if there is no padding and f & s both are equal to 2. Q2. Why are fully connected layers required in an object detection neural network? Q3. List down the strategy/methods for data augmentation. Q4. What is the difference between the anchor box and the bounding box in YOLO? Q5. How is mean average precision calculated? Q6. Explain the concept of NMS or non-max suppression? Q7. What are the different components of the loss function in YOLO? To access the complete jupyter file: click here. I hope this blog gives you comprehensive hands-on practice on YOLO and would help you start with your journey in object detection. In case you wish to discuss more feel free to comment.
[ { "code": null, "e": 832, "s": 172, "text": "This blog will help you to train a model which can identify different objects in an image. It’s fun and exciting to observe how the model can behave better than humans in certain conditions. It can differentiate between car and pickup truck even if the rear of the truck is not clear in an image, personally, I wasn’t able to make that difference. In case you have already used YOLO as a black box this blog will help you to understand the model and its nuances. Finally, there are some questions that can help you to gauge your understanding of the model. Try to answer the questions in the comment section and don’t hesitate to ask me if you need an answer." }, { "code": null, "e": 901, "s": 832, "text": "Requirements: A pc with an internet connection and a Google account." }, { "code": null, "e": 1015, "s": 901, "text": "Learnings: An hands-on experience of object detection using YOLOv3 to deepen the understanding of YOLO algorithm." }, { "code": null, "e": 1364, "s": 1015, "text": "Setup: Set up a Colab notebook account through your google drive (My Drive > New > More > Connect More apps > Colab). To perform the object detection on images in your pc install β€˜Drive Backup and Sync’. Allow one folder on your pc to sync on google drive. The files (images or videos) from this folder will be accessed by Colab (via google drive)." }, { "code": null, "e": 1381, "s": 1364, "text": "Object detection" }, { "code": null, "e": 1613, "s": 1381, "text": "The object detection part is divided into 9 easy steps. It will allow you to apply object detection on the images clicked by you. So let’s begin the object detection first and later on I will explain the algorithm (YOLO) behind it." }, { "code": null, "e": 1831, "s": 1613, "text": "STEP1: Connect your Colab notebook with google drive. Once you import and mount the drive, you need to click on the link which appears below your code. You need to allow the Colab to access the drive by permitting it." }, { "code": null, "e": 1892, "s": 1831, "text": "from google.colab import drivedrive.mount('/content.gdrive')" }, { "code": null, "e": 2148, "s": 1892, "text": "Step2: Change the hardware accelerator to GPU (Runtime > Change Runtime type > Hardware accelerator = GPU). To make sure you are connected to GPU, type !nvidia-smi, if you are connected you should get the details of GPU you are connected (as shown below)." }, { "code": null, "e": 2160, "s": 2148, "text": "!nvidia-smi" }, { "code": null, "e": 2557, "s": 2160, "text": "Step3: Darknet is an open-source neural network written by Joseph Redmon. It is written in C and CUDA. It supports both CPU and GPU computation. The official implementation of the darknet is available at: https://pjreddie.com/darknet/ . We will use a slightly modified version of the darknet available at AlexyAB/darknet. This neural network framework can be used for object detection using YOLO." }, { "code": null, "e": 2697, "s": 2557, "text": "#clone darknet repositoryimport osos.environ['PATH'] += ':/usr/local/cuda/bin'!rm -fr darknet!git clone https://github.com/AlexeyAB/darknet" }, { "code": null, "e": 3033, "s": 2697, "text": "Step4: Check the current directory using !pwd. We should be in /content/darknet folder. Or else change to darknet folder (%cd /darknet). Once in this folder, we using stream editor (sed) to edit the make files of GPU and OpenCV (in, in-place mode, i.e, sed -i). We change all the instances of GPU=0 to GPU =1, to enable GPU and OpenCV." }, { "code": null, "e": 3183, "s": 3033, "text": "#go to the darknet folder, edit and remake Makefiles of GPU and OPENCV!sed -i 's/GPU=0/GPU=1/g' Makefile!sed -i 's/OPENCV=0/OPENCV=1/g' Makefile!make" }, { "code": null, "e": 3381, "s": 3183, "text": "Step5: Loading the pre-trained weights for YOLO object detection. We get the pre-trained weights for YOLOv3 from pjreddie.com. This website belongs to Joseph Redmon the man behind YOLO and darknet." }, { "code": null, "e": 3475, "s": 3381, "text": "# get yolov3 weights!wget https://pjreddie.com/media/files/yolov3.weights!chmod a+x ./darknet" }, { "code": null, "e": 3694, "s": 3475, "text": "Step6: Make sure that you are in the correct directory (/content/darknet) using !pwd. If yes, then install the required packages. For the complete list, I will encourage you to have a look at my jupyter file on github." }, { "code": null, "e": 4105, "s": 3694, "text": "!apt install ffmpeg libopencv-dev libgtk-3-dev python-numpy python3-numpy libdc1394-22 libdc1394-22-dev libjpeg-dev libtiff5-dev libavcodec-dev libavformat-dev libswscale-dev libxine2-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libv4l-dev libtbb-dev qtbase5-dev libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev x264 v4l-utils unzip" }, { "code": null, "e": 4599, "s": 4105, "text": "Step7: Loading the image from your drive to Colab and running YOLO on it. You can transfer any image from your pc to the folder you shared with google drive in step 1. That image will appear in the same folder in the drive. In my case, I named the folder β€˜darknet’ and the name of the image is β€˜test2.jpg’. The address of the folder will be: /content.gdrive/My Drive/darknet/test2.jpg but since space is not allowed in the address path you can use: /content.gdrive/My\\ Drive/darknet/test2.jpg." }, { "code": null, "e": 4691, "s": 4599, "text": "!./darknet detect cfg/yolov3.cfg yolov3.weights /content.gdrive/My\\ Drive/darknet/test2.jpg" }, { "code": null, "e": 4877, "s": 4691, "text": "Step8: You need OpenCV and matplotlib to view your result. If you are on this step first of all congratulations that you have run your very first YOLO object detection using your image." }, { "code": null, "e": 5264, "s": 4877, "text": "import cv2import matplotlib.pyplot as pltimport os.pathfig,ax = plt.subplots()ax.tick_params(labelbottom=\"off\",bottom=\"off\")ax.tick_params(labelleft=\"off\",left=\"off\")ax.set_xticklabels([])ax.axis('off')file = './predictions.jpg'if os.path.exists(file):img = cv2.imread(file)show_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)#show_img(show_img)plt.imshow(show_img)plt.show()#cv2.imshow(img)" }, { "code": null, "e": 5593, "s": 5264, "text": "Step9: Result analysis. Here you can see that algorithm can correctly detect a baby as a person, cell phone, and hairbrush (as a toothbrush). While several other items (hairdryer, small purse, makeup items)can’t be detected. Can you guess the reason? Maybe you should check the weights we used were trained on which all objects." }, { "code": null, "e": 5869, "s": 5593, "text": "Here I have presented an exercise to help new users to start object detection by just using their pc. Moreover, users can use their images so it will further add to their fun. Once you are done with this fun part it will be intriguing to know how YOLO can detect the objects." }, { "code": null, "e": 5918, "s": 5869, "text": "Let’s try to learn how does the algorithm works." }, { "code": null, "e": 6211, "s": 5918, "text": "YOLO (link to original paper ): You Only Look Once is an object detection network. It localizes and classifies an object. It does both these tasks in a single step. The backbone of YOLO in the darknet-53 neural network, there are 53 convolutional layers in the network for feature extraction." }, { "code": null, "e": 6436, "s": 6211, "text": "YOLO divides the input image in m x m grid. Each cell of the grid contains some (B) anchor boxes to localize the object. For an object, the cell in which the center of the object lies is responsible for detecting the object." }, { "code": null, "e": 7088, "s": 6436, "text": "Let’s try to understand the output vector which will give insights into different aspects of this algorithm. The output vector will consist of B * (5 + C) elements. B is the number of anchor boxes that are present in each cell. Each box will give a probability element showing what’s the probability of an object being present in the cell, 4 elements describing the bounding box (2 for center coordinates bx, by and other two to describe height and width of the box bh and bw). C is the number of classes. If there are 6 classes then there will be 11 elements per box, and if there are 3 boxes then in totality there will be 33 elements in the output." }, { "code": null, "e": 7332, "s": 7088, "text": "YOLOv3 is among the fastest object detection algorithm currently present. The speed comes at the cost of accuracy. It makes a high error in object localization compared to fast R-CNN but still, it makes less background error compared to later." }, { "code": null, "e": 7688, "s": 7332, "text": "To detect multiple objects per cell, it makes use of multiple anchor boxes per cell. Of course, these anchors would be of a different dimension. Let’s say one is a wider rectangle (lengthwise) other being a longer rectangle (width-wise). One other aspect to mention is to get rid of multiple bounding boxes per object it uses standard non-max suppression." }, { "code": null, "e": 7962, "s": 7688, "text": "You may comment on your answers in the comment section or ask me in case you want me to answer any of these. I will highly appreciate it if you could answer the questions for which you know the answers, other readers will definitely get benefitted because of your comments." }, { "code": null, "e": 8159, "s": 7962, "text": "Q1. An n x n image convolved with a filter of size f x f, padding of p and stride of s, what will be the size of output? Do check what happens if there is no padding and f & s both are equal to 2." }, { "code": null, "e": 8242, "s": 8159, "text": "Q2. Why are fully connected layers required in an object detection neural network?" }, { "code": null, "e": 8300, "s": 8242, "text": "Q3. List down the strategy/methods for data augmentation." }, { "code": null, "e": 8380, "s": 8300, "text": "Q4. What is the difference between the anchor box and the bounding box in YOLO?" }, { "code": null, "e": 8426, "s": 8380, "text": "Q5. How is mean average precision calculated?" }, { "code": null, "e": 8481, "s": 8426, "text": "Q6. Explain the concept of NMS or non-max suppression?" }, { "code": null, "e": 8549, "s": 8481, "text": "Q7. What are the different components of the loss function in YOLO?" }, { "code": null, "e": 8598, "s": 8549, "text": "To access the complete jupyter file: click here." } ]
Map in C++ Standard Template Library (STL) - GeeksforGeeks
17 Jan, 2022 Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Some basic functions associated with Map: begin() – Returns an iterator to the first element in the map. end() – Returns an iterator to the theoretical element that follows the last element in the map. size() – Returns the number of elements in the map. max_size() – Returns the maximum number of elements that the map can hold. empty() – Returns whether the map is empty. pair insert(keyvalue, mapvalue) – Adds a new element to the map. erase(iterator position) – Removes the element at the position pointed by the iterator. erase(const g)– Removes the key-value β€˜g’ from the map. clear() – Removes all the elements from the map. Implementation: CPP // CPP Program to demonstrate the implementation in Map#include <iostream>#include <iterator>#include <map>using namespace std; int main(){ // empty map container map<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(4, 20)); gquiz1.insert(pair<int, int>(5, 50)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(7, 10)); // printing map gquiz1 map<int, int>::iterator itr; cout << "\nThe map gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the map gquiz2 cout << "\nThe map gquiz2 after" << " assign from gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // remove all elements up to // element with key=3 in gquiz2 cout << "\ngquiz2 after removal of" " elements less than key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // lower bound and upper bound for map gquiz1 key = 5 cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0;} The map gquiz1 is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 6 50 7 10 The map gquiz2 after assign from gquiz1 is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 6 50 7 10 gquiz2 after removal of elements less than key=3 : KEY ELEMENT 3 60 4 20 5 50 6 50 7 10 gquiz2.erase(4) : 1 removed KEY ELEMENT 3 60 5 50 6 50 7 10 gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 50 gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50 Recent Articles on Map YouTubeGeeksforGeeks501K subscribersC++ Programming Language Tutorial | Map in C++ STL | 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 / 1:50β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=kDwXAmLz47w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 cpp-containers-library cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Socket Programming in C/C++ Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples rand() and srand() in C/C++ unordered_map in C++ STL Friend class and function in C++
[ { "code": null, "e": 26962, "s": 26934, "text": "\n17 Jan, 2022" }, { "code": null, "e": 27135, "s": 26962, "text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values." }, { "code": null, "e": 27178, "s": 27135, "text": "Some basic functions associated with Map: " }, { "code": null, "e": 27241, "s": 27178, "text": "begin() – Returns an iterator to the first element in the map." }, { "code": null, "e": 27338, "s": 27241, "text": "end() – Returns an iterator to the theoretical element that follows the last element in the map." }, { "code": null, "e": 27390, "s": 27338, "text": "size() – Returns the number of elements in the map." }, { "code": null, "e": 27465, "s": 27390, "text": "max_size() – Returns the maximum number of elements that the map can hold." }, { "code": null, "e": 27509, "s": 27465, "text": "empty() – Returns whether the map is empty." }, { "code": null, "e": 27574, "s": 27509, "text": "pair insert(keyvalue, mapvalue) – Adds a new element to the map." }, { "code": null, "e": 27662, "s": 27574, "text": "erase(iterator position) – Removes the element at the position pointed by the iterator." }, { "code": null, "e": 27718, "s": 27662, "text": "erase(const g)– Removes the key-value β€˜g’ from the map." }, { "code": null, "e": 27767, "s": 27718, "text": "clear() – Removes all the elements from the map." }, { "code": null, "e": 27783, "s": 27767, "text": "Implementation:" }, { "code": null, "e": 27787, "s": 27783, "text": "CPP" }, { "code": "// CPP Program to demonstrate the implementation in Map#include <iostream>#include <iterator>#include <map>using namespace std; int main(){ // empty map container map<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(4, 20)); gquiz1.insert(pair<int, int>(5, 50)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(7, 10)); // printing map gquiz1 map<int, int>::iterator itr; cout << \"\\nThe map gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the map gquiz2 cout << \"\\nThe map gquiz2 after\" << \" assign from gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // remove all elements up to // element with key=3 in gquiz2 cout << \"\\ngquiz2 after removal of\" \" elements less than key=3 : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << \"\\ngquiz2.erase(4) : \"; cout << num << \" removed \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // lower bound and upper bound for map gquiz1 key = 5 cout << \"gquiz1.lower_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.lower_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.lower_bound(5)->second << endl; cout << \"gquiz1.upper_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.upper_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.upper_bound(5)->second << endl; return 0;}", "e": 30172, "s": 27787, "text": null }, { "code": null, "e": 30790, "s": 30172, "text": "The map gquiz1 is : \n KEY ELEMENT\n 1 40\n 2 30\n 3 60\n 4 20\n 5 50\n 6 50\n 7 10\n\n\nThe map gquiz2 after assign from gquiz1 is : \n KEY ELEMENT\n 1 40\n 2 30\n 3 60\n 4 20\n 5 50\n 6 50\n 7 10\n\n\ngquiz2 after removal of elements less than key=3 : \n KEY ELEMENT\n 3 60\n 4 20\n 5 50\n 6 50\n 7 10\n\ngquiz2.erase(4) : 1 removed \n KEY ELEMENT\n 3 60\n 5 50\n 6 50\n 7 10\n\ngquiz1.lower_bound(5) : KEY = 5 ELEMENT = 50\ngquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50" }, { "code": null, "e": 30815, "s": 30790, "text": " Recent Articles on Map " }, { "code": null, "e": 31664, "s": 30815, "text": "YouTubeGeeksforGeeks501K subscribersC++ Programming Language Tutorial | Map in C++ STL | 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 / 1:50β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=kDwXAmLz47w\" 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": 31789, "s": 31664, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31803, "s": 31789, "text": "anshikajain26" }, { "code": null, "e": 31826, "s": 31803, "text": "cpp-containers-library" }, { "code": null, "e": 31834, "s": 31826, "text": "cpp-map" }, { "code": null, "e": 31838, "s": 31834, "text": "STL" }, { "code": null, "e": 31842, "s": 31838, "text": "C++" }, { "code": null, "e": 31846, "s": 31842, "text": "STL" }, { "code": null, "e": 31850, "s": 31846, "text": "CPP" }, { "code": null, "e": 31948, "s": 31850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31957, "s": 31948, "text": "Comments" }, { "code": null, "e": 31970, "s": 31957, "text": "Old Comments" }, { "code": null, "e": 31988, "s": 31970, "text": "Vector in C++ STL" }, { "code": null, "e": 32034, "s": 31988, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 32057, "s": 32034, "text": "std::sort() in C++ STL" }, { "code": null, "e": 32085, "s": 32057, "text": "Socket Programming in C/C++" }, { "code": null, "e": 32112, "s": 32085, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 32136, "s": 32112, "text": "Virtual Function in C++" }, { "code": null, "e": 32167, "s": 32136, "text": "Templates in C++ with Examples" }, { "code": null, "e": 32195, "s": 32167, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 32220, "s": 32195, "text": "unordered_map in C++ STL" } ]
Folium: Create Interactive Leaflet Maps | by Himanshu Sharma | Towards Data Science
In this article, we will explore Folium, a Python library which makes it easy to visualize data that’s been manipulated in Python on an interactive leaflet map. The maps created using folium are highly interactive which makes it even more useful for dashboard building. So let’s start exploring Folium and learn on our way of exploring it. We can install folium by running the following given below command in our command prompt. pip install folium After installing folium we need to import it in our Jupiter notebook to start working. Folium is an easy to understand library by which you can create highly interactive and visually appealing maps in just a few lines of code. Here we will learn how we can use it to create a world map. For this, we just need to call the Map() function. The code given below will help you understand this better. #importing folium libraryimport folium# calling Map() functionworld_map = folium.Map()#displaying world mapworld_map The map created above is interactive i.e. you can actually zoom-in and zoom-out of the map using the β€˜+’ and β€˜-’ or by just using the cursor of your mouse. We can pass the β€˜location’ argument which contains the longitude and latitude of a particular location to Map() function to display the map of the desired location. For example, you can see the code below I used to create the map of Russia using its coordinates. Here I have also passed an attribute named β€˜zoom_start’ which already zoom-in accordingly. mah_map = folium.Map(location=[61.5240, 105.3188], zoom_start=3)mah_map Further, you can use folium for creating different types of maps. Some of them I have explained below. These are the high contrast Black & White maps. They are perfect for data mashups and exploring river meanders and coastal zones. For creating this we just need to add an attribute to Map() function named β€˜tiles’ and set it to Stamen Toner. The code below is used to create a Stamen Toner map of India. india_map = folium.Map(location=[20.5937, 78.9629 ], zoom_start=4, tiles='Stamen Toner')india_map These maps show hill shading and natural vegetation colors. They also showcase the advanced labeling and linework generalization of dual-carriageway roads. For creating this we need to set the value of attribute tiles as Stamen Terrain. The below code will produce the Stamen Terrain map of India. india_map = folium.Map(location=[20.5937, 78.9629 ], zoom_start=4, tiles='Stamen Terrain')india_map Other than this there are many more tile options like β€˜Mapbox Bright’ etc. that you can explore and learn. Folium also has a marker function that marks the desired location of your choice of given coordinates. We can also select the icon for the marker. Below Given code is used to create a map and displaying the marker on the desired location. my_map = folium.Map(location=[20.5937, 78.9629], zoom_start=4, tiles='Stamen Terrain')folium.Marker([28.73158, 77.13267], popup='MyLocation', marker_icon='cloud').add_to(my_map)my_map In this article, we explored a beautiful library Folium use to create leaflet maps that are interactive and visually appealing. We can use these maps in our dashboards or as needed. Folium is easy to understand the library and creates a map in just one line of code. This article is just a basic understanding of folium, go ahead, and explore folium for many more features. towardsdatascience.com towardsdatascience.com Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can also view the code and data I have used here in my Github.
[ { "code": null, "e": 332, "s": 171, "text": "In this article, we will explore Folium, a Python library which makes it easy to visualize data that’s been manipulated in Python on an interactive leaflet map." }, { "code": null, "e": 511, "s": 332, "text": "The maps created using folium are highly interactive which makes it even more useful for dashboard building. So let’s start exploring Folium and learn on our way of exploring it." }, { "code": null, "e": 601, "s": 511, "text": "We can install folium by running the following given below command in our command prompt." }, { "code": null, "e": 620, "s": 601, "text": "pip install folium" }, { "code": null, "e": 847, "s": 620, "text": "After installing folium we need to import it in our Jupiter notebook to start working. Folium is an easy to understand library by which you can create highly interactive and visually appealing maps in just a few lines of code." }, { "code": null, "e": 1017, "s": 847, "text": "Here we will learn how we can use it to create a world map. For this, we just need to call the Map() function. The code given below will help you understand this better." }, { "code": null, "e": 1134, "s": 1017, "text": "#importing folium libraryimport folium# calling Map() functionworld_map = folium.Map()#displaying world mapworld_map" }, { "code": null, "e": 1290, "s": 1134, "text": "The map created above is interactive i.e. you can actually zoom-in and zoom-out of the map using the β€˜+’ and β€˜-’ or by just using the cursor of your mouse." }, { "code": null, "e": 1644, "s": 1290, "text": "We can pass the β€˜location’ argument which contains the longitude and latitude of a particular location to Map() function to display the map of the desired location. For example, you can see the code below I used to create the map of Russia using its coordinates. Here I have also passed an attribute named β€˜zoom_start’ which already zoom-in accordingly." }, { "code": null, "e": 1716, "s": 1644, "text": "mah_map = folium.Map(location=[61.5240, 105.3188], zoom_start=3)mah_map" }, { "code": null, "e": 1819, "s": 1716, "text": "Further, you can use folium for creating different types of maps. Some of them I have explained below." }, { "code": null, "e": 1949, "s": 1819, "text": "These are the high contrast Black & White maps. They are perfect for data mashups and exploring river meanders and coastal zones." }, { "code": null, "e": 2122, "s": 1949, "text": "For creating this we just need to add an attribute to Map() function named β€˜tiles’ and set it to Stamen Toner. The code below is used to create a Stamen Toner map of India." }, { "code": null, "e": 2233, "s": 2122, "text": "india_map = folium.Map(location=[20.5937, 78.9629 ], zoom_start=4, tiles='Stamen Toner')india_map" }, { "code": null, "e": 2389, "s": 2233, "text": "These maps show hill shading and natural vegetation colors. They also showcase the advanced labeling and linework generalization of dual-carriageway roads." }, { "code": null, "e": 2531, "s": 2389, "text": "For creating this we need to set the value of attribute tiles as Stamen Terrain. The below code will produce the Stamen Terrain map of India." }, { "code": null, "e": 2631, "s": 2531, "text": "india_map = folium.Map(location=[20.5937, 78.9629 ], zoom_start=4, tiles='Stamen Terrain')india_map" }, { "code": null, "e": 2738, "s": 2631, "text": "Other than this there are many more tile options like β€˜Mapbox Bright’ etc. that you can explore and learn." }, { "code": null, "e": 2885, "s": 2738, "text": "Folium also has a marker function that marks the desired location of your choice of given coordinates. We can also select the icon for the marker." }, { "code": null, "e": 2977, "s": 2885, "text": "Below Given code is used to create a map and displaying the marker on the desired location." }, { "code": null, "e": 3194, "s": 2977, "text": "my_map = folium.Map(location=[20.5937, 78.9629], zoom_start=4, tiles='Stamen Terrain')folium.Marker([28.73158, 77.13267], popup='MyLocation', marker_icon='cloud').add_to(my_map)my_map" }, { "code": null, "e": 3568, "s": 3194, "text": "In this article, we explored a beautiful library Folium use to create leaflet maps that are interactive and visually appealing. We can use these maps in our dashboards or as needed. Folium is easy to understand the library and creates a map in just one line of code. This article is just a basic understanding of folium, go ahead, and explore folium for many more features." }, { "code": null, "e": 3591, "s": 3568, "text": "towardsdatascience.com" }, { "code": null, "e": 3614, "s": 3591, "text": "towardsdatascience.com" } ]
CSS Layout - The z-index Property
The z-index property specifies the stack order of an element. When elements are positioned, they can overlap other elements. The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others). An element can have a positive or negative stack order: Because the image has a z-index of -1, it will be placed behind the text. Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements). Here we see that an element with greater stack order is always above an element with a lower stack order: If two positioned elements overlap each other without a z-index specified, the element defined last in the HTML code will be shown on top. Same example as above, but here with no z-index specified: Both the header and the paragraph are positioned at the top of the page. Make sure that the header is placed on top of the paragraph. <style> { position: absolute; top: 0; : 1; } { position: absolute; top: 0; : 0; } </style> <body> <h1 id="mytitle">This is a heading</h1> <p id="myintro">This is a paragraph</p> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 63, "s": 0, "text": "The z-index property specifies the \nstack order of an element." }, { "code": null, "e": 126, "s": 63, "text": "When elements are positioned, they can overlap other elements." }, { "code": null, "e": 256, "s": 126, "text": "The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others)." }, { "code": null, "e": 312, "s": 256, "text": "An element can have a positive or negative stack order:" }, { "code": null, "e": 386, "s": 312, "text": "Because the image has a z-index of -1, it will be placed behind the text." }, { "code": null, "e": 593, "s": 386, "text": "Note: z-index only works on positioned elements (position: absolute, \nposition: relative, position: fixed, or position: sticky) and flex items \n(elements that are direct children of display: flex elements)." }, { "code": null, "e": 699, "s": 593, "text": "Here we see that an element with greater stack order is always above an element with a lower stack order:" }, { "code": null, "e": 839, "s": 699, "text": "If two positioned elements overlap each other without a z-index \nspecified, the element defined last in the HTML code will be shown on top." }, { "code": null, "e": 898, "s": 839, "text": "Same example as above, but here with no z-index specified:" }, { "code": null, "e": 971, "s": 898, "text": "Both the header and the paragraph are positioned at the top of the page." }, { "code": null, "e": 1032, "s": 971, "text": "Make sure that the header is placed on top of the paragraph." }, { "code": null, "e": 1240, "s": 1032, "text": "<style>\n {\n position: absolute;\n top: 0;\n : 1; \n}\n {\n position: absolute;\n top: 0;\n : 0;\n}\n</style>\n\n<body>\n <h1 id=\"mytitle\">This is a heading</h1>\n <p id=\"myintro\">This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 1259, "s": 1240, "text": "Start the Exercise" }, { "code": null, "e": 1292, "s": 1259, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1334, "s": 1292, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1441, "s": 1334, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1460, "s": 1441, "text": "help@w3schools.com" } ]
8051 Program to Subtract two 8 Bit numbers
Here we will see how to subtract two 8-bit numbers using this microcontroller. The register A(Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as the second operand. We are taking two number73H and BDH at location 20H and 21H, After subtracting the result will be stored at location 30H and 31H. MOVR0,#20H;set source address 20H to R0 MOVR1,#30H;set destination address 30H to R1 MOVA,@R0;take the value from source to register A MOVR5,A; Move the value from A to R5 MOVR4,#00H; Clear register R4 to store borrow INCR0; Point to the next location MOVA,@R0; take the value from source to register A MOVR3,A; store second byte MOVA,R5;get back the first operand SUBBA,R3; Subtract R3 from A JNCSAVE INCR4; Increment R4 to get borrow MOVB,R4;Get borrow to register B MOV@R1,B; Store the borrow first INCR1; Increase R1 to point to the next address SAVE: MOV@R1,A; Store the result HALT: SJMP HALT ;Stop the program So by subtracting 73H –BDH, the result will be B6H. At location 30H, we will get 01H. This indicates that the result is negative. The get the actual value from result B6H, we have to perform 2’s complement operation. After performing 2’s Complement, the result will be -4AH.
[ { "code": null, "e": 1320, "s": 1062, "text": "Here we will see how to subtract two 8-bit numbers using this microcontroller. The register A(Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as the second operand." }, { "code": null, "e": 1452, "s": 1320, "text": "We are taking two number73H and BDH at location 20H and 21H, After subtracting the result will be stored at location 30H and 31H. " }, { "code": null, "e": 2109, "s": 1452, "text": "MOVR0,#20H;set source address 20H to R0\nMOVR1,#30H;set destination address 30H to R1\n\nMOVA,@R0;take the value from source to register A\nMOVR5,A; Move the value from A to R5\nMOVR4,#00H; Clear register R4 to store borrow\n\nINCR0; Point to the next location\nMOVA,@R0; take the value from source to register A\nMOVR3,A; store second byte\nMOVA,R5;get back the first operand\nSUBBA,R3; Subtract R3 from A\n JNCSAVE\n INCR4; Increment R4 to get borrow\n MOVB,R4;Get borrow to register B\n MOV@R1,B; Store the borrow first\n INCR1; Increase R1 to point to the next address\n\nSAVE: MOV@R1,A; Store the result\nHALT: SJMP HALT ;Stop the program" }, { "code": null, "e": 2384, "s": 2109, "text": "So by subtracting 73H –BDH, the result will be B6H. At location 30H, we will get 01H. This indicates that the result is negative. The get the actual value from result B6H, we have to perform 2’s complement operation. After performing 2’s Complement, the result will be -4AH." } ]
LISP - Lambda Functions
At times you may need a function in only one place in your program and the function is so trivial that you may not give it a name, or may not like to store it in the symbol table, and would rather write an unnamed or anonymous function. LISP allows you to write anonymous functions that are evaluated only when they are encountered in the program. These functions are called Lambda functions. You can create such functions using the lambda expression. The syntax for the lambda expression is as follows βˆ’ (lambda (parameters) body) A lambda form cannot be evaluated and it must appear only where LISP expects to find a function. Create a new source code file named main.lisp and type the following code in it. (write ((lambda (a b c x) (+ (* a (* x x)) (* b x) c)) 4 2 9 3) ) When you execute the code, it returns the following result βˆ’ 51 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2297, "s": 2060, "text": "At times you may need a function in only one place in your program and the function is so trivial that you may not give it a name, or may not like to store it in the symbol table, and would rather write an unnamed or anonymous function." }, { "code": null, "e": 2453, "s": 2297, "text": "LISP allows you to write anonymous functions that are evaluated only when they are encountered in the program. These functions are called Lambda functions." }, { "code": null, "e": 2565, "s": 2453, "text": "You can create such functions using the lambda expression. The syntax for the lambda expression is as follows βˆ’" }, { "code": null, "e": 2592, "s": 2565, "text": "(lambda (parameters) body)" }, { "code": null, "e": 2689, "s": 2592, "text": "A lambda form cannot be evaluated and it must appear only where LISP expects to find a function." }, { "code": null, "e": 2770, "s": 2689, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 2842, "s": 2770, "text": "(write ((lambda (a b c x)\n (+ (* a (* x x)) (* b x) c))\n 4 2 9 3)\n)" }, { "code": null, "e": 2903, "s": 2842, "text": "When you execute the code, it returns the following result βˆ’" }, { "code": null, "e": 2907, "s": 2903, "text": "51\n" }, { "code": null, "e": 2940, "s": 2907, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 2955, "s": 2940, "text": " Arnold Higuit" }, { "code": null, "e": 2962, "s": 2955, "text": " Print" }, { "code": null, "e": 2973, "s": 2962, "text": " Add Notes" } ]
Check if a File exists in C#
Use the File.exists method in C# to check if a file exits in C# or not. Firstly, check whether the file is present in the current directory. if (File.Exists("MyFile.txt")) { Console.WriteLine("The file exists."); } After that check whether the file exist in a directory or not. if (File.Exists(@"D:\myfile.txt")) { Console.WriteLine("The file exists."); } Let us see the complete example to check if a file exists in C#. Live Demo using System; using System.IO; class Demo { static void Main() { if (File.Exists("MyFile.txt")) { Console.WriteLine("File exists..."); } else { Console.WriteLine("File does not exist in the current directory!"); } if (File.Exists(@"D:\myfile.txt")) { Console.WriteLine("File exists..."); } else { Console.WriteLine("File does not exist in the D directory!"); } } } File does not exist in the current directory! File does not exist in the D directory!
[ { "code": null, "e": 1134, "s": 1062, "text": "Use the File.exists method in C# to check if a file exits in C# or not." }, { "code": null, "e": 1203, "s": 1134, "text": "Firstly, check whether the file is present in the current directory." }, { "code": null, "e": 1280, "s": 1203, "text": "if (File.Exists(\"MyFile.txt\")) {\n Console.WriteLine(\"The file exists.\");\n}" }, { "code": null, "e": 1343, "s": 1280, "text": "After that check whether the file exist in a directory or not." }, { "code": null, "e": 1424, "s": 1343, "text": "if (File.Exists(@\"D:\\myfile.txt\")) {\n Console.WriteLine(\"The file exists.\");\n}" }, { "code": null, "e": 1489, "s": 1424, "text": "Let us see the complete example to check if a file exists in C#." }, { "code": null, "e": 1500, "s": 1489, "text": " Live Demo" }, { "code": null, "e": 1943, "s": 1500, "text": "using System;\nusing System.IO;\nclass Demo {\n static void Main() {\n if (File.Exists(\"MyFile.txt\")) {\n Console.WriteLine(\"File exists...\");\n } else {\n Console.WriteLine(\"File does not exist in the current directory!\");\n }\n if (File.Exists(@\"D:\\myfile.txt\")) {\n Console.WriteLine(\"File exists...\");\n } else {\n Console.WriteLine(\"File does not exist in the D directory!\");\n }\n }\n}" }, { "code": null, "e": 2029, "s": 1943, "text": "File does not exist in the current directory!\nFile does not exist in the D directory!" } ]
override identifier in C++
13 Jun, 2022 Function overriding is a redefinition of the base class function in its derived class with the same signature i.e. return type and parameters. But there may be situations when a programmer makes a mistake while overriding that function. So, to keep track of such an error, C++11 has come up with the override identifier. If the compiler comes across this identifier, it understands that this is an overridden version of the same class. It will make the compiler check the base class to see if there is a virtual function with this exact signature. And if there is not, the compiler will show an error. The programmer’s intentions can be made clear to the compiler by override. If the override identifier is used with a member function, the compiler makes sure that the member function exists in the base class, and also the compiler restricts the program to compile otherwise. Let’s understand through the following example: CPP // A CPP program without override keyword, here// programmer makes a mistake and it is not caught#include <iostream>using namespace std; class Base {public: // user wants to override this in // the derived class virtual void func() { cout << "I am in base" << endl; }}; class derived : public Base {public: // did a silly mistake by putting // an argument "int a" void func(int a) { cout << "I am in derived class" << endl; }}; // Driver codeint main(){ Base b; derived d; cout << "Compiled successfully" << endl; return 0;} Compiled successfully Explanation: Here, the user intended to override the function func() in the derived class but did a silly mistake and redefined the function with a different signature. Which was not detected by the compiler. However, the program is not actually what the user wanted. So, to get rid of such silly mistakes to be on the safe side, the override identifier can be used. Below is a C++ example to show the use of override identifier in C++. CPP // A CPP program that uses override keyword so// that any difference in function signature is// caught during compilation#include <iostream>using namespace std; class Base {public: // user wants to override this in // the derived class virtual void func() { cout << "I am in base" << endl; }}; class derived : public Base {public: // did a silly mistake by putting // an argument "int a" void func(int a) override { cout << "I am in derived class" << endl; }}; int main(){ Base b; derived d; cout << "Compiled successfully" << endl; return 0;} Output(Error) prog.cpp:17:7: error: 'void derived::func(int)' marked 'override', but does not override void func(int a) override ^ In short, it serves the following functions. It helps to check if: There is a method with the same name in the parent class. The method in the parent class is declared as β€œvirtual” which means it was intended to be rewritten. The method in the parent class has the same signature as the method in the subclass. This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. anshikajain26 shivamgupta2 cpp-virtual C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 657, "s": 54, "text": "Function overriding is a redefinition of the base class function in its derived class with the same signature i.e. return type and parameters. But there may be situations when a programmer makes a mistake while overriding that function. So, to keep track of such an error, C++11 has come up with the override identifier. If the compiler comes across this identifier, it understands that this is an overridden version of the same class. It will make the compiler check the base class to see if there is a virtual function with this exact signature. And if there is not, the compiler will show an error. " }, { "code": null, "e": 932, "s": 657, "text": "The programmer’s intentions can be made clear to the compiler by override. If the override identifier is used with a member function, the compiler makes sure that the member function exists in the base class, and also the compiler restricts the program to compile otherwise." }, { "code": null, "e": 981, "s": 932, "text": "Let’s understand through the following example: " }, { "code": null, "e": 985, "s": 981, "text": "CPP" }, { "code": "// A CPP program without override keyword, here// programmer makes a mistake and it is not caught#include <iostream>using namespace std; class Base {public: // user wants to override this in // the derived class virtual void func() { cout << \"I am in base\" << endl; }}; class derived : public Base {public: // did a silly mistake by putting // an argument \"int a\" void func(int a) { cout << \"I am in derived class\" << endl; }}; // Driver codeint main(){ Base b; derived d; cout << \"Compiled successfully\" << endl; return 0;}", "e": 1553, "s": 985, "text": null }, { "code": null, "e": 1575, "s": 1553, "text": "Compiled successfully" }, { "code": null, "e": 2012, "s": 1575, "text": "Explanation: Here, the user intended to override the function func() in the derived class but did a silly mistake and redefined the function with a different signature. Which was not detected by the compiler. However, the program is not actually what the user wanted. So, to get rid of such silly mistakes to be on the safe side, the override identifier can be used. Below is a C++ example to show the use of override identifier in C++." }, { "code": null, "e": 2016, "s": 2012, "text": "CPP" }, { "code": "// A CPP program that uses override keyword so// that any difference in function signature is// caught during compilation#include <iostream>using namespace std; class Base {public: // user wants to override this in // the derived class virtual void func() { cout << \"I am in base\" << endl; }}; class derived : public Base {public: // did a silly mistake by putting // an argument \"int a\" void func(int a) override { cout << \"I am in derived class\" << endl; }}; int main(){ Base b; derived d; cout << \"Compiled successfully\" << endl; return 0;}", "e": 2603, "s": 2016, "text": null }, { "code": null, "e": 2617, "s": 2603, "text": "Output(Error)" }, { "code": null, "e": 2744, "s": 2617, "text": "prog.cpp:17:7: error: 'void derived::func(int)'\nmarked 'override', but does not override\n void func(int a) override \n ^" }, { "code": null, "e": 2812, "s": 2744, "text": "In short, it serves the following functions. It helps to check if: " }, { "code": null, "e": 2870, "s": 2812, "text": "There is a method with the same name in the parent class." }, { "code": null, "e": 2971, "s": 2870, "text": "The method in the parent class is declared as β€œvirtual” which means it was intended to be rewritten." }, { "code": null, "e": 3056, "s": 2971, "text": "The method in the parent class has the same signature as the method in the subclass." }, { "code": null, "e": 3481, "s": 3056, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 3495, "s": 3481, "text": "anshikajain26" }, { "code": null, "e": 3508, "s": 3495, "text": "shivamgupta2" }, { "code": null, "e": 3520, "s": 3508, "text": "cpp-virtual" }, { "code": null, "e": 3524, "s": 3520, "text": "C++" }, { "code": null, "e": 3528, "s": 3524, "text": "CPP" } ]
PLSQL | UPPER Function
11 Oct, 2019 The PLSQL UPPER function is used for converting all letters in the specified string to uppercase. If there are characters in the string that are not letters, they are unaffected by this function. The char to be converted can be any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The value returned by the UPPER function is the same datatype as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set. Syntax: UPPER( string ) Parameters Used: string – It is used to specify the string which needs to be converted. Return Value:The UPPER function in PLSQL returns a string value. Supported Versions of Oracle/PLSQL Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: Passing a string as an argument with first character in uppercase and rest of the characters in lowercase. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(UPPER(Test_String)); END; Output: GEEKSFORGEEKS Example-2: Passing a string as an argument with all the characters in lowercase. DECLARE Test_String string(20) := 'geeksforgeeks'; BEGIN dbms_output.put_line(UPPER(Test_String)); END; Output: GEEKSFORGEEKS Example-3: Passing a string as an argument with numeric values and characters in lowercase. DECLARE Test_String string(20) := '123geeksforgeeks123'; BEGIN dbms_output.put_line(UPPER(Test_String)); END; Output: 123GEEKSFORGEEKS123 Advantage:The UPPER function accepts any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB in the input_string. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 224, "s": 28, "text": "The PLSQL UPPER function is used for converting all letters in the specified string to uppercase. If there are characters in the string that are not letters, they are unaffected by this function." }, { "code": null, "e": 521, "s": 224, "text": "The char to be converted can be any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The value returned by the UPPER function is the same datatype as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set." }, { "code": null, "e": 529, "s": 521, "text": "Syntax:" }, { "code": null, "e": 545, "s": 529, "text": "UPPER( string )" }, { "code": null, "e": 562, "s": 545, "text": "Parameters Used:" }, { "code": null, "e": 633, "s": 562, "text": "string – It is used to specify the string which needs to be converted." }, { "code": null, "e": 698, "s": 633, "text": "Return Value:The UPPER function in PLSQL returns a string value." }, { "code": null, "e": 733, "s": 698, "text": "Supported Versions of Oracle/PLSQL" }, { "code": null, "e": 782, "s": 733, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 793, "s": 782, "text": "Oracle 12c" }, { "code": null, "e": 804, "s": 793, "text": "Oracle 11g" }, { "code": null, "e": 815, "s": 804, "text": "Oracle 10g" }, { "code": null, "e": 825, "s": 815, "text": "Oracle 9i" }, { "code": null, "e": 835, "s": 825, "text": "Oracle 8i" }, { "code": null, "e": 953, "s": 835, "text": "Example-1: Passing a string as an argument with first character in uppercase and rest of the characters in lowercase." }, { "code": null, "e": 1076, "s": 953, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(UPPER(Test_String)); \n \nEND; " }, { "code": null, "e": 1084, "s": 1076, "text": "Output:" }, { "code": null, "e": 1099, "s": 1084, "text": "GEEKSFORGEEKS " }, { "code": null, "e": 1180, "s": 1099, "text": "Example-2: Passing a string as an argument with all the characters in lowercase." }, { "code": null, "e": 1304, "s": 1180, "text": "DECLARE \n Test_String string(20) := 'geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(UPPER(Test_String)); \n \nEND; " }, { "code": null, "e": 1312, "s": 1304, "text": "Output:" }, { "code": null, "e": 1327, "s": 1312, "text": "GEEKSFORGEEKS " }, { "code": null, "e": 1419, "s": 1327, "text": "Example-3: Passing a string as an argument with numeric values and characters in lowercase." }, { "code": null, "e": 1547, "s": 1419, "text": "DECLARE \n Test_String string(20) := '123geeksforgeeks123';\n \nBEGIN \n dbms_output.put_line(UPPER(Test_String)); \n \nEND; " }, { "code": null, "e": 1555, "s": 1547, "text": "Output:" }, { "code": null, "e": 1576, "s": 1555, "text": "123GEEKSFORGEEKS123 " }, { "code": null, "e": 1704, "s": 1576, "text": "Advantage:The UPPER function accepts any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB in the input_string." }, { "code": null, "e": 1715, "s": 1704, "text": "SQL-PL/SQL" }, { "code": null, "e": 1719, "s": 1715, "text": "SQL" }, { "code": null, "e": 1723, "s": 1719, "text": "SQL" } ]
How to Solve java.lang.NoSuchMethodError in Java?
28 Jul, 2021 A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The java.lang.NoSuchMethodError can occur in case application code is partially compiled, or in case an external dependency in a project incompatibly changed the code (e.g. removed the calling method) from one version to another. It is as shown in the illustration below as follows: Illustration: java.lang Class NoSuchMethodError java.lang.Object java.lang.Throwable java.lang.Error java.lang.LinkageError java.lang.IncompatibleClassChangeError java.lang.NoSuchMethodError Note: All Implemented Interfaces is Serializable interface in Java. Now let us discuss the causes behind this exception in order to figure out how to resolve the same problem. java.lang. It occurs when a particular method is not found. This method can either be an instance method or a static method. The java.lang.NoSuchMethodError occurs when an application does not find a method at runtime. In most cases, we’re able to catch this error at compile-time. Hence, it’s not a big issue. However, sometimes it could be thrown at runtime, then finding it becomes a bit difficult. According to the Oracle documentation, this error may occur at runtime if a class has been incomparably changed. Hence, we may encounter this error in the following cases. Firstly, if we do just a partial recompilation of our code. Secondly, if there is version incompatibility with the dependencies in our application, such as the external jars. Note: NoSuchMethodError inheritance tree includes IncompatibleClassChangeError and LinkageError. These errors are associated with an incompatible class change after compilation. Implementation: Now we will be proposing two examples in which first we will illustrate the thrown exception and, in later example, resolve the same via clean java problems. Example 1 Java // Java Program to Demonstrate NoSuchMethodError by // throwing it due to a breaking change // introduced within an application // Importingn I/O classesimport java.io.*; // Class 1// Helper classclass NoSuchMethodError { // Method 1 // Void demo method created to be called // in another class containing main() method public void printer(String myString) { // Print statement System.out.println(myString); }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 NoSuchMethodError obj = new NoSuchMethodError(); // Now calling print() method which is not present // in NoSuchMethodErrorExample class, hence throwing // exception obj.print("Hello World"); }} Output: Now if we try to draw out conclusions about the possible solution to resolve the above error. For that, we need to take care of two parameters as listed: Call correct method which is present in class. Check the name of the method and its signature which you are trying to call. Example 2 Java // Java Program to Resolve NoSuchMethodError // Importing input output classesimport java.io.*; // Class 1// Helper classclass NoSuchMethodError { // Defined printer method public void printer(String myString) { // Print the string which will be passed // in the main() method System.out.println(myString); }} // Class 2// Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of above class in // main() method of this class NoSuchMethodError obj = new NoSuchMethodError(); // Calling printer() method which is present in // NoSuchMethodErrorExample class obj.printer("Hello World"); }} Hello World Java-Exception Handling Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jul, 2021" }, { "code": null, "e": 512, "s": 53, "text": "A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The java.lang.NoSuchMethodError can occur in case application code is partially compiled, or in case an external dependency in a project incompatibly changed the code (e.g. removed the calling method) from one version to another. It is as shown in the illustration below as follows:" }, { "code": null, "e": 526, "s": 512, "text": "Illustration:" }, { "code": null, "e": 787, "s": 526, "text": "java.lang\nClass NoSuchMethodError\n java.lang.Object\n java.lang.Throwable\n java.lang.Error\n java.lang.LinkageError\n java.lang.IncompatibleClassChangeError\n java.lang.NoSuchMethodError" }, { "code": null, "e": 855, "s": 787, "text": "Note: All Implemented Interfaces is Serializable interface in Java." }, { "code": null, "e": 1712, "s": 855, "text": "Now let us discuss the causes behind this exception in order to figure out how to resolve the same problem. java.lang. It occurs when a particular method is not found. This method can either be an instance method or a static method. The java.lang.NoSuchMethodError occurs when an application does not find a method at runtime. In most cases, we’re able to catch this error at compile-time. Hence, it’s not a big issue. However, sometimes it could be thrown at runtime, then finding it becomes a bit difficult. According to the Oracle documentation, this error may occur at runtime if a class has been incomparably changed. Hence, we may encounter this error in the following cases. Firstly, if we do just a partial recompilation of our code. Secondly, if there is version incompatibility with the dependencies in our application, such as the external jars." }, { "code": null, "e": 1890, "s": 1712, "text": "Note: NoSuchMethodError inheritance tree includes IncompatibleClassChangeError and LinkageError. These errors are associated with an incompatible class change after compilation." }, { "code": null, "e": 1906, "s": 1890, "text": "Implementation:" }, { "code": null, "e": 2064, "s": 1906, "text": "Now we will be proposing two examples in which first we will illustrate the thrown exception and, in later example, resolve the same via clean java problems." }, { "code": null, "e": 2074, "s": 2064, "text": "Example 1" }, { "code": null, "e": 2079, "s": 2074, "text": "Java" }, { "code": "// Java Program to Demonstrate NoSuchMethodError by // throwing it due to a breaking change // introduced within an application // Importingn I/O classesimport java.io.*; // Class 1// Helper classclass NoSuchMethodError { // Method 1 // Void demo method created to be called // in another class containing main() method public void printer(String myString) { // Print statement System.out.println(myString); }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 NoSuchMethodError obj = new NoSuchMethodError(); // Now calling print() method which is not present // in NoSuchMethodErrorExample class, hence throwing // exception obj.print(\"Hello World\"); }}", "e": 2919, "s": 2079, "text": null }, { "code": null, "e": 2927, "s": 2919, "text": "Output:" }, { "code": null, "e": 3082, "s": 2927, "text": "Now if we try to draw out conclusions about the possible solution to resolve the above error. For that, we need to take care of two parameters as listed: " }, { "code": null, "e": 3129, "s": 3082, "text": "Call correct method which is present in class." }, { "code": null, "e": 3206, "s": 3129, "text": "Check the name of the method and its signature which you are trying to call." }, { "code": null, "e": 3216, "s": 3206, "text": "Example 2" }, { "code": null, "e": 3221, "s": 3216, "text": "Java" }, { "code": "// Java Program to Resolve NoSuchMethodError // Importing input output classesimport java.io.*; // Class 1// Helper classclass NoSuchMethodError { // Defined printer method public void printer(String myString) { // Print the string which will be passed // in the main() method System.out.println(myString); }} // Class 2// Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of above class in // main() method of this class NoSuchMethodError obj = new NoSuchMethodError(); // Calling printer() method which is present in // NoSuchMethodErrorExample class obj.printer(\"Hello World\"); }}", "e": 3972, "s": 3221, "text": null }, { "code": null, "e": 3985, "s": 3972, "text": "Hello World\n" }, { "code": null, "e": 4009, "s": 3985, "text": "Java-Exception Handling" }, { "code": null, "e": 4016, "s": 4009, "text": "Picked" }, { "code": null, "e": 4021, "s": 4016, "text": "Java" }, { "code": null, "e": 4026, "s": 4021, "text": "Java" } ]
How to get list of parameters name from a function in Python?
29 Dec, 2020 In this article, we are going to discuss how to get list parameters from a function in Python. The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as an argument in one of the methods. Below are some programs which depict how to use the signature() method of the inspect module to get the list of parameters name: Example 1: Getting the parameter list of a method. Python3 # import required modulesimport inspectimport collections # use signature()print(inspect.signature(collections.Counter)) Output: (*args, **kwds) Example 2: Getting the parameter list of an explicit function. Python3 # explicit functiondef fun(a, b): return a**b # import required modules import inspect # use signature() print(inspect.signature(fun)) Output: (a, b) Example 3: Getting the parameter list of an in-built function. Python3 # import required modules import inspect # use signature() print(inspect.signature(len)) Output: (obj, /) Below are some programs which depict how to use the getargspec() method of the inspect module to get the list of parameters name: Example 1: Getting the parameter list of a method. Python3 # import required modulesimport inspectimport collections # use getargspec()print(inspect.getargspec(collections.Counter)) Output: ArgSpec(args=[], varargs=’args’, keywords=’kwds’, defaults=None) Example 2: Getting the parameter list of an explicit function. Python3 # explicit functiondef fun(a, b): return a**b # import required modules import inspect # use getargspec() print(inspect.getargspec(fun)) Output: ArgSpec(args=[β€˜a’, β€˜b’], varargs=None, keywords=None, defaults=None) Example 3: Getting the parameter list of an in-built function. Python3 # import required modules import inspect # use getargspec() print(inspect.getargspec(len)) Output: ArgSpec(args=[β€˜obj’], varargs=None, keywords=None, defaults=None) Picked Python function-programs Python-Functions 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 ? Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2020" }, { "code": null, "e": 439, "s": 53, "text": "In this article, we are going to discuss how to get list parameters from a function in Python. The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as an argument in one of the methods." }, { "code": null, "e": 569, "s": 439, "text": "Below are some programs which depict how to use the signature() method of the inspect module to get the list of parameters name:" }, { "code": null, "e": 620, "s": 569, "text": "Example 1: Getting the parameter list of a method." }, { "code": null, "e": 628, "s": 620, "text": "Python3" }, { "code": "# import required modulesimport inspectimport collections # use signature()print(inspect.signature(collections.Counter))", "e": 750, "s": 628, "text": null }, { "code": null, "e": 758, "s": 750, "text": "Output:" }, { "code": null, "e": 774, "s": 758, "text": "(*args, **kwds)" }, { "code": null, "e": 837, "s": 774, "text": "Example 2: Getting the parameter list of an explicit function." }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": "# explicit functiondef fun(a, b): return a**b # import required modules import inspect # use signature() print(inspect.signature(fun)) ", "e": 987, "s": 845, "text": null }, { "code": null, "e": 995, "s": 987, "text": "Output:" }, { "code": null, "e": 1002, "s": 995, "text": "(a, b)" }, { "code": null, "e": 1065, "s": 1002, "text": "Example 3: Getting the parameter list of an in-built function." }, { "code": null, "e": 1073, "s": 1065, "text": "Python3" }, { "code": "# import required modules import inspect # use signature() print(inspect.signature(len))", "e": 1164, "s": 1073, "text": null }, { "code": null, "e": 1172, "s": 1164, "text": "Output:" }, { "code": null, "e": 1181, "s": 1172, "text": "(obj, /)" }, { "code": null, "e": 1312, "s": 1181, "text": "Below are some programs which depict how to use the getargspec() method of the inspect module to get the list of parameters name:" }, { "code": null, "e": 1363, "s": 1312, "text": "Example 1: Getting the parameter list of a method." }, { "code": null, "e": 1371, "s": 1363, "text": "Python3" }, { "code": "# import required modulesimport inspectimport collections # use getargspec()print(inspect.getargspec(collections.Counter))", "e": 1495, "s": 1371, "text": null }, { "code": null, "e": 1503, "s": 1495, "text": "Output:" }, { "code": null, "e": 1568, "s": 1503, "text": "ArgSpec(args=[], varargs=’args’, keywords=’kwds’, defaults=None)" }, { "code": null, "e": 1631, "s": 1568, "text": "Example 2: Getting the parameter list of an explicit function." }, { "code": null, "e": 1639, "s": 1631, "text": "Python3" }, { "code": "# explicit functiondef fun(a, b): return a**b # import required modules import inspect # use getargspec() print(inspect.getargspec(fun)) ", "e": 1783, "s": 1639, "text": null }, { "code": null, "e": 1791, "s": 1783, "text": "Output:" }, { "code": null, "e": 1860, "s": 1791, "text": "ArgSpec(args=[β€˜a’, β€˜b’], varargs=None, keywords=None, defaults=None)" }, { "code": null, "e": 1923, "s": 1860, "text": "Example 3: Getting the parameter list of an in-built function." }, { "code": null, "e": 1931, "s": 1923, "text": "Python3" }, { "code": "# import required modules import inspect # use getargspec() print(inspect.getargspec(len))", "e": 2024, "s": 1931, "text": null }, { "code": null, "e": 2032, "s": 2024, "text": "Output:" }, { "code": null, "e": 2098, "s": 2032, "text": "ArgSpec(args=[β€˜obj’], varargs=None, keywords=None, defaults=None)" }, { "code": null, "e": 2105, "s": 2098, "text": "Picked" }, { "code": null, "e": 2130, "s": 2105, "text": "Python function-programs" }, { "code": null, "e": 2147, "s": 2130, "text": "Python-Functions" }, { "code": null, "e": 2171, "s": 2147, "text": "Technical Scripter 2020" }, { "code": null, "e": 2178, "s": 2171, "text": "Python" }, { "code": null, "e": 2197, "s": 2178, "text": "Technical Scripter" }, { "code": null, "e": 2295, "s": 2197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2327, "s": 2295, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2354, "s": 2327, "text": "Python Classes and Objects" }, { "code": null, "e": 2377, "s": 2354, "text": "Introduction To PYTHON" }, { "code": null, "e": 2398, "s": 2377, "text": "Python OOPs Concepts" }, { "code": null, "e": 2429, "s": 2398, "text": "Python | os.path.join() method" }, { "code": null, "e": 2485, "s": 2429, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2527, "s": 2485, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2569, "s": 2527, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2608, "s": 2569, "text": "Python | Get unique values from a list" } ]
settextstyle function in C
01 Dec, 2021 The header file graphics.h contains settextstyle() function which is used to change the way in which text appears. Using it we can modify the size of text, change direction of text and change the font of text. Syntax : void settextstyle(int font, int direction, int font_size); where, font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or VERT_DIR (Bottom to top). Examples : Input : font = 8, direction = 0, font_size = 5 Output : Input : font = 3, direction = 0, font_size = 5 Output : The table below shows the fonts with their INT values and appearance: Below is the implementation of settextstyle() function : CPP // C++ implementation for// settextstyle() function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, ""); // location of text int x = 150; int y = 150; // font style int font = 8; // font direction int direction = 0; // font size int font_size = 5; // for setting text style settextstyle(font, direction, font_size); // for printing text in graphics window outtextxy(x, y, "Geeks For Geeks"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by graphics // system . closegraph(); return 0;} Output: Hax4us theshaunsaw c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Dec, 2021" }, { "code": null, "e": 273, "s": 52, "text": "The header file graphics.h contains settextstyle() function which is used to change the way in which text appears. Using it we can modify the size of text, change direction of text and change the font of text. Syntax : " }, { "code": null, "e": 455, "s": 273, "text": "void settextstyle(int font, int direction, int font_size);\n\nwhere,\nfont argument specifies the font of text,\nDirection can be HORIZ_DIR (Left to right) \nor VERT_DIR (Bottom to top)." }, { "code": null, "e": 468, "s": 455, "text": "Examples : " }, { "code": null, "e": 525, "s": 468, "text": "Input : font = 8, direction = 0, font_size = 5\nOutput : " }, { "code": null, "e": 582, "s": 525, "text": "Input : font = 3, direction = 0, font_size = 5\nOutput : " }, { "code": null, "e": 652, "s": 582, "text": "The table below shows the fonts with their INT values and appearance:" }, { "code": null, "e": 711, "s": 652, "text": "Below is the implementation of settextstyle() function : " }, { "code": null, "e": 715, "s": 711, "text": "CPP" }, { "code": "// C++ implementation for// settextstyle() function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, \"\"); // location of text int x = 150; int y = 150; // font style int font = 8; // font direction int direction = 0; // font size int font_size = 5; // for setting text style settextstyle(font, direction, font_size); // for printing text in graphics window outtextxy(x, y, \"Geeks For Geeks\"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by graphics // system . closegraph(); return 0;}", "e": 1651, "s": 715, "text": null }, { "code": null, "e": 1661, "s": 1651, "text": "Output: " }, { "code": null, "e": 1668, "s": 1661, "text": "Hax4us" }, { "code": null, "e": 1680, "s": 1668, "text": "theshaunsaw" }, { "code": null, "e": 1691, "s": 1680, "text": "c-graphics" }, { "code": null, "e": 1709, "s": 1691, "text": "computer-graphics" }, { "code": null, "e": 1720, "s": 1709, "text": "C Language" } ]
Python – Convert Snake Case String to Camel Case
01 Oct, 2020 Given a snake case string, convert to camel case. Input : test_str = β€˜geeksforgeeks_is_best_for_geeks’ Output : geeksforgeeksIsBestForGeeks Explanation : String converted to Camel Case. Input : test_str = β€˜geeksforgeeks_best_for_geeks’ Output : geeksforgeeksBestForGeeks Explanation : String converted to Camel Case. Method #1 : Using split() + join() + title() + generator expression The combination of above functions can be used to solve this problem. In this, we first split all underscores, and then join the string appending initial word, followed by title cased words using generator expression and title(). Python3 # Python3 code to demonstrate working of # Convert Snake Case String to Camel Case# Using split() + join() + title() + generator expression # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint("The original string is : " + str(test_str)) # split underscore using splittemp = test_str.split('_') # joining result res = temp[0] + ''.join(ele.title() for ele in temp[1:]) # printing result print("The camel case string is : " + str(res)) The original string is : geeksforgeeks_is_best The camel case string is : geeksforgeeksIsBest Method #2 : Using split() + join() + title() + map() The combination of above functions can be used to solve this problem. In this, we perform the task of extending logic to entire strings using map(). Python3 # Python3 code to demonstrate working of # Convert Snake Case String to Camel Case# Using split() + join() + title() + map() # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint("The original string is : " + str(test_str)) # saving first and rest using split()init, *temp = test_str.split('_') # using map() to get all words other than 1st# and titlecasing themres = ''.join([init.lower(), *map(str.title, temp)]) # printing result print("The camel case string is : " + str(res)) The original string is : geeksforgeeks_is_best The camel case string is : geeksforgeeksIsBest Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 78, "s": 28, "text": "Given a snake case string, convert to camel case." }, { "code": null, "e": 214, "s": 78, "text": "Input : test_str = β€˜geeksforgeeks_is_best_for_geeks’ Output : geeksforgeeksIsBestForGeeks Explanation : String converted to Camel Case." }, { "code": null, "e": 346, "s": 214, "text": "Input : test_str = β€˜geeksforgeeks_best_for_geeks’ Output : geeksforgeeksBestForGeeks Explanation : String converted to Camel Case. " }, { "code": null, "e": 414, "s": 346, "text": "Method #1 : Using split() + join() + title() + generator expression" }, { "code": null, "e": 644, "s": 414, "text": "The combination of above functions can be used to solve this problem. In this, we first split all underscores, and then join the string appending initial word, followed by title cased words using generator expression and title()." }, { "code": null, "e": 652, "s": 644, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Snake Case String to Camel Case# Using split() + join() + title() + generator expression # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint(\"The original string is : \" + str(test_str)) # split underscore using splittemp = test_str.split('_') # joining result res = temp[0] + ''.join(ele.title() for ele in temp[1:]) # printing result print(\"The camel case string is : \" + str(res)) ", "e": 1132, "s": 652, "text": null }, { "code": null, "e": 1227, "s": 1132, "text": "The original string is : geeksforgeeks_is_best\nThe camel case string is : geeksforgeeksIsBest\n" }, { "code": null, "e": 1282, "s": 1227, "text": "Method #2 : Using split() + join() + title() + map()" }, { "code": null, "e": 1432, "s": 1282, "text": "The combination of above functions can be used to solve this problem. In this, we perform the task of extending logic to entire strings using map(). " }, { "code": null, "e": 1440, "s": 1432, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Snake Case String to Camel Case# Using split() + join() + title() + map() # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint(\"The original string is : \" + str(test_str)) # saving first and rest using split()init, *temp = test_str.split('_') # using map() to get all words other than 1st# and titlecasing themres = ''.join([init.lower(), *map(str.title, temp)]) # printing result print(\"The camel case string is : \" + str(res)) ", "e": 1965, "s": 1440, "text": null }, { "code": null, "e": 2060, "s": 1965, "text": "The original string is : geeksforgeeks_is_best\nThe camel case string is : geeksforgeeksIsBest\n" }, { "code": null, "e": 2083, "s": 2060, "text": "Python string-programs" }, { "code": null, "e": 2090, "s": 2083, "text": "Python" }, { "code": null, "e": 2106, "s": 2090, "text": "Python Programs" } ]
How to set the dropdown button in the center?
26 Aug, 2020 Dropdown menu is a menu that offers a list of options to choose from. The title of the menu is always in display and the rest of the items are hidden. It is a toggleable menu in which all the items can be shown by clicking on it. Dropdown button can be positioned in the center of the page by setting the β€œtext-align” property of dropdown div to center. The following example contains a simple Bootstrap dropdown menu with an added class β€œmy-menu”. The property β€œtext-align: center” is added to the class. Example: Here, the property β€œtext-align: center” aligns the content of dropdown div to center, which sets the dropdown button to the center. <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" /> <style> .my-menu {/*Sets all the content of dropdown div to center*/ text-align: center; } </style> </head> <body><!-- my-menu class is added to dropdown div for styling--> <div class="dropdown my-menu"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">Action 1</a> <a class="dropdown-item" href="#">Action 2</a> <a class="dropdown-item" href="#">Action 3</a> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> </body></html> Output: Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2020" }, { "code": null, "e": 258, "s": 28, "text": "Dropdown menu is a menu that offers a list of options to choose from. The title of the menu is always in display and the rest of the items are hidden. It is a toggleable menu in which all the items can be shown by clicking on it." }, { "code": null, "e": 534, "s": 258, "text": "Dropdown button can be positioned in the center of the page by setting the β€œtext-align” property of dropdown div to center. The following example contains a simple Bootstrap dropdown menu with an added class β€œmy-menu”. The property β€œtext-align: center” is added to the class." }, { "code": null, "e": 675, "s": 534, "text": "Example: Here, the property β€œtext-align: center” aligns the content of dropdown div to center, which sets the dropdown button to the center." }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\" /> <style> .my-menu {/*Sets all the content of dropdown div to center*/ text-align: center; } </style> </head> <body><!-- my-menu class is added to dropdown div for styling--> <div class=\"dropdown my-menu\"> <button class=\"btn btn-secondary dropdown-toggle\" type=\"button\" id=\"dropdownMenuButton\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"> Dropdown button </button> <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\"> <a class=\"dropdown-item\" href=\"#\">Action 1</a> <a class=\"dropdown-item\" href=\"#\">Action 2</a> <a class=\"dropdown-item\" href=\"#\">Action 3</a> </div> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> </body></html>", "e": 2697, "s": 675, "text": null }, { "code": null, "e": 2705, "s": 2697, "text": "Output:" }, { "code": null, "e": 2720, "s": 2705, "text": "Bootstrap-Misc" }, { "code": null, "e": 2730, "s": 2720, "text": "Bootstrap" }, { "code": null, "e": 2747, "s": 2730, "text": "Web Technologies" } ]
Main thread in Java
21 Sep, 2021 Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins. There are certain properties associated with the main thread which are as follows: It is the thread from which other β€œchild” threads will be spawned. Often, it must be the last thread to finish execution because it performs various shutdown actions The flow diagram is as follows: How to control Main thread The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called. The default priority of Main thread is 5 and for all remaining user threads priority will be inherited from parent to child. Example Java // Java program to control the Main Thread // Importing required classesimport java.io.*;import java.util.*; // Class 1// Main class extending thread classpublic class Test extends Thread { // Main driver method public static void main(String[] args) { // Getting reference to Main thread Thread t = Thread.currentThread(); // Getting name of Main thread System.out.println("Current thread: " + t.getName()); // Changing the name of Main thread t.setName("Geeks"); System.out.println("After name change: " + t.getName()); // Getting priority of Main thread System.out.println("Main thread priority: " + t.getPriority()); // Setting priority of Main thread to MAX(10) t.setPriority(MAX_PRIORITY); // Print and display the main thread priority System.out.println("Main thread new priority: " + t.getPriority()); for (int i = 0; i < 5; i++) { System.out.println("Main thread"); } // Main thread creating a child thread Thread ct = new Thread() { // run() method of a thread public void run() { for (int i = 0; i < 5; i++) { System.out.println("Child thread"); } } }; // Getting priority of child thread // which will be inherited from Main thread // as it is created by Main thread System.out.println("Child thread priority: " + ct.getPriority()); // Setting priority of Main thread to MIN(1) ct.setPriority(MIN_PRIORITY); System.out.println("Child thread new priority: " + ct.getPriority()); // Starting child thread ct.start(); }} // Class 2// Helper class extending Thread class// Child Thread classclass ChildThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { // Print statement whenever child thread is // called System.out.println("Child thread"); } }} Current thread: main After name change: Geeks Main thread priority: 5 Main thread new priority: 10 Main thread Main thread Main thread Main thread Main thread Child thread priority: 10 Child thread new priority: 1 Child thread Child thread Child thread Child thread Child thread Now let us discuss the relationship between the main() method and the main thread in Java. For each program, a Main thread is created by JVM(Java Virtual Machine). The β€œMain” thread first verifies the existence of the main() method, and then it initializes the class. Note that from JDK 6, main() method is mandatory in a standalone java application. Deadlocking with use of Main Thread(only single thread) We can create a deadlock by just using the Main thread, i.e. by just using a single thread. Example Java // Java program to demonstrate deadlock// using Main thread // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Print statement System.out.println("Entering into Deadlock"); // Joining the current thread Thread.currentThread().join(); // This statement will never execute System.out.println("This statement will never execute"); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } }} Output: Output explanation: The statement β€œThread.currentThread().join()”, will tell Main thread to wait for this thread(i.e. wait for itself) to die. Thus Main thread wait for itself to die, which is nothing but a deadlock. Related Article: Daemon Threads in Java.This article is contributed by Gaurav Miglani. 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. thalabala628 sagartomar9927 surindertarika1234 Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2021" }, { "code": null, "e": 483, "s": 52, "text": "Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins. " }, { "code": null, "e": 566, "s": 483, "text": "There are certain properties associated with the main thread which are as follows:" }, { "code": null, "e": 633, "s": 566, "text": "It is the thread from which other β€œchild” threads will be spawned." }, { "code": null, "e": 732, "s": 633, "text": "Often, it must be the last thread to finish execution because it performs various shutdown actions" }, { "code": null, "e": 764, "s": 732, "text": "The flow diagram is as follows:" }, { "code": null, "e": 791, "s": 764, "text": "How to control Main thread" }, { "code": null, "e": 1193, "s": 791, "text": "The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called. The default priority of Main thread is 5 and for all remaining user threads priority will be inherited from parent to child." }, { "code": null, "e": 1201, "s": 1193, "text": "Example" }, { "code": null, "e": 1206, "s": 1201, "text": "Java" }, { "code": "// Java program to control the Main Thread // Importing required classesimport java.io.*;import java.util.*; // Class 1// Main class extending thread classpublic class Test extends Thread { // Main driver method public static void main(String[] args) { // Getting reference to Main thread Thread t = Thread.currentThread(); // Getting name of Main thread System.out.println(\"Current thread: \" + t.getName()); // Changing the name of Main thread t.setName(\"Geeks\"); System.out.println(\"After name change: \" + t.getName()); // Getting priority of Main thread System.out.println(\"Main thread priority: \" + t.getPriority()); // Setting priority of Main thread to MAX(10) t.setPriority(MAX_PRIORITY); // Print and display the main thread priority System.out.println(\"Main thread new priority: \" + t.getPriority()); for (int i = 0; i < 5; i++) { System.out.println(\"Main thread\"); } // Main thread creating a child thread Thread ct = new Thread() { // run() method of a thread public void run() { for (int i = 0; i < 5; i++) { System.out.println(\"Child thread\"); } } }; // Getting priority of child thread // which will be inherited from Main thread // as it is created by Main thread System.out.println(\"Child thread priority: \" + ct.getPriority()); // Setting priority of Main thread to MIN(1) ct.setPriority(MIN_PRIORITY); System.out.println(\"Child thread new priority: \" + ct.getPriority()); // Starting child thread ct.start(); }} // Class 2// Helper class extending Thread class// Child Thread classclass ChildThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { // Print statement whenever child thread is // called System.out.println(\"Child thread\"); } }}", "e": 3429, "s": 1206, "text": null }, { "code": null, "e": 3708, "s": 3429, "text": "Current thread: main\nAfter name change: Geeks\nMain thread priority: 5\nMain thread new priority: 10\nMain thread\nMain thread\nMain thread\nMain thread\nMain thread\nChild thread priority: 10\nChild thread new priority: 1\nChild thread\nChild thread\nChild thread\nChild thread\nChild thread" }, { "code": null, "e": 4059, "s": 3708, "text": "Now let us discuss the relationship between the main() method and the main thread in Java. For each program, a Main thread is created by JVM(Java Virtual Machine). The β€œMain” thread first verifies the existence of the main() method, and then it initializes the class. Note that from JDK 6, main() method is mandatory in a standalone java application." }, { "code": null, "e": 4115, "s": 4059, "text": "Deadlocking with use of Main Thread(only single thread)" }, { "code": null, "e": 4207, "s": 4115, "text": "We can create a deadlock by just using the Main thread, i.e. by just using a single thread." }, { "code": null, "e": 4215, "s": 4207, "text": "Example" }, { "code": null, "e": 4220, "s": 4215, "text": "Java" }, { "code": "// Java program to demonstrate deadlock// using Main thread // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Print statement System.out.println(\"Entering into Deadlock\"); // Joining the current thread Thread.currentThread().join(); // This statement will never execute System.out.println(\"This statement will never execute\"); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } }}", "e": 4894, "s": 4220, "text": null }, { "code": null, "e": 4903, "s": 4894, "text": "Output: " }, { "code": null, "e": 5120, "s": 4903, "text": "Output explanation: The statement β€œThread.currentThread().join()”, will tell Main thread to wait for this thread(i.e. wait for itself) to die. Thus Main thread wait for itself to die, which is nothing but a deadlock." }, { "code": null, "e": 5582, "s": 5120, "text": "Related Article: Daemon Threads in Java.This article is contributed by Gaurav Miglani. 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": 5595, "s": 5582, "text": "thalabala628" }, { "code": null, "e": 5610, "s": 5595, "text": "sagartomar9927" }, { "code": null, "e": 5629, "s": 5610, "text": "surindertarika1234" }, { "code": null, "e": 5649, "s": 5629, "text": "Java-Multithreading" }, { "code": null, "e": 5654, "s": 5649, "text": "Java" }, { "code": null, "e": 5659, "s": 5654, "text": "Java" } ]
Removing the object from the top of the Stack in C#
28 Jan, 2019 Stack<T>.Pop Method is used to remove and returns the object at the top of the Stack<T>. This method comes under the System.Collections.Generic namespace. Syntax: public T Pop (); Return Value: It returns the Object which is to be removed from the top of the Stack. Exception : This method will give InvalidOperationException if the Stack<T> is empty. Below programs illustrate the use of the above-discussed method: Example 1: // C# Program to illustrate the// use of Stack<T>.Pop() Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of Strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); Console.WriteLine("Number of elements in the Stack: {0}", myStack.Count); // Retrieveing top element of Stack Console.Write("Top element of Stack is: "); Console.Write(myStack.Pop()); // printing the no of Stack element // after Pop operation Console.WriteLine("\nNumber of elements in the Stack: {0}", myStack.Count); }} Number of elements in the Stack: 5 Top element of Stack is: GeeksforGeeks Number of elements in the Stack: 4 Example 2: // C# Program to illustrate the// use of Stack<T>.Pop() Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(7); myStack.Push(9); Console.WriteLine("Number of elements in the Stack: {0}", myStack.Count); // Retrieveing top element of Stack Console.Write("Top element of Stack is: "); Console.Write(myStack.Pop()); // printing the no of Stack element // after Pop operation Console.WriteLine("\nNumber of elements in the Stack: {0}", myStack.Count); }} Number of elements in the Stack: 2 Top element of Stack is: 9 Number of elements in the Stack: 1 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.pop?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-Generic-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 183, "s": 28, "text": "Stack<T>.Pop Method is used to remove and returns the object at the top of the Stack<T>. This method comes under the System.Collections.Generic namespace." }, { "code": null, "e": 191, "s": 183, "text": "Syntax:" }, { "code": null, "e": 208, "s": 191, "text": "public T Pop ();" }, { "code": null, "e": 294, "s": 208, "text": "Return Value: It returns the Object which is to be removed from the top of the Stack." }, { "code": null, "e": 380, "s": 294, "text": "Exception : This method will give InvalidOperationException if the Stack<T> is empty." }, { "code": null, "e": 445, "s": 380, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 456, "s": 445, "text": "Example 1:" }, { "code": "// C# Program to illustrate the// use of Stack<T>.Pop() Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of Strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); Console.WriteLine(\"Number of elements in the Stack: {0}\", myStack.Count); // Retrieveing top element of Stack Console.Write(\"Top element of Stack is: \"); Console.Write(myStack.Pop()); // printing the no of Stack element // after Pop operation Console.WriteLine(\"\\nNumber of elements in the Stack: {0}\", myStack.Count); }}", "e": 1429, "s": 456, "text": null }, { "code": null, "e": 1539, "s": 1429, "text": "Number of elements in the Stack: 5\nTop element of Stack is: GeeksforGeeks\nNumber of elements in the Stack: 4\n" }, { "code": null, "e": 1550, "s": 1539, "text": "Example 2:" }, { "code": "// C# Program to illustrate the// use of Stack<T>.Pop() Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(7); myStack.Push(9); Console.WriteLine(\"Number of elements in the Stack: {0}\", myStack.Count); // Retrieveing top element of Stack Console.Write(\"Top element of Stack is: \"); Console.Write(myStack.Pop()); // printing the no of Stack element // after Pop operation Console.WriteLine(\"\\nNumber of elements in the Stack: {0}\", myStack.Count); }}", "e": 2391, "s": 1550, "text": null }, { "code": null, "e": 2489, "s": 2391, "text": "Number of elements in the Stack: 2\nTop element of Stack is: 9\nNumber of elements in the Stack: 1\n" }, { "code": null, "e": 2500, "s": 2489, "text": "Reference:" }, { "code": null, "e": 2607, "s": 2500, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.pop?view=netframework-4.7.2" }, { "code": null, "e": 2632, "s": 2607, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 2653, "s": 2632, "text": "CSharp-Generic-Stack" }, { "code": null, "e": 2667, "s": 2653, "text": "CSharp-method" }, { "code": null, "e": 2670, "s": 2667, "text": "C#" } ]
Python | Set 3 (Strings, Lists, Tuples, Iterations)
13 Jul, 2022 In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a part of a string, they define only starting and ending of the string. Strings are immutable, i.e., they cannot be changed. Each element of the string can be accessed using indexing or slicing operations. Python # Assigning string to a variablea = 'This is a string'print (a)b = "This is a string"print (b)c= '''This is a string'''print (c) Output: This is a string This is a string This is a string Lists are one of the most powerful data structures in python. Lists are sequenced data types. In Python, an empty list is created using list() function. They are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogeneous. A single list can contain strings, integers, as well as other objects. Lists can also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared. The elements of list can be accessed using indexing and slicing operations. Python # Declaring a listL = [1, "a" , "string" , 1+2]print L#Adding an element in the listL.append(6) print L#Deleting last element from a listL.pop()print L#Displaying Second element of the listprint L[1] The output is: 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. [1, 'a', 'string', 3] [1, 'a', 'string', 3, 6] [1, 'a', 'string', 3] a Tuples in Python: A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that tuples cannot be changed once declared. Tuples are usually faster than lists. Python tup = (1, "a", "string", 1+2)print(tup)print(tup[1]) The output is : (1, 'a', 'string', 3) a Iterations in Python: Iterations or looping can be performed in python by β€˜for’ and β€˜while’ loops. Apart from iterating upon a particular condition, we can also iterate on strings, lists, and tuples. Example 1: Iteration by while loop for a condition Python i = 1while (i < 10): print(i) i += 1 The output is: 1 2 3 4 5 6 7 8 9 Example 2: Iteration by for loop on the string Python s = "Hello World"for i in s: print(i) The output is: H e l l o W o r l d Example 3: Iteration by for loop on list Python L = [1, 4, 5, 7, 8, 9]for i in L: print(i) The output is: 1 4 5 7 8 9 Example 4: Iteration by for loop for range Python for i in range(0, 10): print(i) The output is: 0 1 2 3 4 5 6 7 8 9 Next Article – Python: Dictionary and Keywords Quiz on Data Types in Python micronick_02 mandvimishra123 sheetal18june python-list python-tuple Python School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 162, "s": 52, "text": "In the previous article, we read about the basics of Python. Now, we continue with some more python concepts." }, { "code": null, "e": 589, "s": 162, "text": "A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a part of a string, they define only starting and ending of the string. Strings are immutable, i.e., they cannot be changed. Each element of the string can be accessed using indexing or slicing operations." }, { "code": null, "e": 596, "s": 589, "text": "Python" }, { "code": "# Assigning string to a variablea = 'This is a string'print (a)b = \"This is a string\"print (b)c= '''This is a string'''print (c)", "e": 725, "s": 596, "text": null }, { "code": null, "e": 733, "s": 725, "text": "Output:" }, { "code": null, "e": 784, "s": 733, "text": "This is a string\nThis is a string\nThis is a string" }, { "code": null, "e": 1336, "s": 784, "text": "Lists are one of the most powerful data structures in python. Lists are sequenced data types. In Python, an empty list is created using list() function. They are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogeneous. A single list can contain strings, integers, as well as other objects. Lists can also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared. The elements of list can be accessed using indexing and slicing operations." }, { "code": null, "e": 1343, "s": 1336, "text": "Python" }, { "code": "# Declaring a listL = [1, \"a\" , \"string\" , 1+2]print L#Adding an element in the listL.append(6) print L#Deleting last element from a listL.pop()print L#Displaying Second element of the listprint L[1]", "e": 1546, "s": 1343, "text": null }, { "code": null, "e": 1563, "s": 1546, "text": "The output is: " }, { "code": null, "e": 1572, "s": 1563, "text": "Chapters" }, { "code": null, "e": 1599, "s": 1572, "text": "descriptions off, selected" }, { "code": null, "e": 1649, "s": 1599, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1672, "s": 1649, "text": "captions off, selected" }, { "code": null, "e": 1680, "s": 1672, "text": "English" }, { "code": null, "e": 1704, "s": 1680, "text": "This is a modal window." }, { "code": null, "e": 1773, "s": 1704, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1795, "s": 1773, "text": "End of dialog window." }, { "code": null, "e": 1866, "s": 1795, "text": "[1, 'a', 'string', 3]\n[1, 'a', 'string', 3, 6]\n[1, 'a', 'string', 3]\na" }, { "code": null, "e": 2064, "s": 1866, "text": "Tuples in Python: A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that tuples cannot be changed once declared. Tuples are usually faster than lists." }, { "code": null, "e": 2071, "s": 2064, "text": "Python" }, { "code": "tup = (1, \"a\", \"string\", 1+2)print(tup)print(tup[1])", "e": 2124, "s": 2071, "text": null }, { "code": null, "e": 2141, "s": 2124, "text": "The output is : " }, { "code": null, "e": 2165, "s": 2141, "text": "(1, 'a', 'string', 3)\na" }, { "code": null, "e": 2365, "s": 2165, "text": "Iterations in Python: Iterations or looping can be performed in python by β€˜for’ and β€˜while’ loops. Apart from iterating upon a particular condition, we can also iterate on strings, lists, and tuples." }, { "code": null, "e": 2416, "s": 2365, "text": "Example 1: Iteration by while loop for a condition" }, { "code": null, "e": 2423, "s": 2416, "text": "Python" }, { "code": "i = 1while (i < 10): print(i) i += 1", "e": 2466, "s": 2423, "text": null }, { "code": null, "e": 2482, "s": 2466, "text": "The output is: " }, { "code": null, "e": 2501, "s": 2482, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9 " }, { "code": null, "e": 2548, "s": 2501, "text": "Example 2: Iteration by for loop on the string" }, { "code": null, "e": 2555, "s": 2548, "text": "Python" }, { "code": "s = \"Hello World\"for i in s: print(i)", "e": 2596, "s": 2555, "text": null }, { "code": null, "e": 2612, "s": 2596, "text": "The output is: " }, { "code": null, "e": 2634, "s": 2612, "text": "H\ne\nl\nl\no\n \nW\no\nr\nl\nd" }, { "code": null, "e": 2675, "s": 2634, "text": "Example 3: Iteration by for loop on list" }, { "code": null, "e": 2682, "s": 2675, "text": "Python" }, { "code": "L = [1, 4, 5, 7, 8, 9]for i in L: print(i)", "e": 2728, "s": 2682, "text": null }, { "code": null, "e": 2744, "s": 2728, "text": "The output is: " }, { "code": null, "e": 2756, "s": 2744, "text": "1\n4\n5\n7\n8\n9" }, { "code": null, "e": 2799, "s": 2756, "text": "Example 4: Iteration by for loop for range" }, { "code": null, "e": 2806, "s": 2799, "text": "Python" }, { "code": "for i in range(0, 10): print(i)", "e": 2841, "s": 2806, "text": null }, { "code": null, "e": 2857, "s": 2841, "text": "The output is: " }, { "code": null, "e": 2879, "s": 2857, "text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9 \n" }, { "code": null, "e": 2926, "s": 2879, "text": "Next Article – Python: Dictionary and Keywords" }, { "code": null, "e": 2955, "s": 2926, "text": "Quiz on Data Types in Python" }, { "code": null, "e": 2968, "s": 2955, "text": "micronick_02" }, { "code": null, "e": 2984, "s": 2968, "text": "mandvimishra123" }, { "code": null, "e": 2998, "s": 2984, "text": "sheetal18june" }, { "code": null, "e": 3010, "s": 2998, "text": "python-list" }, { "code": null, "e": 3023, "s": 3010, "text": "python-tuple" }, { "code": null, "e": 3030, "s": 3023, "text": "Python" }, { "code": null, "e": 3049, "s": 3030, "text": "School Programming" }, { "code": null, "e": 3061, "s": 3049, "text": "python-list" } ]
Counting frequencies of array elements
21 Jun, 2022 Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20} Output : 10 3 20 4 5 1 Input : arr[] = {10, 20, 20} Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items. C++ Java Python3 C# Javascript // CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ // Mark all array elements as not visited vector<bool> visited(n, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } cout << arr[i] << " " << count << endl; }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies of array itemsimport java.util.Arrays; class GFG{public static void countFreq(int arr[], int n){ boolean visited[] = new boolean[n]; Arrays.fill(visited, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } System.out.println(arr[i] + " " + count); }} // Driver codepublic static void main(String []args){ int arr[] = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code contributed by Adarsh_Verma. # Python 3 program to count frequencies# of array itemsdef countFreq(arr, n): # Mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already # processed if (visited[i] == True): continue # Count frequency count = 1 for j in range(i + 1, n, 1): if (arr[i] == arr[j]): visited[j] = True count += 1 print(arr[i], count) # Driver Codeif __name__ == '__main__': arr = [10, 20, 20, 10, 10, 20, 5, 20] n = len(arr) countFreq(arr, n) # This code is contributed by# Shashank_Sharma // C# program to count frequencies of array itemsusing System; class GFG{ public static void countFreq(int []arr, int n) { bool []visited = new bool[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } Console.WriteLine(arr[i] + " " + count); } } // Driver code public static void Main(String []args) { int []arr = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to count frequencies of array items function countFreq(arr, n){ let visited = Array.from({length: n}, (_, i) => false); // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency let count = 1; for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } document.write(arr[i] + " " + count + "<br/>"); }} // Driver Code let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; let n = arr.length; countFreq(arr, n); </script> 10 3 20 4 5 1 Time Complexity : O(n2) Auxiliary Space : O(n) 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. An efficient solution is to use hashing. C++ Java Python3 C# Javascript // CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map and print frequencies for (auto x : mp) cout << x.first << " " << x.second << endl;} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies of array itemsimport java.util.*; class GFG{ static void countFreq(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } // Driver code public static void main(String args[]) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.length; countFreq(arr, n); }} // This code contributed by Rajput-Ji # Python3 program to count frequencies # of array itemsdef countFreq(arr, n): mp = dict() # Traverse through array elements # and count frequencies for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse through map and print # frequencies for x in mp: print(x, " ", mp[x]) # Driver codearr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr)countFreq(arr, n) # This code is contributed by # Mohit kumar 29 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static void countFreq(int []arr, int n) { Dictionary<int, int> mp = new Dictionary<int,int>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Traverse through map and print frequencies foreach(KeyValuePair<int, int> entry in mp) { Console.WriteLine(entry.Key + " " + entry.Value); } } // Driver code public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to count // frequencies of array items function countFreq(arr, n){ var mp = new Map(); // Traverse through array elements and // count frequencies for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } var keys = []; mp.forEach((value, key) => { keys.push(key); }); keys.sort((a,b)=> a-b); // Traverse through map and print frequencies keys.forEach((key) => { document.write(key + " " + mp.get(key)+ "<br>"); });} var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n); </script> 5 1 10 3 20 4 Time Complexity : O(n) Auxiliary Space : O(n) In above efficient solution, how to print elements in same order as they appear in input? C++ Java Python3 C# Javascript // CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { cout << arr[i] << " " << mp[arr[i]] << endl; mp[arr[i]] = -1; } }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies of array items import java.util.*; class GFG { static void countFreq(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1); } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { System.out.println(arr[i] + " " + mp.get(arr[i])); mp.put(arr[i], -1); } } } // Driver code public static void main(String[] args) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.length; countFreq(arr, n); }} // This code contributed by Rajput-Ji # Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] not in mp: mp[arr[i]] = 0 mp[arr[i]] += 1 # To print elements according to first # occurrence, traverse array one more time # print frequencies of elements and mark # frequencies as -1 so that same element # is not printed multiple times. for i in range(n): if (mp[arr[i]] != -1): print(arr[i],mp[arr[i]]) mp[arr[i]] = -1 # Driver code arr = [10, 20, 20, 10, 10, 20, 5, 20]n = len(arr)countFreq(arr, n) # This code is contributed by shubhamsingh10 // C# program to count frequencies of array items using System;using System.Collections.Generic; class GFG { static void countFreq(int []arr, int n) { Dictionary<int,int> mp = new Dictionary<int,int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1) { Console.WriteLine(arr[i] + " " + mp[arr[i]]); mp.Remove(arr[i]); mp.Add(arr[i], -1); } } } // Driver code public static void Main(String[] args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); } } // This code is contributed by Princi Singh <script> // Javascript program to count frequencies of array items function countFreq(arr, n){ var mp = new Map(); // Traverse through array elements and // count frequencies for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (var i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { document.write( arr[i] + " " + mp.get(arr[i]) + "<br>"); mp.set(arr[i], -1); } }} var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n); // This code is contributed by rrrtnx.</script> 10 3 20 4 5 1 Time Complexity : O(n) Auxiliary Space : O(n) This problem can be solved in Java using Hashmap. Below is the program. C++ Java Python3 C# Javascript // C++ program to count frequencies of// integers in array using Hashmap#include <bits/stdc++.h>using namespace std; void frequencyNumber(int arr[],int size){ // Creating a HashMap containing integer // as a key and occurrences as a value unordered_map<int,int>freqMap; for (int i=0;i<size;i++) { freqMap[arr[i]]++; } // Printing the freqMap for (auto it : freqMap) { cout<<it.first<<" "<<it.second<<endl; }} int main(){ int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int size = sizeof(arr)/sizeof(arr[0]); frequencyNumber(arr,size);} // This code is contributed by shinjanpatra. // Java program to count frequencies of// integers in array using Hashmapimport java.io.*;import java.util.*;class OccurenceOfNumberInArray { static void frequencyNumber(int arr[], int size) { // Creating a HashMap containing integer // as a key and occurrences as a value HashMap<Integer, Integer> freqMap = new HashMap<Integer, Integer>(); for (int i=0;i<size;i++) { if (freqMap.containsKey(arr[i])) { // If number is present in freqMap, // incrementing it's count by 1 freqMap.put(arr[i], freqMap.get(arr[i]) + 1); } else { // If integer is not present in freqMap, // putting this integer to freqMap with 1 as it's value freqMap.put(arr[i], 1); } } // Printing the freqMap for (Map.Entry entry : freqMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } // Driver Code public static void main(String[] args) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int size = arr.length; frequencyNumber(arr,size); }} # Python program to count frequencies of# integers in array using Hashmap def frequencyNumber(arr,size): # Creating a HashMap containing integer # as a key and occurrences as a value freqMap = {} for i in range(size): if (arr[i] in freqMap): # If number is present in freqMap, # incrementing it's count by 1 freqMap[arr[i]] = freqMap[arr[i]] + 1 else: # If integer is not present in freqMap, # putting this integer to freqMap with 1 as it's value freqMap[arr[i]] = 1 # Printing the freqMap for key, value in freqMap.items(): print(f"{key} {value}") # Driver Codearr = [10, 20, 20, 10, 10, 20, 5, 20]size = len(arr)frequencyNumber(arr,size) # This code is contributed by shinjanpatra // C# program to count frequencies of// integers in array using Hashmapusing System;using System.Collections.Generic; class GFG{ static void frequencyNumber(int []arr,int size) { // Creating a Dictionary containing integer // as a key and occurrences as a value Dictionary<int, int> freqMap = new Dictionary<int,int>(); for(int i = 0; i < size; i++){ if (freqMap.ContainsKey(arr[i])) { var val = freqMap[arr[i]]; freqMap.Remove(arr[i]); freqMap.Add(arr[i], val + 1); } else { freqMap.Add(arr[i], 1); } } // Printing the freqMap foreach(KeyValuePair<int, int> entry in freqMap) { Console.WriteLine(entry.Key + " " + entry.Value); } } public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int size = arr.Length; frequencyNumber(arr,size); }}// This code is contributed by Taranpreet <script>// Javascript program to count frequencies of// integers in array using Hashmap function frequencyNumber(arr,size){ // Creating a HashMap containing integer // as a key and occurrences as a value let freqMap = new Map(); for (let i=0;i<size;i++) { if (freqMap.has(arr[i])) { // If number is present in freqMap, // incrementing it's count by 1 freqMap.set(arr[i], freqMap.get(arr[i]) + 1); } else { // If integer is not present in freqMap, // putting this integer to freqMap with 1 as it's value freqMap.set(arr[i], 1); } } // Printing the freqMap for (let [key, value] of freqMap.entries()) { document.write(key + " " + value+"<br>"); }} // Driver Codelet arr=[10, 20, 20, 10, 10, 20, 5, 20];let size = arr.length;frequencyNumber(arr,size); // This code is contributed by patel2127</script> 5 1 10 3 20 4 Time Complexity: O(n) since using a single loop to track frequencyAuxiliary Space: O(n) for hashmap Ajit kumar panigrahy mohit kumar 29 Shashank_Sharma Adarsh_Verma 29AjayKumar Rajput-Ji princiraj1992 princi singh neo_700 SHUBHAMSINGH10 sanjoy_62 itsok rrrtnx patel2127 kk9826225 simmytarika5 surinderdawra388 shinjanpatra singhh3010 polymatir3j cpp-unordered_map frequency-counting Arrays Hash Arrays Hash 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 Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search What is Hashing | A Complete Tutorial Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Hashing | Set 1 (Introduction) Internal Working of HashMap in Java Longest Consecutive Subsequence
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 139, "s": 52, "text": "Given an array which may contain duplicates, print all elements and their frequencies." }, { "code": null, "e": 150, "s": 139, "text": "Examples: " }, { "code": null, "e": 300, "s": 150, "text": "Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}\nOutput : 10 3\n 20 4\n 5 1\n\nInput : arr[] = {10, 20, 20}\nOutput : 10 1\n 20 2 " }, { "code": null, "e": 449, "s": 300, "text": "A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items. " }, { "code": null, "e": 453, "s": 449, "text": "C++" }, { "code": null, "e": 458, "s": 453, "text": "Java" }, { "code": null, "e": 466, "s": 458, "text": "Python3" }, { "code": null, "e": 469, "s": 466, "text": "C#" }, { "code": null, "e": 480, "s": 469, "text": "Javascript" }, { "code": "// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ // Mark all array elements as not visited vector<bool> visited(n, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } cout << arr[i] << \" \" << count << endl; }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 1293, "s": 480, "text": null }, { "code": "// Java program to count frequencies of array itemsimport java.util.Arrays; class GFG{public static void countFreq(int arr[], int n){ boolean visited[] = new boolean[n]; Arrays.fill(visited, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } System.out.println(arr[i] + \" \" + count); }} // Driver codepublic static void main(String []args){ int arr[] = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code contributed by Adarsh_Verma.", "e": 2174, "s": 1293, "text": null }, { "code": "# Python 3 program to count frequencies# of array itemsdef countFreq(arr, n): # Mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already # processed if (visited[i] == True): continue # Count frequency count = 1 for j in range(i + 1, n, 1): if (arr[i] == arr[j]): visited[j] = True count += 1 print(arr[i], count) # Driver Codeif __name__ == '__main__': arr = [10, 20, 20, 10, 10, 20, 5, 20] n = len(arr) countFreq(arr, n) # This code is contributed by# Shashank_Sharma", "e": 2932, "s": 2174, "text": null }, { "code": "// C# program to count frequencies of array itemsusing System; class GFG{ public static void countFreq(int []arr, int n) { bool []visited = new bool[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } Console.WriteLine(arr[i] + \" \" + count); } } // Driver code public static void Main(String []args) { int []arr = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 3921, "s": 2932, "text": null }, { "code": "<script> // JavaScript program to count frequencies of array items function countFreq(arr, n){ let visited = Array.from({length: n}, (_, i) => false); // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency let count = 1; for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } document.write(arr[i] + \" \" + count + \"<br/>\"); }} // Driver Code let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; let n = arr.length; countFreq(arr, n); </script>", "e": 4689, "s": 3921, "text": null }, { "code": null, "e": 4703, "s": 4689, "text": "10 3\n20 4\n5 1" }, { "code": null, "e": 4750, "s": 4703, "text": "Time Complexity : O(n2) Auxiliary Space : O(n)" }, { "code": null, "e": 4759, "s": 4750, "text": "Chapters" }, { "code": null, "e": 4786, "s": 4759, "text": "descriptions off, selected" }, { "code": null, "e": 4836, "s": 4786, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4859, "s": 4836, "text": "captions off, selected" }, { "code": null, "e": 4867, "s": 4859, "text": "English" }, { "code": null, "e": 4891, "s": 4867, "text": "This is a modal window." }, { "code": null, "e": 4960, "s": 4891, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 4982, "s": 4960, "text": "End of dialog window." }, { "code": null, "e": 5023, "s": 4982, "text": "An efficient solution is to use hashing." }, { "code": null, "e": 5027, "s": 5023, "text": "C++" }, { "code": null, "e": 5032, "s": 5027, "text": "Java" }, { "code": null, "e": 5040, "s": 5032, "text": "Python3" }, { "code": null, "e": 5043, "s": 5040, "text": "C#" }, { "code": null, "e": 5054, "s": 5043, "text": "Javascript" }, { "code": "// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map and print frequencies for (auto x : mp) cout << x.first << \" \" << x.second << endl;} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 5599, "s": 5054, "text": null }, { "code": "// Java program to count frequencies of array itemsimport java.util.*; class GFG{ static void countFreq(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { System.out.println(entry.getKey() + \" \" + entry.getValue()); } } // Driver code public static void main(String args[]) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.length; countFreq(arr, n); }} // This code contributed by Rajput-Ji", "e": 6535, "s": 5599, "text": null }, { "code": "# Python3 program to count frequencies # of array itemsdef countFreq(arr, n): mp = dict() # Traverse through array elements # and count frequencies for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse through map and print # frequencies for x in mp: print(x, \" \", mp[x]) # Driver codearr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr)countFreq(arr, n) # This code is contributed by # Mohit kumar 29", "e": 7058, "s": 6535, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static void countFreq(int []arr, int n) { Dictionary<int, int> mp = new Dictionary<int,int>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Traverse through map and print frequencies foreach(KeyValuePair<int, int> entry in mp) { Console.WriteLine(entry.Key + \" \" + entry.Value); } } // Driver code public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); }} /* This code contributed by PrinciRaj1992 */", "e": 8071, "s": 7058, "text": null }, { "code": "<script> // JavaScript program to count // frequencies of array items function countFreq(arr, n){ var mp = new Map(); // Traverse through array elements and // count frequencies for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } var keys = []; mp.forEach((value, key) => { keys.push(key); }); keys.sort((a,b)=> a-b); // Traverse through map and print frequencies keys.forEach((key) => { document.write(key + \" \" + mp.get(key)+ \"<br>\"); });} var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n); </script>", "e": 8773, "s": 8071, "text": null }, { "code": null, "e": 8787, "s": 8773, "text": "5 1\n10 3\n20 4" }, { "code": null, "e": 8833, "s": 8787, "text": "Time Complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 8924, "s": 8833, "text": "In above efficient solution, how to print elements in same order as they appear in input? " }, { "code": null, "e": 8928, "s": 8924, "text": "C++" }, { "code": null, "e": 8933, "s": 8928, "text": "Java" }, { "code": null, "e": 8941, "s": 8933, "text": "Python3" }, { "code": null, "e": 8944, "s": 8941, "text": "C#" }, { "code": null, "e": 8955, "s": 8944, "text": "Javascript" }, { "code": "// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { cout << arr[i] << \" \" << mp[arr[i]] << endl; mp[arr[i]] = -1; } }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 9755, "s": 8955, "text": null }, { "code": "// Java program to count frequencies of array items import java.util.*; class GFG { static void countFreq(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1); } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { System.out.println(arr[i] + \" \" + mp.get(arr[i])); mp.put(arr[i], -1); } } } // Driver code public static void main(String[] args) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.length; countFreq(arr, n); }} // This code contributed by Rajput-Ji", "e": 10835, "s": 9755, "text": null }, { "code": "# Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] not in mp: mp[arr[i]] = 0 mp[arr[i]] += 1 # To print elements according to first # occurrence, traverse array one more time # print frequencies of elements and mark # frequencies as -1 so that same element # is not printed multiple times. for i in range(n): if (mp[arr[i]] != -1): print(arr[i],mp[arr[i]]) mp[arr[i]] = -1 # Driver code arr = [10, 20, 20, 10, 10, 20, 5, 20]n = len(arr)countFreq(arr, n) # This code is contributed by shubhamsingh10", "e": 11559, "s": 10835, "text": null }, { "code": "// C# program to count frequencies of array items using System;using System.Collections.Generic; class GFG { static void countFreq(int []arr, int n) { Dictionary<int,int> mp = new Dictionary<int,int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1) { Console.WriteLine(arr[i] + \" \" + mp[arr[i]]); mp.Remove(arr[i]); mp.Add(arr[i], -1); } } } // Driver code public static void Main(String[] args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); } } // This code is contributed by Princi Singh", "e": 12933, "s": 11559, "text": null }, { "code": "<script> // Javascript program to count frequencies of array items function countFreq(arr, n){ var mp = new Map(); // Traverse through array elements and // count frequencies for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (var i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { document.write( arr[i] + \" \" + mp.get(arr[i]) + \"<br>\"); mp.set(arr[i], -1); } }} var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n); // This code is contributed by rrrtnx.</script>", "e": 13807, "s": 12933, "text": null }, { "code": null, "e": 13821, "s": 13807, "text": "10 3\n20 4\n5 1" }, { "code": null, "e": 13867, "s": 13821, "text": "Time Complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 13940, "s": 13867, "text": "This problem can be solved in Java using Hashmap. Below is the program. " }, { "code": null, "e": 13944, "s": 13940, "text": "C++" }, { "code": null, "e": 13949, "s": 13944, "text": "Java" }, { "code": null, "e": 13957, "s": 13949, "text": "Python3" }, { "code": null, "e": 13960, "s": 13957, "text": "C#" }, { "code": null, "e": 13971, "s": 13960, "text": "Javascript" }, { "code": "// C++ program to count frequencies of// integers in array using Hashmap#include <bits/stdc++.h>using namespace std; void frequencyNumber(int arr[],int size){ // Creating a HashMap containing integer // as a key and occurrences as a value unordered_map<int,int>freqMap; for (int i=0;i<size;i++) { freqMap[arr[i]]++; } // Printing the freqMap for (auto it : freqMap) { cout<<it.first<<\" \"<<it.second<<endl; }} int main(){ int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int size = sizeof(arr)/sizeof(arr[0]); frequencyNumber(arr,size);} // This code is contributed by shinjanpatra.", "e": 14577, "s": 13971, "text": null }, { "code": "// Java program to count frequencies of// integers in array using Hashmapimport java.io.*;import java.util.*;class OccurenceOfNumberInArray { static void frequencyNumber(int arr[], int size) { // Creating a HashMap containing integer // as a key and occurrences as a value HashMap<Integer, Integer> freqMap = new HashMap<Integer, Integer>(); for (int i=0;i<size;i++) { if (freqMap.containsKey(arr[i])) { // If number is present in freqMap, // incrementing it's count by 1 freqMap.put(arr[i], freqMap.get(arr[i]) + 1); } else { // If integer is not present in freqMap, // putting this integer to freqMap with 1 as it's value freqMap.put(arr[i], 1); } } // Printing the freqMap for (Map.Entry entry : freqMap.entrySet()) { System.out.println(entry.getKey() + \" \" + entry.getValue()); } } // Driver Code public static void main(String[] args) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int size = arr.length; frequencyNumber(arr,size); }}", "e": 15781, "s": 14577, "text": null }, { "code": "# Python program to count frequencies of# integers in array using Hashmap def frequencyNumber(arr,size): # Creating a HashMap containing integer # as a key and occurrences as a value freqMap = {} for i in range(size): if (arr[i] in freqMap): # If number is present in freqMap, # incrementing it's count by 1 freqMap[arr[i]] = freqMap[arr[i]] + 1 else: # If integer is not present in freqMap, # putting this integer to freqMap with 1 as it's value freqMap[arr[i]] = 1 # Printing the freqMap for key, value in freqMap.items(): print(f\"{key} {value}\") # Driver Codearr = [10, 20, 20, 10, 10, 20, 5, 20]size = len(arr)frequencyNumber(arr,size) # This code is contributed by shinjanpatra", "e": 16640, "s": 15781, "text": null }, { "code": "// C# program to count frequencies of// integers in array using Hashmapusing System;using System.Collections.Generic; class GFG{ static void frequencyNumber(int []arr,int size) { // Creating a Dictionary containing integer // as a key and occurrences as a value Dictionary<int, int> freqMap = new Dictionary<int,int>(); for(int i = 0; i < size; i++){ if (freqMap.ContainsKey(arr[i])) { var val = freqMap[arr[i]]; freqMap.Remove(arr[i]); freqMap.Add(arr[i], val + 1); } else { freqMap.Add(arr[i], 1); } } // Printing the freqMap foreach(KeyValuePair<int, int> entry in freqMap) { Console.WriteLine(entry.Key + \" \" + entry.Value); } } public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int size = arr.Length; frequencyNumber(arr,size); }}// This code is contributed by Taranpreet", "e": 17570, "s": 16640, "text": null }, { "code": "<script>// Javascript program to count frequencies of// integers in array using Hashmap function frequencyNumber(arr,size){ // Creating a HashMap containing integer // as a key and occurrences as a value let freqMap = new Map(); for (let i=0;i<size;i++) { if (freqMap.has(arr[i])) { // If number is present in freqMap, // incrementing it's count by 1 freqMap.set(arr[i], freqMap.get(arr[i]) + 1); } else { // If integer is not present in freqMap, // putting this integer to freqMap with 1 as it's value freqMap.set(arr[i], 1); } } // Printing the freqMap for (let [key, value] of freqMap.entries()) { document.write(key + \" \" + value+\"<br>\"); }} // Driver Codelet arr=[10, 20, 20, 10, 10, 20, 5, 20];let size = arr.length;frequencyNumber(arr,size); // This code is contributed by patel2127</script>", "e": 18592, "s": 17570, "text": null }, { "code": null, "e": 18606, "s": 18592, "text": "5 1\n10 3\n20 4" }, { "code": null, "e": 18706, "s": 18606, "text": "Time Complexity: O(n) since using a single loop to track frequencyAuxiliary Space: O(n) for hashmap" }, { "code": null, "e": 18727, "s": 18706, "text": "Ajit kumar panigrahy" }, { "code": null, "e": 18742, "s": 18727, "text": "mohit kumar 29" }, { "code": null, "e": 18758, "s": 18742, "text": "Shashank_Sharma" }, { "code": null, "e": 18771, "s": 18758, "text": "Adarsh_Verma" }, { "code": null, "e": 18783, "s": 18771, "text": "29AjayKumar" }, { "code": null, "e": 18793, "s": 18783, "text": "Rajput-Ji" }, { "code": null, "e": 18807, "s": 18793, "text": "princiraj1992" }, { "code": null, "e": 18820, "s": 18807, "text": "princi singh" }, { "code": null, "e": 18828, "s": 18820, "text": "neo_700" }, { "code": null, "e": 18843, "s": 18828, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 18853, "s": 18843, "text": "sanjoy_62" }, { "code": null, "e": 18859, "s": 18853, "text": "itsok" }, { "code": null, "e": 18866, "s": 18859, "text": "rrrtnx" }, { "code": null, "e": 18876, "s": 18866, "text": "patel2127" }, { "code": null, "e": 18886, "s": 18876, "text": "kk9826225" }, { "code": null, "e": 18899, "s": 18886, "text": "simmytarika5" }, { "code": null, "e": 18916, "s": 18899, "text": "surinderdawra388" }, { "code": null, "e": 18929, "s": 18916, "text": "shinjanpatra" }, { "code": null, "e": 18940, "s": 18929, "text": "singhh3010" }, { "code": null, "e": 18952, "s": 18940, "text": "polymatir3j" }, { "code": null, "e": 18970, "s": 18952, "text": "cpp-unordered_map" }, { "code": null, "e": 18989, "s": 18970, "text": "frequency-counting" }, { "code": null, "e": 18996, "s": 18989, "text": "Arrays" }, { "code": null, "e": 19001, "s": 18996, "text": "Hash" }, { "code": null, "e": 19008, "s": 19001, "text": "Arrays" }, { "code": null, "e": 19013, "s": 19008, "text": "Hash" }, { "code": null, "e": 19111, "s": 19013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19179, "s": 19111, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 19223, "s": 19179, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 19255, "s": 19223, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 19303, "s": 19255, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 19317, "s": 19303, "text": "Linear Search" }, { "code": null, "e": 19355, "s": 19317, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 19440, "s": 19355, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 19471, "s": 19440, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 19507, "s": 19471, "text": "Internal Working of HashMap in Java" } ]
How to swap two bits in a given integer?
07 Jun, 2022 Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.Examples: Input: n = 28, p1 = 0, p2 = 3Output: 21Explaination: 28 in binary is 11100. If we swap 0’th and 3rd digits, we get 10101 which is 21 in decimal. Input: n = 20, p1 = 2, p2 = 3Output: 24 We strongly recommend you minimize your browser and try this yourself first.Method 1: The idea is to first find the bits, then use XOR based swapping concept, i..e., to swap two numbers β€˜x’ and β€˜y’, we do x = x ^ y, y = y ^ x, and x = x ^ y. Below is the implementation of the above idea C++ C Java C# Javascript Python3 // C++ program to swap bits in an integer#include<bits/stdc++.h>using namespace std; // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){ /* Move p1'th to rightmost side */ unsigned int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ unsigned int bit2 = (n >> p2) & 1; /* XOR the two bits */ unsigned int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){ int res = swapBits(28, 0, 3); cout<<"Result = "<< res<<" "; return 0;} // This code is contributed by pratham76. // C program to swap bits in an integer#include<stdio.h> // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){ /* Move p1'th to rightmost side */ unsigned int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ unsigned int bit2 = (n >> p2) & 1; /* XOR the two bits */ unsigned int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){ int res = swapBits(28, 0, 3); printf("Result = %d ", res); return 0;} // Java program to swap bits in an integerimport java.io.*; class GFG{ // This function swaps bit at// positions p1 and p2 in an integer nstatic int swapBits( int n, int p1, int p2){ /* Move p1'th to rightmost side */ int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ int bit2 = (n >> p2) & 1; /* XOR the two bits */ int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ int result = n ^ x; return result;} /* Driver code*/ public static void main (String[] args) { int res = swapBits(28, 0, 3); System.out.println ("Result = " + res); }} // This code is contributed by ajit.. // C# program to swap bits in an integerusing System;class GFG{ // This function swaps bit at // positions p1 and p2 in an integer n static int swapBits( int n, int p1, int p2) { /* Move p1'th to rightmost side */ int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ int bit2 = (n >> p2) & 1; /* XOR the two bits */ int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ int result = n ^ x; return result; } /* Driver code*/ public static void Main(string[] args) { int res = swapBits(28, 0, 3); Console.Write("Result = " + res); }} // This code is contributed by rutvik_56. <script>// javascript program to swap bits in an integer // This function swaps bit at// positions p1 and p2 in an integer nfunction swapBits(n , p1 , p2){ /* Move p1'th to rightmost side */ var bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ var bit2 = (n >> p2) & 1; /* XOR the two bits */ var x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ var result = n ^ x; return result;} /* Driver code*/var res = swapBits(28, 0, 3);document.write("Result = " + res); // This code contributed by Princi Singh</script> # Python3 program for the above approach # This function swaps bit at positions p1 and p2 in an integer ndef swapBits(n, p1, p2): # Move p1'th to rightmost side bit1 = (n >> p1) & 1 # Move p2'th to rightmost side bit2 = (n >> p2) & 1 # XOR the two bits x = (bit1 ^ bit2) # Put the xor bit back to their original positions x = (x << p1) | (x << p2) # XOR 'x' with the original number so that the # two sets are swapped result = n ^ x return result # Driver program to test above functionif __name__ == '__main__': res = swapBits(28, 0, 3) print("Result = ", res) # This code is contributed by nirajgusain5 Result = 21 Time Complexity: O(1)Auxiliary Space: O(1) C++ C Java Python C# Javascript //C++ code for swapping given bits of a number#include<iostream>using namespace std;int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and p2 times //and using XOR if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2)) { n ^= 1 << p1; n ^= 1 << p2; } return n;} //Driver Codeint main(){ cout << "Result = " << swapBits(28, 0, 3); return 0;} //C code for swapping given bits of a number#include<stdio.h>int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and p2 times //and using XOR if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2)) { n ^= 1 << p1; n ^= 1 << p2; } return n;} //Driver Codeint main(){ printf("Result = %d", swapBits(28, 0, 3)); return 0;} // Java code for swapping// given bits of a numberimport java.util.*;class Main{ public static int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and // p2 times and using XOR int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n;} // Driver codepublic static void main(String[] args){ System.out.print("Result = " + swapBits(28, 0, 3));}} // This code is contributed by divyeshrabadiya07 # Python code for swapping given bits of a numberdef swapBits(n, p1, p2): # left-shift 1 p1 and p2 times # and using XOR if ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2): n ^= 1 << p1 n ^= 1 << p2 return n # Driver Codeprint("Result =",swapBits(28, 0, 3)) # This code is contributed by rag2127 // C# code for swapping given bits of a numberusing System;class GFG { static int swapBits(int n, int p1, int p2) { // left-shift 1 p1 and p2 times // and using XOR int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2))); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n; } // Driver code static void Main() { Console.WriteLine("Result = " + swapBits(28, 0, 3)); }} // This code is contributed by divyesh072019 <script> // JavaScript code for swapping given bits of a number function swapBits(n, p1, p2) { temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n; } document.write("Result = " + swapBits(28, 0, 3)); </script> Result = 21 Time Complexity: O(1)Auxiliary Space: O(1) Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above jit_t SHUBHAMSINGH10 nidhi_biet yashbeersingh42 divyeshrabadiya07 rag2127 divyesh072019 rutvik_56 pratham76 suresh07 princi singh nirajgusain5 subham348 mohammad shuaib sidd harendrakumar123 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 262, "s": 54, "text": "Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.Examples: " }, { "code": null, "e": 408, "s": 262, "text": "Input: n = 28, p1 = 0, p2 = 3Output: 21Explaination: 28 in binary is 11100. If we swap 0’th and 3rd digits, we get 10101 which is 21 in decimal." }, { "code": null, "e": 448, "s": 408, "text": "Input: n = 20, p1 = 2, p2 = 3Output: 24" }, { "code": null, "e": 691, "s": 448, "text": "We strongly recommend you minimize your browser and try this yourself first.Method 1: The idea is to first find the bits, then use XOR based swapping concept, i..e., to swap two numbers β€˜x’ and β€˜y’, we do x = x ^ y, y = y ^ x, and x = x ^ y." }, { "code": null, "e": 737, "s": 691, "text": "Below is the implementation of the above idea" }, { "code": null, "e": 741, "s": 737, "text": "C++" }, { "code": null, "e": 743, "s": 741, "text": "C" }, { "code": null, "e": 748, "s": 743, "text": "Java" }, { "code": null, "e": 751, "s": 748, "text": "C#" }, { "code": null, "e": 762, "s": 751, "text": "Javascript" }, { "code": null, "e": 770, "s": 762, "text": "Python3" }, { "code": "// C++ program to swap bits in an integer#include<bits/stdc++.h>using namespace std; // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){ /* Move p1'th to rightmost side */ unsigned int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ unsigned int bit2 = (n >> p2) & 1; /* XOR the two bits */ unsigned int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){ int res = swapBits(28, 0, 3); cout<<\"Result = \"<< res<<\" \"; return 0;} // This code is contributed by pratham76.", "e": 1582, "s": 770, "text": null }, { "code": "// C program to swap bits in an integer#include<stdio.h> // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){ /* Move p1'th to rightmost side */ unsigned int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ unsigned int bit2 = (n >> p2) & 1; /* XOR the two bits */ unsigned int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){ int res = swapBits(28, 0, 3); printf(\"Result = %d \", res); return 0;}", "e": 2323, "s": 1582, "text": null }, { "code": "// Java program to swap bits in an integerimport java.io.*; class GFG{ // This function swaps bit at// positions p1 and p2 in an integer nstatic int swapBits( int n, int p1, int p2){ /* Move p1'th to rightmost side */ int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ int bit2 = (n >> p2) & 1; /* XOR the two bits */ int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ int result = n ^ x; return result;} /* Driver code*/ public static void main (String[] args) { int res = swapBits(28, 0, 3); System.out.println (\"Result = \" + res); }} // This code is contributed by ajit..", "e": 3111, "s": 2323, "text": null }, { "code": "// C# program to swap bits in an integerusing System;class GFG{ // This function swaps bit at // positions p1 and p2 in an integer n static int swapBits( int n, int p1, int p2) { /* Move p1'th to rightmost side */ int bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ int bit2 = (n >> p2) & 1; /* XOR the two bits */ int x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ int result = n ^ x; return result; } /* Driver code*/ public static void Main(string[] args) { int res = swapBits(28, 0, 3); Console.Write(\"Result = \" + res); }} // This code is contributed by rutvik_56.", "e": 3880, "s": 3111, "text": null }, { "code": "<script>// javascript program to swap bits in an integer // This function swaps bit at// positions p1 and p2 in an integer nfunction swapBits(n , p1 , p2){ /* Move p1'th to rightmost side */ var bit1 = (n >> p1) & 1; /* Move p2'th to rightmost side */ var bit2 = (n >> p2) & 1; /* XOR the two bits */ var x = (bit1 ^ bit2); /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ var result = n ^ x; return result;} /* Driver code*/var res = swapBits(28, 0, 3);document.write(\"Result = \" + res); // This code contributed by Princi Singh</script>", "e": 4576, "s": 3880, "text": null }, { "code": "# Python3 program for the above approach # This function swaps bit at positions p1 and p2 in an integer ndef swapBits(n, p1, p2): # Move p1'th to rightmost side bit1 = (n >> p1) & 1 # Move p2'th to rightmost side bit2 = (n >> p2) & 1 # XOR the two bits x = (bit1 ^ bit2) # Put the xor bit back to their original positions x = (x << p1) | (x << p2) # XOR 'x' with the original number so that the # two sets are swapped result = n ^ x return result # Driver program to test above functionif __name__ == '__main__': res = swapBits(28, 0, 3) print(\"Result = \", res) # This code is contributed by nirajgusain5", "e": 5229, "s": 4576, "text": null }, { "code": null, "e": 5242, "s": 5229, "text": "Result = 21 " }, { "code": null, "e": 5286, "s": 5242, "text": "Time Complexity: O(1)Auxiliary Space: O(1) " }, { "code": null, "e": 5290, "s": 5286, "text": "C++" }, { "code": null, "e": 5292, "s": 5290, "text": "C" }, { "code": null, "e": 5297, "s": 5292, "text": "Java" }, { "code": null, "e": 5304, "s": 5297, "text": "Python" }, { "code": null, "e": 5307, "s": 5304, "text": "C#" }, { "code": null, "e": 5318, "s": 5307, "text": "Javascript" }, { "code": "//C++ code for swapping given bits of a number#include<iostream>using namespace std;int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and p2 times //and using XOR if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2)) { n ^= 1 << p1; n ^= 1 << p2; } return n;} //Driver Codeint main(){ cout << \"Result = \" << swapBits(28, 0, 3); return 0;}", "e": 5683, "s": 5318, "text": null }, { "code": "//C code for swapping given bits of a number#include<stdio.h>int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and p2 times //and using XOR if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2)) { n ^= 1 << p1; n ^= 1 << p2; } return n;} //Driver Codeint main(){ printf(\"Result = %d\", swapBits(28, 0, 3)); return 0;}", "e": 6039, "s": 5683, "text": null }, { "code": "// Java code for swapping// given bits of a numberimport java.util.*;class Main{ public static int swapBits(int n, int p1, int p2){ //left-shift 1 p1 and // p2 times and using XOR int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n;} // Driver codepublic static void main(String[] args){ System.out.print(\"Result = \" + swapBits(28, 0, 3));}} // This code is contributed by divyeshrabadiya07", "e": 6585, "s": 6039, "text": null }, { "code": "# Python code for swapping given bits of a numberdef swapBits(n, p1, p2): # left-shift 1 p1 and p2 times # and using XOR if ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2): n ^= 1 << p1 n ^= 1 << p2 return n # Driver Codeprint(\"Result =\",swapBits(28, 0, 3)) # This code is contributed by rag2127", "e": 6906, "s": 6585, "text": null }, { "code": "// C# code for swapping given bits of a numberusing System;class GFG { static int swapBits(int n, int p1, int p2) { // left-shift 1 p1 and p2 times // and using XOR int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2))); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n; } // Driver code static void Main() { Console.WriteLine(\"Result = \" + swapBits(28, 0, 3)); }} // This code is contributed by divyesh072019", "e": 7404, "s": 6906, "text": null }, { "code": "<script> // JavaScript code for swapping given bits of a number function swapBits(n, p1, p2) { temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2); if (temp >= 1) { n ^= 1 << p1; n ^= 1 << p2; } return n; } document.write(\"Result = \" + swapBits(28, 0, 3)); </script>", "e": 7755, "s": 7404, "text": null }, { "code": null, "e": 7767, "s": 7755, "text": "Result = 21" }, { "code": null, "e": 7810, "s": 7767, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 7937, "s": 7810, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above" }, { "code": null, "e": 7943, "s": 7937, "text": "jit_t" }, { "code": null, "e": 7958, "s": 7943, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7969, "s": 7958, "text": "nidhi_biet" }, { "code": null, "e": 7985, "s": 7969, "text": "yashbeersingh42" }, { "code": null, "e": 8003, "s": 7985, "text": "divyeshrabadiya07" }, { "code": null, "e": 8011, "s": 8003, "text": "rag2127" }, { "code": null, "e": 8025, "s": 8011, "text": "divyesh072019" }, { "code": null, "e": 8035, "s": 8025, "text": "rutvik_56" }, { "code": null, "e": 8045, "s": 8035, "text": "pratham76" }, { "code": null, "e": 8054, "s": 8045, "text": "suresh07" }, { "code": null, "e": 8067, "s": 8054, "text": "princi singh" }, { "code": null, "e": 8080, "s": 8067, "text": "nirajgusain5" }, { "code": null, "e": 8090, "s": 8080, "text": "subham348" }, { "code": null, "e": 8111, "s": 8090, "text": "mohammad shuaib sidd" }, { "code": null, "e": 8128, "s": 8111, "text": "harendrakumar123" }, { "code": null, "e": 8138, "s": 8128, "text": "Bit Magic" }, { "code": null, "e": 8148, "s": 8138, "text": "Bit Magic" } ]
while loop in Julia
19 Feb, 2020 In Julia, while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. If the condition is false when the while loop is executed first time, then the body of the loop will never be executed. Syntax : while expression statement(s) end Here, β€˜whileβ€˜ is the keyword to start while loop, β€˜expressionβ€˜ is the condition to be satisfied, and β€˜endβ€˜ is the keyword to end the while loop. Note: A block of code is the set of statements enclosed between the conditional statement and the β€˜endβ€˜ statement. Example 1: # Julia program to illustrate # the use of while loop # Declaring ArrayArray = ["Geeks", "For", "Geeks"] # Iterator Variablei = 1 # while loopwhile i <= length(Array) # Assigning value to object Object = Array[i] # Printing object println("$Object") # Updating iterator globally global i += 1 # Ending Loopend Output: Example 2: # Julia program to generate # the Fibonacci sequence # The length of Fibonacci sequencelength = 15 # The first two valuesa = 0b = 1 # Iterator Valueitr = 0 # while loop conditionwhile itr < length # Printing fibonacci value print(a, ", ") # Updating value c = a + b # Modify values global a = b global b = c # Updating iterator global itr += 1 # End of while loopend Julia-loops Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 371, "s": 28, "text": "In Julia, while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. If the condition is false when the while loop is executed first time, then the body of the loop will never be executed. Syntax :" }, { "code": null, "e": 412, "s": 371, "text": "while expression\n\n statement(s)\n\nend\n" }, { "code": null, "e": 557, "s": 412, "text": "Here, β€˜whileβ€˜ is the keyword to start while loop, β€˜expressionβ€˜ is the condition to be satisfied, and β€˜endβ€˜ is the keyword to end the while loop." }, { "code": null, "e": 672, "s": 557, "text": "Note: A block of code is the set of statements enclosed between the conditional statement and the β€˜endβ€˜ statement." }, { "code": null, "e": 683, "s": 672, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of while loop # Declaring ArrayArray = [\"Geeks\", \"For\", \"Geeks\"] # Iterator Variablei = 1 # while loopwhile i <= length(Array) # Assigning value to object Object = Array[i] # Printing object println(\"$Object\") # Updating iterator globally global i += 1 # Ending Loopend", "e": 1033, "s": 683, "text": null }, { "code": null, "e": 1052, "s": 1033, "text": "Output: Example 2:" }, { "code": "# Julia program to generate # the Fibonacci sequence # The length of Fibonacci sequencelength = 15 # The first two valuesa = 0b = 1 # Iterator Valueitr = 0 # while loop conditionwhile itr < length # Printing fibonacci value print(a, \", \") # Updating value c = a + b # Modify values global a = b global b = c # Updating iterator global itr += 1 # End of while loopend", "e": 1460, "s": 1052, "text": null }, { "code": null, "e": 1472, "s": 1460, "text": "Julia-loops" }, { "code": null, "e": 1478, "s": 1472, "text": "Julia" } ]
HTML | <img> vspace Attribute
06 Jan, 2022 The HTML <img> vspace Attribute is used to specify the number of whitespaces on bottom and top side of an image. Note: The HTML vspace Attribute not supported by HTML5 Syntax: <img vspace="pixels"> Attribute Values: pixels: It specifies the number of whitespaces on top and bottom of an image in terms of pixels. Example: <!DOCTYPE html> <html> <head> <title> HTML img vspace Attribute </title> <style> h1, h2 { color:green; text-align:center; } h3 { font-weight:bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>HTML <img> vspace Attribute</h2> <h3>Image without vspace Attribute</h3> <p> <img id="myImage" src= "https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="42" height="42" align="middle"/> It is a computer science portal for geeks </p> <h3>Image with vspace Attribute</h3> <p> <img id="myImage" src= "https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" vspace = "60" width="42" height="42" align="middle"/> It is a computer science portal for geeks </p></body> </html> Output: Supported Browsers: The browser supported by HTML <img> vspace Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jan, 2022" }, { "code": null, "e": 166, "s": 53, "text": "The HTML <img> vspace Attribute is used to specify the number of whitespaces on bottom and top side of an image." }, { "code": null, "e": 222, "s": 166, "text": "Note: The HTML vspace Attribute not supported by HTML5" }, { "code": null, "e": 230, "s": 222, "text": "Syntax:" }, { "code": null, "e": 252, "s": 230, "text": "<img vspace=\"pixels\">" }, { "code": null, "e": 270, "s": 252, "text": "Attribute Values:" }, { "code": null, "e": 367, "s": 270, "text": "pixels: It specifies the number of whitespaces on top and bottom of an image in terms of pixels." }, { "code": null, "e": 376, "s": 367, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML img vspace Attribute </title> <style> h1, h2 { color:green; text-align:center; } h3 { font-weight:bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>HTML <img> vspace Attribute</h2> <h3>Image without vspace Attribute</h3> <p> <img id=\"myImage\" src= \"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"42\" height=\"42\" align=\"middle\"/> It is a computer science portal for geeks </p> <h3>Image with vspace Attribute</h3> <p> <img id=\"myImage\" src= \"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" vspace = \"60\" width=\"42\" height=\"42\" align=\"middle\"/> It is a computer science portal for geeks </p></body> </html> ", "e": 1373, "s": 376, "text": null }, { "code": null, "e": 1381, "s": 1373, "text": "Output:" }, { "code": null, "e": 1472, "s": 1381, "text": "Supported Browsers: The browser supported by HTML <img> vspace Attribute are listed below:" }, { "code": null, "e": 1486, "s": 1472, "text": "Google Chrome" }, { "code": null, "e": 1504, "s": 1486, "text": "Internet Explorer" }, { "code": null, "e": 1512, "s": 1504, "text": "Firefox" }, { "code": null, "e": 1519, "s": 1512, "text": "Safari" }, { "code": null, "e": 1525, "s": 1519, "text": "Opera" }, { "code": null, "e": 1539, "s": 1525, "text": "ManasChhabra2" }, { "code": null, "e": 1555, "s": 1539, "text": "HTML-Attributes" }, { "code": null, "e": 1560, "s": 1555, "text": "HTML" }, { "code": null, "e": 1577, "s": 1560, "text": "Web Technologies" }, { "code": null, "e": 1582, "s": 1577, "text": "HTML" } ]
Predicting Amazon review scores using Hierarchical Attention Networks with PyTorch and Apache Mxnet | by Javier Rodriguez Zaurin | Towards Data Science
This post and the code here are part of a larger repo that I have (very creatively) called β€œNLP-stuff”. As the name indicates, I include in that repo projects that I do and/or ideas that I have β€” as long as there is code associated with those ideas β€” that are related to NLP. In every directory, I have included a README file and a series of explanatory notebooks that I hope help explaining the code. I intend to keep adding projects throughout 2020, not necessarily the latest and/or most popular releases, but simply papers or algorithms I find interesting and useful. In particular, the code related to this post is in the directory amazon_reviews_classification_HAN. First things first, let’s start by acknowledging the relevant people that did the hard work. This post and the companion repo are based on the paper β€œHierarchical Attention Networks for Document Classification” (Zichao Yang, et al, 2016). In addition, I have also used in my implementation the results, and code, presented in β€œRegularizing and Optimizing LSTM Language Models” (Stephen Merity, Nitish Shirish Keskar and Richard Socher, 2017). The dataset that I have used for this and other experiments in the repo is the Amazon product data (J. McAuley et al., 2015 and R. He, J. McAuley 2016), in particular the Clothing, Shoes and Jewellery dataset. I strongly recommend having a look at these papers and references therein. Once that is done let’s start by describing the network architecture we will be implementing here. The following figure is Figure 2 in the Zichao Yang et al, paper. We consider a document comprised of L sentences si and each sentence contains Ti words. w_it with t ∈ [1, T], represents the words in the i-th sentence. As shown in the figure, the authors used a word encoder (a bidirectional GRU, Bahdanau et al., 2014), along with a word attention mechanism to encode each sentence into a vector representation. These sentence representations are passed through a sentence encoder with a sentence attention mechanism resulting in a document vector representation. This final representation is passed to a fully connected layer with the corresponding activation function for prediction. The word β€œhierarchical” refers here to the process of encoding first sentences from words, and then documents from sentences, naturally following the β€œsemantic hierarchy” in a document. 1.1 The Attention Mechanism Assuming one is familiar with the GRU formulation (if not have a look here), all the math one needs to understand the attention mechanism is included below. The mathematical expressions I include here refer to the word attention mechanism. The sentence attention mechanism is identical, but at sentence level. Therefore, I believe explaining the following expressions, along with the code snippets below, will be enough to understand the full process. The first 3 expression are pretty standard: Where x_it is the word embedding vector of word t in sentence i. The vectors h_it are the forward and backward output features from the bidirectional GRU, which are concatenated before applying attention. The attention mechanism is formulated as follows: First, the h_it features go through a one-layer MLP with a hyperbolic tangent function. This results in a hidden representation of h_it, u_it. Then, the importance of each word is measured as the dot product between u_it and a context vector u_w, obtaining a so-called normalised importance weight Ξ±_it. After that, the sentence vector si is computed as the weighted sum of the h_it features based on the normalised importance weights. For more details, please, read the paper, section 2.2 β€œHierarchical Attention”. As mentioned earlier, the sentence attention mechanism is identical but at sentence level. Word and sentence attention can be coded as: Pytorch: Mxnet: where inp refers to h_it and h_i for word and sentence attention respectively. As one can see, the Mxnet implementation is nearly identical to that in Pytorch, albeit with some subtle differences. This is going to be the case throughout the whole HAN implementation. However, I would like to add a few lines to clarify the following: this is my second β€œserious” dive into Mxnet and Gluon. The more I use it, the more I like it, but I am pretty sure that I could have written a better, more efficient code. With that in mind, if you, the reader, are a Mxnet user and have suggestions and comments, I would love to hear them. 1.1.1 Word Encoder + Word Attention Once we have the AttentionWithContext class, coding WordAttnNet (Word Encoder + Word Attention) is straightforward. The snippet below is a simplified version of that in the repo, but contains the main components. For the full version, please have a look at the code in the repo. Pytorch Mxnet You will notice the presence of 3 dropout related parameters: embed_drop , weight_drop and locked_drop . I will describe them in detail in Section 2. For the time being, let’s ignore them and focus on the remaining components of the module. Simply, the input tokens ( X ) go through the embeddings lookup table ( word_embed). The resulting token embeddings go through the bidirectional GRU ( rnn) and the output of the GRU goes to AttentionWithContext ( word_attn ) which will return the importance weights (Ξ±), the sentence representation (s) and the hidden state h_n. Note that returning the hidden state is necessary since the document (the amazon review here) is comprised of a series of sentences. Therefore, the initial hidden state of sentence i+1 will be the last hidden state of sentence i. We could say that we will treat the documents themselves as β€œstateful”. I will come back to this later in the post. 1.1.2 Sentence Encoder + Sentence Attention Given the fact that we do not need an embedding lookup table for the sentence encoder, SentAttnNet (Sentence Encoder + Sentence Attention) is simply: Pytorch Mxnet Here, the network will receive the output of WordAttnNet ( X ), which will then go through the bidirectional GRU ( rnn ) and then through AttentionWithContext ( sent_attn ). At this point, we have all the building blocks to code the HAN. 1.1.3 Hierarchical Attention Networks (HANs) Pytorch Mxnet I believe it might be useful here to illustrate the flow of the data through the network with some numbers related to the dimensions of tensors as they navigate the network. Let’s assume we use batch sizes ( bsz ) of 32, token embedding of dim ( embed_dim ) 100 and GRUs with hidden size ( hidden_dim ) 64. The input to HierAttnNet in the snippet before X is a tensor of dim (bzs, maxlen_doc, maxlen_sent) where maxlen_doc and maxlen_sent are the maximum number of sentences per document and words per sentence. Let’s assume that these numbers are 5 and 20. Therefore, X is here a tensor of dim (32, 5, 20) . The first thing we do is to permute the axes, resulting in a tensor of dim (5, 32, 20) . This is because we are going to process one sentence at a time feeding the last hidden state of one sentence as the initial hidden state of the next sentence, in a β€œstateful” manner. This will happen within the loop in the forward pass. In that loop, we are going to process one sentence at a time, i.e. a tensor of dim (32, 20) containing the i-th sentence for all 32 reviews in the batch. This tensor is then passed to wordattnnet , which is simply Word Encoder + Word Attention as described before. There, it will first go through the embeddings layer, resulting in a tensor of dim (32, 20, 100) . Then through the bidirectional GRU, resulting in a tensor of dim (32, 20, 128) and finally through the attention mechanism, resulting in a tensor of dim (32, 1, 128) . This last tensor is si in equation 7 in the Zichao Yang, et al paper, and corresponds to the i-th sentence vector representation. After running the loop we will have maxlen_doc (i.e. 5) tensors of dim (32, 1, 128) that will be concatenated along the 2nd dimension, resulting in a tensor of dim (32, 5, 128) β†’ (bsz, maxlen_doc, hidden_dim*2). This tensor is then passed through sentattnnet , which is simply Sentence Encoder + Sentence Attention as described before. There it will first go through the bidirectional GRU, resulting in a tensor of dim (32, 5, 128) and finally through the attention mechanism resulting in a tensor of dim (32, 128) . This last tensor will be the v in the equation 10 in their paper. Finally, v is then passed through a fully connected layer and a Softmax function for prediction. When I started to run experiments I noticed that the model overfitted quite early during training. The best validation loss and accuracy happened within the first couple of epochs, or even after the first epoch. When overfitting occurs there are a number of options: Reduce model complexity: I explore this by running a number of models with a small number of embeddings and/or hidden sizes. Early Stopping: this is always used via an early_stop function. Additional regularisation, such as dropout, label smoothing (Christian Szegedy et al, 2015) or data augmentation. I write β€œadditional” because I already used weight decay. I have not explored label smoothing or data augmentation in this exercise. If you want to dig a bit more into how to implement label smoothing in Pytorch, have a look at this repo. In the case of Mxnet, the gluonnlp API has its own LabelSmoothing class. Regarding data augmentation, the truth is that I have not tried it here and perhaps I should. Not only because it normally leads to notable improvements in terms of model generalisation, but moreover because I already have most of the code from another experiment where I implemented EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks (Jason Wei and Kai Zou 2019). Nonetheless, one has to stop somewhere and I decided to focus on exploring different dropout mechanisms. The 3 different forms of dropout I used here are: embedding dropout, locked dropout and weight dropout. The code that I used is taken directly from the salesforce repo corresponding to the implementation of the AWD-LTSM (Merity, hirish Keskar and Socher, 2017). In this section, I will focus on discussing the Pytorch implementation, but I will also include information regarding Mxnet’s implementation. Note that these dropout mechanisms were initially thought and implemented in the context of language models. However, there is no reason why they should not work here (or at least no reason why we should not try them). 2.1 Embedding Dropout This is discussed in detail in Section 4.3. in the Merity et al paper and is based in the work of Gal & Ghahramani (2016). No one better than the authors themselves to explain it. In their own words: β€œThis is equivalent to performing dropout on the embedding matrix at a word level, where the dropout is broadcast across all the word vector’s embedding. [...]” In code (the code below is a simplified version of that in the original repo): Basically, we create a mask of 0s and 1s along the 1st dimension of the embeddings tensor (the β€œword” dimension) and then we expand that mask along the second dimension (the β€œembedding” dimension), scaling the remaining weights accordingly. As the authors said, we drop words. 2.2 Locked Dropout This is also based on the work of Gal & Ghahramani (2016). Again in the words of the authors: β€œ[...] sample a binary dropout mask only once upon the first call and then to repeatedly use that locked dropout mask for all repeated connections within the forward and backward pass”. In code: Simply,LockedDropoutwill receive a 3-dim tensor, it will then generate a mask along the second dimension and expand that mask along the first dimension. For example, when applied to a tensor like (batch_size, seq_length, embed_dim), it will create a mask of dim (1, seq_length, embed_dim) and apply it to the whole batch. Mxnet’s nn.Dropout module has an axes parameter that directly implements this type of dropout. And finally... 2.3. Weight Dropout This is discussed in Section 2 in their paper. Once again, in their own words: β€œWe propose the use of DropConnect (Wan et al., 2013) on the recurrent hidden to hidden weight matrices which do not require any modifications to an RNN’s formulation.” In code (the code below is a simplified version of that in the original repo): WeightDrop will first copy and register the hidden-to-hidden weights (or in general terms the weights in the List weights) with a suffix _raw (line 14). Then, it will apply dropout and assign the weights again to the module (line 25 if variationalor 27 otherwise). As shown in the snippet, the variational option does the same as discussed before in the case of Embedding Dropout, i.e. generates a mask along the first dimension of the tensor and expands (or broadcasts) along the second dimension. There are a couple of drawbacks to this implementation. In the first place, given some input weights, the final model will contain the original weights (referred as weight_name_raw ) and those with dropout (refer as weight_name ), which is not very efficient. Secondly, it changes the name of the parameters, adding β€˜ module’ to the original name. To be honest, these are not major drawbacks at all, but I can use them as an excuse to introduce another two implementations that are perhaps a bit better (although of course based on the original one). One is the implementation within the great text API at the fastai library. I guess at this point everyone knows about this library, but if you don’t let me write a couple of lines here. I find this library excellent, not only for the high level APIs that it offers, or the clever defaults, but also because there are a lot of little gems hidden in the source code. If you are not familiar with the library, give it a go, there is no turning back. Another nice implementation is the function apply_weight_drop at the Mxnet’s gluonnlp API, which I used here. In fact, in their implementation of the AWDRNN language model this function is used for both the embedding and the hidden-to-hidden weight dropout. It is available through their utils module: from gluonnlp.model.utils import apply_weight_drop As far as implementation goes, this is it. Time to run some experiments. 3.1. Results I eventually recorded 59 experiments (I ran a few more), 40 of them using the Pytorch implementation and 19 using Mxnet. Throughout the experiments I used different batch sizes, learning rates, embedding dimensions, GRU hidden sizes, dropout rates, learning rate schedulers, optimisers, etc. They are all shown in Tables 1 and 2 in the notebook 04_Review_Score_Prediction_Results.ipynb. The best results on the test dataset for each implementation are shown in the table below, along with the best result I obtained from previous attempts using tf-idf along with LightGBM and Hyperopt for the classification and hyper-parameter optimisation tasks. In the first place, it is worth reiterating that I only run 19 experiments with the Mxnet implementation. This is in part due to the fact that, as I mentioned earlier in the post, I have more experience with Pytorch than with Mxnet and Gluon, which influenced the corresponding experimentation. Therefore, it is quite possible that I missed a minor tweak to the Mxnet models that would have lead to better results than those in the table. Other than that we can see that the HAN-Pytorch model performs better than a thoroughly tuned tf-idf+LighGBM model on the test dataset for all, accuracy, F1 score and precision. Therefore, the next immediate question most will be asking is: is it worth using HAN over tf-idf+LightGBM (or your favourite classifier)? And the answer is, as with most things in life, β€œit depends”. It is true that HANs perform better, but the increase is relatively small. In general, leaving aside the particular case of the Amazon reviews, if in your business a ~3% F1 score is important (i.e. leads to a sizeable increase in revenue, savings or some other benefits) then there is no question, one would use the DL approach. On top of that, attention mechanisms might give you some additional, useful information (such as the expressions within the text that lead to a certain classification) beyond just the keywords that one would obtain by using approaches such as tf-idf (or topic modelling). Finally, my implementation of HANs is inefficient (see next section). Even in that scenario, the results presented in the table are always obtained in less than 10 epochs and each epoch runs in around 3min (or less depending on the batch sizes) on a Tesla K80. Therefore, this is certainly not a computationally expensive algorithm to train and performs well. In summary, I’d say that HANs are a good algorithm to have in your repertoire when it comes to perform text classification. 3.2 Visualising Attention Let’s now have a look at the attention weights, in particular to the word and sentence importance weights (Ξ±). Figure 2 shows both word and sentence attention weights for two reviews that were classified correctly. The xxmaj token is a special token introduced by the fastai tokenizer to indicate that the next token starts with a capital letter. In addition, it is worth mentioning that in the original dataset review scores range from 1–5 stars. During preprocessing, I merge reviews with 1 and 2 starts into one class and re-label the classes to start from 0 (see here for details). Therefore, the final number of classes is 4: {0, 1, 2, 3}. The figure shows how, when predicting the review score, the HAN places attention to phrases and constructions like β€œfit was perfect”, β€œvery superior” or β€œrubs [...] wrong places”, as well as isolated words like β€œbought” or β€œnot”. In addition, we can see that in the top plot, a bit more attention is placed in the 3rd sentence relative to the other 3. Figure 3 shows both word and sentence attention weights for two reviews that were misclassified. The top review was predicted as 0 while the true score was 3 (real score in the original dataset is 5). Someone found those boots β€œyuck”, β€œdisappointing” and β€œbad” yet gave them a 5 star score. The review at the bottom was predicted as 3 while the true score was 0 (real score in the original dataset is 1). It is easy to understand why the HAN misclassified this review mostly based on the first sentence, where it places the highest attention. Nonetheless, the figures show that the attention mechanism works well, capturing the relevant pieces in the reviews that lead to a certain classification. Notebook 05_Visualizing_Attention.ipynb contains the code that I used to generate these plots. At this stage, there are a few comments worth making. First of all, I ran all the experiments manually (with a bash file), which is not the best way of optimising the hyper-parameters of the model. Ideally, one would like to wrap up the train and validation processes in an objective function and use Hyperopt, as I did with all the other experiments in the repo that focus on text classification. I will include a .py script to do that in the near future. On the other hand, looking at figures 2 and 3 one can see that attention is normally focused on isolated words or constructions and phrases or 2 or 3 words. Therefore, one might think that using a non-DL approach along with n-grams might improve the results in the table. I actually did that in this notebook and the difference between using or not using n-grams (in particular bigrams via gensim.models.phrases ) is negligible. Other issues worth discussing are related to model generalisation and efficiency. For example, I already mentioned that one could use label smoothing and data augmentation to add regularisation. In fact, even after adding some dropout, the best validation loss and metrics are still obtained early during training, moreover in the case of the Mxnet implementation. This is not necessarily bad and might simply reflect the fact that the model reaches its best performance just after a few epochs. However, more exploration is required. In addition, if you have a look at the details of my implementation, you will realise that the input tensors have a lot of unnecessary padding. Nothing will be learned from this padding but still has to be processed, i.e. this is inefficient for the GPU. To remedy this situation, one could group reviews of similar lengths into buckets and pad accordingly, reducing the computation required to process the documents. Furthermore, one could adjust both learning rate and batch size according to the document length. All these approaches have already been used to build language models (e.g see this presentation) and are readily available at the gluonnlp API. At this point, I have only scratched the surface of what this API can do and I am looking forward to more experimentation in the near future. I have implemented β€œHierarchical Attention Networks for Document Classification” (Zichao Yang, et al, 2016) using Pytorch and Mxnet to predict Amazon reviews scores, and compared the results with those of previous implementations that did not involve Deep Learning. HANs perform better across all the evaluation metrics, are relatively easy to implement and fast to train. Therefore, I believe this is an algorithm worth having in the repertoire for text classification tasks. Other than that, and as always, I hope you found this post useful. Any comments, suggestions, please email me at: jrzaurin@gmail.com or even better open an issue in the repo. References Dzmitry Bahdanau, KyungHyun Cho, Yoshua Bengio 2016. neural machine translation by jointly learning to align and translate. https://arxiv.org/abs/1409.0473 Yarin Gal, Zoubin Ghahramani 2015. A Theoretically Grounded Application of Dropout in Recurrent Neural Networks. https://arxiv.org/abs/1512.05287. Ruining He, Julian McAuley 2016. Ups and Downs: Modeling the Visual Evolution of Fashion Trends with One-Class Collaborative Filtering. https://arxiv.org/abs/1602.01585 Julian McAuley , Christopher Targett , Qinfeng (β€˜Javen’) Shi , and Anton van den Hengel 2015. Image-based Recommendations on Styles and Substitutes. https://arxiv.org/abs/1506.04757 Stephen Merity, Nitish Shirish Keskar, Richard Socher 2017. Regularizing and Optimizing LSTM Language Models. https://arxiv.org/abs/1708.02182 Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna 2015. Rethinking the Inception Architecture for Computer Vision. https://arxiv.org/abs/1512.00567 Li Wan, Matthew Zeiler, Sixin Zhang, Yann LeCun, Rob Fergus 2013. Regularization of Neural Networks using DropConnect. http://proceedings.mlr.press/v28/wan13.html Jason Wei, Kai Zou 2019. EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks. https://arxiv.org/abs/1901.11196 Zichao Yang , Diyi Yang , Chris Dyer , Xiaodong He , Alex Smola , Eduard Hovy 2016. Hierarchical Attention Networks for Document Classification. https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf
[ { "code": null, "e": 843, "s": 171, "text": "This post and the code here are part of a larger repo that I have (very creatively) called β€œNLP-stuff”. As the name indicates, I include in that repo projects that I do and/or ideas that I have β€” as long as there is code associated with those ideas β€” that are related to NLP. In every directory, I have included a README file and a series of explanatory notebooks that I hope help explaining the code. I intend to keep adding projects throughout 2020, not necessarily the latest and/or most popular releases, but simply papers or algorithms I find interesting and useful. In particular, the code related to this post is in the directory amazon_reviews_classification_HAN." }, { "code": null, "e": 1571, "s": 843, "text": "First things first, let’s start by acknowledging the relevant people that did the hard work. This post and the companion repo are based on the paper β€œHierarchical Attention Networks for Document Classification” (Zichao Yang, et al, 2016). In addition, I have also used in my implementation the results, and code, presented in β€œRegularizing and Optimizing LSTM Language Models” (Stephen Merity, Nitish Shirish Keskar and Richard Socher, 2017). The dataset that I have used for this and other experiments in the repo is the Amazon product data (J. McAuley et al., 2015 and R. He, J. McAuley 2016), in particular the Clothing, Shoes and Jewellery dataset. I strongly recommend having a look at these papers and references therein." }, { "code": null, "e": 1736, "s": 1571, "text": "Once that is done let’s start by describing the network architecture we will be implementing here. The following figure is Figure 2 in the Zichao Yang et al, paper." }, { "code": null, "e": 2543, "s": 1736, "text": "We consider a document comprised of L sentences si and each sentence contains Ti words. w_it with t ∈ [1, T], represents the words in the i-th sentence. As shown in the figure, the authors used a word encoder (a bidirectional GRU, Bahdanau et al., 2014), along with a word attention mechanism to encode each sentence into a vector representation. These sentence representations are passed through a sentence encoder with a sentence attention mechanism resulting in a document vector representation. This final representation is passed to a fully connected layer with the corresponding activation function for prediction. The word β€œhierarchical” refers here to the process of encoding first sentences from words, and then documents from sentences, naturally following the β€œsemantic hierarchy” in a document." }, { "code": null, "e": 2571, "s": 2543, "text": "1.1 The Attention Mechanism" }, { "code": null, "e": 3067, "s": 2571, "text": "Assuming one is familiar with the GRU formulation (if not have a look here), all the math one needs to understand the attention mechanism is included below. The mathematical expressions I include here refer to the word attention mechanism. The sentence attention mechanism is identical, but at sentence level. Therefore, I believe explaining the following expressions, along with the code snippets below, will be enough to understand the full process. The first 3 expression are pretty standard:" }, { "code": null, "e": 3322, "s": 3067, "text": "Where x_it is the word embedding vector of word t in sentence i. The vectors h_it are the forward and backward output features from the bidirectional GRU, which are concatenated before applying attention. The attention mechanism is formulated as follows:" }, { "code": null, "e": 3929, "s": 3322, "text": "First, the h_it features go through a one-layer MLP with a hyperbolic tangent function. This results in a hidden representation of h_it, u_it. Then, the importance of each word is measured as the dot product between u_it and a context vector u_w, obtaining a so-called normalised importance weight Ξ±_it. After that, the sentence vector si is computed as the weighted sum of the h_it features based on the normalised importance weights. For more details, please, read the paper, section 2.2 β€œHierarchical Attention”. As mentioned earlier, the sentence attention mechanism is identical but at sentence level." }, { "code": null, "e": 3974, "s": 3929, "text": "Word and sentence attention can be coded as:" }, { "code": null, "e": 3983, "s": 3974, "text": "Pytorch:" }, { "code": null, "e": 3990, "s": 3983, "text": "Mxnet:" }, { "code": null, "e": 4069, "s": 3990, "text": "where inp refers to h_it and h_i for word and sentence attention respectively." }, { "code": null, "e": 4614, "s": 4069, "text": "As one can see, the Mxnet implementation is nearly identical to that in Pytorch, albeit with some subtle differences. This is going to be the case throughout the whole HAN implementation. However, I would like to add a few lines to clarify the following: this is my second β€œserious” dive into Mxnet and Gluon. The more I use it, the more I like it, but I am pretty sure that I could have written a better, more efficient code. With that in mind, if you, the reader, are a Mxnet user and have suggestions and comments, I would love to hear them." }, { "code": null, "e": 4650, "s": 4614, "text": "1.1.1 Word Encoder + Word Attention" }, { "code": null, "e": 4929, "s": 4650, "text": "Once we have the AttentionWithContext class, coding WordAttnNet (Word Encoder + Word Attention) is straightforward. The snippet below is a simplified version of that in the repo, but contains the main components. For the full version, please have a look at the code in the repo." }, { "code": null, "e": 4937, "s": 4929, "text": "Pytorch" }, { "code": null, "e": 4943, "s": 4937, "text": "Mxnet" }, { "code": null, "e": 5184, "s": 4943, "text": "You will notice the presence of 3 dropout related parameters: embed_drop , weight_drop and locked_drop . I will describe them in detail in Section 2. For the time being, let’s ignore them and focus on the remaining components of the module." }, { "code": null, "e": 5513, "s": 5184, "text": "Simply, the input tokens ( X ) go through the embeddings lookup table ( word_embed). The resulting token embeddings go through the bidirectional GRU ( rnn) and the output of the GRU goes to AttentionWithContext ( word_attn ) which will return the importance weights (Ξ±), the sentence representation (s) and the hidden state h_n." }, { "code": null, "e": 5859, "s": 5513, "text": "Note that returning the hidden state is necessary since the document (the amazon review here) is comprised of a series of sentences. Therefore, the initial hidden state of sentence i+1 will be the last hidden state of sentence i. We could say that we will treat the documents themselves as β€œstateful”. I will come back to this later in the post." }, { "code": null, "e": 5903, "s": 5859, "text": "1.1.2 Sentence Encoder + Sentence Attention" }, { "code": null, "e": 6053, "s": 5903, "text": "Given the fact that we do not need an embedding lookup table for the sentence encoder, SentAttnNet (Sentence Encoder + Sentence Attention) is simply:" }, { "code": null, "e": 6061, "s": 6053, "text": "Pytorch" }, { "code": null, "e": 6067, "s": 6061, "text": "Mxnet" }, { "code": null, "e": 6241, "s": 6067, "text": "Here, the network will receive the output of WordAttnNet ( X ), which will then go through the bidirectional GRU ( rnn ) and then through AttentionWithContext ( sent_attn )." }, { "code": null, "e": 6305, "s": 6241, "text": "At this point, we have all the building blocks to code the HAN." }, { "code": null, "e": 6350, "s": 6305, "text": "1.1.3 Hierarchical Attention Networks (HANs)" }, { "code": null, "e": 6358, "s": 6350, "text": "Pytorch" }, { "code": null, "e": 6364, "s": 6358, "text": "Mxnet" }, { "code": null, "e": 6671, "s": 6364, "text": "I believe it might be useful here to illustrate the flow of the data through the network with some numbers related to the dimensions of tensors as they navigate the network. Let’s assume we use batch sizes ( bsz ) of 32, token embedding of dim ( embed_dim ) 100 and GRUs with hidden size ( hidden_dim ) 64." }, { "code": null, "e": 6973, "s": 6671, "text": "The input to HierAttnNet in the snippet before X is a tensor of dim (bzs, maxlen_doc, maxlen_sent) where maxlen_doc and maxlen_sent are the maximum number of sentences per document and words per sentence. Let’s assume that these numbers are 5 and 20. Therefore, X is here a tensor of dim (32, 5, 20) ." }, { "code": null, "e": 7299, "s": 6973, "text": "The first thing we do is to permute the axes, resulting in a tensor of dim (5, 32, 20) . This is because we are going to process one sentence at a time feeding the last hidden state of one sentence as the initial hidden state of the next sentence, in a β€œstateful” manner. This will happen within the loop in the forward pass." }, { "code": null, "e": 7961, "s": 7299, "text": "In that loop, we are going to process one sentence at a time, i.e. a tensor of dim (32, 20) containing the i-th sentence for all 32 reviews in the batch. This tensor is then passed to wordattnnet , which is simply Word Encoder + Word Attention as described before. There, it will first go through the embeddings layer, resulting in a tensor of dim (32, 20, 100) . Then through the bidirectional GRU, resulting in a tensor of dim (32, 20, 128) and finally through the attention mechanism, resulting in a tensor of dim (32, 1, 128) . This last tensor is si in equation 7 in the Zichao Yang, et al paper, and corresponds to the i-th sentence vector representation." }, { "code": null, "e": 8544, "s": 7961, "text": "After running the loop we will have maxlen_doc (i.e. 5) tensors of dim (32, 1, 128) that will be concatenated along the 2nd dimension, resulting in a tensor of dim (32, 5, 128) β†’ (bsz, maxlen_doc, hidden_dim*2). This tensor is then passed through sentattnnet , which is simply Sentence Encoder + Sentence Attention as described before. There it will first go through the bidirectional GRU, resulting in a tensor of dim (32, 5, 128) and finally through the attention mechanism resulting in a tensor of dim (32, 128) . This last tensor will be the v in the equation 10 in their paper." }, { "code": null, "e": 8641, "s": 8544, "text": "Finally, v is then passed through a fully connected layer and a Softmax function for prediction." }, { "code": null, "e": 8908, "s": 8641, "text": "When I started to run experiments I noticed that the model overfitted quite early during training. The best validation loss and accuracy happened within the first couple of epochs, or even after the first epoch. When overfitting occurs there are a number of options:" }, { "code": null, "e": 9033, "s": 8908, "text": "Reduce model complexity: I explore this by running a number of models with a small number of embeddings and/or hidden sizes." }, { "code": null, "e": 9097, "s": 9033, "text": "Early Stopping: this is always used via an early_stop function." }, { "code": null, "e": 9269, "s": 9097, "text": "Additional regularisation, such as dropout, label smoothing (Christian Szegedy et al, 2015) or data augmentation. I write β€œadditional” because I already used weight decay." }, { "code": null, "e": 9523, "s": 9269, "text": "I have not explored label smoothing or data augmentation in this exercise. If you want to dig a bit more into how to implement label smoothing in Pytorch, have a look at this repo. In the case of Mxnet, the gluonnlp API has its own LabelSmoothing class." }, { "code": null, "e": 10035, "s": 9523, "text": "Regarding data augmentation, the truth is that I have not tried it here and perhaps I should. Not only because it normally leads to notable improvements in terms of model generalisation, but moreover because I already have most of the code from another experiment where I implemented EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks (Jason Wei and Kai Zou 2019). Nonetheless, one has to stop somewhere and I decided to focus on exploring different dropout mechanisms." }, { "code": null, "e": 10658, "s": 10035, "text": "The 3 different forms of dropout I used here are: embedding dropout, locked dropout and weight dropout. The code that I used is taken directly from the salesforce repo corresponding to the implementation of the AWD-LTSM (Merity, hirish Keskar and Socher, 2017). In this section, I will focus on discussing the Pytorch implementation, but I will also include information regarding Mxnet’s implementation. Note that these dropout mechanisms were initially thought and implemented in the context of language models. However, there is no reason why they should not work here (or at least no reason why we should not try them)." }, { "code": null, "e": 10680, "s": 10658, "text": "2.1 Embedding Dropout" }, { "code": null, "e": 11041, "s": 10680, "text": "This is discussed in detail in Section 4.3. in the Merity et al paper and is based in the work of Gal & Ghahramani (2016). No one better than the authors themselves to explain it. In their own words: β€œThis is equivalent to performing dropout on the embedding matrix at a word level, where the dropout is broadcast across all the word vector’s embedding. [...]”" }, { "code": null, "e": 11120, "s": 11041, "text": "In code (the code below is a simplified version of that in the original repo):" }, { "code": null, "e": 11397, "s": 11120, "text": "Basically, we create a mask of 0s and 1s along the 1st dimension of the embeddings tensor (the β€œword” dimension) and then we expand that mask along the second dimension (the β€œembedding” dimension), scaling the remaining weights accordingly. As the authors said, we drop words." }, { "code": null, "e": 11416, "s": 11397, "text": "2.2 Locked Dropout" }, { "code": null, "e": 11696, "s": 11416, "text": "This is also based on the work of Gal & Ghahramani (2016). Again in the words of the authors: β€œ[...] sample a binary dropout mask only once upon the first call and then to repeatedly use that locked dropout mask for all repeated connections within the forward and backward pass”." }, { "code": null, "e": 11705, "s": 11696, "text": "In code:" }, { "code": null, "e": 12122, "s": 11705, "text": "Simply,LockedDropoutwill receive a 3-dim tensor, it will then generate a mask along the second dimension and expand that mask along the first dimension. For example, when applied to a tensor like (batch_size, seq_length, embed_dim), it will create a mask of dim (1, seq_length, embed_dim) and apply it to the whole batch. Mxnet’s nn.Dropout module has an axes parameter that directly implements this type of dropout." }, { "code": null, "e": 12137, "s": 12122, "text": "And finally..." }, { "code": null, "e": 12157, "s": 12137, "text": "2.3. Weight Dropout" }, { "code": null, "e": 12405, "s": 12157, "text": "This is discussed in Section 2 in their paper. Once again, in their own words: β€œWe propose the use of DropConnect (Wan et al., 2013) on the recurrent hidden to hidden weight matrices which do not require any modifications to an RNN’s formulation.”" }, { "code": null, "e": 12484, "s": 12405, "text": "In code (the code below is a simplified version of that in the original repo):" }, { "code": null, "e": 12983, "s": 12484, "text": "WeightDrop will first copy and register the hidden-to-hidden weights (or in general terms the weights in the List weights) with a suffix _raw (line 14). Then, it will apply dropout and assign the weights again to the module (line 25 if variationalor 27 otherwise). As shown in the snippet, the variational option does the same as discussed before in the case of Embedding Dropout, i.e. generates a mask along the first dimension of the tensor and expands (or broadcasts) along the second dimension." }, { "code": null, "e": 13331, "s": 12983, "text": "There are a couple of drawbacks to this implementation. In the first place, given some input weights, the final model will contain the original weights (referred as weight_name_raw ) and those with dropout (refer as weight_name ), which is not very efficient. Secondly, it changes the name of the parameters, adding β€˜ module’ to the original name." }, { "code": null, "e": 13981, "s": 13331, "text": "To be honest, these are not major drawbacks at all, but I can use them as an excuse to introduce another two implementations that are perhaps a bit better (although of course based on the original one). One is the implementation within the great text API at the fastai library. I guess at this point everyone knows about this library, but if you don’t let me write a couple of lines here. I find this library excellent, not only for the high level APIs that it offers, or the clever defaults, but also because there are a lot of little gems hidden in the source code. If you are not familiar with the library, give it a go, there is no turning back." }, { "code": null, "e": 14283, "s": 13981, "text": "Another nice implementation is the function apply_weight_drop at the Mxnet’s gluonnlp API, which I used here. In fact, in their implementation of the AWDRNN language model this function is used for both the embedding and the hidden-to-hidden weight dropout. It is available through their utils module:" }, { "code": null, "e": 14334, "s": 14283, "text": "from gluonnlp.model.utils import apply_weight_drop" }, { "code": null, "e": 14407, "s": 14334, "text": "As far as implementation goes, this is it. Time to run some experiments." }, { "code": null, "e": 14420, "s": 14407, "text": "3.1. Results" }, { "code": null, "e": 15068, "s": 14420, "text": "I eventually recorded 59 experiments (I ran a few more), 40 of them using the Pytorch implementation and 19 using Mxnet. Throughout the experiments I used different batch sizes, learning rates, embedding dimensions, GRU hidden sizes, dropout rates, learning rate schedulers, optimisers, etc. They are all shown in Tables 1 and 2 in the notebook 04_Review_Score_Prediction_Results.ipynb. The best results on the test dataset for each implementation are shown in the table below, along with the best result I obtained from previous attempts using tf-idf along with LightGBM and Hyperopt for the classification and hyper-parameter optimisation tasks." }, { "code": null, "e": 15507, "s": 15068, "text": "In the first place, it is worth reiterating that I only run 19 experiments with the Mxnet implementation. This is in part due to the fact that, as I mentioned earlier in the post, I have more experience with Pytorch than with Mxnet and Gluon, which influenced the corresponding experimentation. Therefore, it is quite possible that I missed a minor tweak to the Mxnet models that would have lead to better results than those in the table." }, { "code": null, "e": 15885, "s": 15507, "text": "Other than that we can see that the HAN-Pytorch model performs better than a thoroughly tuned tf-idf+LighGBM model on the test dataset for all, accuracy, F1 score and precision. Therefore, the next immediate question most will be asking is: is it worth using HAN over tf-idf+LightGBM (or your favourite classifier)? And the answer is, as with most things in life, β€œit depends”." }, { "code": null, "e": 16486, "s": 15885, "text": "It is true that HANs perform better, but the increase is relatively small. In general, leaving aside the particular case of the Amazon reviews, if in your business a ~3% F1 score is important (i.e. leads to a sizeable increase in revenue, savings or some other benefits) then there is no question, one would use the DL approach. On top of that, attention mechanisms might give you some additional, useful information (such as the expressions within the text that lead to a certain classification) beyond just the keywords that one would obtain by using approaches such as tf-idf (or topic modelling)." }, { "code": null, "e": 16970, "s": 16486, "text": "Finally, my implementation of HANs is inefficient (see next section). Even in that scenario, the results presented in the table are always obtained in less than 10 epochs and each epoch runs in around 3min (or less depending on the batch sizes) on a Tesla K80. Therefore, this is certainly not a computationally expensive algorithm to train and performs well. In summary, I’d say that HANs are a good algorithm to have in your repertoire when it comes to perform text classification." }, { "code": null, "e": 16996, "s": 16970, "text": "3.2 Visualising Attention" }, { "code": null, "e": 17107, "s": 16996, "text": "Let’s now have a look at the attention weights, in particular to the word and sentence importance weights (Ξ±)." }, { "code": null, "e": 17641, "s": 17107, "text": "Figure 2 shows both word and sentence attention weights for two reviews that were classified correctly. The xxmaj token is a special token introduced by the fastai tokenizer to indicate that the next token starts with a capital letter. In addition, it is worth mentioning that in the original dataset review scores range from 1–5 stars. During preprocessing, I merge reviews with 1 and 2 starts into one class and re-label the classes to start from 0 (see here for details). Therefore, the final number of classes is 4: {0, 1, 2, 3}." }, { "code": null, "e": 17993, "s": 17641, "text": "The figure shows how, when predicting the review score, the HAN places attention to phrases and constructions like β€œfit was perfect”, β€œvery superior” or β€œrubs [...] wrong places”, as well as isolated words like β€œbought” or β€œnot”. In addition, we can see that in the top plot, a bit more attention is placed in the 3rd sentence relative to the other 3." }, { "code": null, "e": 18536, "s": 17993, "text": "Figure 3 shows both word and sentence attention weights for two reviews that were misclassified. The top review was predicted as 0 while the true score was 3 (real score in the original dataset is 5). Someone found those boots β€œyuck”, β€œdisappointing” and β€œbad” yet gave them a 5 star score. The review at the bottom was predicted as 3 while the true score was 0 (real score in the original dataset is 1). It is easy to understand why the HAN misclassified this review mostly based on the first sentence, where it places the highest attention." }, { "code": null, "e": 18786, "s": 18536, "text": "Nonetheless, the figures show that the attention mechanism works well, capturing the relevant pieces in the reviews that lead to a certain classification. Notebook 05_Visualizing_Attention.ipynb contains the code that I used to generate these plots." }, { "code": null, "e": 19243, "s": 18786, "text": "At this stage, there are a few comments worth making. First of all, I ran all the experiments manually (with a bash file), which is not the best way of optimising the hyper-parameters of the model. Ideally, one would like to wrap up the train and validation processes in an objective function and use Hyperopt, as I did with all the other experiments in the repo that focus on text classification. I will include a .py script to do that in the near future." }, { "code": null, "e": 19672, "s": 19243, "text": "On the other hand, looking at figures 2 and 3 one can see that attention is normally focused on isolated words or constructions and phrases or 2 or 3 words. Therefore, one might think that using a non-DL approach along with n-grams might improve the results in the table. I actually did that in this notebook and the difference between using or not using n-grams (in particular bigrams via gensim.models.phrases ) is negligible." }, { "code": null, "e": 20207, "s": 19672, "text": "Other issues worth discussing are related to model generalisation and efficiency. For example, I already mentioned that one could use label smoothing and data augmentation to add regularisation. In fact, even after adding some dropout, the best validation loss and metrics are still obtained early during training, moreover in the case of the Mxnet implementation. This is not necessarily bad and might simply reflect the fact that the model reaches its best performance just after a few epochs. However, more exploration is required." }, { "code": null, "e": 21009, "s": 20207, "text": "In addition, if you have a look at the details of my implementation, you will realise that the input tensors have a lot of unnecessary padding. Nothing will be learned from this padding but still has to be processed, i.e. this is inefficient for the GPU. To remedy this situation, one could group reviews of similar lengths into buckets and pad accordingly, reducing the computation required to process the documents. Furthermore, one could adjust both learning rate and batch size according to the document length. All these approaches have already been used to build language models (e.g see this presentation) and are readily available at the gluonnlp API. At this point, I have only scratched the surface of what this API can do and I am looking forward to more experimentation in the near future." }, { "code": null, "e": 21486, "s": 21009, "text": "I have implemented β€œHierarchical Attention Networks for Document Classification” (Zichao Yang, et al, 2016) using Pytorch and Mxnet to predict Amazon reviews scores, and compared the results with those of previous implementations that did not involve Deep Learning. HANs perform better across all the evaluation metrics, are relatively easy to implement and fast to train. Therefore, I believe this is an algorithm worth having in the repertoire for text classification tasks." }, { "code": null, "e": 21553, "s": 21486, "text": "Other than that, and as always, I hope you found this post useful." }, { "code": null, "e": 21661, "s": 21553, "text": "Any comments, suggestions, please email me at: jrzaurin@gmail.com or even better open an issue in the repo." }, { "code": null, "e": 21672, "s": 21661, "text": "References" }, { "code": null, "e": 21828, "s": 21672, "text": "Dzmitry Bahdanau, KyungHyun Cho, Yoshua Bengio 2016. neural machine translation by jointly learning to align and translate. https://arxiv.org/abs/1409.0473" }, { "code": null, "e": 21975, "s": 21828, "text": "Yarin Gal, Zoubin Ghahramani 2015. A Theoretically Grounded Application of Dropout in Recurrent Neural Networks. https://arxiv.org/abs/1512.05287." }, { "code": null, "e": 22144, "s": 21975, "text": "Ruining He, Julian McAuley 2016. Ups and Downs: Modeling the Visual Evolution of Fashion Trends with One-Class Collaborative Filtering. https://arxiv.org/abs/1602.01585" }, { "code": null, "e": 22326, "s": 22144, "text": "Julian McAuley , Christopher Targett , Qinfeng (β€˜Javen’) Shi , and Anton van den Hengel 2015. Image-based Recommendations on Styles and Substitutes. https://arxiv.org/abs/1506.04757" }, { "code": null, "e": 22469, "s": 22326, "text": "Stephen Merity, Nitish Shirish Keskar, Richard Socher 2017. Regularizing and Optimizing LSTM Language Models. https://arxiv.org/abs/1708.02182" }, { "code": null, "e": 22651, "s": 22469, "text": "Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna 2015. Rethinking the Inception Architecture for Computer Vision. https://arxiv.org/abs/1512.00567" }, { "code": null, "e": 22814, "s": 22651, "text": "Li Wan, Matthew Zeiler, Sixin Zhang, Yann LeCun, Rob Fergus 2013. Regularization of Neural Networks using DropConnect. http://proceedings.mlr.press/v28/wan13.html" }, { "code": null, "e": 22966, "s": 22814, "text": "Jason Wei, Kai Zou 2019. EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks. https://arxiv.org/abs/1901.11196" } ]
Reading and Writing to text files in Python
Like other languages, Python provides some inbuilt functions for reading, writing, or accessing files. Python can handle mainly two types of files. The normal text file and the binary files. For the text files, each lines are terminated with a special character '\n' (It is known as EOL or End Of Line). For the Binary file, there is no line ending character. It saves the data after converting the content into bit stream. In this section we will discuss about the text files. r It is Read Only mode. It opens the text file for reading. When the file is not present, it raises I/O Error. r+ This mode for Reading and Writing. When the file is not present, it will raise I/O Error. w It is for write only jobs. When file is not present, it will create a file first, then start writing, when the file is present, it will remove the contents of that file, and start writing from beginning. w+ It is Write and Read mode. When file is not present, it can create the file, or when the file is present, the data will be overwritten. a This is append mode. So it writes data at the end of a file. a+ Append and Read mode. It can append data as well as read the data. Now see how a file can be written using writelines() and write() method. Live Demo #Create an empty file and write some lines line1 = 'This is first line. \n' lines = ['This is another line to store into file.\n', 'The Third Line for the file.\n', 'Another line... !@#$%^&*()_+.\n', 'End Line'] #open the file as write mode my_file = open('file_read_write.txt', 'w') my_file.write(line1) my_file.writelines(lines) #Write multiple lines my_file.close() print('Writing Complete') Writing Complete After writing the lines, we are appending some lines into the file. Live Demo #program to append some lines line1 = '\n\nThis is a new line. This line will be appended. \n' #open the file as append mode my_file = open('file_read_write.txt', 'a') my_file.write(line1) my_file.close() print('Appending Done') Appending Done At last, we will see how to read the file content from the read() and readline() method. We can provide some integer number 'n' to get first 'n' characters. #program to read from file #open the file as read mode my_file = open('file_read_write.txt', 'r') print('Show the full content:') print(my_file.read()) #Show first two lines my_file.seek(0) print('First two lines:') print(my_file.readline(), end = '') print(my_file.readline(), end = '') #Show upto 25 characters my_file.seek(0) print('\n\nFirst 25 characters:') print(my_file.read(25), end = '') my_file.close() Show the full content: This is first line. This is another line to store into file. The Third Line for the file. Another line... !@#$%^&*()_+. End Line This is a new line. This line will be appended. First two lines: This is first line. This is another line to store into file. First 25 characters: This is first line. This
[ { "code": null, "e": 1253, "s": 1062, "text": "Like other languages, Python provides some inbuilt functions for reading, writing, or accessing files. Python can handle mainly two types of files. The normal text file and the binary files." }, { "code": null, "e": 1487, "s": 1253, "text": " For the text files, each lines are terminated with a special character '\\n' (It is known as EOL or End Of Line). For the Binary file, there is no line ending character. It saves the data after converting the content into bit stream." }, { "code": null, "e": 1541, "s": 1487, "text": "In this section we will discuss about the text files." }, { "code": null, "e": 1543, "s": 1541, "text": "r" }, { "code": null, "e": 1652, "s": 1543, "text": "It is Read Only mode. It opens the text file for reading. When the file is not present, it raises I/O Error." }, { "code": null, "e": 1655, "s": 1652, "text": "r+" }, { "code": null, "e": 1745, "s": 1655, "text": "This mode for Reading and Writing. When the file is not present, it will raise I/O Error." }, { "code": null, "e": 1747, "s": 1745, "text": "w" }, { "code": null, "e": 1951, "s": 1747, "text": "It is for write only jobs. When file is not present, it will create a file first, then start writing, when the file is present, it will remove the contents of that file, and start writing from beginning." }, { "code": null, "e": 1954, "s": 1951, "text": "w+" }, { "code": null, "e": 2090, "s": 1954, "text": "It is Write and Read mode. When file is not present, it can create the file, or when the file is present, the data will be overwritten." }, { "code": null, "e": 2092, "s": 2090, "text": "a" }, { "code": null, "e": 2153, "s": 2092, "text": "This is append mode. So it writes data at the end of a file." }, { "code": null, "e": 2156, "s": 2153, "text": "a+" }, { "code": null, "e": 2223, "s": 2156, "text": "Append and Read mode. It can append data as well as read the data." }, { "code": null, "e": 2296, "s": 2223, "text": "Now see how a file can be written using writelines() and write() method." }, { "code": null, "e": 2307, "s": 2296, "text": " Live Demo" }, { "code": null, "e": 2711, "s": 2307, "text": "#Create an empty file and write some lines\nline1 = 'This is first line. \\n'\nlines = ['This is another line to store into file.\\n',\n 'The Third Line for the file.\\n',\n 'Another line... !@#$%^&*()_+.\\n',\n 'End Line']\n#open the file as write mode\nmy_file = open('file_read_write.txt', 'w')\nmy_file.write(line1)\nmy_file.writelines(lines) #Write multiple lines\nmy_file.close()\nprint('Writing Complete')" }, { "code": null, "e": 2729, "s": 2711, "text": "Writing Complete\n" }, { "code": null, "e": 2797, "s": 2729, "text": "After writing the lines, we are appending some lines into the file." }, { "code": null, "e": 2808, "s": 2797, "text": " Live Demo" }, { "code": null, "e": 3037, "s": 2808, "text": "#program to append some lines\nline1 = '\\n\\nThis is a new line. This line will be appended. \\n'\n#open the file as append mode\nmy_file = open('file_read_write.txt', 'a')\nmy_file.write(line1)\nmy_file.close()\nprint('Appending Done')" }, { "code": null, "e": 3053, "s": 3037, "text": "Appending Done\n" }, { "code": null, "e": 3210, "s": 3053, "text": "At last, we will see how to read the file content from the read() and readline() method. We can provide some integer number 'n' to get first 'n' characters." }, { "code": null, "e": 3623, "s": 3210, "text": "#program to read from file\n#open the file as read mode\nmy_file = open('file_read_write.txt', 'r')\nprint('Show the full content:')\nprint(my_file.read())\n#Show first two lines\nmy_file.seek(0)\nprint('First two lines:')\nprint(my_file.readline(), end = '')\nprint(my_file.readline(), end = '')\n#Show upto 25 characters\nmy_file.seek(0)\nprint('\\n\\nFirst 25 characters:')\nprint(my_file.read(25), end = '')\nmy_file.close()" }, { "code": null, "e": 3955, "s": 3623, "text": "Show the full content:\nThis is first line. \nThis is another line to store into file.\nThe Third Line for the file.\nAnother line... !@#$%^&*()_+.\nEnd Line\n\nThis is a new line. This line will be appended. \n\nFirst two lines:\nThis is first line. \nThis is another line to store into file.\n\nFirst 25 characters:\nThis is first line. \nThis\n" } ]
Set.clear() function in JavaScript
The clear() function of the Set object removes all elements from the current Set object. Its Syntax is as follows setObj.clear() Live Demo <html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> const setObj = new Set(); setObj.add('Java'); setObj.add('JavaFX'); setObj.add('JavaScript'); setObj.add('HBase'); setObj.clear(); document.write("Contents of the Set:"); for (let item of setObj) { document.write(item); document.write("<br>"); } </script> </body> </html> Contents of the Set:
[ { "code": null, "e": 1151, "s": 1062, "text": "The clear() function of the Set object removes all elements from the current Set object." }, { "code": null, "e": 1176, "s": 1151, "text": "Its Syntax is as follows" }, { "code": null, "e": 1191, "s": 1176, "text": "setObj.clear()" }, { "code": null, "e": 1202, "s": 1191, "text": " Live Demo" }, { "code": null, "e": 1650, "s": 1202, "text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n const setObj = new Set();\n setObj.add('Java');\n setObj.add('JavaFX');\n setObj.add('JavaScript');\n setObj.add('HBase');\n setObj.clear();\n document.write(\"Contents of the Set:\");\n for (let item of setObj) {\n document.write(item);\n document.write(\"<br>\");\n }\n </script>\n</body>\n</html>" }, { "code": null, "e": 1671, "s": 1650, "text": "Contents of the Set:" } ]
How to Eliminate Duplicate User Defined Objects as a Key from Java LinkedHashMap? - GeeksforGeeks
04 Jan, 2021 Duplicate user-defined objects as a key from Java LinkedHashMap can be removed and achieved by implementing equals and hashcode methods at the user-defined objects. Example: Input : LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], Nashik}] Duplicate key = {[Grapes, 80], Delhi} Output: LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], Delhi}] Syntax: equals() Method: public boolean equals (Object obj) // This method checks if some other Object // passed to it as an argument is equal to // the Object on which it is invoked. hashCode() Method: public int hashCode() // This method returns the hash code value // for the object on which this method is invoked. Below is the implementation of the problem statement: Java // Java Program to eliminate duplicate user defined// objects as a key from Java LinkedHashMapimport java.util.*;class Employee { private String name; private int id; // Constructor public Employee(String name, int id) { this.name = name; this.id = id; } // HashCode Method public int hashCode() { System.out.println("In hashcode method"); int hashcode = 0; return hashcode; } // Equals Method public boolean equals(Object obj) { System.out.println("In equals method"); if (obj instanceof Employee) { Employee emp = (Employee)obj; return (emp.name.equals(this.name) && emp.id == this.id); } else { return false; } } // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String toString() { return "Employee Id: " + id + " Name: " + name; }} // Driver codepublic class Duplicate_Value { public static void main(String a[]) { // LinkedHashMap initialization LinkedHashMap<Employee, Integer> lhm = new LinkedHashMap<Employee, Integer>(); // Adding entries in LinkedHashMap lhm.put(new Employee("John", 1020), 1); lhm.put(new Employee("Ravi", 1040), 2); lhm.put(new Employee("Jaya", 1030), 3); // Print LinkedHashMap for (Map.Entry<Employee, Integer> entry : lhm.entrySet()) { System.out.println(entry.getKey() + "=>" + entry.getValue()); } // Create duplicate entry Employee duplicate = new Employee("John", 1020); System.out.println("Inserting duplicate record..."); // Add duplicate entry lhm.put(duplicate, 4); System.out.println("After insertion:"); for (Map.Entry<Employee, Integer> entry : lhm.entrySet()) { System.out.println(entry.getKey() + "=>" + entry.getValue()); } }} In hashcode method In hashcode method In equals method In hashcode method In equals method Employee Id: 1020 Name: John Inserting duplicate record... In hashcode method In equals method After insertion: Employee Id: 1020 Name: John Time Complexity: O(1) Java-LinkedHashMap Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n04 Jan, 2021" }, { "code": null, "e": 23722, "s": 23557, "text": "Duplicate user-defined objects as a key from Java LinkedHashMap can be removed and achieved by implementing equals and hashcode methods at the user-defined objects." }, { "code": null, "e": 23731, "s": 23722, "text": "Example:" }, { "code": null, "e": 23918, "s": 23731, "text": "Input : LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], Nashik}]\n Duplicate key = {[Grapes, 80], Delhi}\nOutput: LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], Delhi}]" }, { "code": null, "e": 23926, "s": 23918, "text": "Syntax:" }, { "code": null, "e": 23943, "s": 23926, "text": "equals() Method:" }, { "code": null, "e": 24105, "s": 23943, "text": "public boolean equals (Object obj)\n\n// This method checks if some other Object\n// passed to it as an argument is equal to \n// the Object on which it is invoked." }, { "code": null, "e": 24124, "s": 24105, "text": "hashCode() Method:" }, { "code": null, "e": 24242, "s": 24124, "text": "public int hashCode()\n\n// This method returns the hash code value \n// for the object on which this method is invoked." }, { "code": null, "e": 24296, "s": 24242, "text": "Below is the implementation of the problem statement:" }, { "code": null, "e": 24301, "s": 24296, "text": "Java" }, { "code": "// Java Program to eliminate duplicate user defined// objects as a key from Java LinkedHashMapimport java.util.*;class Employee { private String name; private int id; // Constructor public Employee(String name, int id) { this.name = name; this.id = id; } // HashCode Method public int hashCode() { System.out.println(\"In hashcode method\"); int hashcode = 0; return hashcode; } // Equals Method public boolean equals(Object obj) { System.out.println(\"In equals method\"); if (obj instanceof Employee) { Employee emp = (Employee)obj; return (emp.name.equals(this.name) && emp.id == this.id); } else { return false; } } // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String toString() { return \"Employee Id: \" + id + \" Name: \" + name; }} // Driver codepublic class Duplicate_Value { public static void main(String a[]) { // LinkedHashMap initialization LinkedHashMap<Employee, Integer> lhm = new LinkedHashMap<Employee, Integer>(); // Adding entries in LinkedHashMap lhm.put(new Employee(\"John\", 1020), 1); lhm.put(new Employee(\"Ravi\", 1040), 2); lhm.put(new Employee(\"Jaya\", 1030), 3); // Print LinkedHashMap for (Map.Entry<Employee, Integer> entry : lhm.entrySet()) { System.out.println(entry.getKey() + \"=>\" + entry.getValue()); } // Create duplicate entry Employee duplicate = new Employee(\"John\", 1020); System.out.println(\"Inserting duplicate record...\"); // Add duplicate entry lhm.put(duplicate, 4); System.out.println(\"After insertion:\"); for (Map.Entry<Employee, Integer> entry : lhm.entrySet()) { System.out.println(entry.getKey() + \"=>\" + entry.getValue()); } }}", "e": 26487, "s": 24301, "text": null }, { "code": null, "e": 26721, "s": 26487, "text": "In hashcode method\nIn hashcode method\nIn equals method\nIn hashcode method\nIn equals method\nEmployee Id: 1020 Name: John\nInserting duplicate record...\nIn hashcode method\nIn equals method\nAfter insertion:\nEmployee Id: 1020 Name: John" }, { "code": null, "e": 26743, "s": 26721, "text": "Time Complexity: O(1)" }, { "code": null, "e": 26762, "s": 26743, "text": "Java-LinkedHashMap" }, { "code": null, "e": 26769, "s": 26762, "text": "Picked" }, { "code": null, "e": 26793, "s": 26769, "text": "Technical Scripter 2020" }, { "code": null, "e": 26798, "s": 26793, "text": "Java" }, { "code": null, "e": 26812, "s": 26798, "text": "Java Programs" }, { "code": null, "e": 26831, "s": 26812, "text": "Technical Scripter" }, { "code": null, "e": 26836, "s": 26831, "text": "Java" }, { "code": null, "e": 26934, "s": 26836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26943, "s": 26934, "text": "Comments" }, { "code": null, "e": 26956, "s": 26943, "text": "Old Comments" }, { "code": null, "e": 26986, "s": 26956, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27001, "s": 26986, "text": "Stream In Java" }, { "code": null, "e": 27022, "s": 27001, "text": "Constructors in Java" }, { "code": null, "e": 27068, "s": 27022, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27087, "s": 27068, "text": "Exceptions in Java" }, { "code": null, "e": 27131, "s": 27087, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27157, "s": 27131, "text": "Java Programming Examples" }, { "code": null, "e": 27191, "s": 27157, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27238, "s": 27191, "text": "Implementing a Linked List in Java using Class" } ]
How to Create a Git Hook to Push to Your Server and Github Repo | by Shinichi Okada | Towards Data Science
Git hooks are scripts that Git executes before or after commit, push, and receive. Setting up a Git hook makes your development and deployment easy. In this article, you will learn how to create a post-receive Git hook that executes when you use the git push command. I use $ for a local terminal prompt and # for a remote server prompt. Also for simplicity, I use john for username and Github username, and yourdomain.com for our domain name. You already have a working Git repository on your local machine. We call it newsletter. You have a Linux server for your website (I use Ubuntu 20.04) and you can use ssh to connect from your local computer to your remote server. I assume you secured your server and set firewalls on your server. You can connect to your server using SSH. Let’s connect to your server: $ ssh john@yourdomain.com// or use your IP address$ ssh john@167.99.123.45 Once you are in the remote server, create a new directory, newsletter: # pwd/home/john# mkdir newsletter# cd newsletter Initialize an empty Git repository in a new directory: # git init --bare This will omit the working directory but create the directories and files we need. Create a new directory under /var/www. We are going to redirect all files to this directory. # sudo mkdir /var/www/newsletter/public_html Using git remote set-url allows you to set multiple Git repo URLs. Find out your current remote config using the git remote -v command: $ git remote -vorigin git@github.com:john/newsletter.git (fetch)origin git@github.com:john/newsletter.git (push) Let’s set remote URLs. One for our remote server and one for our Github repo. $ git remote set-url --add --push origin john@yourdomain.com:/home/john/newsletter$ git remote set-url --add --push origin git@github.com:john/newsletter.git You need to run git remote set-url twice as above since the first one will overwrite the current one. Now you should have one fetch and two pushes: $ git remote -vorigin git@github.com:john/newsletter.git (fetch)origin john@yourdomain.com:/home/john/newslette (push)origin git@github.com:john/newsletter.git (push) On your remote server, create a file ~/newsletter/hooks/post-receive. # cd ~/newsletter/hooks# touch post-receive Add the following: We need to make the file executable: # chmod +x post-receive# $ ls -Al ~/newsletter/hookstotal 56-rwxrwxr-x 1 shin shin 478 Apr 24 03:07 applypatch-msg.sample-rwxrwxr-x 1 shin shin 896 Apr 24 03:07 commit-msg.sample-rwxrwxr-x 1 shin shin 3079 Apr 24 03:07 fsmonitor-watchman.sample-rwxrwxr-x 1 shin shin 732 May 3 00:58 post-receive-rwxrwxr-x 1 shin shin 189 Apr 24 03:07 post-update.sample-rwxrwxr-x 1 shin shin 424 Apr 24 03:07 pre-applypatch.sample... The post-receive file mode should have -rwxrwxr-x. On your local machine, run git push origin main: $ git push origin mainEnumerating objects: 5, done.Counting objects: 100% (5/5), done.Delta compression using up to 4 threadsCompressing objects: 100% (3/3), done.Writing objects: 100% (3/3), 303 bytes | 303.00 KiB/s, done.Total 3 (delta 2), reused 0 (delta 0), pack-reused 0remote: Push received! Deploying branch: main...remote: Already on 'main'To okadia.net:/home/john/newsletter 2b35421..aa80729 main -> mainEnumerating objects: 5, done.Counting objects: 100% (5/5), done.Delta compression using up to 4 threadsCompressing objects: 100% (3/3), done.Writing objects: 100% (3/3), 303 bytes | 303.00 KiB/s, done.Total 3 (delta 2), reused 0 (delta 0), pack-reused 0remote: Resolving deltas: 100% (2/2), completed with 2 local objects.To github.com:john/newsletter.git 2b35421..aa80729 main -> main The Git hook, post-receive, is an excellent tool for developers who frequently work with a server. Git has more tools for client and server-side hooks at your disposal. How about start using it for your project? If you like my article and would like to receive newsletters, please sign up. Get full access to every story on Medium by becoming a member. Githooks Deploying Code with a Git Hook on a DigitalOcean Droplet
[ { "code": null, "e": 321, "s": 172, "text": "Git hooks are scripts that Git executes before or after commit, push, and receive. Setting up a Git hook makes your development and deployment easy." }, { "code": null, "e": 440, "s": 321, "text": "In this article, you will learn how to create a post-receive Git hook that executes when you use the git push command." }, { "code": null, "e": 616, "s": 440, "text": "I use $ for a local terminal prompt and # for a remote server prompt. Also for simplicity, I use john for username and Github username, and yourdomain.com for our domain name." }, { "code": null, "e": 845, "s": 616, "text": "You already have a working Git repository on your local machine. We call it newsletter. You have a Linux server for your website (I use Ubuntu 20.04) and you can use ssh to connect from your local computer to your remote server." }, { "code": null, "e": 954, "s": 845, "text": "I assume you secured your server and set firewalls on your server. You can connect to your server using SSH." }, { "code": null, "e": 984, "s": 954, "text": "Let’s connect to your server:" }, { "code": null, "e": 1059, "s": 984, "text": "$ ssh john@yourdomain.com// or use your IP address$ ssh john@167.99.123.45" }, { "code": null, "e": 1130, "s": 1059, "text": "Once you are in the remote server, create a new directory, newsletter:" }, { "code": null, "e": 1179, "s": 1130, "text": "# pwd/home/john# mkdir newsletter# cd newsletter" }, { "code": null, "e": 1234, "s": 1179, "text": "Initialize an empty Git repository in a new directory:" }, { "code": null, "e": 1252, "s": 1234, "text": "# git init --bare" }, { "code": null, "e": 1335, "s": 1252, "text": "This will omit the working directory but create the directories and files we need." }, { "code": null, "e": 1428, "s": 1335, "text": "Create a new directory under /var/www. We are going to redirect all files to this directory." }, { "code": null, "e": 1473, "s": 1428, "text": "# sudo mkdir /var/www/newsletter/public_html" }, { "code": null, "e": 1540, "s": 1473, "text": "Using git remote set-url allows you to set multiple Git repo URLs." }, { "code": null, "e": 1609, "s": 1540, "text": "Find out your current remote config using the git remote -v command:" }, { "code": null, "e": 1722, "s": 1609, "text": "$ git remote -vorigin git@github.com:john/newsletter.git (fetch)origin git@github.com:john/newsletter.git (push)" }, { "code": null, "e": 1800, "s": 1722, "text": "Let’s set remote URLs. One for our remote server and one for our Github repo." }, { "code": null, "e": 1958, "s": 1800, "text": "$ git remote set-url --add --push origin john@yourdomain.com:/home/john/newsletter$ git remote set-url --add --push origin git@github.com:john/newsletter.git" }, { "code": null, "e": 2060, "s": 1958, "text": "You need to run git remote set-url twice as above since the first one will overwrite the current one." }, { "code": null, "e": 2106, "s": 2060, "text": "Now you should have one fetch and two pushes:" }, { "code": null, "e": 2273, "s": 2106, "text": "$ git remote -vorigin git@github.com:john/newsletter.git (fetch)origin john@yourdomain.com:/home/john/newslette (push)origin git@github.com:john/newsletter.git (push)" }, { "code": null, "e": 2343, "s": 2273, "text": "On your remote server, create a file ~/newsletter/hooks/post-receive." }, { "code": null, "e": 2387, "s": 2343, "text": "# cd ~/newsletter/hooks# touch post-receive" }, { "code": null, "e": 2406, "s": 2387, "text": "Add the following:" }, { "code": null, "e": 2443, "s": 2406, "text": "We need to make the file executable:" }, { "code": null, "e": 2867, "s": 2443, "text": "# chmod +x post-receive# $ ls -Al ~/newsletter/hookstotal 56-rwxrwxr-x 1 shin shin 478 Apr 24 03:07 applypatch-msg.sample-rwxrwxr-x 1 shin shin 896 Apr 24 03:07 commit-msg.sample-rwxrwxr-x 1 shin shin 3079 Apr 24 03:07 fsmonitor-watchman.sample-rwxrwxr-x 1 shin shin 732 May 3 00:58 post-receive-rwxrwxr-x 1 shin shin 189 Apr 24 03:07 post-update.sample-rwxrwxr-x 1 shin shin 424 Apr 24 03:07 pre-applypatch.sample..." }, { "code": null, "e": 2918, "s": 2867, "text": "The post-receive file mode should have -rwxrwxr-x." }, { "code": null, "e": 2967, "s": 2918, "text": "On your local machine, run git push origin main:" }, { "code": null, "e": 3772, "s": 2967, "text": "$ git push origin mainEnumerating objects: 5, done.Counting objects: 100% (5/5), done.Delta compression using up to 4 threadsCompressing objects: 100% (3/3), done.Writing objects: 100% (3/3), 303 bytes | 303.00 KiB/s, done.Total 3 (delta 2), reused 0 (delta 0), pack-reused 0remote: Push received! Deploying branch: main...remote: Already on 'main'To okadia.net:/home/john/newsletter 2b35421..aa80729 main -> mainEnumerating objects: 5, done.Counting objects: 100% (5/5), done.Delta compression using up to 4 threadsCompressing objects: 100% (3/3), done.Writing objects: 100% (3/3), 303 bytes | 303.00 KiB/s, done.Total 3 (delta 2), reused 0 (delta 0), pack-reused 0remote: Resolving deltas: 100% (2/2), completed with 2 local objects.To github.com:john/newsletter.git 2b35421..aa80729 main -> main" }, { "code": null, "e": 3984, "s": 3772, "text": "The Git hook, post-receive, is an excellent tool for developers who frequently work with a server. Git has more tools for client and server-side hooks at your disposal. How about start using it for your project?" }, { "code": null, "e": 4062, "s": 3984, "text": "If you like my article and would like to receive newsletters, please sign up." }, { "code": null, "e": 4125, "s": 4062, "text": "Get full access to every story on Medium by becoming a member." }, { "code": null, "e": 4134, "s": 4125, "text": "Githooks" } ]
Maximum sum Rectangle | Practice | GeeksforGeeks
Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it. Example 1: Input: R=4 C=5 M=[[1,2,-1,-4,-20], [-8,-3,4,2,1], [3,8,10,1,3], [-4,-1,1,7,-6]] Output: 29 Explanation: The matrix is as follows and the blue rectangle denotes the maximum sum rectangle. Example 2: Input: R=2 C=2 M=[[-1,-2],[-3,-4]] Output: -1 Explanation: Taking only the first cell is the optimal choice. Your Task: You don't need to read input or print anything. Your task is to complete the function maximumSumRectangle() which takes the number R, C, and the 2D matrix M as input parameters and returns the maximum sum submatrix. Expected Time Complexity:O(R*R*C) Expected Auxillary Space:O(R*C) Constraints: 1<=R,C<=500 -1000<=M[i][j]<=1000 0 anutigerin 9 hours int ans = 0; int ans1 = -1000; for(int i = 0 ; i < R ; i ++){ for(int j = 0 ; j < C ; j ++){ ans1 = max(ans1,M[i][j]); } } for(int i = 0 ; i < C ; i ++){ vector< int > dp(R,0); for(int j = i ; j < C ; j++){ for(int k = 0 ; k < R; k ++){ dp[k] += M[k][j]; } int res = 0; for(int k = 0 ; k < R ; k ++){ res += dp[k]; if(res < 0) res = 0; ans = max(ans,res); } } } if(ans == 0) return ans1; return ans; 0 wjyjobs1 week ago class Solution: def maximumSumRectangle(self,R,C,M): for r in M: for i in range(1, C): r[i] += r[i-1] ans = float('-inf') for l in range(C): for r in range(l, C): running = 0 for i in range(R): v = M[i][r] if l > 0: v -= M[i][l-1] running += v ans = max(ans, running) if running < 0: running = 0 return ans +1 abhishekkaswan1 week ago Can do it using O(C*C*R) like this also , really easy C++ solution int kadanel(vector<int> &res) { int max1=INT_MIN,max2=0; for(int i=0;i<res.size();i++) { max2+=res[i]; if(max1<max2) max1=max2; if(max2<0) max2=0; } return max1; } int maximumSumRectangle(int r, int c, vector<vector<int>> M) { int ans=INT_MIN; for(int i=0;i<c;i++) { vector<int> res(r); for(int j=i;j<c;j++) { for(int k=0;k<r;k++) { res[k]+=M[k][j]; } ans=max(ans,kadanel(res)); } } return ans; } -1 subhashishde081 week ago class Solution { public: int kadane(vector<int> v,int n){ int ma = INT_MIN; int untill = 0; for(int i=0;i<n;i++){ untill += v[i]; if(untill>ma) ma= untill; if(untill<0) untill = 0; } return ma; } int maximumSumRectangle(int m, int n, vector<vector<int>> M) { // code here int maxi = INT_MIN; for(int i=0;i<m;i++){ vector<int> res(n,0); for(int j=i;j<m;j++){ for(int col=0;col<n;col++){ res[col] += M[j][col]; } maxi = max(maxi,kadane(res,n)); } } return maxi; } }; 0 jrchoudhary24101 week ago Simple and easy || prefix sum || kadane's class Solution { int maximumSumRectangle(int r, int c, int m[][]) { // code here int max = Integer.MIN_VALUE; int [] dp = new int[c]; for(int i=0;i<r;i++){ for(int j=i;j<r;j++){ for(int k=0;k<c;k++){ dp[k] += m[j][k]; } max = Math.max(max, kadane(dp)); } Arrays.fill(dp, 0); } return max; } public static int kadane(int [] dp){ int sum=dp[0], max=dp[0]; for(int i=1;i<dp.length;i++){ sum+= dp[i]; if(sum<dp[i]) sum = dp[i]; max = Math.max(sum, max); } return max; } } 0 jrchoudhary2410 This comment was deleted. +4 harsh63101 week ago Easy to Understand, O(C*C*R) Time and O(R*C) Space Really great problem, can be solved by selecting starting and ending columns ( O(C*C) ) then using kadanes algorithm for finding largest sum of contiguous rows in between those 2 columns we selected. Sum of a row can be found with pre-calculations, thus helping us find Largest Sum of contiguous rows in O(R).....bringing the total time complexity to O(R*C*C). We can do same for columns instead of rows to make time complexity O(C*R*R) interchangeably. Code: class Solution { public: int maximumSumRectangle(int r, int c, vector<vector<int>>& m) { vector< vector<int> > rsum(m.begin(),m.end()) ; for(int i=0 ; i<r ; i++) for(int j=1 ; j<c ; j++) rsum[i][j] += rsum[i][j-1] ; int ans = INT_MIN ; for(int sc=0 ; sc<c ; sc++){ for(int ec=sc ; ec<c ; ec++){ int mrs = 0 , crsum = 0 ; for(int i=0 ; i<r ; i++){ crsum += rsum[i][ec]-(sc == 0 ? 0 : rsum[i][sc-1] ) ; ans = max(ans,crsum - mrs) ; mrs = min(mrs,crsum) ; } } } return ans ; } }; 0 6288261 week ago Use prefix-sum array and Kadane's algorithm. Nice and clear. vector<vector<int>> acc(R, vector<int>(C + 1)); int glo = INT_MIN; // prefix-sum array for (int i = 0; i < R; ++i) for (int j = 0; j < C; ++j) acc[i][j + 1] = acc[i][j] + M[i][j]; for (int i = 0; i < C; ++i) { for (int j = i; j < C; ++j) { // kadane int loc = 0; for (int k = 0; k < R; ++k) { // use prefix-sum to avoid repeated accumulation. loc += acc[k][j + 1] - acc[k][i]; glo = max(glo, loc); loc = max(loc, 0); } } } return glo; +1 priyankapardesiramachander1 week ago My solution in C# β†’ https://github.com/ramacpr/G4G_DailyCodingProblems/tree/master/April15_2022/MaxSumRectangle 0 akshayadivarekar7771 week ago //JAVA Solution // Its just KADANE class Solution { int maximumSumRectangle(int R, int C, int M[][]) { // code here int max = 0; int maxop=Integer.MIN_VALUE; int[] dp = new int[R]; for(int i=0;i<C;i++) { for(int j=i;j<C;j++) { for(int k=0;k<dp.length;k++) { dp[k]+=M[k][j]; maxop = Math.max(maxop,M[k][j]); } max = Math.max(max,kadane(dp)); } Arrays.fill(dp,0); } return max==0? maxop:max; } public int kadane(int[] arr) { int cur=0; int max=0; for(int i:arr) { cur+=i; max = Math.max(max,cur); if(cur<0) cur=0; } return max; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 315, "s": 238, "text": "Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it." }, { "code": null, "e": 326, "s": 315, "text": "Example 1:" }, { "code": null, "e": 515, "s": 326, "text": "Input:\nR=4\nC=5\nM=[[1,2,-1,-4,-20],\n[-8,-3,4,2,1],\n[3,8,10,1,3],\n[-4,-1,1,7,-6]]\nOutput:\n29\nExplanation:\nThe matrix is as follows and the\nblue rectangle denotes the maximum sum\nrectangle.\n\n" }, { "code": null, "e": 526, "s": 515, "text": "Example 2:" }, { "code": null, "e": 636, "s": 526, "text": "Input:\nR=2\nC=2\nM=[[-1,-2],[-3,-4]]\nOutput:\n-1\nExplanation:\nTaking only the first cell is the \noptimal choice." }, { "code": null, "e": 864, "s": 636, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maximumSumRectangle() which takes the number R, C, and the 2D matrix M as input parameters and returns the maximum sum submatrix." }, { "code": null, "e": 933, "s": 864, "text": "\nExpected Time Complexity:O(R*R*C)\nExpected Auxillary Space:O(R*C)\n " }, { "code": null, "e": 979, "s": 933, "text": "Constraints:\n1<=R,C<=500\n-1000<=M[i][j]<=1000" }, { "code": null, "e": 981, "s": 979, "text": "0" }, { "code": null, "e": 1000, "s": 981, "text": "anutigerin 9 hours" }, { "code": null, "e": 1702, "s": 1000, "text": " int ans = 0;\n int ans1 = -1000;\n for(int i = 0 ; i < R ; i ++){\n for(int j = 0 ; j < C ; j ++){\n ans1 = max(ans1,M[i][j]);\n }\n }\n for(int i = 0 ; i < C ; i ++){\n vector< int > dp(R,0);\n for(int j = i ; j < C ; j++){\n for(int k = 0 ; k < R; k ++){\n dp[k] += M[k][j];\n }\n int res = 0;\n for(int k = 0 ; k < R ; k ++){\n res += dp[k];\n if(res < 0) res = 0;\n ans = max(ans,res);\n }\n }\n }\n if(ans == 0) return ans1;\n return ans;" }, { "code": null, "e": 1704, "s": 1702, "text": "0" }, { "code": null, "e": 1722, "s": 1704, "text": "wjyjobs1 week ago" }, { "code": null, "e": 2302, "s": 1722, "text": "class Solution:\n def maximumSumRectangle(self,R,C,M):\n for r in M:\n for i in range(1, C):\n r[i] += r[i-1]\n \n ans = float('-inf') \n for l in range(C):\n for r in range(l, C):\n running = 0\n for i in range(R):\n v = M[i][r]\n if l > 0:\n v -= M[i][l-1]\n running += v\n ans = max(ans, running)\n if running < 0:\n running = 0\n return ans" }, { "code": null, "e": 2305, "s": 2302, "text": "+1" }, { "code": null, "e": 2330, "s": 2305, "text": "abhishekkaswan1 week ago" }, { "code": null, "e": 2397, "s": 2330, "text": "Can do it using O(C*C*R) like this also , really easy C++ solution" }, { "code": null, "e": 3120, "s": 2397, "text": "int kadanel(vector<int> &res)\n {\n int max1=INT_MIN,max2=0;\n for(int i=0;i<res.size();i++)\n {\n max2+=res[i];\n if(max1<max2)\n max1=max2;\n if(max2<0)\n max2=0;\n \n }\n return max1;\n }\n int maximumSumRectangle(int r, int c, vector<vector<int>> M) {\n int ans=INT_MIN;\n for(int i=0;i<c;i++)\n {\n vector<int> res(r);\n for(int j=i;j<c;j++)\n {\n for(int k=0;k<r;k++)\n {\n res[k]+=M[k][j];\n }\n ans=max(ans,kadanel(res));\n }\n \n }\n return ans;\n }" }, { "code": null, "e": 3123, "s": 3120, "text": "-1" }, { "code": null, "e": 3148, "s": 3123, "text": "subhashishde081 week ago" }, { "code": null, "e": 3816, "s": 3148, "text": "class Solution {\n public:\n int kadane(vector<int> v,int n){\n int ma = INT_MIN;\n int untill = 0;\n for(int i=0;i<n;i++){\n untill += v[i];\n if(untill>ma) ma= untill;\n if(untill<0) untill = 0;\n }\n return ma;\n }\n int maximumSumRectangle(int m, int n, vector<vector<int>> M) {\n // code here\n int maxi = INT_MIN;\n for(int i=0;i<m;i++){\n vector<int> res(n,0);\n for(int j=i;j<m;j++){\n for(int col=0;col<n;col++){\n res[col] += M[j][col];\n }\n maxi = max(maxi,kadane(res,n));\n }\n }\n return maxi;\n }\n};" }, { "code": null, "e": 3820, "s": 3818, "text": "0" }, { "code": null, "e": 3846, "s": 3820, "text": "jrchoudhary24101 week ago" }, { "code": null, "e": 3889, "s": 3846, "text": "Simple and easy || prefix sum || kadane's " }, { "code": null, "e": 4607, "s": 3889, "text": "class Solution {\n int maximumSumRectangle(int r, int c, int m[][]) {\n // code here\n int max = Integer.MIN_VALUE;\n int [] dp = new int[c];\n for(int i=0;i<r;i++){\n for(int j=i;j<r;j++){\n for(int k=0;k<c;k++){\n dp[k] += m[j][k]; \n } \n max = Math.max(max, kadane(dp));\n }\n Arrays.fill(dp, 0);\n }\n return max;\n }\n public static int kadane(int [] dp){\n int sum=dp[0], max=dp[0];\n for(int i=1;i<dp.length;i++){\n sum+= dp[i];\n if(sum<dp[i])\n sum = dp[i];\n max = Math.max(sum, max);\n }\n return max;\n }\n}" }, { "code": null, "e": 4609, "s": 4607, "text": "0" }, { "code": null, "e": 4625, "s": 4609, "text": "jrchoudhary2410" }, { "code": null, "e": 4651, "s": 4625, "text": "This comment was deleted." }, { "code": null, "e": 4654, "s": 4651, "text": "+4" }, { "code": null, "e": 4674, "s": 4654, "text": "harsh63101 week ago" }, { "code": null, "e": 4725, "s": 4674, "text": "Easy to Understand, O(C*C*R) Time and O(R*C) Space" }, { "code": null, "e": 4925, "s": 4725, "text": "Really great problem, can be solved by selecting starting and ending columns ( O(C*C) ) then using kadanes algorithm for finding largest sum of contiguous rows in between those 2 columns we selected." }, { "code": null, "e": 5086, "s": 4925, "text": "Sum of a row can be found with pre-calculations, thus helping us find Largest Sum of contiguous rows in O(R).....bringing the total time complexity to O(R*C*C)." }, { "code": null, "e": 5179, "s": 5086, "text": "We can do same for columns instead of rows to make time complexity O(C*R*R) interchangeably." }, { "code": null, "e": 5185, "s": 5179, "text": "Code:" }, { "code": null, "e": 5958, "s": 5185, "text": "class Solution {\n public:\n int maximumSumRectangle(int r, int c, vector<vector<int>>& m) {\n vector< vector<int> > rsum(m.begin(),m.end()) ;\n \n for(int i=0 ; i<r ; i++)\n for(int j=1 ; j<c ; j++)\n rsum[i][j] += rsum[i][j-1] ; \n \n int ans = INT_MIN ;\n \n for(int sc=0 ; sc<c ; sc++){\n for(int ec=sc ; ec<c ; ec++){\n \n int mrs = 0 , crsum = 0 ; \n for(int i=0 ; i<r ; i++){\n crsum += rsum[i][ec]-(sc == 0 ? 0 : rsum[i][sc-1] ) ;\n ans = max(ans,crsum - mrs) ;\n mrs = min(mrs,crsum) ; \n }\n \n }\n }\n \n return ans ;\n }\n};\n" }, { "code": null, "e": 5960, "s": 5958, "text": "0" }, { "code": null, "e": 5977, "s": 5960, "text": "6288261 week ago" }, { "code": null, "e": 6022, "s": 5977, "text": "Use prefix-sum array and Kadane's algorithm." }, { "code": null, "e": 6038, "s": 6022, "text": "Nice and clear." }, { "code": null, "e": 6510, "s": 6038, "text": "vector<vector<int>> acc(R, vector<int>(C + 1));\nint glo = INT_MIN;\n\n// prefix-sum array\nfor (int i = 0; i < R; ++i)\n\tfor (int j = 0; j < C; ++j)\n\t\tacc[i][j + 1] = acc[i][j] + M[i][j];\n\t\t\nfor (int i = 0; i < C; ++i)\n{\n\tfor (int j = i; j < C; ++j)\n\t{\n\t\t// kadane\n\t\tint loc = 0;\n\t\t\n\t\tfor (int k = 0; k < R; ++k)\n\t\t{\n\t\t\t// use prefix-sum to avoid repeated accumulation.\n\t\t\tloc += acc[k][j + 1] - acc[k][i]; \n\t\t\tglo = max(glo, loc);\n\t\t\tloc = max(loc, 0);\n\t\t}\n\t}\n}\n\nreturn glo;" }, { "code": null, "e": 6513, "s": 6510, "text": "+1" }, { "code": null, "e": 6550, "s": 6513, "text": "priyankapardesiramachander1 week ago" }, { "code": null, "e": 6663, "s": 6550, "text": "My solution in C# β†’ https://github.com/ramacpr/G4G_DailyCodingProblems/tree/master/April15_2022/MaxSumRectangle " }, { "code": null, "e": 6665, "s": 6663, "text": "0" }, { "code": null, "e": 6695, "s": 6665, "text": "akshayadivarekar7771 week ago" }, { "code": null, "e": 6730, "s": 6695, "text": "//JAVA Solution\n// Its just KADANE" }, { "code": null, "e": 7614, "s": 6730, "text": "class Solution {\n int maximumSumRectangle(int R, int C, int M[][]) {\n // code here\n \n int max = 0;\n int maxop=Integer.MIN_VALUE;\n int[] dp = new int[R];\n \n for(int i=0;i<C;i++)\n {\n \n for(int j=i;j<C;j++)\n {\n for(int k=0;k<dp.length;k++)\n {\n dp[k]+=M[k][j];\n maxop = Math.max(maxop,M[k][j]);\n }\n max = Math.max(max,kadane(dp));\n \n }\n Arrays.fill(dp,0);\n }\n \n return max==0? maxop:max;\n \n }\n \n public int kadane(int[] arr)\n {\n \n int cur=0;\n int max=0;\n for(int i:arr)\n {\n cur+=i;\n max = Math.max(max,cur);\n if(cur<0)\n cur=0;\n }\n return max;\n \n \n }\n}; " }, { "code": null, "e": 7762, "s": 7616, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7798, "s": 7762, "text": " Login to access your submissions. " }, { "code": null, "e": 7808, "s": 7798, "text": "\nProblem\n" }, { "code": null, "e": 7818, "s": 7808, "text": "\nContest\n" }, { "code": null, "e": 7881, "s": 7818, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8029, "s": 7881, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8237, "s": 8029, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8343, "s": 8237, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Using keyword extraction for unsupervised text classification in NLP | by Evan Hu | Towards Data Science
Text classification is a common task in Natural Language Processing. The main approach tends toward representing the text in a meaningful way β€” whether through TF-IDF, Word2Vec, or more advanced models like BERT β€” and training models on the representations as labelled inputs. Sometimes, however, either labelling the data is impractical or there is just not enough labelled data to build an effective multi classification model. Instead, we are forced to leverage unsupervised methods of learning in order to accomplish the classification task. In this article, I’ll be outlining the process I took to build an unsupervised text classifier for the dataset of interview questions at Interview Query, a data science interview/career prep website. This would be greatly beneficial to them for several reasons. Interview Query wants to be able to offer more insightful information for users about the companies that they are applying to, as well as the functionality to practice only certain question types. Most importantly, it would enable them to β€œcharacterize” different companies by the types of questions that they ask. Our task is to classify a given interview question as either relating to machine learning, statistics, probability, Python, product management, SQL, A/B testing, algorithms, or take-home. I decided the most practical approach would be to first extract as many relevant keywords as possible from the corpus, and then manually assign the resulting keywords into β€œbins” corresponding to our desired classifications. Finally, I’d iterate through each interview question in the dataset and compared the total counts of keywords in each bin in order to classify them. The possibility of using Latent Dirichlet Allocation was also considered in order to generate topic models and retrieve relevant keywords relating to each topic without having to manually assign them, as well as K-means clustering. These proved to be difficult and less effective than simply counting keywords, given the wide and disparate range of our classifications. First the data had to be cleaned and preprocessed. I used SpaCy to tokenize, lemmatize, lowercase, and remove stop-words from the text. import pandas as pdimport nltkimport spacyfrom tqdm import tqdnlp = spacy.load("en_core_web_sm")def create_tokens(dataframe): tokens = [] for doc in tqdm(nlp.pipe(dataframe.astype('unicode').values), total=dataframe.size): if doc.is_parsed: tokens.append([n.lemma_.lower() for n in doc if (not n.is_punct and not n.is_space and not n.is_stop)]) else: tokens.append("") return tokensraw = pd.read_csv("topics_raw.csv")tokens = create_tokens(raw) After this came the problem of choosing a way to extract keywords from the corpus of text. Since my corpus was comprised of a massive number of small β€œdocuments,” each one a different interview question, I decided to extract the keywords from each document separately rather than combining any of the data, and sorting unique keywords from the resulting list by frequency. Then, testing began. Various methods, such as TF-IDF, RAKE, as well as some more recent, state-of-the-art methods such as SGRank, YAKE, and TextRank, were considered. I was also curious enough to try Amazon Comprehend, an auto-ML solution, to see how competent it was. Unfortunately, the results were unsatisfactory as the combination of high level abstraction with the granularity of the NLP task proved still yet impractical. In the end, after comparing the keywords produced by each method, I found that SGRank produced the best results (the highest quantity of relevant keywords). import textacyimport textacy.ketext = " ".join(raw.tolist())nlp = spacy.load('en_core_web_sm')nlp.max_length = len(text)keywords = []for tokenlist in tqdm(question_tokens): doc = nlp(" ".join(tokenlist)) extract = textacy.ke.sgrank(doc, ngrams=(1), window_size=2, normalize=None, topn = 2, include_pos=['NOUN', 'PROPN']) for a, b in extract: keywords.append(a) Finally, I sorted unique keywords by frequency in order to get the most salient ones. res = sorted(set(keywords), key = lambda x: keywords.count(x), reverse=True) The result was around 1900 words, which I then manually went through and assigned the top 200 most relevant ones to our bins. Finally, with the final list of categorized keywords, it is possible to classify each interview question as one of 8 different types by counting the appearance of keywords in each question. Furthermore, we can generate β€œpersonality” profiles for different companies which are displayed on the website. In conclusion, I found that for this specific problem it was best to simply opt for a hybrid approach towards the unsupervised classification task that involved both machine learning as well as manual work. Generally, working without labels in unsupervised contexts within Natural Language Processing leaves quite some distance between the analysis of data and the actual practical application of resultsβ€” forcing alternate approaches like the one seen in this article. This is, in my opinion, a distinct deficiency of NLP which is more severe than in other fields such as computer vision or generative models. Of course, I anticipate future advancements in more insightful models and other research will make marked improvements in this regard. Anyway, thanks for reading this article! I hope you learned something.
[ { "code": null, "e": 718, "s": 172, "text": "Text classification is a common task in Natural Language Processing. The main approach tends toward representing the text in a meaningful way β€” whether through TF-IDF, Word2Vec, or more advanced models like BERT β€” and training models on the representations as labelled inputs. Sometimes, however, either labelling the data is impractical or there is just not enough labelled data to build an effective multi classification model. Instead, we are forced to leverage unsupervised methods of learning in order to accomplish the classification task." }, { "code": null, "e": 1295, "s": 718, "text": "In this article, I’ll be outlining the process I took to build an unsupervised text classifier for the dataset of interview questions at Interview Query, a data science interview/career prep website. This would be greatly beneficial to them for several reasons. Interview Query wants to be able to offer more insightful information for users about the companies that they are applying to, as well as the functionality to practice only certain question types. Most importantly, it would enable them to β€œcharacterize” different companies by the types of questions that they ask." }, { "code": null, "e": 2227, "s": 1295, "text": "Our task is to classify a given interview question as either relating to machine learning, statistics, probability, Python, product management, SQL, A/B testing, algorithms, or take-home. I decided the most practical approach would be to first extract as many relevant keywords as possible from the corpus, and then manually assign the resulting keywords into β€œbins” corresponding to our desired classifications. Finally, I’d iterate through each interview question in the dataset and compared the total counts of keywords in each bin in order to classify them. The possibility of using Latent Dirichlet Allocation was also considered in order to generate topic models and retrieve relevant keywords relating to each topic without having to manually assign them, as well as K-means clustering. These proved to be difficult and less effective than simply counting keywords, given the wide and disparate range of our classifications." }, { "code": null, "e": 2363, "s": 2227, "text": "First the data had to be cleaned and preprocessed. I used SpaCy to tokenize, lemmatize, lowercase, and remove stop-words from the text." }, { "code": null, "e": 2870, "s": 2363, "text": "import pandas as pdimport nltkimport spacyfrom tqdm import tqdnlp = spacy.load(\"en_core_web_sm\")def create_tokens(dataframe): tokens = [] for doc in tqdm(nlp.pipe(dataframe.astype('unicode').values), total=dataframe.size): if doc.is_parsed: tokens.append([n.lemma_.lower() for n in doc if (not n.is_punct and not n.is_space and not n.is_stop)]) else: tokens.append(\"\") return tokensraw = pd.read_csv(\"topics_raw.csv\")tokens = create_tokens(raw)" }, { "code": null, "e": 3243, "s": 2870, "text": "After this came the problem of choosing a way to extract keywords from the corpus of text. Since my corpus was comprised of a massive number of small β€œdocuments,” each one a different interview question, I decided to extract the keywords from each document separately rather than combining any of the data, and sorting unique keywords from the resulting list by frequency." }, { "code": null, "e": 3828, "s": 3243, "text": "Then, testing began. Various methods, such as TF-IDF, RAKE, as well as some more recent, state-of-the-art methods such as SGRank, YAKE, and TextRank, were considered. I was also curious enough to try Amazon Comprehend, an auto-ML solution, to see how competent it was. Unfortunately, the results were unsatisfactory as the combination of high level abstraction with the granularity of the NLP task proved still yet impractical. In the end, after comparing the keywords produced by each method, I found that SGRank produced the best results (the highest quantity of relevant keywords)." }, { "code": null, "e": 4205, "s": 3828, "text": "import textacyimport textacy.ketext = \" \".join(raw.tolist())nlp = spacy.load('en_core_web_sm')nlp.max_length = len(text)keywords = []for tokenlist in tqdm(question_tokens): doc = nlp(\" \".join(tokenlist)) extract = textacy.ke.sgrank(doc, ngrams=(1), window_size=2, normalize=None, topn = 2, include_pos=['NOUN', 'PROPN']) for a, b in extract: keywords.append(a)" }, { "code": null, "e": 4291, "s": 4205, "text": "Finally, I sorted unique keywords by frequency in order to get the most salient ones." }, { "code": null, "e": 4368, "s": 4291, "text": "res = sorted(set(keywords), key = lambda x: keywords.count(x), reverse=True)" }, { "code": null, "e": 4494, "s": 4368, "text": "The result was around 1900 words, which I then manually went through and assigned the top 200 most relevant ones to our bins." }, { "code": null, "e": 4796, "s": 4494, "text": "Finally, with the final list of categorized keywords, it is possible to classify each interview question as one of 8 different types by counting the appearance of keywords in each question. Furthermore, we can generate β€œpersonality” profiles for different companies which are displayed on the website." }, { "code": null, "e": 5003, "s": 4796, "text": "In conclusion, I found that for this specific problem it was best to simply opt for a hybrid approach towards the unsupervised classification task that involved both machine learning as well as manual work." }, { "code": null, "e": 5542, "s": 5003, "text": "Generally, working without labels in unsupervised contexts within Natural Language Processing leaves quite some distance between the analysis of data and the actual practical application of resultsβ€” forcing alternate approaches like the one seen in this article. This is, in my opinion, a distinct deficiency of NLP which is more severe than in other fields such as computer vision or generative models. Of course, I anticipate future advancements in more insightful models and other research will make marked improvements in this regard." } ]
Autoboxing and Unboxing in Java
Autoboxing refers to the automatic conversion of a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is βˆ’ Passed as an argument to a function which is expecting a wrapper class object. Passed as an argument to a function which is expecting a wrapper class object. assigned to a variable of the type of wrapper class. assigned to a variable of the type of wrapper class. Consider the following example. Live Demo import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); for(int i = 0; i< 10; i++){ //autoboxing by passing as an argument //int values is converted to Integer //by compiler during compilation list.add(i); } System.out.println(list); char c = 'a'; //autoboxing by assigning an char to Character object Character ch = c; System.out.println(ch); } } [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a Unboxing is reverse of Autoboxing and it refers to the automatic conversion of a wrapper object to its corresponding primitive variable. The compiler automatically handles the conversion when a wrapper object is βˆ’ Passed as an argument to a function which is expecting a primitive data type variable. Passed as an argument to a function which is expecting a primitive data type variable. assigned to a variable of the type of primitive data type variable. assigned to a variable of the type of primitive data type variable. Consider the following example. Live Demo public class Tester { public static void main(String[] args) { Integer integer = new Integer(-10); //autoboxing by passing as an argument //Integer object is converted to int //by compiler during compilation int i = abs(integer); System.out.println(i); //autoboxing by assigning an Integer object to int variable int j = integer; System.out.println(j); } private static int abs(int i){ return (i < 0)? -i: i; } } 10 -10
[ { "code": null, "e": 1258, "s": 1062, "text": "Autoboxing refers to the automatic conversion of a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is βˆ’" }, { "code": null, "e": 1337, "s": 1258, "text": "Passed as an argument to a function which is expecting a wrapper class object." }, { "code": null, "e": 1416, "s": 1337, "text": "Passed as an argument to a function which is expecting a wrapper class object." }, { "code": null, "e": 1469, "s": 1416, "text": "assigned to a variable of the type of wrapper class." }, { "code": null, "e": 1522, "s": 1469, "text": "assigned to a variable of the type of wrapper class." }, { "code": null, "e": 1554, "s": 1522, "text": "Consider the following example." }, { "code": null, "e": 1564, "s": 1554, "text": "Live Demo" }, { "code": null, "e": 2114, "s": 1564, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Tester {\n public static void main(String[] args) {\n List<Integer> list = new ArrayList<>();\n\n for(int i = 0; i< 10; i++){\n //autoboxing by passing as an argument\n //int values is converted to Integer\n //by compiler during compilation\n list.add(i);\n }\n\n System.out.println(list);\n\n char c = 'a'; \n //autoboxing by assigning an char to Character object\n Character ch = c;\n System.out.println(ch);\n }\n}" }, { "code": null, "e": 2147, "s": 2114, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\na" }, { "code": null, "e": 2361, "s": 2147, "text": "Unboxing is reverse of Autoboxing and it refers to the automatic conversion of a wrapper object to its corresponding primitive variable. The compiler automatically handles the conversion when a wrapper object is βˆ’" }, { "code": null, "e": 2448, "s": 2361, "text": "Passed as an argument to a function which is expecting a primitive data type variable." }, { "code": null, "e": 2535, "s": 2448, "text": "Passed as an argument to a function which is expecting a primitive data type variable." }, { "code": null, "e": 2603, "s": 2535, "text": "assigned to a variable of the type of primitive data type variable." }, { "code": null, "e": 2671, "s": 2603, "text": "assigned to a variable of the type of primitive data type variable." }, { "code": null, "e": 2703, "s": 2671, "text": "Consider the following example." }, { "code": null, "e": 2713, "s": 2703, "text": "Live Demo" }, { "code": null, "e": 3217, "s": 2713, "text": "public class Tester {\n public static void main(String[] args) {\n Integer integer = new Integer(-10);\n //autoboxing by passing as an argument\n //Integer object is converted to int\n //by compiler during compilation\n int i = abs(integer); \n System.out.println(i);\n\n //autoboxing by assigning an Integer object to int variable\n int j = integer; \n System.out.println(j);\n }\n \n private static int abs(int i){\n return (i < 0)? -i: i;\n }\n}" }, { "code": null, "e": 3224, "s": 3217, "text": "10\n-10" } ]
Bayesian Hierarchical Modeling (or β€œmore reasons why autoML cannot replace Data Scientists yet”) | by Alain Tanguy | Towards Data Science
In this article, we will use a Probabilistic Programming library developed for python, pymc3. A first introduction to the efficiency of Bayesian approaches in basic statistics and to pymc3 can be found here and there. Since early 2018, Automated Machine Learning has become one of the trendiest topic in data science. Amazon’s Sagemaker or Google AutoML to mention just a few are now accessible to most Data Scientists, to such an extent that some tend to think exploring and understanding data is not necessary anymore in order to build machine learning models. The promise of AutoML can be summed up this way: the high degree of automation allows non-experts to make use of machine learning models and techniques without requiring to become an expert in a particular field first.1 The reasoning is straightforward ; expertise is no longer required, just give data to the AutoML algorithm, and after testing a fixed number of predefined models, it will return the best one. But here’s the catch... AutoML algorithms ignore what best means to us, and will merely try to minimize an empirical error. Knowledge and expertise are still required to understand what this error really means, and to what extent it differs from the one we are actually hoping to minimize. Given n data points, the empirical error is given by for a particular function fn over all observable values of features xi and target yi where V denotes a loss function.2 It is usually computed through a cross-validation or train/test process. Missing some links between covariates and target will generate a bias often leading to under/over-fitting and eventually to a higher test/cross-validated error. It is too often, and wrongly, the only one taken into account by data scientists (and always by autoML engines). generalization error(also known as the out-of-sample error) is a measure of how accurately an algorithm is able to predict outcome values for previously unseen data. It is defined by: for a particular function fn over all possible values of features x and target y where V denotes a loss function and ρ(x, y) is the unknown joint probability distribution for x and y.3 Obviously, it is usually the one we would prefer to minimize when training our model. Unfortunately, it cannot be computed directly from data, unlike the empirical one which is merely an estimate of the former. With enough good quality data, we interchange those. Now imagine only part of the information is available at training time, or that there just isn’t enough data at all, as it is often the case in Machine Learning. Our model will then be trained on a different distribution ρ(x, y) from the one it will be running on later, and as a consequence, the empirical error will diverge from the generalized one. Biased data leads to biased empirical error. We can already see how much of a problem this is: the empirical error does not estimate the desired quantity anymore, but is the only we can compute from data. We need to make sure it can still be relied on to some extent. This is where human expertise comes into plays and shows its full potential. The same way parametric approaches are preferred over non-parametric ones when the relation between variables is clear, knowledge from the field of study compensate the lack of information from the data by explicitly modeling some dependences. The better our model can extrapolate from partial or truncated distribution, the closer empirical and generalization error will be. β€œCorrelation does not imply causation.” All data scientists have heard this sentence at least once, but it turns out only a few truly realize the implication when it comes to actual modeling. The topic of causality is actually just left out most of the time, sometimes wrongly, sometimes justifiably, but rarely knowingly. A confounder is a variable that is causally related to both the covariate and the outcome of interest. As a causal concept, it cannot be described in terms of correlations. The error yielded by confounders cannot be fully measured by traditional statistical methods since it is not a statistical error per se. One could argue that when the empirical error is low, or even the generalization error; then we shouldn’t care if our model exploits true causality or spurious correlations. It might be true in some cases, but unless we explicitly know why, this situation shouldn’t be overlooked. Simpson’s paradox, described by Edward Simpson in 1951 and George Udny Yule in 1903, is a paradox in which a statistical trend appears when data are segmented into separate groups but reverses when the groups are combined. It is usually observed in the presence of a confounding variable (represented here by the different colour groups) when causal relations are ignored. The impact Simpson’s paradox will have in machine learning is when it comes to decision making, where we are given the choice of which data we should consider to pick an action, the aggregated or the partitioned? Unfortunately the answer usually cannot be inferred from the data itself. Indeed with exact similar values we can have different answers, depending on the causal relationships among the variables. The real source of error lies outside of the data itself and eventually it doesn’t matter how low the test or cross-validation error is. We are not safe from getting making completely wrong decisions unless we are able to correctly model the environment first. We will now through a concrete example show how to handle this situation in the concrete case of hierarchical dependences. Often data scientists have to deal with geographic data, which have the disadvantage of not being easily exploitable by classic machine learning models. The location feature usually has a really high cardinality and is often unbalanced. However it is intuitive that parameters from models will vary from region to region, depending on local variables, but will still be closely related since they model the same phenomenon across different places. We are going to see a way to handle this spatial dependence and thus to minimize all types of error listed above through the following example. We consider the problem of estimating the use of contraceptive in Bangladesh, and to this end we use data come from the 1988 Bangladesh Fertility Survey. It consists of a subsample of 1934 women grouped in 60 districts, with variables are defined as follows: DISTRICT: identifying code for each district. LC: Number of living children at time of survey. AGE: Age of woman at time of survey. URBAN: Type of region of residence. and we’ll consider 3 logistic Bayesian regressions with different characteristics to model different possible approaches. Here we simply obliviate the role of the DISTRICT variable by not using it. The result is a simple logistic regression with only 4 parameters, including the intercept. The location is not seen as a confounder and each region is assumed to behave similarly. For each district we fit a different logistic regression, leading to a total of 60 models with 4 parameters each. Even if we assume behaviour to vary from district to district, we don’t take any advantage of the similarities they could share. Bayesian hierarchical modelling is a statistical model written in multiple levels that estimates the parameters of the posterior distribution using the Bayesian method. The sub-models combine to form the hierarchical model, and Bayes’ theorem is used to integrate them with the observed data and account for all the uncertainty that is present.4 We assume that while Ξ²s are different for each district as in the unpooled case, now the coefficients all share similarity. We can model this by assuming that each individual coefficient comes from a common group distribution: with Though analytically intractable, probabilistic programming allows us to compute the posterior of all our parameters using Markov chain Monte Carlo (MCMC) to sample from the posteriors distributions. Again pymc3 offers an extremely intuitive way to model our network and to compute posteriors! We can also easily compute a graphical representation of our Bayesian network: First of all, let’s try to understand the differences between our models. Inspired by https://docs.pymc.io/notebooks/GLM-hierarchical.html, we can visualize the evolution of our regression parameters over the different regressions. We display the coefficients of each district’s non-hierarchical posterior mean, hierarchical posterior mean, and pooled posterior mean. The small amount of data available at district level led unpooled posteriors to be spread far out and thus the shrinkage effect is really important, yet differences among mean in the hierarchical model are still significant, as betas vary in order of magnitude between districts. We use the Area Under the ROC Curve (AUC) as our error measure for comparing the models. It can be seen as the probability that our models will score a randomly chosen positive class higher than a randomly chosen negative class. It is particularly interesting to us since it has the advantage of not requiring to set a threshold to assign labels. We considered 2 test sets in order to measure performances, a stratified by district one and a non-stratified one. The use of a non-stratified test set is more representative of a case where the generalization error will differ significantly from the empirical model error, since features distributions among districts will vary significantly between train and test sets! The measures have been averaged over multiple seeds for the test set sampling in order to be more representative of the real performance. β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ β”‚ POOLED β”‚ UNPOOLED β”‚ HIERARCHICAL β”‚β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”‚ Train β”‚ 0.632 β”‚ 0.818 β”‚ 0.726 β”‚β”‚ Stratified Test β”‚ 0.623 β”‚ 0.618 β”‚ 0.668 β”‚β”‚ Unstratified Test β”‚ 0.634 β”‚ 0.603 β”‚ 0.663 β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ The unpooled model strongly overfits as the huge gap between the train and test AUC demonstrates. On the other hand, the pooled model is strongly biased and clearly underfits the data. Finally, our hierarchical model performed significantly better than the others by taking advantage of parameters geographic similarities. The shrinkage effect provided us with an improved statistical power and can also be seen as a smart way to regularize. Some districts have extremely few individuals from which to train, and thus the unstratified test error on those gets bigger with the unpooled model. The partial pooling takes into account the similarity between parameters, and provides low density districts with information from others, while keeping their specificities. As a result the difference between models is even more significant regarding the unstratified test set, showing us its generalization capacity is greater as performances are almost not affected by the stratification strategy. => Multi-level hierarchical Bayesian models outperform basic approaches when we have multiple sets of measurements we expect to have similarity. It would be interesting to compare this Bayesian approach to other classic data preprocessing approaches (different encodings of the district variable) or algorithms (gradient boosting, random forest, etc.). AutoML cannot replace Data Scientists yet as it is not able to distinguish empirical error measures from actual business objectives, nor to model correctly dependences between covariates and target. Experts are still required to understand data and model properly the problems. To this end, they have access to a range of mathematics and informatic tools, including pymc3 library and Bayesian hierarchical models, allowing to easily model and compute distributions in the very common case of hierarchically structured data [1]: Wikipedia contributors. β€œAutomated machine learning.” Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 18 Feb. 2020. Web. 1 Mar. 2020. [2,3]: Wikipedia contributors. (2020, February 22). Generalization error. In Wikipedia, The Free Encyclopedia. Retrieved 16:40, March 1, 2020, from https://en.wikipedia.org/w/index.php?title=Generalization_error&oldid=942140633 [4]: Wikipedia contributors. β€œBayesian hierarchical modeling.” Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 12 Dec. 2019. Web. 1 Mar. 2020. Causality: Models, Reasoning, and Inference, Cambridge University Press (2000, 2nd edition 2009). ISBN 0–521–77362–8. https://docs.pymc.io/notebooks/GLM-hierarchical.html Huq, N. M., and Cleland, J. 1990. Bangladesh Fertility Survey 1989 (Main Report). Dhaka: National Institute of Population Research and Training Legendre P. Spatial autocorrelation: Trouble or new paradigm? Ecology. 1993;74:1659–1673.
[ { "code": null, "e": 389, "s": 171, "text": "In this article, we will use a Probabilistic Programming library developed for python, pymc3. A first introduction to the efficiency of Bayesian approaches in basic statistics and to pymc3 can be found here and there." }, { "code": null, "e": 734, "s": 389, "text": "Since early 2018, Automated Machine Learning has become one of the trendiest topic in data science. Amazon’s Sagemaker or Google AutoML to mention just a few are now accessible to most Data Scientists, to such an extent that some tend to think exploring and understanding data is not necessary anymore in order to build machine learning models." }, { "code": null, "e": 783, "s": 734, "text": "The promise of AutoML can be summed up this way:" }, { "code": null, "e": 954, "s": 783, "text": "the high degree of automation allows non-experts to make use of machine learning models and techniques without requiring to become an expert in a particular field first.1" }, { "code": null, "e": 1146, "s": 954, "text": "The reasoning is straightforward ; expertise is no longer required, just give data to the AutoML algorithm, and after testing a fixed number of predefined models, it will return the best one." }, { "code": null, "e": 1436, "s": 1146, "text": "But here’s the catch... AutoML algorithms ignore what best means to us, and will merely try to minimize an empirical error. Knowledge and expertise are still required to understand what this error really means, and to what extent it differs from the one we are actually hoping to minimize." }, { "code": null, "e": 1489, "s": 1436, "text": "Given n data points, the empirical error is given by" }, { "code": null, "e": 1608, "s": 1489, "text": "for a particular function fn over all observable values of features xi and target yi where V denotes a loss function.2" }, { "code": null, "e": 1842, "s": 1608, "text": "It is usually computed through a cross-validation or train/test process. Missing some links between covariates and target will generate a bias often leading to under/over-fitting and eventually to a higher test/cross-validated error." }, { "code": null, "e": 1955, "s": 1842, "text": "It is too often, and wrongly, the only one taken into account by data scientists (and always by autoML engines)." }, { "code": null, "e": 2139, "s": 1955, "text": "generalization error(also known as the out-of-sample error) is a measure of how accurately an algorithm is able to predict outcome values for previously unseen data. It is defined by:" }, { "code": null, "e": 2324, "s": 2139, "text": "for a particular function fn over all possible values of features x and target y where V denotes a loss function and ρ(x, y) is the unknown joint probability distribution for x and y.3" }, { "code": null, "e": 2535, "s": 2324, "text": "Obviously, it is usually the one we would prefer to minimize when training our model. Unfortunately, it cannot be computed directly from data, unlike the empirical one which is merely an estimate of the former." }, { "code": null, "e": 2940, "s": 2535, "text": "With enough good quality data, we interchange those. Now imagine only part of the information is available at training time, or that there just isn’t enough data at all, as it is often the case in Machine Learning. Our model will then be trained on a different distribution ρ(x, y) from the one it will be running on later, and as a consequence, the empirical error will diverge from the generalized one." }, { "code": null, "e": 2985, "s": 2940, "text": "Biased data leads to biased empirical error." }, { "code": null, "e": 3285, "s": 2985, "text": "We can already see how much of a problem this is: the empirical error does not estimate the desired quantity anymore, but is the only we can compute from data. We need to make sure it can still be relied on to some extent. This is where human expertise comes into plays and shows its full potential." }, { "code": null, "e": 3529, "s": 3285, "text": "The same way parametric approaches are preferred over non-parametric ones when the relation between variables is clear, knowledge from the field of study compensate the lack of information from the data by explicitly modeling some dependences." }, { "code": null, "e": 3661, "s": 3529, "text": "The better our model can extrapolate from partial or truncated distribution, the closer empirical and generalization error will be." }, { "code": null, "e": 3701, "s": 3661, "text": "β€œCorrelation does not imply causation.”" }, { "code": null, "e": 3984, "s": 3701, "text": "All data scientists have heard this sentence at least once, but it turns out only a few truly realize the implication when it comes to actual modeling. The topic of causality is actually just left out most of the time, sometimes wrongly, sometimes justifiably, but rarely knowingly." }, { "code": null, "e": 4157, "s": 3984, "text": "A confounder is a variable that is causally related to both the covariate and the outcome of interest. As a causal concept, it cannot be described in terms of correlations." }, { "code": null, "e": 4294, "s": 4157, "text": "The error yielded by confounders cannot be fully measured by traditional statistical methods since it is not a statistical error per se." }, { "code": null, "e": 4575, "s": 4294, "text": "One could argue that when the empirical error is low, or even the generalization error; then we shouldn’t care if our model exploits true causality or spurious correlations. It might be true in some cases, but unless we explicitly know why, this situation shouldn’t be overlooked." }, { "code": null, "e": 4798, "s": 4575, "text": "Simpson’s paradox, described by Edward Simpson in 1951 and George Udny Yule in 1903, is a paradox in which a statistical trend appears when data are segmented into separate groups but reverses when the groups are combined." }, { "code": null, "e": 4948, "s": 4798, "text": "It is usually observed in the presence of a confounding variable (represented here by the different colour groups) when causal relations are ignored." }, { "code": null, "e": 5161, "s": 4948, "text": "The impact Simpson’s paradox will have in machine learning is when it comes to decision making, where we are given the choice of which data we should consider to pick an action, the aggregated or the partitioned?" }, { "code": null, "e": 5619, "s": 5161, "text": "Unfortunately the answer usually cannot be inferred from the data itself. Indeed with exact similar values we can have different answers, depending on the causal relationships among the variables. The real source of error lies outside of the data itself and eventually it doesn’t matter how low the test or cross-validation error is. We are not safe from getting making completely wrong decisions unless we are able to correctly model the environment first." }, { "code": null, "e": 5742, "s": 5619, "text": "We will now through a concrete example show how to handle this situation in the concrete case of hierarchical dependences." }, { "code": null, "e": 6190, "s": 5742, "text": "Often data scientists have to deal with geographic data, which have the disadvantage of not being easily exploitable by classic machine learning models. The location feature usually has a really high cardinality and is often unbalanced. However it is intuitive that parameters from models will vary from region to region, depending on local variables, but will still be closely related since they model the same phenomenon across different places." }, { "code": null, "e": 6334, "s": 6190, "text": "We are going to see a way to handle this spatial dependence and thus to minimize all types of error listed above through the following example." }, { "code": null, "e": 6593, "s": 6334, "text": "We consider the problem of estimating the use of contraceptive in Bangladesh, and to this end we use data come from the 1988 Bangladesh Fertility Survey. It consists of a subsample of 1934 women grouped in 60 districts, with variables are defined as follows:" }, { "code": null, "e": 6639, "s": 6593, "text": "DISTRICT: identifying code for each district." }, { "code": null, "e": 6688, "s": 6639, "text": "LC: Number of living children at time of survey." }, { "code": null, "e": 6725, "s": 6688, "text": "AGE: Age of woman at time of survey." }, { "code": null, "e": 6761, "s": 6725, "text": "URBAN: Type of region of residence." }, { "code": null, "e": 6883, "s": 6761, "text": "and we’ll consider 3 logistic Bayesian regressions with different characteristics to model different possible approaches." }, { "code": null, "e": 7140, "s": 6883, "text": "Here we simply obliviate the role of the DISTRICT variable by not using it. The result is a simple logistic regression with only 4 parameters, including the intercept. The location is not seen as a confounder and each region is assumed to behave similarly." }, { "code": null, "e": 7383, "s": 7140, "text": "For each district we fit a different logistic regression, leading to a total of 60 models with 4 parameters each. Even if we assume behaviour to vary from district to district, we don’t take any advantage of the similarities they could share." }, { "code": null, "e": 7729, "s": 7383, "text": "Bayesian hierarchical modelling is a statistical model written in multiple levels that estimates the parameters of the posterior distribution using the Bayesian method. The sub-models combine to form the hierarchical model, and Bayes’ theorem is used to integrate them with the observed data and account for all the uncertainty that is present.4" }, { "code": null, "e": 7956, "s": 7729, "text": "We assume that while Ξ²s are different for each district as in the unpooled case, now the coefficients all share similarity. We can model this by assuming that each individual coefficient comes from a common group distribution:" }, { "code": null, "e": 7961, "s": 7956, "text": "with" }, { "code": null, "e": 8254, "s": 7961, "text": "Though analytically intractable, probabilistic programming allows us to compute the posterior of all our parameters using Markov chain Monte Carlo (MCMC) to sample from the posteriors distributions. Again pymc3 offers an extremely intuitive way to model our network and to compute posteriors!" }, { "code": null, "e": 8333, "s": 8254, "text": "We can also easily compute a graphical representation of our Bayesian network:" }, { "code": null, "e": 8407, "s": 8333, "text": "First of all, let’s try to understand the differences between our models." }, { "code": null, "e": 8565, "s": 8407, "text": "Inspired by https://docs.pymc.io/notebooks/GLM-hierarchical.html, we can visualize the evolution of our regression parameters over the different regressions." }, { "code": null, "e": 8981, "s": 8565, "text": "We display the coefficients of each district’s non-hierarchical posterior mean, hierarchical posterior mean, and pooled posterior mean. The small amount of data available at district level led unpooled posteriors to be spread far out and thus the shrinkage effect is really important, yet differences among mean in the hierarchical model are still significant, as betas vary in order of magnitude between districts." }, { "code": null, "e": 9328, "s": 8981, "text": "We use the Area Under the ROC Curve (AUC) as our error measure for comparing the models. It can be seen as the probability that our models will score a randomly chosen positive class higher than a randomly chosen negative class. It is particularly interesting to us since it has the advantage of not requiring to set a threshold to assign labels." }, { "code": null, "e": 9700, "s": 9328, "text": "We considered 2 test sets in order to measure performances, a stratified by district one and a non-stratified one. The use of a non-stratified test set is more representative of a case where the generalization error will differ significantly from the empirical model error, since features distributions among districts will vary significantly between train and test sets!" }, { "code": null, "e": 9838, "s": 9700, "text": "The measures have been averaged over multiple seeds for the test set sampling in order to be more representative of the real performance." }, { "code": null, "e": 10231, "s": 9838, "text": "β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ β”‚ POOLED β”‚ UNPOOLED β”‚ HIERARCHICAL β”‚β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”‚ Train β”‚ 0.632 β”‚ 0.818 β”‚ 0.726 β”‚β”‚ Stratified Test β”‚ 0.623 β”‚ 0.618 β”‚ 0.668 β”‚β”‚ Unstratified Test β”‚ 0.634 β”‚ 0.603 β”‚ 0.663 β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜" }, { "code": null, "e": 10329, "s": 10231, "text": "The unpooled model strongly overfits as the huge gap between the train and test AUC demonstrates." }, { "code": null, "e": 10416, "s": 10329, "text": "On the other hand, the pooled model is strongly biased and clearly underfits the data." }, { "code": null, "e": 10554, "s": 10416, "text": "Finally, our hierarchical model performed significantly better than the others by taking advantage of parameters geographic similarities." }, { "code": null, "e": 10673, "s": 10554, "text": "The shrinkage effect provided us with an improved statistical power and can also be seen as a smart way to regularize." }, { "code": null, "e": 10997, "s": 10673, "text": "Some districts have extremely few individuals from which to train, and thus the unstratified test error on those gets bigger with the unpooled model. The partial pooling takes into account the similarity between parameters, and provides low density districts with information from others, while keeping their specificities." }, { "code": null, "e": 11223, "s": 10997, "text": "As a result the difference between models is even more significant regarding the unstratified test set, showing us its generalization capacity is greater as performances are almost not affected by the stratification strategy." }, { "code": null, "e": 11368, "s": 11223, "text": "=> Multi-level hierarchical Bayesian models outperform basic approaches when we have multiple sets of measurements we expect to have similarity." }, { "code": null, "e": 11576, "s": 11368, "text": "It would be interesting to compare this Bayesian approach to other classic data preprocessing approaches (different encodings of the district variable) or algorithms (gradient boosting, random forest, etc.)." }, { "code": null, "e": 11775, "s": 11576, "text": "AutoML cannot replace Data Scientists yet as it is not able to distinguish empirical error measures from actual business objectives, nor to model correctly dependences between covariates and target." }, { "code": null, "e": 12099, "s": 11775, "text": "Experts are still required to understand data and model properly the problems. To this end, they have access to a range of mathematics and informatic tools, including pymc3 library and Bayesian hierarchical models, allowing to easily model and compute distributions in the very common case of hierarchically structured data" }, { "code": null, "e": 12258, "s": 12099, "text": "[1]: Wikipedia contributors. β€œAutomated machine learning.” Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 18 Feb. 2020. Web. 1 Mar. 2020." }, { "code": null, "e": 12486, "s": 12258, "text": "[2,3]: Wikipedia contributors. (2020, February 22). Generalization error. In Wikipedia, The Free Encyclopedia. Retrieved 16:40, March 1, 2020, from https://en.wikipedia.org/w/index.php?title=Generalization_error&oldid=942140633" }, { "code": null, "e": 12649, "s": 12486, "text": "[4]: Wikipedia contributors. β€œBayesian hierarchical modeling.” Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 12 Dec. 2019. Web. 1 Mar. 2020." }, { "code": null, "e": 12767, "s": 12649, "text": "Causality: Models, Reasoning, and Inference, Cambridge University Press (2000, 2nd edition 2009). ISBN 0–521–77362–8." }, { "code": null, "e": 12820, "s": 12767, "text": "https://docs.pymc.io/notebooks/GLM-hierarchical.html" }, { "code": null, "e": 12964, "s": 12820, "text": "Huq, N. M., and Cleland, J. 1990. Bangladesh Fertility Survey 1989 (Main Report). Dhaka: National Institute of Population Research and Training" } ]
Apache NiFi - Quick Guide
Apache NiFi is a powerful, easy to use and reliable system to process and distribute data between disparate systems. It is based on Niagara Files technology developed by NSA and then after 8 years donated to Apache Software foundation. It is distributed under Apache License Version 2.0, January 2004. The latest version for Apache NiFi is 1.7.1. Apache NiFi is a real time data ingestion platform, which can transfer and manage data transfer between different sources and destination systems. It supports a wide variety of data formats like logs, geo location data, social feeds, etc. It also supports many protocols like SFTP, HDFS, and KAFKA, etc. This support to wide variety of data sources and protocols making this platform popular in many IT organizations. The general features of Apache NiFi are as follows βˆ’ Apache NiFi provides a web-based user interface, which provides seamless experience between design, control, feedback, and monitoring. Apache NiFi provides a web-based user interface, which provides seamless experience between design, control, feedback, and monitoring. It is highly configurable. This helps users with guaranteed delivery, low latency, high throughput, dynamic prioritization, back pressure and modify flows on runtime. It is highly configurable. This helps users with guaranteed delivery, low latency, high throughput, dynamic prioritization, back pressure and modify flows on runtime. It also provides data provenance module to track and monitor data from the start to the end of the flow. It also provides data provenance module to track and monitor data from the start to the end of the flow. Developers can create their own custom processors and reporting tasks according to their needs. Developers can create their own custom processors and reporting tasks according to their needs. NiFi also provides support to secure protocols like SSL, HTTPS, SSH and other encryptions. NiFi also provides support to secure protocols like SSL, HTTPS, SSH and other encryptions. It also supports user and role management and also can be configured with LDAP for authorization. It also supports user and role management and also can be configured with LDAP for authorization. The key concepts of Apache NiFi are as follows βˆ’ Process Group βˆ’ It is a group of NiFi flows, which helps a userto manage and keep flows in hierarchical manner. Process Group βˆ’ It is a group of NiFi flows, which helps a userto manage and keep flows in hierarchical manner. Flow βˆ’ It is created connecting different processors to transfer and modify data if required from one data source or sources to another destination data sources. Flow βˆ’ It is created connecting different processors to transfer and modify data if required from one data source or sources to another destination data sources. Processor βˆ’ A processor is a java module responsible for either fetching data from sourcing system or storing it in destination system. Other processors are also used to add attributes or change content in flowfile. Processor βˆ’ A processor is a java module responsible for either fetching data from sourcing system or storing it in destination system. Other processors are also used to add attributes or change content in flowfile. Flowfile βˆ’ It is the basic usage of NiFi, which represents the single object of the data picked from source system in NiFi. NiFiprocessormakes changes to flowfile while it moves from the source processor to the destination. Different events like CREATE, CLONE, RECEIVE, etc. are performed on flowfile by different processors in a flow. Flowfile βˆ’ It is the basic usage of NiFi, which represents the single object of the data picked from source system in NiFi. NiFiprocessormakes changes to flowfile while it moves from the source processor to the destination. Different events like CREATE, CLONE, RECEIVE, etc. are performed on flowfile by different processors in a flow. Event βˆ’ Events represent the change in flowfile while traversing through a NiFi Flow. These events are tracked in data provenance. Event βˆ’ Events represent the change in flowfile while traversing through a NiFi Flow. These events are tracked in data provenance. Data provenance βˆ’ It is a repository.It also has a UI, which enables users to check the information about a flowfile and helps in troubleshooting if any issues that arise during the processing of a flowfile. Data provenance βˆ’ It is a repository.It also has a UI, which enables users to check the information about a flowfile and helps in troubleshooting if any issues that arise during the processing of a flowfile. Apache NiFi enables data fetching from remote machines by using SFTP and guarantees data lineage. Apache NiFi enables data fetching from remote machines by using SFTP and guarantees data lineage. Apache NiFi supports clustering, so it can work on multiple nodes with same flow processing different data, which increase the performance of data processing. Apache NiFi supports clustering, so it can work on multiple nodes with same flow processing different data, which increase the performance of data processing. It also provides security policies on user level, process group level and other modules too. It also provides security policies on user level, process group level and other modules too. Its UI can also run on HTTPS, which makes the interaction of users with NiFi secure. Its UI can also run on HTTPS, which makes the interaction of users with NiFi secure. NiFi supports around 188 processors and a user can also create custom plugins to support a wide variety of data systems. NiFi supports around 188 processors and a user can also create custom plugins to support a wide variety of data systems. When node gets disconnected from NiFi cluster while a user is making any changes in it, then the flow.xml becomes invalid.Anode cannot connect back to the cluster unless admin manually copies flow.xml from the connected node. When node gets disconnected from NiFi cluster while a user is making any changes in it, then the flow.xml becomes invalid.Anode cannot connect back to the cluster unless admin manually copies flow.xml from the connected node. Apache NiFi have state persistence issue in case of primary node switch, which sometimes makes processors not able to fetch data from sourcing systems. Apache NiFi have state persistence issue in case of primary node switch, which sometimes makes processors not able to fetch data from sourcing systems. Apache NiFi consist of a web server, flow controller and a processor, which runs on Java Virtual Machine. It also has 3 repositories Flowfile Repository, Content Repository, and Provenance Repository as shown in the figure below. This repository stores the current state and attributes of every flowfile that goes through the data flows of apache NiFi. The default location of this repository is in the root directory of apache NiFi. The location of this repository can be changed by changing the property named "nifi.flowfile.repository.directory". This repository contains all the content present in all the flowfiles of NiFi. Its default directory is also in the root directory of NiFi and it can be changed using "org.apache.nifi.controller.repository.FileSystemRepository" property. This directory uses large space in disk so it is advisable to have enough space in the installation disk. The repository tracks and stores all the events of all the flowfiles that flow in NiFi. There are two provenance repositories - volatile provenance repository (in this repository all the provenance data get lost after restart) and persistent provenance repository. Its default directory is also in the root directory of NiFi and it can be changed using "org.apache.nifi.provenance.PersistentProvenanceRepository" and "org.apache.nifi.provenance.VolatileProvenanceRepositor" property for the respective repositories. In this chapter, we will learn about the environment setup ofApache NiFi. The steps for installation of Apache NiFi are as follows βˆ’ Step 1 βˆ’ Install the current version of Java in your computer. Please set theJAVA_HOME in your machine. You can check the version as shown below: In Windows Operating System (OS) (using command prompt) βˆ’ > java -version In UNIX OS (Using Terminal): $ echo $JAVA_HOME Step 2 βˆ’ DownloadApache NiFi from https://nifi.apache.org/download.html For windows OSdownload ZIP file. For windows OSdownload ZIP file. For UNIX OSdownload TAR file. For UNIX OSdownload TAR file. For docker images,go to the following link https://hub.docker.com/r/apache/nifi/. For docker images,go to the following link https://hub.docker.com/r/apache/nifi/. Step 3 βˆ’ The installation process for Apache NiFi is very easy. The process differs with the OS βˆ’ Windows OS βˆ’ Unzip the zip package and the Apache NiFi is installed. Windows OS βˆ’ Unzip the zip package and the Apache NiFi is installed. UNIX OS βˆ’ Extract tar file in any location and the Logstash is installed. UNIX OS βˆ’ Extract tar file in any location and the Logstash is installed. $tar -xvf nifi-1.6.0-bin.tar.gz Step 4 βˆ’ Open command prompt, go to the bin directory of NiFi. For example, C:\nifi-1.7.1\bin, and execute run-nifi.bat file. C:\nifi-1.7.1\bin>run-nifi.bat Step 5 βˆ’ It will take a few minutes to get the NiFi UI up. A user cancheck nifi-app.log, once NiFi UI is up then, a user can enter http://localhost:8080/nifi/ to access UI. Apache is a web-based platform that can be accessed by a user using web UI. The NiFi UI is very interactive and provides a wide variety of information about NiFi. As shown in the image below, a user can access information about the following attributes βˆ’ Active Threads Total queued data Transmitting Remote Process Groups Not Transmitting Remote Process Groups Running Components Stopped Components Invalid Components Disabled Components Up to date Versioned Process Groups Locally modified Versioned Process Groups Stale Versioned Process Groups Locally modified and Stale Versioned Process Groups Sync failure Versioned Process Groups Apache NiFi UI has the following components βˆ’ User can drag the process icon on the canvas and select the desired processor for the data flow in NiFi. Below icon is dragged to canvas to add the input port into any data flow. Input port is used to get data from the processor, which is not present in that process group. After dragging this icon, NiFi asks to enter the name of the Input port and then it is added to the NiFi canvas. The below icon is dragged to canvas to add the output port into any data flow. The output port is used to transfer data to the processor, which is not present in that process group. After dragging this icon, NiFi asks to enter the name of the Output port and then it is added to the NiFi canvas. A user uses below icon to add process group in the NiFi canvas. After dragging this icon, NiFi asks to enter the name of the Process Group and then it is added to the NiFi canvas. This is used to add Remote process group in NiFi canvas. Funnel is used to transfer the output of a processor to multiple processors. User can use the below icon to add the funnel in a NiFi data flow. This icon is used to add a data flow template to NiFi canvas. This helps to reuse the data flow in the same or different NiFi instances. After dragging, a user can select the templates already added in the NiFi. These are used to add text on NiFi canvas about any component present in NiFi. It offers a range of colors used by a user to add aesthetic sense. Apache NiFi processors are the basic blocks of creating a data flow. Every processor has different functionality, which contributes to the creation of output flowfile. Dataflow shown in the image below is fetching file from one directory using GetFile processor and storing it in another directory using PutFile processor. GetFile process is used to fetch files of a specific format from a specific directory. It also provides other options to user for more control on fetching. We will discuss it in properties section below. Following are the different settings of GetFile processor βˆ’ In the Name setting, a user can define any name for the processors either according to the project or by that, which makes the name more meaningful. A user can enable or disable the processor using this setting. This setting lets a user to add the penalty time duration, in the event of flowfile failure. This setting is used to specify the yield time for processor. In this duration, the process is not scheduled again. This setting is used to specify the log level of that processor. This has a list of check of all the available relationship of that particular process. By checking the boxes, a user can program processor to terminate the flowfile on that event and do not send it further in the flow. These are the following scheduling options offered by the GetFile processor βˆ’ You can either schedule the process on time basis by selecting time driven or a specified CRON string by selecting a CRON driver option. This option is used to define the concurrent task schedule for this processor. A user can define whether to run the processor in all nodes or only in Primary node by using this option. It is used to define the time for time driven strategy or CRON expression for CRON driven strategy. GetFile offers multiple properties as shown in the image below raging compulsory properties like Input directory and file filter to optional properties like Path Filter and Maximum file Size. A user can manage file fetching process using these properties. This Section is used to specify any information about processor. The PutFile processor is used to store the file from the data flow to a specific location. The PutFile processor has the following settings βˆ’ In the Name setting, a user can define any name for the processors either according to the project or by that which makes the name more meaningful. A user can enable or disable the processor using this setting. This setting lets a user add the penalty time duration, in the event of flowfile failure. This setting is used to specify the yield time for processor. In this duration, the process does not get scheduled again. This setting is used to specify the log level of that processor. This settings has a list of check of all the available relationship of that particular process. By checking the boxes, user can program processor to terminate the flowfile on that event and do not send it further in the flow. These are the following scheduling options offered by the PutFile processor βˆ’ You can schedule the process on time basis either by selecting timer driven or a specified CRON string by selecting CRON driver option. There is also an Experimental strategy Event Driven, which will trigger the processor on a specific event. This option is used to define the concurrent task schedule for this processor. A user can define whether to run the processor in all nodes or only in primary node by using this option. It is used to define the time for timer driven strategy or CRON expression for CRON driven strategy. The PutFile processor provides properties like Directory to specify the output directory for the purpose of file transfer and others to manage the transfer as shown in the image below. This Section is used to specify any information about processor. In this chapter, we will discuss process categorization in Apache NiFi. The processors under Data Ingestion category are used to ingest data into the NiFi data flow. These are mainly the starting point of any data flow in apache NiFi. Some of the processors that belong to these categories are GetFile, GetHTTP, GetFTP, GetKAFKA, etc. Routing and Mediation processors are used to route the flowfiles to different processors or data flows according to the information in attributes or content of those flowfiles. These processors are also responsible to control the NiFi data flows. Some of the processors that belong to this category are RouteOnAttribute, RouteOnContent, ControlRate, RouteText, etc. The processors of this Database Access category are capable of selecting or inserting data or executing and preparing other SQL statements from database. These processors mainly use data connection pool controller setting of Apache NiFi. Some of the processors that belong to this category are ExecuteSQL, PutSQL, PutDatabaseRecord, ListDatabaseTables, etc. Attribute Extraction Processors are responsible to extract, analyze, change flowfile attributes processing in the NiFi data flow. Some of the processors that belong to this category are UpdateAttribute, EvaluateJSONPath, ExtractText, AttributesToJSON, etc. System Interaction processors are used to run processes or commands in any operating system. These processors also run scripts in many languages to interact with a variety of systems. Some of the processors that belong to this category are ExecuteScript, ExecuteProcess, ExecuteGroovyScript, ExecuteStreamCommand, etc. Processors that belong to Data Transformation are capable of altering content of the flowfiles. These can be used to fully replace the data of a flowfile normally used when a user has to send flowfile as an HTTP body to invokeHTTP processor. Some of the processors that belong to this category are ReplaceText, JoltTransformJSON, etc. Sending Data Processors are generally the end processor in a data flow. These processors are responsible to store or send data to the destination server. After successful storing or sending the data, these processors DROP the flowfile with success relationship. Some of the processors that belong to this category are PutEmail, PutKafka, PutSFTP, PutFile, PutFTP, etc. These processors are used to split and merge the content present in a flowfile. Some of the processors that belong to this category are SplitText, SplitJson, SplitXml, MergeContent, SplitContent, etc. These processors deal with the HTTP and HTTPS calls. Some of the processors that belong to this category are InvokeHTTP, PostHTTP, ListenHTTP, etc. AWS processors are responsible to interaction with Amazon web services system. Some of the processors that belong to this category are GetSQS, PutSNS, PutS3Object, FetchS3Object, etc. In an Apache NiFi data flow, flowfiles move from one to another processor through connection that gets validated using a relationship between processors. Whenever a connection is created, a developer selects one or more relationships between those processors. As you can see in the above image, the check boxes in black rectangle are relationships. If a developer selects these check boxes then, the flowfile will terminate in that particular processor, when the relationship is success or failure or both. When a processor successfully processes a flowfile like store or fetch data from any datasource without getting any connection, authentication or any other error, then the flowfile goes to success relationship. When a processor is not able to process a flowfile without errors like authentication error or connection problem, etc. then the flowfile goes to a failure relationship. A developer can also transfer the flowfiles to other processors using connections. The developer can select and also load balance it, but load balancing is just released in version 1.8, which will not be covered in this tutorial. As you can see in the above image the connection marked in red have failure relationship, which means all flowfiles with errors will go to the processor in left and respectively all the flowfiles without errors will be transferred to the connection marked in green. Let us now proceed with the other relationships. This relationship is met, when a Flowfile could not be fetched from the remote server due to a communications failure. Any Flowfile for which we receive a β€˜Not Found’ message from the remote server will move to not.found relationship. When NiFi unable to fetch a flowfile from the remote server due to insufficient permission, it will move through this relationship. A flowfile is a basic processing entity in Apache NiFi. It contains data contents and attributes, which are used by NiFi processors to process data. The file content normally contains the data fetched from source systems. The most common attributes of an Apache NiFi FlowFile are βˆ’ This stands for Universally Unique Identifier, which is a unique identity of a flowfile generated by NiFi. This attribute contains the filename of that flowfile and it should not contain any directory structure. It contains the size of an Apache NiFi FlowFile. It specifies the MIME Type of this FlowFile. This attribute contains the relative path of a file to which a flowfile belongs and does not contain the file name. The Apache NiFi data flow connection has a queuing system to handle the large amount of data inflow. These queues can handle very large amount of FlowFiles to let the processor process them serially. The queue in the above image has 1 flowfile transferred through success relationship. A user can check the flowfile by selecting the List queue option in the drop down list. In case of any overload or error, a user can also clear the queue by selecting the empty queue option and then the user can restart the flow to get those files again in the data flow. The list of flowfiles in a queue, consist of position, UUID, Filename, File size, Queue Duration, and Lineage Duration. A user can see all the attributes and content of a flowfile by clicking the info icon present at the first column of the flowfile list. In Apache NiFi, a user can maintain different data flows in different process groups. These groups can be based on different projects or the organizations, which Apache NiFi instance supports. The fourth symbol in the menu at the top of the NiFi UI as shown in the above picture is used to add a process group in the NiFi canvas. The process group named β€œTutorialspoint.com_ProcessGroup” contains a data flow with four processors currently in stop stage as you can see in the above picture. Process groups can be created in hierarchical manner to manage the data flows in better structure, which is easy to understand. In the footer of NiFi UI, you can see the process groups and can go back to the top of the process group a user is currently present in. To see the full list of process groups present in NiFi, a user can go to the summary by using the menu present in the left top side of the NiFi UI. In summary, there is process groups tab where all the process groups are listed with parameters like Version State, Transferred/Size, In/Size, Read/Write, Out/Size, etc. as shown in the below picture. Apache NiFi offers labels to enable a developer to write information about the components present in the NiFI canvas. The leftmost icon in the top menu of NiFi UI is used to add the label in NiFi canvas. A developer can change the color of the label and the size of the text with a right-click on the label and choose the appropriate option from the menu. Apache NiFi is highly configurable platform. The nifi.properties file in conf directory contains most of the configuration. The commonly used properties of Apache NiFi are as follows βˆ’ This section contains the properties, which are compulsory to run a NiFi instance. These properties are used to store the state of the components helpful to start the processing, where components left after a restart and in the next schedule running. Let us now look into the important details of the FlowFile repository βˆ’ Apache NiFi offers support to multiple tools like ambari, zookeeper for administration purposes. NiFi also provides configuration in nifi.properties file to set up HTTPS and other things for administrators. NiFi itself does not handle voting process in cluster. This means when a cluster is created, all the nodes are primary and coordinator. So, zookeeper is configured to manage the voting of primary node and coordinator. The nifi.properties file contains some properties to setup zookeeper. To use NiFi over HTTPS, administrators have to generate keystore and truststore and set some properties in the nifi.properties file. The TLS toolkit can be used to generate all the necessary keys to enable HTTPS in apache NiFi. There are some other properties, which are used by administrators to manage the NiFi and for its service continuity. Apache NiFi offers a large number of components to help developers to create data flows for any type of protocols or data sources. To create a flow, a developer drags the components from menu bar to canvas and connects them by clicking and dragging the mouse from one component to other. Generally, a NiFi has a listener component at the starting of the flow like getfile, which gets the data from source system. On the other end of there is a transmitter component like putfile and there are components in between, which process the data. For example, let create a flow, which takes an empty file from one directory and add some text in that file and put it in another directory. To begin with, drag the processor icon to the NiFi canvas and select GetFile processor from the list. To begin with, drag the processor icon to the NiFi canvas and select GetFile processor from the list. Create an input directory like c:\inputdir. Create an input directory like c:\inputdir. Right-click on the processor and select configure and in properties tab add Input Directory (c:\inputdir) and click apply and go back to canvas. Right-click on the processor and select configure and in properties tab add Input Directory (c:\inputdir) and click apply and go back to canvas. Drag the processor icon to the canvas and select the ReplaceText processor from the list. Drag the processor icon to the canvas and select the ReplaceText processor from the list. Right-click on the processor and select configure. In the properties tab, add some text like β€œHello tutorialspoint.com” in the textbox of Replacement Value and click apply. Right-click on the processor and select configure. In the properties tab, add some text like β€œHello tutorialspoint.com” in the textbox of Replacement Value and click apply. Go to settings tab, check the failure checkbox at right hand side, and then go back to the canvas. Go to settings tab, check the failure checkbox at right hand side, and then go back to the canvas. Connect GetFIle processor to ReplaceText on success relationship. Connect GetFIle processor to ReplaceText on success relationship. Drag the processor icon to the canvas and select the PutFile processor from the list. Drag the processor icon to the canvas and select the PutFile processor from the list. Create an output directory like c:\outputdir. Create an output directory like c:\outputdir. Right-click on the processor and select configure. In the properties tab, add Directory (c:\outputdir) and click apply and go back to canvas. Right-click on the processor and select configure. In the properties tab, add Directory (c:\outputdir) and click apply and go back to canvas. Go to settings tab and check the failure and success checkbox at right hand side and then go back to the canvas. Go to settings tab and check the failure and success checkbox at right hand side and then go back to the canvas. Connect the ReplaceText processor to PutFile on success relationship. Connect the ReplaceText processor to PutFile on success relationship. Now start the flow and add an empty file in input directory and you will see that, it will move to output directory and the text will be added to the file. Now start the flow and add an empty file in input directory and you will see that, it will move to output directory and the text will be added to the file. By following the above steps, developers can choose any processor and other NiFi component to create suitable flow for their organisation or client. Apache NiFi offers the concept of Templates, which makes it easier to reuse and distribute the NiFi flows. The flows can be used by other developers or in other NiFi clusters. It also helps NiFi developers to share their work in repositories like GitHub. Let us create a template for the flow, which we created in chapter no 15 β€œApache NiFi - Creating Flows”. Select all the components of the flow using shift key and then click on the create template icon at the left hand side of the NiFi canvas. You can also see a tool box as shown in the above image. Click on the icon create template marked in blue as in the above picture. Enter the name for the template. A developer can also add description, which is optional. Then go to the NiFi templates option in the menu present at the top right hand corner of NiFi UI as show in the picture below. Now click the download icon (present at the right hand side in the list) of the template, you want to download. An XML file with the template name will get downloaded. To use a template in NiFi, a developer will have to upload its xml file to NiFi using UI. There is an Upload Template icon (marked with blue in below image) beside Create Template icon click on that and browse the xml. In the top toolbar of NiFi UI, the template icon is before the label icon. The icon is marked in blue as shown in the picture below. Drag the template icon and choose the template from the drop down list and click add. It will add the template to NiFi canvas. NiFi offers a large number of API, which helps developers to make changes and get information of NiFi from any other tool or custom developed applications. In this tutorial, we will use postman app in google chrome to explain some examples. To add postmantoyour Google Chrome, go to the below mentioned URL and click add to chrome button. You will now see a new app added toyour Google Chrome. chrome web store The current version of NiFi rest API is 1.8.0 and the documentation is present in the below mentioned URL. https://nifi.apache.org/docs/nifi-docs/rest-api/index.html Following are the most used NiFi rest API Modules βˆ’ http://<nifi url>:<nifi port>/nifi-api/<api-path> http://<nifi url>:<nifi port>/nifi-api/<api-path> In case HTTPS is enabled https://<nifi url>:<nifi port>/nifi-api/<api-path> In case HTTPS is enabled https://<nifi url>:<nifi port>/nifi-api/<api-path> Let us now consider an example and run on postman to get the details about the running NiFi instance. GET http://localhost:8080/nifi-api/flow/about { "about": { "title": "NiFi", "version": "1.7.1", "uri": "http://localhost:8080/nifi-api/", "contentViewerUrl": "../nifi-content-viewer/", "timezone": "SGT", "buildTag": "nifi-1.7.1-RC1", "buildTimestamp": "07/12/2018 12:54:43 SGT" } } Apache NiFi logs and store every information about the events occur on the ingested data in the flow. Data provenance repository stores this information and provides UI to search this event information. Data provenance can be accessed for full NiFi level and processor level also. The following table lists down the different fields in the NiFi Data Provenance event list have following fields βˆ’ To get more information about the event, a user can click on the information icon present in the first column of the NiFi Data Provenance UI. There are some properties in nifi.properties file, which are used to manage NiFi Data Provenance repository. In Apache NiFi, there are multiple ways to monitor the different statistics of the system like errors, memory usage, CPU usage, Data Flow statistics, etc. We will discuss the most popular ones in this tutorial. In this section, we will learn more about in built monitoring in Apache NiFi. The bulletin board shows the latest ERROR and WARNING getting generated by NiFi processors in real time. To access the bulletin board, a user will have to go the right hand drop down menu and select the Bulletin Board option. It refreshes automatically and a user can disable it also. A user can also navigate to the actual processor by double-clicking the error. A user can also filter the bulletins by working out with the following βˆ’ by message by name by id by group id To monitor the Events occurring on any specific processor or throughout NiFi, a user can access the Data provenance from the same menu as the bulletin board. A user can also filter the events in data provenance repository by working out with the following fields βˆ’ by component name by component type by type Apache NiFi summary also can be accessed from the same menu as the bulletin board. This UI contains information about all the components of that particular NiFi instance or cluster. They can be filtered by name, by type or by URI. There are different tabs for different component types. Following are the components, which can be monitored in the NiFi summary UI βˆ’ Processors Input ports Output ports Remote process groups Connections Process groups In this UI, there is a link at the bottom right hand side named system diagnostics to check the JVM statistics. Apache NiFi provides multiple reporting tasks to support external monitoring systems like Ambari, Grafana, etc. A developer can create a custom reporting task or can configure the inbuilt ones to send the metrics of NiFi to the externals monitoring systems. The following table lists down the reporting tasks offered by NiFi 1.7.1. There is an API named system diagnostics, which can be used to monitor the NiFI stats in any custom developed application. Let us check the API in postman. http://localhost:8080/nifi-api/system-diagnostics { "systemDiagnostics": { "aggregateSnapshot": { "totalNonHeap": "183.89 MB", "totalNonHeapBytes": 192819200, "usedNonHeap": "173.47 MB", "usedNonHeapBytes": 181894560, "freeNonHeap": "10.42 MB", "freeNonHeapBytes": 10924640, "maxNonHeap": "-1 bytes", "maxNonHeapBytes": -1, "totalHeap": "512 MB", "totalHeapBytes": 536870912, "usedHeap": "273.37 MB", "usedHeapBytes": 286652264, "freeHeap": "238.63 MB", "freeHeapBytes": 250218648, "maxHeap": "512 MB", "maxHeapBytes": 536870912, "heapUtilization": "53.0%", "availableProcessors": 4, "processorLoadAverage": -1, "totalThreads": 71, "daemonThreads": 31, "uptime": "17:30:35.277", "flowFileRepositoryStorageUsage": { "freeSpace": "286.93 GB", "totalSpace": "464.78 GB", "usedSpace": "177.85 GB", "freeSpaceBytes": 308090789888, "totalSpaceBytes": 499057160192, "usedSpaceBytes": 190966370304, "utilization": "38.0%" }, "contentRepositoryStorageUsage": [ { "identifier": "default", "freeSpace": "286.93 GB", "totalSpace": "464.78 GB", "usedSpace": "177.85 GB", "freeSpaceBytes": 308090789888, "totalSpaceBytes": 499057160192, "usedSpaceBytes": 190966370304, "utilization": "38.0%" } ], "provenanceRepositoryStorageUsage": [ { "identifier": "default", "freeSpace": "286.93 GB", "totalSpace": "464.78 GB", "usedSpace": "177.85 GB", "freeSpaceBytes": 308090789888, "totalSpaceBytes": 499057160192, "usedSpaceBytes": 190966370304, "utilization": "38.0%" } ], "garbageCollection": [ { "name": "G1 Young Generation", "collectionCount": 344, "collectionTime": "00:00:06.239", "collectionMillis": 6239 }, { "name": "G1 Old Generation", "collectionCount": 0, "collectionTime": "00:00:00.000", "collectionMillis": 0 } ], "statsLastRefreshed": "09:30:20 SGT", "versionInfo": { "niFiVersion": "1.7.1", "javaVendor": "Oracle Corporation", "javaVersion": "1.8.0_151", "osName": "Windows 7", "osVersion": "6.1", "osArchitecture": "amd64", "buildTag": "nifi-1.7.1-RC1", "buildTimestamp": "07/12/2018 12:54:43 SGT" } } } } Before starting the upgrade of Apache NiFi, read the release notes to know about the changes and additions. A user needs to evaluate the impact of these additions and changes in his/her current NiFi installation. Below is the link to get the release notes for the new releases of Apache NiFi. https://cwiki.apache.org/confluence/display/NIFI/Release+Notes In a cluster setup, a user needs to upgrade NiFi installation of every Node in a cluster. Follow the steps given below to upgrade the Apache NiFi. Backup all the custom NARs present in your current NiFi or lib or any other folder. Backup all the custom NARs present in your current NiFi or lib or any other folder. Download the new version of Apache NiFi. Below is the link to download the source and binaries of latest NiFi version. https://nifi.apache.org/download.html Download the new version of Apache NiFi. Below is the link to download the source and binaries of latest NiFi version. https://nifi.apache.org/download.html Create a new directory in the same installation directory of current NiFi and extract the new version of Apache NiFi. Create a new directory in the same installation directory of current NiFi and extract the new version of Apache NiFi. Stop the NiFi gracefully. First stop all the processors and let all the flowfiles present in the flow get processed. Once, no more flowfile is there, stop the NiFi. Stop the NiFi gracefully. First stop all the processors and let all the flowfiles present in the flow get processed. Once, no more flowfile is there, stop the NiFi. Copy the configuration of authorizers.xml from current NiFi installation to the new version. Copy the configuration of authorizers.xml from current NiFi installation to the new version. Update the values in bootstrap-notification-services.xml, and bootstrap.conf of new NiFi version from the current one. Update the values in bootstrap-notification-services.xml, and bootstrap.conf of new NiFi version from the current one. Add the custom logging from logback.xml to the new NiFi installation. Add the custom logging from logback.xml to the new NiFi installation. Configure the login identity provider in login-identity-providers.xml from the current version. Configure the login identity provider in login-identity-providers.xml from the current version. Update all the properties in nifi.properties of the new NiFi installation from current version. Update all the properties in nifi.properties of the new NiFi installation from current version. Please make sure that the group and user of new version is same as the current version, to avoid any permission denied errors. Please make sure that the group and user of new version is same as the current version, to avoid any permission denied errors. Copy the configuration from state-management.xml of current version to the new version. Copy the configuration from state-management.xml of current version to the new version. Copy the contents of the following directories from current version of NiFi installation to the same directories in the new version. ./conf/flow.xml.gz Also flow.xml.gz from the archive directory. For provenance and content repositories change the values in nifi. properties file to the current repositories. copy state from ./state/local or change in nifi.properties if any other external directory is specified. Copy the contents of the following directories from current version of NiFi installation to the same directories in the new version. ./conf/flow.xml.gz ./conf/flow.xml.gz Also flow.xml.gz from the archive directory. Also flow.xml.gz from the archive directory. For provenance and content repositories change the values in nifi. properties file to the current repositories. For provenance and content repositories change the values in nifi. properties file to the current repositories. copy state from ./state/local or change in nifi.properties if any other external directory is specified. copy state from ./state/local or change in nifi.properties if any other external directory is specified. Recheck all the changes performed and check if they have an impact on any new changes added in the new NiFi version. If there is any impact, check for the solutions. Recheck all the changes performed and check if they have an impact on any new changes added in the new NiFi version. If there is any impact, check for the solutions. Start all the NiFi nodes and verify if all the flows are working correctly and repositories are storing data and Ui is retrieving it with any errors. Start all the NiFi nodes and verify if all the flows are working correctly and repositories are storing data and Ui is retrieving it with any errors. Monitor bulletins for some time to check for any new errors. Monitor bulletins for some time to check for any new errors. If the new version is working correctly, then the current version can be archived and deleted from the directories. If the new version is working correctly, then the current version can be archived and deleted from the directories. Apache NiFi Remote Process Group or RPG enables flow to direct the FlowFiles in a flow to different NiFi instances using Site-to-Site protocol. As of version 1.7.1, NiFi does not offer balanced relationships, so RPG is used for load balancing in a NiFi data flow. A developer can add the RPG from the top toolbar of NiFi UI by dragging the icon as shown in the above picture to canvas. To configure an RPG, a Developer has to add the following fields βˆ’ A developer needs to enable it, before using it like we start processors before using them. Apache NiFi offers shared services, which can be shared by processors and reporting task is called controller settings. These are like Database connection pool, which can be used by processors accessing same database. To access the controller settings, use the drop down menu at the right top corner of NiFi UI as shown in the below image. There are many controller settings offered by Apache NiFi, we will discuss a commonly used one and how we set it up in NiFi. Add the plus sign in the Nifi Settings page after clicking the Controller settings option. Then select the DBCPConnectionPool from the list of controller settings. DBCPConnectionPool will be added in the main NiFi settings page as shown in the below image. It contains the following information about the controller setting:Name Type Bundle State Scope Configure and delete icon Click on the configure icon and fill the required fields. The fields are listed down in the table below βˆ’ To stop or configure a controller setting, first all the attached NiFi components should be stopped. NiFi also adds scope in controller settings to manage the configuration of it. Therefore, only the ones which shared the same settings will not get impacted and will use the same controller settings. Apache NiFi reporting tasks are similar to the controller services, which run in the background and send or log the statistics of NiFi instance. NiFi reporting task can also be accessed from the same page as controller settings, but in a different tab. To add a reporting task, a developer needs to click on the plus button present at the top right hand side of the reporting tasks page. These reporting tasks are mainly used for monitoring the activities of a NiFi instance, in either the bulletins or the provenance. Mainly these reporting tasks uses Site-to-Site to transport the NiFi statistics data to other node or external system. Let us now add a configured reporting task for more understanding. This reporting task is used to generate bulletins, when a memory pool crosses specified percentage. Follow these steps to configure the MonitorMemory reporting task βˆ’ Add in the plus sign and search for MonitorMemory in the list. Add in the plus sign and search for MonitorMemory in the list. Select MonitorMemory and click on ADD. Select MonitorMemory and click on ADD. Once it is added in the main page of reporting tasks main page, click on the configure icon. Once it is added in the main page of reporting tasks main page, click on the configure icon. In the properties tab, select the memory pool, which you want to monitor. In the properties tab, select the memory pool, which you want to monitor. Select the percentage after which you want bulletins to alert the users. Select the percentage after which you want bulletins to alert the users. Start the reporting task. Start the reporting task. Apache NiFi is an open source platform and gives developers the options to add their custom processor in the NiFi library. Follow these steps to create a custom processor. Download Maven latest version from the link given below. https://maven.apache.org/download.cgi Download Maven latest version from the link given below. https://maven.apache.org/download.cgi Add an environment variable named M2_HOME and set value as the installation directory of maven. Add an environment variable named M2_HOME and set value as the installation directory of maven. Download Eclipse IDE from the below link. https://www.eclipse.org/downloads/download.php Download Eclipse IDE from the below link. https://www.eclipse.org/downloads/download.php Open command prompt and execute Maven Archetype command. Open command prompt and execute Maven Archetype command. > mvn archetype:generate Search for the nifi type in the archetype projects. Search for the nifi type in the archetype projects. Select org.apache.nifi:nifi-processor-bundle-archetype project. Select org.apache.nifi:nifi-processor-bundle-archetype project. Then from the list of versions select the latest version i.e. 1.7.1 for this tutorial. Then from the list of versions select the latest version i.e. 1.7.1 for this tutorial. Enter the groupId, artifactId, version, package, and artifactBaseName etc. Enter the groupId, artifactId, version, package, and artifactBaseName etc. Then a maven project will be created having to directories. nifi-<artifactBaseName>-processors nifi-<artifactBaseName>-nar Then a maven project will be created having to directories. nifi-<artifactBaseName>-processors nifi-<artifactBaseName>-processors nifi-<artifactBaseName>-nar nifi-<artifactBaseName>-nar Run the below command in nifi-<artifactBaseName>-processors directory to add the project in the eclipse. Run the below command in nifi-<artifactBaseName>-processors directory to add the project in the eclipse. mvn install eclipse:eclipse Open eclipse and select import from the file menu. Open eclipse and select import from the file menu. Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName>-processors directory in eclipse. Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName>-processors directory in eclipse. Add your code in public void onTrigger(ProcessContext context, ProcessSession session) function, which runs when ever a processor is scheduled to run. Add your code in public void onTrigger(ProcessContext context, ProcessSession session) function, which runs when ever a processor is scheduled to run. Then package the code to a NAR file by running the below mentioned command. Then package the code to a NAR file by running the below mentioned command. mvn clean install A NAR file will be created at nifi--nar/target directory. A NAR file will be created at nifi--nar/target directory. Copy the NAR file to the lib folder of Apache NiFi and restart the NiFi. Copy the NAR file to the lib folder of Apache NiFi and restart the NiFi. After successful restart of NiFi, check the processor list for the new custom processor. After successful restart of NiFi, check the processor list for the new custom processor. For any errors, check ./logs/nifi.log file. For any errors, check ./logs/nifi.log file. Apache NiFi is an open source platform and gives developers the options to add their custom controllers service in Apache NiFi. The steps and tools are almost the same as used to create a custom processor. Open command prompt and execute Maven Archetype command. Open command prompt and execute Maven Archetype command. > mvn archetype:generate Search for the nifi type in the archetype projects. Search for the nifi type in the archetype projects. Select org.apache.nifi:nifi-service-bundle-archetype project. Select org.apache.nifi:nifi-service-bundle-archetype project. Then from the list of versions, select the latest version – 1.7.1 for this tutorial. Then from the list of versions, select the latest version – 1.7.1 for this tutorial. Enter the groupId, artifactId, version, package, and artifactBaseName, etc. Enter the groupId, artifactId, version, package, and artifactBaseName, etc. A maven project will be created having directories. nifi-<artifactBaseName> nifi-<artifactBaseName>-nar nifi-<artifactBaseName>-api nifi-<artifactBaseName>-api-nar A maven project will be created having directories. nifi-<artifactBaseName> nifi-<artifactBaseName> nifi-<artifactBaseName>-nar nifi-<artifactBaseName>-nar nifi-<artifactBaseName>-api nifi-<artifactBaseName>-api nifi-<artifactBaseName>-api-nar nifi-<artifactBaseName>-api-nar Run the below command in nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories to add these two projects in the eclipse. mvn install eclipse:eclipse Run the below command in nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories to add these two projects in the eclipse. mvn install eclipse:eclipse mvn install eclipse:eclipse Open eclipse and select import from the file menu. Open eclipse and select import from the file menu. Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories in eclipse. Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories in eclipse. Add your code in the source files. Add your code in the source files. Then package the code to a NAR file by running the below mentioned command. mvn clean install Then package the code to a NAR file by running the below mentioned command. mvn clean install mvn clean install Two NAR files will be created in each nifi-<artifactBaseName>/target and nifi-<artifactBaseName>-api/target directory. Two NAR files will be created in each nifi-<artifactBaseName>/target and nifi-<artifactBaseName>-api/target directory. Copy these NAR files to the lib folder of Apache NiFi and restart the NiFi. Copy these NAR files to the lib folder of Apache NiFi and restart the NiFi. After successful restart of NiFi, check the processor list for the new custom processor. After successful restart of NiFi, check the processor list for the new custom processor. For any errors, check ./logs/nifi.log file. For any errors, check ./logs/nifi.log file. Apache NiFi uses logback library to handle its logging. There is a file logback.xml present in the conf directory of NiFi, which is used to configure the logging in NiFi. The logs are generated in logs folder of NiFi and the log files are as described below. This is the main log file of nifi, which logs all the activities of apache NiFi application ranging from NAR files loading to the run time errors or bulletins encountered by NiFi components. Below is the default appender in logback.xml file for nifi-app.log file. <appender name="APP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-app.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <fileNamePattern> ${org.apache.nifi.bootstrap.config.log.dir}/ nifi-app_%d{yyyy-MM-dd_HH}.%i.log </fileNamePattern> <maxFileSize>100MB</maxFileSize> <maxHistory>30</maxHistory> </rollingPolicy> <immediateFlush>true</immediateFlush> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{40} %msg%n</pattern> </encoder> </appender> The appender name is APP_FILE, and the class is RollingFileAppender, which means logger is using rollback policy. By default, the max file size is 100 MB and can be changed to the required size. The maximum retention for APP_FILE is 30 log files and can be changed as per the user requirement. This log contains the user events like web security, web api config, user authorization, etc. Below is the appender for nifi-user.log in logback.xml file. <appender name="USER_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-user.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern> ${org.apache.nifi.bootstrap.config.log.dir}/ nifi-user_%d.log </fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{40} %msg%n</pattern> </encoder> </appender> The appender name is USER_FILE. It follows the rollover policy. The maximum retention period for USER_FILE is 30 log files. Below is the default loggers for USER_FILE appender present in nifi-user.log. <logger name="org.apache.nifi.web.security" level="INFO" additivity="false"> <appender-ref ref="USER_FILE"/> </logger> <logger name="org.apache.nifi.web.api.config" level="INFO" additivity="false"> <appender-ref ref="USER_FILE"/> </logger> <logger name="org.apache.nifi.authorization" level="INFO" additivity="false"> <appender-ref ref="USER_FILE"/> </logger> <logger name="org.apache.nifi.cluster.authorization" level="INFO" additivity="false"> <appender-ref ref="USER_FILE"/> </logger> <logger name="org.apache.nifi.web.filter.RequestLogger" level="INFO" additivity="false"> <appender-ref ref="USER_FILE"/> </logger> This log contains the bootstrap logs, apache NiFi’s standard output (all system.out written in the code mainly for debugging), and standard error (all system.err written in the code). Below is the default appender for the nifi-bootstrap.log in logback.log. <appender name="BOOTSTRAP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern> ${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap_%d.log </fileNamePattern> <maxHistory>5</maxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{40} %msg%n</pattern> </encoder> </appender> nifi-bootstrap.log file,s appender name is BOOTSTRAP_FILE, which also follows rollback policy. The maximum retention for BOOTSTRAP_FILE appender is 5 log files. Below is the default loggers for nifi-bootstrap.log file. <logger name="org.apache.nifi.bootstrap" level="INFO" additivity="false"> <appender-ref ref="BOOTSTRAP_FILE" /> </logger> <logger name="org.apache.nifi.bootstrap.Command" level="INFO" additivity="false"> <appender-ref ref="CONSOLE" /> <appender-ref ref="BOOTSTRAP_FILE" /> </logger> <logger name="org.apache.nifi.StdOut" level="INFO" additivity="false"> <appender-ref ref="BOOTSTRAP_FILE" /> </logger> <logger name="org.apache.nifi.StdErr" level="ERROR" additivity="false"> <appender-ref ref="BOOTSTRAP_FILE" /> </logger> 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2665, "s": 2318, "text": "Apache NiFi is a powerful, easy to use and reliable system to process and distribute data between disparate systems. It is based on Niagara Files technology developed by NSA and then after 8 years donated to Apache Software foundation. It is distributed under Apache License Version 2.0, January 2004. The latest version for Apache NiFi is 1.7.1." }, { "code": null, "e": 3083, "s": 2665, "text": "Apache NiFi is a real time data ingestion platform, which can transfer and manage data transfer between different sources and destination systems. It supports a wide variety of data formats like logs, geo location data, social feeds, etc. It also supports many protocols like SFTP, HDFS, and KAFKA, etc. This support to wide variety of data sources and protocols making this platform popular in many IT organizations." }, { "code": null, "e": 3136, "s": 3083, "text": "The general features of Apache NiFi are as follows βˆ’" }, { "code": null, "e": 3271, "s": 3136, "text": "Apache NiFi provides a web-based user interface, which provides seamless experience between design, control, feedback, and monitoring." }, { "code": null, "e": 3406, "s": 3271, "text": "Apache NiFi provides a web-based user interface, which provides seamless experience between design, control, feedback, and monitoring." }, { "code": null, "e": 3573, "s": 3406, "text": "It is highly configurable. This helps users with guaranteed delivery, low latency, high throughput, dynamic prioritization, back pressure and modify flows on runtime." }, { "code": null, "e": 3740, "s": 3573, "text": "It is highly configurable. This helps users with guaranteed delivery, low latency, high throughput, dynamic prioritization, back pressure and modify flows on runtime." }, { "code": null, "e": 3845, "s": 3740, "text": "It also provides data provenance module to track and monitor data from the start to the end of the flow." }, { "code": null, "e": 3950, "s": 3845, "text": "It also provides data provenance module to track and monitor data from the start to the end of the flow." }, { "code": null, "e": 4046, "s": 3950, "text": "Developers can create their own custom processors and reporting tasks according to their needs." }, { "code": null, "e": 4142, "s": 4046, "text": "Developers can create their own custom processors and reporting tasks according to their needs." }, { "code": null, "e": 4233, "s": 4142, "text": "NiFi also provides support to secure protocols like SSL, HTTPS, SSH and other encryptions." }, { "code": null, "e": 4324, "s": 4233, "text": "NiFi also provides support to secure protocols like SSL, HTTPS, SSH and other encryptions." }, { "code": null, "e": 4422, "s": 4324, "text": "It also supports user and role management and also can be configured with LDAP for authorization." }, { "code": null, "e": 4520, "s": 4422, "text": "It also supports user and role management and also can be configured with LDAP for authorization." }, { "code": null, "e": 4569, "s": 4520, "text": "The key concepts of Apache NiFi are as follows βˆ’" }, { "code": null, "e": 4681, "s": 4569, "text": "Process Group βˆ’ It is a group of NiFi flows, which helps a userto manage and keep flows in hierarchical manner." }, { "code": null, "e": 4793, "s": 4681, "text": "Process Group βˆ’ It is a group of NiFi flows, which helps a userto manage and keep flows in hierarchical manner." }, { "code": null, "e": 4955, "s": 4793, "text": "Flow βˆ’ It is created connecting different processors to transfer and modify data if required from one data source or sources to another destination data sources." }, { "code": null, "e": 5117, "s": 4955, "text": "Flow βˆ’ It is created connecting different processors to transfer and modify data if required from one data source or sources to another destination data sources." }, { "code": null, "e": 5334, "s": 5117, "text": "Processor βˆ’ A processor is a java module responsible for either fetching data from sourcing system or storing it in destination system. Other processors are also used to add attributes or change content in flowfile." }, { "code": null, "e": 5551, "s": 5334, "text": "Processor βˆ’ A processor is a java module responsible for either fetching data from sourcing system or storing it in destination system. Other processors are also used to add attributes or change content in flowfile." }, { "code": null, "e": 5887, "s": 5551, "text": "Flowfile βˆ’ It is the basic usage of NiFi, which represents the single object of the data picked from source system in NiFi. NiFiprocessormakes changes to flowfile while it moves from the source processor to the destination. Different events like CREATE, CLONE, RECEIVE, etc. are performed on flowfile by different processors in a flow." }, { "code": null, "e": 6223, "s": 5887, "text": "Flowfile βˆ’ It is the basic usage of NiFi, which represents the single object of the data picked from source system in NiFi. NiFiprocessormakes changes to flowfile while it moves from the source processor to the destination. Different events like CREATE, CLONE, RECEIVE, etc. are performed on flowfile by different processors in a flow." }, { "code": null, "e": 6354, "s": 6223, "text": "Event βˆ’ Events represent the change in flowfile while traversing through a NiFi Flow. These events are tracked in data provenance." }, { "code": null, "e": 6485, "s": 6354, "text": "Event βˆ’ Events represent the change in flowfile while traversing through a NiFi Flow. These events are tracked in data provenance." }, { "code": null, "e": 6693, "s": 6485, "text": "Data provenance βˆ’ It is a repository.It also has a UI, which enables users to check the information about a flowfile and helps in troubleshooting if any issues that arise during the processing of a flowfile." }, { "code": null, "e": 6901, "s": 6693, "text": "Data provenance βˆ’ It is a repository.It also has a UI, which enables users to check the information about a flowfile and helps in troubleshooting if any issues that arise during the processing of a flowfile." }, { "code": null, "e": 6999, "s": 6901, "text": "Apache NiFi enables data fetching from remote machines by using SFTP and guarantees data lineage." }, { "code": null, "e": 7097, "s": 6999, "text": "Apache NiFi enables data fetching from remote machines by using SFTP and guarantees data lineage." }, { "code": null, "e": 7256, "s": 7097, "text": "Apache NiFi supports clustering, so it can work on multiple nodes with same flow processing different data, which increase the performance of data processing." }, { "code": null, "e": 7415, "s": 7256, "text": "Apache NiFi supports clustering, so it can work on multiple nodes with same flow processing different data, which increase the performance of data processing." }, { "code": null, "e": 7508, "s": 7415, "text": "It also provides security policies on user level, process group level and other modules too." }, { "code": null, "e": 7601, "s": 7508, "text": "It also provides security policies on user level, process group level and other modules too." }, { "code": null, "e": 7686, "s": 7601, "text": "Its UI can also run on HTTPS, which makes the interaction of users with NiFi secure." }, { "code": null, "e": 7771, "s": 7686, "text": "Its UI can also run on HTTPS, which makes the interaction of users with NiFi secure." }, { "code": null, "e": 7892, "s": 7771, "text": "NiFi supports around 188 processors and a user can also create custom plugins to support a wide variety of data systems." }, { "code": null, "e": 8013, "s": 7892, "text": "NiFi supports around 188 processors and a user can also create custom plugins to support a wide variety of data systems." }, { "code": null, "e": 8239, "s": 8013, "text": "When node gets disconnected from NiFi cluster while a user is making any changes in it, then the flow.xml becomes invalid.Anode cannot connect back to the cluster unless admin manually copies flow.xml from the connected node." }, { "code": null, "e": 8465, "s": 8239, "text": "When node gets disconnected from NiFi cluster while a user is making any changes in it, then the flow.xml becomes invalid.Anode cannot connect back to the cluster unless admin manually copies flow.xml from the connected node." }, { "code": null, "e": 8617, "s": 8465, "text": "Apache NiFi have state persistence issue in case of primary node switch, which sometimes makes processors not able to fetch data from sourcing systems." }, { "code": null, "e": 8769, "s": 8617, "text": "Apache NiFi have state persistence issue in case of primary node switch, which sometimes makes processors not able to fetch data from sourcing systems." }, { "code": null, "e": 8999, "s": 8769, "text": "Apache NiFi consist of a web server, flow controller and a processor, which runs on Java Virtual Machine. It also has 3 repositories Flowfile Repository, Content Repository, and Provenance Repository as shown in the figure below." }, { "code": null, "e": 9319, "s": 8999, "text": "This repository stores the current state and attributes of every flowfile that goes through the data flows of apache NiFi. The default location of this repository is in the root directory of apache NiFi. The location of this repository can be changed by changing the property named \"nifi.flowfile.repository.directory\"." }, { "code": null, "e": 9663, "s": 9319, "text": "This repository contains all the content present in all the flowfiles of NiFi. Its default directory is also in the root directory of NiFi and it can be changed using \"org.apache.nifi.controller.repository.FileSystemRepository\" property. This directory uses large space in disk so it is advisable to have enough space in the installation disk." }, { "code": null, "e": 10179, "s": 9663, "text": "The repository tracks and stores all the events of all the flowfiles that flow in NiFi. There are two provenance repositories - volatile provenance repository (in this repository all the provenance data get lost after restart) and persistent provenance repository. Its default directory is also in the root directory of NiFi and it can be changed using \"org.apache.nifi.provenance.PersistentProvenanceRepository\" and \"org.apache.nifi.provenance.VolatileProvenanceRepositor\" property for the respective repositories." }, { "code": null, "e": 10312, "s": 10179, "text": "In this chapter, we will learn about the environment setup ofApache NiFi. The steps for installation of Apache NiFi are as follows βˆ’" }, { "code": null, "e": 10458, "s": 10312, "text": "Step 1 βˆ’ Install the current version of Java in your computer. Please set theJAVA_HOME in your machine. You can check the version as shown below:" }, { "code": null, "e": 10516, "s": 10458, "text": "In Windows Operating System (OS) (using command prompt) βˆ’" }, { "code": null, "e": 10533, "s": 10516, "text": "> java -version\n" }, { "code": null, "e": 10562, "s": 10533, "text": "In UNIX OS (Using Terminal):" }, { "code": null, "e": 10581, "s": 10562, "text": "$ echo $JAVA_HOME\n" }, { "code": null, "e": 10656, "s": 10584, "text": "Step 2 βˆ’ DownloadApache NiFi from https://nifi.apache.org/download.html" }, { "code": null, "e": 10689, "s": 10656, "text": "For windows OSdownload ZIP file." }, { "code": null, "e": 10722, "s": 10689, "text": "For windows OSdownload ZIP file." }, { "code": null, "e": 10752, "s": 10722, "text": "For UNIX OSdownload TAR file." }, { "code": null, "e": 10782, "s": 10752, "text": "For UNIX OSdownload TAR file." }, { "code": null, "e": 10864, "s": 10782, "text": "For docker images,go to the following link https://hub.docker.com/r/apache/nifi/." }, { "code": null, "e": 10946, "s": 10864, "text": "For docker images,go to the following link https://hub.docker.com/r/apache/nifi/." }, { "code": null, "e": 11044, "s": 10946, "text": "Step 3 βˆ’ The installation process for Apache NiFi is very easy. The process differs with the OS βˆ’" }, { "code": null, "e": 11113, "s": 11044, "text": "Windows OS βˆ’ Unzip the zip package and the Apache NiFi is installed." }, { "code": null, "e": 11182, "s": 11113, "text": "Windows OS βˆ’ Unzip the zip package and the Apache NiFi is installed." }, { "code": null, "e": 11256, "s": 11182, "text": "UNIX OS βˆ’ Extract tar file in any location and the Logstash is installed." }, { "code": null, "e": 11330, "s": 11256, "text": "UNIX OS βˆ’ Extract tar file in any location and the Logstash is installed." }, { "code": null, "e": 11363, "s": 11330, "text": "$tar -xvf nifi-1.6.0-bin.tar.gz\n" }, { "code": null, "e": 11489, "s": 11363, "text": "Step 4 βˆ’ Open command prompt, go to the bin directory of NiFi. For example, C:\\nifi-1.7.1\\bin, and execute run-nifi.bat file." }, { "code": null, "e": 11521, "s": 11489, "text": "C:\\nifi-1.7.1\\bin>run-nifi.bat\n" }, { "code": null, "e": 11694, "s": 11521, "text": "Step 5 βˆ’ It will take a few minutes to get the NiFi UI up. A user cancheck nifi-app.log, once NiFi UI is up then, a user can enter http://localhost:8080/nifi/ to access UI." }, { "code": null, "e": 11949, "s": 11694, "text": "Apache is a web-based platform that can be accessed by a user using web UI. The NiFi UI is very interactive and provides a wide variety of information about NiFi. As shown in the image below, a user can access information about the following attributes βˆ’" }, { "code": null, "e": 11964, "s": 11949, "text": "Active Threads" }, { "code": null, "e": 11982, "s": 11964, "text": "Total queued data" }, { "code": null, "e": 12017, "s": 11982, "text": "Transmitting Remote Process Groups" }, { "code": null, "e": 12056, "s": 12017, "text": "Not Transmitting Remote Process Groups" }, { "code": null, "e": 12075, "s": 12056, "text": "Running Components" }, { "code": null, "e": 12094, "s": 12075, "text": "Stopped Components" }, { "code": null, "e": 12113, "s": 12094, "text": "Invalid Components" }, { "code": null, "e": 12133, "s": 12113, "text": "Disabled Components" }, { "code": null, "e": 12169, "s": 12133, "text": "Up to date Versioned Process Groups" }, { "code": null, "e": 12211, "s": 12169, "text": "Locally modified Versioned Process Groups" }, { "code": null, "e": 12242, "s": 12211, "text": "Stale Versioned Process Groups" }, { "code": null, "e": 12294, "s": 12242, "text": "Locally modified and Stale Versioned Process Groups" }, { "code": null, "e": 12332, "s": 12294, "text": "Sync failure Versioned Process Groups" }, { "code": null, "e": 12378, "s": 12332, "text": "Apache NiFi UI has the following components βˆ’" }, { "code": null, "e": 12483, "s": 12378, "text": "User can drag the process icon on the canvas and select the desired processor for the data flow in NiFi." }, { "code": null, "e": 12557, "s": 12483, "text": "Below icon is dragged to canvas to add the input port into any data flow." }, { "code": null, "e": 12652, "s": 12557, "text": "Input port is used to get data from the processor, which is not present in that process group." }, { "code": null, "e": 12765, "s": 12652, "text": "After dragging this icon, NiFi asks to enter the name of the Input port and then it is added to the NiFi canvas." }, { "code": null, "e": 12844, "s": 12765, "text": "The below icon is dragged to canvas to add the output port into any data flow." }, { "code": null, "e": 12947, "s": 12844, "text": "The output port is used to transfer data to the processor, which is not present in that process group." }, { "code": null, "e": 13061, "s": 12947, "text": "After dragging this icon, NiFi asks to enter the name of the Output port and then it is added to the NiFi canvas." }, { "code": null, "e": 13125, "s": 13061, "text": "A user uses below icon to add process group in the NiFi canvas." }, { "code": null, "e": 13241, "s": 13125, "text": "After dragging this icon, NiFi asks to enter the name of the Process Group and then it is added to the NiFi canvas." }, { "code": null, "e": 13298, "s": 13241, "text": "This is used to add Remote process group in NiFi canvas." }, { "code": null, "e": 13442, "s": 13298, "text": "Funnel is used to transfer the output of a processor to multiple processors. User can use the below icon to add the funnel in a NiFi data flow." }, { "code": null, "e": 13579, "s": 13442, "text": "This icon is used to add a data flow template to NiFi canvas. This helps to reuse the data flow in the same or different NiFi instances." }, { "code": null, "e": 13654, "s": 13579, "text": "After dragging, a user can select the templates already added in the NiFi." }, { "code": null, "e": 13800, "s": 13654, "text": "These are used to add text on NiFi canvas about any component present in NiFi. It offers a range of colors used by a user to add aesthetic sense." }, { "code": null, "e": 14123, "s": 13800, "text": "Apache NiFi processors are the basic blocks of creating a data flow. Every processor has different functionality, which contributes to the creation of output flowfile. Dataflow shown in the image below is fetching file from one directory using GetFile processor and storing it in another directory using PutFile processor." }, { "code": null, "e": 14327, "s": 14123, "text": "GetFile process is used to fetch files of a specific format from a specific directory. It also provides other options to user for more control on fetching. We will discuss it in properties section below." }, { "code": null, "e": 14387, "s": 14327, "text": "Following are the different settings of GetFile processor βˆ’" }, { "code": null, "e": 14536, "s": 14387, "text": "In the Name setting, a user can define any name for the processors either according to the project or by that, which makes the name more meaningful." }, { "code": null, "e": 14599, "s": 14536, "text": "A user can enable or disable the processor using this setting." }, { "code": null, "e": 14692, "s": 14599, "text": "This setting lets a user to add the penalty time duration, in the event of flowfile failure." }, { "code": null, "e": 14808, "s": 14692, "text": "This setting is used to specify the yield time for processor. In this duration, the process is not scheduled again." }, { "code": null, "e": 14873, "s": 14808, "text": "This setting is used to specify the log level of that processor." }, { "code": null, "e": 15092, "s": 14873, "text": "This has a list of check of all the available relationship of that particular process. By checking the boxes, a user can program processor to terminate the flowfile on that event and do not send it further in the flow." }, { "code": null, "e": 15170, "s": 15092, "text": "These are the following scheduling options offered by the GetFile processor βˆ’" }, { "code": null, "e": 15307, "s": 15170, "text": "You can either schedule the process on time basis by selecting time driven or a specified CRON string by selecting a CRON driver option." }, { "code": null, "e": 15386, "s": 15307, "text": "This option is used to define the concurrent task schedule for this processor." }, { "code": null, "e": 15492, "s": 15386, "text": "A user can define whether to run the processor in all nodes or only in Primary node by using this option." }, { "code": null, "e": 15592, "s": 15492, "text": "It is used to define the time for time driven strategy or CRON expression for CRON driven strategy." }, { "code": null, "e": 15848, "s": 15592, "text": "GetFile offers multiple properties as shown in the image below raging compulsory\nproperties like Input directory and file filter to optional properties like Path Filter and Maximum file Size. A user can manage file fetching process using these properties." }, { "code": null, "e": 15913, "s": 15848, "text": "This Section is used to specify any information about processor." }, { "code": null, "e": 16004, "s": 15913, "text": "The PutFile processor is used to store the file from the data flow to a specific location." }, { "code": null, "e": 16055, "s": 16004, "text": "The PutFile processor has the following settings βˆ’" }, { "code": null, "e": 16203, "s": 16055, "text": "In the Name setting, a user can define any name for the processors either according to the project or by that which makes the name more meaningful." }, { "code": null, "e": 16266, "s": 16203, "text": "A user can enable or disable the processor using this setting." }, { "code": null, "e": 16356, "s": 16266, "text": "This setting lets a user add the penalty time duration, in the event of flowfile failure." }, { "code": null, "e": 16478, "s": 16356, "text": "This setting is used to specify the yield time for processor. In this duration, the process does not get scheduled again." }, { "code": null, "e": 16543, "s": 16478, "text": "This setting is used to specify the log level of that processor." }, { "code": null, "e": 16769, "s": 16543, "text": "This settings has a list of check of all the available relationship of that particular process. By checking the boxes, user can program processor to terminate the flowfile on that event and do not send it further in the flow." }, { "code": null, "e": 16847, "s": 16769, "text": "These are the following scheduling options offered by the PutFile processor βˆ’" }, { "code": null, "e": 17090, "s": 16847, "text": "You can schedule the process on time basis either by selecting timer driven or a specified CRON string by selecting CRON driver option. There is also an Experimental strategy Event Driven, which will trigger the processor on a specific event." }, { "code": null, "e": 17169, "s": 17090, "text": "This option is used to define the concurrent task schedule for this processor." }, { "code": null, "e": 17275, "s": 17169, "text": "A user can define whether to run the processor in all nodes or only in primary node by using this option." }, { "code": null, "e": 17376, "s": 17275, "text": "It is used to define the time for timer driven strategy or CRON expression for CRON driven strategy." }, { "code": null, "e": 17561, "s": 17376, "text": "The PutFile processor provides properties like Directory to specify the output directory for the purpose of file transfer and others to manage the transfer as shown in the image below." }, { "code": null, "e": 17626, "s": 17561, "text": "This Section is used to specify any information about processor." }, { "code": null, "e": 17698, "s": 17626, "text": "In this chapter, we will discuss process categorization in Apache NiFi." }, { "code": null, "e": 17961, "s": 17698, "text": "The processors under Data Ingestion category are used to ingest data into the NiFi data flow. These are mainly the starting point of any data flow in apache NiFi. Some of the processors that belong to these categories are GetFile, GetHTTP, GetFTP, GetKAFKA, etc." }, { "code": null, "e": 18327, "s": 17961, "text": "Routing and Mediation processors are used to route the flowfiles to different processors or data flows according to the information in attributes or content of those flowfiles. These processors are also responsible to control the NiFi data flows. Some of the processors that belong to this category are RouteOnAttribute, RouteOnContent, ControlRate, RouteText, etc." }, { "code": null, "e": 18685, "s": 18327, "text": "The processors of this Database Access category are capable of selecting or inserting data or executing and preparing other SQL statements from database. These processors mainly use data connection pool controller setting of Apache NiFi. Some of the processors that belong to this category are ExecuteSQL, PutSQL, PutDatabaseRecord, ListDatabaseTables, etc." }, { "code": null, "e": 18942, "s": 18685, "text": "Attribute Extraction Processors are responsible to extract, analyze, change flowfile attributes processing in the NiFi data flow. Some of the processors that belong to this category are UpdateAttribute, EvaluateJSONPath, ExtractText, AttributesToJSON, etc." }, { "code": null, "e": 19261, "s": 18942, "text": "System Interaction processors are used to run processes or commands in any operating system. These processors also run scripts in many languages to interact with a variety of systems. Some of the processors that belong to this category are ExecuteScript, ExecuteProcess, ExecuteGroovyScript, ExecuteStreamCommand, etc." }, { "code": null, "e": 19596, "s": 19261, "text": "Processors that belong to Data Transformation are capable of altering content of the flowfiles. These can be used to fully replace the data of a flowfile normally used when a user has to send flowfile as an HTTP body to invokeHTTP processor. Some of the processors that belong to this category are ReplaceText, JoltTransformJSON, etc." }, { "code": null, "e": 19965, "s": 19596, "text": "Sending Data Processors are generally the end processor in a data flow. These processors are responsible to store or send data to the destination server. After successful storing or sending the data, these processors DROP the flowfile with success relationship. Some of the processors that belong to this category are PutEmail, PutKafka, PutSFTP, PutFile, PutFTP, etc." }, { "code": null, "e": 20166, "s": 19965, "text": "These processors are used to split and merge the content present in a flowfile. Some of the processors that belong to this category are SplitText, SplitJson, SplitXml, MergeContent, SplitContent, etc." }, { "code": null, "e": 20314, "s": 20166, "text": "These processors deal with the HTTP and HTTPS calls. Some of the processors that belong to this category are InvokeHTTP, PostHTTP, ListenHTTP, etc." }, { "code": null, "e": 20498, "s": 20314, "text": "AWS processors are responsible to interaction with Amazon web services system. Some of the processors that belong to this category are GetSQS, PutSNS, PutS3Object, FetchS3Object, etc." }, { "code": null, "e": 20758, "s": 20498, "text": "In an Apache NiFi data flow, flowfiles move from one to another processor through connection that gets validated using a relationship between processors. Whenever a connection is created, a developer selects one or more relationships between those processors." }, { "code": null, "e": 21005, "s": 20758, "text": "As you can see in the above image, the check boxes in black rectangle are relationships. If a developer selects these check boxes then, the flowfile will terminate in that particular processor, when the relationship is success or failure or both." }, { "code": null, "e": 21216, "s": 21005, "text": "When a processor successfully processes a flowfile like store or fetch data from any datasource without getting any connection, authentication or any other error, then the flowfile goes to success relationship." }, { "code": null, "e": 21386, "s": 21216, "text": "When a processor is not able to process a flowfile without errors like authentication error or connection problem, etc. then the flowfile goes to a failure relationship." }, { "code": null, "e": 21616, "s": 21386, "text": "A developer can also transfer the flowfiles to other processors using connections. The developer can select and also load balance it, but load balancing is just released in version 1.8, which will not be covered in this tutorial." }, { "code": null, "e": 21882, "s": 21616, "text": "As you can see in the above image the connection marked in red have failure relationship, which means all flowfiles with errors will go to the processor in left and respectively all the flowfiles without errors will be transferred to the connection marked in green." }, { "code": null, "e": 21931, "s": 21882, "text": "Let us now proceed with the other relationships." }, { "code": null, "e": 22050, "s": 21931, "text": "This relationship is met, when a Flowfile could not be fetched from the remote server due to a communications failure." }, { "code": null, "e": 22166, "s": 22050, "text": "Any Flowfile for which we receive a β€˜Not Found’ message from the remote server will move to not.found relationship." }, { "code": null, "e": 22298, "s": 22166, "text": "When NiFi unable to fetch a flowfile from the remote server due to insufficient permission, it will move through this relationship." }, { "code": null, "e": 22580, "s": 22298, "text": "A flowfile is a basic processing entity in Apache NiFi. It contains data contents and attributes, which are used by NiFi processors to process data. The file content normally contains the data fetched from source systems. The most common attributes of an Apache NiFi FlowFile are βˆ’" }, { "code": null, "e": 22687, "s": 22580, "text": "This stands for Universally Unique Identifier, which is a unique identity of a flowfile generated by NiFi." }, { "code": null, "e": 22792, "s": 22687, "text": "This attribute contains the filename of that flowfile and it should not contain any directory structure." }, { "code": null, "e": 22841, "s": 22792, "text": "It contains the size of an Apache NiFi FlowFile." }, { "code": null, "e": 22886, "s": 22841, "text": "It specifies the MIME Type of this FlowFile." }, { "code": null, "e": 23002, "s": 22886, "text": "This attribute contains the relative path of a file to which a flowfile belongs and does not contain the file name." }, { "code": null, "e": 23202, "s": 23002, "text": "The Apache NiFi data flow connection has a queuing system to handle the large amount of data inflow. These queues can handle very large amount of FlowFiles to let the processor process them serially." }, { "code": null, "e": 23560, "s": 23202, "text": "The queue in the above image has 1 flowfile transferred through success relationship. A user can check the flowfile by selecting the List queue option in the drop down list. In case of any overload or error, a user can also clear the queue by selecting the empty queue option and then the user can restart the flow to get those files again in the data flow." }, { "code": null, "e": 23816, "s": 23560, "text": "The list of flowfiles in a queue, consist of position, UUID, Filename, File size, Queue Duration, and Lineage Duration. A user can see all the attributes and content of a flowfile by clicking the info icon present at the first column of the flowfile list." }, { "code": null, "e": 24009, "s": 23816, "text": "In Apache NiFi, a user can maintain different data flows in different process groups. These groups can be based on different projects or the organizations, which Apache NiFi instance supports." }, { "code": null, "e": 24435, "s": 24009, "text": "The fourth symbol in the menu at the top of the NiFi UI as shown in the above picture is used to add a process group in the NiFi canvas. The process group named\nβ€œTutorialspoint.com_ProcessGroup” contains a data flow with four processors currently in stop stage as you can see in the above picture. Process groups can be created in hierarchical manner to manage the data flows in better structure, which is easy to understand." }, { "code": null, "e": 24572, "s": 24435, "text": "In the footer of NiFi UI, you can see the process groups and can go back to the top of the process group a user is currently present in." }, { "code": null, "e": 24921, "s": 24572, "text": "To see the full list of process groups present in NiFi, a user can go to the summary by using the menu present in the left top side of the NiFi UI. In summary, there is process groups tab where all the process groups are listed with parameters like Version State, Transferred/Size, In/Size, Read/Write, Out/Size, etc. as shown in the below picture." }, { "code": null, "e": 25125, "s": 24921, "text": "Apache NiFi offers labels to enable a developer to write information about the components present in the NiFI canvas. The leftmost icon in the top menu of NiFi UI is used to add the label in NiFi canvas." }, { "code": null, "e": 25277, "s": 25125, "text": "A developer can change the color of the label and the size of the text with a right-click on the label and choose the appropriate option from the menu." }, { "code": null, "e": 25365, "s": 25277, "text": "Apache NiFi is highly configurable platform. The nifi.properties file in conf directory" }, { "code": null, "e": 25401, "s": 25365, "text": "contains most of the configuration." }, { "code": null, "e": 25462, "s": 25401, "text": "The commonly used properties of Apache NiFi are as follows βˆ’" }, { "code": null, "e": 25545, "s": 25462, "text": "This section contains the properties, which are compulsory to run a NiFi instance." }, { "code": null, "e": 25713, "s": 25545, "text": "These properties are used to store the state of the components helpful to start the processing, where components left after a restart and in the next schedule running." }, { "code": null, "e": 25785, "s": 25713, "text": "Let us now look into the important details of the FlowFile repository βˆ’" }, { "code": null, "e": 25992, "s": 25785, "text": "Apache NiFi offers support to multiple tools like ambari, zookeeper for administration purposes. NiFi also provides configuration in nifi.properties file to set up HTTPS and other things for administrators." }, { "code": null, "e": 26280, "s": 25992, "text": "NiFi itself does not handle voting process in cluster. This means when a cluster is created, all the nodes are primary and coordinator. So, zookeeper is configured to manage the voting of primary node and coordinator. The nifi.properties file contains some properties to setup zookeeper." }, { "code": null, "e": 26508, "s": 26280, "text": "To use NiFi over HTTPS, administrators have to generate keystore and truststore and set some properties in the nifi.properties file. The TLS toolkit can be used to generate all the necessary keys to enable HTTPS in apache NiFi." }, { "code": null, "e": 26625, "s": 26508, "text": "There are some other properties, which are used by administrators to manage the NiFi and for its service continuity." }, { "code": null, "e": 26913, "s": 26625, "text": "Apache NiFi offers a large number of components to help developers to create data flows for any type of protocols or data sources. To create a flow, a developer drags the components from menu bar to canvas and connects them by clicking and dragging the mouse from one component to other." }, { "code": null, "e": 27165, "s": 26913, "text": "Generally, a NiFi has a listener component at the starting of the flow like getfile, which gets the data from source system. On the other end of there is a transmitter component like putfile and there are components in between, which process the data." }, { "code": null, "e": 27306, "s": 27165, "text": "For example, let create a flow, which takes an empty file from one directory and add some text in that file and put it in another directory." }, { "code": null, "e": 27408, "s": 27306, "text": "To begin with, drag the processor icon to the NiFi canvas and select GetFile processor from the list." }, { "code": null, "e": 27510, "s": 27408, "text": "To begin with, drag the processor icon to the NiFi canvas and select GetFile processor from the list." }, { "code": null, "e": 27554, "s": 27510, "text": "Create an input directory like c:\\inputdir." }, { "code": null, "e": 27598, "s": 27554, "text": "Create an input directory like c:\\inputdir." }, { "code": null, "e": 27743, "s": 27598, "text": "Right-click on the processor and select configure and in properties tab add Input Directory (c:\\inputdir) and click apply and go back to canvas." }, { "code": null, "e": 27888, "s": 27743, "text": "Right-click on the processor and select configure and in properties tab add Input Directory (c:\\inputdir) and click apply and go back to canvas." }, { "code": null, "e": 27978, "s": 27888, "text": "Drag the processor icon to the canvas and select the ReplaceText processor from the list." }, { "code": null, "e": 28068, "s": 27978, "text": "Drag the processor icon to the canvas and select the ReplaceText processor from the list." }, { "code": null, "e": 28241, "s": 28068, "text": "Right-click on the processor and select configure. In the properties tab, add some text like β€œHello tutorialspoint.com” in the textbox of Replacement Value and click apply." }, { "code": null, "e": 28414, "s": 28241, "text": "Right-click on the processor and select configure. In the properties tab, add some text like β€œHello tutorialspoint.com” in the textbox of Replacement Value and click apply." }, { "code": null, "e": 28513, "s": 28414, "text": "Go to settings tab, check the failure checkbox at right hand side, and then go back to the canvas." }, { "code": null, "e": 28612, "s": 28513, "text": "Go to settings tab, check the failure checkbox at right hand side, and then go back to the canvas." }, { "code": null, "e": 28678, "s": 28612, "text": "Connect GetFIle processor to ReplaceText on success relationship." }, { "code": null, "e": 28744, "s": 28678, "text": "Connect GetFIle processor to ReplaceText on success relationship." }, { "code": null, "e": 28830, "s": 28744, "text": "Drag the processor icon to the canvas and select the PutFile processor from the list." }, { "code": null, "e": 28916, "s": 28830, "text": "Drag the processor icon to the canvas and select the PutFile processor from the list." }, { "code": null, "e": 28962, "s": 28916, "text": "Create an output directory like c:\\outputdir." }, { "code": null, "e": 29008, "s": 28962, "text": "Create an output directory like c:\\outputdir." }, { "code": null, "e": 29150, "s": 29008, "text": "Right-click on the processor and select configure. In the properties tab, add Directory (c:\\outputdir) and click apply and go back to canvas." }, { "code": null, "e": 29292, "s": 29150, "text": "Right-click on the processor and select configure. In the properties tab, add Directory (c:\\outputdir) and click apply and go back to canvas." }, { "code": null, "e": 29405, "s": 29292, "text": "Go to settings tab and check the failure and success checkbox at right hand side and then go back to the canvas." }, { "code": null, "e": 29518, "s": 29405, "text": "Go to settings tab and check the failure and success checkbox at right hand side and then go back to the canvas." }, { "code": null, "e": 29588, "s": 29518, "text": "Connect the ReplaceText processor to PutFile on success relationship." }, { "code": null, "e": 29658, "s": 29588, "text": "Connect the ReplaceText processor to PutFile on success relationship." }, { "code": null, "e": 29814, "s": 29658, "text": "Now start the flow and add an empty file in input directory and you will see that, it will move to output directory and the text will be added to the file." }, { "code": null, "e": 29970, "s": 29814, "text": "Now start the flow and add an empty file in input directory and you will see that, it will move to output directory and the text will be added to the file." }, { "code": null, "e": 30119, "s": 29970, "text": "By following the above steps, developers can choose any processor and other NiFi component to create suitable flow for their organisation or client." }, { "code": null, "e": 30374, "s": 30119, "text": "Apache NiFi offers the concept of Templates, which makes it easier to reuse and distribute the NiFi flows. The flows can be used by other developers or in other NiFi clusters. It also helps NiFi developers to share their work in repositories like GitHub." }, { "code": null, "e": 30479, "s": 30374, "text": "Let us create a template for the flow, which we created in chapter no 15 β€œApache NiFi - Creating Flows”." }, { "code": null, "e": 30839, "s": 30479, "text": "Select all the components of the flow using shift key and then click on the create template icon at the left hand side of the NiFi canvas. You can also see a tool box as shown in the above image. Click on the icon create template marked in blue as in the above picture. Enter the name for the template. A developer can also add description, which is optional." }, { "code": null, "e": 30966, "s": 30839, "text": "Then go to the NiFi templates option in the menu present at the top right hand corner of NiFi UI as show in the picture below." }, { "code": null, "e": 31134, "s": 30966, "text": "Now click the download icon (present at the right hand side in the list) of the template, you want to download. An XML file with the template name will get downloaded." }, { "code": null, "e": 31353, "s": 31134, "text": "To use a template in NiFi, a developer will have to upload its xml file to NiFi using UI. There is an Upload Template icon (marked with blue in below image) beside Create Template icon click on that and browse the xml." }, { "code": null, "e": 31486, "s": 31353, "text": "In the top toolbar of NiFi UI, the template icon is before the label icon. The icon is marked in blue as shown in the picture below." }, { "code": null, "e": 31613, "s": 31486, "text": "Drag the template icon and choose the template from the drop down list and click add. It will add the template to NiFi canvas." }, { "code": null, "e": 31854, "s": 31613, "text": "NiFi offers a large number of API, which helps developers to make changes and get information of NiFi from any other tool or custom developed applications. In this tutorial, we will use postman app in google chrome to explain some examples." }, { "code": null, "e": 32007, "s": 31854, "text": "To add postmantoyour Google Chrome, go to the below mentioned URL and click add to chrome button. You will now see a new app added toyour Google Chrome." }, { "code": null, "e": 32024, "s": 32007, "text": "chrome web store" }, { "code": null, "e": 32131, "s": 32024, "text": "The current version of NiFi rest API is 1.8.0 and the documentation is present in the below mentioned URL." }, { "code": null, "e": 32190, "s": 32131, "text": "https://nifi.apache.org/docs/nifi-docs/rest-api/index.html" }, { "code": null, "e": 32242, "s": 32190, "text": "Following are the most used NiFi rest API Modules βˆ’" }, { "code": null, "e": 32292, "s": 32242, "text": "http://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 32342, "s": 32292, "text": "http://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 32418, "s": 32342, "text": "In case HTTPS is enabled\nhttps://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 32494, "s": 32418, "text": "In case HTTPS is enabled\nhttps://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 32596, "s": 32494, "text": "Let us now consider an example and run on postman to get the details about the running NiFi instance." }, { "code": null, "e": 32643, "s": 32596, "text": "GET http://localhost:8080/nifi-api/flow/about\n" }, { "code": null, "e": 32928, "s": 32643, "text": "{\n \"about\": {\n \"title\": \"NiFi\",\n \"version\": \"1.7.1\",\n \"uri\": \"http://localhost:8080/nifi-api/\",\n \"contentViewerUrl\": \"../nifi-content-viewer/\",\n \"timezone\": \"SGT\",\n \"buildTag\": \"nifi-1.7.1-RC1\",\n \"buildTimestamp\": \"07/12/2018 12:54:43 SGT\"\n }\n}\n" }, { "code": null, "e": 33209, "s": 32928, "text": "Apache NiFi logs and store every information about the events occur on the ingested data in the flow. Data provenance repository stores this information and provides UI to search this event information. Data provenance can be accessed for full NiFi level and processor level also." }, { "code": null, "e": 33324, "s": 33209, "text": "The following table lists down the different fields in the NiFi Data Provenance event list have following fields βˆ’" }, { "code": null, "e": 33466, "s": 33324, "text": "To get more information about the event, a user can click on the information icon present in the first column of the NiFi Data Provenance UI." }, { "code": null, "e": 33575, "s": 33466, "text": "There are some properties in nifi.properties file, which are used to manage NiFi Data Provenance repository." }, { "code": null, "e": 33786, "s": 33575, "text": "In Apache NiFi, there are multiple ways to monitor the different statistics of the system like errors, memory usage, CPU usage, Data Flow statistics, etc. We will discuss the most popular ones in this tutorial." }, { "code": null, "e": 33864, "s": 33786, "text": "In this section, we will learn more about in built monitoring in Apache NiFi." }, { "code": null, "e": 34301, "s": 33864, "text": "The bulletin board shows the latest ERROR and WARNING getting generated by NiFi processors in real time. To access the bulletin board, a user will have to go the right hand drop down menu and select the Bulletin Board option. It refreshes automatically and a user can disable it also. A user can also navigate to the actual processor by double-clicking the error. A user can also filter the bulletins by working out with the following βˆ’" }, { "code": null, "e": 34312, "s": 34301, "text": "by message" }, { "code": null, "e": 34320, "s": 34312, "text": "by name" }, { "code": null, "e": 34326, "s": 34320, "text": "by id" }, { "code": null, "e": 34338, "s": 34326, "text": "by group id" }, { "code": null, "e": 34603, "s": 34338, "text": "To monitor the Events occurring on any specific processor or throughout NiFi, a user can access the Data provenance from the same menu as the bulletin board. A user can also filter the events in data provenance repository by working out with the following fields βˆ’" }, { "code": null, "e": 34621, "s": 34603, "text": "by component name" }, { "code": null, "e": 34639, "s": 34621, "text": "by component type" }, { "code": null, "e": 34647, "s": 34639, "text": "by type" }, { "code": null, "e": 35012, "s": 34647, "text": "Apache NiFi summary also can be accessed from the same menu as the bulletin board. This UI contains information about all the components of that particular NiFi instance or cluster. They can be filtered by name, by type or by URI. There are different tabs for different component types. Following are the components, which can be monitored in the NiFi summary UI βˆ’" }, { "code": null, "e": 35023, "s": 35012, "text": "Processors" }, { "code": null, "e": 35035, "s": 35023, "text": "Input ports" }, { "code": null, "e": 35048, "s": 35035, "text": "Output ports" }, { "code": null, "e": 35070, "s": 35048, "text": "Remote process groups" }, { "code": null, "e": 35082, "s": 35070, "text": "Connections" }, { "code": null, "e": 35097, "s": 35082, "text": "Process groups" }, { "code": null, "e": 35209, "s": 35097, "text": "In this UI, there is a link at the bottom right hand side named system diagnostics to check the JVM statistics." }, { "code": null, "e": 35541, "s": 35209, "text": "Apache NiFi provides multiple reporting tasks to support external monitoring systems like Ambari, Grafana, etc. A developer can create a custom reporting task or can configure the inbuilt ones to send the metrics of NiFi to the externals monitoring systems. The following table lists down the reporting tasks offered by NiFi 1.7.1." }, { "code": null, "e": 35697, "s": 35541, "text": "There is an API named system diagnostics, which can be used to monitor the NiFI stats in any custom developed application. Let us check the API in postman." }, { "code": null, "e": 35748, "s": 35697, "text": "http://localhost:8080/nifi-api/system-diagnostics\n" }, { "code": null, "e": 38653, "s": 35748, "text": "{\n \"systemDiagnostics\": {\n \"aggregateSnapshot\": {\n \"totalNonHeap\": \"183.89 MB\",\n \"totalNonHeapBytes\": 192819200,\n \"usedNonHeap\": \"173.47 MB\",\n \"usedNonHeapBytes\": 181894560,\n \"freeNonHeap\": \"10.42 MB\",\n \"freeNonHeapBytes\": 10924640,\n \"maxNonHeap\": \"-1 bytes\",\n \"maxNonHeapBytes\": -1,\n \"totalHeap\": \"512 MB\",\n \"totalHeapBytes\": 536870912,\n \"usedHeap\": \"273.37 MB\",\n \"usedHeapBytes\": 286652264,\n \"freeHeap\": \"238.63 MB\",\n \"freeHeapBytes\": 250218648,\n \"maxHeap\": \"512 MB\",\n \"maxHeapBytes\": 536870912,\n \"heapUtilization\": \"53.0%\",\n \"availableProcessors\": 4,\n \"processorLoadAverage\": -1,\n \"totalThreads\": 71,\n \"daemonThreads\": 31,\n \"uptime\": \"17:30:35.277\",\n \"flowFileRepositoryStorageUsage\": {\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n },\n \"contentRepositoryStorageUsage\": [\n {\n \"identifier\": \"default\",\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n }\n ],\n \"provenanceRepositoryStorageUsage\": [\n {\n \"identifier\": \"default\",\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n }\n ],\n \"garbageCollection\": [\n {\n \"name\": \"G1 Young Generation\",\n \"collectionCount\": 344,\n \"collectionTime\": \"00:00:06.239\",\n \"collectionMillis\": 6239\n },\n {\n \"name\": \"G1 Old Generation\",\n \"collectionCount\": 0,\n \"collectionTime\": \"00:00:00.000\",\n \"collectionMillis\": 0\n }\n ],\n \"statsLastRefreshed\": \"09:30:20 SGT\",\n \"versionInfo\": {\n \"niFiVersion\": \"1.7.1\",\n \"javaVendor\": \"Oracle Corporation\",\n \"javaVersion\": \"1.8.0_151\",\n \"osName\": \"Windows 7\",\n \"osVersion\": \"6.1\",\n \"osArchitecture\": \"amd64\",\n \"buildTag\": \"nifi-1.7.1-RC1\",\n \"buildTimestamp\": \"07/12/2018 12:54:43 SGT\"\n }\n }\n }\n}\n" }, { "code": null, "e": 38946, "s": 38653, "text": "Before starting the upgrade of Apache NiFi, read the release notes to know about the changes and additions. A user needs to evaluate the impact of these additions and changes in his/her current NiFi installation. Below is the link to get the release notes for the new releases of Apache NiFi." }, { "code": null, "e": 39009, "s": 38946, "text": "https://cwiki.apache.org/confluence/display/NIFI/Release+Notes" }, { "code": null, "e": 39156, "s": 39009, "text": "In a cluster setup, a user needs to upgrade NiFi installation of every Node in a cluster. Follow the steps given below to upgrade the Apache NiFi." }, { "code": null, "e": 39240, "s": 39156, "text": "Backup all the custom NARs present in your current NiFi or lib or any other folder." }, { "code": null, "e": 39324, "s": 39240, "text": "Backup all the custom NARs present in your current NiFi or lib or any other folder." }, { "code": null, "e": 39481, "s": 39324, "text": "Download the new version of Apache NiFi. Below is the link to download the source and binaries of latest NiFi version.\nhttps://nifi.apache.org/download.html" }, { "code": null, "e": 39600, "s": 39481, "text": "Download the new version of Apache NiFi. Below is the link to download the source and binaries of latest NiFi version." }, { "code": null, "e": 39638, "s": 39600, "text": "https://nifi.apache.org/download.html" }, { "code": null, "e": 39756, "s": 39638, "text": "Create a new directory in the same installation directory of current NiFi and extract the new version of Apache NiFi." }, { "code": null, "e": 39874, "s": 39756, "text": "Create a new directory in the same installation directory of current NiFi and extract the new version of Apache NiFi." }, { "code": null, "e": 40039, "s": 39874, "text": "Stop the NiFi gracefully. First stop all the processors and let all the flowfiles present in the flow get processed. Once, no more flowfile is there, stop the NiFi." }, { "code": null, "e": 40204, "s": 40039, "text": "Stop the NiFi gracefully. First stop all the processors and let all the flowfiles present in the flow get processed. Once, no more flowfile is there, stop the NiFi." }, { "code": null, "e": 40297, "s": 40204, "text": "Copy the configuration of authorizers.xml from current NiFi installation to the new version." }, { "code": null, "e": 40390, "s": 40297, "text": "Copy the configuration of authorizers.xml from current NiFi installation to the new version." }, { "code": null, "e": 40509, "s": 40390, "text": "Update the values in bootstrap-notification-services.xml, and bootstrap.conf of new NiFi version from the current one." }, { "code": null, "e": 40628, "s": 40509, "text": "Update the values in bootstrap-notification-services.xml, and bootstrap.conf of new NiFi version from the current one." }, { "code": null, "e": 40698, "s": 40628, "text": "Add the custom logging from logback.xml to the new NiFi installation." }, { "code": null, "e": 40768, "s": 40698, "text": "Add the custom logging from logback.xml to the new NiFi installation." }, { "code": null, "e": 40864, "s": 40768, "text": "Configure the login identity provider in login-identity-providers.xml from the current version." }, { "code": null, "e": 40960, "s": 40864, "text": "Configure the login identity provider in login-identity-providers.xml from the current version." }, { "code": null, "e": 41056, "s": 40960, "text": "Update all the properties in nifi.properties of the new NiFi installation from current version." }, { "code": null, "e": 41152, "s": 41056, "text": "Update all the properties in nifi.properties of the new NiFi installation from current version." }, { "code": null, "e": 41279, "s": 41152, "text": "Please make sure that the group and user of new version is same as the current version, to avoid any permission denied errors." }, { "code": null, "e": 41406, "s": 41279, "text": "Please make sure that the group and user of new version is same as the current version, to avoid any permission denied errors." }, { "code": null, "e": 41494, "s": 41406, "text": "Copy the configuration from state-management.xml of current version to the new version." }, { "code": null, "e": 41582, "s": 41494, "text": "Copy the configuration from state-management.xml of current version to the new version." }, { "code": null, "e": 41999, "s": 41582, "text": "Copy the contents of the following directories from current version of NiFi installation to the same directories in the new version.\n\n./conf/flow.xml.gz\nAlso flow.xml.gz from the archive directory.\nFor provenance and content repositories change the values in nifi. properties file to the current repositories.\ncopy state from ./state/local or change in nifi.properties if any other external directory is specified.\n\n" }, { "code": null, "e": 42132, "s": 41999, "text": "Copy the contents of the following directories from current version of NiFi installation to the same directories in the new version." }, { "code": null, "e": 42151, "s": 42132, "text": "./conf/flow.xml.gz" }, { "code": null, "e": 42170, "s": 42151, "text": "./conf/flow.xml.gz" }, { "code": null, "e": 42215, "s": 42170, "text": "Also flow.xml.gz from the archive directory." }, { "code": null, "e": 42260, "s": 42215, "text": "Also flow.xml.gz from the archive directory." }, { "code": null, "e": 42372, "s": 42260, "text": "For provenance and content repositories change the values in nifi. properties file to the current repositories." }, { "code": null, "e": 42484, "s": 42372, "text": "For provenance and content repositories change the values in nifi. properties file to the current repositories." }, { "code": null, "e": 42589, "s": 42484, "text": "copy state from ./state/local or change in nifi.properties if any other external directory is specified." }, { "code": null, "e": 42694, "s": 42589, "text": "copy state from ./state/local or change in nifi.properties if any other external directory is specified." }, { "code": null, "e": 42860, "s": 42694, "text": "Recheck all the changes performed and check if they have an impact on any new changes added in the new NiFi version. If there is any impact, check for the solutions." }, { "code": null, "e": 43026, "s": 42860, "text": "Recheck all the changes performed and check if they have an impact on any new changes added in the new NiFi version. If there is any impact, check for the solutions." }, { "code": null, "e": 43176, "s": 43026, "text": "Start all the NiFi nodes and verify if all the flows are working correctly and repositories are storing data and Ui is retrieving it with any errors." }, { "code": null, "e": 43326, "s": 43176, "text": "Start all the NiFi nodes and verify if all the flows are working correctly and repositories are storing data and Ui is retrieving it with any errors." }, { "code": null, "e": 43387, "s": 43326, "text": "Monitor bulletins for some time to check for any new errors." }, { "code": null, "e": 43448, "s": 43387, "text": "Monitor bulletins for some time to check for any new errors." }, { "code": null, "e": 43564, "s": 43448, "text": "If the new version is working correctly, then the current version can be archived and deleted from the directories." }, { "code": null, "e": 43680, "s": 43564, "text": "If the new version is working correctly, then the current version can be archived and deleted from the directories." }, { "code": null, "e": 43944, "s": 43680, "text": "Apache NiFi Remote Process Group or RPG enables flow to direct the FlowFiles in a flow to different NiFi instances using Site-to-Site protocol. As of version 1.7.1, NiFi does not offer balanced relationships, so RPG is used for load balancing in a NiFi data flow." }, { "code": null, "e": 44133, "s": 43944, "text": "A developer can add the RPG from the top toolbar of NiFi UI by dragging the icon as shown in the above picture to canvas. To configure an RPG, a Developer has to add the following fields βˆ’" }, { "code": null, "e": 44225, "s": 44133, "text": "A developer needs to enable it, before using it like we start processors before using them." }, { "code": null, "e": 44443, "s": 44225, "text": "Apache NiFi offers shared services, which can be shared by processors and reporting task is called controller settings. These are like Database connection pool, which can be used by processors accessing same database." }, { "code": null, "e": 44565, "s": 44443, "text": "To access the controller settings, use the drop down menu at the right top corner of NiFi UI as shown in the below image." }, { "code": null, "e": 44690, "s": 44565, "text": "There are many controller settings offered by Apache NiFi, we will discuss a commonly used one and how we set it up in NiFi." }, { "code": null, "e": 44947, "s": 44690, "text": "Add the plus sign in the Nifi Settings page after clicking the Controller settings option. Then select the DBCPConnectionPool from the list of controller settings. DBCPConnectionPool will be added in the main NiFi settings page as shown in the below image." }, { "code": null, "e": 45019, "s": 44947, "text": "It contains the following information about the controller setting:Name" }, { "code": null, "e": 45024, "s": 45019, "text": "Type" }, { "code": null, "e": 45031, "s": 45024, "text": "Bundle" }, { "code": null, "e": 45037, "s": 45031, "text": "State" }, { "code": null, "e": 45043, "s": 45037, "text": "Scope" }, { "code": null, "e": 45069, "s": 45043, "text": "Configure and delete icon" }, { "code": null, "e": 45175, "s": 45069, "text": "Click on the configure icon and fill the required fields. The fields are listed down in the table below βˆ’" }, { "code": null, "e": 45476, "s": 45175, "text": "To stop or configure a controller setting, first all the attached NiFi components should be stopped. NiFi also adds scope in controller settings to manage the configuration of it. Therefore, only the ones which shared the same settings will not get impacted and will use the same controller settings." }, { "code": null, "e": 45729, "s": 45476, "text": "Apache NiFi reporting tasks are similar to the controller services, which run in the background and send or log the statistics of NiFi instance. NiFi reporting task can also be accessed from the same page as controller settings, but in a different tab." }, { "code": null, "e": 46114, "s": 45729, "text": "To add a reporting task, a developer needs to click on the plus button present at the top right hand side of the reporting tasks page. These reporting tasks are mainly used for monitoring the activities of a NiFi instance, in either the bulletins or the provenance. Mainly these reporting tasks uses Site-to-Site to transport the NiFi statistics data to other node or external system." }, { "code": null, "e": 46181, "s": 46114, "text": "Let us now add a configured reporting task for more understanding." }, { "code": null, "e": 46348, "s": 46181, "text": "This reporting task is used to generate bulletins, when a memory pool crosses specified percentage. Follow these steps to configure the MonitorMemory reporting task βˆ’" }, { "code": null, "e": 46411, "s": 46348, "text": "Add in the plus sign and search for MonitorMemory in the list." }, { "code": null, "e": 46474, "s": 46411, "text": "Add in the plus sign and search for MonitorMemory in the list." }, { "code": null, "e": 46513, "s": 46474, "text": "Select MonitorMemory and click on ADD." }, { "code": null, "e": 46552, "s": 46513, "text": "Select MonitorMemory and click on ADD." }, { "code": null, "e": 46645, "s": 46552, "text": "Once it is added in the main page of reporting tasks main page, click on the configure icon." }, { "code": null, "e": 46738, "s": 46645, "text": "Once it is added in the main page of reporting tasks main page, click on the configure icon." }, { "code": null, "e": 46812, "s": 46738, "text": "In the properties tab, select the memory pool, which you want to monitor." }, { "code": null, "e": 46886, "s": 46812, "text": "In the properties tab, select the memory pool, which you want to monitor." }, { "code": null, "e": 46960, "s": 46886, "text": "Select the percentage after which you want bulletins to alert the users.\n" }, { "code": null, "e": 47034, "s": 46960, "text": "Select the percentage after which you want bulletins to alert the users.\n" }, { "code": null, "e": 47060, "s": 47034, "text": "Start the reporting task." }, { "code": null, "e": 47086, "s": 47060, "text": "Start the reporting task." }, { "code": null, "e": 47258, "s": 47086, "text": "Apache NiFi is an open source platform and gives developers the options to add their custom processor in the NiFi library. Follow these steps to create a custom processor." }, { "code": null, "e": 47353, "s": 47258, "text": "Download Maven latest version from the link given below.\nhttps://maven.apache.org/download.cgi" }, { "code": null, "e": 47410, "s": 47353, "text": "Download Maven latest version from the link given below." }, { "code": null, "e": 47448, "s": 47410, "text": "https://maven.apache.org/download.cgi" }, { "code": null, "e": 47544, "s": 47448, "text": "Add an environment variable named M2_HOME and set value as the installation directory of maven." }, { "code": null, "e": 47640, "s": 47544, "text": "Add an environment variable named M2_HOME and set value as the installation directory of maven." }, { "code": null, "e": 47730, "s": 47640, "text": "Download Eclipse IDE from the below link.\nhttps://www.eclipse.org/downloads/download.php\n" }, { "code": null, "e": 47772, "s": 47730, "text": "Download Eclipse IDE from the below link." }, { "code": null, "e": 47820, "s": 47772, "text": "https://www.eclipse.org/downloads/download.php\n" }, { "code": null, "e": 47877, "s": 47820, "text": "Open command prompt and execute Maven Archetype command." }, { "code": null, "e": 47934, "s": 47877, "text": "Open command prompt and execute Maven Archetype command." }, { "code": null, "e": 47960, "s": 47934, "text": "> mvn archetype:generate\n" }, { "code": null, "e": 48012, "s": 47960, "text": "Search for the nifi type in the archetype projects." }, { "code": null, "e": 48064, "s": 48012, "text": "Search for the nifi type in the archetype projects." }, { "code": null, "e": 48128, "s": 48064, "text": "Select org.apache.nifi:nifi-processor-bundle-archetype project." }, { "code": null, "e": 48192, "s": 48128, "text": "Select org.apache.nifi:nifi-processor-bundle-archetype project." }, { "code": null, "e": 48279, "s": 48192, "text": "Then from the list of versions select the latest version i.e. 1.7.1 for this tutorial." }, { "code": null, "e": 48366, "s": 48279, "text": "Then from the list of versions select the latest version i.e. 1.7.1 for this tutorial." }, { "code": null, "e": 48441, "s": 48366, "text": "Enter the groupId, artifactId, version, package, and artifactBaseName etc." }, { "code": null, "e": 48516, "s": 48441, "text": "Enter the groupId, artifactId, version, package, and artifactBaseName etc." }, { "code": null, "e": 48642, "s": 48516, "text": "Then a maven project will be created having to directories.\n\nnifi-<artifactBaseName>-processors\nnifi-<artifactBaseName>-nar\n\n" }, { "code": null, "e": 48702, "s": 48642, "text": "Then a maven project will be created having to directories." }, { "code": null, "e": 48737, "s": 48702, "text": "nifi-<artifactBaseName>-processors" }, { "code": null, "e": 48772, "s": 48737, "text": "nifi-<artifactBaseName>-processors" }, { "code": null, "e": 48800, "s": 48772, "text": "nifi-<artifactBaseName>-nar" }, { "code": null, "e": 48828, "s": 48800, "text": "nifi-<artifactBaseName>-nar" }, { "code": null, "e": 48933, "s": 48828, "text": "Run the below command in nifi-<artifactBaseName>-processors directory to add the project in the eclipse." }, { "code": null, "e": 49038, "s": 48933, "text": "Run the below command in nifi-<artifactBaseName>-processors directory to add the project in the eclipse." }, { "code": null, "e": 49067, "s": 49038, "text": "mvn install eclipse:eclipse\n" }, { "code": null, "e": 49118, "s": 49067, "text": "Open eclipse and select import from the file menu." }, { "code": null, "e": 49169, "s": 49118, "text": "Open eclipse and select import from the file menu." }, { "code": null, "e": 49298, "s": 49169, "text": "Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName>-processors directory in eclipse." }, { "code": null, "e": 49427, "s": 49298, "text": "Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName>-processors directory in eclipse." }, { "code": null, "e": 49578, "s": 49427, "text": "Add your code in public void onTrigger(ProcessContext context, ProcessSession session) function, which runs when ever a processor is scheduled to run." }, { "code": null, "e": 49729, "s": 49578, "text": "Add your code in public void onTrigger(ProcessContext context, ProcessSession session) function, which runs when ever a processor is scheduled to run." }, { "code": null, "e": 49805, "s": 49729, "text": "Then package the code to a NAR file by running the below mentioned command." }, { "code": null, "e": 49881, "s": 49805, "text": "Then package the code to a NAR file by running the below mentioned command." }, { "code": null, "e": 49900, "s": 49881, "text": "mvn clean install\n" }, { "code": null, "e": 49958, "s": 49900, "text": "A NAR file will be created at nifi--nar/target directory." }, { "code": null, "e": 50016, "s": 49958, "text": "A NAR file will be created at nifi--nar/target directory." }, { "code": null, "e": 50089, "s": 50016, "text": "Copy the NAR file to the lib folder of Apache NiFi and restart the NiFi." }, { "code": null, "e": 50162, "s": 50089, "text": "Copy the NAR file to the lib folder of Apache NiFi and restart the NiFi." }, { "code": null, "e": 50251, "s": 50162, "text": "After successful restart of NiFi, check the processor list for the new custom processor." }, { "code": null, "e": 50340, "s": 50251, "text": "After successful restart of NiFi, check the processor list for the new custom processor." }, { "code": null, "e": 50384, "s": 50340, "text": "For any errors, check ./logs/nifi.log file." }, { "code": null, "e": 50428, "s": 50384, "text": "For any errors, check ./logs/nifi.log file." }, { "code": null, "e": 50634, "s": 50428, "text": "Apache NiFi is an open source platform and gives developers the options to add their custom controllers service in Apache NiFi. The steps and tools are almost the same as used to create a custom processor." }, { "code": null, "e": 50691, "s": 50634, "text": "Open command prompt and execute Maven Archetype command." }, { "code": null, "e": 50748, "s": 50691, "text": "Open command prompt and execute Maven Archetype command." }, { "code": null, "e": 50774, "s": 50748, "text": "> mvn archetype:generate\n" }, { "code": null, "e": 50826, "s": 50774, "text": "Search for the nifi type in the archetype projects." }, { "code": null, "e": 50878, "s": 50826, "text": "Search for the nifi type in the archetype projects." }, { "code": null, "e": 50940, "s": 50878, "text": "Select org.apache.nifi:nifi-service-bundle-archetype project." }, { "code": null, "e": 51002, "s": 50940, "text": "Select org.apache.nifi:nifi-service-bundle-archetype project." }, { "code": null, "e": 51087, "s": 51002, "text": "Then from the list of versions, select the latest version – 1.7.1 for this tutorial." }, { "code": null, "e": 51172, "s": 51087, "text": "Then from the list of versions, select the latest version – 1.7.1 for this tutorial." }, { "code": null, "e": 51248, "s": 51172, "text": "Enter the groupId, artifactId, version, package, and artifactBaseName, etc." }, { "code": null, "e": 51324, "s": 51248, "text": "Enter the groupId, artifactId, version, package, and artifactBaseName, etc." }, { "code": null, "e": 51491, "s": 51324, "text": "A maven project will be created having directories.\n\nnifi-<artifactBaseName>\nnifi-<artifactBaseName>-nar\nnifi-<artifactBaseName>-api\nnifi-<artifactBaseName>-api-nar\n\n" }, { "code": null, "e": 51543, "s": 51491, "text": "A maven project will be created having directories." }, { "code": null, "e": 51567, "s": 51543, "text": "nifi-<artifactBaseName>" }, { "code": null, "e": 51591, "s": 51567, "text": "nifi-<artifactBaseName>" }, { "code": null, "e": 51619, "s": 51591, "text": "nifi-<artifactBaseName>-nar" }, { "code": null, "e": 51647, "s": 51619, "text": "nifi-<artifactBaseName>-nar" }, { "code": null, "e": 51675, "s": 51647, "text": "nifi-<artifactBaseName>-api" }, { "code": null, "e": 51703, "s": 51675, "text": "nifi-<artifactBaseName>-api" }, { "code": null, "e": 51735, "s": 51703, "text": "nifi-<artifactBaseName>-api-nar" }, { "code": null, "e": 51767, "s": 51735, "text": "nifi-<artifactBaseName>-api-nar" }, { "code": null, "e": 51933, "s": 51767, "text": "Run the below command in nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories to add these two projects in the eclipse.\n\nmvn install eclipse:eclipse\n\n" }, { "code": null, "e": 52068, "s": 51933, "text": "Run the below command in nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories to add these two projects in the eclipse." }, { "code": null, "e": 52096, "s": 52068, "text": "mvn install eclipse:eclipse" }, { "code": null, "e": 52124, "s": 52096, "text": "mvn install eclipse:eclipse" }, { "code": null, "e": 52175, "s": 52124, "text": "Open eclipse and select import from the file menu." }, { "code": null, "e": 52226, "s": 52175, "text": "Open eclipse and select import from the file menu." }, { "code": null, "e": 52378, "s": 52226, "text": "Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories in eclipse." }, { "code": null, "e": 52530, "s": 52378, "text": "Then select β€œExisting Projects into workspace” and add the project from nifi-<artifactBaseName> and nifi-<artifactBaseName>-api directories in eclipse." }, { "code": null, "e": 52565, "s": 52530, "text": "Add your code in the source files." }, { "code": null, "e": 52600, "s": 52565, "text": "Add your code in the source files." }, { "code": null, "e": 52697, "s": 52600, "text": "Then package the code to a NAR file by running the below mentioned command.\n\nmvn clean install\n\n" }, { "code": null, "e": 52773, "s": 52697, "text": "Then package the code to a NAR file by running the below mentioned command." }, { "code": null, "e": 52791, "s": 52773, "text": "mvn clean install" }, { "code": null, "e": 52809, "s": 52791, "text": "mvn clean install" }, { "code": null, "e": 52928, "s": 52809, "text": "Two NAR files will be created in each nifi-<artifactBaseName>/target and nifi-<artifactBaseName>-api/target directory." }, { "code": null, "e": 53047, "s": 52928, "text": "Two NAR files will be created in each nifi-<artifactBaseName>/target and nifi-<artifactBaseName>-api/target directory." }, { "code": null, "e": 53123, "s": 53047, "text": "Copy these NAR files to the lib folder of Apache NiFi and restart the NiFi." }, { "code": null, "e": 53199, "s": 53123, "text": "Copy these NAR files to the lib folder of Apache NiFi and restart the NiFi." }, { "code": null, "e": 53288, "s": 53199, "text": "After successful restart of NiFi, check the processor list for the new custom processor." }, { "code": null, "e": 53377, "s": 53288, "text": "After successful restart of NiFi, check the processor list for the new custom processor." }, { "code": null, "e": 53421, "s": 53377, "text": "For any errors, check ./logs/nifi.log file." }, { "code": null, "e": 53465, "s": 53421, "text": "For any errors, check ./logs/nifi.log file." }, { "code": null, "e": 53724, "s": 53465, "text": "Apache NiFi uses logback library to handle its logging. There is a file logback.xml present in the conf directory of NiFi, which is used to configure the logging in NiFi. The logs are generated in logs folder of NiFi and the log files are as described below." }, { "code": null, "e": 53988, "s": 53724, "text": "This is the main log file of nifi, which logs all the activities of apache NiFi application ranging from NAR files loading to the run time errors or bulletins encountered by NiFi components. Below is the default appender in logback.xml file for nifi-app.log file." }, { "code": null, "e": 54679, "s": 53988, "text": "<appender name=\"APP_FILE\"\nclass=\"ch.qos.logback.core.rolling.RollingFileAppender\">\n <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-app.log</file>\n <rollingPolicy\n class=\"ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy\">\n <fileNamePattern>\n ${org.apache.nifi.bootstrap.config.log.dir}/\n\t nifi-app_%d{yyyy-MM-dd_HH}.%i.log\n </fileNamePattern>\n <maxFileSize>100MB</maxFileSize>\n <maxHistory>30</maxHistory>\n </rollingPolicy>\n <immediateFlush>true</immediateFlush>\n <encoder class=\"ch.qos.logback.classic.encoder.PatternLayoutEncoder\">\n <pattern>%date %level [%thread] %logger{40} %msg%n</pattern>\n </encoder>\n</appender>" }, { "code": null, "e": 54973, "s": 54679, "text": "The appender name is APP_FILE, and the class is RollingFileAppender, which means logger is using rollback policy. By default, the max file size is 100 MB and can be changed to the required size. The maximum retention for APP_FILE is 30 log files and can be changed as per the user requirement." }, { "code": null, "e": 55128, "s": 54973, "text": "This log contains the user events like web security, web api config, user authorization, etc. Below is the appender for nifi-user.log in logback.xml file." }, { "code": null, "e": 55714, "s": 55128, "text": "<appender name=\"USER_FILE\"\n class=\"ch.qos.logback.core.rolling.RollingFileAppender\">\n <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-user.log</file>\n <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">\n <fileNamePattern>\n ${org.apache.nifi.bootstrap.config.log.dir}/\n\t nifi-user_%d.log\n </fileNamePattern>\n <maxHistory>30</maxHistory>\n </rollingPolicy>\n <encoder class=\"ch.qos.logback.classic.encoder.PatternLayoutEncoder\">\n <pattern>%date %level [%thread] %logger{40} %msg%n</pattern>\n </encoder>\n</appender>" }, { "code": null, "e": 55916, "s": 55714, "text": "The appender name is USER_FILE. It follows the rollover policy. The maximum retention period for USER_FILE is 30 log files. Below is the default loggers for USER_FILE appender present in nifi-user.log." }, { "code": null, "e": 56550, "s": 55916, "text": "<logger name=\"org.apache.nifi.web.security\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"USER_FILE\"/>\n</logger>\n<logger name=\"org.apache.nifi.web.api.config\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"USER_FILE\"/>\n</logger>\n<logger name=\"org.apache.nifi.authorization\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"USER_FILE\"/>\n</logger>\n<logger name=\"org.apache.nifi.cluster.authorization\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"USER_FILE\"/>\n</logger>\n<logger name=\"org.apache.nifi.web.filter.RequestLogger\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"USER_FILE\"/>\n</logger>" }, { "code": null, "e": 56807, "s": 56550, "text": "This log contains the bootstrap logs, apache NiFi’s standard output (all system.out written in the code mainly for debugging), and standard error (all system.err written in the code). Below is the default appender for the nifi-bootstrap.log in logback.log." }, { "code": null, "e": 57396, "s": 56807, "text": "<appender name=\"BOOTSTRAP_FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">\n <file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap.log</file>\n <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">\n <fileNamePattern>\n ${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap_%d.log\n </fileNamePattern>\n <maxHistory>5</maxHistory>\n </rollingPolicy>\n <encoder class=\"ch.qos.logback.classic.encoder.PatternLayoutEncoder\">\n <pattern>%date %level [%thread] %logger{40} %msg%n</pattern>\n </encoder>\n</appender>" }, { "code": null, "e": 57615, "s": 57396, "text": "nifi-bootstrap.log file,s appender name is BOOTSTRAP_FILE, which also follows rollback policy. The maximum retention for BOOTSTRAP_FILE appender is 5 log files. Below is the default loggers for nifi-bootstrap.log file." }, { "code": null, "e": 58152, "s": 57615, "text": "<logger name=\"org.apache.nifi.bootstrap\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"BOOTSTRAP_FILE\" />\n</logger>\n<logger name=\"org.apache.nifi.bootstrap.Command\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"CONSOLE\" />\n <appender-ref ref=\"BOOTSTRAP_FILE\" />\n</logger>\n<logger name=\"org.apache.nifi.StdOut\" level=\"INFO\" additivity=\"false\">\n <appender-ref ref=\"BOOTSTRAP_FILE\" />\n</logger>\n<logger name=\"org.apache.nifi.StdErr\" level=\"ERROR\" additivity=\"false\">\n <appender-ref ref=\"BOOTSTRAP_FILE\" />\n</logger>" }, { "code": null, "e": 58187, "s": 58152, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 58206, "s": 58187, "text": " Arnab Chakraborty" }, { "code": null, "e": 58241, "s": 58206, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58262, "s": 58241, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 58295, "s": 58262, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 58308, "s": 58295, "text": " Nilay Mehta" }, { "code": null, "e": 58343, "s": 58308, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58361, "s": 58343, "text": " Bigdata Engineer" }, { "code": null, "e": 58394, "s": 58361, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 58412, "s": 58394, "text": " Bigdata Engineer" }, { "code": null, "e": 58445, "s": 58412, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 58463, "s": 58445, "text": " Bigdata Engineer" }, { "code": null, "e": 58470, "s": 58463, "text": " Print" }, { "code": null, "e": 58481, "s": 58470, "text": " Add Notes" } ]
Explain abstract class in PHP.
PHP5 comes with the object-oriented model with it, Some of the concepts of object-oriented model are: class, object, encapsulation, polymorphism, abstract and final classes, and methods, interfaces and inheritance, etc... In this article, we will discuss Abstract Class and it's features related to the object-oriented techniques in PHP. Also, we will learn the implementation of Abstract Class along with few examples. But, before diving too deep,let's learn how to define abstract class. We can declare a class as abstract by affixing the name of the class with the abstract keyword. The definition is very clear, the class that contains abstract methods is known as abstract class. Abstract methods define in the abstract class just have name and arguments, and no other code. An object of an abstract class can't be made. Rather, we need to extend child classes that compute the definition of the function into the bodies of the abstract methods in the child classes and utilize these child classes to create objects. Let's discuss some important facts about abstract classes in PHP: <?php abstract class base { abstract function printdata(); public function getdata() { echo "Tutorials Point"; } } class child extends base{ public function printdata(){ echo "Good morning"; } } $obj = new child(); $obj->getdata(); ?> Tutorials Point <?php abstract class AbstractClass{ abstract protected function calculate(); public function adddata() { echo "Addition done"; } } $obj=new AbstractClass(); $obj->adddata(); ?> Fatal error: Uncaught Error: Cannot instantiate abstract class AbstractClass All child class must define all the methods marked as abstract in the parent class, with all these methods need to be defined with the same signature or less restricted signature. Suppose In parent class if we define an abstract method with protected visibilty, in the child class execution it should be defined with protected aorpublic, but not with private. <?php abstract class AbstractBaseClass1{ abstract public function addValue(); abstract protected function getValue(); } class ConcreteClass extends AbstractBaseClass1{ protected function addValue() { return "ConcreteClass"; } public function getValue() { return " Child Class"; } } $classobj = new ConcreteClass; $classobj->addValue(); ?> Fatal errorAccess level to ConcreteClass::addValue() must be public (as in class AbstractBaseClass1) Methods declared as abstract simply declare the method's signature - they cannot define anybody inside them. Although the body can be present inside a non-abstract method. <?php abstract class ParentClass{ abstract protected function printValue(){ return "Good morning"; } } class ClassA extends ParentClass{ protected function printValue() { return "ConcreteClass1"; } } $classobj = new ClassA; $classobj->printValue(); ?> PHP Fatal error: Abstract function ParentClass::printValue() cannot contain body An abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If it contains an abstract method then it should be declared as abstract. <?php class AbstractClass { abstract protected function getValue(); public function printData() { echo " Welcome to Tutorials Point"; } } $obj=new AbstractClass(); $obj->printData(); ?> PHP Fatal error: Class AbstractClass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue) It doesn't support multiple inheritance. <?php Abstract class SuperClass{ public abstract function test(); protected function welcome(){ echo "Good morning"; } } class ClassA extends SuperClass{ public function test(){ echo "Hello"; } protected function welcome(){ echo "Good afternoon"; } } class ClassB extends SuperClass{ public function test(){ echo "Hello"; } protected function welcome(){ echo "Good evening"; } } class ClassC extends ClassA, ClassB{ public function test1(){ $c = new self(); $c->welcome(); } } ?> Error Here we have declare SuperClass as an abstract class having a method test() and welcome() and, ClassA and ClassB and concrete classes extend from an abstract class. Then we have tried to create ClassC extending from ClassA and ClassB. As it is evident from the code, on calling the method welcome() using object ClassC, it’s impossible for the compiler to choose whether it has to call ClassA’s welcome() or ClassB’s welcome() method. So, to stay away from such complications, PHP does not support multiple inheritance. An abstract class can extend another abstract class, Abstract class can provide the implementation of the interface.
[ { "code": null, "e": 1302, "s": 1062, "text": "PHP5 comes with the object-oriented model with it, Some of the concepts of object-oriented model are: class, object, encapsulation, polymorphism, abstract and final classes, and methods, interfaces and inheritance, etc... In this article, " }, { "code": null, "e": 1483, "s": 1302, "text": "we will discuss Abstract Class and it's features related to the object-oriented techniques in PHP. Also, we will learn the implementation of Abstract Class along with few examples." }, { "code": null, "e": 1553, "s": 1483, "text": "But, before diving too deep,let's learn how to define abstract class." }, { "code": null, "e": 1843, "s": 1553, "text": "We can declare a class as abstract by affixing the name of the class with the abstract keyword. The definition is very clear, the class that contains abstract methods is known as abstract class. Abstract methods define in the abstract class just have name and arguments, and no other code." }, { "code": null, "e": 2085, "s": 1843, "text": "An object of an abstract class can't be made. Rather, we need to extend child classes that compute the definition of the function into the bodies of the abstract methods in the child classes and utilize these child classes to create objects." }, { "code": null, "e": 2151, "s": 2085, "text": "Let's discuss some important facts about abstract classes in PHP:" }, { "code": null, "e": 2452, "s": 2151, "text": "<?php\n abstract class base {\n abstract function printdata();\n public function getdata() {\n echo \"Tutorials Point\";\n }\n }\n class child extends base{\n public function printdata(){\n echo \"Good morning\";\n }\n }\n $obj = new child();\n $obj->getdata();\n?>" }, { "code": null, "e": 2468, "s": 2452, "text": "Tutorials Point" }, { "code": null, "e": 2684, "s": 2468, "text": "<?php\n abstract class AbstractClass{\n abstract protected function calculate();\n public function adddata() {\n echo \"Addition done\";\n }\n }\n $obj=new AbstractClass();\n $obj->adddata();\n?>" }, { "code": null, "e": 2761, "s": 2684, "text": "Fatal error: Uncaught Error: Cannot instantiate abstract class AbstractClass" }, { "code": null, "e": 3121, "s": 2761, "text": "All child class must define all the methods marked as abstract in the parent class, with all these methods need to be defined with the same signature or less restricted signature. Suppose In parent class if we define an abstract method with protected visibilty, in the child class execution it should be defined with protected aorpublic, but not with private." }, { "code": null, "e": 3532, "s": 3121, "text": "<?php\n abstract class AbstractBaseClass1{\n abstract public function addValue();\n abstract protected function getValue();\n }\n class ConcreteClass extends AbstractBaseClass1{\n protected function addValue() {\n return \"ConcreteClass\";\n }\n public function getValue() {\n return \" Child Class\";\n }\n }\n $classobj = new ConcreteClass;\n $classobj->addValue();\n?>" }, { "code": null, "e": 3633, "s": 3532, "text": "Fatal errorAccess level to ConcreteClass::addValue() must be public (as in class AbstractBaseClass1)" }, { "code": null, "e": 3805, "s": 3633, "text": "Methods declared as abstract simply declare the method's signature - they cannot define anybody inside them. Although the body can be present inside a non-abstract method." }, { "code": null, "e": 4117, "s": 3805, "text": "<?php\n abstract class ParentClass{\n abstract protected function printValue(){\n return \"Good morning\";\n }\n }\n class ClassA extends ParentClass{\n protected function printValue() {\n return \"ConcreteClass1\";\n }\n }\n $classobj = new ClassA;\n $classobj->printValue();\n?>" }, { "code": null, "e": 4198, "s": 4117, "text": "PHP Fatal error: Abstract function ParentClass::printValue() cannot contain body" }, { "code": null, "e": 4384, "s": 4198, "text": "An abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If it contains an abstract method then it should be declared as abstract." }, { "code": null, "e": 4609, "s": 4384, "text": "<?php\n class AbstractClass {\n abstract protected function getValue();\n public function printData() {\n echo \" Welcome to Tutorials Point\";\n }\n }\n $obj=new AbstractClass();\n $obj->printData();\n?>" }, { "code": null, "e": 4774, "s": 4609, "text": "PHP Fatal error: Class AbstractClass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)" }, { "code": null, "e": 4815, "s": 4774, "text": "It doesn't support multiple inheritance." }, { "code": null, "e": 5460, "s": 4815, "text": "<?php\n Abstract class SuperClass{\n public abstract function test();\n protected function welcome(){\n echo \"Good morning\";\n }\n }\n class ClassA extends SuperClass{\n public function test(){\n echo \"Hello\";\n }\n protected function welcome(){\n echo \"Good afternoon\";\n }\n }\n class ClassB extends SuperClass{\n public function test(){\n echo \"Hello\";\n }\n protected function welcome(){\n echo \"Good evening\";\n }\n }\n class ClassC extends ClassA, ClassB{\n public function test1(){\n $c = new self();\n $c->welcome();\n }\n }\n?>" }, { "code": null, "e": 5466, "s": 5460, "text": "Error" }, { "code": null, "e": 5986, "s": 5466, "text": "Here we have declare SuperClass as an abstract class having a method test() and welcome() and, ClassA and ClassB and concrete classes extend from an abstract class. Then we have tried to create ClassC extending from ClassA and ClassB. As it is evident from the code, on calling the method welcome() using object ClassC, it’s impossible for the compiler to choose whether it has to call ClassA’s welcome() or ClassB’s welcome() method. So, to stay away from such complications, PHP does not support multiple inheritance." }, { "code": null, "e": 6103, "s": 5986, "text": "An abstract class can extend another abstract class, Abstract class can provide the implementation of the interface." } ]
Advanced Excel Financial - PMT Function
The PMT function calculates the payment for a loan based on constant payments and a constant interest rate. PMT (rate, nper, pv, [fv], [type]) The present value, or the total amount that a series of future payments is worth now. Also known as the principal. The future value, or a cash balance you want to attain after the last payment is made. If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0. The number 0 (zero) or 1 and indicates when payments are due. Look at the Type-Payment Table below. The payment returned by PMT includes principal and interest but no taxes, reserve payments, or fees sometimes associated with loans. The payment returned by PMT includes principal and interest but no taxes, reserve payments, or fees sometimes associated with loans. Make sure that you are consistent about the units you use for specifying rate and nper If you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper If you make annual payments on the same loan, use 12 percent for rate and 4 for nper Make sure that you are consistent about the units you use for specifying rate and nper If you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper If you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper If you make annual payments on the same loan, use 12 percent for rate and 4 for nper If you make annual payments on the same loan, use 12 percent for rate and 4 for nper To find the total amount paid over the duration of the loan, multiply the returned PMT value by nper. To find the total amount paid over the duration of the loan, multiply the returned PMT value by nper. If the specified value of rate is less than or equal to -1, PMT returns #NUM! error value. If the specified value of rate is less than or equal to -1, PMT returns #NUM! error value. If the specified value of nper is equal to 0, PMT returns #NUM! error value. If the specified value of nper is equal to 0, PMT returns #NUM! error value. If any of the specified arguments is non-numeric, PMT returns #VALUE! error value. If any of the specified arguments is non-numeric, PMT returns #VALUE! error value. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 1962, "s": 1854, "text": "The PMT function calculates the payment for a loan based on constant payments and a constant interest rate." }, { "code": null, "e": 1998, "s": 1962, "text": "PMT (rate, nper, pv, [fv], [type])\n" }, { "code": null, "e": 2084, "s": 1998, "text": "The present value, or the total amount that a series of future payments is worth now." }, { "code": null, "e": 2113, "s": 2084, "text": "Also known as the principal." }, { "code": null, "e": 2200, "s": 2113, "text": "The future value, or a cash balance you want to attain after the last payment is made." }, { "code": null, "e": 2290, "s": 2200, "text": "If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0." }, { "code": null, "e": 2352, "s": 2290, "text": "The number 0 (zero) or 1 and indicates when payments are due." }, { "code": null, "e": 2390, "s": 2352, "text": "Look at the Type-Payment Table below." }, { "code": null, "e": 2523, "s": 2390, "text": "The payment returned by PMT includes principal and interest but no taxes, reserve payments, or fees sometimes associated with loans." }, { "code": null, "e": 2656, "s": 2523, "text": "The payment returned by PMT includes principal and interest but no taxes, reserve payments, or fees sometimes associated with loans." }, { "code": null, "e": 2960, "s": 2656, "text": "Make sure that you are consistent about the units you use for specifying rate and nper\n\nIf you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper\nIf you make annual payments on the same loan, use 12 percent for rate and 4 for nper\n\n" }, { "code": null, "e": 3047, "s": 2960, "text": "Make sure that you are consistent about the units you use for specifying rate and nper" }, { "code": null, "e": 3176, "s": 3047, "text": "If you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper" }, { "code": null, "e": 3305, "s": 3176, "text": "If you make monthly payments on a four-year loan at an annual interest rate of 12 percent, use 12%/12 for rate and 4*12 for nper" }, { "code": null, "e": 3390, "s": 3305, "text": "If you make annual payments on the same loan, use 12 percent for rate and 4 for nper" }, { "code": null, "e": 3475, "s": 3390, "text": "If you make annual payments on the same loan, use 12 percent for rate and 4 for nper" }, { "code": null, "e": 3577, "s": 3475, "text": "To find the total amount paid over the duration of the loan, multiply the returned PMT value by nper." }, { "code": null, "e": 3679, "s": 3577, "text": "To find the total amount paid over the duration of the loan, multiply the returned PMT value by nper." }, { "code": null, "e": 3770, "s": 3679, "text": "If the specified value of rate is less than or equal to -1, PMT returns #NUM! error value." }, { "code": null, "e": 3861, "s": 3770, "text": "If the specified value of rate is less than or equal to -1, PMT returns #NUM! error value." }, { "code": null, "e": 3938, "s": 3861, "text": "If the specified value of nper is equal to 0, PMT returns #NUM! error value." }, { "code": null, "e": 4015, "s": 3938, "text": "If the specified value of nper is equal to 0, PMT returns #NUM! error value." }, { "code": null, "e": 4098, "s": 4015, "text": "If any of the specified arguments is non-numeric, PMT returns #VALUE! error value." }, { "code": null, "e": 4181, "s": 4098, "text": "If any of the specified arguments is non-numeric, PMT returns #VALUE! error value." }, { "code": null, "e": 4228, "s": 4181, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 4264, "s": 4228, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 4278, "s": 4264, "text": " Arun Motoori" }, { "code": null, "e": 4313, "s": 4278, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4328, "s": 4313, "text": " Pavan Lalwani" }, { "code": null, "e": 4364, "s": 4328, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4373, "s": 4364, "text": " Inf Sid" }, { "code": null, "e": 4409, "s": 4373, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4424, "s": 4409, "text": " Yoda Learning" }, { "code": null, "e": 4459, "s": 4424, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4474, "s": 4459, "text": " William Fiset" }, { "code": null, "e": 4509, "s": 4474, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4523, "s": 4509, "text": " Sasha Miller" }, { "code": null, "e": 4530, "s": 4523, "text": " Print" }, { "code": null, "e": 4541, "s": 4530, "text": " Add Notes" } ]
How to explain your ML model with SHAP | by Yifei Huang | Towards Data Science
With exception of simple linear models like linear regression where you can easily look at the feature coefficients, machine learning models can often be a bit of a blackbox. It can be very difficult to understand why the model predicts a particular output, or to verify that the output makes intuitive sense. Model explainability is the practice that attempts to address this by Disaggregating and quantifying the key drivers of the model outputProviding users tools to intuitively reason about why and how the model inputs lead to the output, both in the aggregate and in specific instances Disaggregating and quantifying the key drivers of the model output Providing users tools to intuitively reason about why and how the model inputs lead to the output, both in the aggregate and in specific instances Humans tend to distrust that which we cannot understand. The inability to understand the model often leads to a lack of trust and adoption, resulting in potentially useful models sitting on the side lines. Even if the stakeholders and operators get over the initial hurdle of distrust, it is often not obvious how to operationalize the model output. Take a churn prediction model for example, the model may be able to tell you that a particular customer is 90% likely to churn, but without a clear understanding of the drivers, it’s not necessarily clear what can be done to prevent churn from happening. Of course, the magnitude of the hurdles depend on the specific use case. For certain classes of models like image recognition models (often deep learning based), it is very apparent if the output is right or wrong, and it is also fairly clear how to use the output. However, in many other use cases (like churn prediction, demand forecasting, credit underwriting, just to name a few), the lack of explainability poses significant obstacles between models and tangible impact. The most accurate model in the world is worthless if it is not being used to drive decisions and actions. Therefore it is crucial to make model as transparent and understandable to the stakeholders and operators, so that it can be leveraged and acted upon appropriately. There are quite a few different approaches (some of which are model type specific) to help explain ML models. Of these, I like SHAP the most, for a few different reasons SHAP is consistent, meaning it provides an exact decomposition of the impact each driver that can be summed to obtain the final predictionSHAP unifies 6 different approaches (including LIME and DeepLIFT) [2] to provide a unified interface for explaining all kinds of different models. Specifically, it has TreeExplainer for tree based (including ensemble) models, DeepExplainer for deep learning models, GradientExplainer for internal layers to deep learning models, LinearExplainer for linear models, and a model agnostic KernelExplainerSHAP provides helpful visualizations to aid in the understanding and explanation of models SHAP is consistent, meaning it provides an exact decomposition of the impact each driver that can be summed to obtain the final prediction SHAP unifies 6 different approaches (including LIME and DeepLIFT) [2] to provide a unified interface for explaining all kinds of different models. Specifically, it has TreeExplainer for tree based (including ensemble) models, DeepExplainer for deep learning models, GradientExplainer for internal layers to deep learning models, LinearExplainer for linear models, and a model agnostic KernelExplainer SHAP provides helpful visualizations to aid in the understanding and explanation of models I won’t go into the details of how SHAP works underneath the hood, except to say that it leverages game theory concepts to optimally allocates the marginal contribution for each input feature. For more details, I encourage the readers to check out the related publications. I will instead focus on a hands on example of how to use SHAP to understand a churn prediction model. The dataset used in this example can be obtained from Kaggle. Model setup Since the model is not the main focus of this walk through, I won’t delve too much into the details, except to provide some quicks notes for the sake of clarity Each row in the dataset is a telco subscriber and contain metadata about the location, tenure, usage metrics, as well as a label of whether the subscriber has churned Before model training, the dataset is pre-processed to convert boolean features into 1 and 0, categorical features into one-hot encoded dummies, and numerical features into Z-scores using the sklearn StandardScaler (remove mean and normalize by standard deviation) Minutes and charges features are found to be perfectly co-linear, so the minutes features are removed The sklearn GradientBoostingClassifier is used to model the churn probability and GridSearchCV is used to optimized the hyper-parameters The resulting model has a 96% accuracy in cross-validation The code that performs the above is as follows Explaining aggregate feature impact with SHAP summary_plot While SHAP can be used to explain any model, it offers an optimized method for tree ensemble models (which GradientBoostingClassifier is) in TreeExplainer. With a couple of lines of code, you can quickly visualize the aggregate feature impact on the model output as follows explainer = shap.TreeExplainer(gbt)shap_values = explainer.shap_values(processed_df[features])shap.summary_plot(shap_values, processed_df[features]) This chart contains a ton of information about the model at the aggregate level, but it may be a bit overwhelming for the uninitiated, so let me walk through what we are looking at The individual dots represent specific training examples.The y-axis are the input features ranked by magnitude of aggregate impact on the model output. The colors of the dots represent the value of the feature on the y-axis. Note that this does not mean the top feature is total_day_charge for every subscriber, we will get to explaining individual examples.The x-axis are the SHAP values, which as the chart indicates, are the impacts on the model output. These are the values that you would sum to get the final model output for any specific example. In this particularly case, since we are working with a classifier, they correspond to the log-odds ratio. A 0 means no marginal impact to the probability, positive value means increases to the churn probability, and negative value means decreases to the churn probability. The exact relationship between overall odds-ratio and probability is log(p/(1-p)), where p is the probability.SHAP adds a bit of perturbation to the vertical positions of points when there is a large number of points occupying the same space to help convey the high density. See the large bulb of points for total_day_charge The individual dots represent specific training examples. The y-axis are the input features ranked by magnitude of aggregate impact on the model output. The colors of the dots represent the value of the feature on the y-axis. Note that this does not mean the top feature is total_day_charge for every subscriber, we will get to explaining individual examples. The x-axis are the SHAP values, which as the chart indicates, are the impacts on the model output. These are the values that you would sum to get the final model output for any specific example. In this particularly case, since we are working with a classifier, they correspond to the log-odds ratio. A 0 means no marginal impact to the probability, positive value means increases to the churn probability, and negative value means decreases to the churn probability. The exact relationship between overall odds-ratio and probability is log(p/(1-p)), where p is the probability. SHAP adds a bit of perturbation to the vertical positions of points when there is a large number of points occupying the same space to help convey the high density. See the large bulb of points for total_day_charge What we can we learn from this plot Similar to what you can get from traditional feature importance plots from classifiers, we can see that the top 5 drivers of churn are total_day_charge, number_customer_service_calls, international_plan, total_eve_charge, and voice_mail_planWe can see how each of the feature impact churn probability β€” total_day_charge impact is asymmetrical and primarily drives up churn probability its value is high, but does not drive down churn probability to the same extent when its value is low. Contrast this with total_eve_charge which has a much more symmetrical impact.We can also see that subscribers who have international_plan are much more likely to churn than those who do not (red dots are far out on the right and blues dots are close to 0). Conversely, those who have voice_mail_plan are much less likely to churn than those do not. Similar to what you can get from traditional feature importance plots from classifiers, we can see that the top 5 drivers of churn are total_day_charge, number_customer_service_calls, international_plan, total_eve_charge, and voice_mail_plan We can see how each of the feature impact churn probability β€” total_day_charge impact is asymmetrical and primarily drives up churn probability its value is high, but does not drive down churn probability to the same extent when its value is low. Contrast this with total_eve_charge which has a much more symmetrical impact. We can also see that subscribers who have international_plan are much more likely to churn than those who do not (red dots are far out on the right and blues dots are close to 0). Conversely, those who have voice_mail_plan are much less likely to churn than those do not. Explaining specific feature impact with SHAP dependence_plot The impact of international_plan is very curious: why would subscribers who have it be more likely to churn than those who do not? SHAP has nice method called dependence_plot to help users unpack this. shap.dependence_plot("international_plan", shap_values, processed_df[features], interaction_index="total_intl_charge") The dependence plot is a deep dive into a specific feature to understand how the model output is impacted by different values of the feature, and how this is impacted by interaction with other features. Again, it can be a bit overwhelming for the uninitiated, so let me walk through it Dots represent individual training examplesColors represent value of the interaction feature (total_intl_charge)y-axis is the SHAP value for the main feature being examined (international_plan)x-axis is the value of the main feature being examined (international_plan, 0 for does not have plan, 1 for have plan) Dots represent individual training examples Colors represent value of the interaction feature (total_intl_charge) y-axis is the SHAP value for the main feature being examined (international_plan) x-axis is the value of the main feature being examined (international_plan, 0 for does not have plan, 1 for have plan) We can see, as before, those with international plan seems to have higher churn probability. Additionally, we can also see from the interaction feature of total international charge, that the red dots (higher total international charge) tends to have higher churn probability. Because of the bunching of points, it is difficult to make out what is happening, so let’s change the order of the two features to get a better look. shap.dependence_plot("total_intl_charge", shap_values, processed_df[features], interaction_index="international_plan") Now this plot tells a very interesting story. As a reminder, the x-axis here is total international charge transformed to the z-score, 0 = the average of all subscribers in the data, non-zero values = standard deviations away from the average value. We can see that for those who have international charge less than 1 standard deviation above the average, having an international plan actually lowers churn impact of international charge (red dots to the left of 1 have lower SHAP value than blue dots). However, as soon as you cross to the right of 1 standard deviation of international charge, having international plan actually significantly increases the churn impact (red dots to the right of 1 have much higher SHAP value than blue dots) It is not that people who have international plan are more likely churn, rather it is that people who have international plan and also high total international charge are a LOT more likely to churn. A plausible way to interpret this is that subscribers who have international plans expect to protected from high international charges, and when they are not, they are much more likely to cancel their subscription and go with a different provider who can offer better rates. This obviously requires additional investigation and perhaps also data collection to validate, but it is already a very interesting and actionable lead that can be pursued. Explaining individual examples with SHAP waterfall_plot In addition to understanding drivers at an aggregate level, SHAP also enables you to examine individual examples and understand the drivers of the final prediction. # visualize the first prediction's explanation using waterfall# 2020-12-28 there is a bug in the current implementation of the waterfall_plot, where the data structured expected does not match the api output, hence the need for a custom classi=1001class ShapObject: def __init__(self, base_values, data, values, feature_names): self.base_values = base_values # Single value self.data = data # Raw feature values for 1 row of data self.values = values # SHAP values for the same row of data self.feature_names = feature_names # Column names shap_object = ShapObject(base_values = explainer.expected_value[0], values = shap_values[i,:], feature_names = features, data = processed_df[features].iloc[i,:])shap.waterfall_plot(shap_object) This plot decomposes the drivers of a specific prediction. the x-axis is the SHAP value (or log-odds ratio). At the very bottom E[f(x)] = -2.84 indicates the baseline log-odds ratio of churn for the population, which translates to a 5.5% churn probability using the formula provided above. the y-axis is the name of features being represented by the arrows, along with their respective values. The impact (SHAP value) of each individual feature (less significant features are lumped together) is represented by the arrows that move the log-odds ratio to the left and right, starting from the baseline value. Red arrows increase the log-odds ratio, and blue arrows reduce the log-odds ratio This particular example has a final predicted log-odds ratio of -3.967 (or 1.8% churn probability) largely driven by relatively average total day charge, and the low number of customer service calls. Contrast this with the example below, where the final predicted log-odds ratio is 1.667 (or 84% churn probability), and is largely primarily by the very high number of customer service calls. ML model explainability creates the ability for users to understand and quantify the drivers of the model predictions, both in the aggregate and for specific examples Explainability is a key component to getting models adopted and operationalized in an actionable way SHAP is a useful tool for quickly enabling model explainability Hope this was a useful walk through. Feel free to reach out if you have comments or questions. Twitter | Linkedin | Medium
[ { "code": null, "e": 552, "s": 172, "text": "With exception of simple linear models like linear regression where you can easily look at the feature coefficients, machine learning models can often be a bit of a blackbox. It can be very difficult to understand why the model predicts a particular output, or to verify that the output makes intuitive sense. Model explainability is the practice that attempts to address this by" }, { "code": null, "e": 765, "s": 552, "text": "Disaggregating and quantifying the key drivers of the model outputProviding users tools to intuitively reason about why and how the model inputs lead to the output, both in the aggregate and in specific instances" }, { "code": null, "e": 832, "s": 765, "text": "Disaggregating and quantifying the key drivers of the model output" }, { "code": null, "e": 979, "s": 832, "text": "Providing users tools to intuitively reason about why and how the model inputs lead to the output, both in the aggregate and in specific instances" }, { "code": null, "e": 1584, "s": 979, "text": "Humans tend to distrust that which we cannot understand. The inability to understand the model often leads to a lack of trust and adoption, resulting in potentially useful models sitting on the side lines. Even if the stakeholders and operators get over the initial hurdle of distrust, it is often not obvious how to operationalize the model output. Take a churn prediction model for example, the model may be able to tell you that a particular customer is 90% likely to churn, but without a clear understanding of the drivers, it’s not necessarily clear what can be done to prevent churn from happening." }, { "code": null, "e": 2331, "s": 1584, "text": "Of course, the magnitude of the hurdles depend on the specific use case. For certain classes of models like image recognition models (often deep learning based), it is very apparent if the output is right or wrong, and it is also fairly clear how to use the output. However, in many other use cases (like churn prediction, demand forecasting, credit underwriting, just to name a few), the lack of explainability poses significant obstacles between models and tangible impact. The most accurate model in the world is worthless if it is not being used to drive decisions and actions. Therefore it is crucial to make model as transparent and understandable to the stakeholders and operators, so that it can be leveraged and acted upon appropriately." }, { "code": null, "e": 2501, "s": 2331, "text": "There are quite a few different approaches (some of which are model type specific) to help explain ML models. Of these, I like SHAP the most, for a few different reasons" }, { "code": null, "e": 3130, "s": 2501, "text": "SHAP is consistent, meaning it provides an exact decomposition of the impact each driver that can be summed to obtain the final predictionSHAP unifies 6 different approaches (including LIME and DeepLIFT) [2] to provide a unified interface for explaining all kinds of different models. Specifically, it has TreeExplainer for tree based (including ensemble) models, DeepExplainer for deep learning models, GradientExplainer for internal layers to deep learning models, LinearExplainer for linear models, and a model agnostic KernelExplainerSHAP provides helpful visualizations to aid in the understanding and explanation of models" }, { "code": null, "e": 3269, "s": 3130, "text": "SHAP is consistent, meaning it provides an exact decomposition of the impact each driver that can be summed to obtain the final prediction" }, { "code": null, "e": 3670, "s": 3269, "text": "SHAP unifies 6 different approaches (including LIME and DeepLIFT) [2] to provide a unified interface for explaining all kinds of different models. Specifically, it has TreeExplainer for tree based (including ensemble) models, DeepExplainer for deep learning models, GradientExplainer for internal layers to deep learning models, LinearExplainer for linear models, and a model agnostic KernelExplainer" }, { "code": null, "e": 3761, "s": 3670, "text": "SHAP provides helpful visualizations to aid in the understanding and explanation of models" }, { "code": null, "e": 4035, "s": 3761, "text": "I won’t go into the details of how SHAP works underneath the hood, except to say that it leverages game theory concepts to optimally allocates the marginal contribution for each input feature. For more details, I encourage the readers to check out the related publications." }, { "code": null, "e": 4199, "s": 4035, "text": "I will instead focus on a hands on example of how to use SHAP to understand a churn prediction model. The dataset used in this example can be obtained from Kaggle." }, { "code": null, "e": 4211, "s": 4199, "text": "Model setup" }, { "code": null, "e": 4372, "s": 4211, "text": "Since the model is not the main focus of this walk through, I won’t delve too much into the details, except to provide some quicks notes for the sake of clarity" }, { "code": null, "e": 4539, "s": 4372, "text": "Each row in the dataset is a telco subscriber and contain metadata about the location, tenure, usage metrics, as well as a label of whether the subscriber has churned" }, { "code": null, "e": 4804, "s": 4539, "text": "Before model training, the dataset is pre-processed to convert boolean features into 1 and 0, categorical features into one-hot encoded dummies, and numerical features into Z-scores using the sklearn StandardScaler (remove mean and normalize by standard deviation)" }, { "code": null, "e": 4906, "s": 4804, "text": "Minutes and charges features are found to be perfectly co-linear, so the minutes features are removed" }, { "code": null, "e": 5043, "s": 4906, "text": "The sklearn GradientBoostingClassifier is used to model the churn probability and GridSearchCV is used to optimized the hyper-parameters" }, { "code": null, "e": 5102, "s": 5043, "text": "The resulting model has a 96% accuracy in cross-validation" }, { "code": null, "e": 5149, "s": 5102, "text": "The code that performs the above is as follows" }, { "code": null, "e": 5208, "s": 5149, "text": "Explaining aggregate feature impact with SHAP summary_plot" }, { "code": null, "e": 5482, "s": 5208, "text": "While SHAP can be used to explain any model, it offers an optimized method for tree ensemble models (which GradientBoostingClassifier is) in TreeExplainer. With a couple of lines of code, you can quickly visualize the aggregate feature impact on the model output as follows" }, { "code": null, "e": 5631, "s": 5482, "text": "explainer = shap.TreeExplainer(gbt)shap_values = explainer.shap_values(processed_df[features])shap.summary_plot(shap_values, processed_df[features])" }, { "code": null, "e": 5812, "s": 5631, "text": "This chart contains a ton of information about the model at the aggregate level, but it may be a bit overwhelming for the uninitiated, so let me walk through what we are looking at" }, { "code": null, "e": 6963, "s": 5812, "text": "The individual dots represent specific training examples.The y-axis are the input features ranked by magnitude of aggregate impact on the model output. The colors of the dots represent the value of the feature on the y-axis. Note that this does not mean the top feature is total_day_charge for every subscriber, we will get to explaining individual examples.The x-axis are the SHAP values, which as the chart indicates, are the impacts on the model output. These are the values that you would sum to get the final model output for any specific example. In this particularly case, since we are working with a classifier, they correspond to the log-odds ratio. A 0 means no marginal impact to the probability, positive value means increases to the churn probability, and negative value means decreases to the churn probability. The exact relationship between overall odds-ratio and probability is log(p/(1-p)), where p is the probability.SHAP adds a bit of perturbation to the vertical positions of points when there is a large number of points occupying the same space to help convey the high density. See the large bulb of points for total_day_charge" }, { "code": null, "e": 7021, "s": 6963, "text": "The individual dots represent specific training examples." }, { "code": null, "e": 7323, "s": 7021, "text": "The y-axis are the input features ranked by magnitude of aggregate impact on the model output. The colors of the dots represent the value of the feature on the y-axis. Note that this does not mean the top feature is total_day_charge for every subscriber, we will get to explaining individual examples." }, { "code": null, "e": 7902, "s": 7323, "text": "The x-axis are the SHAP values, which as the chart indicates, are the impacts on the model output. These are the values that you would sum to get the final model output for any specific example. In this particularly case, since we are working with a classifier, they correspond to the log-odds ratio. A 0 means no marginal impact to the probability, positive value means increases to the churn probability, and negative value means decreases to the churn probability. The exact relationship between overall odds-ratio and probability is log(p/(1-p)), where p is the probability." }, { "code": null, "e": 8117, "s": 7902, "text": "SHAP adds a bit of perturbation to the vertical positions of points when there is a large number of points occupying the same space to help convey the high density. See the large bulb of points for total_day_charge" }, { "code": null, "e": 8153, "s": 8117, "text": "What we can we learn from this plot" }, { "code": null, "e": 8990, "s": 8153, "text": "Similar to what you can get from traditional feature importance plots from classifiers, we can see that the top 5 drivers of churn are total_day_charge, number_customer_service_calls, international_plan, total_eve_charge, and voice_mail_planWe can see how each of the feature impact churn probability β€” total_day_charge impact is asymmetrical and primarily drives up churn probability its value is high, but does not drive down churn probability to the same extent when its value is low. Contrast this with total_eve_charge which has a much more symmetrical impact.We can also see that subscribers who have international_plan are much more likely to churn than those who do not (red dots are far out on the right and blues dots are close to 0). Conversely, those who have voice_mail_plan are much less likely to churn than those do not." }, { "code": null, "e": 9232, "s": 8990, "text": "Similar to what you can get from traditional feature importance plots from classifiers, we can see that the top 5 drivers of churn are total_day_charge, number_customer_service_calls, international_plan, total_eve_charge, and voice_mail_plan" }, { "code": null, "e": 9557, "s": 9232, "text": "We can see how each of the feature impact churn probability β€” total_day_charge impact is asymmetrical and primarily drives up churn probability its value is high, but does not drive down churn probability to the same extent when its value is low. Contrast this with total_eve_charge which has a much more symmetrical impact." }, { "code": null, "e": 9829, "s": 9557, "text": "We can also see that subscribers who have international_plan are much more likely to churn than those who do not (red dots are far out on the right and blues dots are close to 0). Conversely, those who have voice_mail_plan are much less likely to churn than those do not." }, { "code": null, "e": 9890, "s": 9829, "text": "Explaining specific feature impact with SHAP dependence_plot" }, { "code": null, "e": 10092, "s": 9890, "text": "The impact of international_plan is very curious: why would subscribers who have it be more likely to churn than those who do not? SHAP has nice method called dependence_plot to help users unpack this." }, { "code": null, "e": 10211, "s": 10092, "text": "shap.dependence_plot(\"international_plan\", shap_values, processed_df[features], interaction_index=\"total_intl_charge\")" }, { "code": null, "e": 10497, "s": 10211, "text": "The dependence plot is a deep dive into a specific feature to understand how the model output is impacted by different values of the feature, and how this is impacted by interaction with other features. Again, it can be a bit overwhelming for the uninitiated, so let me walk through it" }, { "code": null, "e": 10809, "s": 10497, "text": "Dots represent individual training examplesColors represent value of the interaction feature (total_intl_charge)y-axis is the SHAP value for the main feature being examined (international_plan)x-axis is the value of the main feature being examined (international_plan, 0 for does not have plan, 1 for have plan)" }, { "code": null, "e": 10853, "s": 10809, "text": "Dots represent individual training examples" }, { "code": null, "e": 10923, "s": 10853, "text": "Colors represent value of the interaction feature (total_intl_charge)" }, { "code": null, "e": 11005, "s": 10923, "text": "y-axis is the SHAP value for the main feature being examined (international_plan)" }, { "code": null, "e": 11124, "s": 11005, "text": "x-axis is the value of the main feature being examined (international_plan, 0 for does not have plan, 1 for have plan)" }, { "code": null, "e": 11551, "s": 11124, "text": "We can see, as before, those with international plan seems to have higher churn probability. Additionally, we can also see from the interaction feature of total international charge, that the red dots (higher total international charge) tends to have higher churn probability. Because of the bunching of points, it is difficult to make out what is happening, so let’s change the order of the two features to get a better look." }, { "code": null, "e": 11670, "s": 11551, "text": "shap.dependence_plot(\"total_intl_charge\", shap_values, processed_df[features], interaction_index=\"international_plan\")" }, { "code": null, "e": 11716, "s": 11670, "text": "Now this plot tells a very interesting story." }, { "code": null, "e": 12414, "s": 11716, "text": "As a reminder, the x-axis here is total international charge transformed to the z-score, 0 = the average of all subscribers in the data, non-zero values = standard deviations away from the average value. We can see that for those who have international charge less than 1 standard deviation above the average, having an international plan actually lowers churn impact of international charge (red dots to the left of 1 have lower SHAP value than blue dots). However, as soon as you cross to the right of 1 standard deviation of international charge, having international plan actually significantly increases the churn impact (red dots to the right of 1 have much higher SHAP value than blue dots)" }, { "code": null, "e": 12613, "s": 12414, "text": "It is not that people who have international plan are more likely churn, rather it is that people who have international plan and also high total international charge are a LOT more likely to churn." }, { "code": null, "e": 13061, "s": 12613, "text": "A plausible way to interpret this is that subscribers who have international plans expect to protected from high international charges, and when they are not, they are much more likely to cancel their subscription and go with a different provider who can offer better rates. This obviously requires additional investigation and perhaps also data collection to validate, but it is already a very interesting and actionable lead that can be pursued." }, { "code": null, "e": 13117, "s": 13061, "text": "Explaining individual examples with SHAP waterfall_plot" }, { "code": null, "e": 13282, "s": 13117, "text": "In addition to understanding drivers at an aggregate level, SHAP also enables you to examine individual examples and understand the drivers of the final prediction." }, { "code": null, "e": 14130, "s": 13282, "text": "# visualize the first prediction's explanation using waterfall# 2020-12-28 there is a bug in the current implementation of the waterfall_plot, where the data structured expected does not match the api output, hence the need for a custom classi=1001class ShapObject: def __init__(self, base_values, data, values, feature_names): self.base_values = base_values # Single value self.data = data # Raw feature values for 1 row of data self.values = values # SHAP values for the same row of data self.feature_names = feature_names # Column names shap_object = ShapObject(base_values = explainer.expected_value[0], values = shap_values[i,:], feature_names = features, data = processed_df[features].iloc[i,:])shap.waterfall_plot(shap_object)" }, { "code": null, "e": 14189, "s": 14130, "text": "This plot decomposes the drivers of a specific prediction." }, { "code": null, "e": 14420, "s": 14189, "text": "the x-axis is the SHAP value (or log-odds ratio). At the very bottom E[f(x)] = -2.84 indicates the baseline log-odds ratio of churn for the population, which translates to a 5.5% churn probability using the formula provided above." }, { "code": null, "e": 14524, "s": 14420, "text": "the y-axis is the name of features being represented by the arrows, along with their respective values." }, { "code": null, "e": 14820, "s": 14524, "text": "The impact (SHAP value) of each individual feature (less significant features are lumped together) is represented by the arrows that move the log-odds ratio to the left and right, starting from the baseline value. Red arrows increase the log-odds ratio, and blue arrows reduce the log-odds ratio" }, { "code": null, "e": 15212, "s": 14820, "text": "This particular example has a final predicted log-odds ratio of -3.967 (or 1.8% churn probability) largely driven by relatively average total day charge, and the low number of customer service calls. Contrast this with the example below, where the final predicted log-odds ratio is 1.667 (or 84% churn probability), and is largely primarily by the very high number of customer service calls." }, { "code": null, "e": 15379, "s": 15212, "text": "ML model explainability creates the ability for users to understand and quantify the drivers of the model predictions, both in the aggregate and for specific examples" }, { "code": null, "e": 15480, "s": 15379, "text": "Explainability is a key component to getting models adopted and operationalized in an actionable way" }, { "code": null, "e": 15544, "s": 15480, "text": "SHAP is a useful tool for quickly enabling model explainability" } ]
CouchDB - Quick Guide
Database management system provides mechanism for storage and retrieval of data. There are three main types of database management systems namely RDBMS (Relational Database management Systems), OLAP (Online Analytical Processing Systems) and NoSQL. RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows. It stores only structured data. Online Analytical Processing Server (OLAP) is based on the multidimensional data model. It allows managers and analysts to get an insight of the information through fast, consistent, and interactive access to information. A NoSQL database (sometimes called as Not Only SQL) is a database that provides a mechanism to store and retrieve data other than the tabular relations used in relational databases. These databases are schema-free, support easy replication, have simple API, eventually consistent, and can handle huge amounts of data (big data). The primary objective of a NoSQL database is to have the following βˆ’ Simplicity of design, Horizontal scaling, and Finer control over availability. NoSQL databases use different data structures compared to relational databases. It makes some operations faster in NoSQL. The suitability of a given NoSQL database depends on the problem it must solve. These databases store both structured data and unstructured data like audio files, video files, documents, etc. These NoSQL databases are classified into three types and they are explained below. Key-value Store βˆ’ These databases are designed for storing data in key-value pairs and these databases will not have any schema. In these databases, each data value consists of an indexed key and a value for that key. Examples βˆ’ BerkeleyDB, Cassandra, DynamoDB, Riak. Column Store βˆ’ In these databases, data is stored in cells grouped in columns of data, and these columns are further grouped into Column families. These column families can contain any number of columns. Examples βˆ’ BigTable, HBase, and HyperTable. Document Store βˆ’ These are the databases developed on the basic idea of key-value stores where "documents" contain more complex data. Here, each document is assigned a unique key, which is used to retrieve the document. These are designed for storing, retrieving, and managing document-oriented information, also known as semi-structured data. Examples βˆ’ CouchDB and MongoDB. CouchDB is an open source database developed by Apache software foundation. The focus is on the ease of use, embracing the web. It is a NoSQL document store database. It uses JSON, to store data (documents), java script as its query language to transform the documents, http protocol for api to access the documents, query the indices with the web browser. It is a multi master application released in 2005 and it became an apache project in 2008. CouchDB have an HTTP-based REST API, which helps to communicate with the database easily. And the simple structure of HTTP resources and methods (GET, PUT, DELETE) are easy to understand and use. CouchDB have an HTTP-based REST API, which helps to communicate with the database easily. And the simple structure of HTTP resources and methods (GET, PUT, DELETE) are easy to understand and use. As we store data in the flexible document-based structure, there is no need to worry about the structure of the data. As we store data in the flexible document-based structure, there is no need to worry about the structure of the data. Users are provided with powerful data mapping, which allows querying, combining, and filtering the information. Users are provided with powerful data mapping, which allows querying, combining, and filtering the information. CouchDB provides easy-to-use replication, using which you can copy, share, and synchronize the data between databases and machines. CouchDB provides easy-to-use replication, using which you can copy, share, and synchronize the data between databases and machines. Database is the outermost data structure/container in CouchDB. Database is the outermost data structure/container in CouchDB. Each database is a collection of independent documents. Each database is a collection of independent documents. Each document maintains its own data and self-contained schema. Each document maintains its own data and self-contained schema. Document metadata contains revision information, which makes it possible to merge the differences occurred while the databases were disconnected. Document metadata contains revision information, which makes it possible to merge the differences occurred while the databases were disconnected. CouchDB implements multi version concurrency control, to avoid the need to lock the database field during writes. CouchDB implements multi version concurrency control, to avoid the need to lock the database field during writes. CouchDB is a document storage NoSQL database. It provides the facility of storing documents with unique names, and it also provides an API called RESTful HTTP API for reading and updating (add, edit, delete) database documents. In CouchDB, documents are the primary unit of data and they also include metadata. Document fields are uniquely named and contain values of varying types (text, number, Boolean, lists, etc.), and there is no set limit to text size or element count. Document updates (add, edit, delete) follow Atomicity, i.e., they will be saved completely or not saved at all. The database will not have any partially saved or edited documents. { "field" : "value", "field" : "value", "field" : "value", } CouchDB contains ACID properties as one of its features. Consistency βˆ’ When the data in CouchDB was once committed, then this data will not be modified or overwritten. Thus, CouchDB ensures that the database file will always be in a consistent state. A multi-Version Concurrency Control (MVCC) model is used by CouchDB reads, because of which the client will see a consistent snapshot of the database from the beginning to the end of the read operation. Whenever a documents is updated, CouchDB flushes the data into the disk, and the updated database header is written in two consecutive and identical chunks to make up the first 4k of the file, and then synchronously flushed to disk. Partial updates during the flush will be discarded. If the failure occurred while committing the header, a surviving copy of the previous identical headers will remain, ensuring coherency of all previously committed data. Except the header area, consistency checks or fix-ups after a crash or a power failure are never necessary. Whenever the space in the database file got wasted above certain extent, all the active data will be copied (cloned) to a new file. When the copying process is entirely done, then the old file will be discarded. All this is done by compaction process. The database remains online during the compaction and all updates and reads are allowed to complete successfully. Data in CouchDB is stored in semi-structured documents that are flexible with individual implicit structures, but it is a simple document model for data storage and sharing. If we want see our data in many different ways, we need a way to filter, organize and report on data that hasn’t been decomposed into tables. To solve this problem, CouchDB provides a view model. Views are the method of aggregating and reporting on the documents in a database, and are built on-demand to aggregate, join and report on database documents. Because views are built dynamically and don’t affect the underlying document, you can have as many different view representations of the same data as you like. CouchDB was written in Erlang programming language. It was started by Damien Katz in 2005. CouchDB became an Apache project in 2008. The current version of CouchDB is 1.61. This chapter teaches you how to install CouchDB in windows as well as Linux systems. The official website for CouchDB is https://couchdb.apache.org. If you click the given link, you can get the home page of the CouchDB official website as shown below. If you click on the download button that will lead to a page where download links of CouchDB in various formats are provided. The following snapshot illustrates the same. Choose the download link for windows systems and select one of the provided mirrors to start your download. CouchDB will be downloaded to your system in the form of setup file named setup-couchdb-1.6.1_R16B02.exe. Run the setup file and proceed with the installation. After installation, open built-in web interface of CouchDB by visiting the following link: http://127.0.0.1:5984/. If everything goes fine, this will give you a web page, which have the following output. { "couchdb":"Welcome","uuid":"c8d48ac61bb497f4692b346e0f400d60", "version":"1.6.1", "vendor":{ "version":"1.6.1","name":"The Apache Software Foundation" } } You can interact with the CouchDB web interface by using the following url βˆ’ http://127.0.0.1:5984/_utils/ This shows you the index page of Futon, which is the web interface of CouchDB. For many of the Linux flavored systems, they provide CouchDB internally. To install this CouchDB follow the instructions. On Ubuntu and Debian you can use βˆ’ sudo aptitude install couchdb On Gentoo Linux there is a CouchDB ebuild available βˆ’ sudo emerge couchdb If your Linux system does not have CouchDB, follow the next section to install CouchDB and its dependencies. Following is the list of dependencies that are to be installed to get CouchDB in your systemβˆ’ Erlang OTP ICU OpenSSL Mozilla SpiderMonkey GNU Make GNU Compiler Collection libcurl help2man Python for docs Python Sphinx To install these dependencies, type the following commands in the terminal. Here we are using Centos 6.5 and the following commands will install the required softwares compatible to Centos 6.5. $sudo yum install autoconf $sudo yum install autoconf-archive $sudo yum install automake $sudo yum install curl-devel $sudo yum install erlang-asn1 $sudo yum install erlang-erts $sudo yum install erlang-eunit $sudo yum install erlang-os_mon $sudo yum install erlang-xmerl $sudo yum install help2man $sudo yum install js-devel $sudo yum install libicu-devel $sudo yum install libtool $sudo yum install perl-Test-Harness Note βˆ’ For all these commands you need to use sudo. The following procedure converts a normal user to a sudoer. Login as root in admin user Login as root in admin user Open sudo file using the following command βˆ’ Open sudo file using the following command βˆ’ visudo Then edit as shown below to give your existing user the sudoer privileges βˆ’ Hadoop All=(All) All , and press esc : x to write the changes to the file. After downloading all the dependencies in your system, download CouchDB following the given instructions. Apache software foundation will not provide the complete .tar file for CouchDB, so you have to install it from the source. Create a new directory to install CouchDB, browse to such created directory and download CouchDB source by executing the following commands βˆ’ $ cd $ mkdir CouchDB $ cd CouchDB/ $ wget http://www.google.com/url?q=http%3A%2F%2Fwww.apache.org%2Fdist%2Fcouchdb%2Fsource%2F1.6.1%2Fapache-couchdb-1.6.1.tar.gz This will download CouchDB source file into your system. Now unzip the apache-couchdb-1.6.1.tar.gz as shown below. $ tar zxvf apache-couchdb-1.6.1.tar.gz To configure CouchDB, do the following βˆ’ Browse to the home folder of CouchDB. Login as superuser. Configure using ./configure prompt as shown below βˆ’ $ cd apache-couchdb-1.6.1 $ su Password: # ./configure --with-erlang=/usr/lib64/erlang/usr/include/ It gives you the following output similar to that shown below with a concluding line saying βˆ’ You have configured Apache CouchDB, time to relax. # ./configure --with-erlang=/usr/lib64/erlang/usr/include/ checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... gawk checking whether make sets $(MAKE)... yes checking how to create a ustar tar archive... gnutar ................................................................. ............................ config.status: creating var/Makefile config.status: creating config.h config.status: config.h is unchanged config.status: creating src/snappy/google-snappy/config.h config.status: src/snappy/google-snappy/config.h is unchanged config.status: executing depfiles commands config.status: executing libtool commands You have configured Apache CouchDB, time to relax. Run `make && sudo make install' to install. Now type the following command to install CouchDB in your system. # make && sudo make install It installs CouchDB in your system with a concluding line saying βˆ’ You have installed Apache CouchDB, time to relax. To start CouchDB, browse to the CouchDB home folder and use the following command βˆ’ $ cd apache-couchdb-1.6.1 $ cd etc $ couchdb start It starts CouchDB giving the following output: βˆ’ Apache CouchDB 1.6.1 (LogLevel=info) is starting. Apache CouchDB has started. Time to relax. [info] [lt;0.31.0gt;] Apache CouchDB has started on http://127.0.0.1:5984/ [info] [lt;0.112.0gt;] 127.0.0.1 - - GET / 200 [info] [lt;0.112.0gt;] 127.0.0.1 - - GET /favicon.ico 200 Since CouchDB is a web interface, try to type the following homepage url in the browser. http://127.0.0.1:5984/ It produces the following output βˆ’ { "couchdb":"Welcome", "uuid":"8f0d59acd0e179f5e9f0075fa1f5e804", "version":"1.6.1", "vendor":{ "name":"The Apache Software Foundation", "version":"1.6.1" } } cURL utility is a way to communicate with CouchDB. It is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, TFTP, DICT, TELNET, LDAP or FILE). The command is designed to work without user interaction. cURL offers a busload of useful tricks like proxy support, user authentication, ftp upload, HTTP post, SSL (https:) connections, cookies, file transfer resume and more. The cURL utility is available in operating systems such as UNIX, Linux, Mac OS X and Windows. It is a command line utility using which user can access HTTP protocol straight away from the command line. This chapter teaches you how to use cURL utility. You can access any website using cURL utility by simply typing cURL followed by the website address as shown below βˆ’ curl www.tutorialspoint.com/ By default, the cURL utility returns the source code of the requested page. It displays this code on the terminal window. cURL utility provides various options to work with, and you can see them in cURL utility help. The following code shows some portion of cURL help. $ curl --help Usage: curl [options...] <url> Options: (H) means HTTP/HTTPS only, (F) means FTP only --anyauth Pick "any" authentication method (H) -a/--append Append to target file when uploading (F/SFTP) --basic Use HTTP Basic Authentication (H) --cacert <file> CA certificate to verify peer against (SSL) -d/--data <data> HTTP POST data (H) --data-ascii <data> HTTP POST ASCII data (H) --data-binary <data> HTTP POST binary data (H) --data-urlencode <name=data/name@filename> HTTP POST data urlencoded (H) --delegation STRING GSS-API delegation permission --digest Use HTTP Digest Authentication (H) --disable-eprt Inhibit using EPRT or LPRT (F) --disable-epsv Inhibit using EPSV (F) -F/--form <name=content> Specify HTTP multipart POST data (H) --form-string <name=string> Specify HTTP multipart POST data (H) --ftp-account <data> Account data to send when requested by server (F) --ftp-alternative-to-user <cmd> String to replace "USER [name]" (F) --ftp-create-dirs Create the remote dirs if not present (F) --ftp-method [multi cwd/no cwd/single cwd] Control CWD usage (F) --ftp-pasv Use PASV/EPSV instead of PORT (F) -G/--get Send the -d data with a HTTP GET (H) -H/--header <line> Custom header to pass to server (H) -I/--head Show document info only -h/--help This help text --hostpubmd5 <md5> Hex encoded MD5 string of the host public key. (SSH) -0/--http1.0 Use HTTP 1.0 (H) --ignore-content-length Ignore the HTTP Content-Length header -i/--include Include protocol headers in the output (H/F) -M/--manual Display the full manual -o/--output <file> Write output to <file> instead of stdout --pass <pass> Pass phrase for the private key (SSL/SSH) --post301 Do not switch to GET after following a 301 redirect (H) --post302 Do not switch to GET after following a 302 redirect (H) -O/--remote-name Write output to a file named as the remote file --remote-name-all Use the remote file name for all URLs -R/--remote-time Set the remote file's time on the local output -X/--request <command> Specify request command to use --retry <num> Retry request <num> times if transient problems occur --retry-delay <seconds> When retrying, wait this many seconds between each --retry-max-time <seconds> Retry only within this period -T/--upload-file <file> Transfer <file> to remote site --url <URL> Set URL to work with -B/--use-ascii Use ASCII/text transfer While communicating with CouchDB, certain options of cURL utility were extensively used. Following are the brief descriptions of some important options of cURL utility including those used by CouchDB. (HTTP) Specifies a custom request method used when communicating with the HTTP server. The specified request is used instead of the method otherwise used (which defaults to GET). Read the HTTP 1.1 specification for details and explanations. (FTP) Specifies a custom FTP command to use instead of LIST when doing file lists with ftp. (HTTP) Extra header is used when getting a web page. Note that if you add a custom header that has the same name as one of the internal ones cURL would use, your externally set header will be used instead of the internal one. This allows you to make even trickier work than cURL would normally do. You should not replace internally set headers without perfectly knowing what you’re doing. Replacing an internal header with the one without content on the right side of the colon, will prevent that header from appearing. cURL assures that each header you add/replace get sent with the proper end of line marker. Neither you should add that as a part of the header content nor add newlines or carriage returns to disorder things. See also the -A/--user-agent and -e/--referer options. This option can be used multiple times to add/replace/remove multiple headers. Using this flag of cURL, you can send data along with the HTTP POST request to the server, as if it was filled by the user in the form and submitted. Example Suppose there is a website and you want to login into it or send some data to the website using –d flag of cURL utility as shown below. curl -X PUT http://mywebsite.com/login.html -d userid=001 -d password=tutorialspoint It sends a post chunk that looks like "userid=001&password=tutorialspoint". Likewise you can also send documents (JSON ) using -d flag. Using this flag, cURL writes the output of the request to a file. Example The following example shows the use of -o flag of cURL utility. $ curl -o example.html www.tutorialspoint.com/index.htm % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 81193 0 81193 0 0 48168 0 --:--:-- 0:00:01 --:--:-- 58077 This gets the source code of the homepage of tutorialspoint.com, creates a file named example.com and saves the output in the file named example.html. Following is the snapshot of the example.html. This flag is similar to –o, the only difference is with this flag, a new file with the same name as the requested url was created, and the source code of the requested url will be copied to it. Example The following example shows the use of -O flag of cURL utility. $ curl -O www.tutorialspoint.com/index.htm % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 81285 0 81285 0 0 49794 0 --:--:-- 0:00:01 --:--:-- 60077 It creates a new file with the name index.htm and saves the source code of the index page of tutorialspoint.com in it. You can access the homepage of the CouchDB by sending a GET request to the CouchDB instance installed. First of all make sure you have installed CouchDB in your Linux environment and it is running successfully, and then use the following syntax to send a get request to the CouchDB instance. curl http://127.0.0.1:5984/ This gives you a JSON document as shown below where CouchDB specifies the details such as version number, name of the vendor, and version of the software. $ curl http://127.0.0.1:5984/ { "couchdb" : "Welcome", "uuid" : "8f0d59acd0e179f5e9f0075fa1f5e804", "version" : "1.6.1", "vendor" : { "name":"The Apache Software Foundation", "version":"1.6.1" } } You can get the list of all the databases created, by sending a get request along with the string "_all_dbs string ". Following is the syntax to get the list of all databases in CouchDB. curl -X GET http://127.0.0.1:5984/_all_dbs It gives you the list of all databases in CouchDB as shown below. $ curl -X GET http://127.0.0.1:5984/_all_dbs [ "_replicator" , "_users" ] You can create a database in CouchDB using cURL with PUT header using the following syntax βˆ’ $ curl -X PUT http://127.0.0.1:5984/database_name As an example, using the above given syntax create a database with name my_database as shown below. $ curl -X PUT http://127.0.0.1:5984/my_database {"ok":true} Verify whether the database is created, by listing out all the databases as shown below. Here you can observe the name of newly created database, "my_database" in the list $ curl -X GET http://127.0.0.1:5984/_all_dbs [ "_replicator " , "_users" , "my_database" ] You can get the information about database using the get request along with the database name. Following is the syntax to get the database information. As an example let us get the information of the database named my_database as shown below. Here you can get the information about your database as a response. $ curl -X GET http://127.0.0.1:5984/my_database { "db_name" : "my_database", "doc_count" : 0, "doc_del_count" : 0, "update_seq" : 0, "purge_seq" : 0, "compact_running" : false, "disk_size" : 79, "data_size" : 0, "instance_start_time" : "1423628520835029", "disk_format_version" : 6, "committed_update_seq" : 0 } Futon is the built-in, web based, administration interface of CouchDB. It provides a simple graphical interface using which you can interact with CouchDB. It is a naive interface and it provides full access to all CouchDB features. Following is the list of those features βˆ’ Creates databases. Destroys databases. Creates documents. Updates documents. Edits documents. Deletes documents. Make sure CouchDB is running and then open the following url in browser βˆ’ http://127.0.0.1:5984/_utils/ If you open this url, it displays the Futon home page as shown below βˆ’ On the left hand side of this page you can observe the list of all the current databases of CouchDB. In this illustration, we have a database named my_database, along with system defined databases _replicator and _user. On the left hand side of this page you can observe the list of all the current databases of CouchDB. In this illustration, we have a database named my_database, along with system defined databases _replicator and _user. On the right hand side you can see the following βˆ’ Tools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB. Documentation βˆ’ This section contains the complete documentation for the recent version of CouchDB. Diagnostics βˆ’ Under this you can verify the installation of CouchDB. Recent Databases βˆ’ Under this you can find the names of recently added databases. On the right hand side you can see the following βˆ’ Tools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB. Tools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB. Documentation βˆ’ This section contains the complete documentation for the recent version of CouchDB. Documentation βˆ’ This section contains the complete documentation for the recent version of CouchDB. Diagnostics βˆ’ Under this you can verify the installation of CouchDB. Diagnostics βˆ’ Under this you can verify the installation of CouchDB. Recent Databases βˆ’ Under this you can find the names of recently added databases. Recent Databases βˆ’ Under this you can find the names of recently added databases. Using HTTP request headers, you can communicate with CouchDB. Through these requests we can retrieve data from the database, store data in to the database in the form of documents, and we can view as well as format the documents stored in a database. While communicating with the database we will use different request formats like get, head, post, put, delete, and copy. For all operations in CouchDB, the input data and the output data structures will be in the form of JavaScript Object Notation (JSON) object. Following are the different request formats of HTTP Protocol used to communicate with CouchDB. GET βˆ’ This format is used to get a specific item. To get different items, you have to send specific url patterns. In CouchDB using this GET request, we can get static items, database documents and configuration, and statistical information in the form of JSON documents (in most cases). GET βˆ’ This format is used to get a specific item. To get different items, you have to send specific url patterns. In CouchDB using this GET request, we can get static items, database documents and configuration, and statistical information in the form of JSON documents (in most cases). HEAD βˆ’ The HEAD method is used to get the HTTP header of a GET request without the body of the response. HEAD βˆ’ The HEAD method is used to get the HTTP header of a GET request without the body of the response. POST βˆ’ Post request is used to upload data. In CouchDB using POST request, you can set values, upload documents, set document values, and can also start certain administration commands. POST βˆ’ Post request is used to upload data. In CouchDB using POST request, you can set values, upload documents, set document values, and can also start certain administration commands. PUT βˆ’ Using PUT request, you can create new objects, databases, documents, views and design documents. PUT βˆ’ Using PUT request, you can create new objects, databases, documents, views and design documents. DELETE βˆ’ Using DELETE request, you can delete documents, views, and design documents. DELETE βˆ’ Using DELETE request, you can delete documents, views, and design documents. COPY βˆ’ Using COPY method, you can copy documents and objects. COPY βˆ’ Using COPY method, you can copy documents and objects. HTTP headers should be supplied to get the right format and encoding. While sending the request to the CouchDB server, you can send Http request headers along with the request. Following are the different Http request headers. Content-type βˆ’ This Header is used to specify the content type of the data that we supply to the server along with the request. Mostly the type of the content we send along with the request will be MIME type or JSON (application/json). Using Content-type on a request is highly recommended. Content-type βˆ’ This Header is used to specify the content type of the data that we supply to the server along with the request. Mostly the type of the content we send along with the request will be MIME type or JSON (application/json). Using Content-type on a request is highly recommended. Accept βˆ’ This header is used to specify the server, the list of data types that client can understand, so that the server will send its response using those data types. Generally here, you can send the list of MIME data types the client accepts, separated by colons. Though, using Accept in queries of CouchDB is not required, it is highly recommended to ensure that the data returned can be processed by the client. Accept βˆ’ This header is used to specify the server, the list of data types that client can understand, so that the server will send its response using those data types. Generally here, you can send the list of MIME data types the client accepts, separated by colons. Though, using Accept in queries of CouchDB is not required, it is highly recommended to ensure that the data returned can be processed by the client. These are the headers of the response sent by the server. These headers give information about the content send by the server as response. Content-type βˆ’ This header specifies the MIME type of the data returned by the server. For most request, the returned MIME type is text/plain. Content-type βˆ’ This header specifies the MIME type of the data returned by the server. For most request, the returned MIME type is text/plain. Cache-control βˆ’ This header suggests the client about treating the information sent by the server. CouchDB mostly returns the must-revalidate, which indicates that the information should be revalidated if possible. Cache-control βˆ’ This header suggests the client about treating the information sent by the server. CouchDB mostly returns the must-revalidate, which indicates that the information should be revalidated if possible. Content-length βˆ’ This header returns the length of the content sent by the server, in bytes. Content-length βˆ’ This header returns the length of the content sent by the server, in bytes. Etag βˆ’ This header is used to show the revision for a document, or a view. Etag βˆ’ This header is used to show the revision for a document, or a view. Following is the tabular form of the status code sent by the http header and the description of it. 200 βˆ’ OK This status will be issued when a request completed successfully. 201 βˆ’ Created This status will be issued when a document is created. 202 βˆ’ Accepted This status will be issued when a request is accepted. 404 βˆ’ Not Found This status will be issued when the server is unable to find the requested content. 405 βˆ’ Resource Not Allowed This status is issued when the HTTP request type used is invalid. 409 βˆ’ Conflict This status is issued whenever there is any update conflict. 415 βˆ’ Bad Content Type This status indicated that the requested content type is not supported by the server. 500 βˆ’ Internal Server Error This status is issued whenever the data sent in the request is invalid. There are certain url paths using which, you can interact with the database directly. Following is the tabular format of such url paths. PUT /db This url is used to create a new database. GET /db This url is used to get the information about the existing database. PUT /db/document This url is used to create a document/update an existing document. GET /db/document This url is used to get the document. DELETE /db/document This url is used to delete the specified document from the specified database. GET /db/_design/design-doc This url is used to get the definition of a design document. GET /db/_design/designdoc/_view/view-name This url is used to access the view, view-name from the design document from the specified database. Database is the outermost data structure in CouchDB where your documents are stored. You can create these databases using cURL utility provided by CouchDB, as well as Futon the web interface of CouchDB. You can create a database in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a database βˆ’ $ curl -X PUT http://127.0.0.1:5984/database name Using βˆ’X we can specify HTTP custom request method to be used. In this case, we are using PUT method. When we use the PUT operation/method, the content of the url specifies the object name we are creating using HTTP request. Here we have to send the name of the database using put request in the url to create a database. Using the above given syntax if you want to create a database with name my_database, you can create it as follows curl -X PUT http://127.0.0.1:5984/my_database { "ok":true } As a response the server will return you a JSON document with content β€œok” βˆ’ true indicating the operation was successful. Verify whether the database is created, by listing out all the databases as shown below. Here you can observe the name of a newly created database, " my_database " in the list. $ curl -X GET http://127.0.0.1:5984/_all_dbs [ "_replicator " , " _users " , " my_database " ] To create a database open the http://127.0.0.1:5984/_utils/. You will get an Overview/index page of CouchDB as shown below. In this page, you can see the list of databases in CouchDB, an option button Create Database on the left hand side. Now click on the create database link. You can see a popup window Create New Databases asking for the database name for the new database. Choose any name following the mentioned criteria. Here we are creating another database with name tutorials_point. Click on the create button as shown in the following screenshot. You can delete a database in CouchDB by sending a request to the server using DELETE method through cURL utility. Following is the syntax to create a database βˆ’ $ curl -X DELETE http://127.0.0.1:5984/database name Using βˆ’X we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using the DELETE method. Send the url to the server by specifying the database to be deleted in it. Assume there is a database named my_database2 in CouchDB. Using the above given syntax if you want to delete it, you can do it as follows βˆ’ $ curl -X DELETE http://127.0.0.1:5984/my_database2 { "ok" : true } As a response, the server will return you a JSON document with content β€œok” βˆ’ true indicating the operation was successful. Verify whether the database is deleted by listing out all the databases as shown below. Here you can observe the name of the deleted database, "my_database" is not there in the list. $ curl -X GET http://127.0.0.1:5984/_all_dbs [ "_replicator " , " _users " ] To delete a database, open the http://127.0.0.1:5984/_utils/ url where you will get an Overview/index page of CouchDB as shown below. Here you can see three user created databases. Let us delete the database named tutorials_point2. To delete a database, select one from the list of databases, and click on it, which will lead to the overview page of the selected database where you can see the various operations on databases. The following screenshot shows the same βˆ’ Among them you can find Delete Database option. By clicking on it you will get a popup window, asking whether you are sure! Click on delete, to delete the selected database. Documents are CouchDB’s central data structure. Contents of the database will be stored in the form of Documents instead of tables. You can create these documents using cURL utility provided by CouchDB, as well as Futon. This chapter covers the ways to create a document in a database. Each document in CouchDB has a unique ID. You can choose your own ID that should be in the form of a string. Generally, UUID (Universally Unique IDentifier) is used, which are random numbers that have least chance of creating a duplicate. These are preferred to avoid collisions. You can create a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a document. $ curl -X PUT http://127.0.0.1:5984/database name/"id" -d ' { document} ' Using βˆ’X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using PUT method. When we use the PUT method, the content of the url specifies the object name we are creating using the HTTP request. Here we have to send the following βˆ’ The name of the database name in which we are creating the document. The name of the database name in which we are creating the document. The document id. The document id. The data of the document. βˆ’d option is used to send the data/document through HTTP request. While writing a document simply enter your Field-Value pairs separated by colon, within flower brackets as shown below βˆ’ The data of the document. βˆ’d option is used to send the data/document through HTTP request. While writing a document simply enter your Field-Value pairs separated by colon, within flower brackets as shown below βˆ’ { Name : Raju age : 23 Designation : Designer } Using the above given syntax if you want to create a document with id 001 in a database with name my_database, you can create it as shown below. $ curl -X PUT http://127.0.0.1:5984/my_database/"001" -d '{ " Name " : " Raju " , " age " :" 23 " , " Designation " : " Designer " }' {"ok":true,"id":"001","rev":"1-1c2fae390fa5475d9b809301bbf3f25e"} The response of CouchDB to this request contains three fields βˆ’ "ok", indicating the operation was successful. "ok", indicating the operation was successful. "id", which stores the id of the document and "id", which stores the id of the document and "rev", this indicates the revision id. Every time you revise (update or modify) a document a _rev value will be generated by CouchDB. If you want to update or delete a document, CouchDB expects you to include the _rev field of the revision you wish to change. When CouchDB accepts the change, it will generate a new revision number. This mechanism ensures concurrency control. "rev", this indicates the revision id. Every time you revise (update or modify) a document a _rev value will be generated by CouchDB. If you want to update or delete a document, CouchDB expects you to include the _rev field of the revision you wish to change. When CouchDB accepts the change, it will generate a new revision number. This mechanism ensures concurrency control. If you want to view the created document you can get it using the document as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id": "001", "_rev": "1-3fcc78daac7a90803f0a5e383f4f1e1e", "Name": "Raju", "age": 23, "Designation": "Designer" } To Create a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below. Select the database in which you want to create the document. Open the Overview page of the database and select New Document option as shown below. When you select the New Document option, CouchDB creates a new database document, assigning it a new id. You can edit the value of the id and can assign your own value in the form of a string. In the following illustration, we have created a new document with an id 001. In this page, you can observe three options βˆ’ save Document, Add Field and Upload Attachment. To add field to the document click on Add Field option. After creating a database, you can add a field to it using this option. Clicking on it will get you a pair of text boxes, namely, Field, value. You can edit these values by clicking on them. Edit those values and type your desired Field-Value pair. Click on the green button to save these values. In the following illustration, we have created three fields Name, age and, Designation of the employee. You can save the changes made to the document by clicking on this option. After saving, a new id _rev will be generated as shown below. You can update a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to update a document. curl -X PUT http://127.0.0.1:5984/database_name/document_id/ -d '{ "field" : "value", "_rev" : "revision id" }' Suppose there is a document with id 001 in the database named my_database. You can delete this as shown below. First of all, get the revision id of the document that is to be updated. You can find the _rev of the document in the document itself, therefore get the document as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id" : "001", "_rev" : "2-04d8eac1680d237ca25b68b36b8899d3 " , "age" : "23" } Use revision id _rev from the document to update the document. Here we are updating the age from 23 to 24. $ curl -X PUT http://127.0.0.1:5984/my_database/001/ -d ' { " age " : " 24 " , " _rev " : " 1-1c2fae390fa5475d9b809301bbf3f25e " } ' { " ok " : true , " id " : " 001 " , " rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " } To verify the document, get the document again using GET request as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { " _id " : " 001 ", " _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " , " age " : " 23 " } Following are some important points to be noted while updating a document. The URL we send in the request containing the database name and the document id. The URL we send in the request containing the database name and the document id. Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID. Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID. We have to supply the revision number as a part of the JSON request. We have to supply the revision number as a part of the JSON request. In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number. In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number. To delete a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below. Select the database in which the document to be updated exists and click it. Here we are updating a document in the database named tutorials_point. You will get the list of documents in the database as shown below. Select a document that you want to update and click on it. You will get the contents of the documents as shown below. Here, to update the location from Delhi to Hyderabad, click on the text box, edit the field, and click the green button to save the changes as shown below. You can delete a document in CouchDB by sending an HTTP request to the server using DELETE method through cURL utility. Following is the syntax to delete a document. curl -X DELETE http : // 127.0.0.1:5984 / database name/database id?_rev id Using βˆ’X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using Delete method. To delete a database /database_name/database_id/ is not enough. You have to pass the recent revision id through the url. To mention attributes of any data structure "?" is used. Suppose there is a document in database named my_database with document id 001. To delete this document, you have to get the rev id of the document. Get the document data as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { " _id " : " 001 ", " _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " , " age " : " 23 " } Now specify the revision id of the document to be deleted, id of the document, and database name the document belongs to, as shown below βˆ’ $ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1- 3fcc78daac7a90803f0a5e383f4f1e1e {"ok":true,"id":"001","rev":"2-3a561d56de1ce3305d693bd15630bf96"} To verify whether the document is deleted, try to fetch the document by using the GET method. Since you are fetching a deleted document, this will give you an error message as shown below βˆ’ $ curl -X GET http://127.0.0.1:5984/my_database/001 {"error":"not_found","reason":"deleted"} First of all, verify the documents in the database. Following is the snapshot of the database named tutorials_point. Here you can observe, the database consists of three documents. To delete any of the documents say 003, do the following βˆ’ Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs. Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs. This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document. This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document. Click on Delete Document option. Click on Delete Document option. You will get a dialog box saying "Are you sure you want to delete this document?" Click on delete, to delete the document. You will get a dialog box saying "Are you sure you want to delete this document?" Click on delete, to delete the document. You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document βˆ’ $ curl -vX PUT http://127.0.0.1:5984/database_name/database_id /filename?rev=document rev_id --data-binary @filename -H "Content-Type: type of the content" The request has various options that are explained below. --data-binary@ βˆ’ This option tells cURL to read a file’s contents into the HTTP request body. --data-binary@ βˆ’ This option tells cURL to read a file’s contents into the HTTP request body. -H βˆ’ This option is used to mention the content type of the file we are going to upload. -H βˆ’ This option is used to mention the content type of the file we are going to upload. Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id": "001", "_rev": "1-967a00dff5e02add41819138abb3284d" } Now using the _rev value, send the PUT request to the CouchDB server as shown below. $ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1- 967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H "ContentType: image/jpg" To verify whether the attachment is uploaded, fetch the document content as shown belowβˆ’ $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id": "001", "_rev": "2-4705a219cdcca7c72aac4f623f5c46a8", "_attachments": { "boy.jpg": { "content_type": "image/jpg", "revpos": 2, "digest": "md5-9Swz8jvmga5mfBIsmCxCtQ==", "length": 91408, "stub": true } } } Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button. The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it. Print Add Notes Bookmark this page
[ { "code": null, "e": 2087, "s": 1838, "text": "Database management system provides mechanism for storage and retrieval of data. There are three main types of database management systems namely RDBMS (Relational Database management Systems), OLAP (Online Analytical\nProcessing Systems) and NoSQL." }, { "code": null, "e": 2273, "s": 2087, "text": "RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access." }, { "code": null, "e": 2427, "s": 2273, "text": "A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd." }, { "code": null, "e": 2609, "s": 2427, "text": "The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows. It stores only structured data." }, { "code": null, "e": 2831, "s": 2609, "text": "Online Analytical Processing Server (OLAP) is based on the multidimensional data model. It allows managers and analysts to get an insight of the information through fast, consistent, and interactive access to information." }, { "code": null, "e": 3160, "s": 2831, "text": "A NoSQL database (sometimes called as Not Only SQL) is a database that provides a mechanism to store and retrieve data other than the tabular relations used in relational databases. These databases are schema-free, support easy replication, have simple API, eventually consistent, and can handle huge amounts of data (big data)." }, { "code": null, "e": 3229, "s": 3160, "text": "The primary objective of a NoSQL database is to have the following βˆ’" }, { "code": null, "e": 3251, "s": 3229, "text": "Simplicity of design," }, { "code": null, "e": 3275, "s": 3251, "text": "Horizontal scaling, and" }, { "code": null, "e": 3308, "s": 3275, "text": "Finer control over availability." }, { "code": null, "e": 3706, "s": 3308, "text": "NoSQL databases use different data structures compared to relational databases. It makes some operations faster in NoSQL. The suitability of a given NoSQL database depends on the problem it must solve. These databases store both structured data and unstructured data like audio files, video files, documents, etc. These NoSQL databases are classified into three types and they are explained below." }, { "code": null, "e": 3924, "s": 3706, "text": "Key-value Store βˆ’ These databases are designed for storing data in key-value pairs and these databases will not have any schema. In these databases, each data value consists of an indexed key and a value for that key." }, { "code": null, "e": 3974, "s": 3924, "text": "Examples βˆ’ BerkeleyDB, Cassandra, DynamoDB, Riak." }, { "code": null, "e": 4178, "s": 3974, "text": "Column Store βˆ’ In these databases, data is stored in cells grouped in columns of data, and these columns are further grouped into Column families. These column families can contain any number of columns." }, { "code": null, "e": 4222, "s": 4178, "text": "Examples βˆ’ BigTable, HBase, and HyperTable." }, { "code": null, "e": 4566, "s": 4222, "text": "Document Store βˆ’ These are the databases developed on the basic idea of key-value stores where \"documents\" contain more complex data. Here, each document is assigned a unique key, which is used to retrieve the document. These are designed for storing, retrieving, and managing document-oriented information, also known as semi-structured data." }, { "code": null, "e": 4598, "s": 4566, "text": "Examples βˆ’ CouchDB and MongoDB." }, { "code": null, "e": 4765, "s": 4598, "text": "CouchDB is an open source database developed by Apache software foundation. The focus is on the ease of use, embracing the web. It is a NoSQL document store database." }, { "code": null, "e": 5046, "s": 4765, "text": "It uses JSON, to store data (documents), java script as its query language to transform the documents, http protocol for api to access the documents, query the indices with the web browser. It is a multi master application released in 2005 and it became an apache project in 2008." }, { "code": null, "e": 5242, "s": 5046, "text": "CouchDB have an HTTP-based REST API, which helps to communicate with the database easily. And the simple structure of HTTP resources and methods (GET, PUT, DELETE) are easy to understand and use." }, { "code": null, "e": 5438, "s": 5242, "text": "CouchDB have an HTTP-based REST API, which helps to communicate with the database easily. And the simple structure of HTTP resources and methods (GET, PUT, DELETE) are easy to understand and use." }, { "code": null, "e": 5556, "s": 5438, "text": "As we store data in the flexible document-based structure, there is no need to worry about the structure of the data." }, { "code": null, "e": 5674, "s": 5556, "text": "As we store data in the flexible document-based structure, there is no need to worry about the structure of the data." }, { "code": null, "e": 5786, "s": 5674, "text": "Users are provided with powerful data mapping, which allows querying, combining, and filtering the information." }, { "code": null, "e": 5898, "s": 5786, "text": "Users are provided with powerful data mapping, which allows querying, combining, and filtering the information." }, { "code": null, "e": 6030, "s": 5898, "text": "CouchDB provides easy-to-use replication, using which you can copy, share, and synchronize the data between databases and machines." }, { "code": null, "e": 6162, "s": 6030, "text": "CouchDB provides easy-to-use replication, using which you can copy, share, and synchronize the data between databases and machines." }, { "code": null, "e": 6225, "s": 6162, "text": "Database is the outermost data structure/container in CouchDB." }, { "code": null, "e": 6288, "s": 6225, "text": "Database is the outermost data structure/container in CouchDB." }, { "code": null, "e": 6344, "s": 6288, "text": "Each database is a collection of independent documents." }, { "code": null, "e": 6400, "s": 6344, "text": "Each database is a collection of independent documents." }, { "code": null, "e": 6464, "s": 6400, "text": "Each document maintains its own data and self-contained schema." }, { "code": null, "e": 6528, "s": 6464, "text": "Each document maintains its own data and self-contained schema." }, { "code": null, "e": 6674, "s": 6528, "text": "Document metadata contains revision information, which makes it possible to merge the differences occurred while the databases were disconnected." }, { "code": null, "e": 6820, "s": 6674, "text": "Document metadata contains revision information, which makes it possible to merge the differences occurred while the databases were disconnected." }, { "code": null, "e": 6934, "s": 6820, "text": "CouchDB implements multi version concurrency control, to avoid the need to lock the database field during writes." }, { "code": null, "e": 7048, "s": 6934, "text": "CouchDB implements multi version concurrency control, to avoid the need to lock the database field during writes." }, { "code": null, "e": 7276, "s": 7048, "text": "CouchDB is a document storage NoSQL database. It provides the facility of storing documents with unique names, and it also provides an API called RESTful HTTP API for reading and updating (add, edit, delete) database documents." }, { "code": null, "e": 7525, "s": 7276, "text": "In CouchDB, documents are the primary unit of data and they also include metadata. Document fields are uniquely named and contain values of varying types (text, number, Boolean, lists, etc.), and there is no set limit to text size or element count." }, { "code": null, "e": 7706, "s": 7525, "text": "Document updates (add, edit, delete) follow Atomicity, i.e., they will be saved completely or not saved at all. The database will not have any partially saved or edited documents. " }, { "code": null, "e": 7777, "s": 7706, "text": "{\n \"field\" : \"value\",\n \"field\" : \"value\",\n \"field\" : \"value\",\n}\n" }, { "code": null, "e": 7834, "s": 7777, "text": "CouchDB contains ACID properties as one of its features." }, { "code": null, "e": 8028, "s": 7834, "text": "Consistency βˆ’ When the data in CouchDB was once committed, then this data will not be modified or overwritten. Thus, CouchDB ensures that the database file will always be in a consistent state." }, { "code": null, "e": 8231, "s": 8028, "text": "A multi-Version Concurrency Control (MVCC) model is used by CouchDB reads, because of which the client will see a consistent snapshot of the database from the beginning to the end of the read operation." }, { "code": null, "e": 8516, "s": 8231, "text": "Whenever a documents is updated, CouchDB flushes the data into the disk, and the updated database header is written in two consecutive and identical chunks to make up the first 4k of the file, and then synchronously flushed to disk. Partial updates during the flush will be discarded." }, { "code": null, "e": 8794, "s": 8516, "text": "If the failure occurred while committing the header, a surviving copy of the previous identical headers will remain, ensuring coherency of all previously committed data. Except the header area, consistency checks or fix-ups after a crash or a power failure are never necessary." }, { "code": null, "e": 9160, "s": 8794, "text": "Whenever the space in the database file got wasted above certain extent, all the active data will be copied (cloned) to a new file. When the copying process is entirely done, then the old file will be discarded. All this is done by compaction process. The database remains online during the compaction and all updates and reads are allowed to complete successfully." }, { "code": null, "e": 9476, "s": 9160, "text": "Data in CouchDB is stored in semi-structured documents that are flexible with individual implicit structures, but it is a simple document model for data storage and sharing. If we want see our data in many different ways, we need a way to filter, organize and report on data that hasn’t been decomposed into tables." }, { "code": null, "e": 9849, "s": 9476, "text": "To solve this problem, CouchDB provides a view model. Views are the method of aggregating and reporting on the documents in a database, and are built on-demand to aggregate, join and report on database documents. Because views are built dynamically and don’t affect the underlying document, you can have as many different view representations of the same data as you like." }, { "code": null, "e": 9901, "s": 9849, "text": "CouchDB was written in Erlang programming language." }, { "code": null, "e": 9940, "s": 9901, "text": "It was started by Damien Katz in 2005." }, { "code": null, "e": 9982, "s": 9940, "text": "CouchDB became an Apache project in 2008." }, { "code": null, "e": 10022, "s": 9982, "text": "The current version of CouchDB is 1.61." }, { "code": null, "e": 10107, "s": 10022, "text": "This chapter teaches you how to install CouchDB in windows as well as Linux systems." }, { "code": null, "e": 10274, "s": 10107, "text": "The official website for CouchDB is https://couchdb.apache.org. If you click the given link, you can get the home page of the CouchDB official website as shown below." }, { "code": null, "e": 10445, "s": 10274, "text": "If you click on the download button that will lead to a page where download links of CouchDB in various formats are provided. The following snapshot illustrates the same." }, { "code": null, "e": 10553, "s": 10445, "text": "Choose the download link for windows systems and select one of the provided mirrors to start your download." }, { "code": null, "e": 10713, "s": 10553, "text": "CouchDB will be downloaded to your system in the form of setup file named setup-couchdb-1.6.1_R16B02.exe. Run the setup file and proceed with the\ninstallation." }, { "code": null, "e": 10918, "s": 10713, "text": "After installation, open built-in web interface of CouchDB by visiting the following \nlink: http://127.0.0.1:5984/. If everything goes fine, this will give you a web page, which have the following output." }, { "code": null, "e": 11093, "s": 10918, "text": "{\n \"couchdb\":\"Welcome\",\"uuid\":\"c8d48ac61bb497f4692b346e0f400d60\",\n \"version\":\"1.6.1\",\n \"vendor\":{\n \"version\":\"1.6.1\",\"name\":\"The Apache Software Foundation\"\n }\n}" }, { "code": null, "e": 11170, "s": 11093, "text": "You can interact with the CouchDB web interface by using the following url βˆ’" }, { "code": null, "e": 11201, "s": 11170, "text": "http://127.0.0.1:5984/_utils/\n" }, { "code": null, "e": 11280, "s": 11201, "text": "This shows you the index page of Futon, which is the web interface of CouchDB." }, { "code": null, "e": 11402, "s": 11280, "text": "For many of the Linux flavored systems, they provide CouchDB internally. To install this CouchDB follow the instructions." }, { "code": null, "e": 11437, "s": 11402, "text": "On Ubuntu and Debian you can use βˆ’" }, { "code": null, "e": 11467, "s": 11437, "text": "sudo aptitude install couchdb" }, { "code": null, "e": 11521, "s": 11467, "text": "On Gentoo Linux there is a CouchDB ebuild available βˆ’" }, { "code": null, "e": 11541, "s": 11521, "text": "sudo emerge couchdb" }, { "code": null, "e": 11650, "s": 11541, "text": "If your Linux system does not have CouchDB, follow the next section to install CouchDB and its dependencies." }, { "code": null, "e": 11744, "s": 11650, "text": "Following is the list of dependencies that are to be installed to get CouchDB in your systemβˆ’" }, { "code": null, "e": 11755, "s": 11744, "text": "Erlang OTP" }, { "code": null, "e": 11759, "s": 11755, "text": "ICU" }, { "code": null, "e": 11767, "s": 11759, "text": "OpenSSL" }, { "code": null, "e": 11788, "s": 11767, "text": "Mozilla SpiderMonkey" }, { "code": null, "e": 11797, "s": 11788, "text": "GNU Make" }, { "code": null, "e": 11821, "s": 11797, "text": "GNU Compiler Collection" }, { "code": null, "e": 11829, "s": 11821, "text": "libcurl" }, { "code": null, "e": 11838, "s": 11829, "text": "help2man" }, { "code": null, "e": 11854, "s": 11838, "text": "Python for docs" }, { "code": null, "e": 11868, "s": 11854, "text": "Python Sphinx" }, { "code": null, "e": 12062, "s": 11868, "text": "To install these dependencies, type the following commands in the terminal. Here we are using Centos 6.5 and the following commands will install the required softwares compatible to Centos 6.5." }, { "code": null, "e": 12481, "s": 12062, "text": "$sudo yum install autoconf\n$sudo yum install autoconf-archive\n$sudo yum install automake\n$sudo yum install curl-devel\n$sudo yum install erlang-asn1\n$sudo yum install erlang-erts\n$sudo yum install erlang-eunit\n$sudo yum install erlang-os_mon\n$sudo yum install erlang-xmerl\n$sudo yum install help2man\n$sudo yum install js-devel\n$sudo yum install libicu-devel\n$sudo yum install libtool\n$sudo yum install perl-Test-Harness" }, { "code": null, "e": 12593, "s": 12481, "text": "Note βˆ’ For all these commands you need to use sudo. The following procedure converts a normal user to a sudoer." }, { "code": null, "e": 12621, "s": 12593, "text": "Login as root in admin user" }, { "code": null, "e": 12649, "s": 12621, "text": "Login as root in admin user" }, { "code": null, "e": 12694, "s": 12649, "text": "Open sudo file using the following command βˆ’" }, { "code": null, "e": 12739, "s": 12694, "text": "Open sudo file using the following command βˆ’" }, { "code": null, "e": 12746, "s": 12739, "text": "visudo" }, { "code": null, "e": 12822, "s": 12746, "text": "Then edit as shown below to give your existing user the sudoer privileges βˆ’" }, { "code": null, "e": 12898, "s": 12822, "text": "Hadoop All=(All) All , and press esc : x to write the changes to the file. " }, { "code": null, "e": 13004, "s": 12898, "text": "After downloading all the dependencies in your system, download CouchDB following the given instructions." }, { "code": null, "e": 13128, "s": 13004, "text": "Apache software foundation will not provide the complete .tar file for CouchDB,\nso you have to install it from the source. " }, { "code": null, "e": 13270, "s": 13128, "text": "Create a new directory to install CouchDB, browse to such created directory and download CouchDB source by executing the following commands βˆ’" }, { "code": null, "e": 13432, "s": 13270, "text": "$ cd\n$ mkdir CouchDB\n$ cd CouchDB/\n$ wget\nhttp://www.google.com/url?q=http%3A%2F%2Fwww.apache.org%2Fdist%2Fcouchdb%2Fsource%2F1.6.1%2Fapache-couchdb-1.6.1.tar.gz" }, { "code": null, "e": 13547, "s": 13432, "text": "This will download CouchDB source file into your system. Now unzip the apache-couchdb-1.6.1.tar.gz as shown below." }, { "code": null, "e": 13586, "s": 13547, "text": "$ tar zxvf apache-couchdb-1.6.1.tar.gz" }, { "code": null, "e": 13627, "s": 13586, "text": "To configure CouchDB, do the following βˆ’" }, { "code": null, "e": 13665, "s": 13627, "text": "Browse to the home folder of CouchDB." }, { "code": null, "e": 13685, "s": 13665, "text": "Login as superuser." }, { "code": null, "e": 13737, "s": 13685, "text": "Configure using ./configure prompt as shown below βˆ’" }, { "code": null, "e": 13837, "s": 13737, "text": "$ cd apache-couchdb-1.6.1\n$ su\nPassword:\n# ./configure --with-erlang=/usr/lib64/erlang/usr/include/" }, { "code": null, "e": 13982, "s": 13837, "text": "It gives you the following output similar to that shown below with a concluding\nline saying βˆ’ You have configured Apache CouchDB, time to relax." }, { "code": null, "e": 14831, "s": 13982, "text": "# ./configure --with-erlang=/usr/lib64/erlang/usr/include/\n\nchecking for a BSD-compatible install... /usr/bin/install -c\nchecking whether build environment is sane... yes\nchecking for a thread-safe mkdir -p... /bin/mkdir -p\nchecking for gawk... gawk\nchecking whether make sets $(MAKE)... yes\nchecking how to create a ustar tar archive... gnutar\n.................................................................\n............................\nconfig.status: creating var/Makefile\nconfig.status: creating config.h\nconfig.status: config.h is unchanged\nconfig.status: creating src/snappy/google-snappy/config.h\nconfig.status: src/snappy/google-snappy/config.h is unchanged\nconfig.status: executing depfiles commands\nconfig.status: executing libtool commands\n\nYou have configured Apache CouchDB, time to relax.\n\nRun `make && sudo make install' to install." }, { "code": null, "e": 14897, "s": 14831, "text": "Now type the following command to install CouchDB in your system." }, { "code": null, "e": 14925, "s": 14897, "text": "# make && sudo make install" }, { "code": null, "e": 15042, "s": 14925, "text": "It installs CouchDB in your system with a concluding line saying βˆ’ You have installed Apache CouchDB, time to relax." }, { "code": null, "e": 15126, "s": 15042, "text": "To start CouchDB, browse to the CouchDB home folder and use the following command βˆ’" }, { "code": null, "e": 15177, "s": 15126, "text": "$ cd apache-couchdb-1.6.1\n$ cd etc\n$ couchdb start" }, { "code": null, "e": 15226, "s": 15177, "text": "It starts CouchDB giving the following output: βˆ’" }, { "code": null, "e": 15500, "s": 15226, "text": "Apache CouchDB 1.6.1 (LogLevel=info) is starting.\nApache CouchDB has started. Time to relax.\n[info] [lt;0.31.0gt;] Apache CouchDB has started on http://127.0.0.1:5984/\n[info] [lt;0.112.0gt;] 127.0.0.1 - - GET / 200\n[info] [lt;0.112.0gt;] 127.0.0.1 - - GET /favicon.ico 200\n" }, { "code": null, "e": 15589, "s": 15500, "text": "Since CouchDB is a web interface, try to type the following homepage url in the browser." }, { "code": null, "e": 15612, "s": 15589, "text": "http://127.0.0.1:5984/" }, { "code": null, "e": 15647, "s": 15612, "text": "It produces the following output βˆ’" }, { "code": null, "e": 15834, "s": 15647, "text": "{\n \"couchdb\":\"Welcome\",\n \"uuid\":\"8f0d59acd0e179f5e9f0075fa1f5e804\",\n \"version\":\"1.6.1\",\n \"vendor\":{\n \"name\":\"The Apache Software Foundation\",\n \"version\":\"1.6.1\"\n }\n}\n" }, { "code": null, "e": 15885, "s": 15834, "text": "cURL utility is a way to communicate with CouchDB." }, { "code": null, "e": 16260, "s": 15885, "text": "It is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, TFTP, DICT, TELNET, LDAP or FILE). The command is designed to work without user interaction. cURL offers a busload of useful tricks like proxy support, user authentication, ftp upload, HTTP post, SSL (https:) connections, cookies, file transfer resume and more." }, { "code": null, "e": 16512, "s": 16260, "text": "The cURL utility is available in operating systems such as UNIX, Linux, Mac OS X and Windows. It is a command line utility using which user can access HTTP protocol straight away from the command line. This chapter teaches you how to use cURL utility." }, { "code": null, "e": 16629, "s": 16512, "text": "You can access any website using cURL utility by simply typing cURL followed by the website address as shown below βˆ’" }, { "code": null, "e": 16658, "s": 16629, "text": "curl www.tutorialspoint.com/" }, { "code": null, "e": 16780, "s": 16658, "text": "By default, the cURL utility returns the source code of the requested page. It displays this code on the terminal window." }, { "code": null, "e": 16875, "s": 16780, "text": "cURL utility provides various options to work with, and you can see them in cURL utility help." }, { "code": null, "e": 16927, "s": 16875, "text": "The following code shows some portion of cURL help." }, { "code": null, "e": 19487, "s": 16927, "text": "$ curl --help\nUsage: curl [options...] <url>\nOptions: (H) means HTTP/HTTPS only, (F) means FTP only\n --anyauth Pick \"any\" authentication method (H)\n -a/--append Append to target file when uploading (F/SFTP)\n --basic Use HTTP Basic Authentication (H)\n --cacert <file> CA certificate to verify peer against (SSL)\n-d/--data <data> HTTP POST data (H)\n --data-ascii <data> HTTP POST ASCII data (H)\n --data-binary <data> HTTP POST binary data (H)\n --data-urlencode <name=data/name@filename> HTTP POST data\nurlencoded (H)\n --delegation STRING GSS-API delegation permission\n --digest Use HTTP Digest Authentication (H)\n --disable-eprt Inhibit using EPRT or LPRT (F)\n --disable-epsv Inhibit using EPSV (F)\n\n -F/--form <name=content> Specify HTTP multipart POST data (H)\n --form-string <name=string> Specify HTTP multipart POST data (H)\n --ftp-account <data> Account data to send when requested by server\n(F)\n --ftp-alternative-to-user <cmd> String to replace \"USER [name]\" (F)\n --ftp-create-dirs Create the remote dirs if not present (F)\n --ftp-method [multi cwd/no cwd/single cwd] Control CWD usage (F)\n --ftp-pasv Use PASV/EPSV instead of PORT (F)\n\n -G/--get Send the -d data with a HTTP GET (H)\n\n -H/--header <line> Custom header to pass to server (H)\n -I/--head Show document info only\n -h/--help This help text\n --hostpubmd5 <md5> Hex encoded MD5 string of the host public key.\n(SSH)\n -0/--http1.0 Use HTTP 1.0 (H)\n --ignore-content-length Ignore the HTTP Content-Length header\n -i/--include Include protocol headers in the output (H/F)\n\n -M/--manual Display the full manual\n\n -o/--output <file> Write output to <file> instead of stdout\n --pass <pass> Pass phrase for the private key (SSL/SSH)\n --post301 Do not switch to GET after following a 301\nredirect (H)\n --post302 Do not switch to GET after following a 302\nredirect (H)\n -O/--remote-name Write output to a file named as the remote file\n --remote-name-all Use the remote file name for all URLs\n -R/--remote-time Set the remote file's time on the local output\n -X/--request <command> Specify request command to use\n --retry <num> Retry request <num> times if transient problems\noccur\n --retry-delay <seconds> When retrying, wait this many seconds\nbetween each\n --retry-max-time <seconds> Retry only within this period\n -T/--upload-file <file> Transfer <file> to remote site\n --url <URL> Set URL to work with\n -B/--use-ascii Use ASCII/text transfer" }, { "code": null, "e": 19688, "s": 19487, "text": "While communicating with CouchDB, certain options of cURL utility were extensively used. Following are the brief descriptions of some important options of cURL utility including those used by CouchDB." }, { "code": null, "e": 19929, "s": 19688, "text": "(HTTP) Specifies a custom request method used when communicating with the HTTP server. The specified request is used instead of the method otherwise used (which defaults to GET). Read the HTTP 1.1 specification for details and explanations." }, { "code": null, "e": 20021, "s": 19929, "text": "(FTP) Specifies a custom FTP command to use instead of LIST when doing file lists with ftp." }, { "code": null, "e": 20541, "s": 20021, "text": "(HTTP) Extra header is used when getting a web page. Note that if you add a custom header that has the same name as one of the internal ones cURL would\nuse, your externally set header will be used instead of the internal one. This allows you to make even trickier work than cURL would normally do. You should not replace internally set headers without perfectly knowing what you’re doing. Replacing an internal header with the one without content on the right side of the colon, will prevent that header from appearing." }, { "code": null, "e": 20749, "s": 20541, "text": "cURL assures that each header you add/replace get sent with the proper end of line marker. Neither you should add that as a part of the header content nor add newlines or carriage returns to disorder things." }, { "code": null, "e": 20804, "s": 20749, "text": "See also the -A/--user-agent and -e/--referer options." }, { "code": null, "e": 20883, "s": 20804, "text": "This option can be used multiple times to add/replace/remove multiple headers." }, { "code": null, "e": 21033, "s": 20883, "text": "Using this flag of cURL, you can send data along with the HTTP POST request to the server, as if it was filled by the user in the form and submitted." }, { "code": null, "e": 21041, "s": 21033, "text": "Example" }, { "code": null, "e": 21177, "s": 21041, "text": "Suppose there is a website and you want to login into it or send some data to the website using –d flag of cURL utility as shown below." }, { "code": null, "e": 21262, "s": 21177, "text": "curl -X PUT http://mywebsite.com/login.html -d userid=001 -d password=tutorialspoint" }, { "code": null, "e": 21398, "s": 21262, "text": "It sends a post chunk that looks like \"userid=001&password=tutorialspoint\". Likewise you can also send documents (JSON ) using -d flag." }, { "code": null, "e": 21464, "s": 21398, "text": "Using this flag, cURL writes the output of the request to a file." }, { "code": null, "e": 21472, "s": 21464, "text": "Example" }, { "code": null, "e": 21536, "s": 21472, "text": "The following example shows the use of -o flag of cURL utility." }, { "code": null, "e": 21762, "s": 21536, "text": "$ curl -o example.html www.tutorialspoint.com/index.htm \n% Total % Received % Xferd Average Speed Time Time Time Current \n Dload Upload Total Spent Left Speed\n100 81193 0 81193 0 0 48168 0 --:--:-- 0:00:01 --:--:--\n58077" }, { "code": null, "e": 21913, "s": 21762, "text": "This gets the source code of the homepage of tutorialspoint.com, creates a file named example.com and saves the output in the file named example.html." }, { "code": null, "e": 21960, "s": 21913, "text": "Following is the snapshot of the example.html." }, { "code": null, "e": 22154, "s": 21960, "text": "This flag is similar to –o, the only difference is with this flag, a new file with the same name as the requested url was created, and the source code of the requested url will be copied to it." }, { "code": null, "e": 22162, "s": 22154, "text": "Example" }, { "code": null, "e": 22226, "s": 22162, "text": "The following example shows the use of -O flag of cURL utility." }, { "code": null, "e": 22437, "s": 22226, "text": "$ curl -O www.tutorialspoint.com/index.htm\n% Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left\nSpeed\n100 81285 0 81285 0 0 49794 0 --:--:-- 0:00:01 --:--:--\n60077" }, { "code": null, "e": 22556, "s": 22437, "text": "It creates a new file with the name index.htm and saves the source code of the index page of tutorialspoint.com in it." }, { "code": null, "e": 22848, "s": 22556, "text": "You can access the homepage of the CouchDB by sending a GET request to the CouchDB instance installed. First of all make sure you have installed CouchDB in your Linux environment and it is running successfully, and then use the following syntax to send a get request to the CouchDB instance." }, { "code": null, "e": 22876, "s": 22848, "text": "curl http://127.0.0.1:5984/" }, { "code": null, "e": 23031, "s": 22876, "text": "This gives you a JSON document as shown below where CouchDB specifies the details such as version number, name of the vendor, and version of the software." }, { "code": null, "e": 23256, "s": 23031, "text": "$ curl http://127.0.0.1:5984/\n{\n \"couchdb\" : \"Welcome\",\n \"uuid\" : \"8f0d59acd0e179f5e9f0075fa1f5e804\",\n \"version\" : \"1.6.1\",\n \"vendor\" : {\n \"name\":\"The Apache Software Foundation\",\n \"version\":\"1.6.1\"\n }\n}\n" }, { "code": null, "e": 23443, "s": 23256, "text": "You can get the list of all the databases created, by sending a get request along with the string \"_all_dbs string \". Following is the syntax to get the list of all databases in CouchDB." }, { "code": null, "e": 23486, "s": 23443, "text": "curl -X GET http://127.0.0.1:5984/_all_dbs" }, { "code": null, "e": 23552, "s": 23486, "text": "It gives you the list of all databases in CouchDB as shown below." }, { "code": null, "e": 23626, "s": 23552, "text": "$ curl -X GET http://127.0.0.1:5984/_all_dbs\n[ \"_replicator\" , \"_users\" ]" }, { "code": null, "e": 23719, "s": 23626, "text": "You can create a database in CouchDB using cURL with PUT header using the following syntax βˆ’" }, { "code": null, "e": 23770, "s": 23719, "text": "$ curl -X PUT http://127.0.0.1:5984/database_name\n" }, { "code": null, "e": 23870, "s": 23770, "text": "As an example, using the above given syntax create a database with name my_database as shown below." }, { "code": null, "e": 23930, "s": 23870, "text": "$ curl -X PUT http://127.0.0.1:5984/my_database\n{\"ok\":true}" }, { "code": null, "e": 24102, "s": 23930, "text": "Verify whether the database is created, by listing out all the databases as shown\nbelow. Here you can observe the name of newly created database, \"my_database\" in the list" }, { "code": null, "e": 24194, "s": 24102, "text": "$ curl -X GET http://127.0.0.1:5984/_all_dbs\n\n[ \"_replicator \" , \"_users\" , \"my_database\" ]" }, { "code": null, "e": 24346, "s": 24194, "text": "You can get the information about database using the get request along with the database name. Following is the syntax to get the database information." }, { "code": null, "e": 24505, "s": 24346, "text": "As an example let us get the information of the database named my_database as shown below. Here you can get the information about your database as a response." }, { "code": null, "e": 24852, "s": 24505, "text": "$ curl -X GET http://127.0.0.1:5984/my_database\n\n{\n \"db_name\" : \"my_database\",\n \"doc_count\" : 0,\n \"doc_del_count\" : 0,\n \"update_seq\" : 0,\n \"purge_seq\" : 0,\n \"compact_running\" : false,\n \"disk_size\" : 79,\n \"data_size\" : 0,\n \"instance_start_time\" : \"1423628520835029\",\n \"disk_format_version\" : 6,\n \"committed_update_seq\" : 0\n }" }, { "code": null, "e": 25126, "s": 24852, "text": "Futon is the built-in, web based, administration interface of CouchDB. It provides\na simple graphical interface using which you can interact with CouchDB. It is a naive interface and it provides full access to all CouchDB features. Following is the list of those features βˆ’" }, { "code": null, "e": 25145, "s": 25126, "text": "Creates databases." }, { "code": null, "e": 25165, "s": 25145, "text": "Destroys databases." }, { "code": null, "e": 25184, "s": 25165, "text": "Creates documents." }, { "code": null, "e": 25203, "s": 25184, "text": "Updates documents." }, { "code": null, "e": 25220, "s": 25203, "text": "Edits documents." }, { "code": null, "e": 25239, "s": 25220, "text": "Deletes documents." }, { "code": null, "e": 25313, "s": 25239, "text": "Make sure CouchDB is running and then open the following url in browser βˆ’" }, { "code": null, "e": 25343, "s": 25313, "text": "http://127.0.0.1:5984/_utils/" }, { "code": null, "e": 25414, "s": 25343, "text": "If you open this url, it displays the Futon home page as shown below βˆ’" }, { "code": null, "e": 25634, "s": 25414, "text": "On the left hand side of this page you can observe the list of all the current databases of CouchDB. In this illustration, we have a database named my_database, along with system defined databases _replicator and _user." }, { "code": null, "e": 25854, "s": 25634, "text": "On the left hand side of this page you can observe the list of all the current databases of CouchDB. In this illustration, we have a database named my_database, along with system defined databases _replicator and _user." }, { "code": null, "e": 26349, "s": 25854, "text": "On the right hand side you can see the following βˆ’\n\nTools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB.\nDocumentation βˆ’ This section contains the complete documentation for the recent version of CouchDB.\nDiagnostics βˆ’ Under this you can verify the installation of CouchDB.\nRecent Databases βˆ’ Under this you can find the names of recently added databases.\n\n" }, { "code": null, "e": 26400, "s": 26349, "text": "On the right hand side you can see the following βˆ’" }, { "code": null, "e": 26590, "s": 26400, "text": "Tools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB." }, { "code": null, "e": 26780, "s": 26590, "text": "Tools βˆ’ In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB." }, { "code": null, "e": 26880, "s": 26780, "text": "Documentation βˆ’ This section contains the complete documentation for the recent version of CouchDB." }, { "code": null, "e": 26980, "s": 26880, "text": "Documentation βˆ’ This section contains the complete documentation for the recent version of CouchDB." }, { "code": null, "e": 27049, "s": 26980, "text": "Diagnostics βˆ’ Under this you can verify the installation of CouchDB." }, { "code": null, "e": 27118, "s": 27049, "text": "Diagnostics βˆ’ Under this you can verify the installation of CouchDB." }, { "code": null, "e": 27200, "s": 27118, "text": "Recent Databases βˆ’ Under this you can find the names of recently added databases." }, { "code": null, "e": 27282, "s": 27200, "text": "Recent Databases βˆ’ Under this you can find the names of recently added databases." }, { "code": null, "e": 27533, "s": 27282, "text": "Using HTTP request headers, you can communicate with CouchDB. Through these requests we can retrieve data from the database, store data in to the database in the form of documents, and we can view as well as format the documents stored in a database." }, { "code": null, "e": 27796, "s": 27533, "text": "While communicating with the database we will use different request formats like get, head, post, put, delete, and copy. For all operations in CouchDB, the input data and the output data structures will be in the form of JavaScript Object Notation (JSON) object." }, { "code": null, "e": 27891, "s": 27796, "text": "Following are the different request formats of HTTP Protocol used to communicate with CouchDB." }, { "code": null, "e": 28178, "s": 27891, "text": "GET βˆ’ This format is used to get a specific item. To get different items, you have to send specific url patterns. In CouchDB using this GET request, we can get static items, database documents and configuration, and statistical information in the form of JSON documents (in most cases)." }, { "code": null, "e": 28465, "s": 28178, "text": "GET βˆ’ This format is used to get a specific item. To get different items, you have to send specific url patterns. In CouchDB using this GET request, we can get static items, database documents and configuration, and statistical information in the form of JSON documents (in most cases)." }, { "code": null, "e": 28570, "s": 28465, "text": "HEAD βˆ’ The HEAD method is used to get the HTTP header of a GET request without the body of the response." }, { "code": null, "e": 28675, "s": 28570, "text": "HEAD βˆ’ The HEAD method is used to get the HTTP header of a GET request without the body of the response." }, { "code": null, "e": 28861, "s": 28675, "text": "POST βˆ’ Post request is used to upload data. In CouchDB using POST request, you can set values, upload documents, set document values, and can also start certain administration commands." }, { "code": null, "e": 29047, "s": 28861, "text": "POST βˆ’ Post request is used to upload data. In CouchDB using POST request, you can set values, upload documents, set document values, and can also start certain administration commands." }, { "code": null, "e": 29150, "s": 29047, "text": "PUT βˆ’ Using PUT request, you can create new objects, databases, documents, views and design documents." }, { "code": null, "e": 29253, "s": 29150, "text": "PUT βˆ’ Using PUT request, you can create new objects, databases, documents, views and design documents." }, { "code": null, "e": 29339, "s": 29253, "text": "DELETE βˆ’ Using DELETE request, you can delete documents, views, and design documents." }, { "code": null, "e": 29425, "s": 29339, "text": "DELETE βˆ’ Using DELETE request, you can delete documents, views, and design documents." }, { "code": null, "e": 29487, "s": 29425, "text": "COPY βˆ’ Using COPY method, you can copy documents and objects." }, { "code": null, "e": 29549, "s": 29487, "text": "COPY βˆ’ Using COPY method, you can copy documents and objects." }, { "code": null, "e": 29776, "s": 29549, "text": "HTTP headers should be supplied to get the right format and encoding. While sending the request to the CouchDB server, you can send Http request headers along with the request. Following are the different Http request headers." }, { "code": null, "e": 30067, "s": 29776, "text": "Content-type βˆ’ This Header is used to specify the content type of the data that we supply to the server along with the request. Mostly the type of the content we send along with the request will be MIME type or JSON (application/json). Using Content-type on a request is highly recommended." }, { "code": null, "e": 30358, "s": 30067, "text": "Content-type βˆ’ This Header is used to specify the content type of the data that we supply to the server along with the request. Mostly the type of the content we send along with the request will be MIME type or JSON (application/json). Using Content-type on a request is highly recommended." }, { "code": null, "e": 30775, "s": 30358, "text": "Accept βˆ’ This header is used to specify the server, the list of data types that client can understand, so that the server will send its response using those data types. Generally here, you can send the list of MIME data types the client accepts, separated by colons.\nThough, using Accept in queries of CouchDB is not required, it is highly recommended to ensure that the data returned can be processed by the client." }, { "code": null, "e": 31042, "s": 30775, "text": "Accept βˆ’ This header is used to specify the server, the list of data types that client can understand, so that the server will send its response using those data types. Generally here, you can send the list of MIME data types the client accepts, separated by colons." }, { "code": null, "e": 31192, "s": 31042, "text": "Though, using Accept in queries of CouchDB is not required, it is highly recommended to ensure that the data returned can be processed by the client." }, { "code": null, "e": 31331, "s": 31192, "text": "These are the headers of the response sent by the server. These headers give information about the content send by the server as response." }, { "code": null, "e": 31474, "s": 31331, "text": "Content-type βˆ’ This header specifies the MIME type of the data returned by the server. For most request, the returned MIME type is text/plain." }, { "code": null, "e": 31617, "s": 31474, "text": "Content-type βˆ’ This header specifies the MIME type of the data returned by the server. For most request, the returned MIME type is text/plain." }, { "code": null, "e": 31832, "s": 31617, "text": "Cache-control βˆ’ This header suggests the client about treating the information sent by the server. CouchDB mostly returns the must-revalidate, which indicates that the information should be revalidated if possible." }, { "code": null, "e": 32047, "s": 31832, "text": "Cache-control βˆ’ This header suggests the client about treating the information sent by the server. CouchDB mostly returns the must-revalidate, which indicates that the information should be revalidated if possible." }, { "code": null, "e": 32140, "s": 32047, "text": "Content-length βˆ’ This header returns the length of the content sent by the server, in bytes." }, { "code": null, "e": 32233, "s": 32140, "text": "Content-length βˆ’ This header returns the length of the content sent by the server, in bytes." }, { "code": null, "e": 32308, "s": 32233, "text": "Etag βˆ’ This header is used to show the revision for a document, or a view." }, { "code": null, "e": 32383, "s": 32308, "text": "Etag βˆ’ This header is used to show the revision for a document, or a view." }, { "code": null, "e": 32483, "s": 32383, "text": "Following is the tabular form of the status code sent by the http header and the description of it." }, { "code": null, "e": 32492, "s": 32483, "text": "200 βˆ’ OK" }, { "code": null, "e": 32558, "s": 32492, "text": "This status will be issued when a request completed successfully." }, { "code": null, "e": 32572, "s": 32558, "text": "201 βˆ’ Created" }, { "code": null, "e": 32627, "s": 32572, "text": "This status will be issued when a document is created." }, { "code": null, "e": 32642, "s": 32627, "text": "202 βˆ’ Accepted" }, { "code": null, "e": 32697, "s": 32642, "text": "This status will be issued when a request is accepted." }, { "code": null, "e": 32713, "s": 32697, "text": "404 βˆ’ Not Found" }, { "code": null, "e": 32797, "s": 32713, "text": "This status will be issued when the server is unable to find the requested content." }, { "code": null, "e": 32824, "s": 32797, "text": "405 βˆ’ Resource Not Allowed" }, { "code": null, "e": 32890, "s": 32824, "text": "This status is issued when the HTTP request type used is invalid." }, { "code": null, "e": 32905, "s": 32890, "text": "409 βˆ’ Conflict" }, { "code": null, "e": 32966, "s": 32905, "text": "This status is issued whenever there is any update conflict." }, { "code": null, "e": 32989, "s": 32966, "text": "415 βˆ’ Bad Content Type" }, { "code": null, "e": 33075, "s": 32989, "text": "This status indicated that the requested content type is not supported by the server." }, { "code": null, "e": 33103, "s": 33075, "text": "500 βˆ’ Internal Server Error" }, { "code": null, "e": 33175, "s": 33103, "text": "This status is issued whenever the data sent in the request is invalid." }, { "code": null, "e": 33312, "s": 33175, "text": "There are certain url paths using which, you can interact with the database directly. Following is the tabular format of such url paths." }, { "code": null, "e": 33320, "s": 33312, "text": "PUT /db" }, { "code": null, "e": 33363, "s": 33320, "text": "This url is used to create a new database." }, { "code": null, "e": 33371, "s": 33363, "text": "GET /db" }, { "code": null, "e": 33440, "s": 33371, "text": "This url is used to get the information about the existing database." }, { "code": null, "e": 33457, "s": 33440, "text": "PUT /db/document" }, { "code": null, "e": 33524, "s": 33457, "text": "This url is used to create a document/update an existing document." }, { "code": null, "e": 33541, "s": 33524, "text": "GET /db/document" }, { "code": null, "e": 33579, "s": 33541, "text": "This url is used to get the document." }, { "code": null, "e": 33599, "s": 33579, "text": "DELETE /db/document" }, { "code": null, "e": 33678, "s": 33599, "text": "This url is used to delete the specified document from the specified database." }, { "code": null, "e": 33705, "s": 33678, "text": "GET /db/_design/design-doc" }, { "code": null, "e": 33766, "s": 33705, "text": "This url is used to get the definition of a design document." }, { "code": null, "e": 33808, "s": 33766, "text": "GET /db/_design/designdoc/_view/view-name" }, { "code": null, "e": 33909, "s": 33808, "text": "This url is used to access the view, view-name from the design document from the specified database." }, { "code": null, "e": 34112, "s": 33909, "text": "Database is the outermost data structure in CouchDB where your documents are stored. You can create these databases using cURL utility provided by CouchDB, as well as Futon the web interface of CouchDB." }, { "code": null, "e": 34276, "s": 34112, "text": "You can create a database in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a database βˆ’" }, { "code": null, "e": 34327, "s": 34276, "text": "$ curl -X PUT http://127.0.0.1:5984/database name\n" }, { "code": null, "e": 34649, "s": 34327, "text": "Using βˆ’X we can specify HTTP custom request method to be used. In this case, we are using PUT method. When we use the PUT operation/method, the content of the url specifies the object name we are creating using HTTP request. Here we have to send the name of the database using put request in the url to create a database." }, { "code": null, "e": 34763, "s": 34649, "text": "Using the above given syntax if you want to create a database with name my_database, you can create it as follows" }, { "code": null, "e": 34827, "s": 34763, "text": "curl -X PUT http://127.0.0.1:5984/my_database\n{\n \"ok\":true\n}\n" }, { "code": null, "e": 34950, "s": 34827, "text": "As a response the server will return you a JSON document with content β€œok” βˆ’ true indicating the operation was successful." }, { "code": null, "e": 35127, "s": 34950, "text": "Verify whether the database is created, by listing out all the databases as shown below. Here you can observe the name of a newly created database, \" my_database \" in the list." }, { "code": null, "e": 35223, "s": 35127, "text": "$ curl -X GET http://127.0.0.1:5984/_all_dbs\n\n[ \"_replicator \" , \" _users \" , \" my_database \" ]" }, { "code": null, "e": 35347, "s": 35223, "text": "To create a database open the http://127.0.0.1:5984/_utils/. You will get\nan Overview/index page of CouchDB as shown below." }, { "code": null, "e": 35463, "s": 35347, "text": "In this page, you can see the list of databases in CouchDB, an option button Create Database on the left hand side." }, { "code": null, "e": 35781, "s": 35463, "text": "Now click on the create database link. You can see a popup window Create New Databases asking for the database name for the new database. Choose any name following the mentioned criteria. Here we are creating another database with name tutorials_point. Click on the create button as shown in the following screenshot." }, { "code": null, "e": 35942, "s": 35781, "text": "You can delete a database in CouchDB by sending a request to the server using DELETE method through cURL utility. Following is the syntax to create a database βˆ’" }, { "code": null, "e": 35996, "s": 35942, "text": "$ curl -X DELETE http://127.0.0.1:5984/database name\n" }, { "code": null, "e": 36229, "s": 35996, "text": "Using βˆ’X we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using the DELETE method. Send the url to the server by specifying the database to be deleted in it." }, { "code": null, "e": 36369, "s": 36229, "text": "Assume there is a database named my_database2 in CouchDB. Using the above given syntax if you want to delete it, you can do it as follows βˆ’" }, { "code": null, "e": 36440, "s": 36369, "text": "$ curl -X DELETE http://127.0.0.1:5984/my_database2\n{\n \"ok\" : true\n}" }, { "code": null, "e": 36564, "s": 36440, "text": "As a response, the server will return you a JSON document with content β€œok” βˆ’ true indicating the operation was successful." }, { "code": null, "e": 36747, "s": 36564, "text": "Verify whether the database is deleted by listing out all the databases as shown below. Here you can observe the name of the deleted database, \"my_database\" is not there in the list." }, { "code": null, "e": 36825, "s": 36747, "text": "$ curl -X GET http://127.0.0.1:5984/_all_dbs\n\n[ \"_replicator \" , \" _users \" ]" }, { "code": null, "e": 36959, "s": 36825, "text": "To delete a database, open the http://127.0.0.1:5984/_utils/ url where you will get an Overview/index page of CouchDB as shown below." }, { "code": null, "e": 37294, "s": 36959, "text": "Here you can see three user created databases. Let us delete the database named tutorials_point2. To delete a database, select one from the list of databases, and click on it, which will lead to the overview page of the selected database where you can see the various operations on databases. The following screenshot shows the same βˆ’" }, { "code": null, "e": 37468, "s": 37294, "text": "Among them you can find Delete Database option. By clicking on it you will get a popup window, asking whether you are sure! Click on delete, to delete the selected database." }, { "code": null, "e": 37754, "s": 37468, "text": "Documents are CouchDB’s central data structure. Contents of the database will be stored in the form of Documents instead of tables. You can create these documents using cURL utility provided by CouchDB, as well as Futon. This chapter covers the ways to create a document in a database." }, { "code": null, "e": 38034, "s": 37754, "text": "Each document in CouchDB has a unique ID. You can choose your own ID that should be in the form of a string. Generally, UUID (Universally Unique IDentifier) is used, which are random numbers that have least chance of creating a duplicate. These are preferred to avoid collisions." }, { "code": null, "e": 38197, "s": 38034, "text": "You can create a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a document." }, { "code": null, "e": 38271, "s": 38197, "text": "$ curl -X PUT http://127.0.0.1:5984/database name/\"id\" -d ' { document} '" }, { "code": null, "e": 38577, "s": 38271, "text": "Using βˆ’X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using PUT method. When we use the PUT method, the content of the url specifies the object name we are creating using the HTTP request. Here we have to send the following βˆ’" }, { "code": null, "e": 38646, "s": 38577, "text": "The name of the database name in which we are creating the document." }, { "code": null, "e": 38715, "s": 38646, "text": "The name of the database name in which we are creating the document." }, { "code": null, "e": 38732, "s": 38715, "text": "The document id." }, { "code": null, "e": 38749, "s": 38732, "text": "The document id." }, { "code": null, "e": 38962, "s": 38749, "text": "The data of the document. βˆ’d option is used to send the data/document through HTTP request. While writing a document simply enter your Field-Value pairs separated by colon, within flower brackets as shown below βˆ’" }, { "code": null, "e": 39175, "s": 38962, "text": "The data of the document. βˆ’d option is used to send the data/document through HTTP request. While writing a document simply enter your Field-Value pairs separated by colon, within flower brackets as shown below βˆ’" }, { "code": null, "e": 39232, "s": 39175, "text": "{\n Name : Raju\n age : 23\n Designation : Designer\n}" }, { "code": null, "e": 39377, "s": 39232, "text": "Using the above given syntax if you want to create a document with id 001 in a database with name my_database, you can create it as shown below." }, { "code": null, "e": 39578, "s": 39377, "text": "$ curl -X PUT http://127.0.0.1:5984/my_database/\"001\" -d\n'{ \" Name \" : \" Raju \" , \" age \" :\" 23 \" , \" Designation \" : \" Designer \" }'\n\n{\"ok\":true,\"id\":\"001\",\"rev\":\"1-1c2fae390fa5475d9b809301bbf3f25e\"}" }, { "code": null, "e": 39642, "s": 39578, "text": "The response of CouchDB to this request contains three fields βˆ’" }, { "code": null, "e": 39689, "s": 39642, "text": "\"ok\", indicating the operation was successful." }, { "code": null, "e": 39736, "s": 39689, "text": "\"ok\", indicating the operation was successful." }, { "code": null, "e": 39782, "s": 39736, "text": "\"id\", which stores the id of the document and" }, { "code": null, "e": 39828, "s": 39782, "text": "\"id\", which stores the id of the document and" }, { "code": null, "e": 40205, "s": 39828, "text": "\"rev\", this indicates the revision id. Every time you revise (update or modify) a document a _rev value will be generated by CouchDB. If you want to update or delete a document, CouchDB expects you to include the _rev field of the revision you wish to change. When CouchDB accepts the change, it will generate a new revision number. This mechanism ensures concurrency control." }, { "code": null, "e": 40582, "s": 40205, "text": "\"rev\", this indicates the revision id. Every time you revise (update or modify) a document a _rev value will be generated by CouchDB. If you want to update or delete a document, CouchDB expects you to include the _rev field of the revision you wish to change. When CouchDB accepts the change, it will generate a new revision number. This mechanism ensures concurrency control." }, { "code": null, "e": 40673, "s": 40582, "text": "If you want to view the created document you can get it using the document as shown below." }, { "code": null, "e": 40857, "s": 40673, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\": \"001\",\n \"_rev\": \"1-3fcc78daac7a90803f0a5e383f4f1e1e\",\n \"Name\": \"Raju\",\n \"age\": 23,\n \"Designation\": \"Designer\"\n}" }, { "code": null, "e": 40978, "s": 40857, "text": "To Create a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below." }, { "code": null, "e": 41126, "s": 40978, "text": "Select the database in which you want to create the document. Open the Overview page of the database and select New Document option as shown below." }, { "code": null, "e": 41397, "s": 41126, "text": "When you select the New Document option, CouchDB creates a new database document, assigning it a new id. You can edit the value of the id and can assign your own value in the form of a string. In the following illustration, we have created a new document with an id 001." }, { "code": null, "e": 41491, "s": 41397, "text": "In this page, you can observe three options βˆ’ save Document, Add Field and Upload Attachment." }, { "code": null, "e": 41844, "s": 41491, "text": "To add field to the document click on Add Field option. After creating a database, you can add a field to it using this option. Clicking on it will get you a pair of text boxes, namely, Field, value. You can edit these values by clicking on them. Edit those values and type your desired Field-Value pair. Click on the green button to save these values." }, { "code": null, "e": 41948, "s": 41844, "text": "In the following illustration, we have created three fields Name, age and, Designation of the employee." }, { "code": null, "e": 42084, "s": 41948, "text": "You can save the changes made to the document by clicking on this option. After saving, a new id _rev will be generated as shown below." }, { "code": null, "e": 42247, "s": 42084, "text": "You can update a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to update a document." }, { "code": null, "e": 42359, "s": 42247, "text": "curl -X PUT http://127.0.0.1:5984/database_name/document_id/ -d '{ \"field\" : \"value\", \"_rev\" : \"revision id\" }'" }, { "code": null, "e": 42470, "s": 42359, "text": "Suppose there is a document with id 001 in the database named my_database. You can delete this as shown below." }, { "code": null, "e": 42648, "s": 42470, "text": "First of all, get the revision id of the document that is to be updated. You can find the _rev of the document in the document itself, therefore get the document as shown below." }, { "code": null, "e": 42790, "s": 42648, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\" : \"001\",\n \"_rev\" : \"2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \"age\" : \"23\"\n}" }, { "code": null, "e": 42897, "s": 42790, "text": "Use revision id _rev from the document to update the document. Here we are updating the age from 23 to 24." }, { "code": null, "e": 43119, "s": 42897, "text": "$ curl -X PUT http://127.0.0.1:5984/my_database/001/ -d\n' { \" age \" : \" 24 \" , \" _rev \" : \" 1-1c2fae390fa5475d9b809301bbf3f25e \" } '\n\n{ \" ok \" : true , \" id \" : \" 001 \" , \" rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" }" }, { "code": null, "e": 43200, "s": 43119, "text": "To verify the document, get the document again using GET request as shown below." }, { "code": null, "e": 43355, "s": 43200, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \" _id \" : \" 001 \",\n \" _rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \" age \" : \" 23 \"\n }\n" }, { "code": null, "e": 43430, "s": 43355, "text": "Following are some important points to be noted while updating a document." }, { "code": null, "e": 43511, "s": 43430, "text": "The URL we send in the request containing the database name and the document id." }, { "code": null, "e": 43592, "s": 43511, "text": "The URL we send in the request containing the database name and the document id." }, { "code": null, "e": 43815, "s": 43592, "text": "Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID." }, { "code": null, "e": 44038, "s": 43815, "text": "Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID." }, { "code": null, "e": 44107, "s": 44038, "text": "We have to supply the revision number as a part of the JSON request." }, { "code": null, "e": 44176, "s": 44107, "text": "We have to supply the revision number as a part of the JSON request." }, { "code": null, "e": 44395, "s": 44176, "text": "In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number." }, { "code": null, "e": 44614, "s": 44395, "text": "In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number." }, { "code": null, "e": 44735, "s": 44614, "text": "To delete a document open the http://127.0.0.1:5984/_utils/ url to get an\nOverview/index page of CouchDB as shown below." }, { "code": null, "e": 44950, "s": 44735, "text": "Select the database in which the document to be updated exists and click it. Here we are updating a document in the database named tutorials_point. You will get the list of documents in the database as shown below." }, { "code": null, "e": 45068, "s": 44950, "text": "Select a document that you want to update and click on it. You will get the contents of the documents as shown below." }, { "code": null, "e": 45224, "s": 45068, "text": "Here, to update the location from Delhi to Hyderabad, click on the text box, edit the field, and click the green button to save the changes as shown below." }, { "code": null, "e": 45390, "s": 45224, "text": "You can delete a document in CouchDB by sending an HTTP request to the server using DELETE method through cURL utility. Following is the syntax to delete a document." }, { "code": null, "e": 45466, "s": 45390, "text": "curl -X DELETE http : // 127.0.0.1:5984 / database name/database id?_rev id" }, { "code": null, "e": 45799, "s": 45466, "text": "Using βˆ’X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using Delete method. To delete a database /database_name/database_id/ is not enough. You have to pass the recent revision id through the url. To mention attributes of any data structure \"?\" is used." }, { "code": null, "e": 45986, "s": 45799, "text": "Suppose there is a document in database named my_database with document id 001. To delete this document, you have to get the rev id of the document. Get the document data as shown below." }, { "code": null, "e": 46139, "s": 45986, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \" _id \" : \" 001 \",\n \" _rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \" age \" : \" 23 \"\n}" }, { "code": null, "e": 46278, "s": 46139, "text": "Now specify the revision id of the document to be deleted, id of the document, and database name the document belongs to, as shown below βˆ’" }, { "code": null, "e": 46440, "s": 46278, "text": "$ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-\n3fcc78daac7a90803f0a5e383f4f1e1e\n\n{\"ok\":true,\"id\":\"001\",\"rev\":\"2-3a561d56de1ce3305d693bd15630bf96\"}" }, { "code": null, "e": 46630, "s": 46440, "text": "To verify whether the document is deleted, try to fetch the document by using the GET method. Since you are fetching a deleted document, this will give you an error message as shown below βˆ’" }, { "code": null, "e": 46724, "s": 46630, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\"error\":\"not_found\",\"reason\":\"deleted\"}\n" }, { "code": null, "e": 46841, "s": 46724, "text": "First of all, verify the documents in the database. Following is the snapshot of the database named tutorials_point." }, { "code": null, "e": 46964, "s": 46841, "text": "Here you can observe, the database consists of three documents. To delete any of the documents say 003, do the following βˆ’" }, { "code": null, "e": 47083, "s": 46964, "text": "Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs." }, { "code": null, "e": 47202, "s": 47083, "text": "Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs." }, { "code": null, "e": 47308, "s": 47202, "text": "This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document." }, { "code": null, "e": 47414, "s": 47308, "text": "This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document." }, { "code": null, "e": 47447, "s": 47414, "text": "Click on Delete Document option." }, { "code": null, "e": 47480, "s": 47447, "text": "Click on Delete Document option." }, { "code": null, "e": 47603, "s": 47480, "text": "You will get a dialog box saying \"Are you sure you want to delete this document?\" Click on delete, to delete the document." }, { "code": null, "e": 47726, "s": 47603, "text": "You will get a dialog box saying \"Are you sure you want to delete this document?\" Click on delete, to delete the document." }, { "code": null, "e": 48021, "s": 47726, "text": "You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document βˆ’" }, { "code": null, "e": 48177, "s": 48021, "text": "$ curl -vX PUT http://127.0.0.1:5984/database_name/database_id\n/filename?rev=document rev_id --data-binary @filename -H \"Content-Type:\ntype of the content\"" }, { "code": null, "e": 48235, "s": 48177, "text": "The request has various options that are explained below." }, { "code": null, "e": 48329, "s": 48235, "text": "--data-binary@ βˆ’ This option tells cURL to read a file’s contents into the HTTP request body." }, { "code": null, "e": 48423, "s": 48329, "text": "--data-binary@ βˆ’ This option tells cURL to read a file’s contents into the HTTP request body." }, { "code": null, "e": 48512, "s": 48423, "text": "-H βˆ’ This option is used to mention the content type of the file we are going to upload." }, { "code": null, "e": 48601, "s": 48512, "text": "-H βˆ’ This option is used to mention the content type of the file we are going to upload." }, { "code": null, "e": 48845, "s": 48601, "text": "Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below." }, { "code": null, "e": 48966, "s": 48845, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\": \"001\",\n \"_rev\": \"1-967a00dff5e02add41819138abb3284d\"\n}" }, { "code": null, "e": 49051, "s": 48966, "text": "Now using the _rev value, send the PUT request to the CouchDB server as shown below." }, { "code": null, "e": 49203, "s": 49051, "text": "$ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1-\n967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H \"ContentType:\nimage/jpg\"" }, { "code": null, "e": 49292, "s": 49203, "text": "To verify whether the attachment is uploaded, fetch the document content as shown belowβˆ’" }, { "code": null, "e": 49627, "s": 49292, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\": \"001\",\n \"_rev\": \"2-4705a219cdcca7c72aac4f623f5c46a8\",\n \"_attachments\": {\n \"boy.jpg\": {\n \"content_type\": \"image/jpg\",\n \"revpos\": 2,\n \"digest\": \"md5-9Swz8jvmga5mfBIsmCxCtQ==\",\n \"length\": 91408,\n \"stub\": true\n }\n }\n}\n" }, { "code": null, "e": 49899, "s": 49627, "text": "Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button." }, { "code": null, "e": 50007, "s": 49899, "text": "The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it." }, { "code": null, "e": 50014, "s": 50007, "text": " Print" }, { "code": null, "e": 50025, "s": 50014, "text": " Add Notes" } ]
Make Unordered list with Bootstrap
For unordered list in Bootstrap, you can try to run the following code βˆ’ Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap lists</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <h1>Lists</h1> <h2>Fruits (Ordered List)</h2> <ol> <li>Kiwi</li> <li>Apple</li> <li>Mango</li> </ol> <h2>Vegetables (UnOrdered List)</h2> <ul> <li>Tomato</li> <li>Brinjal</li> <li>Broccoli</li> </ul> </body> </html>
[ { "code": null, "e": 1135, "s": 1062, "text": "For unordered list in Bootstrap, you can try to run the following code βˆ’" }, { "code": null, "e": 1145, "s": 1135, "text": "Live Demo" }, { "code": null, "e": 1946, "s": 1145, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap lists</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/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://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h1>Lists</h1>\n <h2>Fruits (Ordered List)</h2>\n <ol>\n <li>Kiwi</li>\n <li>Apple</li>\n <li>Mango</li>\n </ol>\n <h2>Vegetables (UnOrdered List)</h2>\n <ul>\n <li>Tomato</li>\n <li>Brinjal</li>\n <li>Broccoli</li>\n </ul>\n </body>\n</html>" } ]
How to populate a Map using a lambda expression in Java?
A Map is a collection object that maps keys to values in Java. The data can be stored in key/value pairs and each key is unique. These key/value pairs are also called map entries. In the below example, we can populate a Map using a lambda expression. We have passed Character and Runnable arguments to Map object and pass a lambda expression as the second argument in the put() method of Map class. We need to pass command-line arguments whether the user enters 'h' for Help and 'q' for quit with the help of Scanner class. import java.util.*; public class PopulateUsingMapLambdaTest { public static void main(String[] args) { Map<Character, Runnable> map = new HashMap<>(); map.put('h', () -> System.out.println("Type h or q")); // lambda expression map.put('q', () -> System.exit(0)); // lambda expression while(true) { System.out.println("Menu"); System.out.println("h) Help"); System.out.println("q) Quit"); char key = new Scanner(System.in).nextLine().charAt(0); if(map.containsKey(key)) map.get(key).run(); } } } Menu h) Help q) Quit Type h or q : q
[ { "code": null, "e": 1242, "s": 1062, "text": "A Map is a collection object that maps keys to values in Java. The data can be stored in key/value pairs and each key is unique. These key/value pairs are also called map entries." }, { "code": null, "e": 1586, "s": 1242, "text": "In the below example, we can populate a Map using a lambda expression. We have passed Character and Runnable arguments to Map object and pass a lambda expression as the second argument in the put() method of Map class. We need to pass command-line arguments whether the user enters 'h' for Help and 'q' for quit with the help of Scanner class." }, { "code": null, "e": 2182, "s": 1586, "text": "import java.util.*;\n\npublic class PopulateUsingMapLambdaTest {\n public static void main(String[] args) {\n Map<Character, Runnable> map = new HashMap<>();\n\n map.put('h', () -> System.out.println(\"Type h or q\")); // lambda expression\n map.put('q', () -> System.exit(0)); // lambda expression\n\n while(true) {\n System.out.println(\"Menu\");\n System.out.println(\"h) Help\");\n System.out.println(\"q) Quit\");\n char key = new Scanner(System.in).nextLine().charAt(0);\n if(map.containsKey(key))\n map.get(key).run();\n }\n }\n}" }, { "code": null, "e": 2219, "s": 2182, "text": "Menu\nh) Help\nq) Quit\nType h or q :\nq" } ]
PyQt5 Label – Getting Blur effect object - GeeksforGeeks
10 May, 2020 In this article we will see how we can get blur effect object of the label by default there is no blur effect to the label although we can create blur effect then add it to the label with the help of setGraphicsEffect method. In order to do this we have to do the following – 1. Create a label2. Set geometry to the label3. Create a QGraphicsBlurEffect object4. Add this object to the label with the help of setGraphicsEffect method5. Get the opacity object with the help of graphicsEffect method Note : This object have same properties of the original object Syntax : # creating a blur effect blur_effect = QGraphicsBlurEffect() # adding blur effect to the label label.setGraphicsEffect(blur_effect) # getting the blur object object = label.graphicsEffect() Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Label", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet("QLabel" "{" "border : 2px solid green;" "background : lightgreen;" "}") # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # result label result = QLabel(self) # setting geometry of the result label result.setGeometry(200, 200, 300, 30) # getting the blur object object = label.graphicsEffect() # setting text to the result label result.setText(str(object)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-Label Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n10 May, 2020" }, { "code": null, "e": 24127, "s": 23901, "text": "In this article we will see how we can get blur effect object of the label by default there is no blur effect to the label although we can create blur effect then add it to the label with the help of setGraphicsEffect method." }, { "code": null, "e": 24177, "s": 24127, "text": "In order to do this we have to do the following –" }, { "code": null, "e": 24398, "s": 24177, "text": "1. Create a label2. Set geometry to the label3. Create a QGraphicsBlurEffect object4. Add this object to the label with the help of setGraphicsEffect method5. Get the opacity object with the help of graphicsEffect method" }, { "code": null, "e": 24461, "s": 24398, "text": "Note : This object have same properties of the original object" }, { "code": null, "e": 24470, "s": 24461, "text": "Syntax :" }, { "code": null, "e": 24663, "s": 24470, "text": "# creating a blur effect\nblur_effect = QGraphicsBlurEffect()\n\n# adding blur effect to the label\nlabel.setGraphicsEffect(blur_effect)\n\n# getting the blur object\nobject = label.graphicsEffect()\n" }, { "code": null, "e": 24691, "s": 24663, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Label\", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet(\"QLabel\" \"{\" \"border : 2px solid green;\" \"background : lightgreen;\" \"}\") # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # result label result = QLabel(self) # setting geometry of the result label result.setGeometry(200, 200, 300, 30) # getting the blur object object = label.graphicsEffect() # setting text to the result label result.setText(str(object)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26376, "s": 24691, "text": null }, { "code": null, "e": 26385, "s": 26376, "text": "Output :" }, { "code": null, "e": 26404, "s": 26385, "text": "Python PyQt5-Label" }, { "code": null, "e": 26415, "s": 26404, "text": "Python-gui" }, { "code": null, "e": 26427, "s": 26415, "text": "Python-PyQt" }, { "code": null, "e": 26434, "s": 26427, "text": "Python" }, { "code": null, "e": 26532, "s": 26434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26541, "s": 26532, "text": "Comments" }, { "code": null, "e": 26554, "s": 26541, "text": "Old Comments" }, { "code": null, "e": 26586, "s": 26554, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26642, "s": 26586, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26684, "s": 26642, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26726, "s": 26684, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26762, "s": 26726, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26784, "s": 26762, "text": "Defaultdict in Python" }, { "code": null, "e": 26823, "s": 26784, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26850, "s": 26823, "text": "Python Classes and Objects" }, { "code": null, "e": 26881, "s": 26850, "text": "Python | os.path.join() method" } ]
Spring Security - OAuth2
OAuth2.0 Fundamentals OAuth2.0 Getting started(Practical Guide) OAuth 2.0 was developed by IETF OAuth Working Group and published in October of 2012. It serves as an open authorization protocol for enabling a third party application to get limited access to an HTTP service on behalf of the resource owner. It can do so while not revealing the identity or the long-term credentials of the user. A third-party application itself can also use it on its behalf. The working principle of OAuth consists of the delegation of user authentication to a service hosting the user account and authorizing the third-party application access to the account of the user. Let us consider an example. Let us say we want to login to a website β€œclientsite.com”. We can sign in via Facebook, Github, Google or Microsoft. We select any options of the options given above, and we are redirected to the respective website for login. If login is successful, we are asked if we want to give clientsite.com access to the specific data requested by it. We select our desired option and we are redirected to clientsite.com with an authorization code or error code and our login is successful or not depending on our action in the third-party resource. This is the basic working principle of OAuth 2. There are five key actors involved in an OAuth system. Let’s list them out βˆ’ User / Resource Owner βˆ’ The end-user, who is responsible for the authentication and for providing consent to share resources with the client. User / Resource Owner βˆ’ The end-user, who is responsible for the authentication and for providing consent to share resources with the client. User-Agent βˆ’ The browser used by the User. User-Agent βˆ’ The browser used by the User. Client βˆ’ The application requesting an access token. Client βˆ’ The application requesting an access token. Authorization Server βˆ’ The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime. Authorization Server βˆ’ The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime. Resource Server βˆ’ The API that provides access to the requested resource. It validates the access tokens and provides authorization. Resource Server βˆ’ The API that provides access to the requested resource. It validates the access tokens and provides authorization. We will be developing a Spring Boot Application with Spring Security and OAuth 2.0 to illustrate the above. We will be developing a basic application with an in-memory database to store user credentials now. The application will make it easy for us to understand the workings of OAuth 2.0 with Spring Security. Let’s use the Spring initializer to create a maven project in Java 8. Let’s start by going to start.spring.io. We generate an application with the following dependenciesβˆ’ Spring Web Spring Security Cloud OAuth2 Spring Boot Devtools With the above configuration, we click on the Generate button to generate a project. The project will be downloaded in a zip file. We extract the zip to a folder. We can then open the project in an IDE of our choice. I am using Spring Tools Suite here as it is optimized for spring applications. We can also use Eclipse or IntelliJ Idea as we wish. So, we open the project in STS, let the dependencies get downloaded. Then we can see the project structure in our package explorer window. It should resemble the screenshot below. If we open the pom.xml file we can view the dependencies and other details related to the project. It should look something like this. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorial</groupId> <artifactId>spring.security.oauth2</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring.security.oauth2</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.SR6</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> <dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement><build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Now, to the base package of our application, i.e., com.tutorial.spring.security.oauth2, let’s add a new package named config where we shall add our configuration classes. Let’s create our first configuration class, UserConfig which extends the WebSecurityConfigurerAdapter class of Spring Security to manage the users of the client application. We annotate the class with @Configuration annotation to tell Spring that it is a configuration class. package com.tutorial.spring.security.oauth2.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; @Configuration public class UserConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("john") .password("12345") .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } We then add a bean of the UserDetailsService to retrieve the user details for authentication and authorization. To put it in the Spring context we annotate it with @Bean. To keep this tutorial simple and easy to understand, we use an InMemoryUserDetailsManager instance. For a real-world application, we can use other implementations like JdbcUserDetailsManager to connect to a database and so on. To be able to create users easily for this example we use the UserDetailsManager interface which extends the UserDetailsService and has methods like createUser(), updateUser() and so on. Then, we create a user using the builder class. We give him a username, password and a β€œread” authority for now. Then, using the createUser() method, we add the newly created user and return the instance of UserDetailsManager thus putting it in the Spring context. To be able to use the UserDetailsService defined by us, it is necessary to provide a PasswordEncoder bean in the Spring context. Again, to keep it simple for now we use the NoOpPasswordEncoder. The NoOpPasswordEncoder should not be used otherwise for real-world applications for production as it is not secure. NoOpPasswordEncoder does not encode the password and is only useful for developing or testing scenarios or proof of concepts. We should always use the other highly secure options provided by Spring Security, the most popular of which is the BCryptPasswordEncoder, which we will be using later in our series of tutorials. To put it in the Spring context we annotate the method with @Bean. We then override the AuthenticationManager bean method of WebSecurityConfigurerAdapter, which returns the authenticationManagerBean to put the authentication manager into the Spring context. Now, to add the client configurations we add a new configuration class named AuthorizationServerConfig which extends AuthorizationServerConfigurerAdapter class of Spring Security. The AuthorizationServerConfigurerAdapter class is used to configure the authorization server using the spring security oauth2 module. We annotate this class with @Configuration as well. To add the authorization server functionality to this class we need to add the @EnableAuthorizationServer annotation so that the application can behave as an authorization server. package com.tutorial.spring.security.oauth2.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("oauthclient1") .secret("oauthsecret1") .scopes("read") .authorizedGrantTypes("password") } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } For checking oauth tokens, Spring Security oauth exposes two endpoints – /oauth/check_token and /oauth/token_key. These endpoints are protected by default behind denyAll(). tokenKeyAccess() and checkTokenAccess() methods open these endpoints for use. We autowire the AuthenticationManager bean we configured in the UserConfig class as a dependency here which we shall be using later. We then override two of the configure() methods of the AuthorizationServerConfigurerAdapter to provide an in-memory implementation of the client details service. The first method which uses the ClientDetailsServiceConfigurer as a parameter, as the name suggests, allows us to configure the clients for the authorization server. These clients represent the applications that will be able to use the functionality of this authorization server. Since this is a basic application for learning the implementation of OAuth2, we will keep things simple for now and use an in-memory implementation with the following attributes βˆ’ clientId βˆ’ the id of the client. Required. clientId βˆ’ the id of the client. Required. secret βˆ’ the client secret, required for trusted clients secret βˆ’ the client secret, required for trusted clients scope βˆ’ the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope. scope βˆ’ the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope. authorizedGrantTypes βˆ’ the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the β€œpassword” grant type as it is the simplest. Later, we shall be using another grant type for another use-case. authorizedGrantTypes βˆ’ the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the β€œpassword” grant type as it is the simplest. Later, we shall be using another grant type for another use-case. In β€œpassword” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials for the authorization server we want the tokens from. The other configure() method that we overrode, uses AuthorizationServerEndpointsConfigurer as a parameter, is used to attach the AuthenticationManager to authorization server configuration. With these basic configurations, our Authorization server is ready to use. Let’s go ahead and start it and use it. We will be using Postman ( https://www.postman.com/downloads/ ) for making our requests. When using STS, we can launch our application and start seeing see the logs in our console. When the application starts, we can find the oauth2 endpoints exposed by our application in the console. Of those endpoints, we will be using the following the below token for now βˆ’ /oauth/token – for obtaining the token. If we check the postman snapshot here, we can notice a few things. Let’s list them down below. The URL βˆ’ Our Spring Boot Application is running at port 8080 of our local machine, so the request is pointed to http://localhost:8080. The next part is /oauth/token, which we know, is the endpoint exposed by OAuth for generating the token. The query paramsβˆ’ Since this is a β€œpassword” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials to the authorization server we want the tokens from. Client Authorization βˆ’ The Oauth system requires the client to be authorized to be able to provide the token. Hence, under the Authorization header, we provide the client authentication information, namely username and password that we configured in our application. Let’s take a closer look at the query params and the authorization header βˆ’ The query params Client credentials If everything is correct, we shall be able to see our generated token in the response along with a 200 ok status. The response We can test our server, by putting wrong credentials or no credentials, and we will get back an error which would say the request is unauthorized or has bad credentials. This is our basic oauth authorization server, that uses the password grant type to generate and provide a password. Next, let’s implement a more secure, and a more common application of the oauth2 authentication, i.e. with an authorization code grant type. We will update our current application for this purpose. The authorization grant type is different from the password grant type in the sense that the user doesn’t have to share his credentials with the client application. He shares them with the authorization server only and in return authorization code is sent to the client which it uses to authenticate the client. It is more secure than the password grant type as user credentials are not shared with the client application and hence the user’s information stays safe. The client application doesn’t get access to any important user information unless approved by the user. In a few simple steps, we can set up a basic oauth server with an authorization grant type in our application. Let’s see how. package com.tutorial.spring.security.oauth2.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("oauthclient1") .secret("oauthsecret1") .scopes("read") .authorizedGrantTypes("password") .and() .withClient("oauthclient2") .secret("oauthsecret2") .scopes("read") .authorizedGrantTypes("authorization_code") .redirectUris("http://locahost:9090"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } Let’s add a second client for this operation oauthclient2 for this operation with a new secret and read scope. Here we have changed the grant type to authorization code for this client. We also added a redirect URI so that the authorization server can callback the client. So, basically the redirect URI is the URI of the client. Now, we have to establish a connection between the user and the authorization server. We have to set an interface for the authorization server where the user can provide the credentials. We use the formLogin() implementation of Spring Security to achieve that functionality while keeping things simple. We also make sure that all requests are authenticated. package com.tutorial.spring.security.oauth2.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; @SuppressWarnings("deprecation") @Configuration public class UserConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("john") .password("12345") .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(); http.authorizeRequests().anyRequest().authenticated(); } } This completes our setup for the authorization grant type. Now to test our setup and launch our application. We launch our browser at http://localhost:8080/oauth/authorize?response_type=code&client_id=oauthclient2&scope=read. We will redirected to the default form login page of Spring Security. Here, the response type code implies that the authorization server will return an access code which will be used by the client to log in. When we use the user credentials we will be asked if I want to grant the permissions asked by the client, in a similar screen as shown below. If we approve and click Authorize we shall see we are redirected to our given redirect url along with the access code. In our case the we are redirected to http://locahost:9090/?code=7Hibnw, as we specified in the application. We can use the code now as a client in Postman to login to the authorization server. As we can see here, we have used the code received from the authorization server in our URL, and the grant_type as authorization_code and scope as read. We acted as the client and provided the client credentials as configured in our application. When we make this request we get back our access_token which we can use further. So, we have seen how we can configure Spring Security with OAuth 2.0. The application is pretty simple and easy to understand and helps us understand the process fairly easily. We have used two kinds of authorization grant types and seen how we can use them to acquire access tokens for our client application. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 1857, "s": 1835, "text": "OAuth2.0 Fundamentals" }, { "code": null, "e": 1899, "s": 1857, "text": "OAuth2.0 Getting started(Practical Guide)" }, { "code": null, "e": 2492, "s": 1899, "text": "OAuth 2.0 was developed by IETF OAuth Working Group and published in October of 2012. It serves as an open authorization protocol for enabling a third party application to get limited access to an HTTP service on behalf of the resource owner. It can do so while not revealing the identity or the long-term credentials of the user. A third-party application itself can also use it on its behalf. The working principle of OAuth consists of the delegation of user authentication to a service hosting the user account and authorizing the third-party application access to the account of the user." }, { "code": null, "e": 3108, "s": 2492, "text": "Let us consider an example. Let us say we want to login to a website β€œclientsite.com”. We can sign in via Facebook, Github, Google or Microsoft. We select any options of the options given above, and we are redirected to the respective website for login. If login is successful, we are asked if we want to give clientsite.com access to the specific data requested by it. We select our desired option and we are redirected to clientsite.com with an authorization code or error code and our login is successful or not depending on our action in the third-party resource. This is the basic working principle of OAuth 2." }, { "code": null, "e": 3185, "s": 3108, "text": "There are five key actors involved in an OAuth system. Let’s list them out βˆ’" }, { "code": null, "e": 3327, "s": 3185, "text": "User / Resource Owner βˆ’ The end-user, who is responsible for the authentication and for providing consent to share resources with the client." }, { "code": null, "e": 3469, "s": 3327, "text": "User / Resource Owner βˆ’ The end-user, who is responsible for the authentication and for providing consent to share resources with the client." }, { "code": null, "e": 3512, "s": 3469, "text": "User-Agent βˆ’ The browser used by the User." }, { "code": null, "e": 3555, "s": 3512, "text": "User-Agent βˆ’ The browser used by the User." }, { "code": null, "e": 3608, "s": 3555, "text": "Client βˆ’ The application requesting an access token." }, { "code": null, "e": 3661, "s": 3608, "text": "Client βˆ’ The application requesting an access token." }, { "code": null, "e": 3808, "s": 3661, "text": "Authorization Server βˆ’ The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime." }, { "code": null, "e": 3955, "s": 3808, "text": "Authorization Server βˆ’ The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime." }, { "code": null, "e": 4088, "s": 3955, "text": "Resource Server βˆ’ The API that provides access to the requested resource. It validates the access tokens and provides authorization." }, { "code": null, "e": 4221, "s": 4088, "text": "Resource Server βˆ’ The API that provides access to the requested resource. It validates the access tokens and provides authorization." }, { "code": null, "e": 4532, "s": 4221, "text": "We will be developing a Spring Boot Application with Spring Security and OAuth 2.0 to illustrate the above. We will be developing a basic application with an in-memory database to store user credentials now. The application will make it easy for us to understand the workings of OAuth 2.0 with Spring Security." }, { "code": null, "e": 4703, "s": 4532, "text": "Let’s use the Spring initializer to create a maven project in Java 8. Let’s start by going to start.spring.io. We generate an application with the following dependenciesβˆ’" }, { "code": null, "e": 4714, "s": 4703, "text": "Spring Web" }, { "code": null, "e": 4730, "s": 4714, "text": "Spring Security" }, { "code": null, "e": 4743, "s": 4730, "text": "Cloud OAuth2" }, { "code": null, "e": 4764, "s": 4743, "text": "Spring Boot Devtools" }, { "code": null, "e": 5113, "s": 4764, "text": "With the above configuration, we click on the Generate button to generate a project. The project will be downloaded in a zip file. We extract the zip to a folder. We can then open the project in an IDE of our choice. I am using Spring Tools Suite here as it is optimized for spring applications. We can also use Eclipse or IntelliJ Idea as we wish." }, { "code": null, "e": 5293, "s": 5113, "text": "So, we open the project in STS, let the dependencies get downloaded. Then we can see the project structure in our package explorer window. It should resemble the screenshot below." }, { "code": null, "e": 5428, "s": 5293, "text": "If we open the pom.xml file we can view the dependencies and other details related to the project. It should look something like this." }, { "code": null, "e": 8181, "s": 5428, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE</version> \n <relativePath/> <!-- lookup parent from repository -->\n </parent> \n <groupId>com.tutorial</groupId> \n <artifactId>spring.security.oauth2</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <name>spring.security.oauth2</name> \n <description>Demo project for Spring Boot</description> \n <properties> \n <java.version>1.8</java.version> \n <spring-cloud.version>Hoxton.SR6</spring-cloud.version> \n </properties> \n <dependencies> \n <dependency> \n <groupId>org.springframework.boot<groupId> \n <artifactId>spring-boot-starter-security</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency>\n <groupId>org.springframework.cloud</groupId> \n <artifactId>spring-cloud-starter-oauth2</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot<groupId> \n <artifactId>spring-boot-devtools</artifactId>\n <scope>runtime</scope> \n <optional>true</optional> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> <exclusions> <exclusion> \n <groupId>org.junit.vintage</groupId> \n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n <dependency> \n <dependency>\n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test</artifactId> \n <scope>test</scope> \n </dependency> \n </dependencies> \n <dependencyManagement> \n <dependencies> \n <dependency> \n <groupId>org.springframework.cloud</groupId> \n <artifactId>spring-cloud-dependencies</artifactId> \n <version>${spring-cloud.version}</version> \n <type>pom</type> \n <scope>import</scope> \n </dependency> \n </dependencies> \n </dependencyManagement><build> \n <plugins> \n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 8352, "s": 8181, "text": "Now, to the base package of our application, i.e., com.tutorial.spring.security.oauth2, let’s add a new package named config where we shall add our configuration classes." }, { "code": null, "e": 8628, "s": 8352, "text": "Let’s create our first configuration class, UserConfig which extends the WebSecurityConfigurerAdapter class of Spring Security to manage the users of the client application. We annotate the class with @Configuration annotation to tell Spring that it is a configuration class." }, { "code": null, "e": 10231, "s": 8628, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; \nimport org.springframework.security.provisioning.UserDetailsManager; \n@Configuration public class UserConfig extends WebSecurityConfigurerAdapter { \n @Bean \n public UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"john\") \n .password(\"12345\") .authorities(\"read\") \n .build(); userDetailsManager.createUser(user); return userDetailsManager; \n } \n @Bean\n public PasswordEncoder passwordEncoder() { \n return NoOpPasswordEncoder.getInstance(); \n } \n @Override \n @Bean \n public AuthenticationManager authenticationManagerBean() throws Exception { \n return super.authenticationManagerBean(); \n } \n}" }, { "code": null, "e": 11081, "s": 10231, "text": "We then add a bean of the UserDetailsService to retrieve the user details for authentication and authorization. To put it in the Spring context we annotate it with @Bean. To keep this tutorial simple and easy to understand, we use an InMemoryUserDetailsManager instance. For a real-world application, we can use other implementations like JdbcUserDetailsManager to connect to a database and so on. To be able to create users easily for this example we use the UserDetailsManager interface which extends the UserDetailsService and has methods like createUser(), updateUser() and so on. Then, we create a user using the builder class. We give him a username, password and a β€œread” authority for now. Then, using the createUser() method, we add the newly created user and return the instance of UserDetailsManager thus putting it in the Spring context." }, { "code": null, "e": 11780, "s": 11081, "text": "To be able to use the UserDetailsService defined by us, it is necessary to provide a PasswordEncoder bean in the Spring context. Again, to keep it simple for now we use the NoOpPasswordEncoder. The NoOpPasswordEncoder should not be used otherwise for real-world applications for production as it is not secure. NoOpPasswordEncoder does not encode the password and is only useful for developing or testing scenarios or proof of concepts. We should always use the other highly secure options provided by Spring Security, the most popular of which is the BCryptPasswordEncoder, which we will be using later in our series of tutorials. To put it in the Spring context we annotate the method with @Bean." }, { "code": null, "e": 11971, "s": 11780, "text": "We then override the AuthenticationManager bean method of WebSecurityConfigurerAdapter, which returns the authenticationManagerBean to put the authentication manager into the Spring context." }, { "code": null, "e": 12518, "s": 11971, "text": "Now, to add the client configurations we add a new configuration class named AuthorizationServerConfig which extends AuthorizationServerConfigurerAdapter class of Spring Security. The AuthorizationServerConfigurerAdapter class is used to configure the authorization server using the spring security oauth2 module. We annotate this class with @Configuration as well. To add the authorization server functionality to this class we need to add the @EnableAuthorizationServer annotation so that the application can behave as an authorization server." }, { "code": null, "e": 13826, "s": 12518, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; \nimport org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer \npublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {\n @Autowired private AuthenticationManager authenticationManager; \n @Override \n public void configure(ClientDetailsServiceConfigurer clients) throws Exception { \n clients.inMemory() .withClient(\"oauthclient1\") .secret(\"oauthsecret1\") .scopes(\"read\") .authorizedGrantTypes(\"password\") } \n @Override \n public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { \n endpoints.authenticationManager(authenticationManager); \n } \n}" }, { "code": null, "e": 14077, "s": 13826, "text": "For checking oauth tokens, Spring Security oauth exposes two endpoints – /oauth/check_token and /oauth/token_key. These endpoints are protected by default behind denyAll(). tokenKeyAccess() and checkTokenAccess() methods open these endpoints for use." }, { "code": null, "e": 14210, "s": 14077, "text": "We autowire the AuthenticationManager bean we configured in the UserConfig class as a dependency here which we shall be using later." }, { "code": null, "e": 14832, "s": 14210, "text": "We then override two of the configure() methods of the AuthorizationServerConfigurerAdapter to provide an in-memory implementation of the client details service. The first method which uses the ClientDetailsServiceConfigurer as a parameter, as the name suggests, allows us to configure the clients for the authorization server. These clients represent the applications that will be able to use the functionality of this authorization server. Since this is a basic application for learning the implementation of OAuth2, we will keep things simple for now and use an in-memory implementation with the following attributes βˆ’" }, { "code": null, "e": 14875, "s": 14832, "text": "clientId βˆ’ the id of the client. Required." }, { "code": null, "e": 14918, "s": 14875, "text": "clientId βˆ’ the id of the client. Required." }, { "code": null, "e": 14975, "s": 14918, "text": "secret βˆ’ the client secret, required for trusted clients" }, { "code": null, "e": 15032, "s": 14975, "text": "secret βˆ’ the client secret, required for trusted clients" }, { "code": null, "e": 15178, "s": 15032, "text": "scope βˆ’ the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope." }, { "code": null, "e": 15324, "s": 15178, "text": "scope βˆ’ the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope." }, { "code": null, "e": 15633, "s": 15324, "text": "authorizedGrantTypes βˆ’ the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the β€œpassword” grant type as it is the simplest. Later, we shall be using another grant type for another use-case." }, { "code": null, "e": 15942, "s": 15633, "text": "authorizedGrantTypes βˆ’ the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the β€œpassword” grant type as it is the simplest. Later, we shall be using another grant type for another use-case." }, { "code": null, "e": 16187, "s": 15942, "text": "In β€œpassword” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials for the authorization server we want the tokens from." }, { "code": null, "e": 16377, "s": 16187, "text": "The other configure() method that we overrode, uses AuthorizationServerEndpointsConfigurer as a parameter, is used to attach the AuthenticationManager to authorization server configuration." }, { "code": null, "e": 16581, "s": 16377, "text": "With these basic configurations, our Authorization server is ready to use. Let’s go ahead and start it and use it. We will be using Postman ( https://www.postman.com/downloads/ ) for making our requests." }, { "code": null, "e": 16855, "s": 16581, "text": "When using STS, we can launch our application and start seeing see the logs in our console. When the application starts, we can find the oauth2 endpoints exposed by our application in the console. Of those endpoints, we will be using the following the below token for now βˆ’" }, { "code": null, "e": 16895, "s": 16855, "text": "/oauth/token – for obtaining the token." }, { "code": null, "e": 16990, "s": 16895, "text": "If we check the postman snapshot here, we can notice a few things. Let’s list them down below." }, { "code": null, "e": 17231, "s": 16990, "text": "The URL βˆ’ Our Spring Boot Application is running at port 8080 of our local machine, so the request is pointed to http://localhost:8080. The next part is /oauth/token, which we know, is the endpoint exposed by OAuth for generating the token." }, { "code": null, "e": 17506, "s": 17231, "text": "The query paramsβˆ’ Since this is a β€œpassword” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials to the authorization server we want the tokens from." }, { "code": null, "e": 17773, "s": 17506, "text": "Client Authorization βˆ’ The Oauth system requires the client to be authorized to be able to provide the token. Hence, under the Authorization header, we provide the client authentication information, namely username and password that we configured in our application." }, { "code": null, "e": 17849, "s": 17773, "text": "Let’s take a closer look at the query params and the authorization header βˆ’" }, { "code": null, "e": 17866, "s": 17849, "text": "The query params" }, { "code": null, "e": 17885, "s": 17866, "text": "Client credentials" }, { "code": null, "e": 17999, "s": 17885, "text": "If everything is correct, we shall be able to see our generated token in the response along with a 200 ok status." }, { "code": null, "e": 18012, "s": 17999, "text": "The response" }, { "code": null, "e": 18182, "s": 18012, "text": "We can test our server, by putting wrong credentials or no credentials, and we will get back an error which would say the request is unauthorized or has bad credentials." }, { "code": null, "e": 18298, "s": 18182, "text": "This is our basic oauth authorization server, that uses the password grant type to generate and provide a password." }, { "code": null, "e": 18496, "s": 18298, "text": "Next, let’s implement a more secure, and a more common application of the oauth2 authentication, i.e. with an authorization code grant type. We will update our current application for this purpose." }, { "code": null, "e": 19068, "s": 18496, "text": "The authorization grant type is different from the password grant type in the sense that the user doesn’t have to share his credentials with the client application. He shares them with the authorization server only and in return authorization code is sent to the client which it uses to authenticate the client. It is more secure than the password grant type as user credentials are not shared with the client application and hence the user’s information stays safe. The client application doesn’t get access to any important user information unless approved by the user." }, { "code": null, "e": 19194, "s": 19068, "text": "In a few simple steps, we can set up a basic oauth server with an authorization grant type in our application. Let’s see how." }, { "code": null, "e": 20709, "s": 19194, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; \nimport org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; \n@Configuration \n@EnableAuthorizationServer \npublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { \n @Autowired private AuthenticationManager authenticationManager; \n @Override \n public void configure(ClientDetailsServiceConfigurer clients) throws Exception {\n clients.inMemory() \n .withClient(\"oauthclient1\") \n .secret(\"oauthsecret1\")\n .scopes(\"read\") .authorizedGrantTypes(\"password\") \n .and() .withClient(\"oauthclient2\") .secret(\"oauthsecret2\") \n .scopes(\"read\") .authorizedGrantTypes(\"authorization_code\") \n .redirectUris(\"http://locahost:9090\"); \n }\n @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { \n endpoints.authenticationManager(authenticationManager); \n } \n}" }, { "code": null, "e": 21039, "s": 20709, "text": "Let’s add a second client for this operation oauthclient2 for this operation with a new secret and read scope. Here we have changed the grant type to authorization code for this client. We also added a redirect URI so that the authorization server can callback the client. So, basically the redirect URI is the URI of the client." }, { "code": null, "e": 21397, "s": 21039, "text": "Now, we have to establish a connection between the user and the authorization server. We have to set an interface for the authorization server where the user can provide the credentials. We use the formLogin() implementation of Spring Security to achieve that functionality while keeping things simple. We also make sure that all requests are authenticated." }, { "code": null, "e": 23191, "s": 21397, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; \nimport org.springframework.security.provisioning.UserDetailsManager; \n@SuppressWarnings(\"deprecation\") @Configuration \npublic class UserConfig extends WebSecurityConfigurerAdapter {\n @Bean\n public UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"john\") \n .password(\"12345\") .authorities(\"read\") .build(); \n userDetailsManager.createUser(user); return userDetailsManager; \n } \n @Bean public PasswordEncoder passwordEncoder() { \n return NoOpPasswordEncoder.getInstance(); \n } \n @Override \n @Bean \n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean(); \n }\n @Override protected void configure(HttpSecurity http) throws Exception {\n http.formLogin(); http.authorizeRequests().anyRequest().authenticated(); \n } \n}" }, { "code": null, "e": 23488, "s": 23191, "text": "This completes our setup for the authorization grant type. Now to test our setup and launch our application. We launch our browser at http://localhost:8080/oauth/authorize?response_type=code&client_id=oauthclient2&scope=read. We will redirected to the default form login page of Spring Security." }, { "code": null, "e": 23768, "s": 23488, "text": "Here, the response type code implies that the authorization server will return an access code which will be used by the client to log in. When we use the user credentials we will be asked if I want to grant the permissions asked by the client, in a similar screen as shown below." }, { "code": null, "e": 24080, "s": 23768, "text": "If we approve and click Authorize we shall see we are redirected to our given redirect url along with the access code. In our case the we are redirected to http://locahost:9090/?code=7Hibnw, as we specified in the application. We can use the code now as a client in Postman to login to the authorization server." }, { "code": null, "e": 24407, "s": 24080, "text": "As we can see here, we have used the code received from the authorization server in our URL, and the grant_type as authorization_code and scope as read. We acted as the client and provided the client credentials as configured in our application. When we make this request we get back our access_token which we can use further." }, { "code": null, "e": 24718, "s": 24407, "text": "So, we have seen how we can configure Spring Security with OAuth 2.0. The application is pretty simple and easy to understand and helps us understand the process fairly easily. We have used two kinds of authorization grant types and seen how we can use them to acquire access tokens for our client application." }, { "code": null, "e": 24752, "s": 24718, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 24766, "s": 24752, "text": " Karthikeya T" }, { "code": null, "e": 24799, "s": 24766, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 24814, "s": 24799, "text": " Chaand Sheikh" }, { "code": null, "e": 24849, "s": 24814, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 24861, "s": 24849, "text": " Senol Atac" }, { "code": null, "e": 24896, "s": 24861, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 24908, "s": 24896, "text": " Senol Atac" }, { "code": null, "e": 24943, "s": 24908, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 24955, "s": 24943, "text": " Senol Atac" }, { "code": null, "e": 24988, "s": 24955, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 25000, "s": 24988, "text": " Senol Atac" }, { "code": null, "e": 25007, "s": 25000, "text": " Print" }, { "code": null, "e": 25018, "s": 25007, "text": " Add Notes" } ]
How to Migrate Your Python Machine Learning model to Other Languages | by Roman Orac | Towards Data Science
I recently worked on a project, where I needed to train a Machine Learning model that would run on the Edge β€” meaning, the processing and prediction occur on the device that collects the data. As usual, I did my Machine Learning part in Python and I haven’t thought much about how we’re going to port my ML stuff to the edge device, which was written in Java. When the modeling part was nearing the end, I started researching how to load a LightGBM model in Java. Prior to this, I had a discussion with a colleague who recommended that I retrain the model with the XGBoost model, which can be loaded in Java with XGBoost4J dependency. LightGBM and XGBoost are both gradient boosting libraries with a few differences. I would expect to get a similar model if I decided to retrain the model with XGBoost, but I didn’t want to rerun all the experiments as there had to be a better way. To my luck, I found a simple way to load any Machine Learning model in Python to any other language. By reading this article, you’ll learn: What is PMML? How to save a Python model to PMML format? How to load the PMML model in Java? How to make predictions with the PMML model in Java? Here are few links that might interest you: - Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course] Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything. From Wikipedia: The Predictive Model Markup Language (PMML) is an XML-based predictive model interchange format conceived by Dr. Robert Lee Grossman, then the director of the National Center for Data Mining at the University of Illinois at Chicago. PMML provides a way for analytic applications to describe and exchange predictive models produced by data mining and machine learning algorithms. PMML supports: Neural Networks Support Vector Machines Association rules Naive Bayes classifier Clustering models Text models Decision trees (Random forest) Gradient Boosting (LightGBM and XGBoost) Regression models PMML enables us to load a Machine Learning model, that was trained in Python, in Java, Go lang, C++, Ruby and others. My first thought after learning about PMML was that I would need to radically refactor the code, which would make retraining the model with XGBoost more feasible. After thinking about it, I decided to give PMML a try. It has a well-maintained repository with clear instructions β€” which is always a good sign. You can simply install the PMML package with: pip install sklearn2pmml sklearn2pmml package is needed to export the Python Machine Learning model to PMML format. Using it is simple, we just need to wrap the classifier with PMMLPipeline class. To make it easier for you, I wrote a simple gist that trains a LightGBM model on the Iris dataset and exports the model to PMML format: Import required Python packagesLoad Iris datasetSplit Iris dataset to train and test setsTrain LightGBM model with PMML support β€” this is the only required change in your code.Measure classification accuracy of the model.And finally, save the model to the PMML format. Import required Python packages Load Iris dataset Split Iris dataset to train and test sets Train LightGBM model with PMML support β€” this is the only required change in your code. Measure classification accuracy of the model. And finally, save the model to the PMML format. The code above creates a PMML file, which is an XML file. The XML contains all the model details as seen in the image below. We trained the model with Python and exported it to PMML format, now we need to load it in Java. I created a minimalistic repository LoadPMMLModel on Github, which shows how to load a PMML model in Java. The first step is to add a PMML dependency to pom.xml (I’m using maven dependency manager): <dependency> <groupId>org.jpmml</groupId> <artifactId>pmml-evaluator</artifactId> <version>1.5.15</version></dependency I saved the PMML file to the project’s resources folder so that compiler can package it. Then we need to specify the path to the model: String modelFolder = LoadPMMLModel.class.getClassLoader().getResource("model").getPath();String modelName = "boosting_model.pmml";Path modelPath = Paths.get(modelFolder, modelName); Loading the model with PMML model is as simple as (the variable with the model in Java is Evaluator type): Evaluator evaluator = new LoadingModelEvaluatorBuilder() .load(modelPath.toFile()) .build();evaluator.verify(); Now let’s make a few predictions with the loaded model. In Python, the prediction for the first sample in the test set was 1. Let’s use the same sample as above in Python, but in Java: Map<String, Double> features = new HashMap<>();features.put("sepal length (cm)", 6.1);features.put("sepal width (cm)", 2.8);features.put("petal length (cm)", 4.7);features.put("petal width (cm)", 1.2);Map<FieldName, FieldValue> arguments = new LinkedHashMap<>();for (InputField inputField : inputFields) { FieldName inputName = inputField.getName(); Double value = features.get(inputName.toString()); FieldValue inputValue = inputField.prepare(value); arguments.put(inputName, inputValue);} And query the model in Java for prediction: Map<FieldName, ?> results = evaluator.evaluate(arguments);// Extracting predictionMap<String, ?> resultRecord = EvaluatorUtil.decodeAll(results);Integer yPred = (Integer) resultRecord.get(targetName.toString());System.out.printf("Prediction is %d\n", yPred);System.out.printf("PMML output %s\n", resultRecord); With the code above, we get the following output: In my Machine Learning learning project, I used a regression boosting model. To my surprise, the exported PMML model produced the same results to the fifth decimal as the model in Python. I don’t have anything bad to say about PMML as it works reliably in production. Remember, you don’t need to copy-paste the code from this article as I created LoadPMMLModel repository on Github. Please let me know what are your thoughts about PMML. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 364, "s": 171, "text": "I recently worked on a project, where I needed to train a Machine Learning model that would run on the Edge β€” meaning, the processing and prediction occur on the device that collects the data." }, { "code": null, "e": 531, "s": 364, "text": "As usual, I did my Machine Learning part in Python and I haven’t thought much about how we’re going to port my ML stuff to the edge device, which was written in Java." }, { "code": null, "e": 806, "s": 531, "text": "When the modeling part was nearing the end, I started researching how to load a LightGBM model in Java. Prior to this, I had a discussion with a colleague who recommended that I retrain the model with the XGBoost model, which can be loaded in Java with XGBoost4J dependency." }, { "code": null, "e": 1054, "s": 806, "text": "LightGBM and XGBoost are both gradient boosting libraries with a few differences. I would expect to get a similar model if I decided to retrain the model with XGBoost, but I didn’t want to rerun all the experiments as there had to be a better way." }, { "code": null, "e": 1155, "s": 1054, "text": "To my luck, I found a simple way to load any Machine Learning model in Python to any other language." }, { "code": null, "e": 1194, "s": 1155, "text": "By reading this article, you’ll learn:" }, { "code": null, "e": 1208, "s": 1194, "text": "What is PMML?" }, { "code": null, "e": 1251, "s": 1208, "text": "How to save a Python model to PMML format?" }, { "code": null, "e": 1287, "s": 1251, "text": "How to load the PMML model in Java?" }, { "code": null, "e": 1340, "s": 1287, "text": "How to make predictions with the PMML model in Java?" }, { "code": null, "e": 1384, "s": 1340, "text": "Here are few links that might interest you:" }, { "code": null, "e": 1562, "s": 1384, "text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]" }, { "code": null, "e": 1733, "s": 1562, "text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything." }, { "code": null, "e": 1749, "s": 1733, "text": "From Wikipedia:" }, { "code": null, "e": 2128, "s": 1749, "text": "The Predictive Model Markup Language (PMML) is an XML-based predictive model interchange format conceived by Dr. Robert Lee Grossman, then the director of the National Center for Data Mining at the University of Illinois at Chicago. PMML provides a way for analytic applications to describe and exchange predictive models produced by data mining and machine learning algorithms." }, { "code": null, "e": 2143, "s": 2128, "text": "PMML supports:" }, { "code": null, "e": 2159, "s": 2143, "text": "Neural Networks" }, { "code": null, "e": 2183, "s": 2159, "text": "Support Vector Machines" }, { "code": null, "e": 2201, "s": 2183, "text": "Association rules" }, { "code": null, "e": 2224, "s": 2201, "text": "Naive Bayes classifier" }, { "code": null, "e": 2242, "s": 2224, "text": "Clustering models" }, { "code": null, "e": 2254, "s": 2242, "text": "Text models" }, { "code": null, "e": 2285, "s": 2254, "text": "Decision trees (Random forest)" }, { "code": null, "e": 2326, "s": 2285, "text": "Gradient Boosting (LightGBM and XGBoost)" }, { "code": null, "e": 2344, "s": 2326, "text": "Regression models" }, { "code": null, "e": 2462, "s": 2344, "text": "PMML enables us to load a Machine Learning model, that was trained in Python, in Java, Go lang, C++, Ruby and others." }, { "code": null, "e": 2625, "s": 2462, "text": "My first thought after learning about PMML was that I would need to radically refactor the code, which would make retraining the model with XGBoost more feasible." }, { "code": null, "e": 2771, "s": 2625, "text": "After thinking about it, I decided to give PMML a try. It has a well-maintained repository with clear instructions β€” which is always a good sign." }, { "code": null, "e": 2817, "s": 2771, "text": "You can simply install the PMML package with:" }, { "code": null, "e": 2842, "s": 2817, "text": "pip install sklearn2pmml" }, { "code": null, "e": 3014, "s": 2842, "text": "sklearn2pmml package is needed to export the Python Machine Learning model to PMML format. Using it is simple, we just need to wrap the classifier with PMMLPipeline class." }, { "code": null, "e": 3150, "s": 3014, "text": "To make it easier for you, I wrote a simple gist that trains a LightGBM model on the Iris dataset and exports the model to PMML format:" }, { "code": null, "e": 3419, "s": 3150, "text": "Import required Python packagesLoad Iris datasetSplit Iris dataset to train and test setsTrain LightGBM model with PMML support β€” this is the only required change in your code.Measure classification accuracy of the model.And finally, save the model to the PMML format." }, { "code": null, "e": 3451, "s": 3419, "text": "Import required Python packages" }, { "code": null, "e": 3469, "s": 3451, "text": "Load Iris dataset" }, { "code": null, "e": 3511, "s": 3469, "text": "Split Iris dataset to train and test sets" }, { "code": null, "e": 3599, "s": 3511, "text": "Train LightGBM model with PMML support β€” this is the only required change in your code." }, { "code": null, "e": 3645, "s": 3599, "text": "Measure classification accuracy of the model." }, { "code": null, "e": 3693, "s": 3645, "text": "And finally, save the model to the PMML format." }, { "code": null, "e": 3818, "s": 3693, "text": "The code above creates a PMML file, which is an XML file. The XML contains all the model details as seen in the image below." }, { "code": null, "e": 3915, "s": 3818, "text": "We trained the model with Python and exported it to PMML format, now we need to load it in Java." }, { "code": null, "e": 4022, "s": 3915, "text": "I created a minimalistic repository LoadPMMLModel on Github, which shows how to load a PMML model in Java." }, { "code": null, "e": 4114, "s": 4022, "text": "The first step is to add a PMML dependency to pom.xml (I’m using maven dependency manager):" }, { "code": null, "e": 4234, "s": 4114, "text": "<dependency>\t<groupId>org.jpmml</groupId>\t<artifactId>pmml-evaluator</artifactId>\t<version>1.5.15</version></dependency" }, { "code": null, "e": 4323, "s": 4234, "text": "I saved the PMML file to the project’s resources folder so that compiler can package it." }, { "code": null, "e": 4370, "s": 4323, "text": "Then we need to specify the path to the model:" }, { "code": null, "e": 4552, "s": 4370, "text": "String modelFolder = LoadPMMLModel.class.getClassLoader().getResource(\"model\").getPath();String modelName = \"boosting_model.pmml\";Path modelPath = Paths.get(modelFolder, modelName);" }, { "code": null, "e": 4659, "s": 4552, "text": "Loading the model with PMML model is as simple as (the variable with the model in Java is Evaluator type):" }, { "code": null, "e": 4801, "s": 4659, "text": "Evaluator evaluator = new LoadingModelEvaluatorBuilder() .load(modelPath.toFile()) .build();evaluator.verify();" }, { "code": null, "e": 4857, "s": 4801, "text": "Now let’s make a few predictions with the loaded model." }, { "code": null, "e": 4927, "s": 4857, "text": "In Python, the prediction for the first sample in the test set was 1." }, { "code": null, "e": 4986, "s": 4927, "text": "Let’s use the same sample as above in Python, but in Java:" }, { "code": null, "e": 5521, "s": 4986, "text": "Map<String, Double> features = new HashMap<>();features.put(\"sepal length (cm)\", 6.1);features.put(\"sepal width (cm)\", 2.8);features.put(\"petal length (cm)\", 4.7);features.put(\"petal width (cm)\", 1.2);Map<FieldName, FieldValue> arguments = new LinkedHashMap<>();for (InputField inputField : inputFields) { FieldName inputName = inputField.getName(); Double value = features.get(inputName.toString()); FieldValue inputValue = inputField.prepare(value); arguments.put(inputName, inputValue);}" }, { "code": null, "e": 5565, "s": 5521, "text": "And query the model in Java for prediction:" }, { "code": null, "e": 5876, "s": 5565, "text": "Map<FieldName, ?> results = evaluator.evaluate(arguments);// Extracting predictionMap<String, ?> resultRecord = EvaluatorUtil.decodeAll(results);Integer yPred = (Integer) resultRecord.get(targetName.toString());System.out.printf(\"Prediction is %d\\n\", yPred);System.out.printf(\"PMML output %s\\n\", resultRecord);" }, { "code": null, "e": 5926, "s": 5876, "text": "With the code above, we get the following output:" }, { "code": null, "e": 6114, "s": 5926, "text": "In my Machine Learning learning project, I used a regression boosting model. To my surprise, the exported PMML model produced the same results to the fifth decimal as the model in Python." }, { "code": null, "e": 6194, "s": 6114, "text": "I don’t have anything bad to say about PMML as it works reliably in production." }, { "code": null, "e": 6309, "s": 6194, "text": "Remember, you don’t need to copy-paste the code from this article as I created LoadPMMLModel repository on Github." }, { "code": null, "e": 6363, "s": 6309, "text": "Please let me know what are your thoughts about PMML." } ]
How to change file extension in Python?
When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '.' and replace the last entry by the new extension you want. You can do this using the os.rename method. >>> import os >>> my_file = 'my_file.txt' >>> base = os.path.splitext(my_file)[0] >>> os.rename(my_file, base + '.bin') This will rename my_file.txt to my_file.bin
[ { "code": null, "e": 1321, "s": 1062, "text": "When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '.' and replace the last entry by the new extension you want. You can do this using the os.rename method. " }, { "code": null, "e": 1441, "s": 1321, "text": ">>> import os\n>>> my_file = 'my_file.txt'\n>>> base = os.path.splitext(my_file)[0]\n>>> os.rename(my_file, base + '.bin')" }, { "code": null, "e": 1485, "s": 1441, "text": "This will rename my_file.txt to my_file.bin" } ]
How to Create an Infinite Loop in Windows Batch File? - GeeksforGeeks
23 Mar, 2020 An infinite loop in Batch Script refers to the repetition of a command infinitely. The only way to stop an infinitely loop in Windows Batch Script is by either pressing Ctrl + C or by closing the program. Syntax: Suppose a variable β€˜a’ :a your command here goto a Here, you need to know how to create a batch file in windows. It is very simple. First, copy the code in a notepad file and save this file with .bat extension. To run or execute the file, double click on it or type the file name on cmd. Example 1: Let’s start by looping a simple command, such as β€˜echo’. β€˜echoβ€˜ commands is analogous to β€˜print’ command like in any other programming languages. Save the below code in a notepad file like sample.bat and double click on it to execute. @echo off :x echo Hello! My fellow GFG Members! goto x Output: To stop this infinite loop, press Ctrl + C and then press y and then Enter. Example 2: Suppose we want to loop the command β€˜tree’. β€˜tree’ command pulls and shows directory and file path in the form of a branching tree. @echo off REM turning off the echo-ing of the commands below color 0a REM changing font color to light green cd c:\ REM put the directory name of which you want the tree of in place of c :y REM you can add any other variable in place of y tree goto y Note: β€˜REM’ command is only used for typing comments in the batch script program, you can ignore them while typing the program. They are only put for the understanding of the program script and have no real use in the program. Here you can see the below option also. @echo off color 0a cd c:\ :y tree goto y Output: Batch-script TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Add External JAR File to an IntelliJ IDEA Project? How to Delete Temporary Files in Windows 10? How to Convert Kotlin Code to Java Code in Android Studio? How to Install Z Shell(zsh) on Linux? Difference between RUN vs CMD vs ENTRYPOINT Docker Commands How to Install Flutter on Windows? How to Access Localhost on Mobile Browsers? How to Clone Android Project from GitHub in Android Studio? Basic Linux Commands for day to day life How to Install Selenium WebDriver on MacOS?
[ { "code": null, "e": 24801, "s": 24773, "text": "\n23 Mar, 2020" }, { "code": null, "e": 25006, "s": 24801, "text": "An infinite loop in Batch Script refers to the repetition of a command infinitely. The only way to stop an infinitely loop in Windows Batch Script is by either pressing Ctrl + C or by closing the program." }, { "code": null, "e": 25037, "s": 25006, "text": "Syntax: Suppose a variable β€˜a’" }, { "code": null, "e": 25066, "s": 25037, "text": ":a\nyour command here\ngoto a\n" }, { "code": null, "e": 25303, "s": 25066, "text": "Here, you need to know how to create a batch file in windows. It is very simple. First, copy the code in a notepad file and save this file with .bat extension. To run or execute the file, double click on it or type the file name on cmd." }, { "code": null, "e": 25549, "s": 25303, "text": "Example 1: Let’s start by looping a simple command, such as β€˜echo’. β€˜echoβ€˜ commands is analogous to β€˜print’ command like in any other programming languages. Save the below code in a notepad file like sample.bat and double click on it to execute." }, { "code": null, "e": 25605, "s": 25549, "text": "@echo off\n:x\necho Hello! My fellow GFG Members!\ngoto x\n" }, { "code": null, "e": 25613, "s": 25605, "text": "Output:" }, { "code": null, "e": 25689, "s": 25613, "text": "To stop this infinite loop, press Ctrl + C and then press y and then Enter." }, { "code": null, "e": 25832, "s": 25689, "text": "Example 2: Suppose we want to loop the command β€˜tree’. β€˜tree’ command pulls and shows directory and file path in the form of a branching tree." }, { "code": null, "e": 26085, "s": 25832, "text": "@echo off REM turning off the echo-ing of the commands below\ncolor 0a REM changing font color to light green\ncd c:\\ REM put the directory name of which you want the tree of in place of c\n:y REM you can add any other variable in place of y\ntree \ngoto y\n" }, { "code": null, "e": 26352, "s": 26085, "text": "Note: β€˜REM’ command is only used for typing comments in the batch script program, you can ignore them while typing the program. They are only put for the understanding of the program script and have no real use in the program. Here you can see the below option also." }, { "code": null, "e": 26399, "s": 26352, "text": "@echo off \ncolor 0a \ncd c:\\ \n:y \ntree \ngoto y\n" }, { "code": null, "e": 26407, "s": 26399, "text": "Output:" }, { "code": null, "e": 26420, "s": 26407, "text": "Batch-script" }, { "code": null, "e": 26429, "s": 26420, "text": "TechTips" }, { "code": null, "e": 26527, "s": 26429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26536, "s": 26527, "text": "Comments" }, { "code": null, "e": 26549, "s": 26536, "text": "Old Comments" }, { "code": null, "e": 26607, "s": 26549, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26652, "s": 26607, "text": "How to Delete Temporary Files in Windows 10?" }, { "code": null, "e": 26711, "s": 26652, "text": "How to Convert Kotlin Code to Java Code in Android Studio?" }, { "code": null, "e": 26749, "s": 26711, "text": "How to Install Z Shell(zsh) on Linux?" }, { "code": null, "e": 26809, "s": 26749, "text": "Difference between RUN vs CMD vs ENTRYPOINT Docker Commands" }, { "code": null, "e": 26844, "s": 26809, "text": "How to Install Flutter on Windows?" }, { "code": null, "e": 26888, "s": 26844, "text": "How to Access Localhost on Mobile Browsers?" }, { "code": null, "e": 26948, "s": 26888, "text": "How to Clone Android Project from GitHub in Android Studio?" }, { "code": null, "e": 26989, "s": 26948, "text": "Basic Linux Commands for day to day life" } ]
Broken Pipe Error in Python - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss Pipe Error in python starting from how an error is occurred in python along with the type of solution needed to be followed to rectify the error in python. So, let’s go into this article to understand the concept well. With the advancement of emerging technologies in the IT sector, the use of programming language is playing a vital role. Thus the proper language is considered for the fast executions of the functions. In such a case, Python emerges as the most important language to satisfy the needs of the current problem execution because of its simplicity and availability of various libraries. But along with the execution, the errors during the execution also comes into existence and it becomes difficult for the programmers to rectify the errors for the processing of the problem. A broken Pipe Error is generally an Input/Output Error, which is occurred at the Linux System level. The error has occurred during the reading and writing of the files and it mainly occurs during the operations of the files. The same error that occurred in the Linux system is EPIPE, but every library function which returns its error code also generates a signal called SIGPIPE, this signal is used to terminate the program if it is not handled or blocked. Thus a program will never be able to see the EPIPE error unless it has handled or blocked SIGPIPE. Python interpreter is not capable enough to ignore SIGPIPE by default, instead, it converts this signal into an exception and raises an error which is known as IOError(INPUT/OUTPUT error) also know as β€˜Error 32’ or Broken Pipe Error. python <filename>.py | head This pipeline code written above will create a process that will send the data upstream and a process that reads the data downstream. But when the downstream process will not be able to read the data upstream, it will raise an exception by sending SIGPIPE signal to the upstream process. Thus upstream process in a python problem will raise an error such as IOError: Broken pipe error will occur. Example: Python3 for i in range(4000): print(i) When we run this file from unix commands: python3 main.py | head -n3000 Approach 1: To avoid the error we need to make the terminal run the code efficiently without catching the SIGPIPE signal, so for these, we can add the below code at the top of the python program. from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) Python3 from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) for i in range(4000): print(i) Output: 0 1 20 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 Explanation: The above code which is placed on the top of the python code is used to redirect the SIGPIPE signals to the default SIG_DFL signal, which the system generally ignores so that the rest part of the code can be executed seamlessly. But Approach 11 is not effective because in the Python manual on the signal library, which is mentioned that this type of signal handling should be avoided and should not be practiced in any part of the code. So for this reason we will go for the second approach. Approach 2: We can handle this type of error by using the functionality of try/catch block which is already approved by the python manual and is advised to follow such procedure to handle the errors. import sys, errno try: # INPUT/OUTPUT operation # except IOError as e: if e.errno == errno.EPIPE: # Handling of the error Example: Python3 import sysimport errno try: for i in range(4000): print(i)except IOError as e: if e.errno == errno.EPIPE: pass # Handling of the error Output: 0 1 2 3 4 5 6 7 8 9 Explanation: In the above piece of code, we have used the built-in library of python which is the Sys and Errno module, and use the try/catch block in order to catch the raised SIGPIPE exception and handle it before it stops the program execution. Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24465, "s": 24212, "text": "In this article, we will discuss Pipe Error in python starting from how an error is occurred in python along with the type of solution needed to be followed to rectify the error in python. So, let’s go into this article to understand the concept well. " }, { "code": null, "e": 25038, "s": 24465, "text": "With the advancement of emerging technologies in the IT sector, the use of programming language is playing a vital role. Thus the proper language is considered for the fast executions of the functions. In such a case, Python emerges as the most important language to satisfy the needs of the current problem execution because of its simplicity and availability of various libraries. But along with the execution, the errors during the execution also comes into existence and it becomes difficult for the programmers to rectify the errors for the processing of the problem." }, { "code": null, "e": 25595, "s": 25038, "text": "A broken Pipe Error is generally an Input/Output Error, which is occurred at the Linux System level. The error has occurred during the reading and writing of the files and it mainly occurs during the operations of the files. The same error that occurred in the Linux system is EPIPE, but every library function which returns its error code also generates a signal called SIGPIPE, this signal is used to terminate the program if it is not handled or blocked. Thus a program will never be able to see the EPIPE error unless it has handled or blocked SIGPIPE." }, { "code": null, "e": 25829, "s": 25595, "text": "Python interpreter is not capable enough to ignore SIGPIPE by default, instead, it converts this signal into an exception and raises an error which is known as IOError(INPUT/OUTPUT error) also know as β€˜Error 32’ or Broken Pipe Error." }, { "code": null, "e": 25857, "s": 25829, "text": "python <filename>.py | head" }, { "code": null, "e": 26254, "s": 25857, "text": "This pipeline code written above will create a process that will send the data upstream and a process that reads the data downstream. But when the downstream process will not be able to read the data upstream, it will raise an exception by sending SIGPIPE signal to the upstream process. Thus upstream process in a python problem will raise an error such as IOError: Broken pipe error will occur." }, { "code": null, "e": 26263, "s": 26254, "text": "Example:" }, { "code": null, "e": 26271, "s": 26263, "text": "Python3" }, { "code": "for i in range(4000): print(i)", "e": 26305, "s": 26271, "text": null }, { "code": null, "e": 26347, "s": 26305, "text": "When we run this file from unix commands:" }, { "code": null, "e": 26377, "s": 26347, "text": "python3 main.py | head -n3000" }, { "code": null, "e": 26573, "s": 26377, "text": "Approach 1: To avoid the error we need to make the terminal run the code efficiently without catching the SIGPIPE signal, so for these, we can add the below code at the top of the python program." }, { "code": null, "e": 26644, "s": 26573, "text": "from signal import signal, SIGPIPE, SIG_DFL \nsignal(SIGPIPE,SIG_DFL) " }, { "code": null, "e": 26652, "s": 26644, "text": "Python3" }, { "code": "from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) for i in range(4000): print(i)", "e": 26756, "s": 26652, "text": null }, { "code": null, "e": 26764, "s": 26756, "text": "Output:" }, { "code": null, "e": 26803, "s": 26764, "text": "0\n1\n20\n1\n2\n3\n4\n5\n6\n7\n8\n9\n3\n4\n5\n6\n7\n8\n9" }, { "code": null, "e": 26816, "s": 26803, "text": "Explanation:" }, { "code": null, "e": 27309, "s": 26816, "text": "The above code which is placed on the top of the python code is used to redirect the SIGPIPE signals to the default SIG_DFL signal, which the system generally ignores so that the rest part of the code can be executed seamlessly. But Approach 11 is not effective because in the Python manual on the signal library, which is mentioned that this type of signal handling should be avoided and should not be practiced in any part of the code. So for this reason we will go for the second approach." }, { "code": null, "e": 27509, "s": 27309, "text": "Approach 2: We can handle this type of error by using the functionality of try/catch block which is already approved by the python manual and is advised to follow such procedure to handle the errors." }, { "code": null, "e": 27654, "s": 27509, "text": "import sys, errno \ntry: \n # INPUT/OUTPUT operation #\nexcept IOError as e: \n if e.errno == errno.EPIPE: \n # Handling of the error " }, { "code": null, "e": 27663, "s": 27654, "text": "Example:" }, { "code": null, "e": 27671, "s": 27663, "text": "Python3" }, { "code": "import sysimport errno try: for i in range(4000): print(i)except IOError as e: if e.errno == errno.EPIPE: pass # Handling of the error", "e": 27831, "s": 27671, "text": null }, { "code": null, "e": 27839, "s": 27831, "text": "Output:" }, { "code": null, "e": 27859, "s": 27839, "text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9" }, { "code": null, "e": 27872, "s": 27859, "text": "Explanation:" }, { "code": null, "e": 28107, "s": 27872, "text": "In the above piece of code, we have used the built-in library of python which is the Sys and Errno module, and use the try/catch block in order to catch the raised SIGPIPE exception and handle it before it stops the program execution." }, { "code": null, "e": 28125, "s": 28107, "text": "Python-exceptions" }, { "code": null, "e": 28132, "s": 28125, "text": "Python" }, { "code": null, "e": 28230, "s": 28132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28239, "s": 28230, "text": "Comments" }, { "code": null, "e": 28252, "s": 28239, "text": "Old Comments" }, { "code": null, "e": 28273, "s": 28252, "text": "Python OOPs Concepts" }, { "code": null, "e": 28305, "s": 28273, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28328, "s": 28305, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 28350, "s": 28328, "text": "Defaultdict in Python" }, { "code": null, "e": 28377, "s": 28350, "text": "Python Classes and Objects" }, { "code": null, "e": 28393, "s": 28377, "text": "Deque in Python" }, { "code": null, "e": 28435, "s": 28393, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28491, "s": 28435, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28536, "s": 28491, "text": "Python - Ways to remove duplicates from list" } ]
Hadoop - Enviornment Setup
Hadoop is supported by GNU/Linux platform and its flavors. Therefore, we have to install a Linux operating system for setting up Hadoop environment. In case you have an OS other than Linux, you can install a Virtualbox software in it and have Linux inside the Virtualbox. Before installing Hadoop into the Linux environment, we need to set up Linux using ssh (Secure Shell). Follow the steps given below for setting up the Linux environment. At the beginning, it is recommended to create a separate user for Hadoop to isolate Hadoop file system from Unix file system. Follow the steps given below to create a user βˆ’ Open the root using the command β€œsu”. Open the root using the command β€œsu”. Create a user from the root account using the command β€œuseradd username”. Create a user from the root account using the command β€œuseradd username”. Now you can open an existing user account using the command β€œsu username”. Now you can open an existing user account using the command β€œsu username”. Open the Linux terminal and type the following commands to create a user. $ su password: # useradd hadoop # passwd hadoop New passwd: Retype new passwd SSH setup is required to do different operations on a cluster such as starting, stopping, distributed daemon shell operations. To authenticate different users of Hadoop, it is required to provide public/private key pair for a Hadoop user and share it with different users. The following commands are used for generating a key value pair using SSH. Copy the public keys form id_rsa.pub to authorized_keys, and provide the owner with read and write permissions to authorized_keys file respectively. $ ssh-keygen -t rsa $ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys $ chmod 0600 ~/.ssh/authorized_keys Java is the main prerequisite for Hadoop. First of all, you should verify the existence of java in your system using the command β€œjava -version”. The syntax of java version command is given below. $ java -version If everything is in order, it will give you the following output. java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b13) Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode) If java is not installed in your system, then follow the steps given below for installing java. Download java (JDK <latest version> - X64.tar.gz) by visiting the following link www.oracle.com Then jdk-7u71-linux-x64.tar.gz will be downloaded into your system. Generally you will find the downloaded java file in Downloads folder. Verify it and extract the jdk-7u71-linux-x64.gz file using the following commands. $ cd Downloads/ $ ls jdk-7u71-linux-x64.gz $ tar zxf jdk-7u71-linux-x64.gz $ ls jdk1.7.0_71 jdk-7u71-linux-x64.gz To make java available to all the users, you have to move it to the location β€œ/usr/local/”. Open root, and type the following commands. $ su password: # mv jdk1.7.0_71 /usr/local/ # exit For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file. export JAVA_HOME=/usr/local/jdk1.7.0_71 export PATH=$PATH:$JAVA_HOME/bin Now apply all the changes into the current running system. $ source ~/.bashrc Use the following commands to configure java alternatives βˆ’ # alternatives --install /usr/bin/java java usr/local/java/bin/java 2 # alternatives --install /usr/bin/javac javac usr/local/java/bin/javac 2 # alternatives --install /usr/bin/jar jar usr/local/java/bin/jar 2 # alternatives --set java usr/local/java/bin/java # alternatives --set javac usr/local/java/bin/javac # alternatives --set jar usr/local/java/bin/jar Now verify the java -version command from the terminal as explained above. Download and extract Hadoop 2.4.1 from Apache software foundation using the following commands. $ su password: # cd /usr/local # wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/ hadoop-2.4.1.tar.gz # tar xzf hadoop-2.4.1.tar.gz # mv hadoop-2.4.1/* to hadoop/ # exit Once you have downloaded Hadoop, you can operate your Hadoop cluster in one of the three supported modes βˆ’ Local/Standalone Mode βˆ’ After downloading Hadoop in your system, by default, it is configured in a standalone mode and can be run as a single java process. Local/Standalone Mode βˆ’ After downloading Hadoop in your system, by default, it is configured in a standalone mode and can be run as a single java process. Pseudo Distributed Mode βˆ’ It is a distributed simulation on single machine. Each Hadoop daemon such as hdfs, yarn, MapReduce etc., will run as a separate java process. This mode is useful for development. Pseudo Distributed Mode βˆ’ It is a distributed simulation on single machine. Each Hadoop daemon such as hdfs, yarn, MapReduce etc., will run as a separate java process. This mode is useful for development. Fully Distributed Mode βˆ’ This mode is fully distributed with minimum two or more machines as a cluster. We will come across this mode in detail in the coming chapters. Fully Distributed Mode βˆ’ This mode is fully distributed with minimum two or more machines as a cluster. We will come across this mode in detail in the coming chapters. Here we will discuss the installation of Hadoop 2.4.1 in standalone mode. There are no daemons running and everything runs in a single JVM. Standalone mode is suitable for running MapReduce programs during development, since it is easy to test and debug them. You can set Hadoop environment variables by appending the following commands to ~/.bashrc file. export HADOOP_HOME=/usr/local/hadoop Before proceeding further, you need to make sure that Hadoop is working fine. Just issue the following command βˆ’ $ hadoop version If everything is fine with your setup, then you should see the following result βˆ’ Hadoop 2.4.1 Subversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768 Compiled by hortonmu on 2013-10-07T06:28Z Compiled with protoc 2.5.0 From source with checksum 79e53ce7994d1628b240f09af91e1af4 It means your Hadoop's standalone mode setup is working fine. By default, Hadoop is configured to run in a non-distributed mode on a single machine. Let's check a simple example of Hadoop. Hadoop installation delivers the following example MapReduce jar file, which provides basic functionality of MapReduce and can be used for calculating, like Pi value, word counts in a given list of files, etc. $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.2.0.jar Let's have an input directory where we will push a few files and our requirement is to count the total number of words in those files. To calculate the total number of words, we do not need to write our MapReduce, provided the .jar file contains the implementation for word count. You can try other examples using the same .jar file; just issue the following commands to check supported MapReduce functional programs by hadoop-mapreduce-examples-2.2.0.jar file. $ hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduceexamples-2.2.0.jar Create temporary content files in the input directory. You can create this input directory anywhere you would like to work. $ mkdir input $ cp $HADOOP_HOME/*.txt input $ ls -l input It will give the following files in your input directory βˆ’ total 24 -rw-r--r-- 1 root root 15164 Feb 21 10:14 LICENSE.txt -rw-r--r-- 1 root root 101 Feb 21 10:14 NOTICE.txt -rw-r--r-- 1 root root 1366 Feb 21 10:14 README.txt These files have been copied from the Hadoop installation home directory. For your experiment, you can have different and large sets of files. Let's start the Hadoop process to count the total number of words in all the files available in the input directory, as follows βˆ’ $ hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduceexamples-2.2.0.jar wordcount input output Step-2 will do the required processing and save the output in output/part-r00000 file, which you can check by using βˆ’ $cat output/* It will list down all the words along with their total counts available in all the files available in the input directory. "AS 4 "Contribution" 1 "Contributor" 1 "Derivative 1 "Legal 1 "License" 1 "License"); 1 "Licensor" 1 "NOTICE” 1 "Not 1 "Object" 1 "Source” 1 "Work” 1 "You" 1 "Your") 1 "[]" 1 "control" 1 "printed 1 "submitted" 1 (50%) 1 (BIS), 1 (C) 1 (Don't) 1 (ECCN) 1 (INCLUDING 2 (INCLUDING, 2 ............. Follow the steps given below to install Hadoop 2.4.1 in pseudo distributed mode. You can set Hadoop environment variables by appending the following commands to ~/.bashrc file. export HADOOP_HOME=/usr/local/hadoop export HADOOP_MAPRED_HOME=$HADOOP_HOME export HADOOP_COMMON_HOME=$HADOOP_HOME export HADOOP_HDFS_HOME=$HADOOP_HOME export YARN_HOME=$HADOOP_HOME export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin export HADOOP_INSTALL=$HADOOP_HOME Now apply all the changes into the current running system. $ source ~/.bashrc You can find all the Hadoop configuration files in the location β€œ$HADOOP_HOME/etc/hadoop”. It is required to make changes in those configuration files according to your Hadoop infrastructure. $ cd $HADOOP_HOME/etc/hadoop In order to develop Hadoop programs in java, you have to reset the java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of java in your system. export JAVA_HOME=/usr/local/jdk1.7.0_71 The following are the list of files that you have to edit to configure Hadoop. core-site.xml The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and size of Read/Write buffers. Open the core-site.xml and add the following properties in between <configuration>, </configuration> tags. <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> </configuration> hdfs-site.xml The hdfs-site.xml file contains information such as the value of replication data, namenode path, and datanode paths of your local file systems. It means the place where you want to store the Hadoop infrastructure. Let us assume the following data. dfs.replication (data replication value) = 1 (In the below given path /hadoop/ is the user name. hadoopinfra/hdfs/namenode is the directory created by hdfs file system.) namenode path = //home/hadoop/hadoopinfra/hdfs/namenode (hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) datanode path = //home/hadoop/hadoopinfra/hdfs/datanode Open this file and add the following properties in between the <configuration> </configuration> tags in this file. <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.name.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/namenode </value> </property> <property> <name>dfs.data.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value> </property> </configuration> Note βˆ’ In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure. yarn-site.xml This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file. <configuration> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> </configuration> mapred-site.xml This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, it is required to copy the file from mapred-site.xml.template to mapred-site.xml file using the following command. $ cp mapred-site.xml.template mapred-site.xml Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration>tags in this file. <configuration> <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> </configuration> The following steps are used to verify the Hadoop installation. Set up the namenode using the command β€œhdfs namenode -format” as follows. $ cd ~ $ hdfs namenode -format The expected result is as follows. 10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = localhost/192.168.1.11 STARTUP_MSG: args = [-format] STARTUP_MSG: version = 2.4.1 ... ... 10/24/14 21:30:56 INFO common.Storage: Storage directory /home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. 10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1 images with txid >= 0 10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 ************************************************************/ The following command is used to start dfs. Executing this command will start your Hadoop file system. $ start-dfs.sh The expected output is as follows βˆ’ 10/24/14 21:37:56 Starting namenodes on [localhost] localhost: starting namenode, logging to /home/hadoop/hadoop 2.4.1/logs/hadoop-hadoop-namenode-localhost.out localhost: starting datanode, logging to /home/hadoop/hadoop 2.4.1/logs/hadoop-hadoop-datanode-localhost.out Starting secondary namenodes [0.0.0.0] The following command is used to start the yarn script. Executing this command will start your yarn daemons. $ start-yarn.sh The expected output as follows βˆ’ starting yarn daemons starting resourcemanager, logging to /home/hadoop/hadoop 2.4.1/logs/yarn-hadoop-resourcemanager-localhost.out localhost: starting nodemanager, logging to /home/hadoop/hadoop 2.4.1/logs/yarn-hadoop-nodemanager-localhost.out The default port number to access Hadoop is 50070. Use the following url to get Hadoop services on browser. http://localhost:50070/ The default port number to access all applications of cluster is 8088. Use the following url to visit this service. http://localhost:8088/ 39 Lectures 2.5 hours Arnab Chakraborty 65 Lectures 6 hours Arnab Chakraborty 12 Lectures 1 hours Pranjal Srivastava 24 Lectures 6.5 hours Pari Margu 89 Lectures 11.5 hours TELCOMA Global 43 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 1851, "text": "Hadoop is supported by GNU/Linux platform and its flavors. Therefore, we have to install a Linux operating system for setting up Hadoop environment. In case you have an OS other than Linux, you can install a Virtualbox software in it and have Linux inside the Virtualbox." }, { "code": null, "e": 2293, "s": 2123, "text": "Before installing Hadoop into the Linux environment, we need to set up Linux using ssh (Secure Shell). Follow the steps given below for setting up the Linux environment." }, { "code": null, "e": 2467, "s": 2293, "text": "At the beginning, it is recommended to create a separate user for Hadoop to isolate Hadoop file system from Unix file system. Follow the steps given below to create a user βˆ’" }, { "code": null, "e": 2505, "s": 2467, "text": "Open the root using the command β€œsu”." }, { "code": null, "e": 2543, "s": 2505, "text": "Open the root using the command β€œsu”." }, { "code": null, "e": 2617, "s": 2543, "text": "Create a user from the root account using the command β€œuseradd username”." }, { "code": null, "e": 2691, "s": 2617, "text": "Create a user from the root account using the command β€œuseradd username”." }, { "code": null, "e": 2767, "s": 2691, "text": "Now you can open an existing user account using the command β€œsu username”. " }, { "code": null, "e": 2843, "s": 2767, "text": "Now you can open an existing user account using the command β€œsu username”. " }, { "code": null, "e": 2917, "s": 2843, "text": "Open the Linux terminal and type the following commands to create a user." }, { "code": null, "e": 3011, "s": 2917, "text": "$ su \n password: \n# useradd hadoop \n# passwd hadoop \n New passwd: \n Retype new passwd \n" }, { "code": null, "e": 3284, "s": 3011, "text": "SSH setup is required to do different operations on a cluster such as starting, stopping, distributed daemon shell operations. To authenticate different users of Hadoop, it is required to provide public/private key pair for a Hadoop user and share it with different users." }, { "code": null, "e": 3508, "s": 3284, "text": "The following commands are used for generating a key value pair using SSH. Copy the public keys form id_rsa.pub to authorized_keys, and provide the owner with read and write permissions to authorized_keys file respectively." }, { "code": null, "e": 3618, "s": 3508, "text": "$ ssh-keygen -t rsa \n$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys \n$ chmod 0600 ~/.ssh/authorized_keys \n" }, { "code": null, "e": 3815, "s": 3618, "text": "Java is the main prerequisite for Hadoop. First of all, you should verify the existence of java in your system using the command β€œjava -version”. The syntax of java version command is given below." }, { "code": null, "e": 3833, "s": 3815, "text": "$ java -version \n" }, { "code": null, "e": 3899, "s": 3833, "text": "If everything is in order, it will give you the following output." }, { "code": null, "e": 4037, "s": 3899, "text": "java version \"1.7.0_71\" \nJava(TM) SE Runtime Environment (build 1.7.0_71-b13) \nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode) \n" }, { "code": null, "e": 4133, "s": 4037, "text": "If java is not installed in your system, then follow the steps given below for installing java." }, { "code": null, "e": 4229, "s": 4133, "text": "Download java (JDK <latest version> - X64.tar.gz) by visiting the following link www.oracle.com" }, { "code": null, "e": 4298, "s": 4229, "text": "Then jdk-7u71-linux-x64.tar.gz will be downloaded into your system. " }, { "code": null, "e": 4451, "s": 4298, "text": "Generally you will find the downloaded java file in Downloads folder. Verify it and extract the jdk-7u71-linux-x64.gz file using the following commands." }, { "code": null, "e": 4575, "s": 4451, "text": "$ cd Downloads/ \n$ ls \njdk-7u71-linux-x64.gz \n\n$ tar zxf jdk-7u71-linux-x64.gz \n$ ls \njdk1.7.0_71 jdk-7u71-linux-x64.gz \n" }, { "code": null, "e": 4711, "s": 4575, "text": "To make java available to all the users, you have to move it to the location β€œ/usr/local/”. Open root, and type the following commands." }, { "code": null, "e": 4767, "s": 4711, "text": "$ su \npassword: \n# mv jdk1.7.0_71 /usr/local/ \n# exit \n" }, { "code": null, "e": 4858, "s": 4767, "text": "For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file." }, { "code": null, "e": 4934, "s": 4858, "text": "export JAVA_HOME=/usr/local/jdk1.7.0_71 \nexport PATH=$PATH:$JAVA_HOME/bin \n" }, { "code": null, "e": 4993, "s": 4934, "text": "Now apply all the changes into the current running system." }, { "code": null, "e": 5013, "s": 4993, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 5073, "s": 5013, "text": "Use the following commands to configure java alternatives βˆ’" }, { "code": null, "e": 5435, "s": 5073, "text": "# alternatives --install /usr/bin/java java usr/local/java/bin/java 2\n# alternatives --install /usr/bin/javac javac usr/local/java/bin/javac 2\n# alternatives --install /usr/bin/jar jar usr/local/java/bin/jar 2\n\n# alternatives --set java usr/local/java/bin/java\n# alternatives --set javac usr/local/java/bin/javac\n# alternatives --set jar usr/local/java/bin/jar\n" }, { "code": null, "e": 5510, "s": 5435, "text": "Now verify the java -version command from the terminal as explained above." }, { "code": null, "e": 5606, "s": 5510, "text": "Download and extract Hadoop 2.4.1 from Apache software foundation using the following commands." }, { "code": null, "e": 5792, "s": 5606, "text": "$ su \npassword: \n# cd /usr/local \n# wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/ \nhadoop-2.4.1.tar.gz \n# tar xzf hadoop-2.4.1.tar.gz \n# mv hadoop-2.4.1/* to hadoop/ \n# exit \n" }, { "code": null, "e": 5899, "s": 5792, "text": "Once you have downloaded Hadoop, you can operate your Hadoop cluster in one of the three supported modes βˆ’" }, { "code": null, "e": 6055, "s": 5899, "text": "Local/Standalone Mode βˆ’ After downloading Hadoop in your system, by default, it is configured in a standalone mode and can be run as a single java process." }, { "code": null, "e": 6211, "s": 6055, "text": "Local/Standalone Mode βˆ’ After downloading Hadoop in your system, by default, it is configured in a standalone mode and can be run as a single java process." }, { "code": null, "e": 6416, "s": 6211, "text": "Pseudo Distributed Mode βˆ’ It is a distributed simulation on single machine. Each Hadoop daemon such as hdfs, yarn, MapReduce etc., will run as a separate java process. This mode is useful for development." }, { "code": null, "e": 6621, "s": 6416, "text": "Pseudo Distributed Mode βˆ’ It is a distributed simulation on single machine. Each Hadoop daemon such as hdfs, yarn, MapReduce etc., will run as a separate java process. This mode is useful for development." }, { "code": null, "e": 6789, "s": 6621, "text": "Fully Distributed Mode βˆ’ This mode is fully distributed with minimum two or more machines as a cluster. We will come across this mode in detail in the coming chapters." }, { "code": null, "e": 6957, "s": 6789, "text": "Fully Distributed Mode βˆ’ This mode is fully distributed with minimum two or more machines as a cluster. We will come across this mode in detail in the coming chapters." }, { "code": null, "e": 7031, "s": 6957, "text": "Here we will discuss the installation of Hadoop 2.4.1 in standalone mode." }, { "code": null, "e": 7217, "s": 7031, "text": "There are no daemons running and everything runs in a single JVM. Standalone mode is suitable for running MapReduce programs during development, since it is easy to test and debug them." }, { "code": null, "e": 7313, "s": 7217, "text": "You can set Hadoop environment variables by appending the following commands to ~/.bashrc file." }, { "code": null, "e": 7352, "s": 7313, "text": "export HADOOP_HOME=/usr/local/hadoop \n" }, { "code": null, "e": 7465, "s": 7352, "text": "Before proceeding further, you need to make sure that Hadoop is working fine. Just issue the following command βˆ’" }, { "code": null, "e": 7484, "s": 7465, "text": "$ hadoop version \n" }, { "code": null, "e": 7566, "s": 7484, "text": "If everything is fine with your setup, then you should see the following result βˆ’" }, { "code": null, "e": 7781, "s": 7566, "text": "Hadoop 2.4.1 \nSubversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768 \nCompiled by hortonmu on 2013-10-07T06:28Z \nCompiled with protoc 2.5.0\nFrom source with checksum 79e53ce7994d1628b240f09af91e1af4 \n" }, { "code": null, "e": 7930, "s": 7781, "text": "It means your Hadoop's standalone mode setup is working fine. By default, Hadoop is configured to run in a non-distributed mode on a single machine." }, { "code": null, "e": 8180, "s": 7930, "text": "Let's check a simple example of Hadoop. Hadoop installation delivers the following example MapReduce jar file, which provides basic functionality of MapReduce and can be used for calculating, like Pi value, word counts in a given list of files, etc." }, { "code": null, "e": 8254, "s": 8180, "text": "$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.2.0.jar \n" }, { "code": null, "e": 8716, "s": 8254, "text": "Let's have an input directory where we will push a few files and our requirement is to count the total number of words in those files. To calculate the total number of words, we do not need to write our MapReduce, provided the .jar file contains the implementation for word count. You can try other examples using the same .jar file; just issue the following commands to check supported MapReduce functional programs by hadoop-mapreduce-examples-2.2.0.jar file." }, { "code": null, "e": 8802, "s": 8716, "text": "$ hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduceexamples-2.2.0.jar \n" }, { "code": null, "e": 8926, "s": 8802, "text": "Create temporary content files in the input directory. You can create this input directory anywhere you would like to work." }, { "code": null, "e": 8988, "s": 8926, "text": "$ mkdir input \n$ cp $HADOOP_HOME/*.txt input \n$ ls -l input \n" }, { "code": null, "e": 9047, "s": 8988, "text": "It will give the following files in your input directory βˆ’" }, { "code": null, "e": 9220, "s": 9047, "text": "total 24 \n-rw-r--r-- 1 root root 15164 Feb 21 10:14 LICENSE.txt \n-rw-r--r-- 1 root root 101 Feb 21 10:14 NOTICE.txt\n-rw-r--r-- 1 root root 1366 Feb 21 10:14 README.txt \n" }, { "code": null, "e": 9363, "s": 9220, "text": "These files have been copied from the Hadoop installation home directory. For your experiment, you can have different and large sets of files." }, { "code": null, "e": 9493, "s": 9363, "text": "Let's start the Hadoop process to count the total number of words in all the files available in the input directory, as follows βˆ’" }, { "code": null, "e": 9603, "s": 9493, "text": "$ hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduceexamples-2.2.0.jar wordcount input output \n" }, { "code": null, "e": 9721, "s": 9603, "text": "Step-2 will do the required processing and save the output in output/part-r00000 file, which you can check by using βˆ’" }, { "code": null, "e": 9737, "s": 9721, "text": "$cat output/* \n" }, { "code": null, "e": 9860, "s": 9737, "text": "It will list down all the words along with their total counts available in all the files available in the input directory." }, { "code": null, "e": 10281, "s": 9860, "text": "\"AS 4 \n\"Contribution\" 1 \n\"Contributor\" 1 \n\"Derivative 1\n\"Legal 1\n\"License\" 1\n\"License\"); 1 \n\"Licensor\" 1\n\"NOTICE” 1 \n\"Not 1 \n\"Object\" 1 \n\"Source” 1 \n\"Work” 1 \n\"You\" 1 \n\"Your\") 1 \n\"[]\" 1 \n\"control\" 1 \n\"printed 1 \n\"submitted\" 1 \n(50%) 1 \n(BIS), 1 \n(C) 1 \n(Don't) 1 \n(ECCN) 1 \n(INCLUDING 2 \n(INCLUDING, 2 \n.............\n" }, { "code": null, "e": 10362, "s": 10281, "text": "Follow the steps given below to install Hadoop 2.4.1 in pseudo distributed mode." }, { "code": null, "e": 10458, "s": 10362, "text": "You can set Hadoop environment variables by appending the following commands to ~/.bashrc file." }, { "code": null, "e": 10798, "s": 10458, "text": "export HADOOP_HOME=/usr/local/hadoop \nexport HADOOP_MAPRED_HOME=$HADOOP_HOME \nexport HADOOP_COMMON_HOME=$HADOOP_HOME \n\nexport HADOOP_HDFS_HOME=$HADOOP_HOME \nexport YARN_HOME=$HADOOP_HOME \nexport HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native \nexport PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin \nexport HADOOP_INSTALL=$HADOOP_HOME \n" }, { "code": null, "e": 10857, "s": 10798, "text": "Now apply all the changes into the current running system." }, { "code": null, "e": 10878, "s": 10857, "text": "$ source ~/.bashrc \n" }, { "code": null, "e": 11070, "s": 10878, "text": "You can find all the Hadoop configuration files in the location β€œ$HADOOP_HOME/etc/hadoop”. It is required to make changes in those configuration files according to your Hadoop infrastructure." }, { "code": null, "e": 11100, "s": 11070, "text": "$ cd $HADOOP_HOME/etc/hadoop\n" }, { "code": null, "e": 11287, "s": 11100, "text": "In order to develop Hadoop programs in java, you have to reset the java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of java in your system." }, { "code": null, "e": 11328, "s": 11287, "text": "export JAVA_HOME=/usr/local/jdk1.7.0_71\n" }, { "code": null, "e": 11408, "s": 11328, "text": "The following are the list of files that you have to edit to configure Hadoop. " }, { "code": null, "e": 11422, "s": 11408, "text": "core-site.xml" }, { "code": null, "e": 11621, "s": 11422, "text": "The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and size of Read/Write buffers." }, { "code": null, "e": 11728, "s": 11621, "text": "Open the core-site.xml and add the following properties in between <configuration>, </configuration> tags." }, { "code": null, "e": 11870, "s": 11728, "text": "<configuration>\n <property>\n <name>fs.default.name</name>\n <value>hdfs://localhost:9000</value> \n </property>\n</configuration>\n" }, { "code": null, "e": 11884, "s": 11870, "text": "hdfs-site.xml" }, { "code": null, "e": 12099, "s": 11884, "text": "The hdfs-site.xml file contains information such as the value of replication data, namenode path, and datanode paths of your local file systems. It means the place where you want to store the Hadoop infrastructure." }, { "code": null, "e": 12133, "s": 12099, "text": "Let us assume the following data." }, { "code": null, "e": 12498, "s": 12133, "text": "dfs.replication (data replication value) = 1 \n\n(In the below given path /hadoop/ is the user name. \nhadoopinfra/hdfs/namenode is the directory created by hdfs file system.) \nnamenode path = //home/hadoop/hadoopinfra/hdfs/namenode \n\n(hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) \ndatanode path = //home/hadoop/hadoopinfra/hdfs/datanode \n" }, { "code": null, "e": 12613, "s": 12498, "text": "Open this file and add the following properties in between the <configuration> </configuration> tags in this file." }, { "code": null, "e": 13004, "s": 12613, "text": "<configuration>\n <property>\n <name>dfs.replication</name>\n <value>1</value>\n </property>\n \n <property>\n <name>dfs.name.dir</name>\n <value>file:///home/hadoop/hadoopinfra/hdfs/namenode </value>\n </property>\n \n <property>\n <name>dfs.data.dir</name> \n <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value> \n </property>\n</configuration>\n" }, { "code": null, "e": 13137, "s": 13004, "text": "Note βˆ’ In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure." }, { "code": null, "e": 13151, "s": 13137, "text": "yarn-site.xml" }, { "code": null, "e": 13329, "s": 13151, "text": "This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file." }, { "code": null, "e": 13481, "s": 13329, "text": "<configuration>\n <property>\n <name>yarn.nodemanager.aux-services</name>\n <value>mapreduce_shuffle</value> \n </property>\n</configuration>\n" }, { "code": null, "e": 13497, "s": 13481, "text": "mapred-site.xml" }, { "code": null, "e": 13753, "s": 13497, "text": "This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, it is required to copy the file from mapred-site.xml.template to mapred-site.xml file using the following command." }, { "code": null, "e": 13801, "s": 13753, "text": "$ cp mapred-site.xml.template mapred-site.xml \n" }, { "code": null, "e": 13927, "s": 13801, "text": "Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration>tags in this file." }, { "code": null, "e": 14061, "s": 13927, "text": "<configuration>\n <property> \n <name>mapreduce.framework.name</name>\n <value>yarn</value>\n </property>\n</configuration>\n" }, { "code": null, "e": 14125, "s": 14061, "text": "The following steps are used to verify the Hadoop installation." }, { "code": null, "e": 14199, "s": 14125, "text": "Set up the namenode using the command β€œhdfs namenode -format” as follows." }, { "code": null, "e": 14233, "s": 14199, "text": "$ cd ~ \n$ hdfs namenode -format \n" }, { "code": null, "e": 14268, "s": 14233, "text": "The expected result is as follows." }, { "code": null, "e": 15078, "s": 14268, "text": "10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: \n/************************************************************ \nSTARTUP_MSG: Starting NameNode \nSTARTUP_MSG: host = localhost/192.168.1.11 \nSTARTUP_MSG: args = [-format] \nSTARTUP_MSG: version = 2.4.1 \n...\n...\n10/24/14 21:30:56 INFO common.Storage: Storage directory \n/home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. \n10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to \nretain 1 images with txid >= 0 \n10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 \n10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: \n/************************************************************ \nSHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 \n************************************************************/\n" }, { "code": null, "e": 15181, "s": 15078, "text": "The following command is used to start dfs. Executing this command will start your Hadoop file system." }, { "code": null, "e": 15198, "s": 15181, "text": "$ start-dfs.sh \n" }, { "code": null, "e": 15234, "s": 15198, "text": "The expected output is as follows βˆ’" }, { "code": null, "e": 15548, "s": 15234, "text": "10/24/14 21:37:56 \nStarting namenodes on [localhost] \nlocalhost: starting namenode, logging to /home/hadoop/hadoop\n2.4.1/logs/hadoop-hadoop-namenode-localhost.out \nlocalhost: starting datanode, logging to /home/hadoop/hadoop\n2.4.1/logs/hadoop-hadoop-datanode-localhost.out \nStarting secondary namenodes [0.0.0.0]\n" }, { "code": null, "e": 15657, "s": 15548, "text": "The following command is used to start the yarn script. Executing this command will start your yarn daemons." }, { "code": null, "e": 15675, "s": 15657, "text": "$ start-yarn.sh \n" }, { "code": null, "e": 15708, "s": 15675, "text": "The expected output as follows βˆ’" }, { "code": null, "e": 15957, "s": 15708, "text": "starting yarn daemons \nstarting resourcemanager, logging to /home/hadoop/hadoop\n2.4.1/logs/yarn-hadoop-resourcemanager-localhost.out \nlocalhost: starting nodemanager, logging to /home/hadoop/hadoop\n2.4.1/logs/yarn-hadoop-nodemanager-localhost.out \n" }, { "code": null, "e": 16065, "s": 15957, "text": "The default port number to access Hadoop is 50070. Use the following url to get Hadoop services on browser." }, { "code": null, "e": 16090, "s": 16065, "text": "http://localhost:50070/\n" }, { "code": null, "e": 16206, "s": 16090, "text": "The default port number to access all applications of cluster is 8088. Use the following url to visit this service." }, { "code": null, "e": 16230, "s": 16206, "text": "http://localhost:8088/\n" }, { "code": null, "e": 16265, "s": 16230, "text": "\n 39 Lectures \n 2.5 hours \n" }, { "code": null, "e": 16284, "s": 16265, "text": " Arnab Chakraborty" }, { "code": null, "e": 16317, "s": 16284, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 16336, "s": 16317, "text": " Arnab Chakraborty" }, { "code": null, "e": 16369, "s": 16336, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 16389, "s": 16369, "text": " Pranjal Srivastava" }, { "code": null, "e": 16424, "s": 16389, "text": "\n 24 Lectures \n 6.5 hours \n" }, { "code": null, "e": 16436, "s": 16424, "text": " Pari Margu" }, { "code": null, "e": 16472, "s": 16436, "text": "\n 89 Lectures \n 11.5 hours \n" }, { "code": null, "e": 16488, "s": 16472, "text": " TELCOMA Global" }, { "code": null, "e": 16523, "s": 16488, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 16541, "s": 16523, "text": " Bigdata Engineer" }, { "code": null, "e": 16548, "s": 16541, "text": " Print" }, { "code": null, "e": 16559, "s": 16548, "text": " Add Notes" } ]
Creating fractals with Python. Try it yourself in this post! | by Dhanesh Budhrani | Towards Data Science
First of all, what is a geometric fractal? A geometric fractal is a geometric shape with a repeating structure at different scales: it doesn’t matter whether you get closer to the image or not, you’ll always see the same pattern. Or, as defined by Benoit Mandelbrot, β€œa rough or fragmented geometric shape that can be split into parts, each of which is (at least approximately) a reduced-size copy of the whole”. Now, how can we build a fractal in Python? Given that we are repeating a structure at different scales, we’ll need to apply a recursive solution. Moreover, we’ll be using turtle to draw the fractals. In this post, we’ll be drawing both a fractal tree and a Koch snowflake. In order to create a tree, we are going to divide each branch into two sub-branches (left and right) and shorten the new sub-branches, until we reach a minimum branch length, defined by ourselves: import turtleMINIMUM_BRANCH_LENGTH = 5def build_tree(t, branch_length, shorten_by, angle): passtree = turtle.Turtle()tree.hideturtle()tree.setheading(90)tree.color('green')build_tree(tree, 50, 5, 30)turtle.mainloop() So far, we’ve just defined the basics. We’ve imported turtle and created an instance of turtle.Turtle(), which will be the object moving around the canvas and drawing our tree. We’ve then made it face upwards with setheading(). We’ve also defined the signature of our recursive function, which will be the following: t: our Turtle instance. branch_length: the current length of the branch in pixels. shorten_by: determines by how many pixels the sub-branches will be shorter than the parent branch. angle: the angles from which the sub-branches emerge from the parent branch. Moreover, we’ve defined the MINIMUM_BRANCH_LENGTH (in pixels), which sets the minimum threshold to create further sub-branches. Let’s now build the body of our recursive function: import turtleMINIMUM_BRANCH_LENGTH = 5def build_tree(t, branch_length, shorten_by, angle): if branch_length > MINIMUM_BRANCH_LENGTH: t.forward(branch_length) new_length = branch_length - shorten_by t.left(angle) build_tree(t, new_length, shorten_by, angle) t.right(angle * 2) build_tree(t, new_length, shorten_by, angle) t.left(angle) t.backward(branch_length)tree = turtle.Turtle()tree.hideturtle()tree.setheading(90)tree.color('green')build_tree(tree, 50, 5, 30)turtle.mainloop() As you can see, we reach our base case if branch_length is lower than MINIMUM_BRANCH_LENGTH. Otherwise, we draw the branch and proceed to create the sub-branches by computing their length and turning left and right by β€œangle” degrees and calling build_tree again with the new values. Finally, we move backwards to the root of our branch. If you execute the code you should obtain the following result: Finally, feel free to play around with the code (and the parameters) here! In the second section of this post we’ll be drawing a more complex structure: the Koch snowflake. First of all, we’ll need to create a recursive function to create the Koch curve, and then we’ll be joining 3 of these curves to create a snowflake. Let’s start by defining the parameters of our recursive function: t: our Turtle instance. iterations: represents the value of n in the image below this list (note that n=0 would represent a flat line, which will be the base case in our recursive function). length: the length of each side in our current (sub-)snowflake. shortening_factor: determines the factor by which the side length is divided when we create a new sub-snowflake. angle: determines the angle from which the new side emerges. Once we have defined the basic structure of our recursive function, we may reach the following point: import turtledef koch_curve(t, iterations, length, shortening_factor, angle): passt = turtle.Turtle()t.hideturtle()for i in range(3): koch_curve(t, 4, 200, 3, 60) t.right(120)turtle.mainloop() At this point, we just have to implement the recursive function. If we have reached our base case, we’ll just draw a line. Otherwise, we’ll update our parameters (specifically, iterations and length) and call our recursive function 4 times. Between these function calls we’ll be turning first to the left, then to the right and finally to the left again. Let’s see how the full implementation looks: import turtledef koch_curve(t, iterations, length, shortening_factor, angle): if iterations == 0: t.forward(length) else: iterations = iterations - 1 length = length / shortening_factor koch_curve(t, iterations, length, shortening_factor, angle) t.left(angle) koch_curve(t, iterations, length, shortening_factor, angle) t.right(angle * 2) koch_curve(t, iterations, length, shortening_factor, angle) t.left(angle) koch_curve(t, iterations, length, shortening_factor, angle)t = turtle.Turtle()t.hideturtle()for i in range(3): koch_curve(t, 4, 200, 3, 60) t.right(120)turtle.mainloop() If you execute the code above, you should obtain the following result: Again, feel free to play around with the code (and parameters) here!
[ { "code": null, "e": 584, "s": 171, "text": "First of all, what is a geometric fractal? A geometric fractal is a geometric shape with a repeating structure at different scales: it doesn’t matter whether you get closer to the image or not, you’ll always see the same pattern. Or, as defined by Benoit Mandelbrot, β€œa rough or fragmented geometric shape that can be split into parts, each of which is (at least approximately) a reduced-size copy of the whole”." }, { "code": null, "e": 857, "s": 584, "text": "Now, how can we build a fractal in Python? Given that we are repeating a structure at different scales, we’ll need to apply a recursive solution. Moreover, we’ll be using turtle to draw the fractals. In this post, we’ll be drawing both a fractal tree and a Koch snowflake." }, { "code": null, "e": 1054, "s": 857, "text": "In order to create a tree, we are going to divide each branch into two sub-branches (left and right) and shorten the new sub-branches, until we reach a minimum branch length, defined by ourselves:" }, { "code": null, "e": 1272, "s": 1054, "text": "import turtleMINIMUM_BRANCH_LENGTH = 5def build_tree(t, branch_length, shorten_by, angle): passtree = turtle.Turtle()tree.hideturtle()tree.setheading(90)tree.color('green')build_tree(tree, 50, 5, 30)turtle.mainloop()" }, { "code": null, "e": 1589, "s": 1272, "text": "So far, we’ve just defined the basics. We’ve imported turtle and created an instance of turtle.Turtle(), which will be the object moving around the canvas and drawing our tree. We’ve then made it face upwards with setheading(). We’ve also defined the signature of our recursive function, which will be the following:" }, { "code": null, "e": 1613, "s": 1589, "text": "t: our Turtle instance." }, { "code": null, "e": 1672, "s": 1613, "text": "branch_length: the current length of the branch in pixels." }, { "code": null, "e": 1771, "s": 1672, "text": "shorten_by: determines by how many pixels the sub-branches will be shorter than the parent branch." }, { "code": null, "e": 1848, "s": 1771, "text": "angle: the angles from which the sub-branches emerge from the parent branch." }, { "code": null, "e": 1976, "s": 1848, "text": "Moreover, we’ve defined the MINIMUM_BRANCH_LENGTH (in pixels), which sets the minimum threshold to create further sub-branches." }, { "code": null, "e": 2028, "s": 1976, "text": "Let’s now build the body of our recursive function:" }, { "code": null, "e": 2535, "s": 2028, "text": "import turtleMINIMUM_BRANCH_LENGTH = 5def build_tree(t, branch_length, shorten_by, angle): if branch_length > MINIMUM_BRANCH_LENGTH: t.forward(branch_length) new_length = branch_length - shorten_by t.left(angle) build_tree(t, new_length, shorten_by, angle) t.right(angle * 2) build_tree(t, new_length, shorten_by, angle) t.left(angle) t.backward(branch_length)tree = turtle.Turtle()tree.hideturtle()tree.setheading(90)tree.color('green')build_tree(tree, 50, 5, 30)turtle.mainloop()" }, { "code": null, "e": 2873, "s": 2535, "text": "As you can see, we reach our base case if branch_length is lower than MINIMUM_BRANCH_LENGTH. Otherwise, we draw the branch and proceed to create the sub-branches by computing their length and turning left and right by β€œangle” degrees and calling build_tree again with the new values. Finally, we move backwards to the root of our branch." }, { "code": null, "e": 2937, "s": 2873, "text": "If you execute the code you should obtain the following result:" }, { "code": null, "e": 3012, "s": 2937, "text": "Finally, feel free to play around with the code (and the parameters) here!" }, { "code": null, "e": 3110, "s": 3012, "text": "In the second section of this post we’ll be drawing a more complex structure: the Koch snowflake." }, { "code": null, "e": 3325, "s": 3110, "text": "First of all, we’ll need to create a recursive function to create the Koch curve, and then we’ll be joining 3 of these curves to create a snowflake. Let’s start by defining the parameters of our recursive function:" }, { "code": null, "e": 3349, "s": 3325, "text": "t: our Turtle instance." }, { "code": null, "e": 3516, "s": 3349, "text": "iterations: represents the value of n in the image below this list (note that n=0 would represent a flat line, which will be the base case in our recursive function)." }, { "code": null, "e": 3580, "s": 3516, "text": "length: the length of each side in our current (sub-)snowflake." }, { "code": null, "e": 3693, "s": 3580, "text": "shortening_factor: determines the factor by which the side length is divided when we create a new sub-snowflake." }, { "code": null, "e": 3754, "s": 3693, "text": "angle: determines the angle from which the new side emerges." }, { "code": null, "e": 3856, "s": 3754, "text": "Once we have defined the basic structure of our recursive function, we may reach the following point:" }, { "code": null, "e": 4052, "s": 3856, "text": "import turtledef koch_curve(t, iterations, length, shortening_factor, angle): passt = turtle.Turtle()t.hideturtle()for i in range(3): koch_curve(t, 4, 200, 3, 60) t.right(120)turtle.mainloop()" }, { "code": null, "e": 4452, "s": 4052, "text": "At this point, we just have to implement the recursive function. If we have reached our base case, we’ll just draw a line. Otherwise, we’ll update our parameters (specifically, iterations and length) and call our recursive function 4 times. Between these function calls we’ll be turning first to the left, then to the right and finally to the left again. Let’s see how the full implementation looks:" }, { "code": null, "e": 5069, "s": 4452, "text": "import turtledef koch_curve(t, iterations, length, shortening_factor, angle): if iterations == 0: t.forward(length) else: iterations = iterations - 1 length = length / shortening_factor koch_curve(t, iterations, length, shortening_factor, angle) t.left(angle) koch_curve(t, iterations, length, shortening_factor, angle) t.right(angle * 2) koch_curve(t, iterations, length, shortening_factor, angle) t.left(angle) koch_curve(t, iterations, length, shortening_factor, angle)t = turtle.Turtle()t.hideturtle()for i in range(3): koch_curve(t, 4, 200, 3, 60) t.right(120)turtle.mainloop()" }, { "code": null, "e": 5140, "s": 5069, "text": "If you execute the code above, you should obtain the following result:" } ]
Tryit Editor v3.7
Tryit: Style the ::marker pseudo-element
[]
How to convert Integer array list to float array in Java?
To convert integer array list to float array, let us first create an integer array list βˆ’ ArrayList < Integer > arrList = new ArrayList < Integer > (); arrList.add(25); arrList.add(50); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); Now, convert integer array list to float array. We have first set the size to the float array. With that, each and every value of the integer array is assigned to the float array βˆ’ final float[] arr = new float[arrList.size()]; int index = 0; for (final Integer value: arrList) { arr[index++] = value; } Live Demo import java.util.ArrayList; public class Demo { public static void main(String[] args) { ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(25); arrList.add(50); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); final float[] arr = new float[arrList.size()]; int index = 0; for (final Integer value: arrList) { arr[index++] = value; } System.out.println("Elements of float array..."); for (Float i: arr) { System.out.println(i); } } } Elements of float array... 25.0 50.0 100.0 200.0 300.0 400.0 500.0
[ { "code": null, "e": 1152, "s": 1062, "text": "To convert integer array list to float array, let us first create an integer array list βˆ’" }, { "code": null, "e": 1338, "s": 1152, "text": "ArrayList < Integer > arrList = new ArrayList < Integer > ();\narrList.add(25);\narrList.add(50);\narrList.add(100);\narrList.add(200);\narrList.add(300);\narrList.add(400);\narrList.add(500);" }, { "code": null, "e": 1519, "s": 1338, "text": "Now, convert integer array list to float array. We have first set the size to the float array. With that, each and every value of the integer array is assigned to the float array βˆ’" }, { "code": null, "e": 1645, "s": 1519, "text": "final float[] arr = new float[arrList.size()];\nint index = 0;\nfor (final Integer value: arrList) {\n arr[index++] = value;\n}" }, { "code": null, "e": 1656, "s": 1645, "text": " Live Demo" }, { "code": null, "e": 2260, "s": 1656, "text": "import java.util.ArrayList;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<Integer>arrList = new ArrayList<Integer>();\n arrList.add(25);\n arrList.add(50);\n arrList.add(100);\n arrList.add(200);\n arrList.add(300);\n arrList.add(400);\n arrList.add(500);\n final float[] arr = new float[arrList.size()];\n int index = 0;\n for (final Integer value: arrList) {\n arr[index++] = value;\n }\n System.out.println(\"Elements of float array...\");\n for (Float i: arr) {\n System.out.println(i);\n }\n }\n}" }, { "code": null, "e": 2327, "s": 2260, "text": "Elements of float array...\n25.0\n50.0\n100.0\n200.0\n300.0\n400.0\n500.0" } ]
\strut - Tex Command
\strut - Used to create an invisible box with no width, height 8.6pt and depth 3pt. { \strut} \strut command creates an invisible box with no width, height 8.6pt and depth 3pt. \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \Tiny \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \Large \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} \Tiny \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \Tiny \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} \Large \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} ( )(mathstrutstrut \Large \sqrt{(\ )} \sqrt{\mathstrut\rm mathstrut} \sqrt{\strut\rm strut} 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": 8070, "s": 7986, "text": "\\strut - Used to create an invisible box with no width, height 8.6pt and depth 3pt." }, { "code": null, "e": 8080, "s": 8070, "text": "{ \\strut}" }, { "code": null, "e": 8163, "s": 8080, "text": "\\strut command creates an invisible box with no width, height 8.6pt and depth 3pt." }, { "code": null, "e": 8445, "s": 8163, "text": "\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n\n\\Tiny\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n\n\\Large\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n\n" }, { "code": null, "e": 8534, "s": 8445, "text": "\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n" }, { "code": null, "e": 8601, "s": 8534, "text": "\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n" }, { "code": null, "e": 8696, "s": 8601, "text": "\\Tiny\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n" }, { "code": null, "e": 8769, "s": 8696, "text": "\\Tiny\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n" }, { "code": null, "e": 8865, "s": 8769, "text": "\\Large\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n\n\n( )(mathstrutstrut\n\n" }, { "code": null, "e": 8939, "s": 8865, "text": "\\Large\n\\sqrt{(\\ )}\n\\sqrt{\\mathstrut\\rm mathstrut}\n\\sqrt{\\strut\\rm strut}\n" }, { "code": null, "e": 8971, "s": 8939, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8984, "s": 8971, "text": " Ashraf Said" }, { "code": null, "e": 9017, "s": 8984, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 9030, "s": 9017, "text": " Ashraf Said" }, { "code": null, "e": 9062, "s": 9030, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 9098, "s": 9062, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9133, "s": 9098, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9150, "s": 9133, "text": " Mohammad Nauman" }, { "code": null, "e": 9183, "s": 9150, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9197, "s": 9183, "text": " Daniel Stern" }, { "code": null, "e": 9229, "s": 9197, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 9244, "s": 9229, "text": " Nishant Kumar" }, { "code": null, "e": 9251, "s": 9244, "text": " Print" }, { "code": null, "e": 9262, "s": 9251, "text": " Add Notes" } ]
Constants in C/C++ - GeeksforGeeks
03 Aug, 2021 As the name suggests the name constants are given to such variables or values in C/C++ programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants, etc. Every constant has some range. The integers that are too big to fit into an int will be taken as long. Now there are various ranges that differ from unsigned to signed bits. Under the signed bit, the range of an int varies from -128 to +127, and under the unsigned bit, int varies from 0 to 255. Defining Constants: In C/C++ program we can define constants in two ways as shown below: Using #define preprocessor directiveUsing a const keyword Using #define preprocessor directive Using a const keyword Literals: The values assigned to each constant variables are referred to as the literals. Generally, both terms, constants and literals are used interchangeably. For eg, β€œconst int = 5;β€œ, is a constant expression and the value 5 is referred to as constant integer literal. Refer here for various Types of Literals in C++.Let us now learn about above two ways in details: Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:#define identifierName valueidentifierName: It is the name given to constant.value: This refers to any value assigned to identifierName.using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:#define identifierName valueidentifierName: It is the name given to constant.value: This refers to any value assigned to identifierName. #define identifierName value identifierName: It is the name given to constant. value: This refers to any value assigned to identifierName. using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Below program shows how to use const to declare constants of different data types: C C++ #include <stdio.h> int main(){ // int constant const int intVal = 10; // Real constant const float floatVal = 4.14; // char constant const char charVal = 'A'; // string constant const char stringVal[10] = "ABC"; printf("Integer constant:%d \n", intVal ); printf("Floating point constant: %.2f\n", floatVal ); printf("Character constant: %c\n", charVal ); printf("String constant: %s\n", stringVal); return 0;} #include <iostream>using namespace std; int main() { // int constant const int intVal = 10; // Real constant const float floatVal = 4.14; // char constant const char charVal = 'A'; // string constant const string stringVal = "ABC"; cout << "Integer Constant: " << intVal << "\n"; cout << "Floating point Constant: " << floatVal << "\n"; cout << "Character Constant: "<< charVal << "\n"; cout << "String Constant: "<< stringVal << "\n"; return 0; } Integer constant: 10 Floating point constant: 4.14 Character constant: A String constant: ABC Refer Const Qualifier in C for details. This article is contributed by Chinmoy Lenka. 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. saurabh1990aror sooda367 CBSE - Class 11 school-programming C Language 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++ Command line arguments in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Different methods to reverse a string in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C Enumeration (or enum) in C
[ { "code": null, "e": 24362, "s": 24334, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24955, "s": 24362, "text": "As the name suggests the name constants are given to such variables or values in C/C++ programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants, etc. Every constant has some range. The integers that are too big to fit into an int will be taken as long. Now there are various ranges that differ from unsigned to signed bits. Under the signed bit, the range of an int varies from -128 to +127, and under the unsigned bit, int varies from 0 to 255. " }, { "code": null, "e": 25046, "s": 24955, "text": "Defining Constants: In C/C++ program we can define constants in two ways as shown below: " }, { "code": null, "e": 25104, "s": 25046, "text": "Using #define preprocessor directiveUsing a const keyword" }, { "code": null, "e": 25141, "s": 25104, "text": "Using #define preprocessor directive" }, { "code": null, "e": 25163, "s": 25141, "text": "Using a const keyword" }, { "code": null, "e": 25536, "s": 25163, "text": "Literals: The values assigned to each constant variables are referred to as the literals. Generally, both terms, constants and literals are used interchangeably. For eg, β€œconst int = 5;β€œ, is a constant expression and the value 5 is referred to as constant integer literal. Refer here for various Types of Literals in C++.Let us now learn about above two ways in details: " }, { "code": null, "e": 26026, "s": 25536, "text": "Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:#define identifierName valueidentifierName: It is the name given to constant.value: This refers to any value assigned to identifierName.using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword." }, { "code": null, "e": 26338, "s": 26026, "text": "Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:#define identifierName valueidentifierName: It is the name given to constant.value: This refers to any value assigned to identifierName." }, { "code": null, "e": 26367, "s": 26338, "text": "#define identifierName value" }, { "code": null, "e": 26417, "s": 26367, "text": "identifierName: It is the name given to constant." }, { "code": null, "e": 26477, "s": 26417, "text": "value: This refers to any value assigned to identifierName." }, { "code": null, "e": 26656, "s": 26477, "text": "using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword." }, { "code": null, "e": 26739, "s": 26656, "text": "Below program shows how to use const to declare constants of different data types:" }, { "code": null, "e": 26741, "s": 26739, "text": "C" }, { "code": null, "e": 26745, "s": 26741, "text": "C++" }, { "code": "#include <stdio.h> int main(){ // int constant const int intVal = 10; // Real constant const float floatVal = 4.14; // char constant const char charVal = 'A'; // string constant const char stringVal[10] = \"ABC\"; printf(\"Integer constant:%d \\n\", intVal ); printf(\"Floating point constant: %.2f\\n\", floatVal ); printf(\"Character constant: %c\\n\", charVal ); printf(\"String constant: %s\\n\", stringVal); return 0;}", "e": 27218, "s": 26745, "text": null }, { "code": "#include <iostream>using namespace std; int main() { // int constant const int intVal = 10; // Real constant const float floatVal = 4.14; // char constant const char charVal = 'A'; // string constant const string stringVal = \"ABC\"; cout << \"Integer Constant: \" << intVal << \"\\n\"; cout << \"Floating point Constant: \" << floatVal << \"\\n\"; cout << \"Character Constant: \"<< charVal << \"\\n\"; cout << \"String Constant: \"<< stringVal << \"\\n\"; return 0; }", "e": 27735, "s": 27218, "text": null }, { "code": null, "e": 27832, "s": 27735, "text": "Integer constant: 10 \nFloating point constant: 4.14\nCharacter constant: A \nString constant: ABC " }, { "code": null, "e": 27872, "s": 27832, "text": "Refer Const Qualifier in C for details." }, { "code": null, "e": 28294, "s": 27872, "text": "This article is contributed by Chinmoy Lenka. 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": 28310, "s": 28294, "text": "saurabh1990aror" }, { "code": null, "e": 28319, "s": 28310, "text": "sooda367" }, { "code": null, "e": 28335, "s": 28319, "text": "CBSE - Class 11" }, { "code": null, "e": 28354, "s": 28335, "text": "school-programming" }, { "code": null, "e": 28365, "s": 28354, "text": "C Language" }, { "code": null, "e": 28463, "s": 28365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28472, "s": 28463, "text": "Comments" }, { "code": null, "e": 28485, "s": 28472, "text": "Old Comments" }, { "code": null, "e": 28520, "s": 28485, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28548, "s": 28520, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 28580, "s": 28548, "text": "Command line arguments in C/C++" }, { "code": null, "e": 28626, "s": 28580, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28638, "s": 28626, "text": "fork() in C" }, { "code": null, "e": 28685, "s": 28638, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 28702, "s": 28685, "text": "Substring in C++" }, { "code": null, "e": 28724, "s": 28702, "text": "Function Pointer in C" }, { "code": null, "e": 28762, "s": 28724, "text": "TCP Server-Client implementation in C" } ]
ggplot2 - Bubble Plots & Count Charts
Bubble plots are nothing but bubble charts which is basically a scatter plot with a third numeric variable used for circle size. In this chapter, we will focus on creation of bar count plot and histogram count plots which is considered as replica of bubble plots. Following steps are used to create bubble plots and count charts with mentioned package βˆ’ Load the respective package and the required dataset to create the bubble plots and count charts. > # Load ggplot > library(ggplot2) > > # Read in dataset > data(mpg) > head(mpg) # A tibble: 6 x 11 manufacturer model displ year cyl trans drv cty hwy fl class <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa~ 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa~ 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa~ 4 audi a4 2 2008 4 auto(av) f 21 30 p compa~ 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa~ 6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa~ The bar count plot can be created using the following command βˆ’ > # A bar count plot > p <- ggplot(mpg, aes(x=factor(cyl)))+ + geom_bar(stat="count") > p The histogram count plot can be created using the following command βˆ’ > # A historgram count plot > ggplot(data=mpg, aes(x=hwy)) + + geom_histogram( col="red", + fill="green", + alpha = .2, + binwidth = 5) Now let us create the most basic bubble plot with the required attributes of increasing the dimension of points mentioned in scattered plot. ggplot(mpg, aes(x=cty, y=hwy, size = pop)) +geom_point(alpha=0.7) The plot describes the nature of manufacturers which is included in legend format. The values represented include various dimensions of β€œhwy” attribute. Print Add Notes Bookmark this page
[ { "code": null, "e": 2286, "s": 2022, "text": "Bubble plots are nothing but bubble charts which is basically a scatter plot with a third numeric variable used for circle size. In this chapter, we will focus on creation of bar count plot and histogram count plots which is considered as replica of bubble plots." }, { "code": null, "e": 2376, "s": 2286, "text": "Following steps are used to create bubble plots and count charts with mentioned package βˆ’" }, { "code": null, "e": 2474, "s": 2376, "text": "Load the respective package and the required dataset to create the bubble plots and count charts." }, { "code": null, "e": 3179, "s": 2474, "text": "> # Load ggplot\n> library(ggplot2)\n>\n> # Read in dataset\n> data(mpg)\n> head(mpg)\n# A tibble: 6 x 11\nmanufacturer model displ year cyl trans drv cty hwy fl class\n<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>\n1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa~\n2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa~\n3 audi a4 2 2008 4 manual(m6) f 20 31 p compa~\n4 audi a4 2 2008 4 auto(av) f 21 30 p compa~\n5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa~\n6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa~\n" }, { "code": null, "e": 3243, "s": 3179, "text": "The bar count plot can be created using the following command βˆ’" }, { "code": null, "e": 3334, "s": 3243, "text": "> # A bar count plot\n> p <- ggplot(mpg, aes(x=factor(cyl)))+\n+ geom_bar(stat=\"count\")\n> p\n" }, { "code": null, "e": 3404, "s": 3334, "text": "The histogram count plot can be created using the following command βˆ’" }, { "code": null, "e": 3562, "s": 3404, "text": "> # A historgram count plot\n> ggplot(data=mpg, aes(x=hwy)) +\n+ geom_histogram( col=\"red\",\n+ fill=\"green\",\n+ alpha = .2,\n+ binwidth = 5)\n" }, { "code": null, "e": 3703, "s": 3562, "text": "Now let us create the most basic bubble plot with the required attributes of increasing the dimension of points mentioned in scattered plot." }, { "code": null, "e": 3770, "s": 3703, "text": "ggplot(mpg, aes(x=cty, y=hwy, size = pop)) +geom_point(alpha=0.7)\n" }, { "code": null, "e": 3923, "s": 3770, "text": "The plot describes the nature of manufacturers which is included in legend format. The values represented include various dimensions of β€œhwy” attribute." }, { "code": null, "e": 3930, "s": 3923, "text": " Print" }, { "code": null, "e": 3941, "s": 3930, "text": " Add Notes" } ]
Google AMP - Html Page to Amp Page
In this chapter, we will understand how to convert a normal html page to an amp page. We will also validate the page for amp and check the output at the last. To start with, let us take the normal html page as shown below βˆ’ <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Tutorials</title> <link href = "style.css" rel = "stylesheet" /> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <script src = "js/jquery.js"></script> </head> <body> <header role = "banner"> <h2>Tutorials</h2> </header> <h2>Some Important Tutorials List</h2> <article> <section> <img src = "images/tut1.png" width="90%" height = "90%"/> </section> <section> <img src = "images/tut2.png" width="90%" height = "90%"/> </section> <section> <img src = "images/tut3.png" width="90%" height = "90%"/> </section> <section> <img src = "images/tut4.png" width="90%" height = "90%"/> </section> </article> <footer> <p>For More tutorials Visit <a href = "https://tutorialspoint.com/">Tutorials Point</a></p> </footer> </body> </html> Note that we are using style.css in it and the details of the css file are as given here βˆ’ h1 {color: blue;text-align: center;} h2 {text-align: center;} img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; } article { text-align: center; } header{ width: 100%; height: 50px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: #ccc; } footer { width: 100%; height: 35px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: yellow; } Note that we have also used jquery.js file in the .html listed above. Now, host test.html locally and see the output seen in link given here βˆ’ http://localhost:8080/googleamp/test.html Now, let us go step-by-step to change above test.html file to test_amp.html file. First, we have to save test.html as test_amp.html and follow the steps given below. Step 1 βˆ’ Add the amp library in the head section as shown below βˆ’ <script async src = "https://cdn.ampproject.org/v0.js"> </script> For example, once added to test_amp.html, it will be as follows βˆ’ <head> <meta charset = "utf-8"> <title>Tutorials</title> <script async src = "https://cdn.ampproject.org/v0.js"> </script> <link href = "style.css" rel = "stylesheet" /> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <script src = "js/jquery.js"></script> </head> Now run the page test_amp.html in the browser and open the browser console. It will display the console message as shown below βˆ’ To know if your html file is a valid amp add #development=1 to your html page url at the end as shown below βˆ’ http://localhost:8080/googleamp/test_amp.html#development=1 Hit the above url in the browser and in the Google Chrome console. It will list you errors which amp thinks are invalid from amp specification point of view. The errors we have got for test_amp.html are shown here βˆ’ Let us now fix them one by one till we get amp successful message. Step 2 βˆ’ We can see the following error in the console βˆ’ We can fix that by adding ⚑ or amp for the html tag. We will add amp to html tag as shown below βˆ’ <html amp> Step 3 βˆ’ Please make sure you have the meta tag with charset and name=”viewport” in the head tag as shown below βˆ’ <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> </head> Step 4 βˆ’ The next error that we have is shown here βˆ’ It says href in link rel=stylesheet ie the following link is throwing error. This is because amp does not allow external stylesheet using link with href to be put inside pages. <link href = "style.css" rel = "stylesheet" /> We can add the all the css in style.css as follows βˆ’ <style amp-custom> /*All styles from style.css please add here */ </style> So the css data present in style.css has to be added in style with amp-custom attribute. <style amp-custom> h1 {color: blue;text-align: center;} h2 {text-align: center;} img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; } article { text-align: center; } header{ width: 100%; height: 50px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: #ccc; } footer { width: 100%; height: 35px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: yellow; } </style> Add the style tag to your amp page. Let us now test the same with the above style tag in the browser. The changes we have done so far to test_amp.html are shown here βˆ’ <!DOCTYPE html> <html amp> <head> <meta charset = "utf-8"> <title>Tutorials</title> <script async src = "https://cdn.ampproject.org/v0.js"> </script> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <script src = "js/jquery.js"></script> <style amp-custom> h1 {color: blue;text-align: center;} h2 {text-align: center;} img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; } article { text-align: center; } header{ width: 100%; height: 50px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: #ccc; } footer { width: 100%; height: 35px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: yellow; } </style> </head> <body> <header role = "banner"> <h2>Tutorials</h2> </header> <h2>Some Important Tutorials List</h2> <article> <section> <img src = "images/tut1.png" width = "90%" height = "90%"/> </section> <section> <img src = "images/tut2.png" width = "90%" height = "90%"/> </section> <section> <img src = "images/tut3.png" width = "90%" height = "90%"/> </section> <section> <img src = "images/tut4.png" width="90%" height = "90%"/> </section> </article> <footer> <p>For More tutorials Visit <a href = "https://tutorialspoint.com/">Tutorials Point</a></p> </footer> </body> </html> Let us see the output and errors in console for above page. Observe the following screenshot βˆ’ The error shown in the console is as follows βˆ’ Now, you can see that for some of the errors for amp, style is removed. Let us fix the remaining errors now. Step 5 βˆ’ The next error we see in the list is as follows βˆ’ We have added the script tag calling jquery file. Note that amp pages do not allow any custom javascript in the page. We will have to remove it and make sure to use amp-component which is available. For example, we have amp-animation if any animation is required, amp-analytics incase we want to add google analytics code to the page. Similarly, we have amp-ad component to display ads to be shown on the page. There is also an amp-iframe component which we can point the src to same origin and call any custom javascript if required in the amp-iframe. Now, let us remove the script tag from the page. Step 6 βˆ’ The next error displayed is shown here βˆ’ The above errors are pointing to the image tag we have used on the page. Amp does not allow <img src=”” /> tags to be used inside the page. Note that we need to use amp-img tag instead. Let us replace <img> tag with <amp-img> as shown here βˆ’ <section> <amp-img alt = "Beautiful Flower" src = "images/tut1.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut2.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut3.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut4.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> We have replaced all the <img> tag to <amp-img> as shown above. Now, let us run the page in the browser to see output and errors βˆ’ Observe that the errors are getting less now. Step 7 βˆ’ The next error displayed in console is as follows βˆ’ We need to add link rel=canonical tag in the head section. Please note this is a mandatory tag and should always be added in the head as follows βˆ’ <link rel = "canonical" href = "http://example.ampproject.org/article-metadata.html"> Step 8 βˆ’ The next error displayed in for missing noscript tag in the console as shown here βˆ’ We need to add <noscript> tag enclosed with amp-boilerplate in the head section as follows βˆ’ <noscript> <style amp-boilerplate> body{ -webkit-animation:none; -moz-animation:none; -ms-animation:none; animation:none} </style> </noscript> Step 9 βˆ’ The next error displayed is given below βˆ’ Another mandatory tag is the style tag with amp-boilerplate and has to be placed before noscript tag. The style tag with amp-boilerplate is shown here βˆ’ <style amp-boilerplate> body{ -webkit-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation: -amp-start 8s steps(1,end) 0s 1 normal both;animation: -amp-start 8s steps(1,end) 0s 1 normal both } @-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}} </style> Add above style tag to the test_amp.html page. Once done test the page in the browser to see the output and the console βˆ’ The console details are shown here βˆ’ Thus, we have finally solved all the errors and now the page test_amp.html is a valid amp page. There is some styling to be added as the header and footer is getting truncated, we can update the same in custom style that we have added. So we have removed width:100% from header and footer. Here is the final output βˆ’ <!DOCTYPE html> <html amp> <head> <meta charset = "utf-8"> <title>Tutorials</title> <link rel = "canonical" href= "http://example.ampproject.org/article-metadata.html"> <script async src = "https://cdn.ampproject.org/v0.js"> </script> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <style amp-boilerplate> body{ -webkit-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation: -amp-start 8s steps(1,end) 0s 1 normal both;animation: -amp-start 8s steps(1,end) 0s 1 normal both } @-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}} </style> <noscript> <style amp-boilerplate> body{ -webkit-animation:none; -moz-animation:none; -ms-animation:none; animation:none} </style> </noscript> <style amp-custom> h1 {color: blue;text-align: center;} h2 {text-align: center;} amp-img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; } article { text-align: center; } header{ height: 50px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: #ccc; } footer { height: 35px; margin: 5px auto; border: 1px solid #000000; text-align: center; background-color: yellow; } </style> </head> <body> <header role = "banner"> <h2>Tutorials</h2> </header> <h2>Some Important Tutorials List</h2> <article> <section> <amp-img alt = "Beautiful Flower" src = "images/tut1.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut2.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut3.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> <section> <amp-img alt = "Beautiful Flower" src = "images/tut4.png" width = "500" height = "160" layout = "responsive"> </amp-img> </section> </article> <footer> <p>For More tutorials Visit <a href = "https://tutorialspoint.com/"> Tutorials Point</a> </p> </footer> </body> </html> Thus, finally we are done with converting a normal html file to amp. 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2579, "s": 2420, "text": "In this chapter, we will understand how to convert a normal html page to an amp page. We will also validate the page for amp and check the output at the last." }, { "code": null, "e": 2644, "s": 2579, "text": "To start with, let us take the normal html page as shown below βˆ’" }, { "code": null, "e": 3693, "s": 2644, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>Tutorials</title>\n <link href = \"style.css\" rel = \"stylesheet\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <script src = \"js/jquery.js\"></script>\n </head>\n <body>\n <header role = \"banner\">\n <h2>Tutorials</h2>\n </header>\n <h2>Some Important Tutorials List</h2>\n <article>\n <section>\n <img src = \"images/tut1.png\" width=\"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut2.png\" width=\"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut3.png\" width=\"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut4.png\" width=\"90%\" height = \"90%\"/>\n </section>\n </article>\n <footer>\n <p>For More tutorials Visit <a href = \n \"https://tutorialspoint.com/\">Tutorials Point</a></p>\n </footer>\n </body>\n</html>" }, { "code": null, "e": 3784, "s": 3693, "text": "Note that we are using style.css in it and the details of the css file are as given here βˆ’" }, { "code": null, "e": 4394, "s": 3784, "text": "h1 {color: blue;text-align: center;}\n h2 {text-align: center;}\n img {\n border: 1px solid #ddd;\n border-radius: 4px;\n padding: 5px;\n }\n article {\n text-align: center;\n }\n header{\n width: 100%;\n height: 50px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: #ccc;\n }\n footer {\n width: 100%;\n height: 35px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: yellow;\n }" }, { "code": null, "e": 4464, "s": 4394, "text": "Note that we have also used jquery.js file in the .html listed above." }, { "code": null, "e": 4537, "s": 4464, "text": "Now, host test.html locally and see the output seen in link given here βˆ’" }, { "code": null, "e": 4579, "s": 4537, "text": "http://localhost:8080/googleamp/test.html" }, { "code": null, "e": 4661, "s": 4579, "text": "Now, let us go step-by-step to change above test.html file to test_amp.html file." }, { "code": null, "e": 4745, "s": 4661, "text": "First, we have to save test.html as test_amp.html and follow the steps given below." }, { "code": null, "e": 4811, "s": 4745, "text": "Step 1 βˆ’ Add the amp library in the head section as shown below βˆ’" }, { "code": null, "e": 4878, "s": 4811, "text": "<script async src = \"https://cdn.ampproject.org/v0.js\">\n</script>\n" }, { "code": null, "e": 4944, "s": 4878, "text": "For example, once added to test_amp.html, it will be as follows βˆ’" }, { "code": null, "e": 5265, "s": 4944, "text": "<head>\n <meta charset = \"utf-8\">\n <title>Tutorials</title>\n <script async src = \"https://cdn.ampproject.org/v0.js\">\n </script>\n <link href = \"style.css\" rel = \"stylesheet\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <script src = \"js/jquery.js\"></script>\n</head>\n" }, { "code": null, "e": 5394, "s": 5265, "text": "Now run the page test_amp.html in the browser and open the browser console. It will display the console message as shown below βˆ’" }, { "code": null, "e": 5504, "s": 5394, "text": "To know if your html file is a valid amp add #development=1 to your html page url at the end as shown below βˆ’" }, { "code": null, "e": 5565, "s": 5504, "text": "http://localhost:8080/googleamp/test_amp.html#development=1\n" }, { "code": null, "e": 5723, "s": 5565, "text": "Hit the above url in the browser and in the Google Chrome console. It will list you errors which amp thinks are invalid from amp specification point of view." }, { "code": null, "e": 5781, "s": 5723, "text": "The errors we have got for test_amp.html are shown here βˆ’" }, { "code": null, "e": 5848, "s": 5781, "text": "Let us now fix them one by one till we get amp successful message." }, { "code": null, "e": 5905, "s": 5848, "text": "Step 2 βˆ’ We can see the following error in the console βˆ’" }, { "code": null, "e": 6003, "s": 5905, "text": "We can fix that by adding ⚑ or amp for the html tag. We will add amp to html tag as shown below βˆ’" }, { "code": null, "e": 6015, "s": 6003, "text": "<html amp>\n" }, { "code": null, "e": 6129, "s": 6015, "text": "Step 3 βˆ’ Please make sure you have the meta tag with charset and name=”viewport” in the head tag as shown below βˆ’" }, { "code": null, "e": 6255, "s": 6129, "text": "<head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n</head>\n" }, { "code": null, "e": 6308, "s": 6255, "text": "Step 4 βˆ’ The next error that we have is shown here βˆ’" }, { "code": null, "e": 6485, "s": 6308, "text": "It says href in link rel=stylesheet ie the following link is throwing error. This is because amp does not allow external stylesheet using link with href to be put inside pages." }, { "code": null, "e": 6533, "s": 6485, "text": "<link href = \"style.css\" rel = \"stylesheet\" />\n" }, { "code": null, "e": 6586, "s": 6533, "text": "We can add the all the css in style.css as follows βˆ’" }, { "code": null, "e": 6665, "s": 6586, "text": "<style amp-custom>\n /*All styles from style.css please add here */\n</style>\n" }, { "code": null, "e": 6754, "s": 6665, "text": "So the css data present in style.css has to be added in style with amp-custom attribute." }, { "code": null, "e": 7395, "s": 6754, "text": "<style amp-custom>\n h1 {color: blue;text-align: center;}\n h2 {text-align: center;}\n img {\n border: 1px solid #ddd;\n border-radius: 4px;\n padding: 5px;\n }\n article {\n text-align: center;\n }\n header{\n width: 100%;\n height: 50px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: #ccc;\n }\n footer {\n width: 100%;\n height: 35px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: yellow;\n }\n</style>" }, { "code": null, "e": 7563, "s": 7395, "text": "Add the style tag to your amp page. Let us now test the same with the above style tag in the browser. The changes we have done so far to test_amp.html are shown here βˆ’" }, { "code": null, "e": 9469, "s": 7563, "text": "<!DOCTYPE html>\n<html amp>\n <head>\n <meta charset = \"utf-8\">\n <title>Tutorials</title>\n <script async src = \"https://cdn.ampproject.org/v0.js\">\n </script>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <script src = \"js/jquery.js\"></script>\n <style amp-custom>\n h1 {color: blue;text-align: center;}\n h2 {text-align: center;}\n img {\n border: 1px solid #ddd;\n border-radius: 4px;\n padding: 5px;\n }\n \n article {\n text-align: center;\n }\n header{\n width: 100%;\n height: 50px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: #ccc;\n }\n footer {\n width: 100%;\n height: 35px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: yellow;\n }\n </style>\n </head>\n <body>\n <header role = \"banner\">\n <h2>Tutorials</h2>\n </header>\n <h2>Some Important Tutorials List</h2>\n <article>\n <section>\n <img src = \"images/tut1.png\" width = \"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut2.png\" width = \"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut3.png\" width = \"90%\" height = \"90%\"/>\n </section>\n <section>\n <img src = \"images/tut4.png\" width=\"90%\" height = \"90%\"/>\n </section>\n </article>\n <footer>\n <p>For More tutorials Visit <a href = \n \"https://tutorialspoint.com/\">Tutorials Point</a></p>\n </footer>\n </body>\n</html>" }, { "code": null, "e": 9564, "s": 9469, "text": "Let us see the output and errors in console for above page. Observe the following screenshot βˆ’" }, { "code": null, "e": 9611, "s": 9564, "text": "The error shown in the console is as follows βˆ’" }, { "code": null, "e": 9720, "s": 9611, "text": "Now, you can see that for some of the errors for amp, style is removed. Let us fix the remaining errors now." }, { "code": null, "e": 9779, "s": 9720, "text": "Step 5 βˆ’ The next error we see in the list is as follows βˆ’" }, { "code": null, "e": 9978, "s": 9779, "text": "We have added the script tag calling jquery file. Note that amp pages do not allow any custom javascript in the page. We will have to remove it and make sure to use amp-component which is available." }, { "code": null, "e": 10332, "s": 9978, "text": "For example, we have amp-animation if any animation is required, amp-analytics incase we want to add google analytics code to the page. Similarly, we have amp-ad component to display ads to be shown on the page. There is also an amp-iframe component which we can point the src to same origin and call any custom javascript if required in the amp-iframe." }, { "code": null, "e": 10381, "s": 10332, "text": "Now, let us remove the script tag from the page." }, { "code": null, "e": 10431, "s": 10381, "text": "Step 6 βˆ’ The next error displayed is shown here βˆ’" }, { "code": null, "e": 10617, "s": 10431, "text": "The above errors are pointing to the image tag we have used on the page. Amp does not allow <img src=”” /> tags to be used inside the page. Note that we need to use amp-img tag instead." }, { "code": null, "e": 10673, "s": 10617, "text": "Let us replace <img> tag with <amp-img> as shown here βˆ’" }, { "code": null, "e": 11361, "s": 10673, "text": "<section>\n <amp-img alt = \"Beautiful Flower\"\n src = \"images/tut1.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n</section>\n<section>\n <amp-img alt = \"Beautiful Flower\"\n src = \"images/tut2.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n</section>\n<section>\n <amp-img alt = \"Beautiful Flower\"\n src = \"images/tut3.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n</section>\n<section>\n <amp-img alt = \"Beautiful Flower\"\n src = \"images/tut4.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n</section>" }, { "code": null, "e": 11492, "s": 11361, "text": "We have replaced all the <img> tag to <amp-img> as shown above. Now, let us run the page in the browser to see output and errors βˆ’" }, { "code": null, "e": 11538, "s": 11492, "text": "Observe that the errors are getting less now." }, { "code": null, "e": 11599, "s": 11538, "text": "Step 7 βˆ’ The next error displayed in console is as follows βˆ’" }, { "code": null, "e": 11746, "s": 11599, "text": "We need to add link rel=canonical tag in the head section. Please note this is a mandatory tag and should always be added in the head as follows βˆ’" }, { "code": null, "e": 11836, "s": 11746, "text": "<link rel = \"canonical\" href =\n \"http://example.ampproject.org/article-metadata.html\">\n" }, { "code": null, "e": 11929, "s": 11836, "text": "Step 8 βˆ’ The next error displayed in for missing noscript tag in the console as shown here βˆ’" }, { "code": null, "e": 12022, "s": 11929, "text": "We need to add <noscript> tag enclosed with amp-boilerplate in the head section as follows βˆ’" }, { "code": null, "e": 12214, "s": 12022, "text": "<noscript>\n <style amp-boilerplate>\n body{\n -webkit-animation:none;\n -moz-animation:none;\n -ms-animation:none;\n animation:none}\n </style>\n</noscript>\n" }, { "code": null, "e": 12265, "s": 12214, "text": "Step 9 βˆ’ The next error displayed is given below βˆ’" }, { "code": null, "e": 12418, "s": 12265, "text": "Another mandatory tag is the style tag with amp-boilerplate and has to be placed before noscript tag. The style tag with amp-boilerplate is shown here βˆ’" }, { "code": null, "e": 13116, "s": 12418, "text": "<style amp-boilerplate>\n body{\n -webkit-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;animation:\n -amp-start 8s steps(1,end) 0s 1 normal both\n }\n @-webkit-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}\n</style>" }, { "code": null, "e": 13163, "s": 13116, "text": "Add above style tag to the test_amp.html page." }, { "code": null, "e": 13238, "s": 13163, "text": "Once done test the page in the browser to see the output and the console βˆ’" }, { "code": null, "e": 13275, "s": 13238, "text": "The console details are shown here βˆ’" }, { "code": null, "e": 13371, "s": 13275, "text": "Thus, we have finally solved all the errors and now the page test_amp.html is a valid amp page." }, { "code": null, "e": 13565, "s": 13371, "text": "There is some styling to be added as the header and footer is getting truncated, we can update the same in custom style that we have added. So we have removed width:100% from header and footer." }, { "code": null, "e": 13592, "s": 13565, "text": "Here is the final output βˆ’" }, { "code": null, "e": 17153, "s": 13592, "text": "<!DOCTYPE html>\n<html amp>\n <head>\n <meta charset = \"utf-8\">\n <title>Tutorials</title>\n <link rel = \"canonical\" href=\n \"http://example.ampproject.org/article-metadata.html\">\n <script async src = \"https://cdn.ampproject.org/v0.js\">\n </script>\n <meta name = \"viewport\" content = \"width = device-width, \n initial-scale = 1.0\">\n \n <style amp-boilerplate>\n body{\n -webkit-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;animation:\n -amp-start 8s steps(1,end) 0s 1 normal both\n }\n @-webkit-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes \n -amp-start{from{visibility:hidden}to{visibility:visible}}\n </style>\n <noscript>\n <style amp-boilerplate>\n body{\n -webkit-animation:none;\n -moz-animation:none;\n -ms-animation:none;\n animation:none}\n </style>\n </noscript>\n <style amp-custom>\n h1 {color: blue;text-align: center;}\n h2 {text-align: center;}\n amp-img {\n border: 1px solid #ddd;\n border-radius: 4px;\n padding: 5px;\n }\n article {\n text-align: center;\n }\n header{\n height: 50px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: #ccc;\n }\n footer {\n height: 35px;\n margin: 5px auto;\n border: 1px solid #000000;\n text-align: center;\n background-color: yellow;\n }\n </style>\n </head>\n <body>\n <header role = \"banner\">\n <h2>Tutorials</h2>\n </header>\n <h2>Some Important Tutorials List</h2>\n <article>\n <section>\n <amp-img \n alt = \"Beautiful Flower\"\n src = \"images/tut1.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n </section>\n <section>\n <amp-img \n alt = \"Beautiful Flower\"\n src = \"images/tut2.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n </section>\n <section>\n <amp-img \n alt = \"Beautiful Flower\"\n src = \"images/tut3.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n </section>\n <section>\n <amp-img \n alt = \"Beautiful Flower\"\n src = \"images/tut4.png\"\n width = \"500\"\n height = \"160\"\n layout = \"responsive\">\n </amp-img>\n </section>\n </article>\n <footer>\n <p>For More tutorials Visit <a href = \n \"https://tutorialspoint.com/\">\n Tutorials Point</a>\n </p>\n </footer>\n </body>\n</html>" }, { "code": null, "e": 17222, "s": 17153, "text": "Thus, finally we are done with converting a normal html file to amp." }, { "code": null, "e": 17257, "s": 17222, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 17271, "s": 17257, "text": " Asif Hussain" }, { "code": null, "e": 17303, "s": 17271, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 17320, "s": 17303, "text": " Aditya Kulkarni" }, { "code": null, "e": 17355, "s": 17320, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 17369, "s": 17355, "text": " Sasha Miller" }, { "code": null, "e": 17404, "s": 17369, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17417, "s": 17404, "text": " Zach Miller" }, { "code": null, "e": 17452, "s": 17417, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17466, "s": 17452, "text": " Sasha Miller" }, { "code": null, "e": 17501, "s": 17466, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 17515, "s": 17501, "text": " Sasha Miller" }, { "code": null, "e": 17522, "s": 17515, "text": " Print" }, { "code": null, "e": 17533, "s": 17522, "text": " Add Notes" } ]
How to turn Android device screen on and off programmatically?
This example demonstrate about How to turn Android device screen on and off programmatically. Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project. Step 2 βˆ’ Add the following code to res/layout/activity_main.xml <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <LinearLayout android :layout_width= "match_parent" android :layout_height= "wrap_content" android :layout_centerInParent= "true" android :orientation= "horizontal" > <Button android :id= "@+id/btnEnable" android :layout_width= "0dp" android :layout_height= "wrap_content" android :layout_weight= "1" android :onClick= "enablePhone" android :text= "Enable" /> <Button android :id= "@+id/btnLock" android :layout_width= "0dp" android :layout_height= "wrap_content" android :layout_weight= "1" android :onClick= "lockPhone" android :text= "Lock" /> </LinearLayout> </RelativeLayout> Step 3 βˆ’ Add the following code to res/xml/policies.xml <? xml version= "1.0" encoding= "utf-8" ?> <device-admin xmlns: android = "http://schemas.android.com/apk/res/android" > <uses-policies> <force-lock /> </uses-policies> </device-admin> Step 4 βˆ’ Add the following code to src/DeviceAdmin package app.tutorialspoint.com.sample ; import android.app.admin.DeviceAdminReceiver ; import android.content.Context ; import android.content.Intent ; import android.widget.Toast ; public class DeviceAdmin extends DeviceAdminReceiver { @Override public void onEnabled (Context context , Intent intent) { super .onEnabled(context , intent) ; Toast. makeText (context , "Enabled" , Toast. LENGTH_SHORT ).show() ; } @Override public void onDisabled (Context context , Intent intent) { super .onDisabled(context , intent) ; Toast. makeText (context , "Disabled" , Toast. LENGTH_SHORT ).show() ; } } Step 5 βˆ’ Add the following code to src/MainActivity package app.tutorialspoint.com.sample ; import android.app.Activity ; import android.app.admin.DevicePolicyManager ; import android.content.ComponentName ; import android.content.Context ; import android.content.Intent ; import android.support.annotation. Nullable ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.Toast ; public class MainActivity extends AppCompatActivity { static final int RESULT_ENABLE = 1 ; DevicePolicyManager deviceManger ; ComponentName compName ; Button btnEnable , btnLock ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; btnEnable = findViewById(R.id. btnEnable ) ; btnLock = findViewById(R.id. btnLock ) ; deviceManger = (DevicePolicyManager) getSystemService(Context. DEVICE_POLICY_SERVICE ) ; compName = new ComponentName( this, DeviceAdmin. class ) ; boolean active = deviceManger .isAdminActive( compName ) ; if (active) { btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; } else { btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; } } public void enablePhone (View view) { boolean active = deviceManger .isAdminActive( compName ) ; if (active) { deviceManger .removeActiveAdmin( compName ) ; btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; } else { Intent intent = new Intent(DevicePolicyManager. ACTION_ADD_DEVICE_ADMIN ) ; intent.putExtra(DevicePolicyManager. EXTRA_DEVICE_ADMIN , compName ) ; intent.putExtra(DevicePolicyManager. EXTRA_ADD_EXPLANATION , "You should enable the app!" ) ; startActivityForResult(intent , RESULT_ENABLE ) ; } } public void lockPhone (View view) { deviceManger .lockNow() ; } @Override protected void onActivityResult ( int requestCode , int resultCode , @Nullable Intent data) { super .onActivityResult(requestCode , resultCode , data) ; switch (requestCode) { case RESULT_ENABLE : if (resultCode == Activity. RESULT_OK ) { btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; } else { Toast. makeText (getApplicationContext() , "Failed!" , Toast. LENGTH_SHORT ).show() ; } return; } } } Step 6 βˆ’ Add the following code to androidManifest.xml <? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" android :roundIcon= "@mipmap/ic_launcher_round" android :supportsRtl= "true" android :theme= "@style/AppTheme" > <activity android :name= ".MainActivity" > <intent-filter> <action android :name= "android.intent.action.MAIN" /> <category android :name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android :name= ".DeviceAdmin" android :description= "@string/app_description" android :label= "@string/app_name" android :permission= "android.permission.BIND_DEVICE_ADMIN" > <meta-data android :name= "android.app.device_admin" android :resource= "@xml/policies" /> <intent-filter> <action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1156, "s": 1062, "text": "This example demonstrate about How to turn Android device screen on and off programmatically." }, { "code": null, "e": 1285, "s": 1156, "text": "Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project." }, { "code": null, "e": 1349, "s": 1285, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 2408, "s": 1349, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <LinearLayout\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :layout_centerInParent= \"true\"\n android :orientation= \"horizontal\" >\n <Button\n android :id= \"@+id/btnEnable\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :layout_weight= \"1\"\n android :onClick= \"enablePhone\"\n android :text= \"Enable\" />\n <Button\n android :id= \"@+id/btnLock\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :layout_weight= \"1\"\n android :onClick= \"lockPhone\"\n android :text= \"Lock\" />\n </LinearLayout>\n</RelativeLayout>" }, { "code": null, "e": 2464, "s": 2408, "text": "Step 3 βˆ’ Add the following code to res/xml/policies.xml" }, { "code": null, "e": 2661, "s": 2464, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<device-admin xmlns: android = \"http://schemas.android.com/apk/res/android\" >\n <uses-policies>\n <force-lock />\n </uses-policies>\n</device-admin>" }, { "code": null, "e": 2712, "s": 2661, "text": "Step 4 βˆ’ Add the following code to src/DeviceAdmin" }, { "code": null, "e": 3350, "s": 2712, "text": "package app.tutorialspoint.com.sample ;\nimport android.app.admin.DeviceAdminReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.widget.Toast ;\npublic class DeviceAdmin extends DeviceAdminReceiver {\n @Override\n public void onEnabled (Context context , Intent intent) {\n super .onEnabled(context , intent) ;\n Toast. makeText (context , \"Enabled\" , Toast. LENGTH_SHORT ).show() ;\n }\n @Override\n public void onDisabled (Context context , Intent intent) {\n super .onDisabled(context , intent) ;\n Toast. makeText (context , \"Disabled\" , Toast. LENGTH_SHORT ).show() ;\n }\n}" }, { "code": null, "e": 3402, "s": 3350, "text": "Step 5 βˆ’ Add the following code to src/MainActivity" }, { "code": null, "e": 6028, "s": 3402, "text": "package app.tutorialspoint.com.sample ;\nimport android.app.Activity ;\nimport android.app.admin.DevicePolicyManager ;\nimport android.content.ComponentName ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.support.annotation. Nullable ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.Toast ;\npublic class MainActivity extends AppCompatActivity {\n static final int RESULT_ENABLE = 1 ;\n DevicePolicyManager deviceManger ;\n ComponentName compName ;\n Button btnEnable , btnLock ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n btnEnable = findViewById(R.id. btnEnable ) ;\n btnLock = findViewById(R.id. btnLock ) ;\n deviceManger = (DevicePolicyManager)\n getSystemService(Context. DEVICE_POLICY_SERVICE ) ;\n compName = new ComponentName( this, DeviceAdmin. class ) ;\n boolean active = deviceManger .isAdminActive( compName ) ;\n if (active) {\n btnEnable .setText( \"Disable\" ) ;\n btnLock .setVisibility(View. VISIBLE ) ;\n } else {\n btnEnable .setText( \"Enable\" ) ;\n btnLock .setVisibility(View. GONE ) ;\n }\n }\n public void enablePhone (View view) {\n boolean active = deviceManger .isAdminActive( compName ) ;\n if (active) {\n deviceManger .removeActiveAdmin( compName ) ;\n btnEnable .setText( \"Enable\" ) ;\n btnLock .setVisibility(View. GONE ) ;\n } else {\n Intent intent = new Intent(DevicePolicyManager. ACTION_ADD_DEVICE_ADMIN ) ;\n intent.putExtra(DevicePolicyManager. EXTRA_DEVICE_ADMIN , compName ) ;\n intent.putExtra(DevicePolicyManager. EXTRA_ADD_EXPLANATION , \"You should enable the app!\" ) ;\n startActivityForResult(intent , RESULT_ENABLE ) ;\n }\n }\n public void lockPhone (View view) {\n deviceManger .lockNow() ;\n }\n @Override\n protected void onActivityResult ( int requestCode , int resultCode , @Nullable Intent\n data) {\n super .onActivityResult(requestCode , resultCode , data) ;\n switch (requestCode) {\n case RESULT_ENABLE :\n if (resultCode == Activity. RESULT_OK ) {\n btnEnable .setText( \"Disable\" ) ;\n btnLock .setVisibility(View. VISIBLE ) ;\n } else {\n Toast. makeText (getApplicationContext() , \"Failed!\" ,\n Toast. LENGTH_SHORT ).show() ;\n }\n return;\n }\n }\n}" }, { "code": null, "e": 6083, "s": 6028, "text": "Step 6 βˆ’ Add the following code to androidManifest.xml" }, { "code": null, "e": 7370, "s": 6083, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver\n android :name= \".DeviceAdmin\"\n android :description= \"@string/app_description\"\n android :label= \"@string/app_name\"\n android :permission= \"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android :name= \"android.app.device_admin\"\n android :resource= \"@xml/policies\" />\n <intent-filter>\n <action android :name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>" }, { "code": null, "e": 7717, "s": 7370, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Binary Heap Operations | Practice | GeeksforGeeks
A binary heap is a Binary Tree with the following properties: 1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array. 2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap. You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below: 1) 1 x (a query of this type means to insert an element in the min-heap with value x ) 2) 2 x (a query of this type means to remove an element at position x from the min-heap) 3) 3 (a query like this removes the min element from the min-heap and prints it ). Example 1: Input: Q = 7 Queries: insertKey(4) insertKey(2) extractMin() insertKey(6) deleteKey(0) extractMin() extractMin() Output: 2 6 - 1 Explanation: In the first test case for query insertKey(4) the heap will have {4} insertKey(2) the heap will be {2 4} extractMin() removes min element from heap ie 2 and prints it now heap is {4} insertKey(6) inserts 6 to heap now heap is {4 6} deleteKey(0) delete element at position 0 of the heap,now heap is {6} extractMin() remove min element from heap ie 6 and prints it now the heap is empty extractMin() since the heap is empty thus no min element exist so -1 is printed. Example 2: Input: Q = 5 Queries: insertKey(8) insertKey(9) deleteKey(1) extractMin() extractMin() Output: 8 -1 Your Task: You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty) Expected Time Complexity: O(Q*Log(size of Heap) ). Expected Auxiliary Space: O(1). Constraints: 1 <= Q <= 104 1 <= x <= 104 0 2020aspire503 months ago int MinHeap::extractMin() { if(heap_size<=0)return -1; if(heap_size==1) { heap_size--; return harr[0]; } swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];} //Function to delete a key at ith index.void MinHeap::deleteKey(int i){ if(i>=heap_size||heap_size<=0)return; decreaseKey(i,INT_MIN); extractMin();} //Function to insert a value in Heap.void MinHeap::insertKey(int k) { if(heap_size==capacity)return; heap_size++; harr[heap_size-1]=k; int i=heap_size-1; while(i!=heap_size&&harr[i]<harr[parent(i)]) { swap(harr[i],harr[parent(i)]); i=parent(i); }} //Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i]=new_val; while(i!=0&&harr[parent(i)]>harr[i]) { swap(harr[parent(i)],harr[i]); i=parent(i); }}void MinHeap::MinHeapify(int i) { int lt=left(i); int rt=right(i); int smallest=i; if(heap_size>lt&&harr[lt]<harr[i]) smallest=lt; if(heap_size>rt&&harr[rt]<harr[smallest]) smallest=rt; if(i!=smallest) { swap(harr[smallest],harr[i]); MinHeapify(smallest); }} 0 19it020anku4 months ago int MinHeap::extractMin() { // Your code here if(heap_size==0) return -1; if(heap_size==1){ heap_size--; return harr[0]; } swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];} //Function to delete a key at ith index.void MinHeap::deleteKey(int i){ // Your code here if(heap_size<=0||heap_size<=i) return; decreaseKey(i,INT_MIN); extractMin();} //Function to insert a value in Heap.void MinHeap::insertKey(int k) { // Your code here if(heap_size>=capacity) return; heap_size++; harr[heap_size-1]=k; for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];) { swap(harr[parent(i)],harr[i]); i=parent(i); }} //Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} +3 bijayshaw6354 months ago int extractMin(){ if(heap_size<=0){ return -1; } if(heap_size==1){ heap_size--; return harr[0]; } int answer=harr[0]; harr[0]=harr[heap_size-1]; heap_size--; MinHeapify(0); return answer; } void insertKey(int k){ if(heap_size==capacity){ return; } heap_size++; int i=heap_size-1; harr[i]=k; while(i!=0 && harr[parent(i)]>harr[i]){ int temp=harr[parent(i)]; harr[parent(i)]=harr[i]; harr[i]=temp; i=parent(i); } } void deleteKey(int i){ if(i>heap_size-1){ return; } decreaseKey(i,Integer.MIN_VALUE); extractMin(); } 0 iamx72784 months ago int MinHeap::extractMin() { if(heap_size==0) return -1; if(heap_size==1) {heap_size--; return harr[0];} swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];}void MinHeap::deleteKey(int i){ if(heap_size<=0 || heap_size<=i) return; decreaseKey(i,INT_MIN); extractMin();}void MinHeap::insertKey(int k) { if(heap_size>=capacity)return; heap_size++; decreaseKey(heap_size-1,k);} 0 singhsrijan8094 months ago Java solution 09.sec PLAYERG SOLUTION class MinHeap { int[] harr; int capacity, heap_size; MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } //Function to extract minimum value in heap and then to store //next minimum value at first index. public void swap(int[] harr,int parent, int i) { // TODO Auto-generated method stub int temp=harr[parent]; harr[parent]=harr[i]; harr[i]=temp;} int extractMin() { // Your code here. if(heap_size==0) return -1; if(heap_size==1) { heap_size--; return harr[heap_size]; } swap(harr,0,heap_size-1); heap_size--; MinHeapify(0); return harr[heap_size]; } //Function to insert a value in Heap. void insertKey(int k) { // Your code here.if(heap_size>=capacity) return; heap_size++; int i=heap_size-1; harr[i]=k; while(i!=0 && harr[parent(i)]>harr[i]) { swap(harr,parent(i),i); i=parent(i); } } //Function to delete a key at ith index. void deleteKey(int i) { if(heap_size<=0 || i>=heap_size) return; decreaseKey(i,Integer.MIN_VALUE); extractMin(); } //Function to change value at ith index and store that value at first index. void decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } /* You may call below MinHeapify function in above codes. Please do not delete this code if you are not writing your own MinHeapify */ void MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; MinHeapify(smallest); } }} FEAR THE PLAYERG.......!!!!!!!!!! -1 chunna This comment was deleted. -2 singhiskingdeepankar4 months ago Simple code C++ -- //Function to extract minimum value in heap and then to store //next minimum value at first index.int MinHeap::extractMin() { if(heap_size==0) return -1; if(heap_size==1) {heap_size--; return harr[0];} swap(harr[0], harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];} //Function to delete a key at ith index.void MinHeap::deleteKey(int i){ decreaseKey(i,INT_MIN); extractMin();} //Function to insert a value in Heap.void MinHeap::insertKey(int k) { if(heap_size==capacity) return ; heap_size++; harr[heap_size-1]=k; for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];) { swap(harr[i],harr[parent(i)]); i = parent(i); }} //Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} /* You may call below MinHeapify function in above codes. Please do not delete this code if you are not writing your own MinHeapify */void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }} +1 manojkanakala4444 months ago Python code happy code :) #Back-end complete function Template for Python 3 def getParent(x): # get parent node , if exits else -1 return (x - 1) // 2 def leftChild(x): # get left child if exists, else -1 return (2 * x + 1) if (2 * x + 1) < curr_size else -1 def rightChild(x): # get right child if exits, else -1 return (2 * x + 2) if (2 * x + 2) < curr_size else -1 #Function to maintain the min heap property of heap. def heapify(): curr_ind = curr_size - 1 while getParent(curr_ind) != -1 and heap[getParent(curr_ind)] > heap[curr_ind]: heap[curr_ind], heap[getParent(curr_ind)]=heap[getParent(curr_ind)],heap[curr_ind] curr_ind = getParent(curr_ind) return def heapifyDown(x): # if the removed index was leaf. if x >= curr_size: return if getParent(x) != -1 and heap[x] < heap[getParent(x)]: heap[x], heap[getParent(x)] = heap[getParent(x)], heap[x] heapifyDown(getParent(x)) if leftChild(x)==-1 or (leftChild(x)!=-1 and heap[x]<heap[leftChild(x)]): if rightChild(x)==-1 or (rightChild(x)!=-1 and heap[x]<heap[rightChild(x)]): return #swapping with left child and calling function recursively for left child. if rightChild(x)==-1: heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x] heapifyDown(leftChild(x)) #swapping with right child and calling function recursively for right child. elif leftChild(x) == -1: heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x] heapifyDown(rightChild(x)) #swapping with the minimum of the two childs. else: if heap[rightChild(x)]<heap[leftChild(x)]: heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x] heapifyDown(rightChild(x)) else: heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x] heapifyDown(leftChild(x)) return #Function to insert a value in Heap. def insertKey (x): global curr_size #inserting value at current available index. heap[curr_size] = x curr_size += 1 #calling heapify function to maintain heap property. heapify() #Function to delete a key at ith index. def deleteKey (i): global curr_size if i >= curr_size: return #storing value of leaf node at ith index. heap[i] = heap[curr_size - 1] heap[curr_size - 1] = 0 curr_size -= 1 #calling heapify function to maintain heap property from index i. heapifyDown(i) #Function to extract minimum value in heap and then to store #next minimum value at first index. def extractMin (): if curr_size == 0: return -1 #storing value at first index in a variable. val = heap[0] #deleting the value at first index. deleteKey(0) return val +1 manojkanakala4444 months ago Java code class MinHeap{ int[] harr; int capacity; int heap_size; int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } //Function to insert a value in Heap. void insertKey(int k) { heap_size++; int i = heap_size - 1; //inserting the value at leaf node. harr[i] = k; while (i != 0 && harr[parent(i)] > harr[i]) { //swapping values of ith index with its parent node //if value at parent node is greater. int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } //Function to change value at ith index and store that value at first index. void decreaseKey(int i, int new_val) { //storing new value at ith index. harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { //swapping values of ith index with its parent node //if value at parent node is greater. int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } 0 manojkanakala4444 months ago Any code ? We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 517, "s": 238, "text": "A binary heap is a Binary Tree with the following properties:\n1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array." }, { "code": null, "e": 775, "s": 517, "text": "2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap." }, { "code": null, "e": 1249, "s": 775, "text": "You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:\n1) 1 x (a query of this type means to insert an element in the min-heap with value x )\n2) 2 x (a query of this type means to remove an element at position x from the min-heap)\n3) 3 (a query like this removes the min element from the min-heap and prints it )." }, { "code": null, "e": 1260, "s": 1249, "text": "Example 1:" }, { "code": null, "e": 1980, "s": 1260, "text": "Input:\nQ = 7\nQueries:\ninsertKey(4)\ninsertKey(2)\nextractMin()\ninsertKey(6)\ndeleteKey(0)\nextractMin()\nextractMin()\nOutput: 2 6 - 1\nExplanation: In the first test case for\nquery \ninsertKey(4) the heap will have {4} \ninsertKey(2) the heap will be {2 4}\nextractMin() removes min element from \n heap ie 2 and prints it\n now heap is {4} \ninsertKey(6) inserts 6 to heap now heap\n is {4 6}\ndeleteKey(0) delete element at position 0\n of the heap,now heap is {6}\nextractMin() remove min element from heap\n ie 6 and prints it now the\n heap is empty\nextractMin() since the heap is empty thus\n no min element exist so -1\n is printed.\n" }, { "code": null, "e": 1991, "s": 1980, "text": "Example 2:" }, { "code": null, "e": 2091, "s": 1991, "text": "Input:\nQ = 5\nQueries:\ninsertKey(8)\ninsertKey(9)\ndeleteKey(1)\nextractMin()\nextractMin()\nOutput: 8 -1" }, { "code": null, "e": 2385, "s": 2091, "text": "Your Task:\nYou are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)" }, { "code": null, "e": 2468, "s": 2385, "text": "Expected Time Complexity: O(Q*Log(size of Heap) ).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 2509, "s": 2468, "text": "Constraints:\n1 <= Q <= 104\n1 <= x <= 104" }, { "code": null, "e": 2511, "s": 2509, "text": "0" }, { "code": null, "e": 2536, "s": 2511, "text": "2020aspire503 months ago" }, { "code": null, "e": 2755, "s": 2536, "text": "int MinHeap::extractMin() { if(heap_size<=0)return -1; if(heap_size==1) { heap_size--; return harr[0]; } swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];}" }, { "code": null, "e": 2910, "s": 2755, "text": "//Function to delete a key at ith index.void MinHeap::deleteKey(int i){ if(i>=heap_size||heap_size<=0)return; decreaseKey(i,INT_MIN); extractMin();}" }, { "code": null, "e": 3184, "s": 2910, "text": "//Function to insert a value in Heap.void MinHeap::insertKey(int k) { if(heap_size==capacity)return; heap_size++; harr[heap_size-1]=k; int i=heap_size-1; while(i!=heap_size&&harr[i]<harr[parent(i)]) { swap(harr[i],harr[parent(i)]); i=parent(i); }}" }, { "code": null, "e": 3707, "s": 3184, "text": "//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i]=new_val; while(i!=0&&harr[parent(i)]>harr[i]) { swap(harr[parent(i)],harr[i]); i=parent(i); }}void MinHeap::MinHeapify(int i) { int lt=left(i); int rt=right(i); int smallest=i; if(heap_size>lt&&harr[lt]<harr[i]) smallest=lt; if(heap_size>rt&&harr[rt]<harr[smallest]) smallest=rt; if(i!=smallest) { swap(harr[smallest],harr[i]); MinHeapify(smallest); }} " }, { "code": null, "e": 3709, "s": 3707, "text": "0" }, { "code": null, "e": 3733, "s": 3709, "text": "19it020anku4 months ago" }, { "code": null, "e": 3974, "s": 3733, "text": "int MinHeap::extractMin() { // Your code here if(heap_size==0) return -1; if(heap_size==1){ heap_size--; return harr[0]; } swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];}" }, { "code": null, "e": 4163, "s": 3974, "text": "//Function to delete a key at ith index.void MinHeap::deleteKey(int i){ // Your code here if(heap_size<=0||heap_size<=i) return; decreaseKey(i,INT_MIN); extractMin();}" }, { "code": null, "e": 4463, "s": 4163, "text": "//Function to insert a value in Heap.void MinHeap::insertKey(int k) { // Your code here if(heap_size>=capacity) return; heap_size++; harr[heap_size-1]=k; for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];) { swap(harr[parent(i)],harr[i]); i=parent(i); }}" }, { "code": null, "e": 4720, "s": 4463, "text": "//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }}" }, { "code": null, "e": 4723, "s": 4720, "text": "+3" }, { "code": null, "e": 4748, "s": 4723, "text": "bijayshaw6354 months ago" }, { "code": null, "e": 5484, "s": 4748, "text": "int extractMin(){ if(heap_size<=0){ return -1; } if(heap_size==1){ heap_size--; return harr[0]; } int answer=harr[0]; harr[0]=harr[heap_size-1]; heap_size--; MinHeapify(0); return answer; } void insertKey(int k){ if(heap_size==capacity){ return; } heap_size++; int i=heap_size-1; harr[i]=k; while(i!=0 && harr[parent(i)]>harr[i]){ int temp=harr[parent(i)]; harr[parent(i)]=harr[i]; harr[i]=temp; i=parent(i); } } void deleteKey(int i){ if(i>heap_size-1){ return; } decreaseKey(i,Integer.MIN_VALUE); extractMin(); }" }, { "code": null, "e": 5486, "s": 5484, "text": "0" }, { "code": null, "e": 5507, "s": 5486, "text": "iamx72784 months ago" }, { "code": null, "e": 5931, "s": 5507, "text": "int MinHeap::extractMin() { if(heap_size==0) return -1; if(heap_size==1) {heap_size--; return harr[0];} swap(harr[0],harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];}void MinHeap::deleteKey(int i){ if(heap_size<=0 || heap_size<=i) return; decreaseKey(i,INT_MIN); extractMin();}void MinHeap::insertKey(int k) { if(heap_size>=capacity)return; heap_size++; decreaseKey(heap_size-1,k);}" }, { "code": null, "e": 5933, "s": 5931, "text": "0" }, { "code": null, "e": 5960, "s": 5933, "text": "singhsrijan8094 months ago" }, { "code": null, "e": 5981, "s": 5960, "text": "Java solution 09.sec" }, { "code": null, "e": 6000, "s": 5983, "text": "PLAYERG SOLUTION" }, { "code": null, "e": 6282, "s": 6000, "text": "class MinHeap { int[] harr; int capacity, heap_size; MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); }" }, { "code": null, "e": 6825, "s": 6282, "text": " //Function to extract minimum value in heap and then to store //next minimum value at first index. public void swap(int[] harr,int parent, int i) { // TODO Auto-generated method stub int temp=harr[parent]; harr[parent]=harr[i]; harr[i]=temp;} int extractMin() { // Your code here. if(heap_size==0) return -1; if(heap_size==1) { heap_size--; return harr[heap_size]; } swap(harr,0,heap_size-1); heap_size--; MinHeapify(0); return harr[heap_size]; }" }, { "code": null, "e": 7138, "s": 6825, "text": " //Function to insert a value in Heap. void insertKey(int k) { // Your code here.if(heap_size>=capacity) return; heap_size++; int i=heap_size-1; harr[i]=k; while(i!=0 && harr[parent(i)]>harr[i]) { swap(harr,parent(i),i); i=parent(i); } }" }, { "code": null, "e": 7338, "s": 7138, "text": " //Function to delete a key at ith index. void deleteKey(int i) { if(heap_size<=0 || i>=heap_size) return; decreaseKey(i,Integer.MIN_VALUE); extractMin(); }" }, { "code": null, "e": 7677, "s": 7338, "text": " //Function to change value at ith index and store that value at first index. void decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } }" }, { "code": null, "e": 8219, "s": 7677, "text": " /* You may call below MinHeapify function in above codes. Please do not delete this code if you are not writing your own MinHeapify */ void MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; MinHeapify(smallest); } }}" }, { "code": null, "e": 8255, "s": 8221, "text": "FEAR THE PLAYERG.......!!!!!!!!!!" }, { "code": null, "e": 8260, "s": 8257, "text": "-1" }, { "code": null, "e": 8267, "s": 8260, "text": "chunna" }, { "code": null, "e": 8293, "s": 8267, "text": "This comment was deleted." }, { "code": null, "e": 8296, "s": 8293, "text": "-2" }, { "code": null, "e": 8329, "s": 8296, "text": "singhiskingdeepankar4 months ago" }, { "code": null, "e": 8348, "s": 8329, "text": "Simple code C++ --" }, { "code": null, "e": 8652, "s": 8348, "text": "//Function to extract minimum value in heap and then to store //next minimum value at first index.int MinHeap::extractMin() { if(heap_size==0) return -1; if(heap_size==1) {heap_size--; return harr[0];} swap(harr[0], harr[heap_size-1]); heap_size--; MinHeapify(0); return harr[heap_size];}" }, { "code": null, "e": 8767, "s": 8652, "text": "//Function to delete a key at ith index.void MinHeap::deleteKey(int i){ decreaseKey(i,INT_MIN); extractMin();}" }, { "code": null, "e": 9033, "s": 8767, "text": "//Function to insert a value in Heap.void MinHeap::insertKey(int k) { if(heap_size==capacity) return ; heap_size++; harr[heap_size-1]=k; for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];) { swap(harr[i],harr[parent(i)]); i = parent(i); }}" }, { "code": null, "e": 9290, "s": 9033, "text": "//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }}" }, { "code": null, "e": 9731, "s": 9290, "text": "/* You may call below MinHeapify function in above codes. Please do not delete this code if you are not writing your own MinHeapify */void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }}" }, { "code": null, "e": 9734, "s": 9731, "text": "+1" }, { "code": null, "e": 9763, "s": 9734, "text": "manojkanakala4444 months ago" }, { "code": null, "e": 9789, "s": 9763, "text": "Python code happy code :)" }, { "code": null, "e": 12565, "s": 9791, "text": "#Back-end complete function Template for Python 3 def getParent(x): # get parent node , if exits else -1 return (x - 1) // 2 def leftChild(x): # get left child if exists, else -1 return (2 * x + 1) if (2 * x + 1) < curr_size else -1 def rightChild(x): # get right child if exits, else -1 return (2 * x + 2) if (2 * x + 2) < curr_size else -1 #Function to maintain the min heap property of heap. def heapify(): curr_ind = curr_size - 1 while getParent(curr_ind) != -1 and heap[getParent(curr_ind)] > heap[curr_ind]: heap[curr_ind], heap[getParent(curr_ind)]=heap[getParent(curr_ind)],heap[curr_ind] curr_ind = getParent(curr_ind) return def heapifyDown(x): # if the removed index was leaf. if x >= curr_size: return if getParent(x) != -1 and heap[x] < heap[getParent(x)]: heap[x], heap[getParent(x)] = heap[getParent(x)], heap[x] heapifyDown(getParent(x)) if leftChild(x)==-1 or (leftChild(x)!=-1 and heap[x]<heap[leftChild(x)]): if rightChild(x)==-1 or (rightChild(x)!=-1 and heap[x]<heap[rightChild(x)]): return #swapping with left child and calling function recursively for left child. if rightChild(x)==-1: heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x] heapifyDown(leftChild(x)) #swapping with right child and calling function recursively for right child. elif leftChild(x) == -1: heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x] heapifyDown(rightChild(x)) #swapping with the minimum of the two childs. else: if heap[rightChild(x)]<heap[leftChild(x)]: heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x] heapifyDown(rightChild(x)) else: heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x] heapifyDown(leftChild(x)) return #Function to insert a value in Heap. def insertKey (x): global curr_size #inserting value at current available index. heap[curr_size] = x curr_size += 1 #calling heapify function to maintain heap property. heapify() #Function to delete a key at ith index. def deleteKey (i): global curr_size if i >= curr_size: return #storing value of leaf node at ith index. heap[i] = heap[curr_size - 1] heap[curr_size - 1] = 0 curr_size -= 1 #calling heapify function to maintain heap property from index i. heapifyDown(i) #Function to extract minimum value in heap and then to store #next minimum value at first index. def extractMin (): if curr_size == 0: return -1 #storing value at first index in a variable. val = heap[0] #deleting the value at first index. deleteKey(0) return val " }, { "code": null, "e": 12568, "s": 12565, "text": "+1" }, { "code": null, "e": 12597, "s": 12568, "text": "manojkanakala4444 months ago" }, { "code": null, "e": 12608, "s": 12597, "text": "Java code " }, { "code": null, "e": 14054, "s": 12608, "text": "class MinHeap{ int[] harr; int capacity; int heap_size; int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } //Function to insert a value in Heap. void insertKey(int k) { heap_size++; int i = heap_size - 1; //inserting the value at leaf node. harr[i] = k; while (i != 0 && harr[parent(i)] > harr[i]) { //swapping values of ith index with its parent node //if value at parent node is greater. int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } //Function to change value at ith index and store that value at first index. void decreaseKey(int i, int new_val) { //storing new value at ith index. harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { //swapping values of ith index with its parent node //if value at parent node is greater. int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } " }, { "code": null, "e": 14058, "s": 14056, "text": "0" }, { "code": null, "e": 14087, "s": 14058, "text": "manojkanakala4444 months ago" }, { "code": null, "e": 14098, "s": 14087, "text": "Any code ?" }, { "code": null, "e": 14244, "s": 14098, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 14280, "s": 14244, "text": " Login to access your submissions. " }, { "code": null, "e": 14290, "s": 14280, "text": "\nProblem\n" }, { "code": null, "e": 14300, "s": 14290, "text": "\nContest\n" }, { "code": null, "e": 14363, "s": 14300, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 14511, "s": 14363, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 14719, "s": 14511, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 14825, "s": 14719, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
M_Expensive statement in SAP HANA
This can be checked using system view M_EXPENSIVE_STATEMENTS. SELECT * FROM M_EXPENSIVE_STATEMENTS In SAP HANA, the M_EXPENSIVE_STATEMENTS view provides convenient access to the most expensive statements that were executed on the system. A statement is considered being expensive if its runtime exceeds a particular threshold. Please note that the expensive statements trace needs to be activated first in the Performance β†’ Expensive Statements Trace screen in the SAP HANA studio. Click Configure the Trace Configuration dialog
[ { "code": null, "e": 1124, "s": 1062, "text": "This can be checked using system view M_EXPENSIVE_STATEMENTS." }, { "code": null, "e": 1161, "s": 1124, "text": "SELECT * FROM M_EXPENSIVE_STATEMENTS" }, { "code": null, "e": 1591, "s": 1161, "text": "In SAP HANA, the M_EXPENSIVE_STATEMENTS view provides convenient access to the most expensive statements that were executed on the system. A statement is considered being expensive if its runtime exceeds a particular threshold. Please note that the expensive statements trace needs to be activated first in the Performance β†’ Expensive Statements Trace screen in the SAP HANA studio. Click Configure the Trace Configuration dialog" } ]
Creating Index in Column based tables in SAP HANA
Note that an index not necessary to be NOT NULL. You can create an Index in SAP HANA database by using below query: CREATE INDEX IDX_MY_INDEX ON TABLE1 (MY_COLUMN); To know more about SAP HANA database, Modeling, and Administration features, you can refer our SAP HANA Text and Video tutorials: https://www.tutorialspoint.com/sap_hana/ https://www.tutorialspoint.com/sap_hana_online_training/index.asp
[ { "code": null, "e": 1178, "s": 1062, "text": "Note that an index not necessary to be NOT NULL. You can create an Index in SAP HANA database by using below query:" }, { "code": null, "e": 1227, "s": 1178, "text": "CREATE INDEX IDX_MY_INDEX ON TABLE1 (MY_COLUMN);" }, { "code": null, "e": 1357, "s": 1227, "text": "To know more about SAP HANA database, Modeling, and Administration features, you can refer our SAP HANA Text and Video tutorials:" }, { "code": null, "e": 1398, "s": 1357, "text": "https://www.tutorialspoint.com/sap_hana/" }, { "code": null, "e": 1464, "s": 1398, "text": "https://www.tutorialspoint.com/sap_hana_online_training/index.asp" } ]
Difference Between ArrayList and HashMap in Java - GeeksforGeeks
20 Jan, 2022 ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and in order to access a value, one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles. Here we will proceed by discussing common features shared among them. Then we will discuss differences between them by performing sets of operations over both of them in a single Java program and perceiving the differences between the outputs. First, let us discuss the Similarities Between ArrayList and HashMap in Java The ArrayList and HashMap, both are not synchronized. So in order to use them in the multi-threading environment, it needs to be first synchronized. Both ArrayList and HashMap allow null. ArrayList allows null Values and HashMap allows null key and values Both ArrayList and HashMap allow duplicates, ArrayList allows duplicate elements, and HashMap allows duplicate values Both ArrayList and HashMap can be traversed through Iterator in Java. Both Somewhere use an array, ArrayList is backed by an array, and HashMap is also internally implemented by Array Both use get() method, the ArrayList.get() method works based on an index, and HashMap.get() method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched so both provides constant-time performance. By far we get some clarity from the media provided above and now we will be performing sets of operations over them in order to perceive real differences via concluding differences in outputs over the same operation which increases our intellect in understanding the differences between ArrayList and HashMap. Hierarchy alongside syntax Maintenance of insertion order Memory Consumption Duplicates elements handling Ease of fetching an element Null element storage 1. Hierarchy alongside syntax Interface Implemented: ArrayList implements List Interface while HashMap is the implementation of Map interface. Syntax: Declaration of ArrayList Class public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable Syntax: Declaration of HashMap Class public class HashMap extends AbstractMap implements Map, Cloneable, Serializable 2. Maintenance of the Insertion Order ArrayList maintains the insertion order while HashMap does not maintain the insertion order which means ArrayList returns the list items in the same order while HashMap doesn’t maintain any order so returned key-values pairs any kind of order. Example: Java // Java Program to illustrate Maintenance of Insertion Order// in ArrayList vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add("A"); list.add("B"); list.add("C"); list.add("D"); // Invoking ArrayList object System.out.println("ArrayList: " + list); // Creating HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap object created above // using put() method hm.put(1, "A"); hm.put(2, "B"); hm.put(3, "C"); hm.put(4, "D"); // Invoking HashMap object // It might or might not display elements // in the insertion order System.out.print("Hash Map: " + hm); }} ArrayList: [A, B, C, D] HashMap: {1=A, 2=B, 3=C, 4=D} 3. Memory Consumption ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively. Syntax: ArrayList list.add("A"); // String value is stored in ArrayList Syntax: HashMap hm.put(1, "A"); // Two String values stored // as the key value pair in HashMap 4. Duplicates element handling ArrayList allows duplicate elements while HashMap doesn’t allow duplicate keys but does allow duplicate values. Example Java // Java Program to Illustrate Duplicate Elements Insertion// in ArrayList vs HashMap // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add("A"); list.add("B"); // Add duplicates list.add("A"); list.add("A"); // Invoking ArrayList object System.out.println("ArrayList: " + list); // Creating HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, "A"); hm.put(2, "B"); // Add duplicates key // Change value if index exist hm.put(3, "A"); hm.put(3, "A"); // Add duplicates values // allow duplicates value hm.put(4, "A"); hm.put(5, "A"); // Invoking HashMap object System.out.print("HashMap: " + hm); }} ArrayList: [A, B, A, A] HashMap: {1=A, 2=B, 3=A, 4=A, 5=A} 5. Ease of fetching an element In ArrayList, an element can be fetched easily by specifying its index it. But in HashMap, the elements are fetched by their corresponding key. It means that the key must be remembered always. Note: ArrayList get(index) method always gives O(1) time complexity While HashMap get(key) can be O(1) in the best case and O(n) in the worst case time complexity. Example Java // Java Program to Illustrate Ease of fetching an Element// in ArrayList vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add("A"); list.add("B"); list.add("C"); list.add("D"); // Invoking ArrayList object System.out.println("First Element of ArrayList: " + list.get(0)); System.out.println("Third Element of ArrayList: " + list.get(2)); // Creating HashMap // Declaring object of integer and string type HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, "A"); hm.put(2, "B"); hm.put(3, "C"); hm.put(4, "D"); // Invoking HashMap object System.out.println("HashMap value at Key 1: " + hm.get(1)); System.out.println("HashMap value at Key 3: " + hm.get(3)); }} First Element of ArrayList: A Third Element of ArrayList: C HashMap value at Key 1: A HashMap value at Key 3: C 6. Null element storage In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number. Example Java // Java Program to Illustrate Null Element Storage in// Arraylist vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList // using standard add() method list.add("A"); // Adding first null value list.add(null); list.add("C"); // Adding two null value again list.add(null); list.add(null); // Invoking ArrayList object System.out.println("ArrayList: " + list); // Creating HashMap // Declaring object of integer and string type HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, "A"); hm.put(2, "B"); // add null key hm.put(null, "C"); // Again adding null key // which replace value of first // insert null key value hm.put(null, null); // Adding second null value hm.put(3, null); // Printing the elements of Hashmap System.out.println("HashMap: " + hm); }} ArrayList: [A, null, C, null, null] HashMap: {null=null, 1=A, 2=B, 3=null} So, let us figure out the differences between ArrayList and HashMap in a table: ArrayList HashMap simmytarika5 solankimayank clintra Java-ArrayList Java-Collections Java-HashMap Java-List-Programs 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. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Overriding in Java LinkedList in Java Initializing a List in Java
[ { "code": null, "e": 24360, "s": 24332, "text": "\n20 Jan, 2022" }, { "code": null, "e": 24909, "s": 24360, "text": "ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and in order to access a value, one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. " }, { "code": null, "e": 25222, "s": 24909, "text": "Hashing is a technique of converting a large String to a small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles." }, { "code": null, "e": 25466, "s": 25222, "text": "Here we will proceed by discussing common features shared among them. Then we will discuss differences between them by performing sets of operations over both of them in a single Java program and perceiving the differences between the outputs." }, { "code": null, "e": 25543, "s": 25466, "text": "First, let us discuss the Similarities Between ArrayList and HashMap in Java" }, { "code": null, "e": 25692, "s": 25543, "text": "The ArrayList and HashMap, both are not synchronized. So in order to use them in the multi-threading environment, it needs to be first synchronized." }, { "code": null, "e": 25799, "s": 25692, "text": "Both ArrayList and HashMap allow null. ArrayList allows null Values and HashMap allows null key and values" }, { "code": null, "e": 25917, "s": 25799, "text": "Both ArrayList and HashMap allow duplicates, ArrayList allows duplicate elements, and HashMap allows duplicate values" }, { "code": null, "e": 25987, "s": 25917, "text": "Both ArrayList and HashMap can be traversed through Iterator in Java." }, { "code": null, "e": 26101, "s": 25987, "text": "Both Somewhere use an array, ArrayList is backed by an array, and HashMap is also internally implemented by Array" }, { "code": null, "e": 26363, "s": 26101, "text": "Both use get() method, the ArrayList.get() method works based on an index, and HashMap.get() method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched so both provides constant-time performance." }, { "code": null, "e": 26673, "s": 26363, "text": "By far we get some clarity from the media provided above and now we will be performing sets of operations over them in order to perceive real differences via concluding differences in outputs over the same operation which increases our intellect in understanding the differences between ArrayList and HashMap." }, { "code": null, "e": 26700, "s": 26673, "text": "Hierarchy alongside syntax" }, { "code": null, "e": 26731, "s": 26700, "text": "Maintenance of insertion order" }, { "code": null, "e": 26750, "s": 26731, "text": "Memory Consumption" }, { "code": null, "e": 26779, "s": 26750, "text": "Duplicates elements handling" }, { "code": null, "e": 26807, "s": 26779, "text": "Ease of fetching an element" }, { "code": null, "e": 26828, "s": 26807, "text": "Null element storage" }, { "code": null, "e": 26858, "s": 26828, "text": "1. Hierarchy alongside syntax" }, { "code": null, "e": 26971, "s": 26858, "text": "Interface Implemented: ArrayList implements List Interface while HashMap is the implementation of Map interface." }, { "code": null, "e": 27010, "s": 26971, "text": "Syntax: Declaration of ArrayList Class" }, { "code": null, "e": 27111, "s": 27010, "text": "public class ArrayList \nextends AbstractList \nimplements List, RandomAccess, Cloneable, Serializable" }, { "code": null, "e": 27148, "s": 27111, "text": "Syntax: Declaration of HashMap Class" }, { "code": null, "e": 27233, "s": 27148, "text": "public class HashMap \nextends AbstractMap \nimplements Map, Cloneable, Serializable " }, { "code": null, "e": 27271, "s": 27233, "text": "2. Maintenance of the Insertion Order" }, { "code": null, "e": 27515, "s": 27271, "text": "ArrayList maintains the insertion order while HashMap does not maintain the insertion order which means ArrayList returns the list items in the same order while HashMap doesn’t maintain any order so returned key-values pairs any kind of order." }, { "code": null, "e": 27524, "s": 27515, "text": "Example:" }, { "code": null, "e": 27529, "s": 27524, "text": "Java" }, { "code": "// Java Program to illustrate Maintenance of Insertion Order// in ArrayList vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); // Invoking ArrayList object System.out.println(\"ArrayList: \" + list); // Creating HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap object created above // using put() method hm.put(1, \"A\"); hm.put(2, \"B\"); hm.put(3, \"C\"); hm.put(4, \"D\"); // Invoking HashMap object // It might or might not display elements // in the insertion order System.out.print(\"Hash Map: \" + hm); }}", "e": 28567, "s": 27529, "text": null }, { "code": null, "e": 28621, "s": 28567, "text": "ArrayList: [A, B, C, D]\nHashMap: {1=A, 2=B, 3=C, 4=D}" }, { "code": null, "e": 28645, "s": 28623, "text": "3. Memory Consumption" }, { "code": null, "e": 28870, "s": 28645, "text": "ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively." }, { "code": null, "e": 28888, "s": 28870, "text": "Syntax: ArrayList" }, { "code": null, "e": 28942, "s": 28888, "text": "list.add(\"A\");\n// String value is stored in ArrayList" }, { "code": null, "e": 28958, "s": 28942, "text": "Syntax: HashMap" }, { "code": null, "e": 29038, "s": 28958, "text": "hm.put(1, \"A\");\n// Two String values stored\n// as the key value pair in HashMap" }, { "code": null, "e": 29070, "s": 29038, "text": "4. Duplicates element handling " }, { "code": null, "e": 29182, "s": 29070, "text": "ArrayList allows duplicate elements while HashMap doesn’t allow duplicate keys but does allow duplicate values." }, { "code": null, "e": 29190, "s": 29182, "text": "Example" }, { "code": null, "e": 29195, "s": 29190, "text": "Java" }, { "code": "// Java Program to Illustrate Duplicate Elements Insertion// in ArrayList vs HashMap // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add(\"A\"); list.add(\"B\"); // Add duplicates list.add(\"A\"); list.add(\"A\"); // Invoking ArrayList object System.out.println(\"ArrayList: \" + list); // Creating HashMap HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, \"A\"); hm.put(2, \"B\"); // Add duplicates key // Change value if index exist hm.put(3, \"A\"); hm.put(3, \"A\"); // Add duplicates values // allow duplicates value hm.put(4, \"A\"); hm.put(5, \"A\"); // Invoking HashMap object System.out.print(\"HashMap: \" + hm); }}", "e": 30276, "s": 29195, "text": null }, { "code": null, "e": 30335, "s": 30276, "text": "ArrayList: [A, B, A, A]\nHashMap: {1=A, 2=B, 3=A, 4=A, 5=A}" }, { "code": null, "e": 30368, "s": 30337, "text": "5. Ease of fetching an element" }, { "code": null, "e": 30562, "s": 30368, "text": "In ArrayList, an element can be fetched easily by specifying its index it. But in HashMap, the elements are fetched by their corresponding key. It means that the key must be remembered always. " }, { "code": null, "e": 30726, "s": 30562, "text": "Note: ArrayList get(index) method always gives O(1) time complexity While HashMap get(key) can be O(1) in the best case and O(n) in the worst case time complexity." }, { "code": null, "e": 30734, "s": 30726, "text": "Example" }, { "code": null, "e": 30739, "s": 30734, "text": "Java" }, { "code": "// Java Program to Illustrate Ease of fetching an Element// in ArrayList vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); // Invoking ArrayList object System.out.println(\"First Element of ArrayList: \" + list.get(0)); System.out.println(\"Third Element of ArrayList: \" + list.get(2)); // Creating HashMap // Declaring object of integer and string type HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, \"A\"); hm.put(2, \"B\"); hm.put(3, \"C\"); hm.put(4, \"D\"); // Invoking HashMap object System.out.println(\"HashMap value at Key 1: \" + hm.get(1)); System.out.println(\"HashMap value at Key 3: \" + hm.get(3)); }}", "e": 31960, "s": 30739, "text": null }, { "code": null, "e": 32072, "s": 31960, "text": "First Element of ArrayList: A\nThird Element of ArrayList: C\nHashMap value at Key 1: A\nHashMap value at Key 3: C" }, { "code": null, "e": 32098, "s": 32074, "text": "6. Null element storage" }, { "code": null, "e": 32240, "s": 32098, "text": "In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number." }, { "code": null, "e": 32248, "s": 32240, "text": "Example" }, { "code": null, "e": 32253, "s": 32248, "text": "Java" }, { "code": "// Java Program to Illustrate Null Element Storage in// Arraylist vs HashMap // Importing all utility classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating ArrayList of string type ArrayList<String> list = new ArrayList<String>(); // Adding object in ArrayList // using standard add() method list.add(\"A\"); // Adding first null value list.add(null); list.add(\"C\"); // Adding two null value again list.add(null); list.add(null); // Invoking ArrayList object System.out.println(\"ArrayList: \" + list); // Creating HashMap // Declaring object of integer and string type HashMap<Integer, String> hm = new HashMap<Integer, String>(); // Adding object in HashMap hm.put(1, \"A\"); hm.put(2, \"B\"); // add null key hm.put(null, \"C\"); // Again adding null key // which replace value of first // insert null key value hm.put(null, null); // Adding second null value hm.put(3, null); // Printing the elements of Hashmap System.out.println(\"HashMap: \" + hm); }}", "e": 33523, "s": 32253, "text": null }, { "code": null, "e": 33598, "s": 33523, "text": "ArrayList: [A, null, C, null, null]\nHashMap: {null=null, 1=A, 2=B, 3=null}" }, { "code": null, "e": 33680, "s": 33600, "text": "So, let us figure out the differences between ArrayList and HashMap in a table:" }, { "code": null, "e": 33690, "s": 33680, "text": "ArrayList" }, { "code": null, "e": 33698, "s": 33690, "text": "HashMap" }, { "code": null, "e": 33711, "s": 33698, "text": "simmytarika5" }, { "code": null, "e": 33725, "s": 33711, "text": "solankimayank" }, { "code": null, "e": 33733, "s": 33725, "text": "clintra" }, { "code": null, "e": 33748, "s": 33733, "text": "Java-ArrayList" }, { "code": null, "e": 33765, "s": 33748, "text": "Java-Collections" }, { "code": null, "e": 33778, "s": 33765, "text": "Java-HashMap" }, { "code": null, "e": 33797, "s": 33778, "text": "Java-List-Programs" }, { "code": null, "e": 33815, "s": 33797, "text": "Java-Map-Programs" }, { "code": null, "e": 33839, "s": 33815, "text": "Technical Scripter 2018" }, { "code": null, "e": 33844, "s": 33839, "text": "Java" }, { "code": null, "e": 33863, "s": 33844, "text": "Technical Scripter" }, { "code": null, "e": 33868, "s": 33863, "text": "Java" }, { "code": null, "e": 33885, "s": 33868, "text": "Java-Collections" }, { "code": null, "e": 33983, "s": 33885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34015, "s": 33983, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34034, "s": 34015, "text": "Interfaces in Java" }, { "code": null, "e": 34052, "s": 34034, "text": "ArrayList in Java" }, { "code": null, "e": 34084, "s": 34052, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34104, "s": 34084, "text": "Stack Class in Java" }, { "code": null, "e": 34119, "s": 34104, "text": "Stream In Java" }, { "code": null, "e": 34143, "s": 34119, "text": "Singleton Class in Java" }, { "code": null, "e": 34162, "s": 34143, "text": "Overriding in Java" }, { "code": null, "e": 34181, "s": 34162, "text": "LinkedList in Java" } ]
How to change the legend shape using ggplot2 in R?
By default, the shape of legend is circular but we can change it by using the guides function of ggplot2 package. For example, if we have a data frame with two numerical columns say x and y, and one categorical column Group then the scatterplot between x and y for different color values of categories in categorical column Group having different shape of legends can be created by using the below command βˆ’ ggplot(df,aes(x,y,color=Group))+geom_point()+guides(colour=guide_legend(override.aes=list(shape=0))) Here, we can change the shape argument value to any value between starting from 0 to 25. Consider the below data frame βˆ’ Live Demo x<-rpois(20,5) y<-rpois(20,2) Group<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(x,y,Group) df x y Group 1 7 1 Female 2 7 0 Female 3 4 2 Male 4 3 2 Male 5 2 1 Male 6 9 0 Female 7 5 4 Male 8 3 1 Female 9 5 1 Female 10 6 1 Female 11 3 2 Male 12 5 1 Male 13 4 1 Male 14 5 3 Female 15 1 6 Female 16 5 3 Male 17 4 2 Female 18 5 5 Female 19 2 3 Female 20 5 4 Male Loading ggplot2 package and creating scatterplot between x and y with different colors for Group values βˆ’ library(ggplot2) ggplot(df,aes(x,y,color=Group))+geom_point() Creating the scatterplot between x and y with different legend shape βˆ’ ggplot(df,aes(x,y,color=Group))+geom_point()+guides(colour=guide_legend(override.aes=list(shape=17)))
[ { "code": null, "e": 1470, "s": 1062, "text": "By default, the shape of legend is circular but we can change it by using the guides function of ggplot2 package. For example, if we have a data frame with two numerical columns say x and y, and one categorical column Group then the scatterplot between x and y for different color values of categories in categorical column Group having different shape of legends can be created by using the below command βˆ’" }, { "code": null, "e": 1571, "s": 1470, "text": "ggplot(df,aes(x,y,color=Group))+geom_point()+guides(colour=guide_legend(override.aes=list(shape=0)))" }, { "code": null, "e": 1660, "s": 1571, "text": "Here, we can change the shape argument value to any value between starting from 0 to 25." }, { "code": null, "e": 1692, "s": 1660, "text": "Consider the below data frame βˆ’" }, { "code": null, "e": 1703, "s": 1692, "text": " Live Demo" }, { "code": null, "e": 1812, "s": 1703, "text": "x<-rpois(20,5)\ny<-rpois(20,2)\nGroup<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ndf<-data.frame(x,y,Group)\ndf" }, { "code": null, "e": 2129, "s": 1812, "text": " x y Group\n1 7 1 Female\n2 7 0 Female\n3 4 2 Male\n4 3 2 Male\n5 2 1 Male\n6 9 0 Female\n7 5 4 Male\n8 3 1 Female\n9 5 1 Female\n10 6 1 Female\n11 3 2 Male\n12 5 1 Male\n13 4 1 Male\n14 5 3 Female\n15 1 6 Female\n16 5 3 Male\n17 4 2 Female\n18 5 5 Female\n19 2 3 Female\n20 5 4 Male" }, { "code": null, "e": 2235, "s": 2129, "text": "Loading ggplot2 package and creating scatterplot between x and y with different colors for Group values βˆ’" }, { "code": null, "e": 2297, "s": 2235, "text": "library(ggplot2)\nggplot(df,aes(x,y,color=Group))+geom_point()" }, { "code": null, "e": 2368, "s": 2297, "text": "Creating the scatterplot between x and y with different legend shape βˆ’" }, { "code": null, "e": 2470, "s": 2368, "text": "ggplot(df,aes(x,y,color=Group))+geom_point()+guides(colour=guide_legend(override.aes=list(shape=17)))" } ]
Java - String substring() Method
This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given. Here is the syntax of this method βˆ’ public String substring(int beginIndex) Here is the detail of parameters βˆ’ beginIndex βˆ’ the begin index, inclusive. beginIndex βˆ’ the begin index, inclusive. The specified substring. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.substring(10) ); } } This will produce the following result βˆ’ Return Value : Tutorialspoint.com 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": 2624, "s": 2377, "text": "This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given." }, { "code": null, "e": 2660, "s": 2624, "text": "Here is the syntax of this method βˆ’" }, { "code": null, "e": 2701, "s": 2660, "text": "public String substring(int beginIndex)\n" }, { "code": null, "e": 2736, "s": 2701, "text": "Here is the detail of parameters βˆ’" }, { "code": null, "e": 2777, "s": 2736, "text": "beginIndex βˆ’ the begin index, inclusive." }, { "code": null, "e": 2818, "s": 2777, "text": "beginIndex βˆ’ the begin index, inclusive." }, { "code": null, "e": 2843, "s": 2818, "text": "The specified substring." }, { "code": null, "e": 3088, "s": 2843, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.substring(10) );\n\n }\n}" }, { "code": null, "e": 3129, "s": 3088, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 3164, "s": 3129, "text": "Return Value : Tutorialspoint.com\n" }, { "code": null, "e": 3197, "s": 3164, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3213, "s": 3197, "text": " Malhar Lathkar" }, { "code": null, "e": 3246, "s": 3213, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3262, "s": 3246, "text": " Malhar Lathkar" }, { "code": null, "e": 3297, "s": 3262, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3311, "s": 3297, "text": " Anadi Sharma" }, { "code": null, "e": 3345, "s": 3311, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3359, "s": 3345, "text": " Tushar Kale" }, { "code": null, "e": 3396, "s": 3359, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3411, "s": 3396, "text": " Monica Mittal" }, { "code": null, "e": 3444, "s": 3411, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3463, "s": 3444, "text": " Arnab Chakraborty" }, { "code": null, "e": 3470, "s": 3463, "text": " Print" }, { "code": null, "e": 3481, "s": 3470, "text": " Add Notes" } ]
Java - Covariant Method Overriding with Examples - GeeksforGeeks
05 Feb, 2021 The covariant method overriding approach, implemented in Java 5, helps to remove the client-side typecasting by enabling you to return a subtype of the overridden method’s actual return type. Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any function if the return type is changed in the child class. But now it is possible only return type is subtype class. Overriding the Covariant approach provides a way for you to return the subtype of the overridden method’s actual return class. It helps to eliminate the burden of typecasting from the programmer. This method is often used when an object is returned by the overriding method. Let’s have an example to understand it. The function clone() returns the object of the class Object. But since each class is the child of the object class, we will return the object of our own class. Suppose the overriding concept of the Covariant mechanism has not yet been implemented. Then we still need to cast the object. If the cast is not used then β€œObject cannot be converted to Student” error occurs. Example 1: Java // Covariant Method Overriding of Javaimport java.util.ArrayList;// Student classclass Student implements Cloneable { int rollNo; String className; String name; // Getters and setters public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } // Class constructor public Student(int rollNo, String className, String name) { this.rollNo = rollNo; this.className = className; this.name = name; } // Print method public void printData() { System.out.println("Name : " + name + ", RollNo: " + rollNo + ", Class Name : " + className); } // Override the clone method @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }} // Driver codepublic class GFG { public static void main(String arg[]) throws CloneNotSupportedException { // new student object created Student student1 = new Student(1, "MCA", "Kapil"); student1.printData(); // Student object created using clone method // assuming type casting is required Student student2 = (Student)student1.clone(); student2.setName("Sachin"); student2.setRollNo(2); student2.printData(); }} Name : Kapil, RollNo: 1, Class Name : MCA Name : Sachin, RollNo: 2, Class Name : MCA In the above example when we are using the clone() method, it returns the object of Object class, and then we typecast it into Student class. Student student2 = (Student) student1.clone(); Suppose we use the clone method in the program 10 times, so we need to type it each time. We should override the Covariant approach to solve these types of issues. We will return the object of the student class rather than the object class by using the concept of Covariant. Let’s see how we’re going to use it. Example 2: Java // Covariant Method Overriding of Javaimport java.util.ArrayList;// Student classclass Student implements Cloneable { int rollNo; String className; String name; // Getters and setters public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } // Class constructor public Student(int rollNo, String className, String name) { this.rollNo = rollNo; this.className = className; this.name = name; } // Print method public void printData() { System.out.println("Name : " + name + ", RollNo: " + rollNo + ", Class Name : " + className); } // Override the clone method @Override public Student clone() throws CloneNotSupportedException { return (Student) super.clone(); }} // Driver codepublic class GFG { public static void main(String arg[]) throws CloneNotSupportedException { // new student object created Student student1 = new Student(1, "MCA", "Kapil"); student1.printData(); // Student object created using clone method Student student2 = student1.clone(); student2.setName("Sachin"); student2.setRollNo(2); student2.printData(); }} Name : Kapil, RollNo: 1, Class Name : MCA Name : Sachin, RollNo: 2, Class Name : MCA We can see above, since we’re returning a Student class object instead of an Object class, we don’t need to type the object returned from the clone() method into Student. java-overriding Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java HashMap get() Method in Java Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n05 Feb, 2021" }, { "code": null, "e": 24140, "s": 23948, "text": "The covariant method overriding approach, implemented in Java 5, helps to remove the client-side typecasting by enabling you to return a subtype of the overridden method’s actual return type." }, { "code": null, "e": 24416, "s": 24140, "text": "Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any function if the return type is changed in the child class. But now it is possible only return type is subtype class." }, { "code": null, "e": 24691, "s": 24416, "text": "Overriding the Covariant approach provides a way for you to return the subtype of the overridden method’s actual return class. It helps to eliminate the burden of typecasting from the programmer. This method is often used when an object is returned by the overriding method." }, { "code": null, "e": 25101, "s": 24691, "text": "Let’s have an example to understand it. The function clone() returns the object of the class Object. But since each class is the child of the object class, we will return the object of our own class. Suppose the overriding concept of the Covariant mechanism has not yet been implemented. Then we still need to cast the object. If the cast is not used then β€œObject cannot be converted to Student” error occurs." }, { "code": null, "e": 25112, "s": 25101, "text": "Example 1:" }, { "code": null, "e": 25117, "s": 25112, "text": "Java" }, { "code": "// Covariant Method Overriding of Javaimport java.util.ArrayList;// Student classclass Student implements Cloneable { int rollNo; String className; String name; // Getters and setters public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } // Class constructor public Student(int rollNo, String className, String name) { this.rollNo = rollNo; this.className = className; this.name = name; } // Print method public void printData() { System.out.println(\"Name : \" + name + \", RollNo: \" + rollNo + \", Class Name : \" + className); } // Override the clone method @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }} // Driver codepublic class GFG { public static void main(String arg[]) throws CloneNotSupportedException { // new student object created Student student1 = new Student(1, \"MCA\", \"Kapil\"); student1.printData(); // Student object created using clone method // assuming type casting is required Student student2 = (Student)student1.clone(); student2.setName(\"Sachin\"); student2.setRollNo(2); student2.printData(); }}", "e": 26740, "s": 25117, "text": null }, { "code": null, "e": 26826, "s": 26740, "text": "Name : Kapil, RollNo: 1, Class Name : MCA\nName : Sachin, RollNo: 2, Class Name : MCA\n" }, { "code": null, "e": 26968, "s": 26826, "text": "In the above example when we are using the clone() method, it returns the object of Object class, and then we typecast it into Student class." }, { "code": null, "e": 27015, "s": 26968, "text": "Student student2 = (Student) student1.clone();" }, { "code": null, "e": 27290, "s": 27015, "text": "Suppose we use the clone method in the program 10 times, so we need to type it each time. We should override the Covariant approach to solve these types of issues. We will return the object of the student class rather than the object class by using the concept of Covariant." }, { "code": null, "e": 27327, "s": 27290, "text": "Let’s see how we’re going to use it." }, { "code": null, "e": 27338, "s": 27327, "text": "Example 2:" }, { "code": null, "e": 27343, "s": 27338, "text": "Java" }, { "code": "// Covariant Method Overriding of Javaimport java.util.ArrayList;// Student classclass Student implements Cloneable { int rollNo; String className; String name; // Getters and setters public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } // Class constructor public Student(int rollNo, String className, String name) { this.rollNo = rollNo; this.className = className; this.name = name; } // Print method public void printData() { System.out.println(\"Name : \" + name + \", RollNo: \" + rollNo + \", Class Name : \" + className); } // Override the clone method @Override public Student clone() throws CloneNotSupportedException { return (Student) super.clone(); }} // Driver codepublic class GFG { public static void main(String arg[]) throws CloneNotSupportedException { // new student object created Student student1 = new Student(1, \"MCA\", \"Kapil\"); student1.printData(); // Student object created using clone method Student student2 = student1.clone(); student2.setName(\"Sachin\"); student2.setRollNo(2); student2.printData(); }}", "e": 28924, "s": 27343, "text": null }, { "code": null, "e": 29010, "s": 28924, "text": "Name : Kapil, RollNo: 1, Class Name : MCA\nName : Sachin, RollNo: 2, Class Name : MCA\n" }, { "code": null, "e": 29181, "s": 29010, "text": "We can see above, since we’re returning a Student class object instead of an Object class, we don’t need to type the object returned from the clone() method into Student." }, { "code": null, "e": 29197, "s": 29181, "text": "java-overriding" }, { "code": null, "e": 29204, "s": 29197, "text": "Picked" }, { "code": null, "e": 29209, "s": 29204, "text": "Java" }, { "code": null, "e": 29214, "s": 29209, "text": "Java" }, { "code": null, "e": 29312, "s": 29214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29327, "s": 29312, "text": "Stream In Java" }, { "code": null, "e": 29348, "s": 29327, "text": "Constructors in Java" }, { "code": null, "e": 29394, "s": 29348, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29413, "s": 29394, "text": "Exceptions in Java" }, { "code": null, "e": 29443, "s": 29413, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29460, "s": 29443, "text": "Generics in Java" }, { "code": null, "e": 29503, "s": 29460, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29524, "s": 29503, "text": "Introduction to Java" }, { "code": null, "e": 29553, "s": 29524, "text": "HashMap get() Method in Java" } ]
Classification Algorithms - Logistic Regression
Logistic regression is a supervised learning classification algorithm used to predict the probability of a target variable. The nature of target or dependent variable is dichotomous, which means there would be only two possible classes. In simple words, the dependent variable is binary in nature having data coded as either 1 (stands for success/yes) or 0 (stands for failure/no). Mathematically, a logistic regression model predicts P(Y=1) as a function of X. It is one of the simplest ML algorithms that can be used for various classification problems such as spam detection, Diabetes prediction, cancer detection etc. Generally, logistic regression means binary logistic regression having binary target variables, but there can be two more categories of target variables that can be predicted by it. Based on those number of categories, Logistic regression can be divided into following types βˆ’ In such a kind of classification, a dependent variable will have only two possible types either 1 and 0. For example, these variables may represent success or failure, yes or no, win or loss etc. In such a kind of classification, dependent variable can have 3 or more possible unordered types or the types having no quantitative significance. For example, these variables may represent β€œType A” or β€œType B” or β€œType C”. In such a kind of classification, dependent variable can have 3 or more possible ordered types or the types having a quantitative significance. For example, these variables may represent β€œpoor” or β€œgood”, β€œvery good”, β€œExcellent” and each category can have the scores like 0,1,2,3. Before diving into the implementation of logistic regression, we must be aware of the following assumptions about the same βˆ’ In case of binary logistic regression, the target variables must be binary always and the desired outcome is represented by the factor level 1. In case of binary logistic regression, the target variables must be binary always and the desired outcome is represented by the factor level 1. There should not be any multi-collinearity in the model, which means the independent variables must be independent of each other . There should not be any multi-collinearity in the model, which means the independent variables must be independent of each other . We must include meaningful variables in our model. We must include meaningful variables in our model. We should choose a large sample size for logistic regression. We should choose a large sample size for logistic regression. The simplest form of logistic regression is binary or binomial logistic regression in which the target or dependent variable can have only 2 possible types either 1 or 0. It allows us to model a relationship between multiple predictor variables and a binary/binomial target variable. In case of logistic regression, the linear function is basically used as an input to another function such as g in the following relation βˆ’ Here, g is the logistic or sigmoid function which can be given as follows βˆ’ To sigmoid curve can be represented with the help of following graph. We can see the values of y-axis lie between 0 and 1 and crosses the axis at 0.5. The classes can be divided into positive or negative. The output comes under the probability of positive class if it lies between 0 and 1. For our implementation, we are interpreting the output of hypothesis function as positive if it is β‰₯0.5, otherwise negative. We also need to define a loss function to measure how well the algorithm performs using the weights on functions, represented by theta as follows βˆ’ h=g(XΞΈ) Now, after defining the loss function our prime goal is to minimize the loss function. It can be done with the help of fitting the weights which means by increasing or decreasing the weights. With the help of derivatives of the loss function w.r.t each weight, we would be able to know what parameters should have high weight and what should have smaller weight. The following gradient descent equation tells us how loss would change if we modified the parameters βˆ’ Now we will implement the above concept of binomial logistic regression in Python. For this purpose, we are using a multivariate flower dataset named β€˜iris’ which have 3 classes of 50 instances each, but we will be using the first two feature columns. Every class represents a type of iris flower. First, we need to import the necessary libraries as follows βˆ’ import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets Next, load the iris dataset as follows βˆ’ iris = datasets.load_iris() X = iris.data[:, :2] y = (iris.target != 0) * 1 We can plot our training data s follows βˆ’ plt.figure(figsize=(6, 6)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='g', label='0') plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='y', label='1') plt.legend(); Next, we will define sigmoid function, loss function and gradient descend as follows βˆ’ class LogisticRegression: def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False): self.lr = lr self.num_iter = num_iter self.fit_intercept = fit_intercept self.verbose = verbose def __add_intercept(self, X): intercept = np.ones((X.shape[0], 1)) return np.concatenate((intercept, X), axis=1) def __sigmoid(self, z): return 1 / (1 + np.exp(-z)) def __loss(self, h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def fit(self, X, y): if self.fit_intercept: X = self.__add_intercept(X) Now, initialize the weights as follows βˆ’ self.theta = np.zeros(X.shape[1]) for i in range(self.num_iter): z = np.dot(X, self.theta) h = self.__sigmoid(z) gradient = np.dot(X.T, (h - y)) / y.size self.theta -= self.lr * gradient z = np.dot(X, self.theta) h = self.__sigmoid(z) loss = self.__loss(h, y) if(self.verbose ==True and i % 10000 == 0): print(f'loss: {loss} \t') With the help of the following script, we can predict the output probabilities βˆ’ def predict_prob(self, X): if self.fit_intercept: X = self.__add_intercept(X) return self.__sigmoid(np.dot(X, self.theta)) def predict(self, X): return self.predict_prob(X).round() Next, we can evaluate the model and plot it as follows βˆ’ model = LogisticRegression(lr=0.1, num_iter=300000) preds = model.predict(X) (preds == y).mean() plt.figure(figsize=(10, 6)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='g', label='0') plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='y', label='1') plt.legend() x1_min, x1_max = X[:,0].min(), X[:,0].max(), x2_min, x2_max = X[:,1].min(), X[:,1].max(), xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = model.predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='red'); Another useful form of logistic regression is multinomial logistic regression in which the target or dependent variable can have 3 or more possible unordered types i.e. the types having no quantitative significance. Now we will implement the above concept of multinomial logistic regression in Python. For this purpose, we are using a dataset from sklearn named digit. First, we need to import the necessary libraries as follows βˆ’ Import sklearn from sklearn import datasets from sklearn import linear_model from sklearn import metrics from sklearn.model_selection import train_test_split Next, we need to load digit dataset βˆ’ digits = datasets.load_digits() Now, define the feature matrix(X) and response vector(y)as follows βˆ’ X = digits.data y = digits.target With the help of next line of code, we can split X and y into training and testing sets βˆ’ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) Now create an object of logistic regression as follows βˆ’ digreg = linear_model.LogisticRegression() Now, we need to train the model by using the training sets as follows βˆ’ digreg.fit(X_train, y_train) Next, make the predictions on testing set as follows βˆ’ y_pred = digreg.predict(X_test) Next print the accuracy of the model as follows βˆ’ print("Accuracy of Logistic Regression model is:", metrics.accuracy_score(y_test, y_pred)*100) Accuracy of Logistic Regression model is: 95.6884561891516 From the above output we can see the accuracy of our model is around 96 percent. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2541, "s": 2304, "text": "Logistic regression is a supervised learning classification algorithm used to predict the probability of a target variable. The nature of target or dependent variable is dichotomous, which means there would be only two possible classes." }, { "code": null, "e": 2686, "s": 2541, "text": "In simple words, the dependent variable is binary in nature having data coded as either 1 (stands for success/yes) or 0 (stands for failure/no)." }, { "code": null, "e": 2926, "s": 2686, "text": "Mathematically, a logistic regression model predicts P(Y=1) as a function of X. It is one of the simplest ML algorithms that can be used for various classification problems such as spam detection, Diabetes prediction, cancer detection etc." }, { "code": null, "e": 3203, "s": 2926, "text": "Generally, logistic regression means binary logistic regression having binary target variables, but there can be two more categories of target variables that can be predicted by it. Based on those number of categories, Logistic regression can be divided into following types βˆ’" }, { "code": null, "e": 3399, "s": 3203, "text": "In such a kind of classification, a dependent variable will have only two possible types either 1 and 0. For example, these variables may represent success or failure, yes or no, win or loss etc." }, { "code": null, "e": 3623, "s": 3399, "text": "In such a kind of classification, dependent variable can have 3 or more possible unordered types or the types having no quantitative significance. For example, these variables may represent β€œType A” or β€œType B” or β€œType C”." }, { "code": null, "e": 3905, "s": 3623, "text": "In such a kind of classification, dependent variable can have 3 or more possible ordered types or the types having a quantitative significance. For example, these variables may represent β€œpoor” or β€œgood”, β€œvery good”, β€œExcellent” and each category can have the scores like 0,1,2,3." }, { "code": null, "e": 4030, "s": 3905, "text": "Before diving into the implementation of logistic regression, we must be aware of the following assumptions about the same βˆ’" }, { "code": null, "e": 4174, "s": 4030, "text": "In case of binary logistic regression, the target variables must be binary always and the desired outcome is represented by the factor level 1." }, { "code": null, "e": 4318, "s": 4174, "text": "In case of binary logistic regression, the target variables must be binary always and the desired outcome is represented by the factor level 1." }, { "code": null, "e": 4449, "s": 4318, "text": "There should not be any multi-collinearity in the model, which means the independent variables must be independent of each other ." }, { "code": null, "e": 4580, "s": 4449, "text": "There should not be any multi-collinearity in the model, which means the independent variables must be independent of each other ." }, { "code": null, "e": 4631, "s": 4580, "text": "We must include meaningful variables in our model." }, { "code": null, "e": 4682, "s": 4631, "text": "We must include meaningful variables in our model." }, { "code": null, "e": 4744, "s": 4682, "text": "We should choose a large sample size for logistic regression." }, { "code": null, "e": 4806, "s": 4744, "text": "We should choose a large sample size for logistic regression." }, { "code": null, "e": 5230, "s": 4806, "text": "The simplest form of logistic regression is binary or binomial logistic regression in which the target or dependent variable can have only 2 possible types either 1 or 0. It allows us to model a relationship between multiple predictor variables and a binary/binomial target variable. In case of logistic regression, the linear function is basically used as an input to another function such as g in the following relation βˆ’" }, { "code": null, "e": 5306, "s": 5230, "text": "Here, g is the logistic or sigmoid function which can be given as follows βˆ’" }, { "code": null, "e": 5457, "s": 5306, "text": "To sigmoid curve can be represented with the help of following graph. We can see the values of y-axis lie between 0 and 1 and crosses the axis at 0.5." }, { "code": null, "e": 5721, "s": 5457, "text": "The classes can be divided into positive or negative. The output comes under the probability of positive class if it lies between 0 and 1. For our implementation, we are interpreting the output of hypothesis function as positive if it is β‰₯0.5, otherwise negative." }, { "code": null, "e": 5869, "s": 5721, "text": "We also need to define a loss function to measure how well the algorithm performs using the weights on functions, represented by theta as follows βˆ’" }, { "code": null, "e": 5877, "s": 5869, "text": "h=g(XΞΈ)" }, { "code": null, "e": 6240, "s": 5877, "text": "Now, after defining the loss function our prime goal is to minimize the loss function. It can be done with the help of fitting the weights which means by increasing or decreasing the weights. With the help of derivatives of the loss function w.r.t each weight, we would be able to know what parameters should have high weight and what should have smaller weight." }, { "code": null, "e": 6343, "s": 6240, "text": "The following gradient descent equation tells us how loss would change if we modified the parameters βˆ’" }, { "code": null, "e": 6641, "s": 6343, "text": "Now we will implement the above concept of binomial logistic regression in Python. For this purpose, we are using a multivariate flower dataset named β€˜iris’ which have 3 classes of 50 instances each, but we will be using the first two feature columns. Every class represents a type of iris flower." }, { "code": null, "e": 6703, "s": 6641, "text": "First, we need to import the necessary libraries as follows βˆ’" }, { "code": null, "e": 6805, "s": 6703, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import datasets" }, { "code": null, "e": 6846, "s": 6805, "text": "Next, load the iris dataset as follows βˆ’" }, { "code": null, "e": 6923, "s": 6846, "text": "iris = datasets.load_iris()\nX = iris.data[:, :2]\ny = (iris.target != 0) * 1\n" }, { "code": null, "e": 6965, "s": 6923, "text": "We can plot our training data s follows βˆ’" }, { "code": null, "e": 7143, "s": 6965, "text": "plt.figure(figsize=(6, 6))\nplt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='g', label='0')\nplt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='y', label='1')\nplt.legend();\n" }, { "code": null, "e": 7230, "s": 7143, "text": "Next, we will define sigmoid function, loss function and gradient descend as follows βˆ’" }, { "code": null, "e": 7829, "s": 7230, "text": "class LogisticRegression:\n def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):\n self.lr = lr\n self.num_iter = num_iter\n self.fit_intercept = fit_intercept\n self.verbose = verbose\n def __add_intercept(self, X):\n intercept = np.ones((X.shape[0], 1))\n return np.concatenate((intercept, X), axis=1)\n def __sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n def __loss(self, h, y):\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()\n def fit(self, X, y):\n if self.fit_intercept:\n X = self.__add_intercept(X)" }, { "code": null, "e": 7870, "s": 7829, "text": "Now, initialize the weights as follows βˆ’" }, { "code": null, "e": 8260, "s": 7870, "text": "self.theta = np.zeros(X.shape[1])\n for i in range(self.num_iter):\n z = np.dot(X, self.theta)\n h = self.__sigmoid(z)\n gradient = np.dot(X.T, (h - y)) / y.size\n self.theta -= self.lr * gradient\n z = np.dot(X, self.theta)\n h = self.__sigmoid(z)\n loss = self.__loss(h, y)\n if(self.verbose ==True and i % 10000 == 0):\n print(f'loss: {loss} \\t')" }, { "code": null, "e": 8341, "s": 8260, "text": "With the help of the following script, we can predict the output probabilities βˆ’" }, { "code": null, "e": 8537, "s": 8341, "text": "def predict_prob(self, X):\n if self.fit_intercept:\n X = self.__add_intercept(X)\n return self.__sigmoid(np.dot(X, self.theta))\ndef predict(self, X):\n return self.predict_prob(X).round()" }, { "code": null, "e": 8594, "s": 8537, "text": "Next, we can evaluate the model and plot it as follows βˆ’" }, { "code": null, "e": 9196, "s": 8594, "text": "model = LogisticRegression(lr=0.1, num_iter=300000)\npreds = model.predict(X)\n(preds == y).mean()\n\nplt.figure(figsize=(10, 6))\nplt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='g', label='0')\nplt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='y', label='1')\nplt.legend()\nx1_min, x1_max = X[:,0].min(), X[:,0].max(),\nx2_min, x2_max = X[:,1].min(), X[:,1].max(),\nxx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))\ngrid = np.c_[xx1.ravel(), xx2.ravel()]\nprobs = model.predict_prob(grid).reshape(xx1.shape)\nplt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='red');" }, { "code": null, "e": 9412, "s": 9196, "text": "Another useful form of logistic regression is multinomial logistic regression in which the target or dependent variable can have 3 or more possible unordered types i.e. the types having no quantitative significance." }, { "code": null, "e": 9565, "s": 9412, "text": "Now we will implement the above concept of multinomial logistic regression in Python. For this purpose, we are using a dataset from sklearn named digit." }, { "code": null, "e": 9627, "s": 9565, "text": "First, we need to import the necessary libraries as follows βˆ’" }, { "code": null, "e": 9785, "s": 9627, "text": "Import sklearn\nfrom sklearn import datasets\nfrom sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 9823, "s": 9785, "text": "Next, we need to load digit dataset βˆ’" }, { "code": null, "e": 9856, "s": 9823, "text": "digits = datasets.load_digits()\n" }, { "code": null, "e": 9925, "s": 9856, "text": "Now, define the feature matrix(X) and response vector(y)as follows βˆ’" }, { "code": null, "e": 9960, "s": 9925, "text": "X = digits.data\ny = digits.target\n" }, { "code": null, "e": 10050, "s": 9960, "text": "With the help of next line of code, we can split X and y into training and testing sets βˆ’" }, { "code": null, "e": 10140, "s": 10050, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)\n" }, { "code": null, "e": 10197, "s": 10140, "text": "Now create an object of logistic regression as follows βˆ’" }, { "code": null, "e": 10241, "s": 10197, "text": "digreg = linear_model.LogisticRegression()\n" }, { "code": null, "e": 10313, "s": 10241, "text": "Now, we need to train the model by using the training sets as follows βˆ’" }, { "code": null, "e": 10343, "s": 10313, "text": "digreg.fit(X_train, y_train)\n" }, { "code": null, "e": 10398, "s": 10343, "text": "Next, make the predictions on testing set as follows βˆ’" }, { "code": null, "e": 10431, "s": 10398, "text": "y_pred = digreg.predict(X_test)\n" }, { "code": null, "e": 10481, "s": 10431, "text": "Next print the accuracy of the model as follows βˆ’" }, { "code": null, "e": 10577, "s": 10481, "text": "print(\"Accuracy of Logistic Regression model is:\",\nmetrics.accuracy_score(y_test, y_pred)*100)\n" }, { "code": null, "e": 10637, "s": 10577, "text": "Accuracy of Logistic Regression model is: 95.6884561891516\n" }, { "code": null, "e": 10718, "s": 10637, "text": "From the above output we can see the accuracy of our model is around 96 percent." }, { "code": null, "e": 10755, "s": 10718, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 10778, "s": 10755, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 10814, "s": 10778, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 10842, "s": 10814, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10876, "s": 10842, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 10893, "s": 10876, "text": " Abhilash Nelson" }, { "code": null, "e": 10926, "s": 10893, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 10948, "s": 10926, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10981, "s": 10948, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 11003, "s": 10981, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11036, "s": 11003, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 11058, "s": 11036, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11065, "s": 11058, "text": " Print" }, { "code": null, "e": 11076, "s": 11065, "text": " Add Notes" } ]
How to extract date from text using Python regular expression?
The following code using Python regex extracts the date from given string import datetime from datetime import date import re s = "Jason's birthday is on 1991-09-21" match = re.search(r'\d{4}-\d{2}-\d{2}', s) date = datetime.datetime.strptime(match.group(), '%Y-%m-%d').date() print date This gives the output 1991-09-21
[ { "code": null, "e": 1136, "s": 1062, "text": "The following code using Python regex extracts the date from given string" }, { "code": null, "e": 1350, "s": 1136, "text": "import datetime\nfrom datetime import date\nimport re\ns = \"Jason's birthday is on 1991-09-21\"\nmatch = re.search(r'\\d{4}-\\d{2}-\\d{2}', s)\ndate = datetime.datetime.strptime(match.group(), '%Y-%m-%d').date()\nprint date" }, { "code": null, "e": 1372, "s": 1350, "text": "This gives the output" }, { "code": null, "e": 1383, "s": 1372, "text": "1991-09-21" } ]
EJB - Packaging Applications
Requirement of Packaging applications using EJB 3.0 are similar to that of J2EE platform. EJB components are packaged into modules as jar files and are packaged into application enterprise archive as ear file. There are majorly three components of any enterprise application βˆ’ jar βˆ’ Java Application aRchive, containing EJB modules, EJB client modules and utility modules. jar βˆ’ Java Application aRchive, containing EJB modules, EJB client modules and utility modules. war βˆ’ Web Application aRchive, containing web modules. war βˆ’ Web Application aRchive, containing web modules. ear βˆ’ Enterprise Application aRchive, containing jars and war module. ear βˆ’ Enterprise Application aRchive, containing jars and war module. In NetBeans, it is very easy to create, develop, package, and deploy the J2EE applications. In NetBeans IDE, select ,File > New Project >.Select project type under category,Java EE, Project type as Enterprise Application. Click Next > button. Enter project name and location. Click Finish > button. We've chosen name as EnterpriseApplicaton. Select Server and Settings. Keep Create EJB Module and Create Web Application Module checked with default names provided. Click finish button. NetBeans will create the following structure in project window. Right click on the Project Enterprise Application in project explorer and select Build. ant -f D:\\SVN\\EnterpriseApplication dist pre-init: init-private: init-userdir: init-user: init-project: do-init: post-init: init-check: init: deps-jar: deps-j2ee-archive: EnterpriseApplication-ejb.init: EnterpriseApplication-ejb.deps-jar: EnterpriseApplication-ejb.compile: EnterpriseApplication-ejb.library-inclusion-in-manifest: Building jar: D:\SVN\EnterpriseApplication\EnterpriseApplication-ejb\dist\EnterpriseApplication-ejb.jar EnterpriseApplication-ejb.dist-ear: EnterpriseApplication-war.init: EnterpriseApplication-war.deps-module-jar: EnterpriseApplication-war.deps-ear-jar: EnterpriseApplication-ejb.init: EnterpriseApplication-ejb.deps-jar: EnterpriseApplication-ejb.compile: EnterpriseApplication-ejb.library-inclusion-in-manifest: EnterpriseApplication-ejb.dist-ear: EnterpriseApplication-war.deps-jar: EnterpriseApplication-war.library-inclusion-in-archive: EnterpriseApplication-war.library-inclusion-in-manifest: EnterpriseApplication-war.compile: EnterpriseApplication-war.compile-jsps: EnterpriseApplication-war.do-ear-dist: Building jar: D:\SVN\EnterpriseApplication\EnterpriseApplication-war\dist\EnterpriseApplication-war.war EnterpriseApplication-war.dist-ear: pre-pre-compile: pre-compile: Copying 1 file to D:\SVN\EnterpriseApplication\build Copying 1 file to D:\SVN\EnterpriseApplication\build do-compile: post-compile: compile: pre-dist: do-dist-without-manifest: do-dist-with-manifest: Building jar: D:\SVN\EnterpriseApplication\dist\EnterpriseApplication.ear post-dist: dist: BUILD SUCCESSFUL (total time: 1 second) Here you can see, that Netbeans prepares Jar first, then War and in the end, the ear file carrying the jar and war, file. Each jar,war and ear file carries a meta-inf folder to have meta data as per the J2EE specification. Print Add Notes Bookmark this page
[ { "code": null, "e": 2257, "s": 2047, "text": "Requirement of Packaging applications using EJB 3.0 are similar to that of J2EE platform. EJB components are packaged into modules as jar files and are packaged into application enterprise archive as ear file." }, { "code": null, "e": 2324, "s": 2257, "text": "There are majorly three components of any enterprise application βˆ’" }, { "code": null, "e": 2420, "s": 2324, "text": "jar βˆ’ Java Application aRchive, containing EJB modules, EJB client modules and utility modules." }, { "code": null, "e": 2516, "s": 2420, "text": "jar βˆ’ Java Application aRchive, containing EJB modules, EJB client modules and utility modules." }, { "code": null, "e": 2571, "s": 2516, "text": "war βˆ’ Web Application aRchive, containing web modules." }, { "code": null, "e": 2626, "s": 2571, "text": "war βˆ’ Web Application aRchive, containing web modules." }, { "code": null, "e": 2696, "s": 2626, "text": "ear βˆ’ Enterprise Application aRchive, containing jars and war module." }, { "code": null, "e": 2766, "s": 2696, "text": "ear βˆ’ Enterprise Application aRchive, containing jars and war module." }, { "code": null, "e": 2858, "s": 2766, "text": "In NetBeans, it is very easy to create, develop, package, and deploy the J2EE applications." }, { "code": null, "e": 3108, "s": 2858, "text": "In NetBeans IDE, select ,File > New Project >.Select project type under category,Java EE, Project type as Enterprise Application. Click Next > button. Enter project name and location. Click Finish > button. We've chosen name as EnterpriseApplicaton." }, { "code": null, "e": 3315, "s": 3108, "text": "Select Server and Settings. Keep Create EJB Module and Create Web Application Module checked with default names provided. Click finish button. NetBeans will create the following structure in project window." }, { "code": null, "e": 3403, "s": 3315, "text": "Right click on the Project Enterprise Application in project explorer and select Build." }, { "code": null, "e": 4957, "s": 3403, "text": "ant -f D:\\\\SVN\\\\EnterpriseApplication dist\npre-init:\ninit-private:\ninit-userdir:\ninit-user:\ninit-project:\ndo-init:\npost-init:\ninit-check:\ninit:\ndeps-jar:\ndeps-j2ee-archive:\nEnterpriseApplication-ejb.init:\nEnterpriseApplication-ejb.deps-jar:\nEnterpriseApplication-ejb.compile:\nEnterpriseApplication-ejb.library-inclusion-in-manifest:\n\nBuilding jar: D:\\SVN\\EnterpriseApplication\\EnterpriseApplication-ejb\\dist\\EnterpriseApplication-ejb.jar\n\nEnterpriseApplication-ejb.dist-ear:\nEnterpriseApplication-war.init:\nEnterpriseApplication-war.deps-module-jar:\nEnterpriseApplication-war.deps-ear-jar:\nEnterpriseApplication-ejb.init:\nEnterpriseApplication-ejb.deps-jar:\nEnterpriseApplication-ejb.compile:\nEnterpriseApplication-ejb.library-inclusion-in-manifest:\nEnterpriseApplication-ejb.dist-ear:\nEnterpriseApplication-war.deps-jar:\nEnterpriseApplication-war.library-inclusion-in-archive:\nEnterpriseApplication-war.library-inclusion-in-manifest:\nEnterpriseApplication-war.compile:\nEnterpriseApplication-war.compile-jsps:\nEnterpriseApplication-war.do-ear-dist:\n\nBuilding jar: D:\\SVN\\EnterpriseApplication\\EnterpriseApplication-war\\dist\\EnterpriseApplication-war.war\n\nEnterpriseApplication-war.dist-ear:\npre-pre-compile:\npre-compile:\nCopying 1 file to D:\\SVN\\EnterpriseApplication\\build\nCopying 1 file to D:\\SVN\\EnterpriseApplication\\build\ndo-compile:\npost-compile:\ncompile:\npre-dist:\ndo-dist-without-manifest:\ndo-dist-with-manifest:\n\nBuilding jar: D:\\SVN\\EnterpriseApplication\\dist\\EnterpriseApplication.ear\n\npost-dist:\ndist:\nBUILD SUCCESSFUL (total time: 1 second)" }, { "code": null, "e": 5180, "s": 4957, "text": "Here you can see, that Netbeans prepares Jar first, then War and in the end, the ear file carrying the jar and war, file. Each jar,war and ear file carries a meta-inf folder to have meta data as per the J2EE specification." }, { "code": null, "e": 5187, "s": 5180, "text": " Print" }, { "code": null, "e": 5198, "s": 5187, "text": " Add Notes" } ]
Deep dive into Parameters and Arguments in Python - GeeksforGeeks
24 Oct, 2020 There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Example: Python3 # Here a,b are the parametersdef sum(a,b): print(a+b) sum(1,2) Output: 3 An argument is a value that is passed to a function when it is called. It might be a variable, value or object passed to a function or method as input. They are written when we are calling the function. Example: Python3 def sum(a,b): print(a+b) # Here the values 1,2 are argumentssum(1,2) Output: 3 Python functions can contain two types of arguments: Positional Arguments Keyword Arguments Positional Arguments are needed to be included in proper order i.e the first argument is always listed first when the function is called, second argument needs to be called second and so on. Example: Python3 def person_name(first_name,second_name): print(first_name+second_name) # First name is Ram placed first# Second name is Babu place secondperson_name("Ram","Babu") Output: RamBabu Keyword Arguments is an argument passed to a function or method which is preceded by a keyword and an equal to sign. The order of keyword argument with respect to another keyword argument does not matter because the values are being explicitly assigned. Python3 def person_name(first_name,second_name): print(first_name+second_name) # Here we are explicitly assigning the values person_name(second_name="Babu",first_name="Ram") Output: RamBabu Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n24 Oct, 2020" }, { "code": null, "e": 24511, "s": 24316, "text": "There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively." }, { "code": null, "e": 24651, "s": 24511, "text": "A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. " }, { "code": null, "e": 24660, "s": 24651, "text": "Example:" }, { "code": null, "e": 24668, "s": 24660, "text": "Python3" }, { "code": "# Here a,b are the parametersdef sum(a,b): print(a+b) sum(1,2)", "e": 24735, "s": 24668, "text": null }, { "code": null, "e": 24743, "s": 24735, "text": "Output:" }, { "code": null, "e": 24746, "s": 24743, "text": "3\n" }, { "code": null, "e": 24949, "s": 24746, "text": "An argument is a value that is passed to a function when it is called. It might be a variable, value or object passed to a function or method as input. They are written when we are calling the function." }, { "code": null, "e": 24958, "s": 24949, "text": "Example:" }, { "code": null, "e": 24966, "s": 24958, "text": "Python3" }, { "code": "def sum(a,b): print(a+b) # Here the values 1,2 are argumentssum(1,2)", "e": 25039, "s": 24966, "text": null }, { "code": null, "e": 25047, "s": 25039, "text": "Output:" }, { "code": null, "e": 25050, "s": 25047, "text": "3\n" }, { "code": null, "e": 25103, "s": 25050, "text": "Python functions can contain two types of arguments:" }, { "code": null, "e": 25124, "s": 25103, "text": "Positional Arguments" }, { "code": null, "e": 25142, "s": 25124, "text": "Keyword Arguments" }, { "code": null, "e": 25333, "s": 25142, "text": "Positional Arguments are needed to be included in proper order i.e the first argument is always listed first when the function is called, second argument needs to be called second and so on." }, { "code": null, "e": 25342, "s": 25333, "text": "Example:" }, { "code": null, "e": 25350, "s": 25342, "text": "Python3" }, { "code": "def person_name(first_name,second_name): print(first_name+second_name) # First name is Ram placed first# Second name is Babu place secondperson_name(\"Ram\",\"Babu\")", "e": 25517, "s": 25350, "text": null }, { "code": null, "e": 25525, "s": 25517, "text": "Output:" }, { "code": null, "e": 25534, "s": 25525, "text": "RamBabu\n" }, { "code": null, "e": 25788, "s": 25534, "text": "Keyword Arguments is an argument passed to a function or method which is preceded by a keyword and an equal to sign. The order of keyword argument with respect to another keyword argument does not matter because the values are being explicitly assigned." }, { "code": null, "e": 25796, "s": 25788, "text": "Python3" }, { "code": "def person_name(first_name,second_name): print(first_name+second_name) # Here we are explicitly assigning the values person_name(second_name=\"Babu\",first_name=\"Ram\")", "e": 25964, "s": 25796, "text": null }, { "code": null, "e": 25972, "s": 25964, "text": "Output:" }, { "code": null, "e": 25981, "s": 25972, "text": "RamBabu\n" }, { "code": null, "e": 25998, "s": 25981, "text": "Python-Functions" }, { "code": null, "e": 26005, "s": 25998, "text": "Python" }, { "code": null, "e": 26103, "s": 26005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26135, "s": 26103, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26177, "s": 26135, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26233, "s": 26177, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26275, "s": 26233, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26330, "s": 26275, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26361, "s": 26330, "text": "Python | os.path.join() method" }, { "code": null, "e": 26383, "s": 26361, "text": "Defaultdict in Python" }, { "code": null, "e": 26412, "s": 26383, "text": "Create a directory in Python" }, { "code": null, "e": 26451, "s": 26412, "text": "Python | Get unique values from a list" } ]
Find all close matches of input string from a list in Python
Suppose we are given a word and we want to find its closest matches. Not an exact match but other words which have some close resemblance in pattern with the given word. For this we use a module called difflib and use its method named get_close_matches. This method is part of the module difflib and gives us the match with possible patterns which we specify. Below is the syntax. difflib.get_close_matches(word, possibilities, n, cutoff) word: It is the word to which we need to find the match. Possibilities: This is the patterns which will be compared for matching. n: Maximum number of close matches to return. Should be greater than 0. Cutoff: The possibilities that do not score this float value between 0 and 1 are ignored. Running the above code gives us the following result βˆ’ In the below example we take a word and also a list of possibilities or patterns that need to be compared. Then we apply the method to get the result needed. Live Demo from difflib import get_close_matches word = 'banana' patterns = ['ana', 'nana', 'ban', 'ran','tan'] print('matched words:',get_close_matches(word, patterns)) Running the above code gives us the following result βˆ’ matched words: ['nana', 'ban', 'ana']
[ { "code": null, "e": 1316, "s": 1062, "text": "Suppose we are given a word and we want to find its closest matches. Not an exact match but other words which have some close resemblance in pattern with the given word. For this we use a module called difflib and use its method named get_close_matches." }, { "code": null, "e": 1443, "s": 1316, "text": "This method is part of the module difflib and gives us the match with possible patterns which we specify. Below is the syntax." }, { "code": null, "e": 1793, "s": 1443, "text": "difflib.get_close_matches(word, possibilities, n, cutoff)\nword: It is the word to which we need to find the match.\nPossibilities: This is the patterns which will be compared for matching.\nn: Maximum number of close matches to return. Should be greater than 0.\nCutoff: The possibilities that do not score this float value between 0 and 1 are ignored." }, { "code": null, "e": 1848, "s": 1793, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2006, "s": 1848, "text": "In the below example we take a word and also a list of possibilities or patterns that need to be compared. Then we apply the method to get the result needed." }, { "code": null, "e": 2017, "s": 2006, "text": " Live Demo" }, { "code": null, "e": 2178, "s": 2017, "text": "from difflib import get_close_matches\n\nword = 'banana'\npatterns = ['ana', 'nana', 'ban', 'ran','tan']\n\nprint('matched words:',get_close_matches(word, patterns))" }, { "code": null, "e": 2233, "s": 2178, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2271, "s": 2233, "text": "matched words: ['nana', 'ban', 'ana']" } ]
How to Install and Configure Ansible on CentOS 7
In this article, we will learn how to configure Ansible on CentOS 7 which is an Automation configuration management system. This system can control a large number of client machines with an easy administration, which can be automated from a central location. Ansible communicates over SSH tunnels and it doesn’t need to install any software on the client machine and it can retrieve information from the remote ansible machines which issues commands and copies the files. The Ansible configuration files mainly use the YAML data formation as it can be due to expressive and similarity of popular languages. The clients can be communicated using the command line tools or using with the playbooks. We need CentOS 7 and root user. Needed SSH keys for the users. Since we need to install Ansible software on one machine, it will not be available in the CentOS default repository. Hence, we should add the Ansible personal package to archive the system. Below is the command to add to the repository – $ sudo yum install epel-release -y Output: Loaded plugins: fastest mirror Loading mirror speeds from cached hostfile * base: mirror.fibergrid.in* extras: mirror.digistar.vn * updates: mirror.digistar.vn Resolving Dependencies --> Running transaction check ---> Package epel-release.noarch 0:7-9 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: epel-release noarch 7-9 extras 14 k Transaction Summary ================================================================================ Install 1 Package Total download size: 14 k Installed size: 24 k Downloading packages: epel-release-7-9.noarch.rpm | 14 kB 00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : epel-release-7-9.noarch 1/1 Verifying : epel-release-7-9.noarch 1/1 Installed: epel-release.noarch 0:7-9 Complete! Once the Epel repository is updated, we need to update the system so that we have the dependencies installed perfectly. $ sudo yum update –y Output: Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirror.fibergrid.in * epel: epel.mirror.angkasa.id * extras: mirror.digistar.vn * updates: mirror.digistar.vn Resolving Dependencies --> Running transaction check ---> Package NetworkManager.x86_64 1:1.0.6-31.el7_2 will be updated ---> Package NetworkManager.x86_64 1:1.4.0-14.el7_3 will be an update --> Processing Dependency: libjansson.so.4()(64bit) for package: 1:NetworkManager-1.4.0-14.el7_3.x86_64 ---> Package NetworkManager-libnm.x86_64 1:1.0.6-31.el7_2 will be updated ---> Package NetworkManager-libnm.x86_64 1:1.4.0-14.el7_3 will be an update ---> Package NetworkManager-tui.x86_64 1:1.0.6-31.el7_2 will be updated ---> Package NetworkManager-tui.x86_64 1:1.4.0-14.el7_3 will be an update ---> Package NetworkManager-wifi.x86_64 1:1.0.6-31.el7_2 will be updated ---> Package NetworkManager-wifi.x86_64 1:1.4.0-14.el7_3 will be an update ---> Package alsa-lib.x86_64 0:1.0.28-2.el7 will be updated ---> Package alsa-lib.x86_64 0:1.1.1-1.el7 will be an update ... ... Fetched 19.5 kB in 1s (18.2 kB/s) Reading package lists... Done Complete! Once the package repository is updated, we will install the Ansible using the below command –. $ sudo yum install ansible -y Output: Loaded plugins: fastestmirror epel/x86_64/metalink | 4.8 kB 00:00:00 epel | 4.3 kB 00:00:00 (1/3): epel/x86_64/group_gz | 170 kB 00:00:01 (2/3): epel/x86_64/updateinfo | 721 kB 00:00:03 (3/3): epel/x86_64/primary_db | 4.5 MB 00:00:09 Loading mirror speeds from cached hostfile * base: mirror.fibergrid.in * epel: mirror.rise.ph * extras: mirror.digistar.vn * updates: mirror.digistar.vn Resolving Dependencies --> Running transaction check ---> Package ansible.noarch 0:2.2.1.0-1.el7 will be installed --> Processing Dependency: sshpass for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-six for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-setuptools for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-paramiko for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-keyczar for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-jinja2 for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: python-httplib2 for package: ansible-2.2.1.0-1.el7.noarch --> Processing Dependency: PyYAML for package: ansible-2.2.1.0-1.el7.noarch --> Running transaction check .. .. Verifying : python-jinja2-2.7.2-2.el7.noarch 3/19 Verifying : python-setuptools-0.9.8-4.el7.noarch 4/19 Verifying : python-backports-ssl_match_hostname-3.4.0.2-4.el7.noarch 5/19 Verifying : python-markupsafe-0.11-10.el7.x86_64 6/19 Verifying : python-httplib2-0.7.7-3.el7.noarch 7/19 Verifying : python2-ecdsa-0.13-4.el7.noarch 8/19 Verifying : libtomcrypt-1.17-23.el7.x86_64 9/19 Verifying : python-backports-1.0-8.el7.x86_64 10/19 Verifying : ansible-2.2.1.0-1.el7.noarch 11/19 Verifying : libtommath-0.42.0-4.el7.x86_64 12/19 Verifying : python2-pyasn1-0.1.9-7.el7.noarch 13/19 Verifying : PyYAML-3.10-11.el7.x86_64 14/19 Verifying : python2-crypto-2.6.1-10.el7.x86_64 15/19 Verifying : python-babel-0.9.6-8.el7.noarch 16/19 Verifying : python-six-1.9.0-2.el7.noarch 17/19 Verifying : python2-paramiko-1.16.1-1.el7.noarch 18/19 Verifying : sshpass-1.05-5.el7.x86_64 19/19 Installed: ansible.noarch 0:2.2.1.0-1.el7 Dependency Installed: PyYAML.x86_64 0:3.10-11.el7 libtomcrypt.x86_64 0:1.17-23.el7 libtommath.x86_64 0:0.42.0-4.el7 libyaml.x86_64 0:0.1.4-11.el7_0 python-babel.noarch 0:0.9.6-8.el7 python-backports.x86_64 0:1.0-8.el7 python-backports-ssl_match_hostname.noarch 0:3.4.0.2-4.el7 python-httplib2.noarch 0:0.7.7-3.el7 python-jinja2.noarch 0:2.7.2-2.el7 python-keyczar.noarch 0:0.71c-2.el7 python-markupsafe.x86_64 0:0.11-10.el7 python-setuptools.noarch 0:0.9.8-4.el7 python-six.noarch 0:1.9.0-2.el7 python2-crypto.x86_64 0:2.6.1-10.el7 python2-ecdsa.noarch 0:0.13-4.el7 python2-paramiko.noarch 0:1.16.1-1.el7 python2-pyasn1.noarch 0:0.1.9-7.el7 sshpass.x86_64 0:1.05-5.el7 Complete! We need to keep track of all the servers and clients from β€˜hosts’ file, we also need to create the hosts file so that we can start communicating with the other client or server machines. $ sudo nano /etc/ansible/hosts When we open the configuration file, we will see that all the commented lines and none of the configuration in the files works, as we need to add the below demo machines. [group_name] Alias anisible_ssh_host=your_ansible_server_ip_address [Ansible_server] Client1 ansible_ssh_host=192.168.0.10 Client2 ansible_ssh_host=192.168.0.11 We needed to configure so that SSH keys are copied to all the client machines so that they are authorized without any password. In our scenario, we are using two client machines and all the client machines are accessible using the SSH keys without prompting for the password. With the current configuration if we try to connect to the host with Ansible the command fails because the SSH keys are connected with the root user and we will see the below error. Client1 | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true } We will create a file which tells that the servers will connect using the root user of the client machines. $ sudo mkdir /etc/ansible/group_vars $ sudo vi /etc/ansible/group_vars/servers --- Ansible_ssh_user: root We have to put the β€œ---β€œ in the starting of the YAML file. If you want to specify all the servers at a place we needed to provide those details at /etc/ansible/group_vars/all. To test our configuration we run the below command which will ping all the clients in the configuration file.Watch movie online The Transporter Refueled (2015) $ ansible –m ping all Output: Client1 | SUCCESS => { "changed": false, "ping": "pong" } Client2 | SUCCESS => { "changed": false, "ping": "pong" } We can also ping the individual clients with the below example. $ ansible –m ping servers $ ansible –m ping clien1 We can use the shell module to run a terminal command from the Anisble to the client. $ ansible –m shell –a β€˜df –h’ client1 Output: Client1 | SUCCESS | rc=0 >> Filesystem Size Used Avail Use% Mounted on /dev/mapper/centos-root 42G 2.6G 39G 7% / devtmpfs 1.9G 0 1.9G 0% /dev tmpfs 1.9G 0 1.9G 0% /dev/shm tmpfs 1.9G 8.4M 1.9G 1% /run tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup /dev/sda1 494M 163M 332M 33% /boot /dev/mapper/centos-home 21G 33M 21G 1% /home tmpfs 379M 0 379M 0% /run/user/0 Like the above example we will check for the free memory for the client1 $ ansible –m shell –a β€˜free –m’ client1 Output: Client1|SUCCESS|rc=0 >> total used free shared buff/cache available Mem: 3.7G 868M 1.9G 8.4M 1.0G 2.6G Swap: 2.0G 0B 2.0G In the above article, we have learnt about – how to install and configure the Ansible and configure the clients, communicate with the client or servers and run simple commands and tasks so that we can test the configuration and execute the simple tasks remotely. We will cover the Playbooks in the further articles.
[ { "code": null, "e": 1321, "s": 1062, "text": "In this article, we will learn how to configure Ansible on CentOS 7 which is an Automation configuration management system. This system can control a large number of client machines with an easy administration, which can be automated from a central location." }, { "code": null, "e": 1534, "s": 1321, "text": "Ansible communicates over SSH tunnels and it doesn’t need to install any software on the client machine and it can retrieve information from the remote ansible machines which issues commands and copies the files." }, { "code": null, "e": 1759, "s": 1534, "text": "The Ansible configuration files mainly use the YAML data formation as it can be due to expressive and similarity of popular languages. The clients can be communicated using the command line tools or using with the playbooks." }, { "code": null, "e": 1791, "s": 1759, "text": "We need CentOS 7 and root user." }, { "code": null, "e": 1822, "s": 1791, "text": "Needed SSH keys for the users." }, { "code": null, "e": 2012, "s": 1822, "text": "Since we need to install Ansible software on one machine, it will not be available in the CentOS default repository. Hence, we should add the Ansible personal package to archive the system." }, { "code": null, "e": 2060, "s": 2012, "text": "Below is the command to add to the repository –" }, { "code": null, "e": 3345, "s": 2060, "text": "$ sudo yum install epel-release -y\nOutput:\nLoaded plugins: fastest mirror\nLoading mirror speeds from cached hostfile\n* base: mirror.fibergrid.in* extras: mirror.digistar.vn\n* updates: mirror.digistar.vn\nResolving Dependencies\n --> Running transaction check\n ---> Package epel-release.noarch 0:7-9 will be installed\n --> Finished Dependency Resolution\nDependencies Resolved\n================================================================================\nPackage Arch Version Repository Size\n================================================================================\nInstalling:\nepel-release noarch 7-9 extras 14 k\nTransaction Summary\n================================================================================\nInstall 1 Package\nTotal download size: 14 k\nInstalled size: 24 k\nDownloading packages:\nepel-release-7-9.noarch.rpm | 14 kB 00:00\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\nInstalling : epel-release-7-9.noarch 1/1\nVerifying : epel-release-7-9.noarch 1/1\nInstalled:\nepel-release.noarch 0:7-9\nComplete!" }, { "code": null, "e": 3465, "s": 3345, "text": "Once the Epel repository is updated, we need to update the system so that we have the dependencies installed perfectly." }, { "code": null, "e": 4663, "s": 3465, "text": "$ sudo yum update –y\nOutput:\nLoaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n* base: mirror.fibergrid.in\n* epel: epel.mirror.angkasa.id\n* extras: mirror.digistar.vn\n* updates: mirror.digistar.vn\nResolving Dependencies\n --> Running transaction check\n ---> Package NetworkManager.x86_64 1:1.0.6-31.el7_2 will be updated\n ---> Package NetworkManager.x86_64 1:1.4.0-14.el7_3 will be an update\n --> Processing Dependency: libjansson.so.4()(64bit) for package: 1:NetworkManager-1.4.0-14.el7_3.x86_64\n ---> Package NetworkManager-libnm.x86_64 1:1.0.6-31.el7_2 will be updated\n ---> Package NetworkManager-libnm.x86_64 1:1.4.0-14.el7_3 will be an update\n ---> Package NetworkManager-tui.x86_64 1:1.0.6-31.el7_2 will be updated\n ---> Package NetworkManager-tui.x86_64 1:1.4.0-14.el7_3 will be an update\n ---> Package NetworkManager-wifi.x86_64 1:1.0.6-31.el7_2 will be updated\n ---> Package NetworkManager-wifi.x86_64 1:1.4.0-14.el7_3 will be an update\n ---> Package alsa-lib.x86_64 0:1.0.28-2.el7 will be updated\n ---> Package alsa-lib.x86_64 0:1.1.1-1.el7 will be an update\n...\n...\nFetched 19.5 kB in 1s (18.2 kB/s)\nReading package lists... Done\nComplete!" }, { "code": null, "e": 4758, "s": 4663, "text": "Once the package repository is updated, we will install the Ansible using the below command –." }, { "code": null, "e": 8325, "s": 4758, "text": "$ sudo yum install ansible -y\nOutput:\nLoaded plugins: fastestmirror\nepel/x86_64/metalink | 4.8 kB 00:00:00\nepel | 4.3 kB 00:00:00\n(1/3): epel/x86_64/group_gz | 170 kB 00:00:01\n(2/3): epel/x86_64/updateinfo | 721 kB 00:00:03\n(3/3): epel/x86_64/primary_db | 4.5 MB 00:00:09\nLoading mirror speeds from cached hostfile\n* base: mirror.fibergrid.in\n* epel: mirror.rise.ph\n* extras: mirror.digistar.vn\n* updates: mirror.digistar.vn\nResolving Dependencies\n --> Running transaction check\n ---> Package ansible.noarch 0:2.2.1.0-1.el7 will be installed\n --> Processing Dependency: sshpass for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-six for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-setuptools for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-paramiko for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-keyczar for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-jinja2 for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: python-httplib2 for package: ansible-2.2.1.0-1.el7.noarch\n --> Processing Dependency: PyYAML for package: ansible-2.2.1.0-1.el7.noarch\n --> Running transaction check\n..\n..\nVerifying : python-jinja2-2.7.2-2.el7.noarch 3/19\nVerifying : python-setuptools-0.9.8-4.el7.noarch 4/19\nVerifying : python-backports-ssl_match_hostname-3.4.0.2-4.el7.noarch 5/19\nVerifying : python-markupsafe-0.11-10.el7.x86_64 6/19\nVerifying : python-httplib2-0.7.7-3.el7.noarch 7/19\nVerifying : python2-ecdsa-0.13-4.el7.noarch 8/19\nVerifying : libtomcrypt-1.17-23.el7.x86_64 9/19\nVerifying : python-backports-1.0-8.el7.x86_64 10/19\nVerifying : ansible-2.2.1.0-1.el7.noarch 11/19\nVerifying : libtommath-0.42.0-4.el7.x86_64 12/19\nVerifying : python2-pyasn1-0.1.9-7.el7.noarch 13/19\nVerifying : PyYAML-3.10-11.el7.x86_64 14/19\nVerifying : python2-crypto-2.6.1-10.el7.x86_64 15/19\nVerifying : python-babel-0.9.6-8.el7.noarch 16/19\nVerifying : python-six-1.9.0-2.el7.noarch 17/19\nVerifying : python2-paramiko-1.16.1-1.el7.noarch 18/19\nVerifying : sshpass-1.05-5.el7.x86_64 19/19\nInstalled:\nansible.noarch 0:2.2.1.0-1.el7\nDependency Installed:\nPyYAML.x86_64 0:3.10-11.el7 libtomcrypt.x86_64 0:1.17-23.el7 libtommath.x86_64 0:0.42.0-4.el7\nlibyaml.x86_64 0:0.1.4-11.el7_0 python-babel.noarch 0:0.9.6-8.el7 python-backports.x86_64 0:1.0-8.el7\npython-backports-ssl_match_hostname.noarch 0:3.4.0.2-4.el7 python-httplib2.noarch 0:0.7.7-3.el7 python-jinja2.noarch 0:2.7.2-2.el7\npython-keyczar.noarch 0:0.71c-2.el7 python-markupsafe.x86_64 0:0.11-10.el7 python-setuptools.noarch 0:0.9.8-4.el7\npython-six.noarch 0:1.9.0-2.el7 python2-crypto.x86_64 0:2.6.1-10.el7 python2-ecdsa.noarch 0:0.13-4.el7\npython2-paramiko.noarch 0:1.16.1-1.el7 python2-pyasn1.noarch 0:0.1.9-7.el7 sshpass.x86_64 0:1.05-5.el7\nComplete!" }, { "code": null, "e": 8512, "s": 8325, "text": "We need to keep track of all the servers and clients from β€˜hosts’ file, we also need to create the hosts file so that we can start communicating with the other client or server machines." }, { "code": null, "e": 8543, "s": 8512, "text": "$ sudo nano /etc/ansible/hosts" }, { "code": null, "e": 8714, "s": 8543, "text": "When we open the configuration file, we will see that all the commented lines and none of the configuration in the files works, as we need to add the below demo machines." }, { "code": null, "e": 8782, "s": 8714, "text": "[group_name]\nAlias anisible_ssh_host=your_ansible_server_ip_address" }, { "code": null, "e": 8875, "s": 8782, "text": "[Ansible_server]\nClient1 ansible_ssh_host=192.168.0.10\nClient2 ansible_ssh_host=192.168.0.11" }, { "code": null, "e": 9003, "s": 8875, "text": "We needed to configure so that SSH keys are copied to all the client machines so that they are authorized without any password." }, { "code": null, "e": 9151, "s": 9003, "text": "In our scenario, we are using two client machines and all the client machines are accessible using the SSH keys without prompting for the password." }, { "code": null, "e": 9333, "s": 9151, "text": "With the current configuration if we try to connect to the host with Ansible the command fails because the SSH keys are connected with the root user and we will see the below error." }, { "code": null, "e": 9459, "s": 9333, "text": "Client1 | UNREACHABLE! => {\n \"changed\": false,\n \"msg\": \"Failed to connect to the host via ssh.\",\n \"unreachable\": true\n}" }, { "code": null, "e": 9567, "s": 9459, "text": "We will create a file which tells that the servers will connect using the root user of the client machines." }, { "code": null, "e": 9732, "s": 9567, "text": "$ sudo mkdir /etc/ansible/group_vars\n$ sudo vi /etc/ansible/group_vars/servers\n---\nAnsible_ssh_user: root\nWe have to put the β€œ---β€œ in the starting of the YAML file." }, { "code": null, "e": 9849, "s": 9732, "text": "If you want to specify all the servers at a place we needed to provide those details at /etc/ansible/group_vars/all." }, { "code": null, "e": 10009, "s": 9849, "text": "To test our configuration we run the below command which will ping all the clients in the configuration file.Watch movie online The Transporter Refueled (2015)" }, { "code": null, "e": 10167, "s": 10009, "text": "$ ansible –m ping all\nOutput:\nClient1 | SUCCESS => {\n \"changed\": false,\n \"ping\": \"pong\"\n}\nClient2 | SUCCESS => {\n \"changed\": false,\n \"ping\": \"pong\"\n}" }, { "code": null, "e": 10231, "s": 10167, "text": "We can also ping the individual clients with the below example." }, { "code": null, "e": 10282, "s": 10231, "text": "$ ansible –m ping servers\n$ ansible –m ping clien1" }, { "code": null, "e": 10368, "s": 10282, "text": "We can use the shell module to run a terminal command from the Anisble to the client." }, { "code": null, "e": 11141, "s": 10368, "text": "$ ansible –m shell –a β€˜df –h’ client1\nOutput:\nClient1 | SUCCESS | rc=0 >>\nFilesystem Size Used Avail Use% Mounted on\n/dev/mapper/centos-root 42G 2.6G 39G 7% /\ndevtmpfs 1.9G 0 1.9G 0% /dev\ntmpfs 1.9G 0 1.9G 0% /dev/shm\ntmpfs 1.9G 8.4M 1.9G 1% /run\ntmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup\n/dev/sda1 494M 163M 332M 33% /boot\n/dev/mapper/centos-home 21G 33M 21G 1% /home\ntmpfs 379M 0 379M 0% /run/user/0" }, { "code": null, "e": 11214, "s": 11141, "text": "Like the above example we will check for the free memory for the client1" }, { "code": null, "e": 11478, "s": 11214, "text": "$ ansible –m shell –a β€˜free –m’ client1\nOutput:\nClient1|SUCCESS|rc=0 >>\ntotal used free shared buff/cache available\nMem: 3.7G 868M 1.9G 8.4M 1.0G 2.6G\nSwap: 2.0G 0B 2.0G\n\n" }, { "code": null, "e": 11794, "s": 11478, "text": "In the above article, we have learnt about – how to install and configure the Ansible and configure the clients, communicate with the client or servers and run simple commands and tasks so that we can test the configuration and execute the simple tasks remotely. We will cover the Playbooks in the further articles." } ]
Checkbox verification with Cypress
Cypress handles checking and unchecking of checkbox with the help of its in built functions. For a checkbox, the tagname of the element should be input and the type attribute in the html code should be checkbox. The command used is check(). This command needs to be chained with a command that gives DOM elements and the element should be of type checkbox. The various usage of check commands are listed below βˆ’ check() βˆ’ The check() command without argument checks all the checkboxes. The get method should have the [type="checkbox"] as the css selector when it is chained with check() method. check() βˆ’ The check() command without argument checks all the checkboxes. The get method should have the [type="checkbox"] as the css selector when it is chained with check() method. cy.get('[type="checkbox"]').check() check() βˆ’ The check() command without argument checks the checkbox with a specific id given as an argument to the chained Cypress get() command. check() βˆ’ The check() command without argument checks the checkbox with a specific id given as an argument to the chained Cypress get() command. cy.get('#option1').check() check('Value1') βˆ’ The check() command with value as argument checks the checkbox with the mentioned value. The get method should have the [type="checkbox"] as the css selector when it is chained with check() command. check('Value1') βˆ’ The check() command with value as argument checks the checkbox with the mentioned value. The get method should have the [type="checkbox"] as the css selector when it is chained with check() command. cy.get('[type="checkbox"]').check('Tutorialspoint') check('Value1', 'Value2') βˆ’ The check() command with values as arguments check the checkbox with the mentioned values. The get method should have the [type="checkbox"] as the css selector when it is chained with check() command. check('Value1', 'Value2') βˆ’ The check() command with values as arguments check the checkbox with the mentioned values. The get method should have the [type="checkbox"] as the css selector when it is chained with check() command. cy.get('[type="checkbox"]').check('Tutorialspoint', 'Selenium') check({ force: true }) βˆ’ The check() command with option as argument changes the default behavior of checkbox. There can be three types of options: log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively. check({ force: true }) βˆ’ The check() command with option as argument changes the default behavior of checkbox. There can be three types of options: log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively. cy.get('.check-boxes').should('not.be.visible').check({ force: true }).should('be.checked') The option force is used by Cypress to interact with hidden elements and then forces to check the checkbox internally. Similar to the check commands, there exists the uncheck commands in Cypress. The command used is uncheck(). This command needs to be chained with a command that gives DOM elements and the element should be of type checkbox. The various usage of uncheck commands are listed below βˆ’ uncheck() βˆ’ The uncheck() command without argument unchecks all the checkboxes. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck(). uncheck() βˆ’ The uncheck() command without argument unchecks all the checkboxes. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck(). cy.get('[type="checkbox"]').uncheck() uncheck() βˆ’ The uncheck() command without argument checks the checkbox with a specific id given as an argument to the chained Cypress get() command. uncheck() βˆ’ The uncheck() command without argument checks the checkbox with a specific id given as an argument to the chained Cypress get() command. cy.get('#option1').uncheck() uncheck('Value1') βˆ’ The uncheck() command with value as argument unchecks the checkbox with the mentioned value. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck() command. uncheck('Value1') βˆ’ The uncheck() command with value as argument unchecks the checkbox with the mentioned value. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck() command. cy.get('[type="checkbox"]').uncheck('Tutorialspoint') uncheck('Value1', 'Value2') βˆ’ The uncheck() command with values arguments unchecks the checkbox with the mentioned values. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck(). uncheck('Value1', 'Value2') βˆ’ The uncheck() command with values arguments unchecks the checkbox with the mentioned values. The get method should have the [type="checkbox"] as the css selector when it is chained with uncheck(). cy.get('[type="checkbox"]').uncheck('Tutorialspoint', 'Selenium') uncheck({ force: true }) βˆ’ The uncheck() command with option as argument change in default behavior of checkbox. There can be three types of options βˆ’ log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively. uncheck({ force: true }) βˆ’ The uncheck() command with option as argument change in default behavior of checkbox. There can be three types of options βˆ’ log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively. cy.get('.check-boxes').should('not.be.visible').uncheck({ force: true }).should('be.unchecked') The option force is used by Cypress to interact with hidden elements and then forces to uncheck the checkbox internally. We can apply assertions with both check() and uncheck() commands in Cypress. Code Implementation with checkbox. describe('Tutorialspoint Test', function () { // test case it('Test Case2', function (){ cy.visit("https://www.tutorialspoint.com/selenium/selenium_automatio n_practice.htm"); // checking by values cy.get('input[type="checkbox"]') .check(['Manual Tester','Automation Tester']); // unchecking all values cy.get('input[type="checkbox"]').uncheck(); // checking and assertion combined with and() cy.get('input[value="Automation Tester"]') .check().should('be.checked').and('have.value','Automation Tester'); // unchecking and assertion combined with and() cy.get('input[value="Automation Tester"]') .uncheck().should('not.be.checked'); }); });
[ { "code": null, "e": 1274, "s": 1062, "text": "Cypress handles checking and unchecking of checkbox with the help of its in built\nfunctions. For a checkbox, the tagname of the element should be input and the\ntype attribute in the html code should be checkbox." }, { "code": null, "e": 1474, "s": 1274, "text": "The command used is check(). This command needs to be chained with a command\nthat gives DOM elements and the element should be of type checkbox. The various\nusage of check commands are listed below βˆ’" }, { "code": null, "e": 1657, "s": 1474, "text": "check() βˆ’ The check() command without argument checks all the checkboxes.\nThe get method should have the [type=\"checkbox\"] as the css selector when\nit is chained with check() method." }, { "code": null, "e": 1840, "s": 1657, "text": "check() βˆ’ The check() command without argument checks all the checkboxes.\nThe get method should have the [type=\"checkbox\"] as the css selector when\nit is chained with check() method." }, { "code": null, "e": 1876, "s": 1840, "text": "cy.get('[type=\"checkbox\"]').check()" }, { "code": null, "e": 2021, "s": 1876, "text": "check() βˆ’ The check() command without argument checks the checkbox with\na specific id given as an argument to the chained Cypress get() command." }, { "code": null, "e": 2166, "s": 2021, "text": "check() βˆ’ The check() command without argument checks the checkbox with\na specific id given as an argument to the chained Cypress get() command." }, { "code": null, "e": 2193, "s": 2166, "text": "cy.get('#option1').check()" }, { "code": null, "e": 2410, "s": 2193, "text": "check('Value1') βˆ’ The check() command with value as argument checks the\ncheckbox with the mentioned value. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with check() command." }, { "code": null, "e": 2627, "s": 2410, "text": "check('Value1') βˆ’ The check() command with value as argument checks the\ncheckbox with the mentioned value. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with check() command." }, { "code": null, "e": 2679, "s": 2627, "text": "cy.get('[type=\"checkbox\"]').check('Tutorialspoint')" }, { "code": null, "e": 2908, "s": 2679, "text": "check('Value1', 'Value2') βˆ’ The check() command with values as arguments\ncheck the checkbox with the mentioned values. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with check() command." }, { "code": null, "e": 3137, "s": 2908, "text": "check('Value1', 'Value2') βˆ’ The check() command with values as arguments\ncheck the checkbox with the mentioned values. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with check() command." }, { "code": null, "e": 3201, "s": 3137, "text": "cy.get('[type=\"checkbox\"]').check('Tutorialspoint', 'Selenium')" }, { "code": null, "e": 3470, "s": 3201, "text": "check({ force: true }) βˆ’ The check() command with option as argument\nchanges the default behavior of checkbox. There can be three types of options: log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively." }, { "code": null, "e": 3739, "s": 3470, "text": "check({ force: true }) βˆ’ The check() command with option as argument\nchanges the default behavior of checkbox. There can be three types of options: log, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively." }, { "code": null, "e": 3831, "s": 3739, "text": "cy.get('.check-boxes').should('not.be.visible').check({ force: true\n}).should('be.checked')" }, { "code": null, "e": 3950, "s": 3831, "text": "The option force is used by Cypress to interact with hidden elements and then forces to check the checkbox internally." }, { "code": null, "e": 4027, "s": 3950, "text": "Similar to the check commands, there exists the uncheck commands in Cypress." }, { "code": null, "e": 4231, "s": 4027, "text": "The command used is uncheck(). This command needs to be chained with a command that gives DOM elements and the element should be of type checkbox. The various usage of uncheck commands are listed below βˆ’" }, { "code": null, "e": 4415, "s": 4231, "text": "uncheck() βˆ’ The uncheck() command without argument unchecks all the\ncheckboxes. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck()." }, { "code": null, "e": 4599, "s": 4415, "text": "uncheck() βˆ’ The uncheck() command without argument unchecks all the\ncheckboxes. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck()." }, { "code": null, "e": 4637, "s": 4599, "text": "cy.get('[type=\"checkbox\"]').uncheck()" }, { "code": null, "e": 4786, "s": 4637, "text": "uncheck() βˆ’ The uncheck() command without argument checks the checkbox\nwith a specific id given as an argument to the chained Cypress get() command." }, { "code": null, "e": 4935, "s": 4786, "text": "uncheck() βˆ’ The uncheck() command without argument checks the checkbox\nwith a specific id given as an argument to the chained Cypress get() command." }, { "code": null, "e": 4964, "s": 4935, "text": "cy.get('#option1').uncheck()" }, { "code": null, "e": 5189, "s": 4964, "text": "uncheck('Value1') βˆ’ The uncheck() command with value as argument\nunchecks the checkbox with the mentioned value. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck() command." }, { "code": null, "e": 5414, "s": 5189, "text": "uncheck('Value1') βˆ’ The uncheck() command with value as argument\nunchecks the checkbox with the mentioned value. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck() command." }, { "code": null, "e": 5468, "s": 5414, "text": "cy.get('[type=\"checkbox\"]').uncheck('Tutorialspoint')" }, { "code": null, "e": 5695, "s": 5468, "text": "uncheck('Value1', 'Value2') βˆ’ The uncheck() command with values arguments unchecks the checkbox with the mentioned values. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck()." }, { "code": null, "e": 5922, "s": 5695, "text": "uncheck('Value1', 'Value2') βˆ’ The uncheck() command with values arguments unchecks the checkbox with the mentioned values. The get method should have the [type=\"checkbox\"] as the css selector when it is chained with uncheck()." }, { "code": null, "e": 5988, "s": 5922, "text": "cy.get('[type=\"checkbox\"]').uncheck('Tutorialspoint', 'Selenium')" }, { "code": null, "e": 6260, "s": 5988, "text": "uncheck({ force: true }) βˆ’ The uncheck() command with option as argument\nchange in default behavior of checkbox. There can be three types of options βˆ’\nlog, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively." }, { "code": null, "e": 6532, "s": 6260, "text": "uncheck({ force: true }) βˆ’ The uncheck() command with option as argument\nchange in default behavior of checkbox. There can be three types of options βˆ’\nlog, force and timeout having default values as true, false and defaultCommandTimeout ( 4000 milliseconds) respectively." }, { "code": null, "e": 6628, "s": 6532, "text": "cy.get('.check-boxes').should('not.be.visible').uncheck({ force: true\n}).should('be.unchecked')" }, { "code": null, "e": 6749, "s": 6628, "text": "The option force is used by Cypress to interact with hidden elements and then forces to uncheck the checkbox internally." }, { "code": null, "e": 6826, "s": 6749, "text": "We can apply assertions with both check() and uncheck() commands in Cypress." }, { "code": null, "e": 6861, "s": 6826, "text": "Code Implementation with checkbox." }, { "code": null, "e": 7589, "s": 6861, "text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Test Case2', function (){\n cy.visit(\"https://www.tutorialspoint.com/selenium/selenium_automatio\n n_practice.htm\");\n // checking by values\n cy.get('input[type=\"checkbox\"]')\n .check(['Manual Tester','Automation Tester']);\n // unchecking all values\n cy.get('input[type=\"checkbox\"]').uncheck();\n // checking and assertion combined with and()\n cy.get('input[value=\"Automation Tester\"]')\n .check().should('be.checked').and('have.value','Automation Tester');\n // unchecking and assertion combined with and()\n cy.get('input[value=\"Automation Tester\"]')\n .uncheck().should('not.be.checked');\n });\n});" } ]
MongoDB inverse of query to return all items except specific documents?
To get documents except some specific documents, use noralongwithand. Let us first create a collection with documents βˆ’ > db.demo1.insertOne({"StudentName":"Chris","StudentMarks":38}); { "acknowledged" : true, "insertedId" : ObjectId("5e08a4f025ddae1f53b62216") } > db.demo1.insertOne({"StudentName":"David","StudentMarks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e08a4f725ddae1f53b62217") } > db.demo1.insertOne({"StudentName":"Mike","StudentMarks":96}); { "acknowledged" : true, "insertedId" : ObjectId("5e08a4fd25ddae1f53b62218") } Following is the query to display all documents from a collection with the help of find() method βˆ’ > db.demo1.find().pretty(); This will produce the following output βˆ’ { "_id" : ObjectId("5e08a4f025ddae1f53b62216"), "StudentName" : "Chris", "StudentMarks" : 38 } { "_id" : ObjectId("5e08a4f725ddae1f53b62217"), "StudentName" : "David", "StudentMarks" : 78 } { "_id" : ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName" : "Mike", "StudentMarks" : 96 } Here is the query to get inverse of query βˆ’ > db.demo1.find({$nor:[{$and:[{'StudentName':'David'},{'StudentMarks':78}]}]}); This will produce the following output. The result displays Student records with marks except 78 βˆ’ { "_id" : ObjectId("5e08a4f025ddae1f53b62216"), "StudentName" : "Chris", "StudentMarks" : 38 } { "_id" : ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName" : "Mike", "StudentMarks" : 96 }
[ { "code": null, "e": 1182, "s": 1062, "text": "To get documents except some specific documents, use noralongwithand. Let us first create a collection with documents βˆ’" }, { "code": null, "e": 1631, "s": 1182, "text": "> db.demo1.insertOne({\"StudentName\":\"Chris\",\"StudentMarks\":38});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e08a4f025ddae1f53b62216\")\n}\n> db.demo1.insertOne({\"StudentName\":\"David\",\"StudentMarks\":78});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e08a4f725ddae1f53b62217\")\n}\n> db.demo1.insertOne({\"StudentName\":\"Mike\",\"StudentMarks\":96});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e08a4fd25ddae1f53b62218\")\n}" }, { "code": null, "e": 1730, "s": 1631, "text": "Following is the query to display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 1758, "s": 1730, "text": "> db.demo1.find().pretty();" }, { "code": null, "e": 1799, "s": 1758, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2110, "s": 1799, "text": "{\n \"_id\" : ObjectId(\"5e08a4f025ddae1f53b62216\"),\n \"StudentName\" : \"Chris\",\n \"StudentMarks\" : 38\n}\n{\n \"_id\" : ObjectId(\"5e08a4f725ddae1f53b62217\"),\n \"StudentName\" : \"David\",\n \"StudentMarks\" : 78\n}\n{\n \"_id\" : ObjectId(\"5e08a4fd25ddae1f53b62218\"),\n \"StudentName\" : \"Mike\",\n \"StudentMarks\" : 96\n}" }, { "code": null, "e": 2154, "s": 2110, "text": "Here is the query to get inverse of query βˆ’" }, { "code": null, "e": 2234, "s": 2154, "text": "> db.demo1.find({$nor:[{$and:[{'StudentName':'David'},{'StudentMarks':78}]}]});" }, { "code": null, "e": 2333, "s": 2234, "text": "This will produce the following output. The result displays Student records with marks except 78 βˆ’" }, { "code": null, "e": 2522, "s": 2333, "text": "{ \"_id\" : ObjectId(\"5e08a4f025ddae1f53b62216\"), \"StudentName\" : \"Chris\", \"StudentMarks\" : 38 }\n{ \"_id\" : ObjectId(\"5e08a4fd25ddae1f53b62218\"), \"StudentName\" : \"Mike\", \"StudentMarks\" : 96 }" } ]
Solidity - Cryptographic Functions
Solidity provides inbuilt cryptographic functions as well. Following are important methods βˆ’ keccak256(bytes memory) returns (bytes32) βˆ’ computes the Keccak-256 hash of the input. keccak256(bytes memory) returns (bytes32) βˆ’ computes the Keccak-256 hash of the input. ripemd160(bytes memory) returns (bytes20) βˆ’ compute RIPEMD-160 hash of the input. ripemd160(bytes memory) returns (bytes20) βˆ’ compute RIPEMD-160 hash of the input. sha256(bytes memory) returns (bytes32) βˆ’ computes the SHA-256 hash of the input. sha256(bytes memory) returns (bytes32) βˆ’ computes the SHA-256 hash of the input. ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) βˆ’ recover the address associated with the public key from elliptic curve signature or return zero on error. The function parameters correspond to ECDSA values of the signature: r - first 32 bytes of signature; s: second 32 bytes of signature; v: final 1 byte of signature. This method returns an address. ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) βˆ’ recover the address associated with the public key from elliptic curve signature or return zero on error. The function parameters correspond to ECDSA values of the signature: r - first 32 bytes of signature; s: second 32 bytes of signature; v: final 1 byte of signature. This method returns an address. Following example shows the usage of cryptographic function in Solidity. pragma solidity ^0.5.0; contract Test { function callKeccak256() public pure returns(bytes32 result){ return keccak256("ABC"); } } Run the above program using steps provided in Solidity First Application chapter. 0: bytes32: result 0xe1629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa35d54f3c8 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2648, "s": 2555, "text": "Solidity provides inbuilt cryptographic functions as well. Following are important methods βˆ’" }, { "code": null, "e": 2735, "s": 2648, "text": "keccak256(bytes memory) returns (bytes32) βˆ’ computes the Keccak-256 hash of the input." }, { "code": null, "e": 2822, "s": 2735, "text": "keccak256(bytes memory) returns (bytes32) βˆ’ computes the Keccak-256 hash of the input." }, { "code": null, "e": 2904, "s": 2822, "text": "ripemd160(bytes memory) returns (bytes20) βˆ’ compute RIPEMD-160 hash of the input." }, { "code": null, "e": 2986, "s": 2904, "text": "ripemd160(bytes memory) returns (bytes20) βˆ’ compute RIPEMD-160 hash of the input." }, { "code": null, "e": 3067, "s": 2986, "text": "sha256(bytes memory) returns (bytes32) βˆ’ computes the SHA-256 hash of the input." }, { "code": null, "e": 3148, "s": 3067, "text": "sha256(bytes memory) returns (bytes32) βˆ’ computes the SHA-256 hash of the input." }, { "code": null, "e": 3526, "s": 3148, "text": "ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) βˆ’ recover the address associated with the public key from elliptic curve signature or return zero on error. The function parameters correspond to ECDSA values of the signature: r - first 32 bytes of signature; s: second 32 bytes of signature; v: final 1 byte of signature. This method returns an address." }, { "code": null, "e": 3904, "s": 3526, "text": "ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) βˆ’ recover the address associated with the public key from elliptic curve signature or return zero on error. The function parameters correspond to ECDSA values of the signature: r - first 32 bytes of signature; s: second 32 bytes of signature; v: final 1 byte of signature. This method returns an address." }, { "code": null, "e": 3977, "s": 3904, "text": "Following example shows the usage of cryptographic function in Solidity." }, { "code": null, "e": 4126, "s": 3977, "text": "pragma solidity ^0.5.0;\n\ncontract Test { \n function callKeccak256() public pure returns(bytes32 result){\n return keccak256(\"ABC\");\n } \n}" }, { "code": null, "e": 4208, "s": 4126, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 4295, "s": 4208, "text": "0: bytes32: result 0xe1629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa35d54f3c8\n" }, { "code": null, "e": 4330, "s": 4295, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4347, "s": 4330, "text": " Abhilash Nelson" }, { "code": null, "e": 4382, "s": 4347, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4399, "s": 4382, "text": " Frahaan Hussain" }, { "code": null, "e": 4434, "s": 4399, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4448, "s": 4434, "text": " Swapnil Kole" }, { "code": null, "e": 4455, "s": 4448, "text": " Print" }, { "code": null, "e": 4466, "s": 4455, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Responsive webdesign intro
[]
Apache Kafka - Consumer Group Example
Consumer group is a multi-threaded or multi-machine consumption from Kafka topics. Consumers can join a group by using the samegroup.id. Consumers can join a group by using the samegroup.id. The maximum parallelism of a group is that the number of consumers in the group ← no of partitions. The maximum parallelism of a group is that the number of consumers in the group ← no of partitions. Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group. Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group. Kafka guarantees that a message is only ever read by a single consumer in the group. Kafka guarantees that a message is only ever read by a single consumer in the group. Consumers can see the message in the order they were stored in the log. Consumers can see the message in the order they were stored in the log. Adding more processes/threads will cause Kafka to re-balance. If any consumer or broker fails to send heartbeat to ZooKeeper, then it can be re-configured via the Kafka cluster. During this re-balance, Kafka will assign available partitions to the available threads, possibly moving a partition to another process. import java.util.Properties; import java.util.Arrays; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.ConsumerRecord; public class ConsumerGroup { public static void main(String[] args) throws Exception { if(args.length < 2){ System.out.println("Usage: consumer <topic> <groupname>"); return; } String topic = args[0].toString(); String group = args[1].toString(); Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", group); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.ByteArraySerializer"); props.put("value.deserializer", "org.apache.kafka.common.serializa-tion.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props); consumer.subscribe(Arrays.asList(topic)); System.out.println("Subscribed to topic " + topic); int i = 0; while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value()); } } } javac -cp β€œ/path/to/kafka/kafka_2.11-0.9.0.0/libs/*" ConsumerGroup.java >>java -cp β€œ/path/to/kafka/kafka_2.11-0.9.0.0/libs/*":. ConsumerGroup <topic-name> my-group >>java -cp "/home/bala/Workspace/kafka/kafka_2.11-0.9.0.0/libs/*":. ConsumerGroup <topic-name> my-group Here we have created a sample group name as my-group with two consumers. Similarly, you can create your group and number of consumers in the group. Open producer CLI and send some messages like βˆ’ Test consumer group 01 Test consumer group 02 Subscribed to topic Hello-kafka offset = 3, key = null, value = Test consumer group 01 Subscribed to topic Hello-kafka offset = 3, key = null, value = Test consumer group 02 Now hopefully you would have understood SimpleConsumer and ConsumeGroup by using the Java client demo. Now you have an idea about how to send and receive messages using a Java client. Let us continue Kafka integration with big data technologies in the next chapter. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2050, "s": 1967, "text": "Consumer group is a multi-threaded or multi-machine consumption from Kafka topics." }, { "code": null, "e": 2104, "s": 2050, "text": "Consumers can join a group by using the samegroup.id." }, { "code": null, "e": 2158, "s": 2104, "text": "Consumers can join a group by using the samegroup.id." }, { "code": null, "e": 2258, "s": 2158, "text": "The maximum parallelism of a group is that the number of consumers in the group ← no of partitions." }, { "code": null, "e": 2358, "s": 2258, "text": "The maximum parallelism of a group is that the number of consumers in the group ← no of partitions." }, { "code": null, "e": 2499, "s": 2358, "text": "Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group." }, { "code": null, "e": 2640, "s": 2499, "text": "Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group." }, { "code": null, "e": 2725, "s": 2640, "text": "Kafka guarantees that a message is only ever read by a single consumer in the group." }, { "code": null, "e": 2810, "s": 2725, "text": "Kafka guarantees that a message is only ever read by a single consumer in the group." }, { "code": null, "e": 2882, "s": 2810, "text": "Consumers can see the message in the order they were stored in the log." }, { "code": null, "e": 2954, "s": 2882, "text": "Consumers can see the message in the order they were stored in the log." }, { "code": null, "e": 3269, "s": 2954, "text": "Adding more processes/threads will cause Kafka to re-balance. If any consumer or broker fails to send heartbeat to ZooKeeper, then it can be re-configured via the Kafka cluster. During this re-balance, Kafka will assign available partitions to the available threads, possibly moving a partition to another process." }, { "code": null, "e": 4848, "s": 3269, "text": "import java.util.Properties;\nimport java.util.Arrays;\nimport org.apache.kafka.clients.consumer.KafkaConsumer;\nimport org.apache.kafka.clients.consumer.ConsumerRecords;\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\n\npublic class ConsumerGroup {\n public static void main(String[] args) throws Exception {\n if(args.length < 2){\n System.out.println(\"Usage: consumer <topic> <groupname>\");\n return;\n }\n \n String topic = args[0].toString();\n String group = args[1].toString();\n Properties props = new Properties();\n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"group.id\", group);\n props.put(\"enable.auto.commit\", \"true\");\n props.put(\"auto.commit.interval.ms\", \"1000\");\n props.put(\"session.timeout.ms\", \"30000\");\n props.put(\"key.deserializer\", \n \"org.apache.kafka.common.serialization.ByteArraySerializer\");\n props.put(\"value.deserializer\", \n \"org.apache.kafka.common.serializa-tion.StringDeserializer\");\n KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);\n \n consumer.subscribe(Arrays.asList(topic));\n System.out.println(\"Subscribed to topic \" + topic);\n int i = 0;\n \n while (true) {\n ConsumerRecords<String, String> records = consumer.poll(100);\n for (ConsumerRecord<String, String> record : records)\n System.out.printf(\"offset = %d, key = %s, value = %s\\n\", \n record.offset(), record.key(), record.value());\n } \n } \n}" }, { "code": null, "e": 4920, "s": 4848, "text": "javac -cp β€œ/path/to/kafka/kafka_2.11-0.9.0.0/libs/*\" ConsumerGroup.java" }, { "code": null, "e": 5119, "s": 4920, "text": ">>java -cp β€œ/path/to/kafka/kafka_2.11-0.9.0.0/libs/*\":. \nConsumerGroup <topic-name> my-group\n>>java -cp \"/home/bala/Workspace/kafka/kafka_2.11-0.9.0.0/libs/*\":. \nConsumerGroup <topic-name> my-group\n" }, { "code": null, "e": 5267, "s": 5119, "text": "Here we have created a sample group name as my-group with two consumers. Similarly, you can create your group and number of consumers in the group." }, { "code": null, "e": 5315, "s": 5267, "text": "Open producer CLI and send some messages like βˆ’" }, { "code": null, "e": 5362, "s": 5315, "text": "Test consumer group 01\nTest consumer group 02\n" }, { "code": null, "e": 5449, "s": 5362, "text": "Subscribed to topic Hello-kafka\noffset = 3, key = null, value = Test consumer group 01" }, { "code": null, "e": 5537, "s": 5449, "text": "Subscribed to topic Hello-kafka\noffset = 3, key = null, value = Test consumer group 02\n" }, { "code": null, "e": 5803, "s": 5537, "text": "Now hopefully you would have understood SimpleConsumer and ConsumeGroup by using the Java client demo. Now you have an idea about how to send and receive messages using a Java client. Let us continue Kafka integration with big data technologies in the next chapter." }, { "code": null, "e": 5838, "s": 5803, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5857, "s": 5838, "text": " Arnab Chakraborty" }, { "code": null, "e": 5892, "s": 5857, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5913, "s": 5892, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5946, "s": 5913, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5959, "s": 5946, "text": " Nilay Mehta" }, { "code": null, "e": 5994, "s": 5959, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6012, "s": 5994, "text": " Bigdata Engineer" }, { "code": null, "e": 6045, "s": 6012, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6063, "s": 6045, "text": " Bigdata Engineer" }, { "code": null, "e": 6096, "s": 6063, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6114, "s": 6096, "text": " Bigdata Engineer" }, { "code": null, "e": 6121, "s": 6114, "text": " Print" }, { "code": null, "e": 6132, "s": 6121, "text": " Add Notes" } ]
Go - Nested for Loops
Go programming language allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept βˆ’ The syntax for a nested for loop statement in Go is as follows βˆ’ for [condition | ( init; condition; increment ) | Range] { for [condition | ( init; condition; increment ) | Range] { statement(s); } statement(s); } The following program uses a nested for loop to find the prime numbers from 2 to 100 βˆ’ package main import "fmt" func main() { /* local variable definition */ var i, j int for i = 2; i < 100; i++ { for j = 2; j <= (i/j); j++ { if(i%j==0) { break; // if factor found, not prime } } if(j > (i/j)) { fmt.Printf("%d is prime\n", i); } } } When the above code is compiled and executed, it produces the following result βˆ’ 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2076, "s": 1937, "text": "Go programming language allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept βˆ’" }, { "code": null, "e": 2141, "s": 2076, "text": "The syntax for a nested for loop statement in Go is as follows βˆ’" }, { "code": null, "e": 2309, "s": 2141, "text": "for [condition | ( init; condition; increment ) | Range] {\n for [condition | ( init; condition; increment ) | Range] {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2396, "s": 2309, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 100 βˆ’" }, { "code": null, "e": 2724, "s": 2396, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var i, j int\n\n for i = 2; i < 100; i++ {\n for j = 2; j <= (i/j); j++ {\n if(i%j==0) {\n break; // if factor found, not prime\n }\n }\n if(j > (i/j)) {\n fmt.Printf(\"%d is prime\\n\", i);\n }\n } \n}" }, { "code": null, "e": 2805, "s": 2724, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 3102, "s": 2805, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 3137, "s": 3102, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3150, "s": 3137, "text": " Ridhi Arora" }, { "code": null, "e": 3185, "s": 3150, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3199, "s": 3185, "text": " Asif Hussain" }, { "code": null, "e": 3232, "s": 3199, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3251, "s": 3232, "text": " Dilip Padmanabhan" }, { "code": null, "e": 3284, "s": 3251, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 3303, "s": 3284, "text": " Arnab Chakraborty" }, { "code": null, "e": 3335, "s": 3303, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3352, "s": 3335, "text": " Aditya Kulkarni" }, { "code": null, "e": 3385, "s": 3352, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3404, "s": 3385, "text": " Arnab Chakraborty" }, { "code": null, "e": 3411, "s": 3404, "text": " Print" }, { "code": null, "e": 3422, "s": 3411, "text": " Add Notes" } ]
Visualising Global Population Datasets with Python | by Parvathy Krishnan | Towards Data Science
This work has been done entirely using publicly available data, and was co-authored with Kai Kaiser. All errors and omissions are those of the author(s). Mapping information concerning distribution of people is vital to a host of public policy questions across our planet’s different country settings. The ability to capture geographic distribution of population and their key characteristics is integral to measuring exposure to disasters and climate change, access differentials to key services such as health, and environmental and land-use pressures. Whether for planning, budgeting, or regulatory purposes, sufficiently granular and timely population data for more evidence-based decision making is necessary. A new generation of high-resolution population estimate count layers stand to increasingly make a powerful contribution to public sector decision making, particularly in developing countries. The mapping layers rely on non-traditional methodologies of data collection, including the use of satellite imagery. Consequently, they can provide population estimates for any grid cell on the earth down to 30 meters resolution. Their latest updates can be accessed on-line through Application Programming Interfaces (APIs), making them potentially a very valuable asset for data-driven decision makers. Some critical limitations of the traditional administrative or statistical population census data are addressed by these high-resolution population maps. Population census data typically lack frequent updates, being undertaken only roughly every ten years by most of the countries. They are generally presented in tabular administrative classifications, which limits analytics and visualisation options compared to more granular grid-based layers. Household level population census data is rarely collected on geo-referenced basis, or disclosed at that level. The administrative registers of births and deaths maintained by national and subnational governments are also not always reliable or updated, especially in low and middle-income countries. Datasets such as the Facebook Research High Resolution Settlement Layer (HRSL) and World Pop, employing new generation techniques for high-resolution population estimates can be readily deployed for a range of descriptive and prescriptive analytics. WorldPop Project was initiated in 2013 with the goal to provide open access to population and demographic datasets to support development, disaster, and health applications. It integrates neighborhood-scale micro-census surveys undertaken in small areas and national-level satellite imagery and digital mapping. In short, WorldPop leveraged machine learning modeling (random forest) to extrapolate high-resolution national population estimates from the relatively sparse micro census data (including predicting populations in unsurveyed locations) and are available yearly from 2000-2020 (as of November 2020). The gridded population data or raster images are available at a spatial resolution as detailed as 3 arc seconds (approximately 100m at the equator). This temporal availability of high-resolution estimates of population count makes it easier to identify the growth and dynamics of the population across national and regional levels. Another such collaboration is of Facebook with the Center for International Earth Science Information Network (CIESIN), to use artificial intelligence to identify buildings from satellite imagery and estimate population at a 30meter resolution. Adjustments to match the census population with the UN estimates are also applied at the national level. The adjustments are made to match the UN country population estimates for the years of 2015 and 2020. In practice, policy makers may not yet be familiar enough with how to access, analyze, apply, and ultimate adopt these data for their decision-making purposes. Greater familiarity will also help understand the possible benefits, applications, but also limitations of these new data resources for their decision-making purposes. To support data-informed and data-driven decision making, online Jupyter Notebook Python Environments (JPNEs) allows for accessible and replicable ways of realising data analytics and visualisation. JNPEs integrate programming code, intuitive description, and numeric and visual outputs (cite). When implemented on-line, they do not require users to install or download any local software. JPNE are not just powerful for delivery work, but above all to facilitate closer collaboration with the domain and public sector experts with the data scientists. In this blog, we explore the WorldPop Population Counts (Raster format at 100m resolution downloaded as tif file) and High Resolution Population Density Maps from Facebook (Vector format at 30m resolution downloaded as csv) with Python in a JPNE and visualise the population counts at different administrative units for Vietnam. To extract the estimated population count for different administrative units, we also need data representing the digital boundaries of Vietnam as shapefiles (a simple non-topological format for storing geometric location and attribute information of features represented as a polygon or area). Thus, this analysis requires three datasets-Population data from WorldPop and Facebook, and Administrative Boundaries data from GADM. The analysis includes 4 steps - Load and Explore data on Administrative Boundaries from GADMLoad, Explore, and Visualize Population data from WorldPopLoad, Explore and Visualize Population data from FacebookCompare and summarise results Load and Explore data on Administrative Boundaries from GADM Load, Explore, and Visualize Population data from WorldPop Load, Explore and Visualize Population data from Facebook Compare and summarise results GADM, the Database of Global Administrative Areas, is a high-resolution database of country administrative areas, latest version of which delimits 386,735 administrative areas. The country-level data for vietnam was downloaded which resulted in a folder with the following structure. The index of the file (0,1,2,3) denotes the administrative level at which the boundaries are available. Vietnam is divided into fifty-eight provinces and five municipalities under the command of the central government, making a total of 63 polygons under ADM Level 1. The provinces of Vietnam are then subdivided into second-level administrative units, namely districts, provincial cities, and district-level towns. The municipalities are subdivided into rural districts, district-level towns, and urban districts that are further subdivided into wards. The GADM data thus includes 686 units at level 2 and 7658 at level 3 administrative units of Vietnam. The gadm shapefiles are read with geopandas. vietnam_administrative_boundaries = geopandas.read_file('Data/gadm36_VNM_shp/gadm36_VNM_3.shp')vietnam_administrative_boundaries['NAME_0'].unique()> Vietnamvietnam_administrative_boundaries['NAME_1'].nunique()> 63vietnam_administrative_boundaries['NAME_2'].nunique()> 686vietnam_administrative_boundaries['NAME_3'].nunique()> 7658 We downloaded the data of people per pixel (ppp) for Vietnam in Raster format from WorldPop at 100m resolution adjusted to match UN national estimates. We use rasterio, a GDAL and numpy based python library to read the raster data downloaded as a tif file. vietnam_worldpop_raster = rasterio.open('vnm_ppp_2020_UNadj.tif') Raster data is any pixelated (or gridded) data where each pixel is associated with a specific geographical location. The value of a pixel can be continuous (e.g. elevation) or categorical (e.g. land use). A geospatial raster is only different from a digital photo in that it is accompanied by spatial information that connects the data to a particular location. This includes the raster’s extent and cell size, the number of rows and columns, and its coordinate reference system (or CRS). A raster dataset contains one or more layers called bands. For example, a color image has three bands (red, green, and blue) while a digital elevation model (DEM) has one band (holding elevation values), and a multispectral image may have many bands. print('No. of bands:',(vietnam_worldpop_raster.count))> No. of bands: 1 # Calculating total population of Vietnamworldpop_raster_nonzero = vietnam_worldpop_raster_tot[vietnam_worldpop_raster_tot>0]population_worldpop = worldpop_raster_nonzero[worldpop_raster_nonzero > 0].sum()print(round(population_worldpop/1000000,2),'million')> 97.34 million The raster layer gives a total population of 97.34 million in Vietnam. We then mask this raster layer with the polygons extracted from the GADM file to identify population counts within each of the 63 provinces+municipalities (level 1 administrative units) of Vietnam. The following function returns the population count of a raster_layer within a vector_polygon. The code creates the following result adding a column called population_count_wp which have the population estimate of the ADM Level 1 based on the WorldPop raster data. We then use Plotly Choropleth map to visualise the population count using the code snippet below. The facebook population map that estimate the number of people living within 30-meter grid tiles for Vietnam is available for download at HDX either as tif file or as a csv file. As we did the preprocessing of WorldPop data in tif format, we demonstrate here with the csv file downloaded in the following format. The csv file consists of latitude, longitude and population estimates at the points as of 2015, and 2020. The facebook data estimates a total population of 98.16 million in Vietnam. Inorder to use the geospatial tools and techniques demonstrated with WorldPop data, we need to convert this dataframe into a geodataframe which includes a geometry field. We then get the population counts per administrative boundaries with the masking function for vector layer with a polygon. We then plot the choropleth map with Plotly using the code below With the two mapping layers now previewed in a JPNE, we now turn to compare results through the more familiar administrative definitions lens familiar to most policymakers. To do this, we can visualize comparative ratios of Worldpop versus Facebook results with the scatterplots presented below. A 45-degree line would suggest that results are identical for any given locality. At the provincial/municipality level, the population counts with both Worldpop and Facebook shows high correlation. At the second administrative level, especially in some of the municipalities like Binh Duong and Ho Chi Minh, the Facebook gives a relatively smaller population count compared to WorldPop. Whether this is an issue ultimately depends on the question being asked. JPNEs allow for quick reviews of the extent to which using one data source over another makes a substantive difference for the issue at hand. Digital technologies developments in terms of platforms (e.g., JPNEs) and data (Facebook Research HRSL and World Pop) provide for a powerful combination to address a range of policy questions. But these require practical collaborations between domain specialists (e.g., governments officials in planning, finance or health) along with data scientists-engineers/programmers). This practitioner’s blog was generated as part of the Disruptive Technologies for Public Asset Governance (DT4PAG) program for Vietnam, initiated by the World Bank in Vietnam with the support of the Swiss State Secretariat for Economic Affairs (SECO). DT4PAG promotes the use of cloud-based and open-source platforms and data, along with practitioner’s learning by doing skills building. to better inform green, including, and resilient development. The views expressed in this note are those of the authors, and all remaining errors and omissions are our own. Full code for this tutorial can be found in the GitHub repo. Even if you are not a Python programmer, we hope this contribution gives you an intuitive sense of the possibilities and processes for leveraging this type of data for a new generation of decision support.
[ { "code": null, "e": 326, "s": 172, "text": "This work has been done entirely using publicly available data, and was co-authored with Kai Kaiser. All errors and omissions are those of the author(s)." }, { "code": null, "e": 887, "s": 326, "text": "Mapping information concerning distribution of people is vital to a host of public policy questions across our planet’s different country settings. The ability to capture geographic distribution of population and their key characteristics is integral to measuring exposure to disasters and climate change, access differentials to key services such as health, and environmental and land-use pressures. Whether for planning, budgeting, or regulatory purposes, sufficiently granular and timely population data for more evidence-based decision making is necessary." }, { "code": null, "e": 1484, "s": 887, "text": "A new generation of high-resolution population estimate count layers stand to increasingly make a powerful contribution to public sector decision making, particularly in developing countries. The mapping layers rely on non-traditional methodologies of data collection, including the use of satellite imagery. Consequently, they can provide population estimates for any grid cell on the earth down to 30 meters resolution. Their latest updates can be accessed on-line through Application Programming Interfaces (APIs), making them potentially a very valuable asset for data-driven decision makers." }, { "code": null, "e": 2233, "s": 1484, "text": "Some critical limitations of the traditional administrative or statistical population census data are addressed by these high-resolution population maps. Population census data typically lack frequent updates, being undertaken only roughly every ten years by most of the countries. They are generally presented in tabular administrative classifications, which limits analytics and visualisation options compared to more granular grid-based layers. Household level population census data is rarely collected on geo-referenced basis, or disclosed at that level. The administrative registers of births and deaths maintained by national and subnational governments are also not always reliable or updated, especially in low and middle-income countries." }, { "code": null, "e": 2483, "s": 2233, "text": "Datasets such as the Facebook Research High Resolution Settlement Layer (HRSL) and World Pop, employing new generation techniques for high-resolution population estimates can be readily deployed for a range of descriptive and prescriptive analytics." }, { "code": null, "e": 3426, "s": 2483, "text": "WorldPop Project was initiated in 2013 with the goal to provide open access to population and demographic datasets to support development, disaster, and health applications. It integrates neighborhood-scale micro-census surveys undertaken in small areas and national-level satellite imagery and digital mapping. In short, WorldPop leveraged machine learning modeling (random forest) to extrapolate high-resolution national population estimates from the relatively sparse micro census data (including predicting populations in unsurveyed locations) and are available yearly from 2000-2020 (as of November 2020). The gridded population data or raster images are available at a spatial resolution as detailed as 3 arc seconds (approximately 100m at the equator). This temporal availability of high-resolution estimates of population count makes it easier to identify the growth and dynamics of the population across national and regional levels." }, { "code": null, "e": 3878, "s": 3426, "text": "Another such collaboration is of Facebook with the Center for International Earth Science Information Network (CIESIN), to use artificial intelligence to identify buildings from satellite imagery and estimate population at a 30meter resolution. Adjustments to match the census population with the UN estimates are also applied at the national level. The adjustments are made to match the UN country population estimates for the years of 2015 and 2020." }, { "code": null, "e": 4206, "s": 3878, "text": "In practice, policy makers may not yet be familiar enough with how to access, analyze, apply, and ultimate adopt these data for their decision-making purposes. Greater familiarity will also help understand the possible benefits, applications, but also limitations of these new data resources for their decision-making purposes." }, { "code": null, "e": 4405, "s": 4206, "text": "To support data-informed and data-driven decision making, online Jupyter Notebook Python Environments (JPNEs) allows for accessible and replicable ways of realising data analytics and visualisation." }, { "code": null, "e": 4759, "s": 4405, "text": "JNPEs integrate programming code, intuitive description, and numeric and visual outputs (cite). When implemented on-line, they do not require users to install or download any local software. JPNE are not just powerful for delivery work, but above all to facilitate closer collaboration with the domain and public sector experts with the data scientists." }, { "code": null, "e": 5088, "s": 4759, "text": "In this blog, we explore the WorldPop Population Counts (Raster format at 100m resolution downloaded as tif file) and High Resolution Population Density Maps from Facebook (Vector format at 30m resolution downloaded as csv) with Python in a JPNE and visualise the population counts at different administrative units for Vietnam." }, { "code": null, "e": 5382, "s": 5088, "text": "To extract the estimated population count for different administrative units, we also need data representing the digital boundaries of Vietnam as shapefiles (a simple non-topological format for storing geometric location and attribute information of features represented as a polygon or area)." }, { "code": null, "e": 5548, "s": 5382, "text": "Thus, this analysis requires three datasets-Population data from WorldPop and Facebook, and Administrative Boundaries data from GADM. The analysis includes 4 steps -" }, { "code": null, "e": 5753, "s": 5548, "text": "Load and Explore data on Administrative Boundaries from GADMLoad, Explore, and Visualize Population data from WorldPopLoad, Explore and Visualize Population data from FacebookCompare and summarise results" }, { "code": null, "e": 5814, "s": 5753, "text": "Load and Explore data on Administrative Boundaries from GADM" }, { "code": null, "e": 5873, "s": 5814, "text": "Load, Explore, and Visualize Population data from WorldPop" }, { "code": null, "e": 5931, "s": 5873, "text": "Load, Explore and Visualize Population data from Facebook" }, { "code": null, "e": 5961, "s": 5931, "text": "Compare and summarise results" }, { "code": null, "e": 6245, "s": 5961, "text": "GADM, the Database of Global Administrative Areas, is a high-resolution database of country administrative areas, latest version of which delimits 386,735 administrative areas. The country-level data for vietnam was downloaded which resulted in a folder with the following structure." }, { "code": null, "e": 6349, "s": 6245, "text": "The index of the file (0,1,2,3) denotes the administrative level at which the boundaries are available." }, { "code": null, "e": 6901, "s": 6349, "text": "Vietnam is divided into fifty-eight provinces and five municipalities under the command of the central government, making a total of 63 polygons under ADM Level 1. The provinces of Vietnam are then subdivided into second-level administrative units, namely districts, provincial cities, and district-level towns. The municipalities are subdivided into rural districts, district-level towns, and urban districts that are further subdivided into wards. The GADM data thus includes 686 units at level 2 and 7658 at level 3 administrative units of Vietnam." }, { "code": null, "e": 6946, "s": 6901, "text": "The gadm shapefiles are read with geopandas." }, { "code": null, "e": 7277, "s": 6946, "text": "vietnam_administrative_boundaries = geopandas.read_file('Data/gadm36_VNM_shp/gadm36_VNM_3.shp')vietnam_administrative_boundaries['NAME_0'].unique()> Vietnamvietnam_administrative_boundaries['NAME_1'].nunique()> 63vietnam_administrative_boundaries['NAME_2'].nunique()> 686vietnam_administrative_boundaries['NAME_3'].nunique()> 7658" }, { "code": null, "e": 7534, "s": 7277, "text": "We downloaded the data of people per pixel (ppp) for Vietnam in Raster format from WorldPop at 100m resolution adjusted to match UN national estimates. We use rasterio, a GDAL and numpy based python library to read the raster data downloaded as a tif file." }, { "code": null, "e": 7600, "s": 7534, "text": "vietnam_worldpop_raster = rasterio.open('vnm_ppp_2020_UNadj.tif')" }, { "code": null, "e": 8340, "s": 7600, "text": "Raster data is any pixelated (or gridded) data where each pixel is associated with a specific geographical location. The value of a pixel can be continuous (e.g. elevation) or categorical (e.g. land use). A geospatial raster is only different from a digital photo in that it is accompanied by spatial information that connects the data to a particular location. This includes the raster’s extent and cell size, the number of rows and columns, and its coordinate reference system (or CRS). A raster dataset contains one or more layers called bands. For example, a color image has three bands (red, green, and blue) while a digital elevation model (DEM) has one band (holding elevation values), and a multispectral image may have many bands." }, { "code": null, "e": 8412, "s": 8340, "text": "print('No. of bands:',(vietnam_worldpop_raster.count))> No. of bands: 1" }, { "code": null, "e": 8686, "s": 8412, "text": "# Calculating total population of Vietnamworldpop_raster_nonzero = vietnam_worldpop_raster_tot[vietnam_worldpop_raster_tot>0]population_worldpop = worldpop_raster_nonzero[worldpop_raster_nonzero > 0].sum()print(round(population_worldpop/1000000,2),'million')> 97.34 million" }, { "code": null, "e": 9050, "s": 8686, "text": "The raster layer gives a total population of 97.34 million in Vietnam. We then mask this raster layer with the polygons extracted from the GADM file to identify population counts within each of the 63 provinces+municipalities (level 1 administrative units) of Vietnam. The following function returns the population count of a raster_layer within a vector_polygon." }, { "code": null, "e": 9318, "s": 9050, "text": "The code creates the following result adding a column called population_count_wp which have the population estimate of the ADM Level 1 based on the WorldPop raster data. We then use Plotly Choropleth map to visualise the population count using the code snippet below." }, { "code": null, "e": 9631, "s": 9318, "text": "The facebook population map that estimate the number of people living within 30-meter grid tiles for Vietnam is available for download at HDX either as tif file or as a csv file. As we did the preprocessing of WorldPop data in tif format, we demonstrate here with the csv file downloaded in the following format." }, { "code": null, "e": 9813, "s": 9631, "text": "The csv file consists of latitude, longitude and population estimates at the points as of 2015, and 2020. The facebook data estimates a total population of 98.16 million in Vietnam." }, { "code": null, "e": 9984, "s": 9813, "text": "Inorder to use the geospatial tools and techniques demonstrated with WorldPop data, we need to convert this dataframe into a geodataframe which includes a geometry field." }, { "code": null, "e": 10107, "s": 9984, "text": "We then get the population counts per administrative boundaries with the masking function for vector layer with a polygon." }, { "code": null, "e": 10172, "s": 10107, "text": "We then plot the choropleth map with Plotly using the code below" }, { "code": null, "e": 10550, "s": 10172, "text": "With the two mapping layers now previewed in a JPNE, we now turn to compare results through the more familiar administrative definitions lens familiar to most policymakers. To do this, we can visualize comparative ratios of Worldpop versus Facebook results with the scatterplots presented below. A 45-degree line would suggest that results are identical for any given locality." }, { "code": null, "e": 10666, "s": 10550, "text": "At the provincial/municipality level, the population counts with both Worldpop and Facebook shows high correlation." }, { "code": null, "e": 11070, "s": 10666, "text": "At the second administrative level, especially in some of the municipalities like Binh Duong and Ho Chi Minh, the Facebook gives a relatively smaller population count compared to WorldPop. Whether this is an issue ultimately depends on the question being asked. JPNEs allow for quick reviews of the extent to which using one data source over another makes a substantive difference for the issue at hand." }, { "code": null, "e": 11445, "s": 11070, "text": "Digital technologies developments in terms of platforms (e.g., JPNEs) and data (Facebook Research HRSL and World Pop) provide for a powerful combination to address a range of policy questions. But these require practical collaborations between domain specialists (e.g., governments officials in planning, finance or health) along with data scientists-engineers/programmers)." }, { "code": null, "e": 11697, "s": 11445, "text": "This practitioner’s blog was generated as part of the Disruptive Technologies for Public Asset Governance (DT4PAG) program for Vietnam, initiated by the World Bank in Vietnam with the support of the Swiss State Secretariat for Economic Affairs (SECO)." }, { "code": null, "e": 12006, "s": 11697, "text": "DT4PAG promotes the use of cloud-based and open-source platforms and data, along with practitioner’s learning by doing skills building. to better inform green, including, and resilient development. The views expressed in this note are those of the authors, and all remaining errors and omissions are our own." } ]
Difference between on() and live() or bind() in jQuery - GeeksforGeeks
17 Dec, 2021 jQuery offers various event handlers like on(), live() and bind(). Though, there are some minor differences which are discussed below. bind() method: This method only attaches events to elements which exist beforehand i.e. state of initialized document before the events are attached. If the selector condition is satisfied for an event afterward, bind() will not work on that function. It also won’t work in the case if selector condition is removed from the element. Example:<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src="https://code.jquery.com/jquery-3.4.1.js"> </script></head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* Here, the bind() works on elements initialized beforehand only */ $(".a").bind("click",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- click() method works on Statement 1 but not on Statement 2. --> </div></body></html> <!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src="https://code.jquery.com/jquery-3.4.1.js"> </script></head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* Here, the bind() works on elements initialized beforehand only */ $(".a").bind("click",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- click() method works on Statement 1 but not on Statement 2. --> </div></body></html> Output:Before clicking those statement:After clicking those statement: live() method: This method attaches events not only to existing elements but also for the ones appended in the future as well but it won’t work in the case if selector condition is removed from the element. Note: The live() method was deprecated in jQuery version 1.7, and removed in version 1.9. Example:<!DOCTYPE html><html><head> <!-- Old CDN for .live() to work in jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script> </head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* live() method works for elements appended later as well */ $(".a").live("click",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- live() method works on both Statement 1 and Statement 2. --> </div></body></html> <!DOCTYPE html><html><head> <!-- Old CDN for .live() to work in jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script> </head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* live() method works for elements appended later as well */ $(".a").live("click",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- live() method works on both Statement 1 and Statement 2. --> </div></body></html> Output:Before clicking those statement:After clicking those statement: on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods. Example:<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src="https://code.jquery.com/jquery-3.4.1.js"> </script></head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* Works on all elements within scope of the document */ $(document).on("click",".a",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- on() method works on both Statement 1 and Statement 2. --> </div></body></html> <!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src="https://code.jquery.com/jquery-3.4.1.js"> </script></head><body> <div class="content"> <p class="a">This is Statement 1.</p> <script> /* Works on all elements within scope of the document */ $(document).on("click",".a",function(){ $(this).css("color","red"); }); </script> <p class="a">This is Statement 2.</p> <!-- on() method works on both Statement 1 and Statement 2. --> </div></body></html> Output:Before clicking those statement:After clicking those statement: Differences summarized for the above methods: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. younessarbouhdev jQuery-Methods jQuery-Misc Picked HTML JQuery Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to add options to a select element using jQuery?
[ { "code": null, "e": 24566, "s": 24538, "text": "\n17 Dec, 2021" }, { "code": null, "e": 24701, "s": 24566, "text": "jQuery offers various event handlers like on(), live() and bind(). Though, there are some minor differences which are discussed below." }, { "code": null, "e": 25035, "s": 24701, "text": "bind() method: This method only attaches events to elements which exist beforehand i.e. state of initialized document before the events are attached. If the selector condition is satisfied for an event afterward, bind() will not work on that function. It also won’t work in the case if selector condition is removed from the element." }, { "code": null, "e": 25671, "s": 25035, "text": "Example:<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"> </script></head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* Here, the bind() works on elements initialized beforehand only */ $(\".a\").bind(\"click\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- click() method works on Statement 1 but not on Statement 2. --> </div></body></html> " }, { "code": "<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"> </script></head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* Here, the bind() works on elements initialized beforehand only */ $(\".a\").bind(\"click\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- click() method works on Statement 1 but not on Statement 2. --> </div></body></html> ", "e": 26299, "s": 25671, "text": null }, { "code": null, "e": 26370, "s": 26299, "text": "Output:Before clicking those statement:After clicking those statement:" }, { "code": null, "e": 26577, "s": 26370, "text": "live() method: This method attaches events not only to existing elements but also for the ones appended in the future as well but it won’t work in the case if selector condition is removed from the element." }, { "code": null, "e": 26667, "s": 26577, "text": "Note: The live() method was deprecated in jQuery version 1.7, and removed in version 1.9." }, { "code": null, "e": 27333, "s": 26667, "text": "Example:<!DOCTYPE html><html><head> <!-- Old CDN for .live() to work in jQuery --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js\"> </script> </head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* live() method works for elements appended later as well */ $(\".a\").live(\"click\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- live() method works on both Statement 1 and Statement 2. --> </div></body></html> " }, { "code": "<!DOCTYPE html><html><head> <!-- Old CDN for .live() to work in jQuery --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js\"> </script> </head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* live() method works for elements appended later as well */ $(\".a\").live(\"click\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- live() method works on both Statement 1 and Statement 2. --> </div></body></html> ", "e": 27991, "s": 27333, "text": null }, { "code": null, "e": 28062, "s": 27991, "text": "Output:Before clicking those statement:After clicking those statement:" }, { "code": null, "e": 28346, "s": 28062, "text": "on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods." }, { "code": null, "e": 28985, "s": 28346, "text": "Example:<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"> </script></head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* Works on all elements within scope of the document */ $(document).on(\"click\",\".a\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- on() method works on both Statement 1 and Statement 2. --> </div></body></html> " }, { "code": "<!DOCTYPE html><html><head> <!-- CDN for jQuery --> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"> </script></head><body> <div class=\"content\"> <p class=\"a\">This is Statement 1.</p> <script> /* Works on all elements within scope of the document */ $(document).on(\"click\",\".a\",function(){ $(this).css(\"color\",\"red\"); }); </script> <p class=\"a\">This is Statement 2.</p> <!-- on() method works on both Statement 1 and Statement 2. --> </div></body></html> ", "e": 29616, "s": 28985, "text": null }, { "code": null, "e": 29687, "s": 29616, "text": "Output:Before clicking those statement:After clicking those statement:" }, { "code": null, "e": 29733, "s": 29687, "text": "Differences summarized for the above methods:" }, { "code": null, "e": 29870, "s": 29733, "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": 29887, "s": 29870, "text": "younessarbouhdev" }, { "code": null, "e": 29902, "s": 29887, "text": "jQuery-Methods" }, { "code": null, "e": 29914, "s": 29902, "text": "jQuery-Misc" }, { "code": null, "e": 29921, "s": 29914, "text": "Picked" }, { "code": null, "e": 29926, "s": 29921, "text": "HTML" }, { "code": null, "e": 29933, "s": 29926, "text": "JQuery" }, { "code": null, "e": 29952, "s": 29933, "text": "Technical Scripter" }, { "code": null, "e": 29969, "s": 29952, "text": "Web Technologies" }, { "code": null, "e": 29974, "s": 29969, "text": "HTML" }, { "code": null, "e": 30072, "s": 29974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30081, "s": 30072, "text": "Comments" }, { "code": null, "e": 30094, "s": 30081, "text": "Old Comments" }, { "code": null, "e": 30118, "s": 30094, "text": "REST API (Introduction)" }, { "code": null, "e": 30155, "s": 30118, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30184, "s": 30155, "text": "Form validation using jQuery" }, { "code": null, "e": 30231, "s": 30184, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 30293, "s": 30231, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 30339, "s": 30293, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 30368, "s": 30339, "text": "Form validation using jQuery" }, { "code": null, "e": 30431, "s": 30368, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 30508, "s": 30431, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Print all Strong numbers less than or equal to N
15 Mar, 2021 Given a number N, print all the Strong Numbers less than or equal to N. Strong number is a special number whose sum of the factorial of digits is equal to the original number. For Example: 145 is strong number. Since, 1! + 4! + 5! = 145. Examples: Input: N = 100 Output: 1 2 Explanation: Only 1 and 2 are the strong numbers from 1 to 100 because 1! = 1, and 2! = 2 Input: N = 1000 Output: 1 2 145 Explanation: Only 1, 2 and 145 are the strong numbers from 1 to 1000 because 1! = 1, 2! = 2, and (1! + 4! + 5!) = 145 Approach: The idea is to iterate from [1, N] and check if any number between the range is strong number or not. If yes then print the corresponding number, else check for the next number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Store the factorial of all the// digits from [0, 9]int factorial[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true// if number is strong or notbool isStrong(int N){ // Converting N to String so that // can easily access all it's digit string num = to_string(N); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for(int i = 0; i < num.length(); i++) { sum += factorial[num[i] - '0']; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Nvoid printStrongNumbers(int N){ // Iterating from 1 to N for(int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { cout << i << " "; } }} // Driver Codeint main(){ // Given number int N = 1000; // Function call printStrongNumbers(N); return 0;} // This code is contributed by rutvik_56 // Java program for the above approach class GFG { // Store the factorial of all the // digits from [0, 9] static int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true // if number is strong or not public static boolean isStrong(int N) { // Converting N to String so that // can easily access all it's digit String num = Integer.toString(N); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for (int i = 0; i < num.length(); i++) { sum += factorial[Integer .parseInt(num .charAt(i) + "")]; } // Returns true of N is strong number return sum == N; } // Function to print all // strong number till N public static void printStrongNumbers(int N) { // Iterating from 1 to N for (int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { System.out.print(i + " "); } } } // Driver Code public static void main(String[] args) throws java.lang.Exception { // Given Number int N = 1000; // Function Call printStrongNumbers(N); }} # Python3 program for the# above approach # Store the factorial of# all the digits from [0, 9]factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] # Function to return true# if number is strong or notdef isStrong(N): # Converting N to String # so that can easily access # all it's digit num = str(N) # sum will store summation # of factorial of all # digits of a number N sum = 0 for i in range (len(num)): sum += factorial[ord(num[i]) - ord('0')] # Returns true of N # is strong number if sum == N: return True else: return False # Function to print all# strong number till Ndef printStrongNumbers(N): # Iterating from 1 to N for i in range (1, N + 1): # Checking if a number is # strong then print it if (isStrong(i)): print (i, end = " ") # Driver Codeif __name__ == "__main__": # Given number N = 1000 # Function call printStrongNumbers(N) # This code is contributed by Chitranayal // C# program for the above approachusing System;class GFG{ // Store the factorial of all the// digits from [0, 9]static int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true// if number is strong or notpublic static bool isStrong(int N){ // Converting N to String so that // can easily access all it's digit String num = N.ToString(); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for (int i = 0; i < num.Length; i++) { sum += factorial[int.Parse(num[i] + "")]; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Npublic static void printStrongNumbers(int N){ // Iterating from 1 to N for (int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { Console.Write(i + " "); } }} // Driver Codepublic static void Main(String[] args){ // Given Number int N = 1000; // Function Call printStrongNumbers(N);}} // This code is contributed by sapnasingh4991 <script> // Javascript program for the above approach // Store the factorial of all the// digits from [0, 9]let factorial = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 ]; // Function to return true// if number is strong or notfunction isStrong(N){ // Converting N to String so that // can easily access all it's digit let num = N.toString(); // sum will store summation of // factorial of all digits // of a number N let sum = 0; for(let i = 0; i < num.length; i++) { sum += factorial[num[i] - '0']; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Nfunction printStrongNumbers(N){ // Iterating from 1 to N for(let i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { document.write(i + " "); } }} // Driver Code // Given number let N = 1000; // Function call printStrongNumbers(N); // This code is contributed by Mayank Tyagi </script> 1 2 145 Time Complexity: O(N) sapnasingh4991 rutvik_56 ukasp mayanktyagi1709 factorial Analysis Combinatorial Greedy Mathematical Greedy Mathematical Combinatorial factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Analysis of Algorithms | Set 4 (Analysis of Loops) Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Time Complexity of building a heap Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Mar, 2021" }, { "code": null, "e": 125, "s": 52, "text": "Given a number N, print all the Strong Numbers less than or equal to N. " }, { "code": null, "e": 292, "s": 125, "text": "Strong number is a special number whose sum of the factorial of digits is equal to the original number. For Example: 145 is strong number. Since, 1! + 4! + 5! = 145. " }, { "code": null, "e": 303, "s": 292, "text": "Examples: " }, { "code": null, "e": 420, "s": 303, "text": "Input: N = 100 Output: 1 2 Explanation: Only 1 and 2 are the strong numbers from 1 to 100 because 1! = 1, and 2! = 2" }, { "code": null, "e": 571, "s": 420, "text": "Input: N = 1000 Output: 1 2 145 Explanation: Only 1, 2 and 145 are the strong numbers from 1 to 1000 because 1! = 1, 2! = 2, and (1! + 4! + 5!) = 145 " }, { "code": null, "e": 759, "s": 571, "text": "Approach: The idea is to iterate from [1, N] and check if any number between the range is strong number or not. If yes then print the corresponding number, else check for the next number." }, { "code": null, "e": 811, "s": 759, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 815, "s": 811, "text": "C++" }, { "code": null, "e": 820, "s": 815, "text": "Java" }, { "code": null, "e": 828, "s": 820, "text": "Python3" }, { "code": null, "e": 831, "s": 828, "text": "C#" }, { "code": null, "e": 842, "s": 831, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Store the factorial of all the// digits from [0, 9]int factorial[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true// if number is strong or notbool isStrong(int N){ // Converting N to String so that // can easily access all it's digit string num = to_string(N); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for(int i = 0; i < num.length(); i++) { sum += factorial[num[i] - '0']; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Nvoid printStrongNumbers(int N){ // Iterating from 1 to N for(int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { cout << i << \" \"; } }} // Driver Codeint main(){ // Given number int N = 1000; // Function call printStrongNumbers(N); return 0;} // This code is contributed by rutvik_56", "e": 1989, "s": 842, "text": null }, { "code": "// Java program for the above approach class GFG { // Store the factorial of all the // digits from [0, 9] static int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true // if number is strong or not public static boolean isStrong(int N) { // Converting N to String so that // can easily access all it's digit String num = Integer.toString(N); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for (int i = 0; i < num.length(); i++) { sum += factorial[Integer .parseInt(num .charAt(i) + \"\")]; } // Returns true of N is strong number return sum == N; } // Function to print all // strong number till N public static void printStrongNumbers(int N) { // Iterating from 1 to N for (int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { System.out.print(i + \" \"); } } } // Driver Code public static void main(String[] args) throws java.lang.Exception { // Given Number int N = 1000; // Function Call printStrongNumbers(N); }}", "e": 3471, "s": 1989, "text": null }, { "code": "# Python3 program for the# above approach # Store the factorial of# all the digits from [0, 9]factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] # Function to return true# if number is strong or notdef isStrong(N): # Converting N to String # so that can easily access # all it's digit num = str(N) # sum will store summation # of factorial of all # digits of a number N sum = 0 for i in range (len(num)): sum += factorial[ord(num[i]) - ord('0')] # Returns true of N # is strong number if sum == N: return True else: return False # Function to print all# strong number till Ndef printStrongNumbers(N): # Iterating from 1 to N for i in range (1, N + 1): # Checking if a number is # strong then print it if (isStrong(i)): print (i, end = \" \") # Driver Codeif __name__ == \"__main__\": # Given number N = 1000 # Function call printStrongNumbers(N) # This code is contributed by Chitranayal", "e": 4535, "s": 3471, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Store the factorial of all the// digits from [0, 9]static int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to return true// if number is strong or notpublic static bool isStrong(int N){ // Converting N to String so that // can easily access all it's digit String num = N.ToString(); // sum will store summation of // factorial of all digits // of a number N int sum = 0; for (int i = 0; i < num.Length; i++) { sum += factorial[int.Parse(num[i] + \"\")]; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Npublic static void printStrongNumbers(int N){ // Iterating from 1 to N for (int i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { Console.Write(i + \" \"); } }} // Driver Codepublic static void Main(String[] args){ // Given Number int N = 1000; // Function Call printStrongNumbers(N);}} // This code is contributed by sapnasingh4991", "e": 5704, "s": 4535, "text": null }, { "code": "<script> // Javascript program for the above approach // Store the factorial of all the// digits from [0, 9]let factorial = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 ]; // Function to return true// if number is strong or notfunction isStrong(N){ // Converting N to String so that // can easily access all it's digit let num = N.toString(); // sum will store summation of // factorial of all digits // of a number N let sum = 0; for(let i = 0; i < num.length; i++) { sum += factorial[num[i] - '0']; } // Returns true of N is strong number return sum == N;} // Function to print all// strong number till Nfunction printStrongNumbers(N){ // Iterating from 1 to N for(let i = 1; i <= N; i++) { // Checking if a number is // strong then print it if (isStrong(i)) { document.write(i + \" \"); } }} // Driver Code // Given number let N = 1000; // Function call printStrongNumbers(N); // This code is contributed by Mayank Tyagi </script>", "e": 6807, "s": 5704, "text": null }, { "code": null, "e": 6815, "s": 6807, "text": "1 2 145" }, { "code": null, "e": 6839, "s": 6817, "text": "Time Complexity: O(N)" }, { "code": null, "e": 6854, "s": 6839, "text": "sapnasingh4991" }, { "code": null, "e": 6864, "s": 6854, "text": "rutvik_56" }, { "code": null, "e": 6870, "s": 6864, "text": "ukasp" }, { "code": null, "e": 6886, "s": 6870, "text": "mayanktyagi1709" }, { "code": null, "e": 6896, "s": 6886, "text": "factorial" }, { "code": null, "e": 6905, "s": 6896, "text": "Analysis" }, { "code": null, "e": 6919, "s": 6905, "text": "Combinatorial" }, { "code": null, "e": 6926, "s": 6919, "text": "Greedy" }, { "code": null, "e": 6939, "s": 6926, "text": "Mathematical" }, { "code": null, "e": 6946, "s": 6939, "text": "Greedy" }, { "code": null, "e": 6959, "s": 6946, "text": "Mathematical" }, { "code": null, "e": 6973, "s": 6959, "text": "Combinatorial" }, { "code": null, "e": 6983, "s": 6973, "text": "factorial" }, { "code": null, "e": 7081, "s": 6983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7132, "s": 7081, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 7169, "s": 7132, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 7220, "s": 7169, "text": "Analysis of Algorithms | Set 4 (Analysis of Loops)" }, { "code": null, "e": 7287, "s": 7220, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 7322, "s": 7287, "text": "Time Complexity of building a heap" }, { "code": null, "e": 7382, "s": 7322, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7420, "s": 7382, "text": "Permutation and Combination in Python" }, { "code": null, "e": 7448, "s": 7420, "text": "Factorial of a large number" }, { "code": null, "e": 7485, "s": 7448, "text": "Count of subsets with sum equal to X" } ]
Python – Negative index of Element in List
20 Oct, 2020 Given a list of elements, find its negative index in the List. Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 2 Output : -4 Explanation : 2 is 4th element from rear. Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5 Output : -2 Explanation : 5 is 2nd element from rear. Method #1 : Using index() + len() In this, we get the index of the element using index(), and then subtract it from the list length to get the required result. Python3 # Python3 code to demonstrate working of# Negative index of Element# Using index() + len() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing ElementK = 3 # getting length using len() and subtracting index from itres = len(test_list) - test_list.index(K) # printing resultprint("The required Negative index : -" + str(res)) Output: The original list is : [5, 7, 8, 2, 3, 5, 1] The required Negative index : -3 Method #2 : Using ~ operator + list slicing + index() In this, we reverse the list using slicing, and use ~ operator to get negation, index() is used to get the desired negative index. Python3 # Python3 code to demonstrate working of# Negative index of Element# Using ~ operator + list slicing + index() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing ElementK = 3 # -1 operator to reverse list, index() used to get indexres = ~test_list[::-1].index(K) # printing resultprint("The required Negative index : " + str(res)) Output: The original list is : [5, 7, 8, 2, 3, 5, 1] The required Negative index : -3 pulkitagarwal03pulkit Python list-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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Oct, 2020" }, { "code": null, "e": 117, "s": 54, "text": "Given a list of elements, find its negative index in the List." }, { "code": null, "e": 220, "s": 117, "text": "Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 2 Output : -4 Explanation : 2 is 4th element from rear." }, { "code": null, "e": 324, "s": 220, "text": "Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5 Output : -2 Explanation : 5 is 2nd element from rear. " }, { "code": null, "e": 358, "s": 324, "text": "Method #1 : Using index() + len()" }, { "code": null, "e": 484, "s": 358, "text": "In this, we get the index of the element using index(), and then subtract it from the list length to get the required result." }, { "code": null, "e": 492, "s": 484, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Negative index of Element# Using index() + len() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ElementK = 3 # getting length using len() and subtracting index from itres = len(test_list) - test_list.index(K) # printing resultprint(\"The required Negative index : -\" + str(res))", "e": 907, "s": 492, "text": null }, { "code": null, "e": 917, "s": 907, "text": " Output:" }, { "code": null, "e": 995, "s": 917, "text": "The original list is : [5, 7, 8, 2, 3, 5, 1]\nThe required Negative index : -3" }, { "code": null, "e": 1051, "s": 997, "text": "Method #2 : Using ~ operator + list slicing + index()" }, { "code": null, "e": 1183, "s": 1051, "text": "In this, we reverse the list using slicing, and use ~ operator to get negation, index() is used to get the desired negative index. " }, { "code": null, "e": 1191, "s": 1183, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Negative index of Element# Using ~ operator + list slicing + index() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ElementK = 3 # -1 operator to reverse list, index() used to get indexres = ~test_list[::-1].index(K) # printing resultprint(\"The required Negative index : \" + str(res))", "e": 1613, "s": 1191, "text": null }, { "code": null, "e": 1622, "s": 1613, "text": " Output:" }, { "code": null, "e": 1700, "s": 1622, "text": "The original list is : [5, 7, 8, 2, 3, 5, 1]\nThe required Negative index : -3" }, { "code": null, "e": 1722, "s": 1700, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 1743, "s": 1722, "text": "Python list-programs" }, { "code": null, "e": 1750, "s": 1743, "text": "Python" }, { "code": null, "e": 1766, "s": 1750, "text": "Python Programs" }, { "code": null, "e": 1864, "s": 1766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1896, "s": 1864, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1923, "s": 1896, "text": "Python Classes and Objects" }, { "code": null, "e": 1944, "s": 1923, "text": "Python OOPs Concepts" }, { "code": null, "e": 1967, "s": 1944, "text": "Introduction To PYTHON" }, { "code": null, "e": 2023, "s": 1967, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2045, "s": 2023, "text": "Defaultdict in Python" }, { "code": null, "e": 2084, "s": 2045, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2122, "s": 2084, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2171, "s": 2122, "text": "Python | Convert string dictionary to dictionary" } ]
Projection Profile method
25 Jun, 2019 In Image Processing, projection profile refers to projection of sum of hits/positives along an axis from bi-dimensional image. Projection profile method is majorly used for segmentation of text objects present inside text documents. Solution: Note: Projection profile is calculated for a thresholded image or binarized image where a thresholded image is a grayscale image with pixel values as 0 or 255. Image pixels are replaced by 1 and 0 for pixel values 0 and 255 respectively. Projection profile is calculated separately for different axis. Projection profile along vertical axis is called Vertical Projection profile. Vertical projection profile is calculated for every column as sum of all row pixel values inside the column. Horizontal Projection profile is the projection profile of a image along horizontal axis. Horizontal Projection profile is calculated for every row as sum of all column pixel values inside the row. Code Implementation for Horizontal Projection Profile: C++ Python3 #include <bits/stdc++.h>using namespace std; // Function to generate horizontal projection profilevector<int> getHorizontalProjectionProfile( vector<vector<int> > image, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Convert black spots to ones if (image[i][j] == 0) { image[i][j] = 1; } // Convert white spots to zeros else if (image[i][j] == 255) { image[i][j] = 0; } } } vector<int> horizontal_projection(rows, 0); // Calculate sum of 1's for every row for (int i = 0; i < rows; i++) { // Sum all 1's for (int j = 0; j < cols; j++) { horizontal_projection[i] += image[i][j]; } } return horizontal_projection;}// Driver Functionint main(){ int rows = 5, cols = 3; vector<vector<int> > image = { { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 } }; vector<int> horizontal_projection = getHorizontalProjectionProfile( image, rows, cols); for (auto it : horizontal_projection) { cout << it << " "; } return 0;} import numpy as np # Function to generate horizontal projection profiledef getHorizontalProjectionProfile(image): # Convert black spots to ones image[image == 0] = 1 # Convert white spots to zeros image[image == 255] = 0 horizontal_projection = np.sum(image, axis = 1) return horizontal_projection # Driver Functionif __name__ == '__main__': rows = 5 cols = 3 image = np.array([[0, 0, 0], [0, 255, 255], [0, 0, 0], [0, 255, 255], [0, 0, 0]]) horizontal_projection = getHorizontalProjectionProfile(image.copy()) print(*horizontal_projection) 3 1 3 1 3 Code Implementation for Vertical Projection Profile: C++ Python3 #include <bits/stdc++.h>using namespace std; // Function to generate vertical projection profilevector<int> getVerticalProjectionProfile( vector<vector<int> > image, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Convert black spots to ones if (image[i][j] == 0) { image[i][j] = 1; } // Convert white spots to zeros else if (image[i][j] == 255) { image[i][j] = 0; } } } vector<int> vertical_projection(cols, 0); // Calculate sum of 1's for every column for (int j = 0; j < cols; j++) { // Sum all 1's for (int i = 0; i < rows; i++) { vertical_projection[j] += image[i][j]; } } return vertical_projection;} // Driver Functionint main(){ int rows = 5, cols = 3; vector<vector<int> > image = { { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 } }; vector<int> vertical_projection = getVerticalProjectionProfile( image, rows, cols); for (auto it : vertical_projection) { cout << it << " "; } return 0;} import numpy as np # Function to generate vertical projection profiledef getVerticalProjectionProfile(image): # Convert black spots to ones image[image == 0] = 1 # Convert white spots to zeros image[image == 255] = 0 vertical_projection = np.sum(image, axis = 0) return vertical_projection # Driver Functionif __name__ == '__main__': rows = 5 cols = 3 image = np.array([[0, 0, 0], [0, 255, 255], [0, 0, 0], [0, 255, 255], [0, 0, 0]]) vertical_projection = getVerticalProjectionProfile(image.copy()) print(*vertical_projection) 5 3 3 Time Complexity: O(rows*columns)Space Complexity: O(rows*columns) Image-Processing 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": 261, "s": 28, "text": "In Image Processing, projection profile refers to projection of sum of hits/positives along an axis from bi-dimensional image. Projection profile method is majorly used for segmentation of text objects present inside text documents." }, { "code": null, "e": 271, "s": 261, "text": "Solution:" }, { "code": null, "e": 509, "s": 271, "text": "Note: Projection profile is calculated for a thresholded image or binarized image where a thresholded image is a grayscale image with pixel values as 0 or 255. Image pixels are replaced by 1 and 0 for pixel values 0 and 255 respectively." }, { "code": null, "e": 958, "s": 509, "text": "Projection profile is calculated separately for different axis. Projection profile along vertical axis is called Vertical Projection profile. Vertical projection profile is calculated for every column as sum of all row pixel values inside the column. Horizontal Projection profile is the projection profile of a image along horizontal axis. Horizontal Projection profile is calculated for every row as sum of all column pixel values inside the row." }, { "code": null, "e": 1013, "s": 958, "text": "Code Implementation for Horizontal Projection Profile:" }, { "code": null, "e": 1017, "s": 1013, "text": "C++" }, { "code": null, "e": 1025, "s": 1017, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to generate horizontal projection profilevector<int> getHorizontalProjectionProfile( vector<vector<int> > image, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Convert black spots to ones if (image[i][j] == 0) { image[i][j] = 1; } // Convert white spots to zeros else if (image[i][j] == 255) { image[i][j] = 0; } } } vector<int> horizontal_projection(rows, 0); // Calculate sum of 1's for every row for (int i = 0; i < rows; i++) { // Sum all 1's for (int j = 0; j < cols; j++) { horizontal_projection[i] += image[i][j]; } } return horizontal_projection;}// Driver Functionint main(){ int rows = 5, cols = 3; vector<vector<int> > image = { { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 } }; vector<int> horizontal_projection = getHorizontalProjectionProfile( image, rows, cols); for (auto it : horizontal_projection) { cout << it << \" \"; } return 0;}", "e": 2319, "s": 1025, "text": null }, { "code": "import numpy as np # Function to generate horizontal projection profiledef getHorizontalProjectionProfile(image): # Convert black spots to ones image[image == 0] = 1 # Convert white spots to zeros image[image == 255] = 0 horizontal_projection = np.sum(image, axis = 1) return horizontal_projection # Driver Functionif __name__ == '__main__': rows = 5 cols = 3 image = np.array([[0, 0, 0], [0, 255, 255], [0, 0, 0], [0, 255, 255], [0, 0, 0]]) horizontal_projection = getHorizontalProjectionProfile(image.copy()) print(*horizontal_projection)", "e": 2960, "s": 2319, "text": null }, { "code": null, "e": 2971, "s": 2960, "text": "3 1 3 1 3\n" }, { "code": null, "e": 3024, "s": 2971, "text": "Code Implementation for Vertical Projection Profile:" }, { "code": null, "e": 3028, "s": 3024, "text": "C++" }, { "code": null, "e": 3036, "s": 3028, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to generate vertical projection profilevector<int> getVerticalProjectionProfile( vector<vector<int> > image, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Convert black spots to ones if (image[i][j] == 0) { image[i][j] = 1; } // Convert white spots to zeros else if (image[i][j] == 255) { image[i][j] = 0; } } } vector<int> vertical_projection(cols, 0); // Calculate sum of 1's for every column for (int j = 0; j < cols; j++) { // Sum all 1's for (int i = 0; i < rows; i++) { vertical_projection[j] += image[i][j]; } } return vertical_projection;} // Driver Functionint main(){ int rows = 5, cols = 3; vector<vector<int> > image = { { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 }, { 0, 255, 255 }, { 0, 0, 0 } }; vector<int> vertical_projection = getVerticalProjectionProfile( image, rows, cols); for (auto it : vertical_projection) { cout << it << \" \"; } return 0;}", "e": 4317, "s": 3036, "text": null }, { "code": "import numpy as np # Function to generate vertical projection profiledef getVerticalProjectionProfile(image): # Convert black spots to ones image[image == 0] = 1 # Convert white spots to zeros image[image == 255] = 0 vertical_projection = np.sum(image, axis = 0) return vertical_projection # Driver Functionif __name__ == '__main__': rows = 5 cols = 3 image = np.array([[0, 0, 0], [0, 255, 255], [0, 0, 0], [0, 255, 255], [0, 0, 0]]) vertical_projection = getVerticalProjectionProfile(image.copy()) print(*vertical_projection)", "e": 4939, "s": 4317, "text": null }, { "code": null, "e": 4946, "s": 4939, "text": "5 3 3\n" }, { "code": null, "e": 5012, "s": 4946, "text": "Time Complexity: O(rows*columns)Space Complexity: O(rows*columns)" }, { "code": null, "e": 5029, "s": 5012, "text": "Image-Processing" }, { "code": null, "e": 5036, "s": 5029, "text": "Python" } ]
How to initialize array in Ruby
24 Oct, 2019 In this article, we will learn how to initialize the array in Ruby. There are several ways to create an array. Let’s see each of them one by one. new method can be used to create the arrays with the help of dot operator. Using arguments we can provide the size to array and elements to array. Without any argument – # creating array using new method # without passing any parameter arr = Array.new() # displaying the size of arrays # using size method puts arr.size Output: 0 Passing size of array as parameter – # creating array using new method # passing one parameter i.e. the # size of array arr2 = Array.new(7) # displaying the length of arrays # using length method puts arr2.length Output: 7 Passing size of array and elements as parameter – # creating array using new method # passing two parameters i.e. the # size of array & element of array arr3 = Array.new(4, "GFG") puts "#{arr3}" Output: ["GFG", "GFG", "GFG", "GFG"] In Ruby, [] is known as the literal constructor which can be used to create the arrays. # Ruby program to demonstrate the # creation of array using literal # constructor[] and to find the size # and length of array # creating array of characters arr = Array['a', 'b', 'c', 'd', 'e', 'f'] # displaying array elements puts "#{arr}" # displaying array size puts "Size of arr is: #{arr.size}" # displaying array length puts "Length of arr is: #{arr.length}" Output: ["a", "b", "c", "d", "e", "f"] [1, 2, 3, 4, 5, 6, 7] Size of arr is: 6 Length of arr is: 6 arr1 = ('1'..'6').to_a # displaying array elements puts "#{arr1}" arr2 = *'11'..'15'puts "#{arr2}" Output: ["1", "2", "3", "4", "5", "6"] ["11", "12", "13", "14", "15"] Ruby Array Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2019" }, { "code": null, "e": 174, "s": 28, "text": "In this article, we will learn how to initialize the array in Ruby. There are several ways to create an array. Let’s see each of them one by one." }, { "code": null, "e": 321, "s": 174, "text": "new method can be used to create the arrays with the help of dot operator. Using arguments we can provide the size to array and elements to array." }, { "code": null, "e": 344, "s": 321, "text": "Without any argument –" }, { "code": "# creating array using new method # without passing any parameter arr = Array.new() # displaying the size of arrays # using size method puts arr.size ", "e": 498, "s": 344, "text": null }, { "code": null, "e": 506, "s": 498, "text": "Output:" }, { "code": null, "e": 508, "s": 506, "text": "0" }, { "code": null, "e": 545, "s": 508, "text": "Passing size of array as parameter –" }, { "code": "# creating array using new method # passing one parameter i.e. the # size of array arr2 = Array.new(7) # displaying the length of arrays # using length method puts arr2.length ", "e": 727, "s": 545, "text": null }, { "code": null, "e": 735, "s": 727, "text": "Output:" }, { "code": null, "e": 737, "s": 735, "text": "7" }, { "code": null, "e": 787, "s": 737, "text": "Passing size of array and elements as parameter –" }, { "code": "# creating array using new method # passing two parameters i.e. the # size of array & element of array arr3 = Array.new(4, \"GFG\") puts \"#{arr3}\"", "e": 936, "s": 787, "text": null }, { "code": null, "e": 944, "s": 936, "text": "Output:" }, { "code": null, "e": 973, "s": 944, "text": "[\"GFG\", \"GFG\", \"GFG\", \"GFG\"]" }, { "code": null, "e": 1061, "s": 973, "text": "In Ruby, [] is known as the literal constructor which can be used to create the arrays." }, { "code": "# Ruby program to demonstrate the # creation of array using literal # constructor[] and to find the size # and length of array # creating array of characters arr = Array['a', 'b', 'c', 'd', 'e', 'f'] # displaying array elements puts \"#{arr}\" # displaying array size puts \"Size of arr is: #{arr.size}\" # displaying array length puts \"Length of arr is: #{arr.length}\"", "e": 1444, "s": 1061, "text": null }, { "code": null, "e": 1452, "s": 1444, "text": "Output:" }, { "code": null, "e": 1543, "s": 1452, "text": "[\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n[1, 2, 3, 4, 5, 6, 7]\nSize of arr is: 6\nLength of arr is: 6" }, { "code": "arr1 = ('1'..'6').to_a # displaying array elements puts \"#{arr1}\" arr2 = *'11'..'15'puts \"#{arr2}\"", "e": 1644, "s": 1543, "text": null }, { "code": null, "e": 1652, "s": 1644, "text": "Output:" }, { "code": null, "e": 1715, "s": 1652, "text": "[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]\n[\"11\", \"12\", \"13\", \"14\", \"15\"]\n" }, { "code": null, "e": 1726, "s": 1715, "text": "Ruby Array" }, { "code": null, "e": 1731, "s": 1726, "text": "Ruby" } ]
Statistics with Python
27 Sep, 2021 Statistics, in general, is the method of collection of data, tabulation, and interpretation of numerical data. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. With statistics, we can see how data can be used to solve complex problems. In this tutorial, we will learn about solving statistical problems with Python and will also learn the concept behind it. Let’s start by understanding some concepts that will be useful throughout the article. Note: We will be covering descriptive statistics with the help of the statistics module provided by Python. In a layman’s term, descriptive statistics generally means describing the data with the help of some representative methods like charts, tables, Excel files, etc. The data is described in such a way that it can express some meaningful information that can also be used to find some future trends. Describing and summarizing a single variable is called univariate analysis. Describing a statistical relationship between two variables is called bivariate analysis. Describing the statistical relationship between multiple variables is called multivariate analysis. There are two types of descriptive Statistics – Measure of central tendency Measure of variability The measure of central tendency is a single value that attempts to describe the whole set of data. There are three main features of central tendency – Mean MedianMedian LowMedian High Median Low Median High Mode It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count. The mean() function returns the mean or average of the data passed in its arguments. If passed argument is empty, StatisticsError is raised. Example: Python3 # Python code to demonstrate the working of# mean() # importing statistics to handle statistical# operationsimport statistics # initializing listli = [1, 2, 3, 3, 2, 2, 2, 1] # using mean() to calculate average of list# elementsprint ("The average of list values is : ",end="")print (statistics.mean(li)) Output: The average of list values is : 2 It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements. For Odd Numbers: For Even Numbers: median() function is used to calculate the median, i.e middle element of data. If the passed argument is empty, StatisticsError is raised. Example: Python3 # Python code to demonstrate the# working of median() on various# range of data-sets # importing the statistics modulefrom statistics import median # Importing fractions module as frfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 4, 5, 7, 9, 11) # tuple of floating point valuesdata2 = (2.4, 5.1, 6.7, 8.9) # tuple of fractional numbersdata3 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-5, -1, -12, -19, -3) # tuple of set of positive# and negative integersdata5 = (-1, -2, -3, -4, 4, 3, 2, 1) # Printing the median of above datasetsprint("Median of data-set 1 is % s" % (median(data1)))print("Median of data-set 2 is % s" % (median(data2)))print("Median of data-set 3 is % s" % (median(data3)))print("Median of data-set 4 is % s" % (median(data4)))print("Median of data-set 5 is % s" % (median(data5))) Output: Median of data-set 1 is 5 Median of data-set 2 is 5.9 Median of data-set 3 is 2 Median of data-set 4 is -5 Median of data-set 5 is 0.0 median_low() function returns the median of data in case of odd number of elements, but in case of even number of elements, returns the lower of two middle elements. If the passed argument is empty, StatisticsError is raised Example: Python3 # Python code to demonstrate the# working of median_low() # importing the statistics moduleimport statistics # simple list of a set of integersset1 = [1, 3, 3, 4, 5, 7] # Print median of the data-set # Median value may or may not# lie within the data-setprint("Median of the set is % s" % (statistics.median(set1))) # Print low median of the data-setprint("Low Median of the set is % s " % (statistics.median_low(set1))) Output: Median of the set is 3.5 Low Median of the set is 3 median_high() function returns the median of data in case of odd number of elements, but in case of even number of elements, returns the higher of two middle elements. If passed argument is empty, StatisticsError is raised. Example: Python3 # Working of median_high() and median() to# demonstrate the difference between them. # importing the statistics moduleimport statistics # simple list of a set of integersset1 = [1, 3, 3, 4, 5, 7] # Print median of the data-set # Median value may or may not# lie within the data-setprint("Median of the set is %s" % (statistics.median(set1))) # Print high median of the data-setprint("High Median of the set is %s " % (statistics.median_high(set1))) Output: Median of the set is 3.5 High Median of the set is 4 It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency. mode() function returns the number with the maximum number of occurrences. If the passed argument is empty, StatisticsError is raised. Example: Python3 # Python code to demonstrate the# working of mode() function# on a various range of data types # Importing the statistics modulefrom statistics import mode # Importing fractions module as fr# Enables to calculate harmonic_mean of a# set in Fractionfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7) # tuple of a set of floating point valuesdata2 = (2.4, 1.3, 1.3, 1.3, 2.4, 4.6) # tuple of a set of fractional numbersdata3 = (fr(1, 2), fr(1, 2), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-1, -2, -2, -2, -7, -7, -9) # tuple of stringsdata5 = ("red", "blue", "black", "blue", "black", "black", "brown") # Printing out the mode of the above data-setsprint("Mode of data set 1 is % s" % (mode(data1)))print("Mode of data set 2 is % s" % (mode(data2)))print("Mode of data set 3 is % s" % (mode(data3)))print("Mode of data set 4 is % s" % (mode(data4)))print("Mode of data set 5 is % s" % (mode(data5))) Output: Mode of data set 1 is 5 Mode of data set 2 is 1.3 Mode of data set 3 is 1/2 Mode of data set 4 is -2 Mode of data set 5 is black Refer to the below article to get detailed information about averages and Measures of central tendency. Statistical Functions in Python | Set 1 (Averages and Measure of Central Location) Till now, we have studied the measure of central tendency but this alone is not sufficient to describe the data. To overcome this we need the measure of variability. Measure of variability is known as the spread of data or how well is our data is distributed. The most common variability measures are: Range Variance Standard deviation The difference between the largest and smallest data point in our data set is known as the range. The range is directly proportional to the spread of data that means the bigger the range, more the spread of data and vice versa. Range = Largest data value – smallest data value We can calculate the maximum and minimum value using the max() and min() methods respectively. Example: Python3 # Sample Dataarr = [1, 2, 3, 4, 5] #Finding MaxMaximum = max(arr)# Finding MinMinimum = min(arr) # Difference Of Max and MinRange = Maximum-Minimum print("Maximum = {}, Minimum = {} and Range = {}".format( Maximum, Minimum, Range)) Output: Maximum = 5, Minimum = 1 and Range = 4 It is defined as an average squared deviation from the mean. It is being calculated by finding the difference between every data point and the average which is also known as the mean, squaring them, adding all of them, and then dividing by the number of data points present in our data set. where N = number of terms u = Mean The statistics module provides the variance() method that does all the maths behind the scene. If passed argument is empty, StatisticsError is raised. Example: Python3 # Python code to demonstrate variance()# function on varying range of data-types # importing statistics modulefrom statistics import variance # importing fractions as parameter valuesfrom fractions import Fraction as fr # tuple of a set of positive integers# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of fractional numberssample4 = (fr(1, 2), fr(2, 3), fr(3, 4), fr(5, 6), fr(7, 8)) # tuple of a set of floating point valuessample5 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the variance of each samplesprint("Variance of Sample1 is % s " % (variance(sample1)))print("Variance of Sample2 is % s " % (variance(sample2)))print("Variance of Sample3 is % s " % (variance(sample3)))print("Variance of Sample4 is % s " % (variance(sample4)))print("Variance of Sample5 is % s " % (variance(sample5))) Output: Variance of Sample1 is 15.80952380952381 Variance of Sample2 is 3.5 Variance of Sample3 is 61.125 Variance of Sample4 is 1/45 Variance of Sample5 is 0.17613000000000006 It is defined as the square root of the variance. It is being calculated by finding the Mean, then subtract each number from the Mean which is also known as average and square the result. Adding all the values and then divide by the no of terms followed the square root. where N = number of terms u = Mean stdev() method of the statistics module returns the standard deviation of the data. If passed argument is empty, StatisticsError is raised. Example: Python3 # Python code to demonstrate stdev()# function on various range of datasets # importing the statistics modulefrom statistics import stdev # importing fractions as parameter valuesfrom fractions import Fraction as fr # creating a varying range of sample sets# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of floating point valuessample4 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the standard deviation of# following sample sets of observationsprint("The Standard Deviation of Sample1 is % s" % (stdev(sample1))) print("The Standard Deviation of Sample2 is % s" % (stdev(sample2))) print("The Standard Deviation of Sample3 is % s" % (stdev(sample3))) print("The Standard Deviation of Sample4 is % s" % (stdev(sample4))) Output: The Standard Deviation of Sample1 is 3.9761191895520196 The Standard Deviation of Sample2 is 1.8708286933869707 The Standard Deviation of Sample3 is 7.8182478855559445 The Standard Deviation of Sample4 is 0.41967844833872525 Refer to the below article to get detailed information about the Measure of variability. Statistical Functions in Python | Set 2 ( Measure of Spread) kalrap615 adnanirshad158 abhishek0719kadiyan ML-Statistics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Sep, 2021" }, { "code": null, "e": 350, "s": 52, "text": "Statistics, in general, is the method of collection of data, tabulation, and interpretation of numerical data. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. With statistics, we can see how data can be used to solve complex problems. " }, { "code": null, "e": 559, "s": 350, "text": "In this tutorial, we will learn about solving statistical problems with Python and will also learn the concept behind it. Let’s start by understanding some concepts that will be useful throughout the article." }, { "code": null, "e": 667, "s": 559, "text": "Note: We will be covering descriptive statistics with the help of the statistics module provided by Python." }, { "code": null, "e": 1230, "s": 667, "text": "In a layman’s term, descriptive statistics generally means describing the data with the help of some representative methods like charts, tables, Excel files, etc. The data is described in such a way that it can express some meaningful information that can also be used to find some future trends. Describing and summarizing a single variable is called univariate analysis. Describing a statistical relationship between two variables is called bivariate analysis. Describing the statistical relationship between multiple variables is called multivariate analysis." }, { "code": null, "e": 1279, "s": 1230, "text": "There are two types of descriptive Statistics – " }, { "code": null, "e": 1307, "s": 1279, "text": "Measure of central tendency" }, { "code": null, "e": 1330, "s": 1307, "text": "Measure of variability" }, { "code": null, "e": 1482, "s": 1330, "text": "The measure of central tendency is a single value that attempts to describe the whole set of data. There are three main features of central tendency – " }, { "code": null, "e": 1487, "s": 1482, "text": "Mean" }, { "code": null, "e": 1515, "s": 1487, "text": "MedianMedian LowMedian High" }, { "code": null, "e": 1526, "s": 1515, "text": "Median Low" }, { "code": null, "e": 1538, "s": 1526, "text": "Median High" }, { "code": null, "e": 1543, "s": 1538, "text": "Mode" }, { "code": null, "e": 1684, "s": 1543, "text": "It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count. " }, { "code": null, "e": 1825, "s": 1684, "text": "The mean() function returns the mean or average of the data passed in its arguments. If passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 1834, "s": 1825, "text": "Example:" }, { "code": null, "e": 1842, "s": 1834, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# mean() # importing statistics to handle statistical# operationsimport statistics # initializing listli = [1, 2, 3, 3, 2, 2, 2, 1] # using mean() to calculate average of list# elementsprint (\"The average of list values is : \",end=\"\")print (statistics.mean(li))", "e": 2147, "s": 1842, "text": null }, { "code": null, "e": 2155, "s": 2147, "text": "Output:" }, { "code": null, "e": 2189, "s": 2155, "text": "The average of list values is : 2" }, { "code": null, "e": 2429, "s": 2189, "text": "It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements. " }, { "code": null, "e": 2446, "s": 2429, "text": "For Odd Numbers:" }, { "code": null, "e": 2464, "s": 2446, "text": "For Even Numbers:" }, { "code": null, "e": 2603, "s": 2464, "text": "median() function is used to calculate the median, i.e middle element of data. If the passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 2612, "s": 2603, "text": "Example:" }, { "code": null, "e": 2620, "s": 2612, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of median() on various# range of data-sets # importing the statistics modulefrom statistics import median # Importing fractions module as frfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 4, 5, 7, 9, 11) # tuple of floating point valuesdata2 = (2.4, 5.1, 6.7, 8.9) # tuple of fractional numbersdata3 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-5, -1, -12, -19, -3) # tuple of set of positive# and negative integersdata5 = (-1, -2, -3, -4, 4, 3, 2, 1) # Printing the median of above datasetsprint(\"Median of data-set 1 is % s\" % (median(data1)))print(\"Median of data-set 2 is % s\" % (median(data2)))print(\"Median of data-set 3 is % s\" % (median(data3)))print(\"Median of data-set 4 is % s\" % (median(data4)))print(\"Median of data-set 5 is % s\" % (median(data5)))", "e": 3518, "s": 2620, "text": null }, { "code": null, "e": 3526, "s": 3518, "text": "Output:" }, { "code": null, "e": 3661, "s": 3526, "text": "Median of data-set 1 is 5\nMedian of data-set 2 is 5.9\nMedian of data-set 3 is 2\nMedian of data-set 4 is -5\nMedian of data-set 5 is 0.0" }, { "code": null, "e": 3886, "s": 3661, "text": "median_low() function returns the median of data in case of odd number of elements, but in case of even number of elements, returns the lower of two middle elements. If the passed argument is empty, StatisticsError is raised" }, { "code": null, "e": 3895, "s": 3886, "text": "Example:" }, { "code": null, "e": 3903, "s": 3895, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of median_low() # importing the statistics moduleimport statistics # simple list of a set of integersset1 = [1, 3, 3, 4, 5, 7] # Print median of the data-set # Median value may or may not# lie within the data-setprint(\"Median of the set is % s\" % (statistics.median(set1))) # Print low median of the data-setprint(\"Low Median of the set is % s \" % (statistics.median_low(set1)))", "e": 4330, "s": 3903, "text": null }, { "code": null, "e": 4338, "s": 4330, "text": "Output:" }, { "code": null, "e": 4391, "s": 4338, "text": "Median of the set is 3.5\nLow Median of the set is 3 " }, { "code": null, "e": 4615, "s": 4391, "text": "median_high() function returns the median of data in case of odd number of elements, but in case of even number of elements, returns the higher of two middle elements. If passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 4624, "s": 4615, "text": "Example:" }, { "code": null, "e": 4632, "s": 4624, "text": "Python3" }, { "code": "# Working of median_high() and median() to# demonstrate the difference between them. # importing the statistics moduleimport statistics # simple list of a set of integersset1 = [1, 3, 3, 4, 5, 7] # Print median of the data-set # Median value may or may not# lie within the data-setprint(\"Median of the set is %s\" % (statistics.median(set1))) # Print high median of the data-setprint(\"High Median of the set is %s \" % (statistics.median_high(set1)))", "e": 5087, "s": 4632, "text": null }, { "code": null, "e": 5095, "s": 5087, "text": "Output:" }, { "code": null, "e": 5149, "s": 5095, "text": "Median of the set is 3.5\nHigh Median of the set is 4 " }, { "code": null, "e": 5403, "s": 5149, "text": "It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency. " }, { "code": null, "e": 5538, "s": 5403, "text": "mode() function returns the number with the maximum number of occurrences. If the passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 5547, "s": 5538, "text": "Example:" }, { "code": null, "e": 5555, "s": 5547, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of mode() function# on a various range of data types # Importing the statistics modulefrom statistics import mode # Importing fractions module as fr# Enables to calculate harmonic_mean of a# set in Fractionfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7) # tuple of a set of floating point valuesdata2 = (2.4, 1.3, 1.3, 1.3, 2.4, 4.6) # tuple of a set of fractional numbersdata3 = (fr(1, 2), fr(1, 2), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-1, -2, -2, -2, -7, -7, -9) # tuple of stringsdata5 = (\"red\", \"blue\", \"black\", \"blue\", \"black\", \"black\", \"brown\") # Printing out the mode of the above data-setsprint(\"Mode of data set 1 is % s\" % (mode(data1)))print(\"Mode of data set 2 is % s\" % (mode(data2)))print(\"Mode of data set 3 is % s\" % (mode(data3)))print(\"Mode of data set 4 is % s\" % (mode(data4)))print(\"Mode of data set 5 is % s\" % (mode(data5)))", "e": 6546, "s": 5555, "text": null }, { "code": null, "e": 6554, "s": 6546, "text": "Output:" }, { "code": null, "e": 6683, "s": 6554, "text": "Mode of data set 1 is 5\nMode of data set 2 is 1.3\nMode of data set 3 is 1/2\nMode of data set 4 is -2\nMode of data set 5 is black" }, { "code": null, "e": 6787, "s": 6683, "text": "Refer to the below article to get detailed information about averages and Measures of central tendency." }, { "code": null, "e": 6870, "s": 6787, "text": "Statistical Functions in Python | Set 1 (Averages and Measure of Central Location)" }, { "code": null, "e": 7172, "s": 6870, "text": "Till now, we have studied the measure of central tendency but this alone is not sufficient to describe the data. To overcome this we need the measure of variability. Measure of variability is known as the spread of data or how well is our data is distributed. The most common variability measures are:" }, { "code": null, "e": 7178, "s": 7172, "text": "Range" }, { "code": null, "e": 7187, "s": 7178, "text": "Variance" }, { "code": null, "e": 7206, "s": 7187, "text": "Standard deviation" }, { "code": null, "e": 7434, "s": 7206, "text": "The difference between the largest and smallest data point in our data set is known as the range. The range is directly proportional to the spread of data that means the bigger the range, more the spread of data and vice versa." }, { "code": null, "e": 7483, "s": 7434, "text": "Range = Largest data value – smallest data value" }, { "code": null, "e": 7578, "s": 7483, "text": "We can calculate the maximum and minimum value using the max() and min() methods respectively." }, { "code": null, "e": 7587, "s": 7578, "text": "Example:" }, { "code": null, "e": 7595, "s": 7587, "text": "Python3" }, { "code": "# Sample Dataarr = [1, 2, 3, 4, 5] #Finding MaxMaximum = max(arr)# Finding MinMinimum = min(arr) # Difference Of Max and MinRange = Maximum-Minimum print(\"Maximum = {}, Minimum = {} and Range = {}\".format( Maximum, Minimum, Range))", "e": 7833, "s": 7595, "text": null }, { "code": null, "e": 7841, "s": 7833, "text": "Output:" }, { "code": null, "e": 7880, "s": 7841, "text": "Maximum = 5, Minimum = 1 and Range = 4" }, { "code": null, "e": 8171, "s": 7880, "text": "It is defined as an average squared deviation from the mean. It is being calculated by finding the difference between every data point and the average which is also known as the mean, squaring them, adding all of them, and then dividing by the number of data points present in our data set." }, { "code": null, "e": 8197, "s": 8171, "text": "where N = number of terms" }, { "code": null, "e": 8206, "s": 8197, "text": "u = Mean" }, { "code": null, "e": 8357, "s": 8206, "text": "The statistics module provides the variance() method that does all the maths behind the scene. If passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 8366, "s": 8357, "text": "Example:" }, { "code": null, "e": 8374, "s": 8366, "text": "Python3" }, { "code": "# Python code to demonstrate variance()# function on varying range of data-types # importing statistics modulefrom statistics import variance # importing fractions as parameter valuesfrom fractions import Fraction as fr # tuple of a set of positive integers# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of fractional numberssample4 = (fr(1, 2), fr(2, 3), fr(3, 4), fr(5, 6), fr(7, 8)) # tuple of a set of floating point valuessample5 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the variance of each samplesprint(\"Variance of Sample1 is % s \" % (variance(sample1)))print(\"Variance of Sample2 is % s \" % (variance(sample2)))print(\"Variance of Sample3 is % s \" % (variance(sample3)))print(\"Variance of Sample4 is % s \" % (variance(sample4)))print(\"Variance of Sample5 is % s \" % (variance(sample5)))", "e": 9426, "s": 8374, "text": null }, { "code": null, "e": 9434, "s": 9426, "text": "Output:" }, { "code": null, "e": 9608, "s": 9434, "text": "Variance of Sample1 is 15.80952380952381 \nVariance of Sample2 is 3.5 \nVariance of Sample3 is 61.125 \nVariance of Sample4 is 1/45 \nVariance of Sample5 is 0.17613000000000006 " }, { "code": null, "e": 9879, "s": 9608, "text": "It is defined as the square root of the variance. It is being calculated by finding the Mean, then subtract each number from the Mean which is also known as average and square the result. Adding all the values and then divide by the no of terms followed the square root." }, { "code": null, "e": 9905, "s": 9879, "text": "where N = number of terms" }, { "code": null, "e": 9914, "s": 9905, "text": "u = Mean" }, { "code": null, "e": 10054, "s": 9914, "text": "stdev() method of the statistics module returns the standard deviation of the data. If passed argument is empty, StatisticsError is raised." }, { "code": null, "e": 10063, "s": 10054, "text": "Example:" }, { "code": null, "e": 10071, "s": 10063, "text": "Python3" }, { "code": "# Python code to demonstrate stdev()# function on various range of datasets # importing the statistics modulefrom statistics import stdev # importing fractions as parameter valuesfrom fractions import Fraction as fr # creating a varying range of sample sets# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of floating point valuessample4 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the standard deviation of# following sample sets of observationsprint(\"The Standard Deviation of Sample1 is % s\" % (stdev(sample1))) print(\"The Standard Deviation of Sample2 is % s\" % (stdev(sample2))) print(\"The Standard Deviation of Sample3 is % s\" % (stdev(sample3))) print(\"The Standard Deviation of Sample4 is % s\" % (stdev(sample4)))", "e": 11056, "s": 10071, "text": null }, { "code": null, "e": 11064, "s": 11056, "text": "Output:" }, { "code": null, "e": 11289, "s": 11064, "text": "The Standard Deviation of Sample1 is 3.9761191895520196\nThe Standard Deviation of Sample2 is 1.8708286933869707\nThe Standard Deviation of Sample3 is 7.8182478855559445\nThe Standard Deviation of Sample4 is 0.41967844833872525" }, { "code": null, "e": 11378, "s": 11289, "text": "Refer to the below article to get detailed information about the Measure of variability." }, { "code": null, "e": 11439, "s": 11378, "text": "Statistical Functions in Python | Set 2 ( Measure of Spread)" }, { "code": null, "e": 11449, "s": 11439, "text": "kalrap615" }, { "code": null, "e": 11464, "s": 11449, "text": "adnanirshad158" }, { "code": null, "e": 11484, "s": 11464, "text": "abhishek0719kadiyan" }, { "code": null, "e": 11498, "s": 11484, "text": "ML-Statistics" }, { "code": null, "e": 11505, "s": 11498, "text": "Python" }, { "code": null, "e": 11603, "s": 11505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11635, "s": 11603, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 11662, "s": 11635, "text": "Python Classes and Objects" }, { "code": null, "e": 11683, "s": 11662, "text": "Python OOPs Concepts" }, { "code": null, "e": 11706, "s": 11683, "text": "Introduction To PYTHON" }, { "code": null, "e": 11762, "s": 11706, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 11793, "s": 11762, "text": "Python | os.path.join() method" }, { "code": null, "e": 11835, "s": 11793, "text": "Check if element exists in list in Python" }, { "code": null, "e": 11877, "s": 11835, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 11916, "s": 11877, "text": "Python | Get unique values from a list" } ]
Gauss’s Forward Interpolation
17 Jun, 2021 Interpolation refers to the process of creating new data points given within the given set of data. The below code computes the desired data point within the given range of discrete data sets using the formula given by Gauss and this method known as Gauss’s Forward Method. Gauss’s Forward Method: The gaussian interpolation comes under the Central Difference Interpolation Formulae. Suppose we are given the following value of y=f(x) for a set values of x:X: x0 x1 x2 .......... xn Y: y0 y1 y2 ............ yn The differences y1 – y0, y2 – y1, y3 – y2, ......, yn – yn–1 when denoted by Ξ”y0, Ξ”y1, Ξ”y2, ......, Ξ”yn–1 are respectively, called the first forward differences. Thus the first forward differences are :Ξ”y0 = y1 – y0and in the same way we can calculate higher order differences. And after the creating table we calculate the value on the basis of following formula: Now, Let’s take an example and solve it for better understanding. Problem: From the following table, find the value of e1.17 using Gauss’s Forward formula. Solution: We have yp = y0 + pΞ”y0 + (p(p-1)/2!).Ξ”y20 + ((p+1)p(p-1)/3!).Ξ”y30 + ... where p = (x1.17 – x1.15) / h and h = x1 – x0 = 0.05so, p = 0.04Now, we need to calculate Ξ”y0, Ξ”y20, Ξ”y30 ... etc. Put the required values in the formula- yx = 1.17 = 3.158 + (2/5)(0.162) + (2/5)(2/5 – 1)/2.(0.008) ... yx = 1.17 = 3.2246Code : Python code for implementing Gauss’s Forward Formula Python3 # Python3 code for Gauss's Forward Formula# importing libraryimport numpy as np # function for calculating coefficient of Ydef p_cal(p, n): temp = p; for i in range(1, n): if(i%2==1): temp * (p - i) else: temp * (p + i) return temp;# function for factorialdef fact(n): f = 1 for i in range(2, n + 1): f *= i return f # storing available datan = 7;x = [ 1, 1.05, 1.10, 1.15, 1.20, 1.25, 1.30 ]; y = [[0 for i in range(n)] for j in range(n)];y[0][0] = 2.7183;y[1][0] = 2.8577;y[2][0] = 3.0042;y[3][0] = 3.1582; y[4][0] = 3.3201;y[5][0] = 3.4903;y[6][0] = 3.6693; # Generating Gauss's trianglefor i in range(1, n): for j in range(n - i): y[j][i] = np.round((y[j + 1][i - 1] - y[j][i - 1]),4); # Printing the Trianglefor i in range(n): print(x[i], end = "\t"); for j in range(n - i): print(y[i][j], end = "\t"); print(""); # Value of Y need to predict onvalue = 1.17; # implementing Formulasum = y[int(n/2)][0];p = (value - x[int(n/2)]) / (x[1] - x[0]) for i in range(1,n): # print(y[int((n-i)/2)][i]) sum = sum + (p_cal(p, i) * y[int((n-i)/2)][i]) / fact(i) print("\nValue at", value, "is", round(sum, 4)); Output : 1 2.7183 0.1394 0.0071 0.0004 0.0 0.0 0.0001 1.05 2.8577 0.1465 0.0075 0.0004 0.0 0.0001 1.1 3.0042 0.154 0.0079 0.0004 0.0001 1.15 3.1582 0.1619 0.0083 0.0005 1.2 3.3201 0.1702 0.0088 1.25 3.4903 0.179 1.3 3.6693 Value at 1.17 is 3.2246 adnanirshad158 Engineering Mathematics Engineering Mathematics Questions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Activation Functions Logic Notations in LaTeX Modular Arithmetic Mathematics | Introduction of Set theory Regular Graph in Graph Theory Abelian Group Example Homogeneous Poisson Process Mathematics concept required for Deep Learning Number of Pentagons and Hexagons on a Football
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 304, "s": 28, "text": "Interpolation refers to the process of creating new data points given within the given set of data. The below code computes the desired data point within the given range of discrete data sets using the formula given by Gauss and this method known as Gauss’s Forward Method. " }, { "code": null, "e": 330, "s": 306, "text": "Gauss’s Forward Method:" }, { "code": null, "e": 822, "s": 330, "text": "The gaussian interpolation comes under the Central Difference Interpolation Formulae. Suppose we are given the following value of y=f(x) for a set values of x:X: x0 x1 x2 .......... xn Y: y0 y1 y2 ............ yn The differences y1 – y0, y2 – y1, y3 – y2, ......, yn – yn–1 when denoted by Ξ”y0, Ξ”y1, Ξ”y2, ......, Ξ”yn–1 are respectively, called the first forward differences. Thus the first forward differences are :Ξ”y0 = y1 – y0and in the same way we can calculate higher order differences. " }, { "code": null, "e": 910, "s": 822, "text": "And after the creating table we calculate the value on the basis of following formula: " }, { "code": null, "e": 1066, "s": 910, "text": "Now, Let’s take an example and solve it for better understanding. Problem: From the following table, find the value of e1.17 using Gauss’s Forward formula." }, { "code": null, "e": 1087, "s": 1068, "text": "Solution: We have " }, { "code": null, "e": 1268, "s": 1087, "text": "yp = y0 + pΞ”y0 + (p(p-1)/2!).Ξ”y20 + ((p+1)p(p-1)/3!).Ξ”y30 + ... where p = (x1.17 – x1.15) / h and h = x1 – x0 = 0.05so, p = 0.04Now, we need to calculate Ξ”y0, Ξ”y20, Ξ”y30 ... etc. " }, { "code": null, "e": 1452, "s": 1268, "text": "Put the required values in the formula- yx = 1.17 = 3.158 + (2/5)(0.162) + (2/5)(2/5 – 1)/2.(0.008) ... yx = 1.17 = 3.2246Code : Python code for implementing Gauss’s Forward Formula " }, { "code": null, "e": 1460, "s": 1452, "text": "Python3" }, { "code": "# Python3 code for Gauss's Forward Formula# importing libraryimport numpy as np # function for calculating coefficient of Ydef p_cal(p, n): temp = p; for i in range(1, n): if(i%2==1): temp * (p - i) else: temp * (p + i) return temp;# function for factorialdef fact(n): f = 1 for i in range(2, n + 1): f *= i return f # storing available datan = 7;x = [ 1, 1.05, 1.10, 1.15, 1.20, 1.25, 1.30 ]; y = [[0 for i in range(n)] for j in range(n)];y[0][0] = 2.7183;y[1][0] = 2.8577;y[2][0] = 3.0042;y[3][0] = 3.1582; y[4][0] = 3.3201;y[5][0] = 3.4903;y[6][0] = 3.6693; # Generating Gauss's trianglefor i in range(1, n): for j in range(n - i): y[j][i] = np.round((y[j + 1][i - 1] - y[j][i - 1]),4); # Printing the Trianglefor i in range(n): print(x[i], end = \"\\t\"); for j in range(n - i): print(y[i][j], end = \"\\t\"); print(\"\"); # Value of Y need to predict onvalue = 1.17; # implementing Formulasum = y[int(n/2)][0];p = (value - x[int(n/2)]) / (x[1] - x[0]) for i in range(1,n): # print(y[int((n-i)/2)][i]) sum = sum + (p_cal(p, i) * y[int((n-i)/2)][i]) / fact(i) print(\"\\nValue at\", value, \"is\", round(sum, 4));", "e": 2672, "s": 1460, "text": null }, { "code": null, "e": 2683, "s": 2672, "text": "Output : " }, { "code": null, "e": 2995, "s": 2683, "text": "1 2.7183 0.1394 0.0071 0.0004 0.0 0.0 0.0001 \n1.05 2.8577 0.1465 0.0075 0.0004 0.0 0.0001 \n1.1 3.0042 0.154 0.0079 0.0004 0.0001 \n1.15 3.1582 0.1619 0.0083 0.0005 \n1.2 3.3201 0.1702 0.0088 \n1.25 3.4903 0.179 \n1.3 3.6693 \n\nValue at 1.17 is 3.2246" }, { "code": null, "e": 3012, "s": 2997, "text": "adnanirshad158" }, { "code": null, "e": 3036, "s": 3012, "text": "Engineering Mathematics" }, { "code": null, "e": 3070, "s": 3036, "text": "Engineering Mathematics Questions" }, { "code": null, "e": 3077, "s": 3070, "text": "Python" }, { "code": null, "e": 3175, "s": 3077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3234, "s": 3175, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 3255, "s": 3234, "text": "Activation Functions" }, { "code": null, "e": 3280, "s": 3255, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 3299, "s": 3280, "text": "Modular Arithmetic" }, { "code": null, "e": 3340, "s": 3299, "text": "Mathematics | Introduction of Set theory" }, { "code": null, "e": 3370, "s": 3340, "text": "Regular Graph in Graph Theory" }, { "code": null, "e": 3392, "s": 3370, "text": "Abelian Group Example" }, { "code": null, "e": 3420, "s": 3392, "text": "Homogeneous Poisson Process" }, { "code": null, "e": 3467, "s": 3420, "text": "Mathematics concept required for Deep Learning" } ]
Disease Prediction Using Machine Learning
30 Jan, 2022 This article aims to implement a robust machine learning model that can efficiently predict the disease of a human, based on the symptoms that he/she posses. Let us look into how we can approach this machine learning problem: Gathering the Data: Data preparation is the primary step for any machine learning problem. We will be using a dataset from Kaggle for this problem. This dataset consists of two CSV files one for training and one for testing. There is a total of 133 columns in the dataset out of which 132 columns represent the symptoms and the last column is the prognosis. Cleaning the Data: Cleaning is the most important step in a machine learning project. The quality of our data determines the quality of our machine learning model. So it is always necessary to clean the data before feeding it to the model for training. In our dataset all the columns are numerical, the target column i.e. prognosis is a string type and is encoded to numerical form using a label encoder. Model Building: After gathering and cleaning the data, the data is ready and can be used to train a machine learning model. We will be using this cleaned data to train the Support Vector Classifier, Naive Bayes Classifier, and Random Forest Classifier. We will be using a confusion matrix to determine the quality of the models. Inference: After training the three models we will be predicting the disease for the input symptoms by combining the predictions of all three models. This makes our overall prediction more robust and accurate. At last, we will be defining a function that takes symptoms separated by commas as input, predicts the disease based on the symptoms by using the trained models, and returns the predictions in a JSON format. Make sure that the Training and Testing are downloaded and the train.csv, test.csv are put in the dataset folder. Open jupyter notebook and run the code individually for better understanding. Python3 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. # Importing librariesimport numpy as npimport pandas as pdfrom scipy.stats import modeimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split, cross_val_scorefrom sklearn.svm import SVCfrom sklearn.naive_bayes import GaussianNBfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score, confusion_matrix %matplotlib inline Firstly we will be loading the dataset from the folders using the pandas library. While reading the dataset we will be dropping the null column. This dataset is a clean dataset with no null values and all the features consist of 0’s and 1’s. Whenever we are solving a classification task it is necessary to check whether our target column is balanced or not. We will be using a bar plot, to check whether the dataset is balanced or not. Python3 # Reading the train.csv by removing the# last column since it's an empty columnDATA_PATH = "dataset/Training.csv"data = pd.read_csv(DATA_PATH).dropna(axis = 1) # Checking whether the dataset is balanced or notdisease_counts = data["prognosis"].value_counts()temp_df = pd.DataFrame({ "Disease": disease_counts.index, "Counts": disease_counts.values}) plt.figure(figsize = (18,8))sns.barplot(x = "Disease", y = "Counts", data = temp_df)plt.xticks(rotation=90)plt.show() Output: From the above plot, we can observe that the dataset is a balanced dataset i.e. there are exactly 120 samples for each disease, and no further balancing is required. We can notice that our target column i.e. prognosis column is of object datatype, this format is not suitable to train a machine learning model. So, we will be using a label encoder to convert the prognosis column to the numerical datatype. Label Encoder converts the labels into numerical form by assigning a unique index to the labels. If the total number of labels is n, then the numbers assigned to each label will be between 0 to n-1. Python3 # Encoding the target value into numerical# value using LabelEncoderencoder = LabelEncoder()data["prognosis"] = encoder.fit_transform(data["prognosis"]) Now that we have cleaned our data by removing the Null values and converting the labels to numerical format, It’s time to split the data to train and test the model. We will be splitting the data into 80:20 format i.e. 80% of the dataset will be used for training the model and 20% of the data will be used to evaluate the performance of the models. Python3 X = data.iloc[:,:-1]y = data.iloc[:, -1]X_train, X_test, y_train, y_test =train_test_split( X, y, test_size = 0.2, random_state = 24) print(f"Train: {X_train.shape}, {y_train.shape}")print(f"Test: {X_test.shape}, {y_test.shape}") Output: Train: (3936, 132), (3936,) Test: (984, 132), (984,) After splitting the data, we will be now working on the modeling part. We will be using K-Fold cross-validation to evaluate the machine learning models. We will be using Support Vector Classifier, Gaussian Naive Bayes Classifier, and Random Forest Classifier for cross-validation. Before moving into the implementation part let us get familiar with k-fold cross-validation and the machine learning models. K-Fold Cross-Validation: K-Fold cross-validation is one of the cross-validation techniques in which the whole dataset is split into k number of subsets, also known as folds, then training of the model is performed on the k-1 subsets and the remaining one subset is used to evaluate the model performance. Support Vector Classifier: Support Vector Classifier is a discriminative classifier i.e. when given a labeled training data, the algorithm tries to find an optimal hyperplane that accurately separates the samples into different categories in hyperspace. Gaussian Naive Bayes Classifier: It is a probabilistic machine learning algorithm that internally uses Bayes Theorem to classify the data points. Random Forest Classifier: Random Forest is an ensemble learning-based supervised machine learning classification algorithm that internally uses multiple decision trees to make the classification. In a random forest classifier, all the internal decision trees are weak learners, the outputs of these weak decision trees are combined i.e. mode of all the predictions is as the final prediction. Using K-Fold Cross-Validation for model selection Python3 # Defining scoring metric for k-fold cross validationdef cv_scoring(estimator, X, y): return accuracy_score(y, estimator.predict(X)) # Initializing Modelsmodels = { "SVC":SVC(), "Gaussian NB":GaussianNB(), "Random Forest":RandomForestClassifier(random_state=18)} # Producing cross validation score for the modelsfor model_name in models: model = models[model_name] scores = cross_val_score(model, X, y, cv = 10, n_jobs = -1, scoring = cv_scoring) print("=="*30) print(model_name) print(f"Scores: {scores}") print(f"Mean Score: {np.mean(scores)}") Output: ============================================================ SVC Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] Mean Score: 1.0 ============================================================ Gaussian NB Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] Mean Score: 1.0 ============================================================ Random Forest Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] Mean Score: 1.0 From the above output, we can notice that all our machine learning algorithms are performing very well and the mean scores after k fold cross-validation are also very high. To build a robust model we can combine i.e. take the mode of the predictions of all three models so that even one of the models makes wrong predictions and the other two make correct predictions then the final output would be the correct one. This approach will help us to keep the predictions much more accurate on completely unseen data. In the below code we will be training all the three models on the train data, checking the quality of our models using a confusion matrix, and then combine the predictions of all the three models. Building robust classifier by combining all models: Python3 # Training and testing SVM Classifiersvm_model = SVC()svm_model.fit(X_train, y_train)preds = svm_model.predict(X_test) print(f"Accuracy on train data by SVM Classifier\: {accuracy_score(y_train, svm_model.predict(X_train))*100}") print(f"Accuracy on test data by SVM Classifier\: {accuracy_score(y_test, preds)*100}")cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title("Confusion Matrix for SVM Classifier on Test Data")plt.show() # Training and testing Naive Bayes Classifiernb_model = GaussianNB()nb_model.fit(X_train, y_train)preds = nb_model.predict(X_test)print(f"Accuracy on train data by Naive Bayes Classifier\: {accuracy_score(y_train, nb_model.predict(X_train))*100}") print(f"Accuracy on test data by Naive Bayes Classifier\: {accuracy_score(y_test, preds)*100}")cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title("Confusion Matrix for Naive Bayes Classifier on Test Data")plt.show() # Training and testing Random Forest Classifierrf_model = RandomForestClassifier(random_state=18)rf_model.fit(X_train, y_train)preds = rf_model.predict(X_test)print(f"Accuracy on train data by Random Forest Classifier\: {accuracy_score(y_train, rf_model.predict(X_train))*100}") print(f"Accuracy on test data by Random Forest Classifier\: {accuracy_score(y_test, preds)*100}") cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title("Confusion Matrix for Random Forest Classifier on Test Data")plt.show() Output: Accuracy on train data by SVM Classifier: 100.0 Accuracy on test data by SVM Classifier: 100.0 Accuracy on train data by Naive Bayes Classifier: 100.0 Accuracy on test data by Naive Bayes Classifier: 100.0 Accuracy on train data by Random Forest Classifier: 100.0 Accuracy on test data by Random Forest Classifier: 100.0 From the above confusion matrices, we can see that the models are performing very well on the unseen data. Now we will be training the models on the whole train data present in the dataset that we downloaded and then test our combined model on test data present in the dataset. Fitting the model on whole data and validating on the Test dataset: Python3 # Training the models on whole datafinal_svm_model = SVC()final_nb_model = GaussianNB()final_rf_model = RandomForestClassifier(random_state=18)final_svm_model.fit(X, y)final_nb_model.fit(X, y)final_rf_model.fit(X, y) # Reading the test datatest_data = pd.read_csv("./dataset/Testing.csv").dropna(axis=1) test_X = test_data.iloc[:, :-1]test_Y = encoder.transform(test_data.iloc[:, -1]) # Making prediction by take mode of predictions# made by all the classifierssvm_preds = final_svm_model.predict(test_X)nb_preds = final_nb_model.predict(test_X)rf_preds = final_rf_model.predict(test_X) final_preds = [mode([i,j,k])[0][0] for i,j, k in zip(svm_preds, nb_preds, rf_preds)] print(f"Accuracy on Test dataset by the combined model\: {accuracy_score(test_Y, final_preds)*100}") cf_matrix = confusion_matrix(test_Y, final_preds)plt.figure(figsize=(12,8)) sns.heatmap(cf_matrix, annot = True)plt.title("Confusion Matrix for Combined Model on Test Dataset")plt.show() Output: Accuracy on Test dataset by the combined model: 100.0 We can see that our combined model has classified all the data points accurately. We have come to the final part of this whole implementation, we will be creating a function that takes symptoms separated by commas as input and outputs the predicted disease using the combined model based on the input symptoms. Creating a function that can take symptoms as input and generate predictions for disease Python3 symptoms = X.columns.values # Creating a symptom index dictionary to encode the# input symptoms into numerical formsymptom_index = {}for index, value in enumerate(symptoms): symptom = " ".join([i.capitalize() for i in value.split("_")]) symptom_index[symptom] = index data_dict = { "symptom_index":symptom_index, "predictions_classes":encoder.classes_} # Defining the Function# Input: string containing symptoms separated by commmas# Output: Generated predictions by modelsdef predictDisease(symptoms): symptoms = symptoms.split(",") # creating input data for the models input_data = [0] * len(data_dict["symptom_index"]) for symptom in symptoms: index = data_dict["symptom_index"][symptom] input_data[index] = 1 # reshaping the input data and converting it # into suitable format for model predictions input_data = np.array(input_data).reshape(1,-1) # generating individual outputs rf_prediction = data_dict["predictions_classes"][final_rf_model.predict(input_data)[0]] nb_prediction = data_dict["predictions_classes"][final_nb_model.predict(input_data)[0]] svm_prediction = data_dict["predictions_classes"][final_svm_model.predict(input_data)[0]] # making final prediction by taking mode of all predictions final_prediction = mode([rf_prediction, nb_prediction, svm_prediction])[0][0] predictions = { "rf_model_prediction": rf_prediction, "naive_bayes_prediction": nb_prediction, "svm_model_prediction": nb_prediction, "final_prediction":final_prediction } return predictions # Testing the functionprint(predictDisease("Itching,Skin Rash,Nodal Skin Eruptions")) Output: { 'rf_model_prediction': 'Fungal infection', 'naive_bayes_prediction': 'Fungal infection', 'svm_model_prediction': 'Fungal infection', 'final_prediction': 'Fungal infection' } Note: The symptoms that are given as input to the function should be exactly the same among the 132 symptoms in the dataset. clintra sumitgumber28 the01ankit Picked Python-numpy Python-pandas Python-scipy Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Getting started with Machine Learning Markov Decision Process Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jan, 2022" }, { "code": null, "e": 278, "s": 52, "text": "This article aims to implement a robust machine learning model that can efficiently predict the disease of a human, based on the symptoms that he/she posses. Let us look into how we can approach this machine learning problem:" }, { "code": null, "e": 636, "s": 278, "text": "Gathering the Data: Data preparation is the primary step for any machine learning problem. We will be using a dataset from Kaggle for this problem. This dataset consists of two CSV files one for training and one for testing. There is a total of 133 columns in the dataset out of which 132 columns represent the symptoms and the last column is the prognosis." }, { "code": null, "e": 1041, "s": 636, "text": "Cleaning the Data: Cleaning is the most important step in a machine learning project. The quality of our data determines the quality of our machine learning model. So it is always necessary to clean the data before feeding it to the model for training. In our dataset all the columns are numerical, the target column i.e. prognosis is a string type and is encoded to numerical form using a label encoder." }, { "code": null, "e": 1370, "s": 1041, "text": "Model Building: After gathering and cleaning the data, the data is ready and can be used to train a machine learning model. We will be using this cleaned data to train the Support Vector Classifier, Naive Bayes Classifier, and Random Forest Classifier. We will be using a confusion matrix to determine the quality of the models." }, { "code": null, "e": 1580, "s": 1370, "text": "Inference: After training the three models we will be predicting the disease for the input symptoms by combining the predictions of all three models. This makes our overall prediction more robust and accurate." }, { "code": null, "e": 1789, "s": 1580, "text": "At last, we will be defining a function that takes symptoms separated by commas as input, predicts the disease based on the symptoms by using the trained models, and returns the predictions in a JSON format. " }, { "code": null, "e": 1981, "s": 1789, "text": "Make sure that the Training and Testing are downloaded and the train.csv, test.csv are put in the dataset folder. Open jupyter notebook and run the code individually for better understanding." }, { "code": null, "e": 1989, "s": 1981, "text": "Python3" }, { "code": null, "e": 1998, "s": 1989, "text": "Chapters" }, { "code": null, "e": 2025, "s": 1998, "text": "descriptions off, selected" }, { "code": null, "e": 2075, "s": 2025, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2098, "s": 2075, "text": "captions off, selected" }, { "code": null, "e": 2106, "s": 2098, "text": "English" }, { "code": null, "e": 2130, "s": 2106, "text": "This is a modal window." }, { "code": null, "e": 2199, "s": 2130, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2221, "s": 2199, "text": "End of dialog window." }, { "code": "# Importing librariesimport numpy as npimport pandas as pdfrom scipy.stats import modeimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split, cross_val_scorefrom sklearn.svm import SVCfrom sklearn.naive_bayes import GaussianNBfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score, confusion_matrix %matplotlib inline", "e": 2674, "s": 2221, "text": null }, { "code": null, "e": 3113, "s": 2674, "text": "Firstly we will be loading the dataset from the folders using the pandas library. While reading the dataset we will be dropping the null column. This dataset is a clean dataset with no null values and all the features consist of 0’s and 1’s. Whenever we are solving a classification task it is necessary to check whether our target column is balanced or not. We will be using a bar plot, to check whether the dataset is balanced or not. " }, { "code": null, "e": 3121, "s": 3113, "text": "Python3" }, { "code": "# Reading the train.csv by removing the# last column since it's an empty columnDATA_PATH = \"dataset/Training.csv\"data = pd.read_csv(DATA_PATH).dropna(axis = 1) # Checking whether the dataset is balanced or notdisease_counts = data[\"prognosis\"].value_counts()temp_df = pd.DataFrame({ \"Disease\": disease_counts.index, \"Counts\": disease_counts.values}) plt.figure(figsize = (18,8))sns.barplot(x = \"Disease\", y = \"Counts\", data = temp_df)plt.xticks(rotation=90)plt.show()", "e": 3595, "s": 3121, "text": null }, { "code": null, "e": 3604, "s": 3595, "text": "Output: " }, { "code": null, "e": 4210, "s": 3604, "text": "From the above plot, we can observe that the dataset is a balanced dataset i.e. there are exactly 120 samples for each disease, and no further balancing is required. We can notice that our target column i.e. prognosis column is of object datatype, this format is not suitable to train a machine learning model. So, we will be using a label encoder to convert the prognosis column to the numerical datatype. Label Encoder converts the labels into numerical form by assigning a unique index to the labels. If the total number of labels is n, then the numbers assigned to each label will be between 0 to n-1." }, { "code": null, "e": 4218, "s": 4210, "text": "Python3" }, { "code": "# Encoding the target value into numerical# value using LabelEncoderencoder = LabelEncoder()data[\"prognosis\"] = encoder.fit_transform(data[\"prognosis\"])", "e": 4371, "s": 4218, "text": null }, { "code": null, "e": 4721, "s": 4371, "text": "Now that we have cleaned our data by removing the Null values and converting the labels to numerical format, It’s time to split the data to train and test the model. We will be splitting the data into 80:20 format i.e. 80% of the dataset will be used for training the model and 20% of the data will be used to evaluate the performance of the models." }, { "code": null, "e": 4729, "s": 4721, "text": "Python3" }, { "code": "X = data.iloc[:,:-1]y = data.iloc[:, -1]X_train, X_test, y_train, y_test =train_test_split( X, y, test_size = 0.2, random_state = 24) print(f\"Train: {X_train.shape}, {y_train.shape}\")print(f\"Test: {X_test.shape}, {y_test.shape}\")", "e": 4960, "s": 4729, "text": null }, { "code": null, "e": 4969, "s": 4960, "text": "Output: " }, { "code": null, "e": 5022, "s": 4969, "text": "Train: (3936, 132), (3936,)\nTest: (984, 132), (984,)" }, { "code": null, "e": 5429, "s": 5022, "text": "After splitting the data, we will be now working on the modeling part. We will be using K-Fold cross-validation to evaluate the machine learning models. We will be using Support Vector Classifier, Gaussian Naive Bayes Classifier, and Random Forest Classifier for cross-validation. Before moving into the implementation part let us get familiar with k-fold cross-validation and the machine learning models. " }, { "code": null, "e": 5734, "s": 5429, "text": "K-Fold Cross-Validation: K-Fold cross-validation is one of the cross-validation techniques in which the whole dataset is split into k number of subsets, also known as folds, then training of the model is performed on the k-1 subsets and the remaining one subset is used to evaluate the model performance." }, { "code": null, "e": 5988, "s": 5734, "text": "Support Vector Classifier: Support Vector Classifier is a discriminative classifier i.e. when given a labeled training data, the algorithm tries to find an optimal hyperplane that accurately separates the samples into different categories in hyperspace." }, { "code": null, "e": 6134, "s": 5988, "text": "Gaussian Naive Bayes Classifier: It is a probabilistic machine learning algorithm that internally uses Bayes Theorem to classify the data points." }, { "code": null, "e": 6527, "s": 6134, "text": "Random Forest Classifier: Random Forest is an ensemble learning-based supervised machine learning classification algorithm that internally uses multiple decision trees to make the classification. In a random forest classifier, all the internal decision trees are weak learners, the outputs of these weak decision trees are combined i.e. mode of all the predictions is as the final prediction." }, { "code": null, "e": 6578, "s": 6527, "text": "Using K-Fold Cross-Validation for model selection " }, { "code": null, "e": 6586, "s": 6578, "text": "Python3" }, { "code": "# Defining scoring metric for k-fold cross validationdef cv_scoring(estimator, X, y): return accuracy_score(y, estimator.predict(X)) # Initializing Modelsmodels = { \"SVC\":SVC(), \"Gaussian NB\":GaussianNB(), \"Random Forest\":RandomForestClassifier(random_state=18)} # Producing cross validation score for the modelsfor model_name in models: model = models[model_name] scores = cross_val_score(model, X, y, cv = 10, n_jobs = -1, scoring = cv_scoring) print(\"==\"*30) print(model_name) print(f\"Scores: {scores}\") print(f\"Mean Score: {np.mean(scores)}\")", "e": 7219, "s": 6586, "text": null }, { "code": null, "e": 7228, "s": 7219, "text": "Output: " }, { "code": null, "e": 7289, "s": 7228, "text": "============================================================" }, { "code": null, "e": 7293, "s": 7289, "text": "SVC" }, { "code": null, "e": 7333, "s": 7293, "text": "Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]" }, { "code": null, "e": 7349, "s": 7333, "text": "Mean Score: 1.0" }, { "code": null, "e": 7410, "s": 7349, "text": "============================================================" }, { "code": null, "e": 7422, "s": 7410, "text": "Gaussian NB" }, { "code": null, "e": 7462, "s": 7422, "text": "Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]" }, { "code": null, "e": 7478, "s": 7462, "text": "Mean Score: 1.0" }, { "code": null, "e": 7539, "s": 7478, "text": "============================================================" }, { "code": null, "e": 7553, "s": 7539, "text": "Random Forest" }, { "code": null, "e": 7593, "s": 7553, "text": "Scores: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]" }, { "code": null, "e": 7609, "s": 7593, "text": "Mean Score: 1.0" }, { "code": null, "e": 8319, "s": 7609, "text": "From the above output, we can notice that all our machine learning algorithms are performing very well and the mean scores after k fold cross-validation are also very high. To build a robust model we can combine i.e. take the mode of the predictions of all three models so that even one of the models makes wrong predictions and the other two make correct predictions then the final output would be the correct one. This approach will help us to keep the predictions much more accurate on completely unseen data. In the below code we will be training all the three models on the train data, checking the quality of our models using a confusion matrix, and then combine the predictions of all the three models." }, { "code": null, "e": 8372, "s": 8319, "text": "Building robust classifier by combining all models: " }, { "code": null, "e": 8380, "s": 8372, "text": "Python3" }, { "code": "# Training and testing SVM Classifiersvm_model = SVC()svm_model.fit(X_train, y_train)preds = svm_model.predict(X_test) print(f\"Accuracy on train data by SVM Classifier\\: {accuracy_score(y_train, svm_model.predict(X_train))*100}\") print(f\"Accuracy on test data by SVM Classifier\\: {accuracy_score(y_test, preds)*100}\")cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title(\"Confusion Matrix for SVM Classifier on Test Data\")plt.show() # Training and testing Naive Bayes Classifiernb_model = GaussianNB()nb_model.fit(X_train, y_train)preds = nb_model.predict(X_test)print(f\"Accuracy on train data by Naive Bayes Classifier\\: {accuracy_score(y_train, nb_model.predict(X_train))*100}\") print(f\"Accuracy on test data by Naive Bayes Classifier\\: {accuracy_score(y_test, preds)*100}\")cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title(\"Confusion Matrix for Naive Bayes Classifier on Test Data\")plt.show() # Training and testing Random Forest Classifierrf_model = RandomForestClassifier(random_state=18)rf_model.fit(X_train, y_train)preds = rf_model.predict(X_test)print(f\"Accuracy on train data by Random Forest Classifier\\: {accuracy_score(y_train, rf_model.predict(X_train))*100}\") print(f\"Accuracy on test data by Random Forest Classifier\\: {accuracy_score(y_test, preds)*100}\") cf_matrix = confusion_matrix(y_test, preds)plt.figure(figsize=(12,8))sns.heatmap(cf_matrix, annot=True)plt.title(\"Confusion Matrix for Random Forest Classifier on Test Data\")plt.show()", "e": 9960, "s": 8380, "text": null }, { "code": null, "e": 9969, "s": 9960, "text": "Output: " }, { "code": null, "e": 10064, "s": 9969, "text": "Accuracy on train data by SVM Classifier: 100.0\nAccuracy on test data by SVM Classifier: 100.0" }, { "code": null, "e": 10175, "s": 10064, "text": "Accuracy on train data by Naive Bayes Classifier: 100.0\nAccuracy on test data by Naive Bayes Classifier: 100.0" }, { "code": null, "e": 10290, "s": 10175, "text": "Accuracy on train data by Random Forest Classifier: 100.0\nAccuracy on test data by Random Forest Classifier: 100.0" }, { "code": null, "e": 10568, "s": 10290, "text": "From the above confusion matrices, we can see that the models are performing very well on the unseen data. Now we will be training the models on the whole train data present in the dataset that we downloaded and then test our combined model on test data present in the dataset." }, { "code": null, "e": 10637, "s": 10568, "text": "Fitting the model on whole data and validating on the Test dataset: " }, { "code": null, "e": 10645, "s": 10637, "text": "Python3" }, { "code": "# Training the models on whole datafinal_svm_model = SVC()final_nb_model = GaussianNB()final_rf_model = RandomForestClassifier(random_state=18)final_svm_model.fit(X, y)final_nb_model.fit(X, y)final_rf_model.fit(X, y) # Reading the test datatest_data = pd.read_csv(\"./dataset/Testing.csv\").dropna(axis=1) test_X = test_data.iloc[:, :-1]test_Y = encoder.transform(test_data.iloc[:, -1]) # Making prediction by take mode of predictions# made by all the classifierssvm_preds = final_svm_model.predict(test_X)nb_preds = final_nb_model.predict(test_X)rf_preds = final_rf_model.predict(test_X) final_preds = [mode([i,j,k])[0][0] for i,j, k in zip(svm_preds, nb_preds, rf_preds)] print(f\"Accuracy on Test dataset by the combined model\\: {accuracy_score(test_Y, final_preds)*100}\") cf_matrix = confusion_matrix(test_Y, final_preds)plt.figure(figsize=(12,8)) sns.heatmap(cf_matrix, annot = True)plt.title(\"Confusion Matrix for Combined Model on Test Dataset\")plt.show()", "e": 11619, "s": 10645, "text": null }, { "code": null, "e": 11628, "s": 11619, "text": "Output: " }, { "code": null, "e": 11682, "s": 11628, "text": "Accuracy on Test dataset by the combined model: 100.0" }, { "code": null, "e": 11993, "s": 11682, "text": "We can see that our combined model has classified all the data points accurately. We have come to the final part of this whole implementation, we will be creating a function that takes symptoms separated by commas as input and outputs the predicted disease using the combined model based on the input symptoms." }, { "code": null, "e": 12083, "s": 11993, "text": "Creating a function that can take symptoms as input and generate predictions for disease " }, { "code": null, "e": 12091, "s": 12083, "text": "Python3" }, { "code": "symptoms = X.columns.values # Creating a symptom index dictionary to encode the# input symptoms into numerical formsymptom_index = {}for index, value in enumerate(symptoms): symptom = \" \".join([i.capitalize() for i in value.split(\"_\")]) symptom_index[symptom] = index data_dict = { \"symptom_index\":symptom_index, \"predictions_classes\":encoder.classes_} # Defining the Function# Input: string containing symptoms separated by commmas# Output: Generated predictions by modelsdef predictDisease(symptoms): symptoms = symptoms.split(\",\") # creating input data for the models input_data = [0] * len(data_dict[\"symptom_index\"]) for symptom in symptoms: index = data_dict[\"symptom_index\"][symptom] input_data[index] = 1 # reshaping the input data and converting it # into suitable format for model predictions input_data = np.array(input_data).reshape(1,-1) # generating individual outputs rf_prediction = data_dict[\"predictions_classes\"][final_rf_model.predict(input_data)[0]] nb_prediction = data_dict[\"predictions_classes\"][final_nb_model.predict(input_data)[0]] svm_prediction = data_dict[\"predictions_classes\"][final_svm_model.predict(input_data)[0]] # making final prediction by taking mode of all predictions final_prediction = mode([rf_prediction, nb_prediction, svm_prediction])[0][0] predictions = { \"rf_model_prediction\": rf_prediction, \"naive_bayes_prediction\": nb_prediction, \"svm_model_prediction\": nb_prediction, \"final_prediction\":final_prediction } return predictions # Testing the functionprint(predictDisease(\"Itching,Skin Rash,Nodal Skin Eruptions\"))", "e": 13781, "s": 12091, "text": null }, { "code": null, "e": 13790, "s": 13781, "text": "Output: " }, { "code": null, "e": 13982, "s": 13790, "text": "{\n 'rf_model_prediction': 'Fungal infection',\n 'naive_bayes_prediction': 'Fungal infection',\n 'svm_model_prediction': 'Fungal infection',\n 'final_prediction': 'Fungal infection'\n}" }, { "code": null, "e": 14108, "s": 13982, "text": "Note: The symptoms that are given as input to the function should be exactly the same among the 132 symptoms in the dataset. " }, { "code": null, "e": 14118, "s": 14110, "text": "clintra" }, { "code": null, "e": 14132, "s": 14118, "text": "sumitgumber28" }, { "code": null, "e": 14143, "s": 14132, "text": "the01ankit" }, { "code": null, "e": 14150, "s": 14143, "text": "Picked" }, { "code": null, "e": 14163, "s": 14150, "text": "Python-numpy" }, { "code": null, "e": 14177, "s": 14163, "text": "Python-pandas" }, { "code": null, "e": 14190, "s": 14177, "text": "Python-scipy" }, { "code": null, "e": 14207, "s": 14190, "text": "Machine Learning" }, { "code": null, "e": 14214, "s": 14207, "text": "Python" }, { "code": null, "e": 14231, "s": 14214, "text": "Machine Learning" }, { "code": null, "e": 14329, "s": 14231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14370, "s": 14329, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 14406, "s": 14370, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 14444, "s": 14406, "text": "Getting started with Machine Learning" }, { "code": null, "e": 14468, "s": 14444, "text": "Markov Decision Process" }, { "code": null, "e": 14501, "s": 14468, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 14529, "s": 14501, "text": "Read JSON file using Python" }, { "code": null, "e": 14579, "s": 14529, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 14601, "s": 14579, "text": "Python map() function" }, { "code": null, "e": 14619, "s": 14601, "text": "Python Dictionary" } ]
How to convert speech into text using JavaScript ?
05 Jan, 2021 In this article, we will learn to convert speech into text using HTML and JavaScript. Approach: We added a content editable β€œdiv” by which we make any HTML element editable. HTML <div class="words" contenteditable> <p id="p"></p></div> We use the SpeechRecognition object to convert the speech into text and then display the text on the screen. We also added WebKit Speech Recognition to perform speech recognition in Google chrome and Apple safari. Javascript window.SpeechRecognition=window.SpeechRecognition || window.webkitSpeechRecognition; InterimResults results should be returned true and the default value of this is false. So set interimResults= true Javascript recognition.interimResults = true; Use appendChild() method to append a node as the last child of a node. Javascript const words=document.querySelector('.words');words.appendChild(p); Add eventListener, in this event listener, map() method is used to create a new array with the results of calling a function for every array element. Note: This method does not change the original array. Use join() method to return array as a string. Javascript recognition.addEventListener('result', e => { const transcript = Array.from(e.results) .map(result => result[0]) .map(result => result.transcript) .join('') document.getElementById("p").innerHTML = transcript; console.log(transcript);}); Final Code: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Speech to Text</title></head> <body> <div class="words" contenteditable> <p id="p"></p> </div> <script> var speech = true; window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; const recognition = new SpeechRecognition(); recognition.interimResults = true; const words = document.querySelector('.words'); words.appendChild(p); recognition.addEventListener('result', e => { const transcript = Array.from(e.results) .map(result => result[0]) .map(result => result.transcript) .join('') document.getElementById("p").innerHTML = transcript; console.log(transcript); }); if (speech == true) { recognition.start(); recognition.addEventListener('end', recognition.start); } </script></body> </html> Output: If the user tells β€œHello World” after running the file, it shows the following on the screen. Hello World HTML-Misc JavaScript-Misc Technical Scripter 2020 HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ?
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jan, 2021" }, { "code": null, "e": 141, "s": 54, "text": "In this article, we will learn to convert speech into text using HTML and JavaScript. " }, { "code": null, "e": 229, "s": 141, "text": "Approach: We added a content editable β€œdiv” by which we make any HTML element editable." }, { "code": null, "e": 234, "s": 229, "text": "HTML" }, { "code": "<div class=\"words\" contenteditable> <p id=\"p\"></p></div>", "e": 294, "s": 234, "text": null }, { "code": null, "e": 403, "s": 294, "text": "We use the SpeechRecognition object to convert the speech into text and then display the text on the screen." }, { "code": null, "e": 508, "s": 403, "text": "We also added WebKit Speech Recognition to perform speech recognition in Google chrome and Apple safari." }, { "code": null, "e": 519, "s": 508, "text": "Javascript" }, { "code": "window.SpeechRecognition=window.SpeechRecognition || window.webkitSpeechRecognition;", "e": 608, "s": 519, "text": null }, { "code": null, "e": 723, "s": 608, "text": "InterimResults results should be returned true and the default value of this is false. So set interimResults= true" }, { "code": null, "e": 734, "s": 723, "text": "Javascript" }, { "code": "recognition.interimResults = true;", "e": 769, "s": 734, "text": null }, { "code": null, "e": 840, "s": 769, "text": "Use appendChild() method to append a node as the last child of a node." }, { "code": null, "e": 851, "s": 840, "text": "Javascript" }, { "code": "const words=document.querySelector('.words');words.appendChild(p);", "e": 918, "s": 851, "text": null }, { "code": null, "e": 1069, "s": 918, "text": "Add eventListener, in this event listener, map() method is used to create a new array with the results of calling a function for every array element. " }, { "code": null, "e": 1124, "s": 1069, "text": "Note: This method does not change the original array. " }, { "code": null, "e": 1171, "s": 1124, "text": "Use join() method to return array as a string." }, { "code": null, "e": 1182, "s": 1171, "text": "Javascript" }, { "code": "recognition.addEventListener('result', e => { const transcript = Array.from(e.results) .map(result => result[0]) .map(result => result.transcript) .join('') document.getElementById(\"p\").innerHTML = transcript; console.log(transcript);});", "e": 1452, "s": 1182, "text": null }, { "code": null, "e": 1464, "s": 1452, "text": "Final Code:" }, { "code": null, "e": 1469, "s": 1464, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Speech to Text</title></head> <body> <div class=\"words\" contenteditable> <p id=\"p\"></p> </div> <script> var speech = true; window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; const recognition = new SpeechRecognition(); recognition.interimResults = true; const words = document.querySelector('.words'); words.appendChild(p); recognition.addEventListener('result', e => { const transcript = Array.from(e.results) .map(result => result[0]) .map(result => result.transcript) .join('') document.getElementById(\"p\").innerHTML = transcript; console.log(transcript); }); if (speech == true) { recognition.start(); recognition.addEventListener('end', recognition.start); } </script></body> </html>", "e": 2586, "s": 1469, "text": null }, { "code": null, "e": 2595, "s": 2586, "text": "Output: " }, { "code": null, "e": 2689, "s": 2595, "text": "If the user tells β€œHello World” after running the file, it shows the following on the screen." }, { "code": null, "e": 2701, "s": 2689, "text": "Hello World" }, { "code": null, "e": 2711, "s": 2701, "text": "HTML-Misc" }, { "code": null, "e": 2727, "s": 2711, "text": "JavaScript-Misc" }, { "code": null, "e": 2751, "s": 2727, "text": "Technical Scripter 2020" }, { "code": null, "e": 2756, "s": 2751, "text": "HTML" }, { "code": null, "e": 2767, "s": 2756, "text": "JavaScript" }, { "code": null, "e": 2786, "s": 2767, "text": "Technical Scripter" }, { "code": null, "e": 2803, "s": 2786, "text": "Web Technologies" }, { "code": null, "e": 2808, "s": 2803, "text": "HTML" }, { "code": null, "e": 2906, "s": 2808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2930, "s": 2906, "text": "REST API (Introduction)" }, { "code": null, "e": 2969, "s": 2930, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3008, "s": 2969, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3028, "s": 3008, "text": "Angular File Upload" }, { "code": null, "e": 3057, "s": 3028, "text": "Form validation using jQuery" }, { "code": null, "e": 3118, "s": 3057, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3190, "s": 3118, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3230, "s": 3190, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3271, "s": 3230, "text": "Difference Between PUT and PATCH Request" } ]
Python Tkinter – ListBox Widget
26 Mar, 2020 Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs. Note: For more information, refer to Python GUI – tkinter The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement. Syntax: listbox = Listbox(root, bg, fg, bd, height, width, font, ..) Optional parameters root – root window. bg – background colour fg – foreground colour bd – border height – height of the widget. width – width of the widget. font – Font type of the text. highlightcolor – The colour of the list items when focused. yscrollcommand – for scrolling vertically. xscrollcommand – for scrolling horizontally. cursor – The cursor on the widget which can be an arrow, a dot etc. Common methods yview – allows the widget to be vertically scrollable. xview – allows the widget to be horizontally scrollable. get() – to get the list items in a given range. activate(index) – to select the lines with a specified index. size() – return the number of lines present. delete(start, last) – delete lines in the specified range. nearest(y) – returns the index of the nearest line. curseselection() – returns a tuple for all the line numbers that are being selected. Example 1: from tkinter import * # create a root window.top = Tk() # create listbox objectlistbox = Listbox(top, height = 10, width = 15, bg = "grey", activestyle = 'dotbox', font = "Helvetica", fg = "yellow") # Define the size of the window.top.geometry("300x250") # Define a label for the list. label = Label(top, text = " FOOD ITEMS") # insert elements by their# index and names.listbox.insert(1, "Nachos")listbox.insert(2, "Sandwich")listbox.insert(3, "Burger")listbox.insert(4, "Pizza")listbox.insert(5, "Burrito") # pack the widgetslabel.pack()listbox.pack() # Display untill User # exits themselves.top.mainloop() OutputExample 2: Let’s Delete the elements from the above created listbox # Delete Items from the list# by specifying the index.listbox.delete(2) Output Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Mar, 2020" }, { "code": null, "e": 263, "s": 53, "text": "Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs." }, { "code": null, "e": 321, "s": 263, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 587, "s": 321, "text": "The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement." }, { "code": null, "e": 595, "s": 587, "text": "Syntax:" }, { "code": null, "e": 658, "s": 595, "text": "listbox = Listbox(root, bg, fg, bd, height, width, font, ..) \n" }, { "code": null, "e": 678, "s": 658, "text": "Optional parameters" }, { "code": null, "e": 698, "s": 678, "text": "root – root window." }, { "code": null, "e": 721, "s": 698, "text": "bg – background colour" }, { "code": null, "e": 744, "s": 721, "text": "fg – foreground colour" }, { "code": null, "e": 756, "s": 744, "text": "bd – border" }, { "code": null, "e": 787, "s": 756, "text": "height – height of the widget." }, { "code": null, "e": 816, "s": 787, "text": "width – width of the widget." }, { "code": null, "e": 846, "s": 816, "text": "font – Font type of the text." }, { "code": null, "e": 906, "s": 846, "text": "highlightcolor – The colour of the list items when focused." }, { "code": null, "e": 949, "s": 906, "text": "yscrollcommand – for scrolling vertically." }, { "code": null, "e": 994, "s": 949, "text": "xscrollcommand – for scrolling horizontally." }, { "code": null, "e": 1062, "s": 994, "text": "cursor – The cursor on the widget which can be an arrow, a dot etc." }, { "code": null, "e": 1077, "s": 1062, "text": "Common methods" }, { "code": null, "e": 1132, "s": 1077, "text": "yview – allows the widget to be vertically scrollable." }, { "code": null, "e": 1189, "s": 1132, "text": "xview – allows the widget to be horizontally scrollable." }, { "code": null, "e": 1237, "s": 1189, "text": "get() – to get the list items in a given range." }, { "code": null, "e": 1299, "s": 1237, "text": "activate(index) – to select the lines with a specified index." }, { "code": null, "e": 1344, "s": 1299, "text": "size() – return the number of lines present." }, { "code": null, "e": 1403, "s": 1344, "text": "delete(start, last) – delete lines in the specified range." }, { "code": null, "e": 1455, "s": 1403, "text": "nearest(y) – returns the index of the nearest line." }, { "code": null, "e": 1540, "s": 1455, "text": "curseselection() – returns a tuple for all the line numbers that are being selected." }, { "code": null, "e": 1551, "s": 1540, "text": "Example 1:" }, { "code": "from tkinter import * # create a root window.top = Tk() # create listbox objectlistbox = Listbox(top, height = 10, width = 15, bg = \"grey\", activestyle = 'dotbox', font = \"Helvetica\", fg = \"yellow\") # Define the size of the window.top.geometry(\"300x250\") # Define a label for the list. label = Label(top, text = \" FOOD ITEMS\") # insert elements by their# index and names.listbox.insert(1, \"Nachos\")listbox.insert(2, \"Sandwich\")listbox.insert(3, \"Burger\")listbox.insert(4, \"Pizza\")listbox.insert(5, \"Burrito\") # pack the widgetslabel.pack()listbox.pack() # Display untill User # exits themselves.top.mainloop()", "e": 2264, "s": 1551, "text": null }, { "code": null, "e": 2338, "s": 2264, "text": "OutputExample 2: Let’s Delete the elements from the above created listbox" }, { "code": "# Delete Items from the list# by specifying the index.listbox.delete(2)", "e": 2411, "s": 2338, "text": null }, { "code": null, "e": 2418, "s": 2411, "text": "Output" }, { "code": null, "e": 2433, "s": 2418, "text": "Python-tkinter" }, { "code": null, "e": 2440, "s": 2433, "text": "Python" }, { "code": null, "e": 2538, "s": 2440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2566, "s": 2538, "text": "Read JSON file using Python" }, { "code": null, "e": 2588, "s": 2566, "text": "Python map() function" }, { "code": null, "e": 2638, "s": 2588, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2682, "s": 2638, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2724, "s": 2682, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2746, "s": 2724, "text": "Enumerate() in Python" }, { "code": null, "e": 2781, "s": 2746, "text": "Read a file line by line in Python" }, { "code": null, "e": 2807, "s": 2781, "text": "Python String | replace()" }, { "code": null, "e": 2839, "s": 2807, "text": "How to Install PIP on Windows ?" } ]
Graph Plotting in Python | Set 2
27 Oct, 2021 Graph Plotting in Python | Set 1 Subplots Subplots are required when we want to show two or more plots in same figure. We can do it in two ways using two slightly different methods.Method 1 Python # importing required modulesimport matplotlib.pyplot as pltimport numpy as np # function to generate coordinatesdef create_plot(ptype): # setting the x-axis values x = np.arange(-10, 10, 0.01) # setting the y-axis values if ptype == 'linear': y = x elif ptype == 'quadratic': y = x**2 elif ptype == 'cubic': y = x**3 elif ptype == 'quartic': y = x**4 return(x, y) # setting a style to useplt.style.use('fivethirtyeight') # create a figurefig = plt.figure() # define subplots and their positions in figureplt1 = fig.add_subplot(221)plt2 = fig.add_subplot(222)plt3 = fig.add_subplot(223)plt4 = fig.add_subplot(224) # plotting points on each subplotx, y = create_plot('linear')plt1.plot(x, y, color ='r')plt1.set_title('$y_1 = x$') x, y = create_plot('quadratic')plt2.plot(x, y, color ='b')plt2.set_title('$y_2 = x^2$') x, y = create_plot('cubic')plt3.plot(x, y, color ='g')plt3.set_title('$y_3 = x^3$') x, y = create_plot('quartic')plt4.plot(x, y, color ='k')plt4.set_title('$y_4 = x^4$') # adjusting space between subplotsfig.subplots_adjust(hspace=.5,wspace=0.5) # function to show the plotplt.show() Output: 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. Let us go through this program step by step: plt.style.use('fivethirtyeight') The styling of plots can be configured by setting different styles available or setting your own. You can learn more about this feature here fig = plt.figure() Figure acts as a top level container for all plot elements. So, we define a figure as fig which will contain all our subplots. plt1 = fig.add_subplot(221) plt2 = fig.add_subplot(222) plt3 = fig.add_subplot(223) plt4 = fig.add_subplot(224) Here we use fig.add_subplot method to define subplots and their positions. The function prototype is like this: add_subplot(nrows, ncols, plot_number) If a subplot is applied to a figure, the figure will be notionally split into β€˜nrows’ * β€˜ncols’ sub-axes. The parameter β€˜plot_number’ identifies the subplot that the function call has to create. β€˜plot_number’ can range from 1 to a maximum of β€˜nrows’ * β€˜ncols’.If the values of the three parameters are less than 10, the function subplot can be called with one int parameter, where the hundreds represent β€˜nrows’, the tens represent β€˜ncols’ and the units represent β€˜plot_number’. This means: Instead of subplot(2, 3, 4) we can write subplot(234).This figure will make it clear that how positions are specified: x, y = create_plot('linear') plt1.plot(x, y, color ='r') plt1.set_title('$y_1 = x$') Next, we plot our points on each subplot. First, we generate x and y axis coordinates using create_plot function by specifying the type of curve we want. Then, we plot those points on our subplot using .plot method. Title of subplot is set by using set_title method. Using $ at starting and end of the title text will ensure that β€˜_'(underscore) is read as a subscript and β€˜^’ is read as a superscript. fig.subplots_adjust(hspace=.5,wspace=0.5) This is another utility method which creates space between subplots. plt.show() In the end, we call plt.show() method which will show the current figure. Method 2 Python # importing required modulesimport matplotlib.pyplot as pltimport numpy as np # function to generate coordinatesdef create_plot(ptype): # setting the x-axis values x = np.arange(0, 5, 0.01) # setting y-axis values if ptype == 'sin': # a sine wave y = np.sin(2*np.pi*x) elif ptype == 'exp': # negative exponential function y = np.exp(-x) elif ptype == 'hybrid': # a damped sine wave y = (np.sin(2*np.pi*x))*(np.exp(-x)) return(x, y) # setting a style to useplt.style.use('ggplot') # defining subplots and their positionsplt1 = plt.subplot2grid((11,1), (0,0), rowspan = 3, colspan = 1)plt2 = plt.subplot2grid((11,1), (4,0), rowspan = 3, colspan = 1)plt3 = plt.subplot2grid((11,1), (8,0), rowspan = 3, colspan = 1) # plotting points on each subplotx, y = create_plot('sin')plt1.plot(x, y, label = 'sine wave', color ='b')x, y = create_plot('exp')plt2.plot(x, y, label = 'negative exponential', color = 'r')x, y = create_plot('hybrid')plt3.plot(x, y, label = 'damped sine wave', color = 'g') # show legends of each subplotplt1.legend()plt2.legend()plt3.legend() # function to show plotplt.show() Output: Let us go through important parts of this program as well: plt1 = plt.subplot2grid((11,1), (0,0), rowspan = 3, colspan = 1) plt2 = plt.subplot2grid((11,1), (4,0), rowspan = 3, colspan = 1) plt3 = plt.subplot2grid((11,1), (8,0), rowspan = 3, colspan = 1) subplot2grid is similar to β€œpyplot.subplot” but uses 0-based indexing and let subplot to occupy multiple cells. Let us try to understand the arguments of the subplot2grid method: 1. argument 1 : geometry of the grid 2. argument 2: location of the subplot in the grid 3. argument 3: (rowspan) No. of rows covered by subplot. 4. argument 4: (colspan) No. of columns covered by subplot.This figure will make this concept more clear: In our example, each subplot spans over 3 rows and 1 column with two empty rows (row no. 4,8) . x, y = create_plot('sin') plt1.plot(x, y, label = 'sine wave', color ='b') Nothing special in this part as the syntax to plot points on a subplot remains same. plt1.legend() This will show the label of the subplot on the figure. plt.show() Finally, we call the plt.show() function to show the current plot. Note: After going through the above two examples, we can infer that one should use subplot() method when the plots are of uniform size where as subplot2grid() method should be preferred when we want more flexibility on position and sizes of our subplots. 3-D plotting We can easily plot 3-D figures in matplotlib. Now, we discuss some important and commonly used 3-D plots. Plotting points Python from mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figure# and set projection as 3dax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinatesx = np.random.randint(0, 10, size = 20)y = np.random.randint(0, 10, size = 20)z = np.random.randint(0, 10, size = 20) # plotting the points on subplot # setting labels for the axesax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') # function to show the plotplt.show() Output of above program will provide you with a window which can rotate or enlarge the plot. Here is a screenshot: (dark points are nearer than light ones) Let us try to understand some important aspects of this code now. from mpl_toolkits.mplot3d import axes3d This is the module required to plot on 3-D space. ax1 = fig.add_subplot(111, projection='3d') Here, we create a subplot on our figure and set projection argument as 3d. ax1.scatter(x, y, z, c = 'm', marker = 'o') Now we use .scatter() function to plot the points in XYZ plane. Plotting lines Python # importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinatesx = np.random.randint(0, 10, size = 5)y = np.random.randint(0, 10, size = 5)z = np.random.randint(0, 10, size = 5) # plotting the points on subplotax1.plot_wireframe(x,y,z) # setting the labelsax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') plt.show() A screenshot of the 3-D plot of above program will look like: The main difference in this program with previous one is: ax1.plot_wireframe(x,y,z) We used .plot_wireframe() method to plot lines over a given set of 3-D points. Plotting Bars Python # importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinates for bar positionx = [1,2,3,4,5,6,7,8,9,10]y = [4,3,1,6,5,3,7,5,3,7]z = np.zeros(10) # size of barsdx = np.ones(10) # length along x-axisdy = np.ones(10) # length along y-axsdz = [1,3,4,2,6,7,5,5,10,9] # height of bar # setting color schemecolor = []for h in dz: if h > 5: color.append('r') else: color.append('b') # plotting the barsax1.bar3d(x, y, z, dx, dy, dz, color = color) # setting axes labelsax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') plt.show() A screenshot of the 3-D environment created is here: Let us go through important aspects of this program: x = [1,2,3,4,5,6,7,8,9,10] y = [4,3,1,6,5,3,7,5,3,7] z = np.zeros(10) Here, we define the base positions of bars. Setting z = 0 means all bars start from XY plane. dx = np.ones(10) # length along x-axis dy = np.ones(10) # length along y-axs dz = [1,3,4,2,6,7,5,5,10,9] # height of bar dx, dy, dz denote the size of bar. Consider he bar as a cuboid, then dx, dy, dz are its expansions along x, y, z axis respectively. for h in dz: if h > 5: color.append('r') else: color.append('b') Here, we set the color for each bar as a list. The color scheme is red for bars with height greater than 5 and blue otherwise. ax1.bar3d(x, y, z, dx, dy, dz, color = color) Finally, to plot the bars, we use .bar3d() function. Plotting curves Python # importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # get points for a mesh gridu, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j] # setting x, y, z co-ordinatesx=np.cos(u)*np.sin(v)y=np.sin(u)*np.sin(v)z=np.cos(v) # plotting the curveax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1) plt.show() Output of this program will look like this: Here, we plotted a sphere as a mesh grid. Let us go through some important parts: u, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j] We use np.mgrid in order to get points so that we can create a mesh. You can read more about this here. x=np.cos(u)*np.sin(v) y=np.sin(u)*np.sin(v) z=np.cos(v) This is nothing but the parametric equation of a sphere. ax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1) Agan, we use .plot_wireframe() method. Here, rstride and cstride arguments can be used to set how much dense our mesh must be. Next Article: Graph Plotting in Python | Set 3This article 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. varshagumber28 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Oct, 2021" }, { "code": null, "e": 89, "s": 54, "text": "Graph Plotting in Python | Set 1 " }, { "code": null, "e": 99, "s": 89, "text": " Subplots" }, { "code": null, "e": 247, "s": 99, "text": "Subplots are required when we want to show two or more plots in same figure. We can do it in two ways using two slightly different methods.Method 1" }, { "code": null, "e": 254, "s": 247, "text": "Python" }, { "code": "# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # function to generate coordinatesdef create_plot(ptype): # setting the x-axis values x = np.arange(-10, 10, 0.01) # setting the y-axis values if ptype == 'linear': y = x elif ptype == 'quadratic': y = x**2 elif ptype == 'cubic': y = x**3 elif ptype == 'quartic': y = x**4 return(x, y) # setting a style to useplt.style.use('fivethirtyeight') # create a figurefig = plt.figure() # define subplots and their positions in figureplt1 = fig.add_subplot(221)plt2 = fig.add_subplot(222)plt3 = fig.add_subplot(223)plt4 = fig.add_subplot(224) # plotting points on each subplotx, y = create_plot('linear')plt1.plot(x, y, color ='r')plt1.set_title('$y_1 = x$') x, y = create_plot('quadratic')plt2.plot(x, y, color ='b')plt2.set_title('$y_2 = x^2$') x, y = create_plot('cubic')plt3.plot(x, y, color ='g')plt3.set_title('$y_3 = x^3$') x, y = create_plot('quartic')plt4.plot(x, y, color ='k')plt4.set_title('$y_4 = x^4$') # adjusting space between subplotsfig.subplots_adjust(hspace=.5,wspace=0.5) # function to show the plotplt.show()", "e": 1425, "s": 254, "text": null }, { "code": null, "e": 1433, "s": 1425, "text": "Output:" }, { "code": null, "e": 1442, "s": 1433, "text": "Chapters" }, { "code": null, "e": 1469, "s": 1442, "text": "descriptions off, selected" }, { "code": null, "e": 1519, "s": 1469, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1542, "s": 1519, "text": "captions off, selected" }, { "code": null, "e": 1550, "s": 1542, "text": "English" }, { "code": null, "e": 1574, "s": 1550, "text": "This is a modal window." }, { "code": null, "e": 1643, "s": 1574, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1665, "s": 1643, "text": "End of dialog window." }, { "code": null, "e": 1711, "s": 1665, "text": "Let us go through this program step by step: " }, { "code": null, "e": 1744, "s": 1711, "text": "plt.style.use('fivethirtyeight')" }, { "code": null, "e": 1885, "s": 1744, "text": "The styling of plots can be configured by setting different styles available or setting your own. You can learn more about this feature here" }, { "code": null, "e": 1904, "s": 1885, "text": "fig = plt.figure()" }, { "code": null, "e": 2031, "s": 1904, "text": "Figure acts as a top level container for all plot elements. So, we define a figure as fig which will contain all our subplots." }, { "code": null, "e": 2143, "s": 2031, "text": "plt1 = fig.add_subplot(221)\nplt2 = fig.add_subplot(222)\nplt3 = fig.add_subplot(223)\nplt4 = fig.add_subplot(224)" }, { "code": null, "e": 2256, "s": 2143, "text": "Here we use fig.add_subplot method to define subplots and their positions. The function prototype is like this: " }, { "code": null, "e": 2295, "s": 2256, "text": "add_subplot(nrows, ncols, plot_number)" }, { "code": null, "e": 2906, "s": 2295, "text": "If a subplot is applied to a figure, the figure will be notionally split into β€˜nrows’ * β€˜ncols’ sub-axes. The parameter β€˜plot_number’ identifies the subplot that the function call has to create. β€˜plot_number’ can range from 1 to a maximum of β€˜nrows’ * β€˜ncols’.If the values of the three parameters are less than 10, the function subplot can be called with one int parameter, where the hundreds represent β€˜nrows’, the tens represent β€˜ncols’ and the units represent β€˜plot_number’. This means: Instead of subplot(2, 3, 4) we can write subplot(234).This figure will make it clear that how positions are specified: " }, { "code": null, "e": 2991, "s": 2906, "text": "x, y = create_plot('linear')\nplt1.plot(x, y, color ='r')\nplt1.set_title('$y_1 = x$')" }, { "code": null, "e": 3394, "s": 2991, "text": "Next, we plot our points on each subplot. First, we generate x and y axis coordinates using create_plot function by specifying the type of curve we want. Then, we plot those points on our subplot using .plot method. Title of subplot is set by using set_title method. Using $ at starting and end of the title text will ensure that β€˜_'(underscore) is read as a subscript and β€˜^’ is read as a superscript." }, { "code": null, "e": 3436, "s": 3394, "text": "fig.subplots_adjust(hspace=.5,wspace=0.5)" }, { "code": null, "e": 3505, "s": 3436, "text": "This is another utility method which creates space between subplots." }, { "code": null, "e": 3516, "s": 3505, "text": "plt.show()" }, { "code": null, "e": 3590, "s": 3516, "text": "In the end, we call plt.show() method which will show the current figure." }, { "code": null, "e": 3599, "s": 3590, "text": "Method 2" }, { "code": null, "e": 3606, "s": 3599, "text": "Python" }, { "code": "# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # function to generate coordinatesdef create_plot(ptype): # setting the x-axis values x = np.arange(0, 5, 0.01) # setting y-axis values if ptype == 'sin': # a sine wave y = np.sin(2*np.pi*x) elif ptype == 'exp': # negative exponential function y = np.exp(-x) elif ptype == 'hybrid': # a damped sine wave y = (np.sin(2*np.pi*x))*(np.exp(-x)) return(x, y) # setting a style to useplt.style.use('ggplot') # defining subplots and their positionsplt1 = plt.subplot2grid((11,1), (0,0), rowspan = 3, colspan = 1)plt2 = plt.subplot2grid((11,1), (4,0), rowspan = 3, colspan = 1)plt3 = plt.subplot2grid((11,1), (8,0), rowspan = 3, colspan = 1) # plotting points on each subplotx, y = create_plot('sin')plt1.plot(x, y, label = 'sine wave', color ='b')x, y = create_plot('exp')plt2.plot(x, y, label = 'negative exponential', color = 'r')x, y = create_plot('hybrid')plt3.plot(x, y, label = 'damped sine wave', color = 'g') # show legends of each subplotplt1.legend()plt2.legend()plt3.legend() # function to show plotplt.show()", "e": 4779, "s": 3606, "text": null }, { "code": null, "e": 4788, "s": 4779, "text": "Output: " }, { "code": null, "e": 4848, "s": 4788, "text": "Let us go through important parts of this program as well: " }, { "code": null, "e": 5043, "s": 4848, "text": "plt1 = plt.subplot2grid((11,1), (0,0), rowspan = 3, colspan = 1)\nplt2 = plt.subplot2grid((11,1), (4,0), rowspan = 3, colspan = 1)\nplt3 = plt.subplot2grid((11,1), (8,0), rowspan = 3, colspan = 1)" }, { "code": null, "e": 5473, "s": 5043, "text": "subplot2grid is similar to β€œpyplot.subplot” but uses 0-based indexing and let subplot to occupy multiple cells. Let us try to understand the arguments of the subplot2grid method: 1. argument 1 : geometry of the grid 2. argument 2: location of the subplot in the grid 3. argument 3: (rowspan) No. of rows covered by subplot. 4. argument 4: (colspan) No. of columns covered by subplot.This figure will make this concept more clear:" }, { "code": null, "e": 5569, "s": 5473, "text": "In our example, each subplot spans over 3 rows and 1 column with two empty rows (row no. 4,8) ." }, { "code": null, "e": 5644, "s": 5569, "text": "x, y = create_plot('sin')\nplt1.plot(x, y, label = 'sine wave', color ='b')" }, { "code": null, "e": 5729, "s": 5644, "text": "Nothing special in this part as the syntax to plot points on a subplot remains same." }, { "code": null, "e": 5743, "s": 5729, "text": "plt1.legend()" }, { "code": null, "e": 5798, "s": 5743, "text": "This will show the label of the subplot on the figure." }, { "code": null, "e": 5809, "s": 5798, "text": "plt.show()" }, { "code": null, "e": 5876, "s": 5809, "text": "Finally, we call the plt.show() function to show the current plot." }, { "code": null, "e": 6133, "s": 5876, "text": "Note: After going through the above two examples, we can infer that one should use subplot() method when the plots are of uniform size where as subplot2grid() method should be preferred when we want more flexibility on position and sizes of our subplots. " }, { "code": null, "e": 6146, "s": 6133, "text": "3-D plotting" }, { "code": null, "e": 6253, "s": 6146, "text": "We can easily plot 3-D figures in matplotlib. Now, we discuss some important and commonly used 3-D plots. " }, { "code": null, "e": 6269, "s": 6253, "text": "Plotting points" }, { "code": null, "e": 6276, "s": 6269, "text": "Python" }, { "code": "from mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figure# and set projection as 3dax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinatesx = np.random.randint(0, 10, size = 20)y = np.random.randint(0, 10, size = 20)z = np.random.randint(0, 10, size = 20) # plotting the points on subplot # setting labels for the axesax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') # function to show the plotplt.show()", "e": 6926, "s": 6276, "text": null }, { "code": null, "e": 7082, "s": 6926, "text": "Output of above program will provide you with a window which can rotate or enlarge the plot. Here is a screenshot: (dark points are nearer than light ones)" }, { "code": null, "e": 7149, "s": 7082, "text": "Let us try to understand some important aspects of this code now. " }, { "code": null, "e": 7189, "s": 7149, "text": "from mpl_toolkits.mplot3d import axes3d" }, { "code": null, "e": 7240, "s": 7189, "text": "This is the module required to plot on 3-D space. " }, { "code": null, "e": 7284, "s": 7240, "text": "ax1 = fig.add_subplot(111, projection='3d')" }, { "code": null, "e": 7360, "s": 7284, "text": "Here, we create a subplot on our figure and set projection argument as 3d. " }, { "code": null, "e": 7404, "s": 7360, "text": "ax1.scatter(x, y, z, c = 'm', marker = 'o')" }, { "code": null, "e": 7468, "s": 7404, "text": "Now we use .scatter() function to plot the points in XYZ plane." }, { "code": null, "e": 7484, "s": 7468, "text": "Plotting lines " }, { "code": null, "e": 7491, "s": 7484, "text": "Python" }, { "code": "# importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinatesx = np.random.randint(0, 10, size = 5)y = np.random.randint(0, 10, size = 5)z = np.random.randint(0, 10, size = 5) # plotting the points on subplotax1.plot_wireframe(x,y,z) # setting the labelsax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') plt.show()", "e": 8128, "s": 7491, "text": null }, { "code": null, "e": 8190, "s": 8128, "text": "A screenshot of the 3-D plot of above program will look like:" }, { "code": null, "e": 8249, "s": 8190, "text": "The main difference in this program with previous one is: " }, { "code": null, "e": 8275, "s": 8249, "text": "ax1.plot_wireframe(x,y,z)" }, { "code": null, "e": 8354, "s": 8275, "text": "We used .plot_wireframe() method to plot lines over a given set of 3-D points." }, { "code": null, "e": 8368, "s": 8354, "text": "Plotting Bars" }, { "code": null, "e": 8375, "s": 8368, "text": "Python" }, { "code": "# importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # defining x, y, z co-ordinates for bar positionx = [1,2,3,4,5,6,7,8,9,10]y = [4,3,1,6,5,3,7,5,3,7]z = np.zeros(10) # size of barsdx = np.ones(10) # length along x-axisdy = np.ones(10) # length along y-axsdz = [1,3,4,2,6,7,5,5,10,9] # height of bar # setting color schemecolor = []for h in dz: if h > 5: color.append('r') else: color.append('b') # plotting the barsax1.bar3d(x, y, z, dx, dy, dz, color = color) # setting axes labelsax1.set_xlabel('x-axis')ax1.set_ylabel('y-axis')ax1.set_zlabel('z-axis') plt.show()", "e": 9268, "s": 8375, "text": null }, { "code": null, "e": 9321, "s": 9268, "text": "A screenshot of the 3-D environment created is here:" }, { "code": null, "e": 9375, "s": 9321, "text": "Let us go through important aspects of this program: " }, { "code": null, "e": 9445, "s": 9375, "text": "x = [1,2,3,4,5,6,7,8,9,10]\ny = [4,3,1,6,5,3,7,5,3,7]\nz = np.zeros(10)" }, { "code": null, "e": 9540, "s": 9445, "text": "Here, we define the base positions of bars. Setting z = 0 means all bars start from XY plane. " }, { "code": null, "e": 9689, "s": 9540, "text": "dx = np.ones(10) # length along x-axis\ndy = np.ones(10) # length along y-axs\ndz = [1,3,4,2,6,7,5,5,10,9] # height of bar" }, { "code": null, "e": 9822, "s": 9689, "text": "dx, dy, dz denote the size of bar. Consider he bar as a cuboid, then dx, dy, dz are its expansions along x, y, z axis respectively. " }, { "code": null, "e": 9911, "s": 9822, "text": "for h in dz:\n if h > 5:\n color.append('r')\n else:\n color.append('b')" }, { "code": null, "e": 10039, "s": 9911, "text": "Here, we set the color for each bar as a list. The color scheme is red for bars with height greater than 5 and blue otherwise. " }, { "code": null, "e": 10085, "s": 10039, "text": "ax1.bar3d(x, y, z, dx, dy, dz, color = color)" }, { "code": null, "e": 10138, "s": 10085, "text": "Finally, to plot the bars, we use .bar3d() function." }, { "code": null, "e": 10155, "s": 10138, "text": "Plotting curves " }, { "code": null, "e": 10162, "s": 10155, "text": "Python" }, { "code": "# importing required modulesfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np # setting a custom style to usestyle.use('ggplot') # create a new figure for plottingfig = plt.figure() # create a new subplot on our figureax1 = fig.add_subplot(111, projection='3d') # get points for a mesh gridu, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j] # setting x, y, z co-ordinatesx=np.cos(u)*np.sin(v)y=np.sin(u)*np.sin(v)z=np.cos(v) # plotting the curveax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1) plt.show()", "e": 10749, "s": 10162, "text": null }, { "code": null, "e": 10794, "s": 10749, "text": "Output of this program will look like this: " }, { "code": null, "e": 10877, "s": 10794, "text": "Here, we plotted a sphere as a mesh grid. Let us go through some important parts: " }, { "code": null, "e": 10923, "s": 10877, "text": "u, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j]" }, { "code": null, "e": 11028, "s": 10923, "text": "We use np.mgrid in order to get points so that we can create a mesh. You can read more about this here. " }, { "code": null, "e": 11084, "s": 11028, "text": "x=np.cos(u)*np.sin(v)\ny=np.sin(u)*np.sin(v)\nz=np.cos(v)" }, { "code": null, "e": 11142, "s": 11084, "text": "This is nothing but the parametric equation of a sphere. " }, { "code": null, "e": 11211, "s": 11142, "text": "ax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1)" }, { "code": null, "e": 11338, "s": 11211, "text": "Agan, we use .plot_wireframe() method. Here, rstride and cstride arguments can be used to set how much dense our mesh must be." }, { "code": null, "e": 11804, "s": 11338, "text": "Next Article: Graph Plotting in Python | Set 3This article 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": 11819, "s": 11804, "text": "varshagumber28" }, { "code": null, "e": 11826, "s": 11819, "text": "Python" } ]
Sort an array of 0s, 1s and 2s | Practice | GeeksforGeeks
Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. Example 1: Input: N = 5 arr[]= {0 2 1 2 0} Output: 0 0 1 2 2 Explanation: 0s 1s and 2s are segregated into ascending order. Example 2: Input: N = 3 arr[] = {0 1 0} Output: 0 0 1 Explanation: 0s 1s and 2s are segregated into ascending order. Your Task: You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 10^6 0 <= A[i] <= 2 0 kambledhruva14 hours ago What is wrong with this code??? it shows runtime error. Segmentation Fault (SIGSEGV) Learn More aboutSeg Fault ---------------------------------------- void sort012(int a[], int n){ int s= 0, e= n-1; while(s<=e){ if(a[s]==0){ s++; } if(a[s]>a[e]){ int temp= a[s]; a[s] = a[e]; a[e] = temp; // swap(a[s],a[e]); s++; } else e++; } } +2 prajapatiaakash3641 day ago This Solution is best It take Time Complexity O(n) Without Extra Space Plz Upvote If like Solution int low=0; int mid=0; int high=n-1; while(mid<=high) { if(a[mid]==0){ swap(a[low],a[mid]); low++; mid++; } else if(a[mid]==1) mid++; else{ swap(a[mid],a[high]); high--; } } #Logic Initially low, mid are set at 0 and high is at n-1 Now, we iterate mid from 0 to high, and for every element if it is equal to 0, we swap it with element at low, and increment low and mid else if it is equal to 2, we swap it with element at high, and decrement high else we just increment mid (i.e element is equal to 1) 0 dhanakdeepak422 days ago Arrays.sort(a); 0 shlokdayma662 days ago res0 = [] res1 = [] res2 = [] for i in range(n): if arr[i] == 0: res0.append(arr[i]) elif arr[i] == 1: res1.append(arr[i]) else: res2.append(arr[i]) return res0+res1+res2 why this code fails in test case with 65k inputs and works well in jnotebook +3 vaibsu2 days ago void sort012(int a[], int n) { int mp[] = {0, 0, 0}; // counts of 0, 1, 2 for(int i=0; i<n; i++){ mp[a[i]]++; } int writeIndex = 0; for(int i = 0; i < 3; i++){ // 0, 1, 2 for(int j = 0; j < mp[i]; j++){ // 0...count a[writeIndex++] = i; } } } -2 rohitraj31313 days ago void sort012(int a[], int n) { sort(a, a + n); for(int i = 0; i < n; i++){ cout << a[i] << " "; } +1 aligrewal213 days ago int zeros=0,ones=0,two=0; for(int i=0; i<n; i++) { if(a[i]==0) zeros++; else if(a[i]==1) ones++; else two++; } for(int i=0; i<n; i++) { if(zeros) { a[i] = 0; zeros--; } else if(ones) { a[i] = 1; ones--; } else a[i] = 2; } -1 19r11agd1m3 days ago public static void sort012(int a[], int n) { // code here Arrays.sort(a); }} 0 abhishekdubey953 days ago this is the most simple solution. Just count 0,1,&2 and put it in the array. Please upvote. public static void sort012(int a[], int n) { // code here int count0 = 0; int count1 = 0; int count2 = 0; for(int i=0; i<a.length; i++){ if(a[i] == 0){ count0++; } else if(a[i] == 1){ count1++; } else{ count2++; } } int k = 0; while(k < count0){ a[k] = 0; k++; } int l = k; while(l < count0+count1){ a[l] = 1; l++; } int m = l; while (m<a.length){ a[m] = 2; m++; } }} +1 adamyasharma4933 days ago void sort012(int arr[], int n) { // code here // O(n) solution int low=0,mid=0,high=n-1; while(mid<=high) { if(arr[mid]==1)mid++; else if(arr[mid]==2) { swap(arr[high],arr[mid]); high--; } else //0s { swap(arr[low],arr[mid]); low++; mid++; } } return ; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 330, "s": 238, "text": "Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order." }, { "code": null, "e": 342, "s": 330, "text": "\nExample 1:" }, { "code": null, "e": 457, "s": 342, "text": "Input: \nN = 5\narr[]= {0 2 1 2 0}\nOutput:\n0 0 1 2 2\nExplanation:\n0s 1s and 2s are segregated \ninto ascending order." }, { "code": null, "e": 468, "s": 457, "text": "Example 2:" }, { "code": null, "e": 576, "s": 468, "text": "Input: \nN = 3\narr[] = {0 1 0}\nOutput:\n0 0 1\nExplanation:\n0s 1s and 2s are segregated \ninto ascending order." }, { "code": null, "e": 765, "s": 576, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. " }, { "code": null, "e": 828, "s": 765, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 872, "s": 828, "text": "\nConstraints:\n1 <= N <= 10^6\n0 <= A[i] <= 2" }, { "code": null, "e": 874, "s": 872, "text": "0" }, { "code": null, "e": 899, "s": 874, "text": "kambledhruva14 hours ago" }, { "code": null, "e": 931, "s": 899, "text": "What is wrong with this code???" }, { "code": null, "e": 955, "s": 931, "text": "it shows runtime error." }, { "code": null, "e": 984, "s": 955, "text": "Segmentation Fault (SIGSEGV)" }, { "code": null, "e": 1010, "s": 984, "text": "Learn More aboutSeg Fault" }, { "code": null, "e": 1051, "s": 1010, "text": "----------------------------------------" }, { "code": null, "e": 1081, "s": 1051, "text": "void sort012(int a[], int n){" }, { "code": null, "e": 1102, "s": 1081, "text": " int s= 0, e= n-1;" }, { "code": null, "e": 1389, "s": 1102, "text": " while(s<=e){ if(a[s]==0){ s++; } if(a[s]>a[e]){ int temp= a[s]; a[s] = a[e]; a[e] = temp; // swap(a[s],a[e]); s++; } else e++; } }" }, { "code": null, "e": 1392, "s": 1389, "text": "+2" }, { "code": null, "e": 1420, "s": 1392, "text": "prajapatiaakash3641 day ago" }, { "code": null, "e": 1492, "s": 1420, "text": "This Solution is best It take Time Complexity O(n) Without Extra Space " }, { "code": null, "e": 1522, "s": 1492, "text": "Plz Upvote If like Solution " }, { "code": null, "e": 1871, "s": 1524, "text": " int low=0; int mid=0; int high=n-1; while(mid<=high) { if(a[mid]==0){ swap(a[low],a[mid]); low++; mid++; } else if(a[mid]==1) mid++; else{ swap(a[mid],a[high]); high--; } }" }, { "code": null, "e": 1881, "s": 1873, "text": "#Logic " }, { "code": null, "e": 1942, "s": 1881, "text": " Initially low, mid are set at 0 and high is at n-1" }, { "code": null, "e": 2010, "s": 1942, "text": " Now, we iterate mid from 0 to high, and for every element" }, { "code": null, "e": 2106, "s": 2010, "text": " if it is equal to 0, we swap it with element at low, and increment low and mid" }, { "code": null, "e": 2201, "s": 2106, "text": " else if it is equal to 2, we swap it with element at high, and decrement high" }, { "code": null, "e": 2273, "s": 2201, "text": " else we just increment mid (i.e element is equal to 1)" }, { "code": null, "e": 2275, "s": 2273, "text": "0" }, { "code": null, "e": 2300, "s": 2275, "text": "dhanakdeepak422 days ago" }, { "code": null, "e": 2317, "s": 2300, "text": " Arrays.sort(a);" }, { "code": null, "e": 2319, "s": 2317, "text": "0" }, { "code": null, "e": 2342, "s": 2319, "text": "shlokdayma662 days ago" }, { "code": null, "e": 2610, "s": 2342, "text": "res0 = [] res1 = [] res2 = [] for i in range(n): if arr[i] == 0: res0.append(arr[i]) elif arr[i] == 1: res1.append(arr[i]) else: res2.append(arr[i]) return res0+res1+res2 " }, { "code": null, "e": 2689, "s": 2612, "text": "why this code fails in test case with 65k inputs and works well in jnotebook" }, { "code": null, "e": 2692, "s": 2689, "text": "+3" }, { "code": null, "e": 2709, "s": 2692, "text": "vaibsu2 days ago" }, { "code": null, "e": 3012, "s": 2709, "text": "void sort012(int a[], int n)\n{\n int mp[] = {0, 0, 0}; // counts of 0, 1, 2\n for(int i=0; i<n; i++){\n mp[a[i]]++;\n }\n int writeIndex = 0;\n for(int i = 0; i < 3; i++){ // 0, 1, 2\n for(int j = 0; j < mp[i]; j++){ // 0...count\n a[writeIndex++] = i;\n }\n }\n}" }, { "code": null, "e": 3015, "s": 3012, "text": "-2" }, { "code": null, "e": 3038, "s": 3015, "text": "rohitraj31313 days ago" }, { "code": null, "e": 3151, "s": 3038, "text": "void sort012(int a[], int n)\n{\n\nsort(a, a + n);\n \n for(int i = 0; i < n; i++){\n cout << a[i] << \" \";\n}" }, { "code": null, "e": 3154, "s": 3151, "text": "+1" }, { "code": null, "e": 3176, "s": 3154, "text": "aligrewal213 days ago" }, { "code": null, "e": 3470, "s": 3176, "text": "int zeros=0,ones=0,two=0;\n for(int i=0; i<n; i++)\n {\n if(a[i]==0) zeros++;\n else if(a[i]==1) ones++;\n else two++;\n }\n for(int i=0; i<n; i++)\n {\n if(zeros) { a[i] = 0; zeros--; }\n else if(ones) { a[i] = 1; ones--; }\n else a[i] = 2;\n }" }, { "code": null, "e": 3473, "s": 3470, "text": "-1" }, { "code": null, "e": 3494, "s": 3473, "text": "19r11agd1m3 days ago" }, { "code": null, "e": 3595, "s": 3494, "text": "public static void sort012(int a[], int n) { // code here Arrays.sort(a); }}" }, { "code": null, "e": 3597, "s": 3595, "text": "0" }, { "code": null, "e": 3623, "s": 3597, "text": "abhishekdubey953 days ago" }, { "code": null, "e": 3847, "s": 3623, "text": "this is the most simple solution. Just count 0,1,&2 and put it in the array. Please upvote. public static void sort012(int a[], int n) { // code here int count0 = 0; int count1 = 0; int count2 = 0;" }, { "code": null, "e": 4072, "s": 3847, "text": " for(int i=0; i<a.length; i++){ if(a[i] == 0){ count0++; } else if(a[i] == 1){ count1++; } else{ count2++; } }" }, { "code": null, "e": 4178, "s": 4072, "text": " int k = 0; while(k < count0){ a[k] = 0; k++; }" }, { "code": null, "e": 4424, "s": 4178, "text": " int l = k; while(l < count0+count1){ a[l] = 1; l++; } int m = l; while (m<a.length){ a[m] = 2; m++; } }}" }, { "code": null, "e": 4427, "s": 4424, "text": "+1" }, { "code": null, "e": 4453, "s": 4427, "text": "adamyasharma4933 days ago" }, { "code": null, "e": 4946, "s": 4453, "text": "void sort012(int arr[], int n)\n {\n // code here \n \n // O(n) solution\n int low=0,mid=0,high=n-1;\n while(mid<=high)\n {\n if(arr[mid]==1)mid++;\n else if(arr[mid]==2)\n {\n swap(arr[high],arr[mid]);\n high--;\n }\n else //0s\n {\n swap(arr[low],arr[mid]);\n low++;\n mid++;\n }\n }\n return ;\n }" }, { "code": null, "e": 5092, "s": 4946, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5128, "s": 5092, "text": " Login to access your submissions. " }, { "code": null, "e": 5138, "s": 5128, "text": "\nProblem\n" }, { "code": null, "e": 5148, "s": 5138, "text": "\nContest\n" }, { "code": null, "e": 5211, "s": 5148, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5396, "s": 5211, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5680, "s": 5396, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 5826, "s": 5680, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 5903, "s": 5826, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5944, "s": 5903, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5972, "s": 5944, "text": "Disable browser extensions." }, { "code": null, "e": 6043, "s": 5972, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6230, "s": 6043, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
JMS - Quick Guide
The term JMS stands for Java Message Service, a Java API which acts as a interface between applications to create, send, receive and read messages between them. Java Message Service is developed by Sun Microsystems as a part of Java Platform Enterprise Edition. The first version of JMS i.e. JMS 1.0.2b was released in June 26, 2001. The stable version of JMS is JMS 2.0 released in May 21, 2013. JMS is a messaging service which provides reliable and asynchronous communication to implement the messaging system between Java based applications and software components. The JMS API provides set of interfaces to communicate with Java programs and also defines standard messaging protocols to support the Java programming language. It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications. It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications. It provides a common interface to communicate with messaging implementations. It provides a common interface to communicate with messaging implementations. The application developed with JMS API, can be deployed in any JMS provider software. The application developed with JMS API, can be deployed in any JMS provider software. Developers can easily create messaging enterprise applications by quickly learning JMS API. Developers can easily create messaging enterprise applications by quickly learning JMS API. It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily. It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily. It allows exchanging and using information between other Java Platform languages such as Scala and Groovy. It allows exchanging and using information between other Java Platform languages such as Scala and Groovy. If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself. If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself. If you forward the message to receivers via server, then the communication will get slower than direct communication. If you forward the message to receivers via server, then the communication will get slower than direct communication. The Java Messaging Service is an API used in J2EE technology for exchanging information between two separate and independent network entities (group of hosts). It also provides reliable, asynchronous communication with other applications. Before beginning with JMS API, we will see what is messaging system? Message is an information that communicates between different components in the same system or different systems. Message can be a text, XML document, and JSON data etc which take place either in synchronous or asynchronous manner. A client can create, send, receive and read the messages by using the messaging agent. Messaging is quite different from electronic mail (e-mail). E-mail communicates between people whereas Messaging system communicates between software applications or software components. The Java Message Service API provides a set of interfaces for applications to create, send, receive, and read messages. It also exchanges information between different systems. It provides reliable and asynchronous communication to implement the messaging systems in Java-based applications. It maximizes the portability of the JMS applications in the messaging domain. If you develop the messaging system by using JMS API, then you can deploy the same application in any JMS Provider software. JMS application contains following elements βˆ’ JMS clients βˆ’ JMS clients use JMS API to send and receive messages. JMS clients βˆ’ JMS clients use JMS API to send and receive messages. Messages βˆ’ It includes the data which will be exchanged between JMS clients. Messages βˆ’ It includes the data which will be exchanged between JMS clients. JMS provider βˆ’ It is a message oriented middleware software, that provides UI components to administrate the JMS application. JMS provider βˆ’ It is a message oriented middleware software, that provides UI components to administrate the JMS application. JMS Sender βˆ’ It is commonly known as JMS Producer or Publisher, which is used to send messages to destination system. JMS Sender βˆ’ It is commonly known as JMS Producer or Publisher, which is used to send messages to destination system. JMS Receiver βˆ’ It is generally known as JMS Consumer or Subscriber, which is used to receive messages to the destination system. JMS Receiver βˆ’ It is generally known as JMS Consumer or Subscriber, which is used to receive messages to the destination system. JMS provides two types of messaging domains βˆ’ Point-to-Point Messaging Domain Publish/Subscribe Messaging Domain In this type, it includes a sender, a receiver and a queue in which one message will be sent to only one receiver. Each message will communicate to a specific queue. The queue will carry the message until receiver is ready. In this type, it includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages. We will look on point-to-point and publish/Subscribe approaches in the upcoming chapters. The following table shows available JMS providers βˆ’ In the previous chapters, we have discussed about overview of JMS API. Now we will see how to setup the development environment for executing JMS examples. We need to use JMS provider to run JMS API in the applications. Here, we are using OpenJMS service provider for running examples. You need to have JDK and Eclipse to configure the OpenJMS provider. Download the Java EE (Enterprise Edition) from this link and Eclipse IDE can be downloaded from here. Step 1 βˆ’ Download the OpenJMS archive from here. Step 2 βˆ’ Click on the highlighted link and extract the openjms-0.7.7-beta-1.zip to C drive. Step 3 βˆ’ Confirm the JAVA_HOME environment variable is set properly. Go to System Properties and click on the Environment Variables. Edit the User Variable and check for the JAVA_HOME variable. Step 4 βˆ’ Now open the command prompt and navigate to the extracted folder. Go to the bin folder and type startup as shown in the image below. Step 5 βˆ’ Next, it will open the OpenJMS window, which shows the ports for accepting connections. The above image indicates that OpenJMS server is started. JMS architecture is designed by Sun Microsystems as a part of Java Platform Enterprise Edition, which makes Java Message Service (JMS) to develop business applications asynchronously and provides support for wide range of enterprise messaging products. JMS supports two types of messaging domains; one is point-to-point messaging domain and another one is publish-subscribe messaging domain. We will be studying about these topics in the upcoming chapters. The below diagram depicts architecture of JMS API βˆ’ JMS API uses an administered tool to bind the administered objects such as connection factories and destinations, to the Java Naming and Directory Interface (JNDI) name space. JNDI is a Java API used to find the data with particular name. A JMS client looks for the administered objects in the JNDI namespace to create logical connection with these objects and destination by using the service provider. JMS API includes following components βˆ’ JMS Provider βˆ’ It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients. JMS Provider βˆ’ It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients. JMS Clients βˆ’ JMS clients use JMS API to send and receive messages. JMS Clients βˆ’ JMS clients use JMS API to send and receive messages. Messages βˆ’ It communicates with clients and exchanges the data between JMS clients to the design of a JMS application. Messages βˆ’ It communicates with clients and exchanges the data between JMS clients to the design of a JMS application. Administered Objects βˆ’ These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider. Administered Objects βˆ’ These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider. The point-to-point message approach includes a sender, a receiver and a queue; in which one message will be sent to only one receiver. Each message will communicate to a specific queue and the same queue will carry the message until receiver is ready. The parts (sender, receiver and queue) of this approach will specify that, each message communicates with a specific queue. The sending client will forward the message to queue and receiver client then extracts the message from the queue. A queue will keep all the messages, until they are consumed or expired. The point-to-point message approach has following features βˆ’ It contains one client for each message. It contains one client for each message. The sender and receiver of message will not have any timing dependency. The sender and receiver of message will not have any timing dependency. The receiver will send an acknowledgment, after successfully receiving the message. The receiver will send an acknowledgment, after successfully receiving the message. Each message communicates with a specific queue. Each message communicates with a specific queue. The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages. This approach includes multiple publishers and consumers and, a single publisher can include multiple consumers. A message will be delivered to an object called topic (specify the destination), which is responsible for the delivery of a message. The topic will keep the messages and distribute to the present subscribers. The publish/subscribe message approach has following features βˆ’ It contains various subscribers for each message. It contains various subscribers for each message. This approach has multiple publishers as well as multiple consumers. This approach has multiple publishers as well as multiple consumers. There is timing dependency for publishers and consumers. There is timing dependency for publishers and consumers. The JMS API contains following building blocks βˆ’ Administered Objects Connections Sessions Message Producers Message Consumers Messages Administered objects are pre-built objects, which can be used by the JMS clients. Administrator uses the Java Naming and Directory Interface (JNDI: It is a Java API, used to find the data with particular name) API namespace to build administered objects. There are two types of administered objects βˆ’ Connection Factory βˆ’ This object provides the connection between JMS client and Service provider. Connection Factory βˆ’ This object provides the connection between JMS client and Service provider. Destination βˆ’ This object defines the JMS clients, to target the messages and receive messages from the destination. Destination βˆ’ This object defines the JMS clients, to target the messages and receive messages from the destination. Connection uses some JMS providers such as WebSphere, Active MQ, Open MQ etc to create connection with client and defines these provider resources virtually outide the Java Virtual Machine (JVM). It creates connection between client and provider. It will use the Connection interface along with ConnectionFactory object to create a connection as shown below βˆ’ Connection connection = connectionFactory.createConnection(); The connection can be closed by using below line βˆ’ connection.close(); It is a light weight JMS object, used for producing and consuming messages. You can create message producers, message consumers, and messages by using sessions. You can create a session by using Connection object and Session interface as shown below βˆ’ //The AUTO_ACKNOWLEDGE field automatically gives the client's receipt messages, when they have been received successfully Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); The message producer is generated by a session, which sends messages to the destination by implementing MessageProducer interface. You can establish a MessageProducer for the destination or queue object as shown below βˆ’ MessageProducer producer = session.createProducer(destination); MessageProducer producer = session.createProducer(queue); Use the send() method to send the messages after creating message producer. producer.send(message); The message consumer is generated by a session, which receives messages from the destination by implementing the MessageConsumer interface. You can establish a MessageConsumer for the destination or queue object as shown below βˆ’ MessageConsumer producer = session.createConsumer(destination); MessageConsumer producer = session.createConsumer(queue); JMS Messages includes the data, which will be exchanged between JMS clients to the design of a JMS application. Messages are highly flexible, that create messages with the matching formats. For more information, refer this chapter. JMS message communicates with JMS clients by using three JMS components βˆ’ Message Header Message Properties Message Body The JMS message header includes following fields, which are used by clients and providers to indicate and send messages. JMSDestination JMSDeliveryMode JMSTimestamp JMSMessageID JMSReplyTo JMSCorrelationID JMSReplyTo JMSRedelivered JMSType JMSExpiration JMSPriority Properties can be created and set for the messages by using the custom name value pairs. The message properties are used with other messaging systems, to create message selectors and for supporting filtering messages. The JMS API provides following message body formats, which are used to send and receive the information in various forms βˆ’ Text message βˆ’ It defines the text message by using the javax.jms.TextMessage interface. Text message βˆ’ It defines the text message by using the javax.jms.TextMessage interface. Object message βˆ’ It defines the Java object by using the javax.jms.ObjectMessage interface. Object message βˆ’ It defines the Java object by using the javax.jms.ObjectMessage interface. Bytes message βˆ’ It specifies the binary data by using the javax.jms.BytesMessage interface. Bytes message βˆ’ It specifies the binary data by using the javax.jms.BytesMessage interface. Stream message βˆ’ It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface. Stream message βˆ’ It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface. Map message βˆ’ It specifies the key/value pair by using the javax.jms.MapMessage interface. Map message βˆ’ It specifies the key/value pair by using the javax.jms.MapMessage interface. An enterprise messaging system is frequently called as message oriented middleware (MOM) to combine the applications in a flexible way. The MOM acts as mediator between two applications to communicate with each other. The messaging flexibility can be explained as shown in the figure below βˆ’ In the above figure, you can see that, Application One communicates with Application Two by using Enterprise Messaging System and sends message via Application Programming Interface (API). The Enterprise Messaging System sends the message to Application Two which is present on different system by handling the network communications. The messaging system will forward the message to Application Two, if there is a network connection; otherwise it will store the message until the connection becomes available, and then send it to Application Two. It is a process of connecting the components of a system by reducing the inter dependencies between them. Loose Coupling increases the flexibility of system and makes the application more maintainable and stable. JMS is a standard Java interface for enterprise messaging system and it is widely used technology for loosely coupled systems, which are executed in Java. The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies For more information on publish/subscribe message approach, refer this chapter. The JMS API can be used to create, send, receive and read message in the applications and has become integral part of Java EE platform. The Java EE applications use JMS API within EJB (Enterprise Java Beans) and web containers, which apply Java EE platform specification to Java EE components. EJB is an essential part of a J2EE (Java 2 Enterprise Edition) platform, which develops and deploy the enterprise applications, by considering robustness, high scalability, and high performance. Web containers are used for the execution of web pages, which run on web servers like Jetty, Tomcat etc. The following ways describe the use of JMS API in the J2EE application βˆ’ These are preconfigured objects in the J2EE application, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider. For more information, refer to the Programming Model chapter. It defines the name of the injected bean in Java EE applications and you can specify the JMS resource as static in an application client component. It can be specified as shown below βˆ’ @Resource(lookup = "jms/ConnectionFactory") private static ConnectionFactory connectionFactory; @Resource(lookup = "jms/Queue") private static Queue queue; In the J2EE application, the JMS API resources contain JMS API connection and session. If you are using JMS API for an enterprise bean instance, then create the resource by using @PostConstruct callback method and close the resource by using @PreDestroy callback method. The JMS API allows developers to create enterprise applications easily and defines the synchronous and asynchronous, reliable communications between J2EE components and other applications. The enterprise applications can be developed with new message-driven beans for defining business events along with existing business events. The bean method can send and receive the message by using the container-managed transactions, instead of using local transactions and manipulates the transaction separation with help of EJB container. Keep the occurrence of JMS operations and database access in a single transaction, by sending and receiving the messages in Java Transaction API (JTA) transactions. You don't need to use an annotation to specify the container-managed transactions, because they are default transactions in the Java EE applications. The message-driven bean is special type of enterprise bean supported by J2EE application, which processes the JMS messages asynchronously in the Java EE applications. The session bean sends and receives the JMS messages synchronously. The messages sent from client's application, enterprise bean, or a web component does not use Java EE technology. The message-driven bean class contains below features βˆ’ This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener. This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener. It creates a connection by using @PostConstruct callback method and closes the connection by using @PreDestroy callback method. Generally, this class uses these methods to produce the messages and receive the messages from another destination. It creates a connection by using @PostConstruct callback method and closes the connection by using @PreDestroy callback method. Generally, this class uses these methods to produce the messages and receive the messages from another destination.
[ { "code": null, "e": 2123, "s": 1961, "text": "The term JMS stands for Java Message Service, a Java API which acts as a interface between applications to create, send, receive and read messages between them. " }, { "code": null, "e": 2359, "s": 2123, "text": "Java Message Service is developed by Sun Microsystems as a part of Java Platform Enterprise Edition. The first version of JMS i.e. JMS 1.0.2b was released in June 26, 2001. The stable version of JMS is JMS 2.0 released in May 21, 2013." }, { "code": null, "e": 2693, "s": 2359, "text": "JMS is a messaging service which provides reliable and asynchronous communication to implement the messaging system between Java based applications and software components. The JMS API provides set of interfaces to communicate with Java programs and also defines standard messaging protocols to support the Java programming language." }, { "code": null, "e": 2834, "s": 2693, "text": "It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications." }, { "code": null, "e": 2975, "s": 2834, "text": "It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications." }, { "code": null, "e": 3053, "s": 2975, "text": "It provides a common interface to communicate with messaging implementations." }, { "code": null, "e": 3131, "s": 3053, "text": "It provides a common interface to communicate with messaging implementations." }, { "code": null, "e": 3217, "s": 3131, "text": "The application developed with JMS API, can be deployed in any JMS provider software." }, { "code": null, "e": 3303, "s": 3217, "text": "The application developed with JMS API, can be deployed in any JMS provider software." }, { "code": null, "e": 3395, "s": 3303, "text": "Developers can easily create messaging enterprise applications by quickly learning JMS API." }, { "code": null, "e": 3487, "s": 3395, "text": "Developers can easily create messaging enterprise applications by quickly learning JMS API." }, { "code": null, "e": 3705, "s": 3487, "text": "It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. " }, { "code": null, "e": 3923, "s": 3705, "text": "It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. " }, { "code": null, "e": 4103, "s": 3923, "text": "It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily." }, { "code": null, "e": 4283, "s": 4103, "text": "It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily." }, { "code": null, "e": 4390, "s": 4283, "text": "It allows exchanging and using information between other Java Platform languages such as Scala and Groovy." }, { "code": null, "e": 4497, "s": 4390, "text": "It allows exchanging and using information between other Java Platform languages such as Scala and Groovy." }, { "code": null, "e": 4698, "s": 4497, "text": "If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself." }, { "code": null, "e": 4899, "s": 4698, "text": "If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself." }, { "code": null, "e": 5017, "s": 4899, "text": "If you forward the message to receivers via server, then the communication will get slower than direct communication." }, { "code": null, "e": 5135, "s": 5017, "text": "If you forward the message to receivers via server, then the communication will get slower than direct communication." }, { "code": null, "e": 5374, "s": 5135, "text": "The Java Messaging Service is an API used in J2EE technology for exchanging information between two separate and independent network entities (group of hosts). It also provides reliable, asynchronous communication with other applications." }, { "code": null, "e": 5443, "s": 5374, "text": "Before beginning with JMS API, we will see what is messaging system?" }, { "code": null, "e": 5949, "s": 5443, "text": "Message is an information that communicates between different components in the same system or different systems. Message can be a text, XML document, and JSON data etc which take place either in synchronous or asynchronous manner. A client can create, send, receive and read the messages by using the messaging agent. Messaging is quite different from electronic mail (e-mail). E-mail communicates between people whereas Messaging system communicates between software applications or software components." }, { "code": null, "e": 6319, "s": 5949, "text": "The Java Message Service API provides a set of interfaces for applications to create, send, receive, and read messages. It also exchanges information between different systems. It provides reliable and asynchronous communication to implement the messaging systems in Java-based applications. It maximizes the portability of the JMS applications in the messaging domain." }, { "code": null, "e": 6444, "s": 6319, "text": "If you develop the messaging system by using JMS API, then you can deploy the same application in any JMS Provider software." }, { "code": null, "e": 6490, "s": 6444, "text": "JMS application contains following elements βˆ’" }, { "code": null, "e": 6558, "s": 6490, "text": "JMS clients βˆ’ JMS clients use JMS API to send and receive messages." }, { "code": null, "e": 6626, "s": 6558, "text": "JMS clients βˆ’ JMS clients use JMS API to send and receive messages." }, { "code": null, "e": 6703, "s": 6626, "text": "Messages βˆ’ It includes the data which will be exchanged between JMS clients." }, { "code": null, "e": 6780, "s": 6703, "text": "Messages βˆ’ It includes the data which will be exchanged between JMS clients." }, { "code": null, "e": 6906, "s": 6780, "text": "JMS provider βˆ’ It is a message oriented middleware software, that provides UI components to administrate the JMS application." }, { "code": null, "e": 7032, "s": 6906, "text": "JMS provider βˆ’ It is a message oriented middleware software, that provides UI components to administrate the JMS application." }, { "code": null, "e": 7151, "s": 7032, "text": "JMS Sender βˆ’ It is commonly known as JMS Producer or Publisher, which is used to send messages to destination system." }, { "code": null, "e": 7270, "s": 7151, "text": "JMS Sender βˆ’ It is commonly known as JMS Producer or Publisher, which is used to send messages to destination system." }, { "code": null, "e": 7400, "s": 7270, "text": "JMS Receiver βˆ’ It is generally known as JMS Consumer or Subscriber, which is used to receive messages to the destination system." }, { "code": null, "e": 7530, "s": 7400, "text": "JMS Receiver βˆ’ It is generally known as JMS Consumer or Subscriber, which is used to receive messages to the destination system." }, { "code": null, "e": 7576, "s": 7530, "text": "JMS provides two types of messaging domains βˆ’" }, { "code": null, "e": 7608, "s": 7576, "text": "Point-to-Point Messaging Domain" }, { "code": null, "e": 7643, "s": 7608, "text": "Publish/Subscribe Messaging Domain" }, { "code": null, "e": 7868, "s": 7643, "text": "In this type, it includes a sender, a receiver and a queue in which one message will be sent to only one receiver. Each message will communicate to a specific queue. The queue will carry the message until receiver is ready. " }, { "code": null, "e": 8171, "s": 7868, "text": "In this type, it includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages." }, { "code": null, "e": 8261, "s": 8171, "text": "We will look on point-to-point and publish/Subscribe approaches in the upcoming chapters." }, { "code": null, "e": 8313, "s": 8261, "text": "The following table shows available JMS providers βˆ’" }, { "code": null, "e": 8601, "s": 8313, "text": "In the previous chapters, we have discussed about overview of JMS API. Now we will see how to setup the development environment for executing JMS examples. We need to use JMS provider to run JMS API in the applications. Here, we are using OpenJMS service provider for running examples." }, { "code": null, "e": 8771, "s": 8601, "text": "You need to have JDK and Eclipse to configure the OpenJMS provider. Download the Java EE (Enterprise Edition) from this link and Eclipse IDE can be downloaded from here." }, { "code": null, "e": 8821, "s": 8771, "text": "Step 1 βˆ’ Download the OpenJMS archive from here. " }, { "code": null, "e": 8913, "s": 8821, "text": "Step 2 βˆ’ Click on the highlighted link and extract the openjms-0.7.7-beta-1.zip to C drive." }, { "code": null, "e": 9107, "s": 8913, "text": "Step 3 βˆ’ Confirm the JAVA_HOME environment variable is set properly. Go to System Properties and click on the Environment Variables. Edit the User Variable and check for the JAVA_HOME variable." }, { "code": null, "e": 9249, "s": 9107, "text": "Step 4 βˆ’ Now open the command prompt and navigate to the extracted folder. Go to the bin folder and type startup as shown in the image below." }, { "code": null, "e": 9347, "s": 9249, "text": "Step 5 βˆ’ Next, it will open the OpenJMS window, which shows the ports for accepting connections. " }, { "code": null, "e": 9405, "s": 9347, "text": "The above image indicates that OpenJMS server is started." }, { "code": null, "e": 9863, "s": 9405, "text": "JMS architecture is designed by Sun Microsystems as a part of Java Platform Enterprise Edition, which makes Java Message Service (JMS) to develop business applications asynchronously and provides support for wide range of enterprise messaging products. JMS supports two types of messaging domains; one is point-to-point messaging domain and another one is publish-subscribe messaging domain. We will be studying about these topics in the upcoming chapters." }, { "code": null, "e": 9915, "s": 9863, "text": "The below diagram depicts architecture of JMS API βˆ’" }, { "code": null, "e": 10320, "s": 9915, "text": "JMS API uses an administered tool to bind the administered objects such as connection factories and destinations, to the Java Naming and Directory Interface (JNDI) name space. JNDI is a Java API used to find the data with particular name. A JMS client looks for the administered objects in the JNDI namespace to create logical connection with these objects and destination by using the service provider." }, { "code": null, "e": 10360, "s": 10320, "text": "JMS API includes following components βˆ’" }, { "code": null, "e": 10531, "s": 10360, "text": "JMS Provider βˆ’ It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients." }, { "code": null, "e": 10702, "s": 10531, "text": "JMS Provider βˆ’ It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients." }, { "code": null, "e": 10770, "s": 10702, "text": "JMS Clients βˆ’ JMS clients use JMS API to send and receive messages." }, { "code": null, "e": 10838, "s": 10770, "text": "JMS Clients βˆ’ JMS clients use JMS API to send and receive messages." }, { "code": null, "e": 10957, "s": 10838, "text": "Messages βˆ’ It communicates with clients and exchanges the data between JMS clients to the design of a JMS application." }, { "code": null, "e": 11076, "s": 10957, "text": "Messages βˆ’ It communicates with clients and exchanges the data between JMS clients to the design of a JMS application." }, { "code": null, "e": 11502, "s": 11076, "text": "Administered Objects βˆ’ These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider." }, { "code": null, "e": 11928, "s": 11502, "text": "Administered Objects βˆ’ These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider." }, { "code": null, "e": 12181, "s": 11928, "text": "The point-to-point message approach includes a sender, a receiver and a queue; in which one message will be sent to only one receiver. Each message will communicate to a specific queue and the same queue will carry the message until receiver is ready. " }, { "code": null, "e": 12492, "s": 12181, "text": "The parts (sender, receiver and queue) of this approach will specify that, each message communicates with a specific queue. The sending client will forward the message to queue and receiver client then extracts the message from the queue. A queue will keep all the messages, until they are consumed or expired." }, { "code": null, "e": 12553, "s": 12492, "text": "The point-to-point message approach has following features βˆ’" }, { "code": null, "e": 12594, "s": 12553, "text": "It contains one client for each message." }, { "code": null, "e": 12635, "s": 12594, "text": "It contains one client for each message." }, { "code": null, "e": 12707, "s": 12635, "text": "The sender and receiver of message will not have any timing dependency." }, { "code": null, "e": 12779, "s": 12707, "text": "The sender and receiver of message will not have any timing dependency." }, { "code": null, "e": 12863, "s": 12779, "text": "The receiver will send an acknowledgment, after successfully receiving the message." }, { "code": null, "e": 12947, "s": 12863, "text": "The receiver will send an acknowledgment, after successfully receiving the message." }, { "code": null, "e": 12996, "s": 12947, "text": "Each message communicates with a specific queue." }, { "code": null, "e": 13045, "s": 12996, "text": "Each message communicates with a specific queue." }, { "code": null, "e": 13370, "s": 13045, "text": "The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages." }, { "code": null, "e": 13692, "s": 13370, "text": "This approach includes multiple publishers and consumers and, a single publisher can include multiple consumers. A message will be delivered to an object called topic (specify the destination), which is responsible for the delivery of a message. The topic will keep the messages and distribute to the present subscribers." }, { "code": null, "e": 13756, "s": 13692, "text": "The publish/subscribe message approach has following features βˆ’" }, { "code": null, "e": 13806, "s": 13756, "text": "It contains various subscribers for each message." }, { "code": null, "e": 13856, "s": 13806, "text": "It contains various subscribers for each message." }, { "code": null, "e": 13925, "s": 13856, "text": "This approach has multiple publishers as well as multiple consumers." }, { "code": null, "e": 13994, "s": 13925, "text": "This approach has multiple publishers as well as multiple consumers." }, { "code": null, "e": 14051, "s": 13994, "text": "There is timing dependency for publishers and consumers." }, { "code": null, "e": 14108, "s": 14051, "text": "There is timing dependency for publishers and consumers." }, { "code": null, "e": 14157, "s": 14108, "text": "The JMS API contains following building blocks βˆ’" }, { "code": null, "e": 14178, "s": 14157, "text": "Administered Objects" }, { "code": null, "e": 14190, "s": 14178, "text": "Connections" }, { "code": null, "e": 14199, "s": 14190, "text": "Sessions" }, { "code": null, "e": 14217, "s": 14199, "text": "Message Producers" }, { "code": null, "e": 14235, "s": 14217, "text": "Message Consumers" }, { "code": null, "e": 14244, "s": 14235, "text": "Messages" }, { "code": null, "e": 14545, "s": 14244, "text": "Administered objects are pre-built objects, which can be used by the JMS clients. Administrator uses the Java Naming and Directory Interface (JNDI: It is a Java API, used to find the data with particular name) API namespace to build administered objects. There are two types of administered objects βˆ’" }, { "code": null, "e": 14643, "s": 14545, "text": "Connection Factory βˆ’ This object provides the connection between JMS client and Service provider." }, { "code": null, "e": 14741, "s": 14643, "text": "Connection Factory βˆ’ This object provides the connection between JMS client and Service provider." }, { "code": null, "e": 14858, "s": 14741, "text": "Destination βˆ’ This object defines the JMS clients, to target the messages and receive messages from the destination." }, { "code": null, "e": 14975, "s": 14858, "text": "Destination βˆ’ This object defines the JMS clients, to target the messages and receive messages from the destination." }, { "code": null, "e": 15222, "s": 14975, "text": "Connection uses some JMS providers such as WebSphere, Active MQ, Open MQ etc to create connection with client and defines these provider resources virtually outide the Java Virtual Machine (JVM). It creates connection between client and provider." }, { "code": null, "e": 15335, "s": 15222, "text": "It will use the Connection interface along with ConnectionFactory object to create a connection as shown below βˆ’" }, { "code": null, "e": 15398, "s": 15335, "text": "Connection connection = connectionFactory.createConnection();\n" }, { "code": null, "e": 15449, "s": 15398, "text": "The connection can be closed by using below line βˆ’" }, { "code": null, "e": 15470, "s": 15449, "text": "connection.close();\n" }, { "code": null, "e": 15631, "s": 15470, "text": "It is a light weight JMS object, used for producing and consuming messages. You can create message producers, message consumers, and messages by using sessions." }, { "code": null, "e": 15722, "s": 15631, "text": "You can create a session by using Connection object and Session interface as shown below βˆ’" }, { "code": null, "e": 15922, "s": 15722, "text": "//The AUTO_ACKNOWLEDGE field automatically gives the client's receipt messages, when they have been received successfully\nSession session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n" }, { "code": null, "e": 16142, "s": 15922, "text": "The message producer is generated by a session, which sends messages to the destination by implementing MessageProducer interface. You can establish a MessageProducer for the destination or queue object as shown below βˆ’" }, { "code": null, "e": 16265, "s": 16142, "text": "MessageProducer producer = session.createProducer(destination);\nMessageProducer producer = session.createProducer(queue);\n" }, { "code": null, "e": 16341, "s": 16265, "text": "Use the send() method to send the messages after creating message producer." }, { "code": null, "e": 16366, "s": 16341, "text": "producer.send(message);\n" }, { "code": null, "e": 16595, "s": 16366, "text": "The message consumer is generated by a session, which receives messages from the destination by implementing the MessageConsumer interface. You can establish a MessageConsumer for the destination or queue object as shown below βˆ’" }, { "code": null, "e": 16718, "s": 16595, "text": "MessageConsumer producer = session.createConsumer(destination);\nMessageConsumer producer = session.createConsumer(queue);\n" }, { "code": null, "e": 16950, "s": 16718, "text": "JMS Messages includes the data, which will be exchanged between JMS clients to the design of a JMS application. Messages are highly flexible, that create messages with the matching formats. For more information, refer this chapter." }, { "code": null, "e": 17024, "s": 16950, "text": "JMS message communicates with JMS clients by using three JMS components βˆ’" }, { "code": null, "e": 17039, "s": 17024, "text": "Message Header" }, { "code": null, "e": 17058, "s": 17039, "text": "Message Properties" }, { "code": null, "e": 17071, "s": 17058, "text": "Message Body" }, { "code": null, "e": 17192, "s": 17071, "text": "The JMS message header includes following fields, which are used by clients and providers to indicate and send messages." }, { "code": null, "e": 17207, "s": 17192, "text": "JMSDestination" }, { "code": null, "e": 17223, "s": 17207, "text": "JMSDeliveryMode" }, { "code": null, "e": 17236, "s": 17223, "text": "JMSTimestamp" }, { "code": null, "e": 17249, "s": 17236, "text": "JMSMessageID" }, { "code": null, "e": 17260, "s": 17249, "text": "JMSReplyTo" }, { "code": null, "e": 17277, "s": 17260, "text": "JMSCorrelationID" }, { "code": null, "e": 17288, "s": 17277, "text": "JMSReplyTo" }, { "code": null, "e": 17303, "s": 17288, "text": "JMSRedelivered" }, { "code": null, "e": 17311, "s": 17303, "text": "JMSType" }, { "code": null, "e": 17325, "s": 17311, "text": "JMSExpiration" }, { "code": null, "e": 17337, "s": 17325, "text": "JMSPriority" }, { "code": null, "e": 17555, "s": 17337, "text": "Properties can be created and set for the messages by using the custom name value pairs. The message properties are used with other messaging systems, to create message selectors and for supporting filtering messages." }, { "code": null, "e": 17678, "s": 17555, "text": "The JMS API provides following message body formats, which are used to send and receive the information in various forms βˆ’" }, { "code": null, "e": 17767, "s": 17678, "text": "Text message βˆ’ It defines the text message by using the javax.jms.TextMessage interface." }, { "code": null, "e": 17856, "s": 17767, "text": "Text message βˆ’ It defines the text message by using the javax.jms.TextMessage interface." }, { "code": null, "e": 17948, "s": 17856, "text": "Object message βˆ’ It defines the Java object by using the javax.jms.ObjectMessage interface." }, { "code": null, "e": 18040, "s": 17948, "text": "Object message βˆ’ It defines the Java object by using the javax.jms.ObjectMessage interface." }, { "code": null, "e": 18132, "s": 18040, "text": "Bytes message βˆ’ It specifies the binary data by using the javax.jms.BytesMessage interface." }, { "code": null, "e": 18224, "s": 18132, "text": "Bytes message βˆ’ It specifies the binary data by using the javax.jms.BytesMessage interface." }, { "code": null, "e": 18361, "s": 18224, "text": "Stream message βˆ’ It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface." }, { "code": null, "e": 18498, "s": 18361, "text": "Stream message βˆ’ It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface." }, { "code": null, "e": 18589, "s": 18498, "text": "Map message βˆ’ It specifies the key/value pair by using the javax.jms.MapMessage interface." }, { "code": null, "e": 18680, "s": 18589, "text": "Map message βˆ’ It specifies the key/value pair by using the javax.jms.MapMessage interface." }, { "code": null, "e": 18898, "s": 18680, "text": "An enterprise messaging system is frequently called as message oriented middleware (MOM) to combine the applications in a flexible way. The MOM acts as mediator between two applications to communicate with each other." }, { "code": null, "e": 18972, "s": 18898, "text": "The messaging flexibility can be explained as shown in the figure below βˆ’" }, { "code": null, "e": 19520, "s": 18972, "text": "In the above figure, you can see that, Application One communicates with Application Two by using Enterprise Messaging System and sends message via Application Programming Interface (API). The Enterprise Messaging System sends the message to Application Two which is present on different system by handling the network communications. The messaging system will forward the message to Application Two, if there is a network connection; otherwise it will store the message until the connection becomes available, and then send it to Application Two." }, { "code": null, "e": 19733, "s": 19520, "text": "It is a process of connecting the components of a system by reducing the inter dependencies between them. Loose Coupling increases the flexibility of system and makes the application more maintainable and stable." }, { "code": null, "e": 19889, "s": 19733, "text": "JMS is a standard Java interface for enterprise messaging system and it is widely used technology for loosely coupled systems, which are executed in Java. " }, { "code": null, "e": 20129, "s": 19889, "text": "The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies" }, { "code": null, "e": 20209, "s": 20129, "text": "For more information on publish/subscribe message approach, refer this chapter." }, { "code": null, "e": 20503, "s": 20209, "text": "The JMS API can be used to create, send, receive and read message in the applications and has become integral part of Java EE platform. The Java EE applications use JMS API within EJB (Enterprise Java Beans) and web containers, which apply Java EE platform specification to Java EE components." }, { "code": null, "e": 20804, "s": 20503, "text": "EJB is an essential part of a J2EE (Java 2 Enterprise Edition) platform, which develops and deploy the enterprise applications, by considering robustness, high scalability, and high performance. Web containers are used for the execution of web pages, which run on web servers like Jetty, Tomcat etc." }, { "code": null, "e": 20877, "s": 20804, "text": "The following ways describe the use of JMS API in the J2EE application βˆ’" }, { "code": null, "e": 21366, "s": 20877, "text": "These are preconfigured objects in the J2EE application, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider. For more information, refer to the Programming Model chapter." }, { "code": null, "e": 21551, "s": 21366, "text": "It defines the name of the injected bean in Java EE applications and you can specify the JMS resource as static in an application client component. It can be specified as shown below βˆ’" }, { "code": null, "e": 21708, "s": 21551, "text": "@Resource(lookup = \"jms/ConnectionFactory\")\nprivate static ConnectionFactory connectionFactory;\n\n@Resource(lookup = \"jms/Queue\")\nprivate static Queue queue;" }, { "code": null, "e": 21979, "s": 21708, "text": "In the J2EE application, the JMS API resources contain JMS API connection and session. If you are using JMS API for an enterprise bean instance, then create the resource by using @PostConstruct callback method and close the resource by using @PreDestroy callback method." }, { "code": null, "e": 22309, "s": 21979, "text": "The JMS API allows developers to create enterprise applications easily and defines the synchronous and asynchronous, reliable communications between J2EE components and other applications. The enterprise applications can be developed with new message-driven beans for defining business events along with existing business events." }, { "code": null, "e": 22825, "s": 22309, "text": "The bean method can send and receive the message by using the container-managed transactions, instead of using local transactions and manipulates the transaction separation with help of EJB container. Keep the occurrence of JMS operations and database access in a single transaction, by sending and receiving the messages in Java Transaction API (JTA) transactions. You don't need to use an annotation to specify the container-managed transactions, because they are default transactions in the Java EE applications." }, { "code": null, "e": 23174, "s": 22825, "text": "The message-driven bean is special type of enterprise bean supported by J2EE application, which processes the JMS messages asynchronously in the Java EE applications. The session bean sends and receives the JMS messages synchronously. The messages sent from client's application, enterprise bean, or a web component does not use Java EE technology." }, { "code": null, "e": 23230, "s": 23174, "text": "The message-driven bean class contains below features βˆ’" }, { "code": null, "e": 23388, "s": 23230, "text": "This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener." }, { "code": null, "e": 23546, "s": 23388, "text": "This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener." }, { "code": null, "e": 23790, "s": 23546, "text": "It creates a connection by using @PostConstruct callback method and closes the connection by using @PreDestroy callback method. Generally, this class uses these methods to produce the messages and receive the messages from another destination." } ]
How to generate and read QR code with Java using ZXing Library
08 Oct, 2020 QRCode is abbreviated as Quic Response Code and we are quite familiar with QRCodes now a days. It is used for authenticated and quick online payments. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.A QRCode is an arrangement of black and white squares and can be read with various QRCode Scanners and is convenient today because every smartphone has a QRcode scanner app. Library used for generating QRCodes (ZXing) ZXing (β€œZebra Crossing”) is the popular API for QR code processing in Java. Its library has multiple components and we will be using the β€˜core’ for QR code creation in our Java example. How to generate QR code? Following code is an example to create a QR code image. Download the ZXING library from here. Add ZXING dependency in maven file. Download the ZXING library from here. Add ZXING dependency in maven file. XML <dependencies> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency></dependencies> Write the code to generate QR code and save it as a jpg file in the native folder. Write the code to generate QR code and save it as a jpg file in the native folder. Java // Java code to generate QR code import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class MyQr { // Function to create the QR code public static void createQR(String data, String path, String charset, Map hashMap, int height, int width) throws WriterException, IOException { BitMatrix matrix = new MultiFormatWriter().encode( new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToFile( matrix, path.substring(path.lastIndexOf('.') + 1), new File(path)); } // Driver code public static void main(String[] args) throws WriterException, IOException, NotFoundException { // The data that the QR code will contain String data = "www.geeksforgeeks.org"; // The path where the image will get saved String path = "demo.png"; // Encoding charset String charset = "UTF-8"; Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // Create the QR code and save // in the specified folder // as a jpg file createQR(data, path, charset, hashMap, 200, 200); System.out.println("QR Code Generated!!! "); }} The output file will be by name demo.jpg On scanning this QRCode you will be redirected to geeksforgeeks home page. How to generate QR code? After generating the QR code, we can also read the QR code image file using ZXing library. Below is the code to do so. Java // Java code to read the QR code import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;import com.google.zxing.BinaryBitmap;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.Result;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCode { // Function to read the QR file public static String readQR(String path, String charset, Map hashMap) throws FileNotFoundException, IOException, NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageLuminanceSource( ImageIO.read( new FileInputStream(path))))); Result result = new MultiFormatReader().decode(binaryBitmap); return result.getText(); } // Driver code public static void main(String[] args) throws WriterException, IOException, NotFoundException { // Path where the QR code is saved String path = "F:\user\QRCodes"; // Encoding charset String charset = "UTF-8"; Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); System.out.println( "QRCode output: " + readQRCode(filePath, charset, hintMap)); } } Output: QRCode output: www.geeksforgeeks.org shubhamagarwal11 Image-Processing Java Programs Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java Java program to count the occurrence of each character in a string using Hashmap How to Iterate HashMap in Java? SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Oct, 2020" }, { "code": null, "e": 531, "s": 54, "text": "QRCode is abbreviated as Quic Response Code and we are quite familiar with QRCodes now a days. It is used for authenticated and quick online payments. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.A QRCode is an arrangement of black and white squares and can be read with various QRCode Scanners and is convenient today because every smartphone has a QRcode scanner app. " }, { "code": null, "e": 575, "s": 531, "text": "Library used for generating QRCodes (ZXing)" }, { "code": null, "e": 763, "s": 575, "text": "ZXing (β€œZebra Crossing”) is the popular API for QR code processing in Java. Its library has multiple components and we will be using the β€˜core’ for QR code creation in our Java example. " }, { "code": null, "e": 788, "s": 763, "text": "How to generate QR code?" }, { "code": null, "e": 844, "s": 788, "text": "Following code is an example to create a QR code image." }, { "code": null, "e": 918, "s": 844, "text": "Download the ZXING library from here. Add ZXING dependency in maven file." }, { "code": null, "e": 957, "s": 918, "text": "Download the ZXING library from here. " }, { "code": null, "e": 993, "s": 957, "text": "Add ZXING dependency in maven file." }, { "code": null, "e": 997, "s": 993, "text": "XML" }, { "code": "<dependencies> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency></dependencies> ", "e": 1322, "s": 997, "text": null }, { "code": null, "e": 1406, "s": 1322, "text": "Write the code to generate QR code and save it as a jpg file in the native folder. " }, { "code": null, "e": 1490, "s": 1406, "text": "Write the code to generate QR code and save it as a jpg file in the native folder. " }, { "code": null, "e": 1495, "s": 1490, "text": "Java" }, { "code": "// Java code to generate QR code import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class MyQr { // Function to create the QR code public static void createQR(String data, String path, String charset, Map hashMap, int height, int width) throws WriterException, IOException { BitMatrix matrix = new MultiFormatWriter().encode( new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToFile( matrix, path.substring(path.lastIndexOf('.') + 1), new File(path)); } // Driver code public static void main(String[] args) throws WriterException, IOException, NotFoundException { // The data that the QR code will contain String data = \"www.geeksforgeeks.org\"; // The path where the image will get saved String path = \"demo.png\"; // Encoding charset String charset = \"UTF-8\"; Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // Create the QR code and save // in the specified folder // as a jpg file createQR(data, path, charset, hashMap, 200, 200); System.out.println(\"QR Code Generated!!! \"); }}", "e": 3412, "s": 1495, "text": null }, { "code": null, "e": 3454, "s": 3412, "text": "The output file will be by name demo.jpg " }, { "code": null, "e": 3531, "s": 3454, "text": "On scanning this QRCode you will be redirected to geeksforgeeks home page. " }, { "code": null, "e": 3556, "s": 3531, "text": "How to generate QR code?" }, { "code": null, "e": 3675, "s": 3556, "text": "After generating the QR code, we can also read the QR code image file using ZXing library. Below is the code to do so." }, { "code": null, "e": 3680, "s": 3675, "text": "Java" }, { "code": "// Java code to read the QR code import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;import com.google.zxing.BinaryBitmap;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.Result;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCode { // Function to read the QR file public static String readQR(String path, String charset, Map hashMap) throws FileNotFoundException, IOException, NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageLuminanceSource( ImageIO.read( new FileInputStream(path))))); Result result = new MultiFormatReader().decode(binaryBitmap); return result.getText(); } // Driver code public static void main(String[] args) throws WriterException, IOException, NotFoundException { // Path where the QR code is saved String path = \"F:\\user\\QRCodes\"; // Encoding charset String charset = \"UTF-8\"; Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); System.out.println( \"QRCode output: \" + readQRCode(filePath, charset, hintMap)); } }", "e": 5729, "s": 3680, "text": null }, { "code": null, "e": 5738, "s": 5729, "text": "Output: " }, { "code": null, "e": 5776, "s": 5738, "text": "QRCode output: www.geeksforgeeks.org\n" }, { "code": null, "e": 5793, "s": 5776, "text": "shubhamagarwal11" }, { "code": null, "e": 5810, "s": 5793, "text": "Image-Processing" }, { "code": null, "e": 5824, "s": 5810, "text": "Java Programs" }, { "code": null, "e": 5832, "s": 5824, "text": "Project" }, { "code": null, "e": 5930, "s": 5832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5968, "s": 5930, "text": "Factory method design pattern in Java" }, { "code": null, "e": 6025, "s": 5968, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 6054, "s": 6025, "text": "Iterate through List in Java" }, { "code": null, "e": 6135, "s": 6054, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 6167, "s": 6135, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 6216, "s": 6167, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6271, "s": 6216, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 6304, "s": 6271, "text": "Working with zip files in Python" }, { "code": null, "e": 6326, "s": 6304, "text": "XML parsing in Python" } ]