Datasets:

Modalities:
Text
Formats:
json
Languages:
English
Tags:
code
Libraries:
Datasets
pandas
License:
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
title
stringlengths
3
221
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." } ]
What is the difference between UNIX TIMESTAMPS and MySQL TIMESTAMPS?
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." } ]
How do I display the current date and time in an Android application?
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" } ]
Kotlin Get Started
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)" } ]
What MySQL COALESCE() function returns if all the arguments provided to it are NULL?
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" } ]
java.time.LocalDate.atTime() Method Example
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" } ]
Vim - Using Vim As Ide
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" } ]
C# | Char.ToString() Method - GeeksforGeeks
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)" } ]
NLP: Contextualized word embeddings from BERT | by Andreas Pogiatzis | Towards Data Science
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" } ]
C++ File Writer-Reader application using Windows Threads - 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 print Superscript and Subscript in Python? - GeeksforGeeks
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..." } ]
How to display PDF file in web page from Database in PHP
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" } ]
DB2 - Backup and Recovery
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" } ]
Handle missing data with R: 10 daily used idioms | by Pavlo Horbonos | Towards Data Science
Tryit: HTML image map - execute a function
[]
Tryit Editor v3.7
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." } ]
Object Detection Using YOLOv3 on Colab with questions for interview preparation | by Manish Sharma | Towards Data Science
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" } ]
Map in C++ Standard Template Library (STL) - GeeksforGeeks
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" } ]
Folium: Create Interactive Leaflet Maps | by Himanshu Sharma | Towards Data Science
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" } ]
CSS Layout - The z-index Property
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." } ]
8051 Program to Subtract two 8 Bit numbers
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" } ]
LISP - Lambda Functions
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!" } ]
Check if a File exists 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" } ]
override identifier in C++

The online tutorials retrieval source for code-rag-bench, consisting tutorials pages collected from GeeksforGeeks, W3Schools, tutorialspoint, and Towards Data Science.

Downloads last month
55

Collection including code-rag-bench/online-tutorials