title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Populate Inorder Successor for all nodes | Practice | GeeksforGeeks
|
Given a Binary Tree, write a function to populate next pointer for all nodes. The next pointer for every node should be set to point to inorder successor.
Example 1:
Input:
10
/ \
8 12
/
3
Output: 3->8 8->10 10->12 12->-1
Explanation: The inorder of the above tree is :
3 8 10 12. So the next pointer of node 3 is
pointing to 8 , next pointer of 8 is pointing
to 10 and so on.And next pointer of 12 is
pointing to -1 as there is no inorder successor
of 12.
Example 2:
Input:
1
/ \
2 3
Output: 2->1 1->3 3->-1
Your Task:
You do not need to read input or print anything. Your task is to complete the function populateNext() that takes the root node of the binary tree as input parameter.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1<=n<=10^5
1<=data of the node<=10^5
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 393,
"s": 238,
"text": "Given a Binary Tree, write a function to populate next pointer for all nodes. The next pointer for every node should be set to point to inorder successor."
},
{
"code": null,
"e": 404,
"s": 393,
"text": "Example 1:"
},
{
"code": null,
"e": 738,
"s": 404,
"text": "Input:\n 10\n / \\\n 8 12\n /\n 3\n \n\nOutput: 3->8 8->10 10->12 12->-1\nExplanation: The inorder of the above tree is :\n3 8 10 12. So the next pointer of node 3 is \npointing to 8 , next pointer of 8 is pointing\nto 10 and so on.And next pointer of 12 is\npointing to -1 as there is no inorder successor \nof 12."
},
{
"code": null,
"e": 749,
"s": 738,
"text": "Example 2:"
},
{
"code": null,
"e": 819,
"s": 749,
"text": "Input:\n 1\n / \\\n 2 3\nOutput: 2->1 1->3 3->-1 "
},
{
"code": null,
"e": 996,
"s": 819,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function populateNext() that takes the root node of the binary tree as input parameter."
},
{
"code": null,
"e": 1108,
"s": 996,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1<=n<=10^5\n1<=data of the node<=10^5"
},
{
"code": null,
"e": 1254,
"s": 1108,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 1290,
"s": 1254,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1300,
"s": 1290,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1310,
"s": 1300,
"text": "\nContest\n"
},
{
"code": null,
"e": 1373,
"s": 1310,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1521,
"s": 1373,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 1729,
"s": 1521,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 1835,
"s": 1729,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to Export a certificate from a certificate store using PowerShell?
|
To export or download a certificate from the certificate store using PowerShell, we need to use the command Export-Certificate.
First, you need to get the certificate details from the store. If you know the thumbprint, you can directly get the certificate details using the thumbprint and then use that details to export the certificate.
$cert = (Get-ChildItem Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F)
Export-Certificate -Cert $cert -Type CERT -FilePath C:\Temp\Mycert.cer
In the above example, we are exporting the certificate from the LocalMachine -> Personal Store. You can choose a different path. Here, the certificate would be exported to the C:\temp\MyCert.cer.
You can use the different types like P7B, SST to export the certificate. Alternatively, you can use the below command.
Get-ChildItem Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F `
| Export-Certificate -Type cer -FilePath C:\Temp\newcert.cer -Force
If you don't know the certificate thumbprint then you can use any of the certificate's unique properties like Subject, FriendlyName, etc to retrieve the details. For example,
Get-ChildItem Cert:\LocalMachine\My\ `
| where{$_.FriendlyName -eq "mysitecert"} `
| Export-Certificate -Type cer -FilePath C:\Temp\newcert.cer -Force
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "To export or download a certificate from the certificate store using PowerShell, we need to use the command Export-Certificate."
},
{
"code": null,
"e": 1400,
"s": 1190,
"text": "First, you need to get the certificate details from the store. If you know the thumbprint, you can directly get the certificate details using the thumbprint and then use that details to export the certificate."
},
{
"code": null,
"e": 1552,
"s": 1400,
"text": "$cert = (Get-ChildItem Cert:\\LocalMachine\\My\\43E6035D120EBE9ECE8100E8F38B85A9F)\nExport-Certificate -Cert $cert -Type CERT -FilePath C:\\Temp\\Mycert.cer"
},
{
"code": null,
"e": 1748,
"s": 1552,
"text": "In the above example, we are exporting the certificate from the LocalMachine -> Personal Store. You can choose a different path. Here, the certificate would be exported to the C:\\temp\\MyCert.cer."
},
{
"code": null,
"e": 1868,
"s": 1748,
"text": " You can use the different types like P7B, SST to export the certificate. Alternatively, you can use the below command."
},
{
"code": null,
"e": 2018,
"s": 1868,
"text": "Get-ChildItem Cert:\\LocalMachine\\My\\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F `\n | Export-Certificate -Type cer -FilePath C:\\Temp\\newcert.cer -Force"
},
{
"code": null,
"e": 2194,
"s": 2018,
"text": "If you don't know the certificate thumbprint then you can use any of the certificate's unique properties like Subject, FriendlyName, etc to retrieve the details. For example,"
},
{
"code": null,
"e": 2353,
"s": 2194,
"text": "Get-ChildItem Cert:\\LocalMachine\\My\\ `\n | where{$_.FriendlyName -eq \"mysitecert\"} `\n | Export-Certificate -Type cer -FilePath C:\\Temp\\newcert.cer -Force"
}
] |
Tryit Editor v3.7
|
Tryit: Using the animation-iteration-count property
|
[] |
Tryit Editor v3.7
|
HTML Form elements
Tryit: HTML selected option
|
[
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML Form elements"
}
] |
Format Year in yy format in Java
|
To format year in yy format is like displaying year as 01, 02, 03, 04, etc. For example, 18 for 2018.
Use the yy format like this.
SimpleDateFormat("yy");
Let us see an example −
// year in yy format
SimpleDateFormat simpleformat = new SimpleDateFormat("yy");
String strYear = simpleformat.format(new Date());
System.out.println("Current Year = "+strYear);
Above, we have used the SimpleDateFormat class, therefore the following package is imported −
import java.text.SimpleDateFormat;
The following is an example −
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss");
System.out.println("Date and time = "+simpleformat.format(cal.getTime()));
// displaying date
simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
String str = simpleformat.format(new Date());
System.out.println("Current Date = "+str);
// year in yy format
simpleformat = new SimpleDateFormat("yy");
String strYear = simpleformat.format(new Date());
System.out.println("Current Year = "+strYear);
}
}
Date and time = Mon, 26 Nov 2018 11:05:15
Current Date = 26/November/2018
Current Year = 18
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To format year in yy format is like displaying year as 01, 02, 03, 04, etc. For example, 18 for 2018."
},
{
"code": null,
"e": 1193,
"s": 1164,
"text": "Use the yy format like this."
},
{
"code": null,
"e": 1217,
"s": 1193,
"text": "SimpleDateFormat(\"yy\");"
},
{
"code": null,
"e": 1241,
"s": 1217,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1419,
"s": 1241,
"text": "// year in yy format\nSimpleDateFormat simpleformat = new SimpleDateFormat(\"yy\");\nString strYear = simpleformat.format(new Date());\nSystem.out.println(\"Current Year = \"+strYear);"
},
{
"code": null,
"e": 1513,
"s": 1419,
"text": "Above, we have used the SimpleDateFormat class, therefore the following package is imported −"
},
{
"code": null,
"e": 1548,
"s": 1513,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1578,
"s": 1548,
"text": "The following is an example −"
},
{
"code": null,
"e": 1589,
"s": 1578,
"text": " Live Demo"
},
{
"code": null,
"e": 2412,
"s": 1589,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss\");\n System.out.println(\"Date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date\n simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String str = simpleformat.format(new Date());\n System.out.println(\"Current Date = \"+str);\n // year in yy format\n simpleformat = new SimpleDateFormat(\"yy\");\n String strYear = simpleformat.format(new Date());\n System.out.println(\"Current Year = \"+strYear);\n }\n}"
},
{
"code": null,
"e": 2504,
"s": 2412,
"text": "Date and time = Mon, 26 Nov 2018 11:05:15\nCurrent Date = 26/November/2018\nCurrent Year = 18"
}
] |
How to convert ISO 8601 String to Date/Time object in Android using Kotlin?
|
This example demonstrates how to convert an ISO 8601 String to Date/Time object in Android using Kotlin.
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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/holo_red_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val dtStart = "2020-07-05T09:27:37Z"
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
val date: Date = format.parse(dtStart)
textView.text = "ISO 1801 date/time: $date"
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "This example demonstrates how to convert an ISO 8601 String to Date/Time object in Android using Kotlin."
},
{
"code": null,
"e": 1295,
"s": 1167,
"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": 1360,
"s": 1295,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2304,
"s": 1360,
"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:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n<TextView\n android:id=\"@+id/textView\"\n android:textAlignment=\"center\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/holo_red_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2359,
"s": 2304,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3016,
"s": 2359,
"text": "import android.os.Bundle\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport java.text.SimpleDateFormat\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n val dtStart = \"2020-07-05T09:27:37Z\"\n val format = SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\")\n val date: Date = format.parse(dtStart)\n textView.text = \"ISO 1801 date/time: $date\"\n }\n}"
},
{
"code": null,
"e": 3071,
"s": 3016,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3742,
"s": 3071,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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": 4090,
"s": 3742,
"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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 4131,
"s": 4090,
"text": "Click here to download the project code."
}
] |
How to create a Dictionary in Python - GeeksforGeeks
|
31 Dec, 2019
Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1) and have been heavily optimized for memory overhead and lookup speed efficiency.
Example 1: The first element of each of the sublists is the key and the second element is the value. We want to store the key-value pair dynamically.
# Python program to demonstrate# dynamic dictionary creation # Initialize an empty dictionaryD = {} L = [['a', 1], ['b', 2], ['a', 3], ['c', 4]] # Loop to add key-value pair# to dictionaryfor i in range(len(L)): # If the key is already # present in dictionary # then append the value # to the list of values if L[i][0] in D: D[L[i][0]].append(L[i][1]) # If the key is not present # in the dictionary then add # the key-value pair else: D[L[i][0]]= [] D[L[i][0]].append(L[i][1]) print(D)
Output:
{'a': [1, 3], 'b': [2], 'c': [4]}
Example 2:
# Python program to demonstrate# dynamic dictionary creation # Key to be addedkey_ref = 'More Nested Things'my_dict = { 'Nested Things': [{'name', 'thing one'}, {'name', 'thing two'}]} # Value to be addedmy_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}] # try-except to take care of errors# while adding key-value pairtry: my_dict[key_ref].append(my_list_of_things) except KeyError: my_dict = {**my_dict, **{key_ref: my_list_of_things}} print(my_dict)
Output:
{
'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}],
'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}]
}
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 23845,
"s": 23817,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 24214,
"s": 23845,
"text": "Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1) and have been heavily optimized for memory overhead and lookup speed efficiency."
},
{
"code": null,
"e": 24364,
"s": 24214,
"text": "Example 1: The first element of each of the sublists is the key and the second element is the value. We want to store the key-value pair dynamically."
},
{
"code": "# Python program to demonstrate# dynamic dictionary creation # Initialize an empty dictionaryD = {} L = [['a', 1], ['b', 2], ['a', 3], ['c', 4]] # Loop to add key-value pair# to dictionaryfor i in range(len(L)): # If the key is already # present in dictionary # then append the value # to the list of values if L[i][0] in D: D[L[i][0]].append(L[i][1]) # If the key is not present # in the dictionary then add # the key-value pair else: D[L[i][0]]= [] D[L[i][0]].append(L[i][1]) print(D) ",
"e": 24923,
"s": 24364,
"text": null
},
{
"code": null,
"e": 24931,
"s": 24923,
"text": "Output:"
},
{
"code": null,
"e": 24966,
"s": 24931,
"text": "{'a': [1, 3], 'b': [2], 'c': [4]}\n"
},
{
"code": null,
"e": 24977,
"s": 24966,
"text": "Example 2:"
},
{
"code": "# Python program to demonstrate# dynamic dictionary creation # Key to be addedkey_ref = 'More Nested Things'my_dict = { 'Nested Things': [{'name', 'thing one'}, {'name', 'thing two'}]} # Value to be addedmy_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}] # try-except to take care of errors# while adding key-value pairtry: my_dict[key_ref].append(my_list_of_things) except KeyError: my_dict = {**my_dict, **{key_ref: my_list_of_things}} print(my_dict)",
"e": 25473,
"s": 24977,
"text": null
},
{
"code": null,
"e": 25481,
"s": 25473,
"text": "Output:"
},
{
"code": null,
"e": 25626,
"s": 25481,
"text": "{\n 'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}], \n 'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}]\n}\n"
},
{
"code": null,
"e": 25653,
"s": 25626,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 25665,
"s": 25653,
"text": "python-dict"
},
{
"code": null,
"e": 25672,
"s": 25665,
"text": "Python"
},
{
"code": null,
"e": 25684,
"s": 25672,
"text": "python-dict"
},
{
"code": null,
"e": 25782,
"s": 25684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25791,
"s": 25782,
"text": "Comments"
},
{
"code": null,
"e": 25804,
"s": 25791,
"text": "Old Comments"
},
{
"code": null,
"e": 25839,
"s": 25804,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25861,
"s": 25839,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25893,
"s": 25861,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25923,
"s": 25893,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25965,
"s": 25923,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25991,
"s": 25965,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26034,
"s": 25991,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26078,
"s": 26034,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26103,
"s": 26078,
"text": "sum() function in Python"
}
] |
Add hours to current time using Calendar.add() method in Java
|
Import the following package for Calendar class in Java.
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time.
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the hours using the calendar.add() method and Calendar.HOUR_OF_DAY constant.
calendar.add(Calendar.HOUR_OF_DAY, +5);
Live Demo
import java.util.Calendar;
public class Demo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date = " + calendar.getTime());
// Incrementing hours by 5
calendar.add(Calendar.HOUR_OF_DAY, +5);
System.out.println("Updated Date = " + calendar.getTime());
}
}
Current Date = Thu Nov 22 16:13:04 UTC 2018
Updated Date = Thu Nov 22 21:13:04 UTC 2018
|
[
{
"code": null,
"e": 1119,
"s": 1062,
"text": "Import the following package for Calendar class in Java."
},
{
"code": null,
"e": 1146,
"s": 1119,
"text": "import java.util.Calendar;"
},
{
"code": null,
"e": 1219,
"s": 1146,
"text": "Firstly, create a Calendar object and display the current date and time."
},
{
"code": null,
"e": 1332,
"s": 1219,
"text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(\"Current Date and Time = \" + calendar.getTime());"
},
{
"code": null,
"e": 1431,
"s": 1332,
"text": "Now, let us increment the hours using the calendar.add() method and Calendar.HOUR_OF_DAY constant."
},
{
"code": null,
"e": 1471,
"s": 1431,
"text": "calendar.add(Calendar.HOUR_OF_DAY, +5);"
},
{
"code": null,
"e": 1482,
"s": 1471,
"text": " Live Demo"
},
{
"code": null,
"e": 1841,
"s": 1482,
"text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(\"Current Date = \" + calendar.getTime());\n // Incrementing hours by 5\n calendar.add(Calendar.HOUR_OF_DAY, +5);\n System.out.println(\"Updated Date = \" + calendar.getTime());\n }\n}"
},
{
"code": null,
"e": 1929,
"s": 1841,
"text": "Current Date = Thu Nov 22 16:13:04 UTC 2018\nUpdated Date = Thu Nov 22 21:13:04 UTC 2018"
}
] |
Python Sequence Types
|
Some basic sequence type classes in python are, list, tuple, range. There are some additional sequence type objects, these are binary data and text string.
Some common operations for the sequence type object can work on both mutable and immutable sequences. Some of the operations are as follows −
x in seq
True, when x is found in the sequence seq, otherwise False
x not in seq
False, when x is found in the sequence seq, otherwise True
x + y
Concatenate two sequences x and y
x * n or n * x
Add sequence x with itself n times
seq[i]
ith item of the sequence.
seq[i:j]
Slice sequence from index i to j
seq[i:j:k]
Slice sequence from index i to j with step k
len(seq)
Length or number of elements in the sequence
min(seq)
Minimum element in the sequence
max(seq)
Maximum element in the sequence
seq.index(x[, i[, j]])
Index of the first occurrence of x (in the index range i and j)
seq.count(x)
Count total number of elements in the sequence
seq.append(x)
Add x at the end of the sequence
seq.clear()
Clear the contents of the sequence
seq.insert(i, x)
Insert x at the position i
seq.pop([i])
Return the item at position i, and also remove it from sequence. Default is last element.
seq.remove(x)
Remove first occurrence of item x
seq.reverse()
Reverse the list
Live Demo
myList1 = [10, 20, 30, 40, 50]
myList2 = [56, 42, 79, 42, 85, 96, 23]
if 30 in myList1:
print('30 is present')
if 120 not in myList1:
print('120 is not present')
print(myList1 + myList2) #Concatinate lists
print(myList1 * 3) #Add myList1 three times with itself
print(max(myList2))
print(myList2.count(42)) #42 has two times in the list
print(myList2[2:7])
print(myList2[2:7:2])
myList1.append(60)
print(myList1)
myList2.insert(5, 17)
print(myList2)
myList2.pop(3)
print(myList2)
myList1.reverse()
print(myList1)
myList1.clear()
print(myList1)
30 is present
120 is not present
[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
96
2
[79, 42, 85, 96, 23]
[79, 85, 23]
[10, 20, 30, 40, 50, 60]
[56, 42, 79, 42, 85, 17, 96, 23]
[56, 42, 79, 85, 17, 96, 23]
[60, 50, 40, 30, 20, 10]
[]
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "Some basic sequence type classes in python are, list, tuple, range. There are some additional sequence type objects, these are binary data and text string."
},
{
"code": null,
"e": 1360,
"s": 1218,
"text": "Some common operations for the sequence type object can work on both mutable and immutable sequences. Some of the operations are as follows −"
},
{
"code": null,
"e": 1369,
"s": 1360,
"text": "x in seq"
},
{
"code": null,
"e": 1428,
"s": 1369,
"text": "True, when x is found in the sequence seq, otherwise False"
},
{
"code": null,
"e": 1441,
"s": 1428,
"text": "x not in seq"
},
{
"code": null,
"e": 1500,
"s": 1441,
"text": "False, when x is found in the sequence seq, otherwise True"
},
{
"code": null,
"e": 1506,
"s": 1500,
"text": "x + y"
},
{
"code": null,
"e": 1541,
"s": 1506,
"text": "Concatenate two sequences x and y "
},
{
"code": null,
"e": 1556,
"s": 1541,
"text": "x * n or n * x"
},
{
"code": null,
"e": 1591,
"s": 1556,
"text": "Add sequence x with itself n times"
},
{
"code": null,
"e": 1598,
"s": 1591,
"text": "seq[i]"
},
{
"code": null,
"e": 1624,
"s": 1598,
"text": "ith item of the sequence."
},
{
"code": null,
"e": 1633,
"s": 1624,
"text": "seq[i:j]"
},
{
"code": null,
"e": 1666,
"s": 1633,
"text": "Slice sequence from index i to j"
},
{
"code": null,
"e": 1677,
"s": 1666,
"text": "seq[i:j:k]"
},
{
"code": null,
"e": 1722,
"s": 1677,
"text": "Slice sequence from index i to j with step k"
},
{
"code": null,
"e": 1731,
"s": 1722,
"text": "len(seq)"
},
{
"code": null,
"e": 1777,
"s": 1731,
"text": "Length or number of elements in the sequence "
},
{
"code": null,
"e": 1786,
"s": 1777,
"text": "min(seq)"
},
{
"code": null,
"e": 1818,
"s": 1786,
"text": "Minimum element in the sequence"
},
{
"code": null,
"e": 1827,
"s": 1818,
"text": "max(seq)"
},
{
"code": null,
"e": 1859,
"s": 1827,
"text": "Maximum element in the sequence"
},
{
"code": null,
"e": 1882,
"s": 1859,
"text": "seq.index(x[, i[, j]])"
},
{
"code": null,
"e": 1946,
"s": 1882,
"text": "Index of the first occurrence of x (in the index range i and j)"
},
{
"code": null,
"e": 1959,
"s": 1946,
"text": "seq.count(x)"
},
{
"code": null,
"e": 2006,
"s": 1959,
"text": "Count total number of elements in the sequence"
},
{
"code": null,
"e": 2020,
"s": 2006,
"text": "seq.append(x)"
},
{
"code": null,
"e": 2053,
"s": 2020,
"text": "Add x at the end of the sequence"
},
{
"code": null,
"e": 2065,
"s": 2053,
"text": "seq.clear()"
},
{
"code": null,
"e": 2100,
"s": 2065,
"text": "Clear the contents of the sequence"
},
{
"code": null,
"e": 2117,
"s": 2100,
"text": "seq.insert(i, x)"
},
{
"code": null,
"e": 2144,
"s": 2117,
"text": "Insert x at the position i"
},
{
"code": null,
"e": 2157,
"s": 2144,
"text": "seq.pop([i])"
},
{
"code": null,
"e": 2247,
"s": 2157,
"text": "Return the item at position i, and also remove it from sequence. Default is last element."
},
{
"code": null,
"e": 2261,
"s": 2247,
"text": "seq.remove(x)"
},
{
"code": null,
"e": 2295,
"s": 2261,
"text": "Remove first occurrence of item x"
},
{
"code": null,
"e": 2309,
"s": 2295,
"text": "seq.reverse()"
},
{
"code": null,
"e": 2326,
"s": 2309,
"text": "Reverse the list"
},
{
"code": null,
"e": 2337,
"s": 2326,
"text": " Live Demo"
},
{
"code": null,
"e": 2903,
"s": 2337,
"text": "myList1 = [10, 20, 30, 40, 50]\nmyList2 = [56, 42, 79, 42, 85, 96, 23]\n\nif 30 in myList1:\n print('30 is present')\n \nif 120 not in myList1:\n print('120 is not present')\n \nprint(myList1 + myList2) #Concatinate lists\nprint(myList1 * 3) #Add myList1 three times with itself\nprint(max(myList2))\nprint(myList2.count(42)) #42 has two times in the list\n\nprint(myList2[2:7])\nprint(myList2[2:7:2])\n\nmyList1.append(60)\nprint(myList1)\n\nmyList2.insert(5, 17)\nprint(myList2)\n\nmyList2.pop(3)\nprint(myList2)\nmyList1.reverse()\nprint(myList1)\n\nmyList1.clear()\nprint(myList1)"
},
{
"code": null,
"e": 3201,
"s": 2903,
"text": "30 is present\n120 is not present\n[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]\n[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]\n96\n2\n[79, 42, 85, 96, 23]\n[79, 85, 23]\n[10, 20, 30, 40, 50, 60]\n[56, 42, 79, 42, 85, 17, 96, 23]\n[56, 42, 79, 85, 17, 96, 23]\n[60, 50, 40, 30, 20, 10]\n[]\n"
}
] |
How to get root directory information in android?
|
This example demonstrate about How to get root directory information in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show root directory.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.KeyguardManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
textView.setText(Environment.getRootDirectory().getAbsolutePath().toString());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
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": 1143,
"s": 1062,
"text": "This example demonstrate about How to get root directory information in android."
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1897,
"s": 1337,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1964,
"s": 1897,
"text": "In the above code, we have taken text view to show root directory."
},
{
"code": null,
"e": 2021,
"s": 1964,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2988,
"s": 2021,
"text": "package com.example.myapplication;\nimport android.app.KeyguardManager;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.Network;\nimport android.net.NetworkInfo;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n textView.setText(Environment.getRootDirectory().getAbsolutePath().toString());\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3335,
"s": 2988,
"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": 3375,
"s": 3335,
"text": "Click here to download the project code"
}
] |
numpy.array_str() in Python - GeeksforGeeks
|
29 Nov, 2018
numpy.array_str()function is used to represent the data of an array as a string.
The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type.
Syntax : numpy.array_str(arr, max_line_width=None, precision=None, suppress_small=None)
Parameters :arr : [array_like] Input array.max_line_width : [int, optional] Inserts newlines if text is longer than max_line_width. The default is, indirectly, 75.precision : [int, optional] Floating point precision. Default is the current printing precision(generally 8).suppress_small : [bool, optional] It represent very small numbers as zero, default is False. Very small number is defined by precision, if the precision is 8 then numbers smaller than 5e-9 are represented as zero.
Return : [str] The string representation of an array.
Code #1 : Working
# Python program explaining# array_str() function import numpy as geekarr = geek.array([4, -8, 7 ]) print ("Input array : ", arr)print(type(arr)) out_arr = geek.array_str(arr)print ("The string representation of input array : ", out_arr) print(type(out_arr))
Output :
Input array : [ 4 -8 7]
class 'numpy.ndarray'
The string representation of input array : array([ 4, -8, 7])
class 'str'
Code #2 : Working
# Python program explaining# array_str() function import numpy as geekin_arr = geek.array([5e-8, 4e-7, 8, -4]) print ("Input array : ", in_arr)print(type(in_arr)) out_arr = geek.array_str(in_arr, precision = 6, suppress_small = True)print ("The string representation of input array : ", out_arr) print(type(out_arr))
Output :
Input array : [ 5.00000000e-08 4.00000000e-07 8.00000000e+00 -4.00000000e+00]
class 'numpy.ndarray'
The string representation of input array : array([ 0., 0., 8., -4.])
class 'str'
Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
|
[
{
"code": null,
"e": 24440,
"s": 24412,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 24521,
"s": 24440,
"text": "numpy.array_str()function is used to represent the data of an array as a string."
},
{
"code": null,
"e": 24717,
"s": 24521,
"text": "The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type."
},
{
"code": null,
"e": 24805,
"s": 24717,
"text": "Syntax : numpy.array_str(arr, max_line_width=None, precision=None, suppress_small=None)"
},
{
"code": null,
"e": 25291,
"s": 24805,
"text": "Parameters :arr : [array_like] Input array.max_line_width : [int, optional] Inserts newlines if text is longer than max_line_width. The default is, indirectly, 75.precision : [int, optional] Floating point precision. Default is the current printing precision(generally 8).suppress_small : [bool, optional] It represent very small numbers as zero, default is False. Very small number is defined by precision, if the precision is 8 then numbers smaller than 5e-9 are represented as zero."
},
{
"code": null,
"e": 25345,
"s": 25291,
"text": "Return : [str] The string representation of an array."
},
{
"code": null,
"e": 25363,
"s": 25345,
"text": "Code #1 : Working"
},
{
"code": "# Python program explaining# array_str() function import numpy as geekarr = geek.array([4, -8, 7 ]) print (\"Input array : \", arr)print(type(arr)) out_arr = geek.array_str(arr)print (\"The string representation of input array : \", out_arr) print(type(out_arr))",
"e": 25628,
"s": 25363,
"text": null
},
{
"code": null,
"e": 25637,
"s": 25628,
"text": "Output :"
},
{
"code": null,
"e": 25763,
"s": 25637,
"text": "Input array : [ 4 -8 7]\nclass 'numpy.ndarray'\nThe string representation of input array : array([ 4, -8, 7])\nclass 'str'\n"
},
{
"code": null,
"e": 25782,
"s": 25763,
"text": " Code #2 : Working"
},
{
"code": "# Python program explaining# array_str() function import numpy as geekin_arr = geek.array([5e-8, 4e-7, 8, -4]) print (\"Input array : \", in_arr)print(type(in_arr)) out_arr = geek.array_str(in_arr, precision = 6, suppress_small = True)print (\"The string representation of input array : \", out_arr) print(type(out_arr))",
"e": 26105,
"s": 25782,
"text": null
},
{
"code": null,
"e": 26114,
"s": 26105,
"text": "Output :"
},
{
"code": null,
"e": 26307,
"s": 26114,
"text": "Input array : [ 5.00000000e-08 4.00000000e-07 8.00000000e+00 -4.00000000e+00]\nclass 'numpy.ndarray'\nThe string representation of input array : array([ 0., 0., 8., -4.])\nclass 'str'\n"
},
{
"code": null,
"e": 26325,
"s": 26309,
"text": "Python numpy-io"
},
{
"code": null,
"e": 26338,
"s": 26325,
"text": "Python-numpy"
},
{
"code": null,
"e": 26345,
"s": 26338,
"text": "Python"
},
{
"code": null,
"e": 26443,
"s": 26345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26461,
"s": 26443,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26483,
"s": 26461,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26515,
"s": 26483,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26557,
"s": 26515,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26583,
"s": 26557,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26620,
"s": 26583,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26649,
"s": 26620,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26691,
"s": 26649,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26747,
"s": 26691,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Change figure window title in pylab(Python)
|
Using pylab.gcf(), we can create a fig variable and can set the fig.canvas.set_window_title('Setting up window title.') window title.
Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`.
Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`.
Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend).
Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend).
Please use Ipython and follow the steps given below -
In [1]: from matplotlib import pylab
In [2]: fig = pylab.gcf()
In [3]: fig.canvas.set_window_title('Setting up window title.')
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Using pylab.gcf(), we can create a fig variable and can set the fig.canvas.set_window_title('Setting up window title.') window title."
},
{
"code": null,
"e": 1317,
"s": 1196,
"text": "Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`."
},
{
"code": null,
"e": 1438,
"s": 1317,
"text": "Using gcf() method, get the current figure. If no current figure exists, a new one is created using `~.pyplot.figure()`."
},
{
"code": null,
"e": 1601,
"s": 1438,
"text": "Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend)."
},
{
"code": null,
"e": 1764,
"s": 1601,
"text": "Set the title text of the window containing the figure, using set_window_title() method.. Note that this has no effect if there is no window (e.g., a PS backend)."
},
{
"code": null,
"e": 1818,
"s": 1764,
"text": "Please use Ipython and follow the steps given below -"
},
{
"code": null,
"e": 1947,
"s": 1818,
"text": "In [1]: from matplotlib import pylab\n\nIn [2]: fig = pylab.gcf()\n\nIn [3]: fig.canvas.set_window_title('Setting up window title.')"
}
] |
Matplotlib animation not working in IPython Notebook?
|
To animate a plot in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a random data of shape 10X10 dimension.
Create a random data of shape 10X10 dimension.
Create a figure and a set of subplots, using subplots() method.
Create a figure and a set of subplots, using subplots() method.
Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class.
Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class.
To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class.
To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()
def animate(i):
ax.clear()
ax.contourf(data[:, :, i])
ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)
plt.show()
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To animate a plot in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1205,
"s": 1129,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1281,
"s": 1205,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1328,
"s": 1281,
"text": "Create a random data of shape 10X10 dimension."
},
{
"code": null,
"e": 1375,
"s": 1328,
"text": "Create a random data of shape 10X10 dimension."
},
{
"code": null,
"e": 1439,
"s": 1375,
"text": "Create a figure and a set of subplots, using subplots() method."
},
{
"code": null,
"e": 1503,
"s": 1439,
"text": "Create a figure and a set of subplots, using subplots() method."
},
{
"code": null,
"e": 1592,
"s": 1503,
"text": "Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class."
},
{
"code": null,
"e": 1681,
"s": 1592,
"text": "Makes an animation by repeatedly calling a function *func*, using FuncAnimation() class."
},
{
"code": null,
"e": 1798,
"s": 1681,
"text": "To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class."
},
{
"code": null,
"e": 1915,
"s": 1798,
"text": "To update the contour value in a function, we can define a method animate that can be used in FuncAnimation() class."
},
{
"code": null,
"e": 1957,
"s": 1915,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1999,
"s": 1957,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2396,
"s": 1999,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.randn(800).reshape(10, 10, 8)\nfig, ax = plt.subplots()\n\ndef animate(i):\n ax.clear()\n ax.contourf(data[:, :, i])\n\nani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)\nplt.show()"
}
] |
MySQL GROUP BY date when using datetime?
|
To GROUP BY date while using datetime, the following is the syntax −
select *from yourTableName GROUP BY date(yourColumnName);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table groupByDateDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(20),
-> UserPostDatetime datetime
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Larry','2018-01-02 13:45:40');
Query OK, 1 row affected (0.18 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Mike','2018-01-02 13:45:40');
Query OK, 1 row affected (0.14 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Sam','2019-01-28 12:30:34');
Query OK, 1 row affected (0.33 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('David','2019-02-10 11:35:54');
Query OK, 1 row affected (0.18 sec)
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Maxwell','2019-02-10 11:35:54');
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from groupByDateDemo;
Here is the output −
+----+----------+---------------------+
| Id | UserName | UserPostDatetime |
+----+----------+---------------------+
| 1 | Larry | 2018-01-02 13:45:40 |
| 2 | Mike | 2018-01-02 13:45:40 |
| 3 | Sam | 2019-01-28 12:30:34 |
| 4 | David | 2019-02-10 11:35:54 |
| 5 | Maxwell | 2019-02-10 11:35:54 |
+----+----------+---------------------+
5 rows in set (0.00 sec)
Let us now GROUP BY date while using datetime. The query is as follows −
mysql> select *from groupByDateDemo GROUP BY date(UserPostDatetime);
The following is the output −
+----+----------+---------------------+
| Id | UserName | UserPostDatetime |
+----+----------+---------------------+
| 1 | Larry | 2018-01-02 13:45:40 |
| 3 | Sam | 2019-01-28 12:30:34 |
| 4 | David | 2019-02-10 11:35:54 |
+----+----------+---------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To GROUP BY date while using datetime, the following is the syntax −"
},
{
"code": null,
"e": 1189,
"s": 1131,
"text": "select *from yourTableName GROUP BY date(yourColumnName);"
},
{
"code": null,
"e": 1288,
"s": 1189,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1488,
"s": 1288,
"text": "mysql> create table groupByDateDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserName varchar(20),\n -> UserPostDatetime datetime\n -> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1569,
"s": 1488,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2253,
"s": 1569,
"text": "mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Larry','2018-01-02 13:45:40');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Mike','2018-01-02 13:45:40');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Sam','2019-01-28 12:30:34');\nQuery OK, 1 row affected (0.33 sec)\nmysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('David','2019-02-10 11:35:54');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Maxwell','2019-02-10 11:35:54');\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 2338,
"s": 2253,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2375,
"s": 2338,
"text": "mysql> select *from groupByDateDemo;"
},
{
"code": null,
"e": 2396,
"s": 2375,
"text": "Here is the output −"
},
{
"code": null,
"e": 2781,
"s": 2396,
"text": "+----+----------+---------------------+\n| Id | UserName | UserPostDatetime |\n+----+----------+---------------------+\n| 1 | Larry | 2018-01-02 13:45:40 |\n| 2 | Mike | 2018-01-02 13:45:40 |\n| 3 | Sam | 2019-01-28 12:30:34 |\n| 4 | David | 2019-02-10 11:35:54 |\n| 5 | Maxwell | 2019-02-10 11:35:54 |\n+----+----------+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2854,
"s": 2781,
"text": "Let us now GROUP BY date while using datetime. The query is as follows −"
},
{
"code": null,
"e": 2923,
"s": 2854,
"text": "mysql> select *from groupByDateDemo GROUP BY date(UserPostDatetime);"
},
{
"code": null,
"e": 2953,
"s": 2923,
"text": "The following is the output −"
},
{
"code": null,
"e": 3258,
"s": 2953,
"text": "+----+----------+---------------------+\n| Id | UserName | UserPostDatetime |\n+----+----------+---------------------+\n| 1 | Larry | 2018-01-02 13:45:40 |\n| 3 | Sam | 2019-01-28 12:30:34 |\n| 4 | David | 2019-02-10 11:35:54 |\n+----+----------+---------------------+\n3 rows in set (0.00 sec)"
}
] |
Different Ways to Check Which Shell You are Using on Linux - GeeksforGeeks
|
28 Mar, 2021
A shell is a program through which users can interact with the Operating System. Linux provides commonly 4 types of Shell The Bourne Shell ( /bin/sh or /sbin/sh ), The C shell ( /bin/csh ), The Korn Shell ( /bin/ksh ), The GNU Bourne-Again Shell ( /bin/bash ). This article is about to Check that which shell we are using. Here, we discuss five ways by which we can check which shell we are using.
1) Using echo command: Basically, the echo command is used to print the input string, but it is also used to print the name of the shell which we are using with the help of the command.
$ echo "My Shell name is: $SHELL"
2) Using ps command: ps command stands for “Process Status”. It is used to check the currently running status and their PIDs. If the ps command is run generally in the shell then it simply tells the name of the shell.
$ ps
2. Shell name using ps
The first column tells the PID and the last column tells the type of shell i.e. bash.
3) By viewing /etc/passwd file: This tells the feature of the user just like it’s name, shell, and ID. This command is used with the grep command.
$ grep "^$USER" /etc/passwd
4) Using lsof command: lsof stands for LIST OF OPEN FILES. This command used when we want the list of open files in our system. By using the specific flag it gives a pointer to the shell and tells us about that which shell are we using and that specific flag is -p $$. The command looks like.
$ lsof -p $$
As you can see clearly in the 3rd line it tells us about the shell we are using.
5) Using readlink /proc/$$/exe: The readlink is used to print the file name. So with the help of this, we print the location of the current shell using the /proc/$$/exe. Command can be written as
$ readlink /proc/$$/exe
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
mv command in Linux with examples
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
|
[
{
"code": null,
"e": 24430,
"s": 24402,
"text": "\n28 Mar, 2021"
},
{
"code": null,
"e": 24828,
"s": 24430,
"text": "A shell is a program through which users can interact with the Operating System. Linux provides commonly 4 types of Shell The Bourne Shell ( /bin/sh or /sbin/sh ), The C shell ( /bin/csh ), The Korn Shell ( /bin/ksh ), The GNU Bourne-Again Shell ( /bin/bash ). This article is about to Check that which shell we are using. Here, we discuss five ways by which we can check which shell we are using."
},
{
"code": null,
"e": 25014,
"s": 24828,
"text": "1) Using echo command: Basically, the echo command is used to print the input string, but it is also used to print the name of the shell which we are using with the help of the command."
},
{
"code": null,
"e": 25048,
"s": 25014,
"text": "$ echo \"My Shell name is: $SHELL\""
},
{
"code": null,
"e": 25266,
"s": 25048,
"text": "2) Using ps command: ps command stands for “Process Status”. It is used to check the currently running status and their PIDs. If the ps command is run generally in the shell then it simply tells the name of the shell."
},
{
"code": null,
"e": 25271,
"s": 25266,
"text": "$ ps"
},
{
"code": null,
"e": 25294,
"s": 25271,
"text": "2. Shell name using ps"
},
{
"code": null,
"e": 25380,
"s": 25294,
"text": "The first column tells the PID and the last column tells the type of shell i.e. bash."
},
{
"code": null,
"e": 25527,
"s": 25380,
"text": "3) By viewing /etc/passwd file: This tells the feature of the user just like it’s name, shell, and ID. This command is used with the grep command."
},
{
"code": null,
"e": 25555,
"s": 25527,
"text": "$ grep \"^$USER\" /etc/passwd"
},
{
"code": null,
"e": 25848,
"s": 25555,
"text": "4) Using lsof command: lsof stands for LIST OF OPEN FILES. This command used when we want the list of open files in our system. By using the specific flag it gives a pointer to the shell and tells us about that which shell are we using and that specific flag is -p $$. The command looks like."
},
{
"code": null,
"e": 25861,
"s": 25848,
"text": "$ lsof -p $$"
},
{
"code": null,
"e": 25942,
"s": 25861,
"text": "As you can see clearly in the 3rd line it tells us about the shell we are using."
},
{
"code": null,
"e": 26138,
"s": 25942,
"text": "5) Using readlink /proc/$$/exe: The readlink is used to print the file name. So with the help of this, we print the location of the current shell using the /proc/$$/exe. Command can be written as"
},
{
"code": null,
"e": 26162,
"s": 26138,
"text": "$ readlink /proc/$$/exe"
},
{
"code": null,
"e": 26169,
"s": 26162,
"text": "Picked"
},
{
"code": null,
"e": 26182,
"s": 26169,
"text": "Shell Script"
},
{
"code": null,
"e": 26193,
"s": 26182,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26291,
"s": 26193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26300,
"s": 26291,
"text": "Comments"
},
{
"code": null,
"e": 26313,
"s": 26300,
"text": "Old Comments"
},
{
"code": null,
"e": 26339,
"s": 26313,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26376,
"s": 26339,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26411,
"s": 26376,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26448,
"s": 26411,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26488,
"s": 26448,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26523,
"s": 26488,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 26557,
"s": 26523,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26586,
"s": 26557,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26612,
"s": 26586,
"text": "Docker - COPY Instruction"
}
] |
How to check if a text field is empty or not in swift?
|
It’s very easy to check whether text field is empty or not in Swift.
You will first need to check whether text is available or not in text field i.e. it’s not nil, then you will need to check if its present then its empty or not. Assuming myTextField is your text field variable name, you can do the following
if let text = myTextField.text, text.isEmpty {
// myTextField is not empty here
} else {
// myTextField is Empty
}
Above code will check if textField is empty or not.
If you want to look at how the text field can be added and checked in details . Follow the below steps.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “CheckEmptyTextField”
Step 2 − Open Main.storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label.
Step 3 − Add IBOutlet for text field in ViewController, name it textField
@IBOutlet weak var textField: UITextField!
Step 4 − Add IBoutlet for label, it resultLabel
@IBOutlet weak var resultLabel: UILabel!
Step 5 − Add @IBAction for touchUpInside ‘Check’ button as follows
@IBAction func checkTextFeild(_ sender: Any) {
}
Step 6 − In checkTextFeild function we will test whether the textField is empty or not, and show the result in label. Add below code to do so
@IBAction func checkTextFeild(_ sender: Any) {
if let text = textField.text, text.isEmpty {
resultLabel.text = "Text field is empty"
} else {
resultLabel.text = "Text Field is not empty"
}
}
Step 7 − Run the project. Click on ‘Check’ button, you should see that the label gets updated saying ‘Text field is empty"’
Step 8 − Type something in textField, now click on ‘Check’ button, you should see that the label gets updated saying ‘Text Field is not empty"’
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "It’s very easy to check whether text field is empty or not in Swift."
},
{
"code": null,
"e": 1372,
"s": 1131,
"text": "You will first need to check whether text is available or not in text field i.e. it’s not nil, then you will need to check if its present then its empty or not. Assuming myTextField is your text field variable name, you can do the following"
},
{
"code": null,
"e": 1493,
"s": 1372,
"text": "if let text = myTextField.text, text.isEmpty {\n // myTextField is not empty here\n} else {\n // myTextField is Empty\n}"
},
{
"code": null,
"e": 1545,
"s": 1493,
"text": "Above code will check if textField is empty or not."
},
{
"code": null,
"e": 1649,
"s": 1545,
"text": "If you want to look at how the text field can be added and checked in details . Follow the below steps."
},
{
"code": null,
"e": 1747,
"s": 1649,
"text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “CheckEmptyTextField”"
},
{
"code": null,
"e": 1967,
"s": 1747,
"text": "Step 2 − Open Main.storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label."
},
{
"code": null,
"e": 2041,
"s": 1967,
"text": "Step 3 − Add IBOutlet for text field in ViewController, name it textField"
},
{
"code": null,
"e": 2084,
"s": 2041,
"text": "@IBOutlet weak var textField: UITextField!"
},
{
"code": null,
"e": 2132,
"s": 2084,
"text": "Step 4 − Add IBoutlet for label, it resultLabel"
},
{
"code": null,
"e": 2173,
"s": 2132,
"text": "@IBOutlet weak var resultLabel: UILabel!"
},
{
"code": null,
"e": 2240,
"s": 2173,
"text": "Step 5 − Add @IBAction for touchUpInside ‘Check’ button as follows"
},
{
"code": null,
"e": 2289,
"s": 2240,
"text": "@IBAction func checkTextFeild(_ sender: Any) {\n}"
},
{
"code": null,
"e": 2431,
"s": 2289,
"text": "Step 6 − In checkTextFeild function we will test whether the textField is empty or not, and show the result in label. Add below code to do so"
},
{
"code": null,
"e": 2643,
"s": 2431,
"text": "@IBAction func checkTextFeild(_ sender: Any) {\n if let text = textField.text, text.isEmpty {\n resultLabel.text = \"Text field is empty\"\n } else {\n resultLabel.text = \"Text Field is not empty\"\n }\n}"
},
{
"code": null,
"e": 2767,
"s": 2643,
"text": "Step 7 − Run the project. Click on ‘Check’ button, you should see that the label gets updated saying ‘Text field is empty\"’"
},
{
"code": null,
"e": 2911,
"s": 2767,
"text": "Step 8 − Type something in textField, now click on ‘Check’ button, you should see that the label gets updated saying ‘Text Field is not empty\"’"
}
] |
Tryit Editor v3.7
|
Tryit: The flex shorthand property
|
[] |
AutoML + Pentaho + Grafana for fast solution prototyping | by Gwyn | Towards Data Science
|
Written by Elena Salova and Gwyn Evans
When building machine learning solutions, data scientists are often following their noses to select appropriate features, modelling techniques and hyperparameters to tackle the problem at hand. In practice, this involves drawing on experience (and code!) from previous projects, incorporating domain knowledge from subject matter experts, and many (many, many, many, many, many....!?!) iterative development cycles.
Whether the experimentation phase is fun, excruciatingly tedious or somewhere in between, one thing is for sure; this development process does not lend itself well to fast solution prototyping, especially for new or unfamiliar problem domains.
In this post, we’ll cover the use of automated machine learning (AutoML) with Pentaho (our data integration platform of choice) and Grafana (visualisation) to rapidly design, build and evaluate a number of modelling approaches to predict air pressure system (APS) failures in heavy Scania trucks (Industrial Challenge 2016 set at The 15th International Symposium on Intelligent Data Analysis). We wanted to see if this approach could:
(1) Speed up time to an adequately performing model.
(2) Help us explore alternative modelling/data prep approaches.
(3) Give us a repeatable, rapid development template for future projects.
Dataset
We decided to use the dataset released by Scania CV AB on the UCI Machine Learning Repository. It’s separated into a training and test set, both having 171 attributes. Attribute names were anonymised due to proprietary reasons, but each field corresponds to sensors on the truck. The training set had 60,000 examples in total, where 59,000 belong to the negative class and 1000 belong to the positive. To deal with the many missing values in the dataset we used a median imputation technique. The dataset is highly unbalanced and in order to undersample the negative class we used a combination of Random Undersampling and the Condensed Nearest Neighbour Rule Undersampling in order to create a balanced dataset. As for the scoring, we used the same indicative values of costs as in this article. In this case, each False Positive will cost $10 (unnecessary check), with False Negatives costing $500 for associated repairs. Based on these values, we will be calculating total cost.
Our AutoML Toolkit
AutoML libraries aim to automate the process of feature engineering and model selection. We decided to use the Python TPOT (Tree-based Pipeline Optimization Tool) library, which uses an evolutionary algorithm to evaluate multiple machine learning techniques, feature engineering steps and hyperparameters. In other words, TPOT tries out a particular machine learning pipeline, evaluates its performance and randomly changes parts of the pipeline in search of better overall predictive power.
In addition to this, we used Pentaho to build a reusable AutoML template for future projects, curate a real-time model catalogue and manage data prep. Grafana was used to visualise the performance of the various pipeline/algorithm combinations as the search progressed.
Getting started
In Pentaho we imported the Scania APS data, sampled to re-balance classes and embedded the required Python code into the data flow to make use of the TPOT functions.
Our current task is a classification task (APS system failure/non-failure), so we’ll be using the TPOT Classifier. TPOT usage and syntax is similar to any other sklearn classifier. A full list of classifier parameters can be found here. For our development purposes we used:
generations: Number of iterations to the run pipeline optimization process.
population_size: Number of individuals to retain in the genetic programming population every generation.
mutation_rate: Tells the evolutionary algorithm how many pipelines to apply random changes to every generation.
scoring: Function used to evaluate the quality of a given pipeline for the classification problem. We used “recall” for starters, as it made sense to initially optimise for identifying all of the True APS failures due to the larger associated cost, rather than minimising unnecessary call outs.
periodic_checkpoint_folder: If supplied, a folder in which TPOT will periodically save pipelines in pareto front so far while optimizing. We wanted to record the best performing pipelines as the search progressed real-time to get a feel for the best performing algorithms and record them for comparison later.
verbosity: How much information TPOT communicates while it’s running. We wanted to see everything as the search progressed.
#example TPOT codeimport pandas as pdimport numpy as npimport pickleimport timefrom tpot import TPOTClassifierfrom sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.externals import joblib#scaling training data and saving scalermin_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)scaler_name=’/home/demouser/Desktop/Aldrin/scalers/scaler’+str(int(time.time()))+’.save’joblib.dump(min_max_scaler, scaler_name)X=np.asarray(x_scaled)#splitting train and CV setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=None)#Training TPOT classifiertpot = TPOTClassifier(generations=50, verbosity=3,population_size=100, periodic_checkpoint_folder=path_to_folder, scoring=’roc_auc’ , mutation_rate=0.9)tpot.fit(X_train, y_train)output_score=str(tpot.score(X_test, y_test))tpot.export(path_to_pipeline)pickle.dump(tpot.fitted_pipeline_, open(file_name, ‘wb’))
Building and Visualising the Model Catalogue
We also ran a Pentaho job to collect the ML pipelines generated by TPOT and create a real-time model catalogue (Figures 2 & 3).
We visualised the search for the best performing pipelines in Grafana (Figure 4), which allowed us to tweak our initial TPOT search parameters to get the right balance of running time vs accuracy.
Fast prototyping?
Our test set consisted of 16k samples, where 375 of them are class Positive, failures in the APS System. To put that into context, these would failures cost 375 * $500 = $187,500 for Scania.
We were able to get pretty good results on our first pass: 82% recall and 78% precision on the test set’s positive class in less than 30 minutes with our training dataset. Overall however, the cost is quite high — $33,400. After a 30min run, TPOT suggested using an XGBoost based model. How long you have to run TPOT for it to work well will depend on data size, dimensionality, accuracy requirements and the computational power you have to throw at it. Normally users run the TPOT algorithm for hours or even days to get the best pipeline. We are aiming to get to the overall cost <$20k, decreasing the initial cost by a factor of two.
Model Explainability
Next, we wanted to understand how much each of the 170 features (in this case sensor feeds) contributed to our APS failure predictions. This would help us to understand which sensor feeds are important (given our lack of domain knowledge specific to Scania heavy trucks!), as well as those which actively hinder our success. Using the SHAP (SHapley Additive exPlanations) library and embedding the required Python code into our Pentaho data flow, we were able to identify the 30 most important features out of 170 and reduce the number used in the model training.
Exploring different modelling approaches
Our AutoML dashboard in Grafana allowed us to see which modelling approaches were performing well for our use case (example view in Figure 4). Further to this, the SHAP values allowed us to explore which features are most important for model predictions, the distributions for each feature contributing to the probability of a positive classification, and the dependencies between different features (Figure 5).
Initial Results
After running our refined data flow for 8 hours TPOT came up with a RandomForest model, which is inline with the previous work [1], where RandomForests also produced the best results. We identified a threshold of 0.2 as the most promising, in terms of balancing the False Positive and False Negatives. Our final model with 0.2 threshold for positive class probability identified 357 True Positive, 639 False Positive, 14986 True Negative, 18 False Negative or 95.2% Recall and 35.8% Precision. This equated to a total cost of $6390 for unnecessary maintenance call outs and $9000 for missed APS failures, comparing well to the costs reported in previous work and during the intial challenge . The total cost was $15390, which is more than x2 times improvement from the initial run.
Further improvements
We were able to significantly improve the model performance, but it is still far from the best model performance shown in [1]. We decided to play with the hyperparameter tuning for the best pipeline outputted by TPOT. After performing a hyperparameter grid search for the Random Forest model (best parameters n_estimators=200 , max_depth=10 ) we were able to get to an overall cost of $12320, with 13 False Negatives and 582 False Positives, 38.3% precision and 96.5% recall. This brings us closer to the best cost produced by models in [1] and the original challenge[2].
Summary
The TPOT library paired with SHAP provides a nice toolset for exploring a variety of models, whilst building a better understanding of which features are influencing model behaviour. Pros’ to this approach include the relative ease of usage and the minimum number of parameters that require configuration. On the other hand, TPOT was able to find the best model configuration, but couldn’t optimally tune the hyperparameters within a 10-hour running period. This highlights one of the main con’s from our perspective — the computational complexity of both methods (TPOT and SHAP). One would need to wait for quite a long time (e.g 10 hours) to get a to a result, but as stated by the creators of TPOT, AutoML algorithms are not meant to run for half an hour. In all, we felt that the AutoML approach reduced our experimentation time or “time to an adequate prototype solution”, given our unfamiliarity with the dataset. There may be little benefit in terms of reduced development time when working with familiar data sources, however TPOT could be used in an ancillary fashion to search for alternative modelling approaches, or to justify the current modelling techniques used.
References
[1] APS Failure at Scania Trucks by mrunal sawant in @thestartup_ https://link.medium.com/zrKQJkThv6
[2] Ferreira Costa, Camila & Nascimento, Mario. (2016). IDA 2016 Industrial Challenge: Using Machine Learning for Predicting Failures. 381–386. 10.1007/978–3–319–46349–0_33. https://archive.ics.uci.edu/ml/datasets/IDA2016Challenge
Written by Elena Salova and Gwyn Evans
|
[
{
"code": null,
"e": 211,
"s": 172,
"text": "Written by Elena Salova and Gwyn Evans"
},
{
"code": null,
"e": 627,
"s": 211,
"text": "When building machine learning solutions, data scientists are often following their noses to select appropriate features, modelling techniques and hyperparameters to tackle the problem at hand. In practice, this involves drawing on experience (and code!) from previous projects, incorporating domain knowledge from subject matter experts, and many (many, many, many, many, many....!?!) iterative development cycles."
},
{
"code": null,
"e": 871,
"s": 627,
"text": "Whether the experimentation phase is fun, excruciatingly tedious or somewhere in between, one thing is for sure; this development process does not lend itself well to fast solution prototyping, especially for new or unfamiliar problem domains."
},
{
"code": null,
"e": 1306,
"s": 871,
"text": "In this post, we’ll cover the use of automated machine learning (AutoML) with Pentaho (our data integration platform of choice) and Grafana (visualisation) to rapidly design, build and evaluate a number of modelling approaches to predict air pressure system (APS) failures in heavy Scania trucks (Industrial Challenge 2016 set at The 15th International Symposium on Intelligent Data Analysis). We wanted to see if this approach could:"
},
{
"code": null,
"e": 1359,
"s": 1306,
"text": "(1) Speed up time to an adequately performing model."
},
{
"code": null,
"e": 1423,
"s": 1359,
"text": "(2) Help us explore alternative modelling/data prep approaches."
},
{
"code": null,
"e": 1497,
"s": 1423,
"text": "(3) Give us a repeatable, rapid development template for future projects."
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Dataset"
},
{
"code": null,
"e": 2487,
"s": 1505,
"text": "We decided to use the dataset released by Scania CV AB on the UCI Machine Learning Repository. It’s separated into a training and test set, both having 171 attributes. Attribute names were anonymised due to proprietary reasons, but each field corresponds to sensors on the truck. The training set had 60,000 examples in total, where 59,000 belong to the negative class and 1000 belong to the positive. To deal with the many missing values in the dataset we used a median imputation technique. The dataset is highly unbalanced and in order to undersample the negative class we used a combination of Random Undersampling and the Condensed Nearest Neighbour Rule Undersampling in order to create a balanced dataset. As for the scoring, we used the same indicative values of costs as in this article. In this case, each False Positive will cost $10 (unnecessary check), with False Negatives costing $500 for associated repairs. Based on these values, we will be calculating total cost."
},
{
"code": null,
"e": 2506,
"s": 2487,
"text": "Our AutoML Toolkit"
},
{
"code": null,
"e": 2998,
"s": 2506,
"text": "AutoML libraries aim to automate the process of feature engineering and model selection. We decided to use the Python TPOT (Tree-based Pipeline Optimization Tool) library, which uses an evolutionary algorithm to evaluate multiple machine learning techniques, feature engineering steps and hyperparameters. In other words, TPOT tries out a particular machine learning pipeline, evaluates its performance and randomly changes parts of the pipeline in search of better overall predictive power."
},
{
"code": null,
"e": 3268,
"s": 2998,
"text": "In addition to this, we used Pentaho to build a reusable AutoML template for future projects, curate a real-time model catalogue and manage data prep. Grafana was used to visualise the performance of the various pipeline/algorithm combinations as the search progressed."
},
{
"code": null,
"e": 3284,
"s": 3268,
"text": "Getting started"
},
{
"code": null,
"e": 3450,
"s": 3284,
"text": "In Pentaho we imported the Scania APS data, sampled to re-balance classes and embedded the required Python code into the data flow to make use of the TPOT functions."
},
{
"code": null,
"e": 3725,
"s": 3450,
"text": "Our current task is a classification task (APS system failure/non-failure), so we’ll be using the TPOT Classifier. TPOT usage and syntax is similar to any other sklearn classifier. A full list of classifier parameters can be found here. For our development purposes we used:"
},
{
"code": null,
"e": 3801,
"s": 3725,
"text": "generations: Number of iterations to the run pipeline optimization process."
},
{
"code": null,
"e": 3906,
"s": 3801,
"text": "population_size: Number of individuals to retain in the genetic programming population every generation."
},
{
"code": null,
"e": 4018,
"s": 3906,
"text": "mutation_rate: Tells the evolutionary algorithm how many pipelines to apply random changes to every generation."
},
{
"code": null,
"e": 4313,
"s": 4018,
"text": "scoring: Function used to evaluate the quality of a given pipeline for the classification problem. We used “recall” for starters, as it made sense to initially optimise for identifying all of the True APS failures due to the larger associated cost, rather than minimising unnecessary call outs."
},
{
"code": null,
"e": 4623,
"s": 4313,
"text": "periodic_checkpoint_folder: If supplied, a folder in which TPOT will periodically save pipelines in pareto front so far while optimizing. We wanted to record the best performing pipelines as the search progressed real-time to get a feel for the best performing algorithms and record them for comparison later."
},
{
"code": null,
"e": 4747,
"s": 4623,
"text": "verbosity: How much information TPOT communicates while it’s running. We wanted to see everything as the search progressed."
},
{
"code": null,
"e": 5708,
"s": 4747,
"text": "#example TPOT codeimport pandas as pdimport numpy as npimport pickleimport timefrom tpot import TPOTClassifierfrom sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.externals import joblib#scaling training data and saving scalermin_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)scaler_name=’/home/demouser/Desktop/Aldrin/scalers/scaler’+str(int(time.time()))+’.save’joblib.dump(min_max_scaler, scaler_name)X=np.asarray(x_scaled)#splitting train and CV setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=None)#Training TPOT classifiertpot = TPOTClassifier(generations=50, verbosity=3,population_size=100, periodic_checkpoint_folder=path_to_folder, scoring=’roc_auc’ , mutation_rate=0.9)tpot.fit(X_train, y_train)output_score=str(tpot.score(X_test, y_test))tpot.export(path_to_pipeline)pickle.dump(tpot.fitted_pipeline_, open(file_name, ‘wb’))"
},
{
"code": null,
"e": 5753,
"s": 5708,
"text": "Building and Visualising the Model Catalogue"
},
{
"code": null,
"e": 5881,
"s": 5753,
"text": "We also ran a Pentaho job to collect the ML pipelines generated by TPOT and create a real-time model catalogue (Figures 2 & 3)."
},
{
"code": null,
"e": 6078,
"s": 5881,
"text": "We visualised the search for the best performing pipelines in Grafana (Figure 4), which allowed us to tweak our initial TPOT search parameters to get the right balance of running time vs accuracy."
},
{
"code": null,
"e": 6096,
"s": 6078,
"text": "Fast prototyping?"
},
{
"code": null,
"e": 6287,
"s": 6096,
"text": "Our test set consisted of 16k samples, where 375 of them are class Positive, failures in the APS System. To put that into context, these would failures cost 375 * $500 = $187,500 for Scania."
},
{
"code": null,
"e": 6924,
"s": 6287,
"text": "We were able to get pretty good results on our first pass: 82% recall and 78% precision on the test set’s positive class in less than 30 minutes with our training dataset. Overall however, the cost is quite high — $33,400. After a 30min run, TPOT suggested using an XGBoost based model. How long you have to run TPOT for it to work well will depend on data size, dimensionality, accuracy requirements and the computational power you have to throw at it. Normally users run the TPOT algorithm for hours or even days to get the best pipeline. We are aiming to get to the overall cost <$20k, decreasing the initial cost by a factor of two."
},
{
"code": null,
"e": 6945,
"s": 6924,
"text": "Model Explainability"
},
{
"code": null,
"e": 7509,
"s": 6945,
"text": "Next, we wanted to understand how much each of the 170 features (in this case sensor feeds) contributed to our APS failure predictions. This would help us to understand which sensor feeds are important (given our lack of domain knowledge specific to Scania heavy trucks!), as well as those which actively hinder our success. Using the SHAP (SHapley Additive exPlanations) library and embedding the required Python code into our Pentaho data flow, we were able to identify the 30 most important features out of 170 and reduce the number used in the model training."
},
{
"code": null,
"e": 7550,
"s": 7509,
"text": "Exploring different modelling approaches"
},
{
"code": null,
"e": 7962,
"s": 7550,
"text": "Our AutoML dashboard in Grafana allowed us to see which modelling approaches were performing well for our use case (example view in Figure 4). Further to this, the SHAP values allowed us to explore which features are most important for model predictions, the distributions for each feature contributing to the probability of a positive classification, and the dependencies between different features (Figure 5)."
},
{
"code": null,
"e": 7978,
"s": 7962,
"text": "Initial Results"
},
{
"code": null,
"e": 8760,
"s": 7978,
"text": "After running our refined data flow for 8 hours TPOT came up with a RandomForest model, which is inline with the previous work [1], where RandomForests also produced the best results. We identified a threshold of 0.2 as the most promising, in terms of balancing the False Positive and False Negatives. Our final model with 0.2 threshold for positive class probability identified 357 True Positive, 639 False Positive, 14986 True Negative, 18 False Negative or 95.2% Recall and 35.8% Precision. This equated to a total cost of $6390 for unnecessary maintenance call outs and $9000 for missed APS failures, comparing well to the costs reported in previous work and during the intial challenge . The total cost was $15390, which is more than x2 times improvement from the initial run."
},
{
"code": null,
"e": 8781,
"s": 8760,
"text": "Further improvements"
},
{
"code": null,
"e": 9353,
"s": 8781,
"text": "We were able to significantly improve the model performance, but it is still far from the best model performance shown in [1]. We decided to play with the hyperparameter tuning for the best pipeline outputted by TPOT. After performing a hyperparameter grid search for the Random Forest model (best parameters n_estimators=200 , max_depth=10 ) we were able to get to an overall cost of $12320, with 13 False Negatives and 582 False Positives, 38.3% precision and 96.5% recall. This brings us closer to the best cost produced by models in [1] and the original challenge[2]."
},
{
"code": null,
"e": 9361,
"s": 9353,
"text": "Summary"
},
{
"code": null,
"e": 10539,
"s": 9361,
"text": "The TPOT library paired with SHAP provides a nice toolset for exploring a variety of models, whilst building a better understanding of which features are influencing model behaviour. Pros’ to this approach include the relative ease of usage and the minimum number of parameters that require configuration. On the other hand, TPOT was able to find the best model configuration, but couldn’t optimally tune the hyperparameters within a 10-hour running period. This highlights one of the main con’s from our perspective — the computational complexity of both methods (TPOT and SHAP). One would need to wait for quite a long time (e.g 10 hours) to get a to a result, but as stated by the creators of TPOT, AutoML algorithms are not meant to run for half an hour. In all, we felt that the AutoML approach reduced our experimentation time or “time to an adequate prototype solution”, given our unfamiliarity with the dataset. There may be little benefit in terms of reduced development time when working with familiar data sources, however TPOT could be used in an ancillary fashion to search for alternative modelling approaches, or to justify the current modelling techniques used."
},
{
"code": null,
"e": 10550,
"s": 10539,
"text": "References"
},
{
"code": null,
"e": 10651,
"s": 10550,
"text": "[1] APS Failure at Scania Trucks by mrunal sawant in @thestartup_ https://link.medium.com/zrKQJkThv6"
},
{
"code": null,
"e": 10882,
"s": 10651,
"text": "[2] Ferreira Costa, Camila & Nascimento, Mario. (2016). IDA 2016 Industrial Challenge: Using Machine Learning for Predicting Failures. 381–386. 10.1007/978–3–319–46349–0_33. https://archive.ics.uci.edu/ml/datasets/IDA2016Challenge"
}
] |
Python | Pandas Index.is_categorical() - GeeksforGeeks
|
17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.is_categorical() function checks if the index holds categorical data. Categorical variables represent types of data which may be divided into groups. Examples of categorical variables are race, sex, age group, and educational level.
Syntax: Index.is_categorical()
Parameters : Doesn’t take any parameter.
Returns : True if the Index is categorical.
Example #1: Use Index.is_categorical() function to check if the input Index is categorical or not.
# importing pandas as pdimport pandas as pd # Creating the categorical Indexidx = pd.Index(['Labrador', 'Beagle', 'Mastiff', 'Lhasa', 'Husky', 'Beagle']).astype('category') # Print the Indexidx
Output :
Now we find if idx labels are categorical or not.
# Find whether idx1 is categorical or not.idx.is_categorical()
Output :The function has returned true indicating that the values contained in the index are categorical. Example #2: Use Index.is_categorical() function to find if the values contained in the index is categorical or not.
# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', '2014-02-11']) # Print the Indexidx
Output :
Now we check if the labels in the idx are categorical or not.
# test whether idx is having categorical values.idx.is_categorical()
Output :
As we can see in the output, the function has returned False indicating that the values are not categorical in the idx Index.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n17 Dec, 2018"
},
{
"code": null,
"e": 24115,
"s": 23901,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 24361,
"s": 24115,
"text": "Pandas Index.is_categorical() function checks if the index holds categorical data. Categorical variables represent types of data which may be divided into groups. Examples of categorical variables are race, sex, age group, and educational level."
},
{
"code": null,
"e": 24392,
"s": 24361,
"text": "Syntax: Index.is_categorical()"
},
{
"code": null,
"e": 24433,
"s": 24392,
"text": "Parameters : Doesn’t take any parameter."
},
{
"code": null,
"e": 24477,
"s": 24433,
"text": "Returns : True if the Index is categorical."
},
{
"code": null,
"e": 24576,
"s": 24477,
"text": "Example #1: Use Index.is_categorical() function to check if the input Index is categorical or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the categorical Indexidx = pd.Index(['Labrador', 'Beagle', 'Mastiff', 'Lhasa', 'Husky', 'Beagle']).astype('category') # Print the Indexidx",
"e": 24791,
"s": 24576,
"text": null
},
{
"code": null,
"e": 24800,
"s": 24791,
"text": "Output :"
},
{
"code": null,
"e": 24850,
"s": 24800,
"text": "Now we find if idx labels are categorical or not."
},
{
"code": "# Find whether idx1 is categorical or not.idx.is_categorical()",
"e": 24913,
"s": 24850,
"text": null
},
{
"code": null,
"e": 25135,
"s": 24913,
"text": "Output :The function has returned true indicating that the values contained in the index are categorical. Example #2: Use Index.is_categorical() function to find if the values contained in the index is categorical or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', '2014-02-11']) # Print the Indexidx",
"e": 25350,
"s": 25135,
"text": null
},
{
"code": null,
"e": 25359,
"s": 25350,
"text": "Output :"
},
{
"code": null,
"e": 25421,
"s": 25359,
"text": "Now we check if the labels in the idx are categorical or not."
},
{
"code": "# test whether idx is having categorical values.idx.is_categorical()",
"e": 25490,
"s": 25421,
"text": null
},
{
"code": null,
"e": 25499,
"s": 25490,
"text": "Output :"
},
{
"code": null,
"e": 25625,
"s": 25499,
"text": "As we can see in the output, the function has returned False indicating that the values are not categorical in the idx Index."
},
{
"code": null,
"e": 25648,
"s": 25625,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 25662,
"s": 25648,
"text": "Python-pandas"
},
{
"code": null,
"e": 25669,
"s": 25662,
"text": "Python"
},
{
"code": null,
"e": 25767,
"s": 25669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25776,
"s": 25767,
"text": "Comments"
},
{
"code": null,
"e": 25789,
"s": 25776,
"text": "Old Comments"
},
{
"code": null,
"e": 25821,
"s": 25789,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25877,
"s": 25821,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25919,
"s": 25877,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25961,
"s": 25919,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25997,
"s": 25961,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26019,
"s": 25997,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26058,
"s": 26019,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26085,
"s": 26058,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26116,
"s": 26085,
"text": "Python | os.path.join() method"
}
] |
Standard Input Stream (cin) in C++
|
std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.
As an object of class istream, characters can be retrieved either as formatted data using the extraction operator (operator>>) or as unformatted data, using member functions such as read. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
You can use this object to read from standard input to a variable. For example, if you want to read an int value in a variable my_intand then print it to the screen, you'd write −
#include<iostream>
int main() {
int my_int;
std::cin >> my_int;
std::cout << my_int;
return 0;
}
Then save this program to the hello.cpp file. Finally, navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
If you give it the input: 15, this will give the output−
15
|
[
{
"code": null,
"e": 1403,
"s": 1062,
"text": "std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file."
},
{
"code": null,
"e": 1723,
"s": 1403,
"text": "As an object of class istream, characters can be retrieved either as formatted data using the extraction operator (operator>>) or as unformatted data, using member functions such as read. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program."
},
{
"code": null,
"e": 1903,
"s": 1723,
"text": "You can use this object to read from standard input to a variable. For example, if you want to read an int value in a variable my_intand then print it to the screen, you'd write −"
},
{
"code": null,
"e": 2012,
"s": 1903,
"text": "#include<iostream>\nint main() {\n int my_int;\n std::cin >> my_int;\n std::cout << my_int;\n return 0;\n}"
},
{
"code": null,
"e": 2154,
"s": 2012,
"text": "Then save this program to the hello.cpp file. Finally, navigate to the saved location of this file in the terminal/cmd and compile it using −"
},
{
"code": null,
"e": 2170,
"s": 2154,
"text": "$ g++ hello.cpp"
},
{
"code": null,
"e": 2185,
"s": 2170,
"text": "Run it using −"
},
{
"code": null,
"e": 2195,
"s": 2185,
"text": "$ ./a.out"
},
{
"code": null,
"e": 2252,
"s": 2195,
"text": "If you give it the input: 15, this will give the output−"
},
{
"code": null,
"e": 2255,
"s": 2252,
"text": "15"
}
] |
Practical Guide to Semantic Segmentation | by Alex Simkiv | Towards Data Science
|
Object detection and extracting, especially with semantic segmentation, is a well-studied problem with a developed set of almost standard solutions. So if you’re a seasoned data scientist, most likely you won’t find anything new or special in this article. But if you’re relatively new to data science and image processing, in particular, this article may become your practical tutorial on making your first semantic segmentation model. Please note, that we’re not going to discuss any theoretical basis for semantic segmentation. This is only an example of a code\solution that was developed as a baseline approach during a proof of concept.
Our journey begins with a simple customer request. She needed to detect documents of a kind in images. To deliver this we need a dataset of sample documents. Most datasets that contained photos of documents do not provide the ground truth data we needed to train and evaluate our PoC. Fortunately, we found a dataset suitable for this particular problem: MIDV500 : A Dataset for Identity Documents Analysis and Recognition on Mobile Devices in Video Stream. All source document images used in MIDV-500 are either in the public domain or distributed under public copyright licenses.
Before we start showing and explaining the code, we would like to point out that it usually takes a few futile attempts and trying out things that don’t work in order to get to the working result, it is a necessary learning curve. This time we started our efforts performing some straight actions with OpenCV, like:
filtering
edges detection
brightness\contrast,etc.
thresholding the image
extracting contours
selecting the one that fits our given criteria.
There were, of course, a few images, where this relatively simple approach worked well (like the one in the bottom right corner of the bottom image). But for most of the images, we had to conclude that their colors, lightning, shadows, blur, and other conditions were so versatile, that one simple image processing algorithm can’t cover it all.
Although we believed that there might exist an algorithm that can perform well under these conditions, we saw no point in continuing to work on this approach. So we switched to a little more complex approach: neural networks.
Specifically, we decided to try semantic segmentation. That’s mostly because we have created a few of them, that developing a new one took only a few hours to write generators and train the model. We didn’t even tune hyperparameters, since we achieved our purpose on the very first try.
To create a model we need to prepare the data and implement the model itself. Generally, most NN models may be split into 3 main parts: the generator, the predictor, and the neural network itself. Additionally, there might be some trainers.
We converted the data in our dataset (mentioned above) into the following format:
Here:
path — stands for the path to an image inside a dataset
x0, y0, x1, y1, x2, y2, x3, y3 — ground truth quadrangle coordinates
part — a number specifying a part of the dataset (the number that goes first in the name of each folder)
group — background used on the image (name of the folder containing the image)
The purpose of a generator is to provide batches for training. Therefore, it should provide both input and output images. An example of initialization of such a generator may look like this:
Here the samples parameter is simply a part of the dataframe we prepared beforehand, data_path — a path to the dataset. The idea is simple: iterate through all of the images, resize them, draw the ground truth on a blank image, and store them in the corresponding variables. We believe the code above to be self-explanatory (just read it sequentially and don’t jump into the middle). Feel free to contact me if any doubts :-). Then, we can return a batch using __getitem__ method, as simple as that:
#create you generatoryour_sample_generator = BatchGenerator(your_df, your_data_path, batch_size)#return a batchnext(your_sample_generator)#return a butch number iyour_sample_generator[i]
Now let’s create our neural network architecture. The provided architecture has proved to work well enough for a great variety of similar tasks.
The idea behind this model is the next: we downsample the input image to the size 8x8 while learning some features about most of the regions. Then, we pass those features to a few dense layers that, in fact, make a decision on whether there is an ID card on the image and if yes, where it is located. And finally, we use that decision as well as the features calculated during the downsampling part (all those Concatenate layers are implementing so-called skip-connections in CNN) to clarify the exact shape of the prediction. Despite this decision layer inside the model, it is still a semantic segmentation network that produces a probability map to define whether a pixel belongs to an ID card or not.
Now we proceed to the training of our model. First, let’s split the data into training and testing sets:
and initialize the generators:
Build the model and compile it:
We got the next model architecture
Well, the model appears to be not too big (832Kb). So, perhaps, it can even fit into a phone :-)
Finally, we can train our model:
We used a few simple callbacks to monitor training process, delivering easy to interpret plots and storing training results for further usage. If you are interested in actual code please let me know.
To analyze model results we plot accuracy against IoU threshold.
We can see that for an IoU threshold of 0.8 we reached a ~71% accuracy. It’s not perfect, but we didn’t even perform any optimizations for this model. There is room for improvement. Please find an example of the model input, ground truth, and its prediction:
Looks promising, right?
With all that said and done, we can finally extract ID cards from images. For this let’s prepare a few helper functions.
And use them in our final model:
Explanation: after NN makes its prediction on the resize of a given image, we threshold the result by 0.5 and search it for all the contours. After we smooth each contour, we check whether it has 4 edges and if it occupies the minimum allowed area. If yes, it is checked to be the biggest among other such contours. The selected contour is resized correspondingly to an input image and the rectangle is extracted using OpenCV tools. The result looks like this:
That is, of course, not even close to what can be called a solution. There are still many things that can be improved and tested. Here are a few of them:
Trying object detection instead of semantic segmentation (YOLO, perhaps)Tuning the hyperparameters, as a potentially better data split strategyAnalyzing the nature of mistakesImproving the prediction processing algorithm to better select hardcoded values
Trying object detection instead of semantic segmentation (YOLO, perhaps)
Tuning the hyperparameters, as a potentially better data split strategy
Analyzing the nature of mistakes
Improving the prediction processing algorithm to better select hardcoded values
This turns into an even greater list when you need to generalize this solution to process arbitrary documents. But still, this may be a good starting point for the task.
I want to thank my colleagues Andy Bosyi, Mykola Kozlenko, Volodymyr Sendetskyi, Viach Bosyi and Nazar Savchenko for fruitful discussions, cooperation, and helpful tips as well as the entire MindCraft.ai team for their constant support.
Alex Simkiv,
Data Scientist, MindCraft.ai
Information Technology & Data Science
|
[
{
"code": null,
"e": 815,
"s": 172,
"text": "Object detection and extracting, especially with semantic segmentation, is a well-studied problem with a developed set of almost standard solutions. So if you’re a seasoned data scientist, most likely you won’t find anything new or special in this article. But if you’re relatively new to data science and image processing, in particular, this article may become your practical tutorial on making your first semantic segmentation model. Please note, that we’re not going to discuss any theoretical basis for semantic segmentation. This is only an example of a code\\solution that was developed as a baseline approach during a proof of concept."
},
{
"code": null,
"e": 1397,
"s": 815,
"text": "Our journey begins with a simple customer request. She needed to detect documents of a kind in images. To deliver this we need a dataset of sample documents. Most datasets that contained photos of documents do not provide the ground truth data we needed to train and evaluate our PoC. Fortunately, we found a dataset suitable for this particular problem: MIDV500 : A Dataset for Identity Documents Analysis and Recognition on Mobile Devices in Video Stream. All source document images used in MIDV-500 are either in the public domain or distributed under public copyright licenses."
},
{
"code": null,
"e": 1713,
"s": 1397,
"text": "Before we start showing and explaining the code, we would like to point out that it usually takes a few futile attempts and trying out things that don’t work in order to get to the working result, it is a necessary learning curve. This time we started our efforts performing some straight actions with OpenCV, like:"
},
{
"code": null,
"e": 1723,
"s": 1713,
"text": "filtering"
},
{
"code": null,
"e": 1739,
"s": 1723,
"text": "edges detection"
},
{
"code": null,
"e": 1764,
"s": 1739,
"text": "brightness\\contrast,etc."
},
{
"code": null,
"e": 1787,
"s": 1764,
"text": "thresholding the image"
},
{
"code": null,
"e": 1807,
"s": 1787,
"text": "extracting contours"
},
{
"code": null,
"e": 1855,
"s": 1807,
"text": "selecting the one that fits our given criteria."
},
{
"code": null,
"e": 2200,
"s": 1855,
"text": "There were, of course, a few images, where this relatively simple approach worked well (like the one in the bottom right corner of the bottom image). But for most of the images, we had to conclude that their colors, lightning, shadows, blur, and other conditions were so versatile, that one simple image processing algorithm can’t cover it all."
},
{
"code": null,
"e": 2426,
"s": 2200,
"text": "Although we believed that there might exist an algorithm that can perform well under these conditions, we saw no point in continuing to work on this approach. So we switched to a little more complex approach: neural networks."
},
{
"code": null,
"e": 2713,
"s": 2426,
"text": "Specifically, we decided to try semantic segmentation. That’s mostly because we have created a few of them, that developing a new one took only a few hours to write generators and train the model. We didn’t even tune hyperparameters, since we achieved our purpose on the very first try."
},
{
"code": null,
"e": 2954,
"s": 2713,
"text": "To create a model we need to prepare the data and implement the model itself. Generally, most NN models may be split into 3 main parts: the generator, the predictor, and the neural network itself. Additionally, there might be some trainers."
},
{
"code": null,
"e": 3036,
"s": 2954,
"text": "We converted the data in our dataset (mentioned above) into the following format:"
},
{
"code": null,
"e": 3042,
"s": 3036,
"text": "Here:"
},
{
"code": null,
"e": 3098,
"s": 3042,
"text": "path — stands for the path to an image inside a dataset"
},
{
"code": null,
"e": 3167,
"s": 3098,
"text": "x0, y0, x1, y1, x2, y2, x3, y3 — ground truth quadrangle coordinates"
},
{
"code": null,
"e": 3272,
"s": 3167,
"text": "part — a number specifying a part of the dataset (the number that goes first in the name of each folder)"
},
{
"code": null,
"e": 3351,
"s": 3272,
"text": "group — background used on the image (name of the folder containing the image)"
},
{
"code": null,
"e": 3542,
"s": 3351,
"text": "The purpose of a generator is to provide batches for training. Therefore, it should provide both input and output images. An example of initialization of such a generator may look like this:"
},
{
"code": null,
"e": 4042,
"s": 3542,
"text": "Here the samples parameter is simply a part of the dataframe we prepared beforehand, data_path — a path to the dataset. The idea is simple: iterate through all of the images, resize them, draw the ground truth on a blank image, and store them in the corresponding variables. We believe the code above to be self-explanatory (just read it sequentially and don’t jump into the middle). Feel free to contact me if any doubts :-). Then, we can return a batch using __getitem__ method, as simple as that:"
},
{
"code": null,
"e": 4306,
"s": 4042,
"text": "#create you generatoryour_sample_generator = BatchGenerator(your_df, your_data_path, batch_size)#return a batchnext(your_sample_generator)#return a butch number iyour_sample_generator[i]"
},
{
"code": null,
"e": 4451,
"s": 4306,
"text": "Now let’s create our neural network architecture. The provided architecture has proved to work well enough for a great variety of similar tasks."
},
{
"code": null,
"e": 5156,
"s": 4451,
"text": "The idea behind this model is the next: we downsample the input image to the size 8x8 while learning some features about most of the regions. Then, we pass those features to a few dense layers that, in fact, make a decision on whether there is an ID card on the image and if yes, where it is located. And finally, we use that decision as well as the features calculated during the downsampling part (all those Concatenate layers are implementing so-called skip-connections in CNN) to clarify the exact shape of the prediction. Despite this decision layer inside the model, it is still a semantic segmentation network that produces a probability map to define whether a pixel belongs to an ID card or not."
},
{
"code": null,
"e": 5261,
"s": 5156,
"text": "Now we proceed to the training of our model. First, let’s split the data into training and testing sets:"
},
{
"code": null,
"e": 5292,
"s": 5261,
"text": "and initialize the generators:"
},
{
"code": null,
"e": 5324,
"s": 5292,
"text": "Build the model and compile it:"
},
{
"code": null,
"e": 5359,
"s": 5324,
"text": "We got the next model architecture"
},
{
"code": null,
"e": 5456,
"s": 5359,
"text": "Well, the model appears to be not too big (832Kb). So, perhaps, it can even fit into a phone :-)"
},
{
"code": null,
"e": 5489,
"s": 5456,
"text": "Finally, we can train our model:"
},
{
"code": null,
"e": 5689,
"s": 5489,
"text": "We used a few simple callbacks to monitor training process, delivering easy to interpret plots and storing training results for further usage. If you are interested in actual code please let me know."
},
{
"code": null,
"e": 5754,
"s": 5689,
"text": "To analyze model results we plot accuracy against IoU threshold."
},
{
"code": null,
"e": 6013,
"s": 5754,
"text": "We can see that for an IoU threshold of 0.8 we reached a ~71% accuracy. It’s not perfect, but we didn’t even perform any optimizations for this model. There is room for improvement. Please find an example of the model input, ground truth, and its prediction:"
},
{
"code": null,
"e": 6037,
"s": 6013,
"text": "Looks promising, right?"
},
{
"code": null,
"e": 6158,
"s": 6037,
"text": "With all that said and done, we can finally extract ID cards from images. For this let’s prepare a few helper functions."
},
{
"code": null,
"e": 6191,
"s": 6158,
"text": "And use them in our final model:"
},
{
"code": null,
"e": 6652,
"s": 6191,
"text": "Explanation: after NN makes its prediction on the resize of a given image, we threshold the result by 0.5 and search it for all the contours. After we smooth each contour, we check whether it has 4 edges and if it occupies the minimum allowed area. If yes, it is checked to be the biggest among other such contours. The selected contour is resized correspondingly to an input image and the rectangle is extracted using OpenCV tools. The result looks like this:"
},
{
"code": null,
"e": 6806,
"s": 6652,
"text": "That is, of course, not even close to what can be called a solution. There are still many things that can be improved and tested. Here are a few of them:"
},
{
"code": null,
"e": 7061,
"s": 6806,
"text": "Trying object detection instead of semantic segmentation (YOLO, perhaps)Tuning the hyperparameters, as a potentially better data split strategyAnalyzing the nature of mistakesImproving the prediction processing algorithm to better select hardcoded values"
},
{
"code": null,
"e": 7134,
"s": 7061,
"text": "Trying object detection instead of semantic segmentation (YOLO, perhaps)"
},
{
"code": null,
"e": 7206,
"s": 7134,
"text": "Tuning the hyperparameters, as a potentially better data split strategy"
},
{
"code": null,
"e": 7239,
"s": 7206,
"text": "Analyzing the nature of mistakes"
},
{
"code": null,
"e": 7319,
"s": 7239,
"text": "Improving the prediction processing algorithm to better select hardcoded values"
},
{
"code": null,
"e": 7489,
"s": 7319,
"text": "This turns into an even greater list when you need to generalize this solution to process arbitrary documents. But still, this may be a good starting point for the task."
},
{
"code": null,
"e": 7726,
"s": 7489,
"text": "I want to thank my colleagues Andy Bosyi, Mykola Kozlenko, Volodymyr Sendetskyi, Viach Bosyi and Nazar Savchenko for fruitful discussions, cooperation, and helpful tips as well as the entire MindCraft.ai team for their constant support."
},
{
"code": null,
"e": 7739,
"s": 7726,
"text": "Alex Simkiv,"
},
{
"code": null,
"e": 7768,
"s": 7739,
"text": "Data Scientist, MindCraft.ai"
}
] |
JWT Authentication with Django REST Framework - GeeksforGeeks
|
04 May, 2020
JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in Django.
django : Django Installation
djangorestframework_simplejwt :pip install djangorestframework_simplejwt
pip install djangorestframework_simplejwt
Basic setup :
Start a project by the following command –
django-admin startproject config
Change directory to project config –
cd config
Start the server- Start the server by typing following command in terminal –
python manage.py runserver
To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL.
Now stop the server by pressing
ctrl-c
Let’s create an app now called the “app”.
python manage.py startapp app
adding configuration to settings.py file :
open settings.py file in config folder and add configuration.
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ],}
edit urls.py fileopen urls.py in config folder
from django.urls import path, includefrom rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('api/token/', jwt_views.TokenObtainPairView.as_view(), name ='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'), path('', include('app.urls')),]
edit views.pyopen views.py in app folder and make a API view
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.permissions import IsAuthenticated class HelloView(APIView): permission_classes = (IsAuthenticated, ) def get(self, request): content = {'message': 'Hello, GeeksforGeeks'} return Response(content)
edit urls.pycreate a urls.py in app folder and edit it
from django.urls import pathfrom . import views urlpatterns = [ path('hello/', views.HelloView.as_view(), name ='hello'),]
Usage :
To make an HTTP request we have used HTTPie, to install it.
$ sudo apt install httpie
Step 1 :migrate project, create a superuser and runserver
$ python3 manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserver 4000
Step 2 :Now, we need to authenticate and obtain the token. which we will get at endpoint is/api/token/
$ http post http://127.0.0.1:4000/api/token/ username=spider password=vinayak
add your user name and password
Step 3 :copy access token and make a request
$ http http://127.0.0.1:4000/hello/ "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg3Mjc5NDIxLCJqdGkiOiIzYWMwNDgzOTY3NjE0ZDgxYmFjMjBiMTBjMDlkMmYwOCIsInVzZXJfaWQiOjF9.qtNrUpyPQI8W2K2T22NhcgVZGFTyLN1UL7uqJ0KnF0Y"
Project
Python
Technical Scripter
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Twitter Sentiment Analysis using Python
Snake Game in C
Java Swing | Simple User Registration Form
Banking Transaction System using Java
Simple registration form using Python Tkinter
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24219,
"s": 24191,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 24559,
"s": 24219,
"text": "JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in Django."
},
{
"code": null,
"e": 24588,
"s": 24559,
"text": "django : Django Installation"
},
{
"code": null,
"e": 24661,
"s": 24588,
"text": "djangorestframework_simplejwt :pip install djangorestframework_simplejwt"
},
{
"code": null,
"e": 24703,
"s": 24661,
"text": "pip install djangorestframework_simplejwt"
},
{
"code": null,
"e": 24717,
"s": 24703,
"text": "Basic setup :"
},
{
"code": null,
"e": 24760,
"s": 24717,
"text": "Start a project by the following command –"
},
{
"code": null,
"e": 24794,
"s": 24760,
"text": " django-admin startproject config"
},
{
"code": null,
"e": 24831,
"s": 24794,
"text": "Change directory to project config –"
},
{
"code": null,
"e": 24842,
"s": 24831,
"text": " cd config"
},
{
"code": null,
"e": 24919,
"s": 24842,
"text": "Start the server- Start the server by typing following command in terminal –"
},
{
"code": null,
"e": 24947,
"s": 24919,
"text": " python manage.py runserver"
},
{
"code": null,
"e": 25054,
"s": 24947,
"text": "To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL."
},
{
"code": null,
"e": 25086,
"s": 25054,
"text": "Now stop the server by pressing"
},
{
"code": null,
"e": 25093,
"s": 25086,
"text": "ctrl-c"
},
{
"code": null,
"e": 25135,
"s": 25093,
"text": "Let’s create an app now called the “app”."
},
{
"code": null,
"e": 25165,
"s": 25135,
"text": "python manage.py startapp app"
},
{
"code": null,
"e": 25208,
"s": 25165,
"text": "adding configuration to settings.py file :"
},
{
"code": null,
"e": 25270,
"s": 25208,
"text": "open settings.py file in config folder and add configuration."
},
{
"code": "REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ],}",
"e": 25403,
"s": 25270,
"text": null
},
{
"code": null,
"e": 25450,
"s": 25403,
"text": "edit urls.py fileopen urls.py in config folder"
},
{
"code": "from django.urls import path, includefrom rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('api/token/', jwt_views.TokenObtainPairView.as_view(), name ='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'), path('', include('app.urls')),]",
"e": 25810,
"s": 25450,
"text": null
},
{
"code": null,
"e": 25871,
"s": 25810,
"text": "edit views.pyopen views.py in app folder and make a API view"
},
{
"code": "from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.permissions import IsAuthenticated class HelloView(APIView): permission_classes = (IsAuthenticated, ) def get(self, request): content = {'message': 'Hello, GeeksforGeeks'} return Response(content)",
"e": 26197,
"s": 25871,
"text": null
},
{
"code": null,
"e": 26252,
"s": 26197,
"text": "edit urls.pycreate a urls.py in app folder and edit it"
},
{
"code": "from django.urls import pathfrom . import views urlpatterns = [ path('hello/', views.HelloView.as_view(), name ='hello'),]",
"e": 26379,
"s": 26252,
"text": null
},
{
"code": null,
"e": 26387,
"s": 26379,
"text": "Usage :"
},
{
"code": null,
"e": 26447,
"s": 26387,
"text": "To make an HTTP request we have used HTTPie, to install it."
},
{
"code": null,
"e": 26473,
"s": 26447,
"text": "$ sudo apt install httpie"
},
{
"code": null,
"e": 26531,
"s": 26473,
"text": "Step 1 :migrate project, create a superuser and runserver"
},
{
"code": null,
"e": 26559,
"s": 26531,
"text": "$ python3 manage.py migrate"
},
{
"code": null,
"e": 26594,
"s": 26559,
"text": "$ python manage.py createsuperuser"
},
{
"code": null,
"e": 26628,
"s": 26594,
"text": "$ python manage.py runserver 4000"
},
{
"code": null,
"e": 26731,
"s": 26628,
"text": "Step 2 :Now, we need to authenticate and obtain the token. which we will get at endpoint is/api/token/"
},
{
"code": null,
"e": 26809,
"s": 26731,
"text": "$ http post http://127.0.0.1:4000/api/token/ username=spider password=vinayak"
},
{
"code": null,
"e": 26841,
"s": 26809,
"text": "add your user name and password"
},
{
"code": null,
"e": 26886,
"s": 26841,
"text": "Step 3 :copy access token and make a request"
},
{
"code": null,
"e": 27153,
"s": 26886,
"text": "$ http http://127.0.0.1:4000/hello/ \"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg3Mjc5NDIxLCJqdGkiOiIzYWMwNDgzOTY3NjE0ZDgxYmFjMjBiMTBjMDlkMmYwOCIsInVzZXJfaWQiOjF9.qtNrUpyPQI8W2K2T22NhcgVZGFTyLN1UL7uqJ0KnF0Y\""
},
{
"code": null,
"e": 27161,
"s": 27153,
"text": "Project"
},
{
"code": null,
"e": 27168,
"s": 27161,
"text": "Python"
},
{
"code": null,
"e": 27187,
"s": 27168,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27203,
"s": 27187,
"text": "Write From Home"
},
{
"code": null,
"e": 27301,
"s": 27203,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27310,
"s": 27301,
"text": "Comments"
},
{
"code": null,
"e": 27323,
"s": 27310,
"text": "Old Comments"
},
{
"code": null,
"e": 27363,
"s": 27323,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 27379,
"s": 27363,
"text": "Snake Game in C"
},
{
"code": null,
"e": 27422,
"s": 27379,
"text": "Java Swing | Simple User Registration Form"
},
{
"code": null,
"e": 27460,
"s": 27422,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 27506,
"s": 27460,
"text": "Simple registration form using Python Tkinter"
},
{
"code": null,
"e": 27534,
"s": 27506,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27584,
"s": 27534,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27606,
"s": 27584,
"text": "Python map() function"
}
] |
PDFBox - Splitting a PDF Document
|
In the previous chapter, we have seen how to add JavaScript to a PDF document. Let us now learn how to split a given PDF document into multiple documents.
You can split the given PDF document in to multiple PDF documents using the class named Splitter. This class is used to split the given PDF document into several other documents.
Following are the steps to split an existing PDF document
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
The class named Splitter contains the methods to split the given PDF document therefore, instantiate this class as shown below.
Splitter splitter = new Splitter();
You can split the given document using the Split() method of the Splitter class this class. This method accepts an object of the PDDocument class as a parameter.
List<PDDocument> Pages = splitter.split(document);
The split() method splits each page of the given document as an individual document and returns all these in the form of a list.
In order to traverse through the list of documents you need to get an iterator object of the list acquired in the above step, you need to get the iterator object of the list using the listIterator() method as shown below.
Iterator<PDDocument> iterator = Pages.listIterator();
Finally, close the document using close() method of PDDocument class as shown below.
document.close();
Suppose, there is a PDF document with name sample.pdf in the path C:\PdfBox_Examples\ and this document contains two pages — one page containing image and another page containing text as shown below.
This example demonstrates how to split the above mentioned PDF document. Here, we will split the PDF document named sample.pdf into two different documents sample1.pdf and sample2.pdf. Save this code in a file with name SplitPages.java.
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
public class SplitPages {
public static void main(String[] args) throws IOException {
//Loading an existing PDF document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Instantiating Splitter class
Splitter splitter = new Splitter();
//splitting the pages of a PDF document
List<PDDocument> Pages = splitter.split(document);
//Creating an iterator
Iterator<PDDocument> iterator = Pages.listIterator();
//Saving each page as an individual document
int i = 1;
while(iterator.hasNext()) {
PDDocument pd = iterator.next();
pd.save("C:/PdfBox_Examples/sample"+ i++ +".pdf");
}
System.out.println("Multiple PDF’s created");
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands
javac SplitPages.java
java SplitPages
Upon execution, the above program encrypts the given PDF document displaying the following message.
Multiple PDF’s created
If you verify the given path, you can observe that multiple PDFs were created with names sample1 and sample2 as shown below.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2182,
"s": 2027,
"text": "In the previous chapter, we have seen how to add JavaScript to a PDF document. Let us now learn how to split a given PDF document into multiple documents."
},
{
"code": null,
"e": 2361,
"s": 2182,
"text": "You can split the given PDF document in to multiple PDF documents using the class named Splitter. This class is used to split the given PDF document into several other documents."
},
{
"code": null,
"e": 2419,
"s": 2361,
"text": "Following are the steps to split an existing PDF document"
},
{
"code": null,
"e": 2636,
"s": 2419,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 2728,
"s": 2636,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 2856,
"s": 2728,
"text": "The class named Splitter contains the methods to split the given PDF document therefore, instantiate this class as shown below."
},
{
"code": null,
"e": 2893,
"s": 2856,
"text": "Splitter splitter = new Splitter();\n"
},
{
"code": null,
"e": 3055,
"s": 2893,
"text": "You can split the given document using the Split() method of the Splitter class this class. This method accepts an object of the PDDocument class as a parameter."
},
{
"code": null,
"e": 3107,
"s": 3055,
"text": "List<PDDocument> Pages = splitter.split(document);\n"
},
{
"code": null,
"e": 3236,
"s": 3107,
"text": "The split() method splits each page of the given document as an individual document and returns all these in the form of a list."
},
{
"code": null,
"e": 3458,
"s": 3236,
"text": "In order to traverse through the list of documents you need to get an iterator object of the list acquired in the above step, you need to get the iterator object of the list using the listIterator() method as shown below."
},
{
"code": null,
"e": 3513,
"s": 3458,
"text": "Iterator<PDDocument> iterator = Pages.listIterator();\n"
},
{
"code": null,
"e": 3598,
"s": 3513,
"text": "Finally, close the document using close() method of PDDocument class as shown below."
},
{
"code": null,
"e": 3617,
"s": 3598,
"text": "document.close();\n"
},
{
"code": null,
"e": 3817,
"s": 3617,
"text": "Suppose, there is a PDF document with name sample.pdf in the path C:\\PdfBox_Examples\\ and this document contains two pages — one page containing image and another page containing text as shown below."
},
{
"code": null,
"e": 4054,
"s": 3817,
"text": "This example demonstrates how to split the above mentioned PDF document. Here, we will split the PDF document named sample.pdf into two different documents sample1.pdf and sample2.pdf. Save this code in a file with name SplitPages.java."
},
{
"code": null,
"e": 5065,
"s": 4054,
"text": "import org.apache.pdfbox.multipdf.Splitter; \nimport org.apache.pdfbox.pdmodel.PDDocument;\n\nimport java.io.File; \nimport java.io.IOException; \nimport java.util.List; \nimport java.util.Iterator;\n \npublic class SplitPages {\n public static void main(String[] args) throws IOException {\n\n //Loading an existing PDF document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument document = PDDocument.load(file); \n\n //Instantiating Splitter class\n Splitter splitter = new Splitter();\n\n //splitting the pages of a PDF document\n List<PDDocument> Pages = splitter.split(document);\n\n //Creating an iterator \n Iterator<PDDocument> iterator = Pages.listIterator();\n\n //Saving each page as an individual document\n int i = 1;\n while(iterator.hasNext()) {\n PDDocument pd = iterator.next();\n pd.save(\"C:/PdfBox_Examples/sample\"+ i++ +\".pdf\");\n }\n System.out.println(\"Multiple PDF’s created\");\n document.close();\n }\n}"
},
{
"code": null,
"e": 5158,
"s": 5065,
"text": "Compile and execute the saved Java file from the command prompt using the following commands"
},
{
"code": null,
"e": 5198,
"s": 5158,
"text": "javac SplitPages.java \njava SplitPages\n"
},
{
"code": null,
"e": 5298,
"s": 5198,
"text": "Upon execution, the above program encrypts the given PDF document displaying the following message."
},
{
"code": null,
"e": 5322,
"s": 5298,
"text": "Multiple PDF’s created\n"
},
{
"code": null,
"e": 5447,
"s": 5322,
"text": "If you verify the given path, you can observe that multiple PDFs were created with names sample1 and sample2 as shown below."
},
{
"code": null,
"e": 5454,
"s": 5447,
"text": " Print"
},
{
"code": null,
"e": 5465,
"s": 5454,
"text": " Add Notes"
}
] |
What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__ in C/C++?
|
Here we will see what are the differences between __FUNCTION__, __func__ and the __PRETTY_FUNCTION__ in C++.
Basically the __FUNCTION__ and __func__ are same. Some old versions of C and C++ supports __func__. This macro is used to get the name of the current function. The _PRETTY_FUNCTION__ is used to return the detail about the function. Using this we can get which function is used, and in which class it is belonging, etc.
#include<iostream>
using namespace std;
class MyClass{
public:
void Class_Function(){
cout << "The result of __PRETTY_FUNCTION__: " << __PRETTY_FUNCTION__ << endl;
}
};
void TestFunction(){
cout << "Output of __func__ is: " << __func__ << endl;
}
main() {
cout << "Output of __FUNCTION__ is: " << __FUNCTION__ << endl;
TestFunction();
MyClass myObj;
myObj.Class_Function();
}
Output of __FUNCTION__ is: main
Output of __func__ is: TestFunction
The result of __PRETTY_FUNCTION__: void MyClass::Class_Function()
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "Here we will see what are the differences between __FUNCTION__, __func__ and the __PRETTY_FUNCTION__ in C++."
},
{
"code": null,
"e": 1490,
"s": 1171,
"text": "Basically the __FUNCTION__ and __func__ are same. Some old versions of C and C++ supports __func__. This macro is used to get the name of the current function. The _PRETTY_FUNCTION__ is used to return the detail about the function. Using this we can get which function is used, and in which class it is belonging, etc."
},
{
"code": null,
"e": 1905,
"s": 1490,
"text": "#include<iostream>\nusing namespace std;\nclass MyClass{\n public:\n void Class_Function(){\n cout << \"The result of __PRETTY_FUNCTION__: \" << __PRETTY_FUNCTION__ << endl;\n }\n};\nvoid TestFunction(){\n cout << \"Output of __func__ is: \" << __func__ << endl;\n}\nmain() {\n cout << \"Output of __FUNCTION__ is: \" << __FUNCTION__ << endl;\n TestFunction();\n MyClass myObj;\n myObj.Class_Function();\n}"
},
{
"code": null,
"e": 2039,
"s": 1905,
"text": "Output of __FUNCTION__ is: main\nOutput of __func__ is: TestFunction\nThe result of __PRETTY_FUNCTION__: void MyClass::Class_Function()"
}
] |
Accuracy Paradox. “If you don’t know anything about... | by Tejumade Afonja | Towards Data Science
|
“If you don’t know anything about Machine Learning, you should definitely know Accuracy Paradox” — Akinkunle Allen
I wrote about Model Evaluation I, If you haven’t checked it out, you should.
Accuracy is defined as the freedom from mistake or error. For example, a piece of information is accurate if it exactly represent what is being discussed.
Paradox is a statement that is seemingly contradictory or opposed to common sense and yet is perhaps true.
Have you considered that the phrase “ignore all the rules” ... is a rule itself — uhm! a paradox
In Machine Learning lingo, Accuracy is the proportion of correctness in a classification system.
Meaning, if we have a Spam detection system, and out of 5 mails we received, 4 were classified by a Model X as Spam and these mails were indeed Spam. We would say Model X has 80% Accuracy i.e you can rely on Model X, 80% of the time.
Accuracy of Model X = 4/5 * 100 = 80%
So, What exactly is an Accuracy Paradox? We’ll get to that later but first let’s consider a case study as a way of an example.
Hawkins hospital software team (Will, Dustin, Mike and Lucas) built a classification model for diagnosing Breast Cancer in women. A sample of 1000 women were studied in a given population and 100 of them with Breast Cancer while the remaining 900 were without it. Hawkins software team trained their model based of this dataset. They split the dataset into 70/30 train/test set.
The accuracy was excellent and they deployed the model.
Alas! a couple of months after deployment, some of the women who were diagnosed by the hospital as having “no breast cancer” started showing symptoms of Breast Cancer.
How could this be?
This raised a series of questions and fear amongst the entire population. Hawkins hospital had to do something about this as more and more patient started showing symptoms of Breast Cancer.
They decided to hire a Machine Learning Expert, Bob to help them understand what their software team got wrong considering the fact that the model had an accuracy of about 90%.
By splitting the data set, we have
Training set:
No Breast cancer = 70/100 * 900 = 630Breast cancer= 70/100 * 100 = 70
Test set:
No Breast cancer = 30/100 * 900 = 270Breast cancer= 30/100 * 100 = 30
In order for Bob to explain how their model got the predictions wrong, he introduced two assumptions using one of the women, Joyce as an example- Bob began his explanation as follow,
Say, we have an assumption H, that Joyce is suffering from Breast Pain and not Breast Cancer but another assumption Ho, (that counters the first) says Joyce is suffering from Breast Cancer.
If Assumption Ho is true (positive) — Breast Cancer
else Assumption Ho is false (negative) — No Breast Cancer
The table below represents what happens if this other assumption Ho is true or not.
Where:
TP = True Positive
FP = False Positive
FN = False Negative
TN = True Negative
After training their model with 70% of the data set, Hawkins scientist tested this model with the remaining 30% data to evaluate the model for its accuracy. Their model got 270 prediction right out of the 300.
Hawkins Accuracy = 270 / 300 = 0.9
This looked like a pretty convincing model with an accuracy of 90%, why then did it fail?
Bob re-evaluated their model and below is the breakdown:
Number of women with breast cancer and classified as no breast cancer (FN) = 30Number of women with breast cancer and classified as breast cancer(TP) = 0Number of women without breast cancer and classified as no breast cancer (TN) = 270Number of women without breast cancer and classified as breast cancer (FP) =
Bob represented this with a confusion matrix table below.
In summary,
Hawkins model correctly classified 270 women who do not have breast cancer as “NO Breast Cancer” while it incorrectly classified 30 women who have breast cancer as “NO Breast Cancer”.
We gave Hawkins Model 300 questions and it got 270 answers right. The model scored 270/300 — so, we’d say the model passed excellently right? but did it?
Bob noticed that the model has conveniently classified all the test data as “NO Breast Cancer”.
Bob calculated the accuracy of this model which is correct 90% all the time.
Accuracy = (TP + TN) / (TP+TN+FP+FN)Accuracy = (0 + 270) / (0 + 270 + 0 + 30)= 0.90Accuracy in % = 90%
Bob noticed a pattern, none of the “Breast Cancer” data was correctly labeled. Bob went a little further as an expert, he decided to see how the model is doing in terms of Precision and Recall.
Bob thought to himself, if none of these people who have Breast Cancer came out as “having Breast Cancer” this model isn’t a precise model and neither is it going to recall anything except “NO Breast Cancer”.
He proved this using the formula for Precision and Recall below:-
Precision = TP / (TP + FP)Precision = 0 / (0 + 0) = 0Precision in % = 0%Recall = TP / (TP + FN)Recall = 0 / (0 + 30) = 0Recall in % = 0%
What this means is that, this model will always classify any data passed into it as “NO BREAST CANCER”.
This explains why some of the patients were showing symptoms of Breast Cancer.
Hawkins Model simply did not work.
Bob cracked it, Hawkins Model is a Demogorgon (scam).
Bob proposed a slightly modified Model, he wanted them to understand what he meant by their Model being a Demogorgon.
After training his model with 70% of the data set, Bob then tested the model with the remaining 30% data to evaluate the model. Bob, unlike Hawkins software team did not rely on accuracy as the only metric to evaluate his model.
Below is the result of Bob’s Model;
Number of women with breast cancer and classified as no breast cancer (FN) = 10Number of women with breast cancer and classified as breast cancer(TP) = 20Number of women without breast cancer and classified as no breast cancer (TN) = 200Number of women without breast cancer and classified as breast cancer (FP) = 70
Clearly, Bob’s model made some mistakes by scaring 70 perfectly healthy people who don’t have Breast Cancer. **Bob thought to himself, isn’t it better to think you have Breast Cancer and not have it than to think you don’t have Breast Cancer but you’ve got it.
Accuracy = (TP + TN) / (TP + TN + FP + FN)Accuracy = (20 + 200) / (20 + 200 + 10 + 70) = 0.733Accuracy in % = 73.3%
Questions arose within the software team of Hawkins, how could Bob possibly tell them that his model ( with 73% accuracy) is better than theirs (with an accuracy of 90%.)
Bob went further to calculate Precision and Recall of his new model
Precision = TP / (TP + FP)Precision = 20 / (20 + 70) = 0.222Precision in % = 22.2%Recall = TP / (TP + FN)Recall = 20/ (20 + 10) = 0.67Recall in % = 67%
Although Bob’s model assumed 90 women instead of 30 had cancer in total, it predicted Breast Cancer correctly 22.2% of the time as opposed to Hawkins Model with Precision of 0.
Also, out of the 30 women that actually has Breast Cancer, Bob’s Model was able to correctly recall that someone has Breast Cancer 67% of the time as opposed to Hawkins Model which has 0 recall.
After this, Bob was able to convince the team that his model was better than what they currently have.
But what about the difference in Accuracy, Dustin asked?
Bob replied: it’s a Paradox.
Accuracy Paradox for Predictive Analytics states that Predictive Models with a given level of Accuracy may have greater Predictive Power than Models with higher Accuracy.
Breaking this down,
Predictive models with a given level of accuracy (73% — Bob’s Model) may have greater predictive power (higher Precision and Recall) than models with higher accuracy (90% —Hawkins Model)
And that’s why it’s called a Paradox because, intuitively, you’d expect a Model with a higher Accuracy to have been the best Model but Accuracy Paradox tells us that this, sometimes, isn’t the case.
So, for some systems (like Hawkins’) Precision and Recall are better than the “Good ol’ Accuracy” and thus it’s important to use the appropriate metrics to evaluate your model.
Bob the brain, saved the day!
** it’s important to note that trading False Positives could come at a very deadly cost as tweetypsych pointed out in the comment section.
While a search engine model could probably make do with a few false positives, a breast cancer model shouldn’t as this could lead to perfectly healthy people being introduced to a brutal treatment or worse.
— all characters inspired by ‘stranger things’. All characters are fictional as well as the story.
|
[
{
"code": null,
"e": 286,
"s": 171,
"text": "“If you don’t know anything about Machine Learning, you should definitely know Accuracy Paradox” — Akinkunle Allen"
},
{
"code": null,
"e": 363,
"s": 286,
"text": "I wrote about Model Evaluation I, If you haven’t checked it out, you should."
},
{
"code": null,
"e": 518,
"s": 363,
"text": "Accuracy is defined as the freedom from mistake or error. For example, a piece of information is accurate if it exactly represent what is being discussed."
},
{
"code": null,
"e": 625,
"s": 518,
"text": "Paradox is a statement that is seemingly contradictory or opposed to common sense and yet is perhaps true."
},
{
"code": null,
"e": 722,
"s": 625,
"text": "Have you considered that the phrase “ignore all the rules” ... is a rule itself — uhm! a paradox"
},
{
"code": null,
"e": 819,
"s": 722,
"text": "In Machine Learning lingo, Accuracy is the proportion of correctness in a classification system."
},
{
"code": null,
"e": 1053,
"s": 819,
"text": "Meaning, if we have a Spam detection system, and out of 5 mails we received, 4 were classified by a Model X as Spam and these mails were indeed Spam. We would say Model X has 80% Accuracy i.e you can rely on Model X, 80% of the time."
},
{
"code": null,
"e": 1091,
"s": 1053,
"text": "Accuracy of Model X = 4/5 * 100 = 80%"
},
{
"code": null,
"e": 1218,
"s": 1091,
"text": "So, What exactly is an Accuracy Paradox? We’ll get to that later but first let’s consider a case study as a way of an example."
},
{
"code": null,
"e": 1597,
"s": 1218,
"text": "Hawkins hospital software team (Will, Dustin, Mike and Lucas) built a classification model for diagnosing Breast Cancer in women. A sample of 1000 women were studied in a given population and 100 of them with Breast Cancer while the remaining 900 were without it. Hawkins software team trained their model based of this dataset. They split the dataset into 70/30 train/test set."
},
{
"code": null,
"e": 1653,
"s": 1597,
"text": "The accuracy was excellent and they deployed the model."
},
{
"code": null,
"e": 1821,
"s": 1653,
"text": "Alas! a couple of months after deployment, some of the women who were diagnosed by the hospital as having “no breast cancer” started showing symptoms of Breast Cancer."
},
{
"code": null,
"e": 1840,
"s": 1821,
"text": "How could this be?"
},
{
"code": null,
"e": 2030,
"s": 1840,
"text": "This raised a series of questions and fear amongst the entire population. Hawkins hospital had to do something about this as more and more patient started showing symptoms of Breast Cancer."
},
{
"code": null,
"e": 2207,
"s": 2030,
"text": "They decided to hire a Machine Learning Expert, Bob to help them understand what their software team got wrong considering the fact that the model had an accuracy of about 90%."
},
{
"code": null,
"e": 2242,
"s": 2207,
"text": "By splitting the data set, we have"
},
{
"code": null,
"e": 2256,
"s": 2242,
"text": "Training set:"
},
{
"code": null,
"e": 2326,
"s": 2256,
"text": "No Breast cancer = 70/100 * 900 = 630Breast cancer= 70/100 * 100 = 70"
},
{
"code": null,
"e": 2336,
"s": 2326,
"text": "Test set:"
},
{
"code": null,
"e": 2406,
"s": 2336,
"text": "No Breast cancer = 30/100 * 900 = 270Breast cancer= 30/100 * 100 = 30"
},
{
"code": null,
"e": 2589,
"s": 2406,
"text": "In order for Bob to explain how their model got the predictions wrong, he introduced two assumptions using one of the women, Joyce as an example- Bob began his explanation as follow,"
},
{
"code": null,
"e": 2779,
"s": 2589,
"text": "Say, we have an assumption H, that Joyce is suffering from Breast Pain and not Breast Cancer but another assumption Ho, (that counters the first) says Joyce is suffering from Breast Cancer."
},
{
"code": null,
"e": 2831,
"s": 2779,
"text": "If Assumption Ho is true (positive) — Breast Cancer"
},
{
"code": null,
"e": 2889,
"s": 2831,
"text": "else Assumption Ho is false (negative) — No Breast Cancer"
},
{
"code": null,
"e": 2973,
"s": 2889,
"text": "The table below represents what happens if this other assumption Ho is true or not."
},
{
"code": null,
"e": 2980,
"s": 2973,
"text": "Where:"
},
{
"code": null,
"e": 2999,
"s": 2980,
"text": "TP = True Positive"
},
{
"code": null,
"e": 3019,
"s": 2999,
"text": "FP = False Positive"
},
{
"code": null,
"e": 3039,
"s": 3019,
"text": "FN = False Negative"
},
{
"code": null,
"e": 3058,
"s": 3039,
"text": "TN = True Negative"
},
{
"code": null,
"e": 3268,
"s": 3058,
"text": "After training their model with 70% of the data set, Hawkins scientist tested this model with the remaining 30% data to evaluate the model for its accuracy. Their model got 270 prediction right out of the 300."
},
{
"code": null,
"e": 3303,
"s": 3268,
"text": "Hawkins Accuracy = 270 / 300 = 0.9"
},
{
"code": null,
"e": 3393,
"s": 3303,
"text": "This looked like a pretty convincing model with an accuracy of 90%, why then did it fail?"
},
{
"code": null,
"e": 3450,
"s": 3393,
"text": "Bob re-evaluated their model and below is the breakdown:"
},
{
"code": null,
"e": 3764,
"s": 3450,
"text": "Number of women with breast cancer and classified as no breast cancer (FN) = 30Number of women with breast cancer and classified as breast cancer(TP) = 0Number of women without breast cancer and classified as no breast cancer (TN) = 270Number of women without breast cancer and classified as breast cancer (FP) = "
},
{
"code": null,
"e": 3822,
"s": 3764,
"text": "Bob represented this with a confusion matrix table below."
},
{
"code": null,
"e": 3834,
"s": 3822,
"text": "In summary,"
},
{
"code": null,
"e": 4018,
"s": 3834,
"text": "Hawkins model correctly classified 270 women who do not have breast cancer as “NO Breast Cancer” while it incorrectly classified 30 women who have breast cancer as “NO Breast Cancer”."
},
{
"code": null,
"e": 4172,
"s": 4018,
"text": "We gave Hawkins Model 300 questions and it got 270 answers right. The model scored 270/300 — so, we’d say the model passed excellently right? but did it?"
},
{
"code": null,
"e": 4268,
"s": 4172,
"text": "Bob noticed that the model has conveniently classified all the test data as “NO Breast Cancer”."
},
{
"code": null,
"e": 4345,
"s": 4268,
"text": "Bob calculated the accuracy of this model which is correct 90% all the time."
},
{
"code": null,
"e": 4448,
"s": 4345,
"text": "Accuracy = (TP + TN) / (TP+TN+FP+FN)Accuracy = (0 + 270) / (0 + 270 + 0 + 30)= 0.90Accuracy in % = 90%"
},
{
"code": null,
"e": 4642,
"s": 4448,
"text": "Bob noticed a pattern, none of the “Breast Cancer” data was correctly labeled. Bob went a little further as an expert, he decided to see how the model is doing in terms of Precision and Recall."
},
{
"code": null,
"e": 4851,
"s": 4642,
"text": "Bob thought to himself, if none of these people who have Breast Cancer came out as “having Breast Cancer” this model isn’t a precise model and neither is it going to recall anything except “NO Breast Cancer”."
},
{
"code": null,
"e": 4917,
"s": 4851,
"text": "He proved this using the formula for Precision and Recall below:-"
},
{
"code": null,
"e": 5054,
"s": 4917,
"text": "Precision = TP / (TP + FP)Precision = 0 / (0 + 0) = 0Precision in % = 0%Recall = TP / (TP + FN)Recall = 0 / (0 + 30) = 0Recall in % = 0%"
},
{
"code": null,
"e": 5158,
"s": 5054,
"text": "What this means is that, this model will always classify any data passed into it as “NO BREAST CANCER”."
},
{
"code": null,
"e": 5237,
"s": 5158,
"text": "This explains why some of the patients were showing symptoms of Breast Cancer."
},
{
"code": null,
"e": 5272,
"s": 5237,
"text": "Hawkins Model simply did not work."
},
{
"code": null,
"e": 5326,
"s": 5272,
"text": "Bob cracked it, Hawkins Model is a Demogorgon (scam)."
},
{
"code": null,
"e": 5444,
"s": 5326,
"text": "Bob proposed a slightly modified Model, he wanted them to understand what he meant by their Model being a Demogorgon."
},
{
"code": null,
"e": 5673,
"s": 5444,
"text": "After training his model with 70% of the data set, Bob then tested the model with the remaining 30% data to evaluate the model. Bob, unlike Hawkins software team did not rely on accuracy as the only metric to evaluate his model."
},
{
"code": null,
"e": 5709,
"s": 5673,
"text": "Below is the result of Bob’s Model;"
},
{
"code": null,
"e": 6026,
"s": 5709,
"text": "Number of women with breast cancer and classified as no breast cancer (FN) = 10Number of women with breast cancer and classified as breast cancer(TP) = 20Number of women without breast cancer and classified as no breast cancer (TN) = 200Number of women without breast cancer and classified as breast cancer (FP) = 70"
},
{
"code": null,
"e": 6287,
"s": 6026,
"text": "Clearly, Bob’s model made some mistakes by scaring 70 perfectly healthy people who don’t have Breast Cancer. **Bob thought to himself, isn’t it better to think you have Breast Cancer and not have it than to think you don’t have Breast Cancer but you’ve got it."
},
{
"code": null,
"e": 6403,
"s": 6287,
"text": "Accuracy = (TP + TN) / (TP + TN + FP + FN)Accuracy = (20 + 200) / (20 + 200 + 10 + 70) = 0.733Accuracy in % = 73.3%"
},
{
"code": null,
"e": 6574,
"s": 6403,
"text": "Questions arose within the software team of Hawkins, how could Bob possibly tell them that his model ( with 73% accuracy) is better than theirs (with an accuracy of 90%.)"
},
{
"code": null,
"e": 6642,
"s": 6574,
"text": "Bob went further to calculate Precision and Recall of his new model"
},
{
"code": null,
"e": 6794,
"s": 6642,
"text": "Precision = TP / (TP + FP)Precision = 20 / (20 + 70) = 0.222Precision in % = 22.2%Recall = TP / (TP + FN)Recall = 20/ (20 + 10) = 0.67Recall in % = 67%"
},
{
"code": null,
"e": 6971,
"s": 6794,
"text": "Although Bob’s model assumed 90 women instead of 30 had cancer in total, it predicted Breast Cancer correctly 22.2% of the time as opposed to Hawkins Model with Precision of 0."
},
{
"code": null,
"e": 7166,
"s": 6971,
"text": "Also, out of the 30 women that actually has Breast Cancer, Bob’s Model was able to correctly recall that someone has Breast Cancer 67% of the time as opposed to Hawkins Model which has 0 recall."
},
{
"code": null,
"e": 7269,
"s": 7166,
"text": "After this, Bob was able to convince the team that his model was better than what they currently have."
},
{
"code": null,
"e": 7326,
"s": 7269,
"text": "But what about the difference in Accuracy, Dustin asked?"
},
{
"code": null,
"e": 7355,
"s": 7326,
"text": "Bob replied: it’s a Paradox."
},
{
"code": null,
"e": 7526,
"s": 7355,
"text": "Accuracy Paradox for Predictive Analytics states that Predictive Models with a given level of Accuracy may have greater Predictive Power than Models with higher Accuracy."
},
{
"code": null,
"e": 7546,
"s": 7526,
"text": "Breaking this down,"
},
{
"code": null,
"e": 7733,
"s": 7546,
"text": "Predictive models with a given level of accuracy (73% — Bob’s Model) may have greater predictive power (higher Precision and Recall) than models with higher accuracy (90% —Hawkins Model)"
},
{
"code": null,
"e": 7932,
"s": 7733,
"text": "And that’s why it’s called a Paradox because, intuitively, you’d expect a Model with a higher Accuracy to have been the best Model but Accuracy Paradox tells us that this, sometimes, isn’t the case."
},
{
"code": null,
"e": 8109,
"s": 7932,
"text": "So, for some systems (like Hawkins’) Precision and Recall are better than the “Good ol’ Accuracy” and thus it’s important to use the appropriate metrics to evaluate your model."
},
{
"code": null,
"e": 8139,
"s": 8109,
"text": "Bob the brain, saved the day!"
},
{
"code": null,
"e": 8278,
"s": 8139,
"text": "** it’s important to note that trading False Positives could come at a very deadly cost as tweetypsych pointed out in the comment section."
},
{
"code": null,
"e": 8485,
"s": 8278,
"text": "While a search engine model could probably make do with a few false positives, a breast cancer model shouldn’t as this could lead to perfectly healthy people being introduced to a brutal treatment or worse."
}
] |
PyQt - QInputDialog Widget
|
This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter.
The user input can be a number, a string or an item from the list. A label prompting the user what he should do is also displayed.
The QInputDialog class has the following static methods to accept input from the user −
getInt()
Creates a spinner box for integer number
getDouble()
Spinner box with floating point number can be input
getText()
A simple line edit field to type text
getItem()
A combo box from which user can choose item
The following example implements the input dialog functionality. The top level window has three buttons. Their clicked() signal pops up InputDialog through connected slots.
items = ("C", "C++", "Java", "Python")
item, ok = QInputDialog.getItem(self, "select input dialog",
"list of languages", items, 0, False)
if ok and item:
self.le.setText(item)
def gettext(self):
text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
if ok:
self.le1.setText(str(text))
def getint(self):
num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
if ok:
self.le2.setText(str(num))
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class inputdialogdemo(QWidget):
def __init__(self, parent = None):
super(inputdialogdemo, self).__init__(parent)
layout = QFormLayout()
self.btn = QPushButton("Choose from list")
self.btn.clicked.connect(self.getItem)
self.le = QLineEdit()
layout.addRow(self.btn,self.le)
self.btn1 = QPushButton("get name")
self.btn1.clicked.connect(self.gettext)
self.le1 = QLineEdit()
layout.addRow(self.btn1,self.le1)
self.btn2 = QPushButton("Enter an integer")
self.btn2.clicked.connect(self.getint)
self.le2 = QLineEdit()
layout.addRow(self.btn2,self.le2)
self.setLayout(layout)
self.setWindowTitle("Input Dialog demo")
def getItem(self):
items = ("C", "C++", "Java", "Python")
item, ok = QInputDialog.getItem(self, "select input dialog",
"list of languages", items, 0, False)
if ok and item:
self.le.setText(item)
def gettext(self):
text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
if ok:
self.le1.setText(str(text))
def getint(self):
num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
if ok:
self.le2.setText(str(num))
def main():
app = QApplication(sys.argv)
ex = inputdialogdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2113,
"s": 1926,
"text": "This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter."
},
{
"code": null,
"e": 2244,
"s": 2113,
"text": "The user input can be a number, a string or an item from the list. A label prompting the user what he should do is also displayed."
},
{
"code": null,
"e": 2332,
"s": 2244,
"text": "The QInputDialog class has the following static methods to accept input from the user −"
},
{
"code": null,
"e": 2341,
"s": 2332,
"text": "getInt()"
},
{
"code": null,
"e": 2382,
"s": 2341,
"text": "Creates a spinner box for integer number"
},
{
"code": null,
"e": 2394,
"s": 2382,
"text": "getDouble()"
},
{
"code": null,
"e": 2446,
"s": 2394,
"text": "Spinner box with floating point number can be input"
},
{
"code": null,
"e": 2456,
"s": 2446,
"text": "getText()"
},
{
"code": null,
"e": 2494,
"s": 2456,
"text": "A simple line edit field to type text"
},
{
"code": null,
"e": 2504,
"s": 2494,
"text": "getItem()"
},
{
"code": null,
"e": 2548,
"s": 2504,
"text": "A combo box from which user can choose item"
},
{
"code": null,
"e": 2721,
"s": 2548,
"text": "The following example implements the input dialog functionality. The top level window has three buttons. Their clicked() signal pops up InputDialog through connected slots."
},
{
"code": null,
"e": 3231,
"s": 2721,
"text": "items = (\"C\", \"C++\", \"Java\", \"Python\")\n\nitem, ok = QInputDialog.getItem(self, \"select input dialog\", \n \"list of languages\", items, 0, False)\n\t\n if ok and item:\n self.le.setText(item)\n\t\t\n def gettext(self):\n text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')\n if ok:\n self.le1.setText(str(text))\n\t\t\t\n def getint(self):\n num,ok = QInputDialog.getInt(self,\"integer input dualog\",\"enter a number\")\n\t\t\n if ok:\n self.le2.setText(str(num))"
},
{
"code": null,
"e": 3265,
"s": 3231,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 4769,
"s": 3265,
"text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass inputdialogdemo(QWidget):\n def __init__(self, parent = None):\n super(inputdialogdemo, self).__init__(parent)\n\t\t\n layout = QFormLayout()\n self.btn = QPushButton(\"Choose from list\")\n self.btn.clicked.connect(self.getItem)\n\t\t\n self.le = QLineEdit()\n layout.addRow(self.btn,self.le)\n self.btn1 = QPushButton(\"get name\")\n self.btn1.clicked.connect(self.gettext)\n\t\t\n self.le1 = QLineEdit()\n layout.addRow(self.btn1,self.le1)\n self.btn2 = QPushButton(\"Enter an integer\")\n self.btn2.clicked.connect(self.getint)\n\t\t\n self.le2 = QLineEdit()\n layout.addRow(self.btn2,self.le2)\n self.setLayout(layout)\n self.setWindowTitle(\"Input Dialog demo\")\n\t\t\n def getItem(self):\n items = (\"C\", \"C++\", \"Java\", \"Python\")\n\t\t\n item, ok = QInputDialog.getItem(self, \"select input dialog\", \n \"list of languages\", items, 0, False)\n\t\t\t\n if ok and item:\n self.le.setText(item)\n\t\t\t\n def gettext(self):\n text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')\n\t\t\n if ok:\n self.le1.setText(str(text))\n\t\t\t\n def getint(self):\n num,ok = QInputDialog.getInt(self,\"integer input dualog\",\"enter a number\")\n\t\t\n if ok:\n self.le2.setText(str(num))\n\t\t\t\ndef main(): \n app = QApplication(sys.argv)\n ex = inputdialogdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 4816,
"s": 4769,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4853,
"s": 4816,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4863,
"s": 4853,
"text": " ALAA EID"
},
{
"code": null,
"e": 4870,
"s": 4863,
"text": " Print"
},
{
"code": null,
"e": 4881,
"s": 4870,
"text": " Add Notes"
}
] |
Precision on a number format in Java
|
You can include a precision specifier to the following format specifiers −
%f
%e
%g
%s
On floating point, the number of decimal places is known.
Let’s say we declared a Formatter object −
Formatter f1 = new Formatter();
Now, we want 3 decimal places. For that, use 1.3f −
f1.format("%1.3f", 29292929.98765432);
The above will return the number with 3 decimal places −
29292929.988
The following is the final example −
Live Demo
import java.util.Formatter;
public class Demo {
public static void main(String args[]) {
Formatter f1, f2, f3;
f1 = new Formatter();
f1.format("%1.3f", 29292929.98765432);
System.out.println(f1);
f2 = new Formatter();
f2.format("%1.7f", 29292929.98765432);
System.out.println(f2);
f3 = new Formatter();
f3.format("%1.9f", 29292929.98765432);
System.out.println(f3);
}
}
29292929.988
29292929.9876543
292929.987654320
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "You can include a precision specifier to the following format specifiers −"
},
{
"code": null,
"e": 1149,
"s": 1137,
"text": "%f\n%e\n%g\n%s"
},
{
"code": null,
"e": 1207,
"s": 1149,
"text": "On floating point, the number of decimal places is known."
},
{
"code": null,
"e": 1250,
"s": 1207,
"text": "Let’s say we declared a Formatter object −"
},
{
"code": null,
"e": 1282,
"s": 1250,
"text": "Formatter f1 = new Formatter();"
},
{
"code": null,
"e": 1334,
"s": 1282,
"text": "Now, we want 3 decimal places. For that, use 1.3f −"
},
{
"code": null,
"e": 1373,
"s": 1334,
"text": "f1.format(\"%1.3f\", 29292929.98765432);"
},
{
"code": null,
"e": 1430,
"s": 1373,
"text": "The above will return the number with 3 decimal places −"
},
{
"code": null,
"e": 1443,
"s": 1430,
"text": "29292929.988"
},
{
"code": null,
"e": 1480,
"s": 1443,
"text": "The following is the final example −"
},
{
"code": null,
"e": 1491,
"s": 1480,
"text": " Live Demo"
},
{
"code": null,
"e": 1939,
"s": 1491,
"text": "import java.util.Formatter;\npublic class Demo {\n public static void main(String args[]) {\n Formatter f1, f2, f3;\n f1 = new Formatter();\n f1.format(\"%1.3f\", 29292929.98765432);\n System.out.println(f1);\n f2 = new Formatter();\n f2.format(\"%1.7f\", 29292929.98765432);\n System.out.println(f2);\n f3 = new Formatter();\n f3.format(\"%1.9f\", 29292929.98765432);\n System.out.println(f3);\n }\n}"
},
{
"code": null,
"e": 1986,
"s": 1939,
"text": "29292929.988\n29292929.9876543\n292929.987654320"
}
] |
Sorting Tricks in Node.js - GeeksforGeeks
|
26 Aug, 2020
Sorting an array using the timer class:
Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements.
Now here, we can use setInterval() method to visit all those elements, and perform those operations. And during the visit, we can use setTimer() method to visit all elements, and print the minimum of the array during that period of time.
The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() method of JavaScript API, however, a string of code can’t be passed to get it executed.
Syntax:
setInterval(timerFunction, millisecondsTime);
Parameters: It accepts two parameters which are mentioned above and described below:
timerFunction <function>: It is the function to be executed.
millisecondsTime <Time>: It indicates a period of time between each execution.
The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed.
Syntax:
setTimeout(timerFunction, millisecondsTime);
Parameter: It accepts two parameters which are mentioned above and described below:
timerFunction <function>: It is the function to be executed.
millisecondsTime <Time>: It indicates a period of time between each execution.
Examples:
Input: Array = [ 46, 55, 2, 100, 0, 500 ]
Output: [0, 2, 46, 55, 100, 500]
Input: Array = [8, 9, 2, 7, 18, 5, 25]
Output: [ 2, 5, 7, 8, 9, 18, 25 ]
Example 1: File Name: Index.js
const arr = [10, 50, 100, 500, 0, 200];var arr1 = []; function sortIt() {for (let i of arr) { // setTimeout(()=> console.log(i), i) setTimeout(()=> { arr1.push(i); arr.splice(arr.indexOf(i), 1); if(arr.length === 0){ console.log(arr1); } }, i)}} sortIt();
Output:
[ 0, 10, 50, 100, 200, 500 ]
Example 2: File Name: Index.js
const arr = [10, 50, 100, 500, 0, 200];var arr1 = []; function sortIt() { for (let i of arr) { // setTimeout(()=> console.log(i), i) setTimeout(()=> { arr1.push(i); i = Math.max.apply(null, arr); // arr.splice(arr.indexOf(i), 1); if(arr1.length === arr.length) { console.log(arr1); } }, i)}} sortIt();
Run Index.js File using the below command.
node index.js
Output:
[ 0, 10, 50, 100, 200, 500 ]
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
JavaScript | console.log() with Examples
Installation of Node.js on Linux
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
|
[
{
"code": null,
"e": 25004,
"s": 24976,
"text": "\n26 Aug, 2020"
},
{
"code": null,
"e": 25044,
"s": 25004,
"text": "Sorting an array using the timer class:"
},
{
"code": null,
"e": 25183,
"s": 25044,
"text": "Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements."
},
{
"code": null,
"e": 25421,
"s": 25183,
"text": "Now here, we can use setInterval() method to visit all those elements, and perform those operations. And during the visit, we can use setTimer() method to visit all elements, and print the minimum of the array during that period of time."
},
{
"code": null,
"e": 25648,
"s": 25421,
"text": "The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() method of JavaScript API, however, a string of code can’t be passed to get it executed."
},
{
"code": null,
"e": 25656,
"s": 25648,
"text": "Syntax:"
},
{
"code": null,
"e": 25702,
"s": 25656,
"text": "setInterval(timerFunction, millisecondsTime);"
},
{
"code": null,
"e": 25787,
"s": 25702,
"text": "Parameters: It accepts two parameters which are mentioned above and described below:"
},
{
"code": null,
"e": 25848,
"s": 25787,
"text": "timerFunction <function>: It is the function to be executed."
},
{
"code": null,
"e": 25927,
"s": 25848,
"text": "millisecondsTime <Time>: It indicates a period of time between each execution."
},
{
"code": null,
"e": 26167,
"s": 25927,
"text": "The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed."
},
{
"code": null,
"e": 26175,
"s": 26167,
"text": "Syntax:"
},
{
"code": null,
"e": 26220,
"s": 26175,
"text": "setTimeout(timerFunction, millisecondsTime);"
},
{
"code": null,
"e": 26304,
"s": 26220,
"text": "Parameter: It accepts two parameters which are mentioned above and described below:"
},
{
"code": null,
"e": 26365,
"s": 26304,
"text": "timerFunction <function>: It is the function to be executed."
},
{
"code": null,
"e": 26444,
"s": 26365,
"text": "millisecondsTime <Time>: It indicates a period of time between each execution."
},
{
"code": null,
"e": 26454,
"s": 26444,
"text": "Examples:"
},
{
"code": null,
"e": 26603,
"s": 26454,
"text": "Input: Array = [ 46, 55, 2, 100, 0, 500 ]\nOutput: [0, 2, 46, 55, 100, 500]\n\nInput: Array = [8, 9, 2, 7, 18, 5, 25]\nOutput: [ 2, 5, 7, 8, 9, 18, 25 ]"
},
{
"code": null,
"e": 26634,
"s": 26603,
"text": "Example 1: File Name: Index.js"
},
{
"code": "const arr = [10, 50, 100, 500, 0, 200];var arr1 = []; function sortIt() {for (let i of arr) { // setTimeout(()=> console.log(i), i) setTimeout(()=> { arr1.push(i); arr.splice(arr.indexOf(i), 1); if(arr.length === 0){ console.log(arr1); } }, i)}} sortIt();",
"e": 26913,
"s": 26634,
"text": null
},
{
"code": null,
"e": 26921,
"s": 26913,
"text": "Output:"
},
{
"code": null,
"e": 26950,
"s": 26921,
"text": "[ 0, 10, 50, 100, 200, 500 ]"
},
{
"code": null,
"e": 26981,
"s": 26950,
"text": "Example 2: File Name: Index.js"
},
{
"code": "const arr = [10, 50, 100, 500, 0, 200];var arr1 = []; function sortIt() { for (let i of arr) { // setTimeout(()=> console.log(i), i) setTimeout(()=> { arr1.push(i); i = Math.max.apply(null, arr); // arr.splice(arr.indexOf(i), 1); if(arr1.length === arr.length) { console.log(arr1); } }, i)}} sortIt();",
"e": 27359,
"s": 26981,
"text": null
},
{
"code": null,
"e": 27402,
"s": 27359,
"text": "Run Index.js File using the below command."
},
{
"code": null,
"e": 27416,
"s": 27402,
"text": "node index.js"
},
{
"code": null,
"e": 27424,
"s": 27416,
"text": "Output:"
},
{
"code": null,
"e": 27453,
"s": 27424,
"text": "[ 0, 10, 50, 100, 200, 500 ]"
},
{
"code": null,
"e": 27466,
"s": 27453,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 27477,
"s": 27466,
"text": "JavaScript"
},
{
"code": null,
"e": 27485,
"s": 27477,
"text": "Node.js"
},
{
"code": null,
"e": 27502,
"s": 27485,
"text": "Web Technologies"
},
{
"code": null,
"e": 27600,
"s": 27502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27609,
"s": 27600,
"text": "Comments"
},
{
"code": null,
"e": 27622,
"s": 27609,
"text": "Old Comments"
},
{
"code": null,
"e": 27683,
"s": 27622,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27755,
"s": 27683,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27800,
"s": 27755,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27842,
"s": 27800,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 27883,
"s": 27842,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 27916,
"s": 27883,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27953,
"s": 27916,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28001,
"s": 27953,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28034,
"s": 28001,
"text": "Node.js fs.readFileSync() Method"
}
] |
Count the occurrence of Nth term in first N terms of Van Eck's sequence - GeeksforGeeks
|
07 Feb, 2020
Prerequisite: Van Eck’s sequence
Given a positive integer N, the task is to count the occurrences of Nth term in first N terms of Van Eck’s sequence.
Examples:
Input: N = 5Output: 1Explanation:First 5 terms of Van Eck’s Sequence 0, 0, 1, 0, 2Occurrence of 5th term i.e 2 = 1
Input: 11Output: 5Explanation:First 11 terms of Van Eck’s Sequence 0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0,Occurrence of 11th term i.e 0 is 5
Naive Approach:Generate Van Eck’s sequence upto Nth termIterate through the generated sequence and count the occurrence of Nth term.To serve multiple queries we can pre-compute the Van Eck’s sequence.Below is the implementation of above approach:C++JavaPython3C#C++// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1
5
Efficient Approach:For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term.So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop.Below is the implementation of above approach:CPPJavaPython3C#CPP// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1
5
Naive Approach:Generate Van Eck’s sequence upto Nth termIterate through the generated sequence and count the occurrence of Nth term.To serve multiple queries we can pre-compute the Van Eck’s sequence.Below is the implementation of above approach:C++JavaPython3C#C++// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1
5
Generate Van Eck’s sequence upto Nth term
Iterate through the generated sequence and count the occurrence of Nth term.
To serve multiple queries we can pre-compute the Van Eck’s sequence.
Below is the implementation of above approach:
C++
Java
Python3
C#
// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}
// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}
# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01
// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}
1
5
Efficient Approach:For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term.So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop.Below is the implementation of above approach:CPPJavaPython3C#CPP// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1
5
For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term.
So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:
Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:
Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop.
Let us consider Nth term of the sequence as SN
If SN+1 is non-zero then increment countand do the same for (N- SN+1)th term
And if SN+1 is zero then stop.
Below is the implementation of above approach:
CPP
Java
Python3
C#
// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}
// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}
# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01
// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}
1
5
ankthon
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Modulo 10^9+7 (1000000007)
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 24661,
"s": 24633,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 24694,
"s": 24661,
"text": "Prerequisite: Van Eck’s sequence"
},
{
"code": null,
"e": 24811,
"s": 24694,
"text": "Given a positive integer N, the task is to count the occurrences of Nth term in first N terms of Van Eck’s sequence."
},
{
"code": null,
"e": 24821,
"s": 24811,
"text": "Examples:"
},
{
"code": null,
"e": 24936,
"s": 24821,
"text": "Input: N = 5Output: 1Explanation:First 5 terms of Van Eck’s Sequence 0, 0, 1, 0, 2Occurrence of 5th term i.e 2 = 1"
},
{
"code": null,
"e": 25070,
"s": 24936,
"text": "Input: 11Output: 5Explanation:First 11 terms of Van Eck’s Sequence 0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0,Occurrence of 11th term i.e 0 is 5"
},
{
"code": null,
"e": 40169,
"s": 25070,
"text": "Naive Approach:Generate Van Eck’s sequence upto Nth termIterate through the generated sequence and count the occurrence of Nth term.To serve multiple queries we can pre-compute the Van Eck’s sequence.Below is the implementation of above approach:C++JavaPython3C#C++// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1\n5\nEfficient Approach:For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term.So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop.Below is the implementation of above approach:CPPJavaPython3C#CPP// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1\n5\n"
},
{
"code": null,
"e": 47396,
"s": 40169,
"text": "Naive Approach:Generate Van Eck’s sequence upto Nth termIterate through the generated sequence and count the occurrence of Nth term.To serve multiple queries we can pre-compute the Van Eck’s sequence.Below is the implementation of above approach:C++JavaPython3C#C++// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1\n5\n"
},
{
"code": null,
"e": 47438,
"s": 47396,
"text": "Generate Van Eck’s sequence upto Nth term"
},
{
"code": null,
"e": 47515,
"s": 47438,
"text": "Iterate through the generated sequence and count the occurrence of Nth term."
},
{
"code": null,
"e": 47584,
"s": 47515,
"text": "To serve multiple queries we can pre-compute the Van Eck’s sequence."
},
{
"code": null,
"e": 47631,
"s": 47584,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 47635,
"s": 47631,
"text": "C++"
},
{
"code": null,
"e": 47640,
"s": 47635,
"text": "Java"
},
{
"code": null,
"e": 47648,
"s": 47640,
"text": "Python3"
},
{
"code": null,
"e": 47651,
"s": 47648,
"text": "C#"
},
{
"code": "// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}",
"e": 49301,
"s": 47651,
"text": null
},
{
"code": "// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}",
"e": 51208,
"s": 49301,
"text": null
},
{
"code": "# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0]*(MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range(i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Get nth term of the sequence nthTerm = sequence[n - 1]; count = 0; # Count the occurrence of nth term # in first n terms of the sequence for i in range(n) : if (sequence[i] == nthTerm) : count += 1; # Return count return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); # This code is contributed by AnkitRai01",
"e": 52689,
"s": 51208,
"text": null
},
{
"code": "// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Get nth term of the sequence int nthTerm = sequence[n - 1]; int count = 0; // Count the occurrence of nth term // in first n terms of the sequence for (int i = 0; i < n; i++) { if (sequence[i] == nthTerm) count++; } // Return count return count; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}",
"e": 54592,
"s": 52689,
"text": null
},
{
"code": null,
"e": 54597,
"s": 54592,
"text": "1\n5\n"
},
{
"code": null,
"e": 62470,
"s": 54597,
"text": "Efficient Approach:For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term.So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop.Below is the implementation of above approach:CPPJavaPython3C#CPP// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}Java// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}Python3# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01C#// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}Output:1\n5\n"
},
{
"code": null,
"e": 62590,
"s": 62470,
"text": "For a given term in Van Eck’s sequence, its next term indicates the distance between last occurrence of the given term."
},
{
"code": null,
"e": 62681,
"s": 62590,
"text": "So, for ith term, its previous occurrence will be at i – value (i + 1)th term.For example:"
},
{
"code": null,
"e": 62792,
"s": 62681,
"text": "Also, if the next term in the sequence is 0 then this means that the term has not occurred before.For example:"
},
{
"code": null,
"e": 62955,
"s": 62792,
"text": "Algorithm:Let us consider Nth term of the sequence as SNIf SN+1 is non-zero then increment countand do the same for (N- SN+1)th termAnd if SN+1 is zero then stop."
},
{
"code": null,
"e": 63002,
"s": 62955,
"text": "Let us consider Nth term of the sequence as SN"
},
{
"code": null,
"e": 63079,
"s": 63002,
"text": "If SN+1 is non-zero then increment countand do the same for (N- SN+1)th term"
},
{
"code": null,
"e": 63110,
"s": 63079,
"text": "And if SN+1 is zero then stop."
},
{
"code": null,
"e": 63157,
"s": 63110,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 63161,
"s": 63157,
"text": "CPP"
},
{
"code": null,
"e": 63166,
"s": 63161,
"text": "Java"
},
{
"code": null,
"e": 63174,
"s": 63166,
"text": "Python3"
},
{
"code": null,
"e": 63177,
"s": 63174,
"text": "C#"
},
{
"code": "// C++ program to count the occurrence// of nth term in first n terms// of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 100000int sequence[MAX + 1]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } }} // Utility function to count// the occurrence of nth term// in first n terms of the sequenceint getCount(int n){ // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count;} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence cout << getCount(n) << endl; return 0;}",
"e": 64901,
"s": 63177,
"text": null
},
{
"code": "// Java program to count the occurrence// of nth term in first n terms// of Van Eck's sequence class GFG { static int MAX = 100000; static int sequence[] = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence System.out.println(getCount(n)); }}",
"e": 66888,
"s": 64901,
"text": null
},
{
"code": "# Python3 program to count the occurrence # of nth term in first n terms # of Van Eck's sequence MAX = 10000sequence = [0] * (MAX + 1); # Utility function to compute # Van Eck's sequence def vanEckSequence() : # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occured # previously or is new to sequence for j in range( i - 1, -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occured previously sequence[i + 1] = i - j; break; # Utility function to count # the occurrence of nth term # in first n terms of the sequence def getCount(n) : # Initialize count as 1 count = 1; i = n - 1; while (sequence[i + 1] != 0) : # Increment count if (i+1)th term # is non-zero count += 1; # Previous occurrence of sequence[i] # will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; # Return the count of occurrence return count; # Driver code if __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 5; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)); n = 11; # Print count of the occurrence of nth term # in first n terms of the sequence print(getCount(n)) ; # This code is contributed by AnkitRai01",
"e": 68468,
"s": 66888,
"text": null
},
{
"code": "// C# program to count the occurrence// of nth term in first n terms// of Van Eck's sequence using System;class GFG { static int MAX = 100000; static int[] sequence = new int[MAX + 1]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occured // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occured previously sequence[i + 1] = i - j; break; } } } } // Utility function to count // the occurrence of nth term // in first n terms of the sequence static int getCount(int n) { // Initialize count as 1 int count = 1; int i = n - 1; while (sequence[i + 1] != 0) { // Increment count if (i+1)th term // is non-zero count++; // Previous occurrence of sequence[i] // will be it (i - sequence[i+1])th position i = i - sequence[i + 1]; } // Return the count of occurrence return count; } // Driver code public static void Main(string[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 5; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); n = 11; // Print count of the occurrence of nth term // in first n terms of the sequence Console.WriteLine(getCount(n)); }}",
"e": 70464,
"s": 68468,
"text": null
},
{
"code": null,
"e": 70469,
"s": 70464,
"text": "1\n5\n"
},
{
"code": null,
"e": 70477,
"s": 70469,
"text": "ankthon"
},
{
"code": null,
"e": 70490,
"s": 70477,
"text": "Mathematical"
},
{
"code": null,
"e": 70503,
"s": 70490,
"text": "Mathematical"
},
{
"code": null,
"e": 70601,
"s": 70503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 70610,
"s": 70601,
"text": "Comments"
},
{
"code": null,
"e": 70623,
"s": 70610,
"text": "Old Comments"
},
{
"code": null,
"e": 70647,
"s": 70623,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 70661,
"s": 70647,
"text": "Prime Numbers"
},
{
"code": null,
"e": 70704,
"s": 70661,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 70745,
"s": 70704,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 70790,
"s": 70745,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 70817,
"s": 70790,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 70866,
"s": 70817,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 70909,
"s": 70866,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 70943,
"s": 70909,
"text": "Program for factorial of a number"
}
] |
How to change Seaborn legends font size, location and color? - GeeksforGeeks
|
27 Oct, 2021
Seaborn is a library for making statistical graphics on top of matplotlib with pandas data structures in python. Seaborn legend is the dialog box which is located on the graph which includes the description of the different attributes with their respected colors in the graph. We can easily change the properties of the seaborn legend including font size, location, background colour, and many others.
Here, We will learn about the way to change the font size, location, and the color of seaborn legend.
To change the font size of Seaborn legends there are two different ways which are listed as follows:
Using matplotlib.pyplot.setp() function from matplotlib library.Using matplotlib.pyplot.legend() function from matplotlib library.
Using matplotlib.pyplot.setp() function from matplotlib library.
Using matplotlib.pyplot.legend() function from matplotlib library.
Using matplotlib.pyplot.setp() function from matplotlib library:
With the help of this method, the user can easily change the font size of the seaborn legends by specifying the particular font size, graph, and subject(whether the user has to change the font size of the text of the title in the legends.
Python3
# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style("whitegrid") # load datasettips = sns.load_dataset("tips") # depict illustrationgfg = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True) # for legend textplt.setp(gfg.get_legend().get_texts(), fontsize='10') # for legend titleplt.setp(gfg.get_legend().get_title(), fontsize='20') plt.show()
Output:
Using matplotlib.pyplot.legend() function from matplotlib library:-
This is one of the easiest methods to change the font size of any Seaborn legends, in this we just have to pass the parameter of the fontsize which allows us to pass the font-size value and it will change the font size.
Python3
# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style("whitegrid") # load datasettips = sns.load_dataset("tips") # depict illustrationgfg = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True)gfg.legend(fontsize=5)plt.show()
Output:
We use matplotlib.pyplot.legend() function from matplotlib library and pass the bbox_to_anchor parameter which allows us to pass an (x,y) tuple with the required offset for changing the location of the seaborn legends.
Python3
# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style("whitegrid") # load datasettips = sns.load_dataset("tips") # depict illustrationfg = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True) # to change the legends locationgfg.legend(bbox_to_anchor= (1.2,1))plt.show()
Output:
Just with the use of matplotlib.pyplot.set_facecolor() function from matplotlib library and pass the name of the color user want to in the seaborn legends.
Python3
# import modulesimport matplotlib.pyplot as pltimport numpy as np # depict illustrationg = np.random.rand(20,1)plt.plot(g, label='gfg')legend = plt.legend()frame = legend.get_frame()frame.set_facecolor('green')plt.show()
Output:
gabaa406
simmytarika5
sagar0719kumar
Picked
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 23929,
"s": 23901,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 24331,
"s": 23929,
"text": "Seaborn is a library for making statistical graphics on top of matplotlib with pandas data structures in python. Seaborn legend is the dialog box which is located on the graph which includes the description of the different attributes with their respected colors in the graph. We can easily change the properties of the seaborn legend including font size, location, background colour, and many others."
},
{
"code": null,
"e": 24433,
"s": 24331,
"text": "Here, We will learn about the way to change the font size, location, and the color of seaborn legend."
},
{
"code": null,
"e": 24534,
"s": 24433,
"text": "To change the font size of Seaborn legends there are two different ways which are listed as follows:"
},
{
"code": null,
"e": 24665,
"s": 24534,
"text": "Using matplotlib.pyplot.setp() function from matplotlib library.Using matplotlib.pyplot.legend() function from matplotlib library."
},
{
"code": null,
"e": 24730,
"s": 24665,
"text": "Using matplotlib.pyplot.setp() function from matplotlib library."
},
{
"code": null,
"e": 24797,
"s": 24730,
"text": "Using matplotlib.pyplot.legend() function from matplotlib library."
},
{
"code": null,
"e": 24862,
"s": 24797,
"text": "Using matplotlib.pyplot.setp() function from matplotlib library:"
},
{
"code": null,
"e": 25101,
"s": 24862,
"text": "With the help of this method, the user can easily change the font size of the seaborn legends by specifying the particular font size, graph, and subject(whether the user has to change the font size of the text of the title in the legends."
},
{
"code": null,
"e": 25109,
"s": 25101,
"text": "Python3"
},
{
"code": "# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style(\"whitegrid\") # load datasettips = sns.load_dataset(\"tips\") # depict illustrationgfg = sns.stripplot(x=\"sex\", y=\"total_bill\", hue=\"day\", data=tips, jitter=True) # for legend textplt.setp(gfg.get_legend().get_texts(), fontsize='10') # for legend titleplt.setp(gfg.get_legend().get_title(), fontsize='20') plt.show()",
"e": 25524,
"s": 25109,
"text": null
},
{
"code": null,
"e": 25532,
"s": 25524,
"text": "Output:"
},
{
"code": null,
"e": 25600,
"s": 25532,
"text": "Using matplotlib.pyplot.legend() function from matplotlib library:-"
},
{
"code": null,
"e": 25820,
"s": 25600,
"text": "This is one of the easiest methods to change the font size of any Seaborn legends, in this we just have to pass the parameter of the fontsize which allows us to pass the font-size value and it will change the font size."
},
{
"code": null,
"e": 25828,
"s": 25820,
"text": "Python3"
},
{
"code": "# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style(\"whitegrid\") # load datasettips = sns.load_dataset(\"tips\") # depict illustrationgfg = sns.stripplot(x=\"sex\", y=\"total_bill\", hue=\"day\", data=tips, jitter=True)gfg.legend(fontsize=5)plt.show()",
"e": 26120,
"s": 25828,
"text": null
},
{
"code": null,
"e": 26128,
"s": 26120,
"text": "Output:"
},
{
"code": null,
"e": 26347,
"s": 26128,
"text": "We use matplotlib.pyplot.legend() function from matplotlib library and pass the bbox_to_anchor parameter which allows us to pass an (x,y) tuple with the required offset for changing the location of the seaborn legends."
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Python3"
},
{
"code": "# import modulesimport seaborn as snsimport matplotlib.pylab as pltsns.set_style(\"whitegrid\") # load datasettips = sns.load_dataset(\"tips\") # depict illustrationfg = sns.stripplot(x=\"sex\", y=\"total_bill\", hue=\"day\", data=tips, jitter=True) # to change the legends locationgfg.legend(bbox_to_anchor= (1.2,1))plt.show()",
"e": 26691,
"s": 26355,
"text": null
},
{
"code": null,
"e": 26702,
"s": 26694,
"text": "Output:"
},
{
"code": null,
"e": 26862,
"s": 26706,
"text": "Just with the use of matplotlib.pyplot.set_facecolor() function from matplotlib library and pass the name of the color user want to in the seaborn legends."
},
{
"code": null,
"e": 26872,
"s": 26864,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.pyplot as pltimport numpy as np # depict illustrationg = np.random.rand(20,1)plt.plot(g, label='gfg')legend = plt.legend()frame = legend.get_frame()frame.set_facecolor('green')plt.show()",
"e": 27093,
"s": 26872,
"text": null
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Output:"
},
{
"code": null,
"e": 27110,
"s": 27101,
"text": "gabaa406"
},
{
"code": null,
"e": 27123,
"s": 27110,
"text": "simmytarika5"
},
{
"code": null,
"e": 27138,
"s": 27123,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27145,
"s": 27138,
"text": "Picked"
},
{
"code": null,
"e": 27160,
"s": 27145,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 27167,
"s": 27160,
"text": "Python"
},
{
"code": null,
"e": 27265,
"s": 27167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27274,
"s": 27265,
"text": "Comments"
},
{
"code": null,
"e": 27287,
"s": 27274,
"text": "Old Comments"
},
{
"code": null,
"e": 27305,
"s": 27287,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27327,
"s": 27305,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27359,
"s": 27327,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27389,
"s": 27359,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27431,
"s": 27389,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27457,
"s": 27431,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27500,
"s": 27457,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27525,
"s": 27500,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27562,
"s": 27525,
"text": "Create a Pandas DataFrame from Lists"
}
] |
sosreport - Unix, Linux Command
|
Navid Sheikhol-Eslami <[email protected]>
Eva Schaller <[email protected]> [Italian]
Imed Chihi <[email protected]> [Arabic] [French]
Steve Conklin <[email protected]>
John Berninger <[email protected]>
Navid Sheikhol-Eslami <[email protected]>
Pierre Amadio <[email protected]>
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10619,
"s": 10577,
"text": "Navid Sheikhol-Eslami <[email protected]>\n"
},
{
"code": null,
"e": 10714,
"s": 10619,
"text": "Eva Schaller <[email protected]> [Italian]\nImed Chihi <[email protected]> [Arabic] [French]\n"
},
{
"code": null,
"e": 10859,
"s": 10714,
"text": "Steve Conklin <[email protected]>\nJohn Berninger <[email protected]>\nNavid Sheikhol-Eslami <[email protected]>\nPierre Amadio <[email protected]>\n"
},
{
"code": null,
"e": 10876,
"s": 10859,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 10911,
"s": 10876,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 10939,
"s": 10911,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10973,
"s": 10939,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10990,
"s": 10973,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11023,
"s": 10990,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11034,
"s": 11023,
"text": " Pradeep D"
},
{
"code": null,
"e": 11069,
"s": 11034,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11085,
"s": 11069,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 11118,
"s": 11085,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11130,
"s": 11118,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11162,
"s": 11130,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11170,
"s": 11162,
"text": " Uplatz"
},
{
"code": null,
"e": 11177,
"s": 11170,
"text": " Print"
},
{
"code": null,
"e": 11188,
"s": 11177,
"text": " Add Notes"
}
] |
MySQL | AES_DECRYPT ( ) Function - GeeksforGeeks
|
14 Sep, 2021
The MySQL AES_DECRYPT function returns the original string after decrypting an encrypted string. It uses AES(Advanced Encryption Standard) algorithm to perform the decryption. The AES_DECRYPT function returns the decrypted string or NULL if it detects invalid data.
The value returned by the AES_DECRYPT function is the original plaintext string encrypted using AES_ENCRYPT function. The AES_DECRYPT function accepts two parameters which are the encrypted string and a string used to decrypt the encrypted string.
Syntax:
AES_DECRYPT(encrypted_string, key_string)
Parameters Used:
encrypted_string – It is used to specify the encrypted string.
key_string – It is used to specify the String which is used to decrypt encrypted_string.
Return Value: The AES_DECRYPT function in MySQL returns the original plaintext string encrypted using AES_ENCRYPT function.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing AES_DECRYPT function on a string.
SELECT
AES_DECRYPT(AES_ENCRYPT('ABC', 'key_string'), 'key_string');
Output:
ABC
Example-2: Implementing AES_DECRYPT function on a string with a combination of characters and integer values.
SELECT
AES_DECRYPT(AES_ENCRYPT('ABC123', 'key_string'), 'key_string');
Output:
ABC123
Example-3: Implementing AES_DECRYPT function on a bigger string.
SELECT
AES_DECRYPT(AES_ENCRYPT('geeksforgeeks', 'key_string'), 'key_string');
Output:
geeksforgeeks
Example-4: Implementing AES_DECRYPT function on a NULL string.
SELECT
AES_DECRYPT(AES_ENCRYPT(NULL, 'key_string'), 'key_string');
Output:
NULL
nnr223442
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
SQL Interview Questions
What is Temporary Table in SQL?
MySQL | Group_CONCAT() Function
Difference between Where and Having Clause in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | INSERT INTO Statement
|
[
{
"code": null,
"e": 23715,
"s": 23687,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 23982,
"s": 23715,
"text": "The MySQL AES_DECRYPT function returns the original string after decrypting an encrypted string. It uses AES(Advanced Encryption Standard) algorithm to perform the decryption. The AES_DECRYPT function returns the decrypted string or NULL if it detects invalid data. "
},
{
"code": null,
"e": 24231,
"s": 23982,
"text": "The value returned by the AES_DECRYPT function is the original plaintext string encrypted using AES_ENCRYPT function. The AES_DECRYPT function accepts two parameters which are the encrypted string and a string used to decrypt the encrypted string. "
},
{
"code": null,
"e": 24240,
"s": 24231,
"text": "Syntax: "
},
{
"code": null,
"e": 24282,
"s": 24240,
"text": "AES_DECRYPT(encrypted_string, key_string)"
},
{
"code": null,
"e": 24301,
"s": 24282,
"text": "Parameters Used: "
},
{
"code": null,
"e": 24364,
"s": 24301,
"text": "encrypted_string – It is used to specify the encrypted string."
},
{
"code": null,
"e": 24453,
"s": 24364,
"text": "key_string – It is used to specify the String which is used to decrypt encrypted_string."
},
{
"code": null,
"e": 24578,
"s": 24453,
"text": "Return Value: The AES_DECRYPT function in MySQL returns the original plaintext string encrypted using AES_ENCRYPT function. "
},
{
"code": null,
"e": 24608,
"s": 24578,
"text": "Supported Versions of MySQL: "
},
{
"code": null,
"e": 24618,
"s": 24608,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 24628,
"s": 24618,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 24638,
"s": 24628,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 24648,
"s": 24638,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 24658,
"s": 24648,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 24668,
"s": 24658,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 24727,
"s": 24668,
"text": "Example-1: Implementing AES_DECRYPT function on a string. "
},
{
"code": null,
"e": 24798,
"s": 24727,
"text": "SELECT \nAES_DECRYPT(AES_ENCRYPT('ABC', 'key_string'), 'key_string'); "
},
{
"code": null,
"e": 24808,
"s": 24798,
"text": "Output: "
},
{
"code": null,
"e": 24813,
"s": 24808,
"text": "ABC "
},
{
"code": null,
"e": 24924,
"s": 24813,
"text": "Example-2: Implementing AES_DECRYPT function on a string with a combination of characters and integer values. "
},
{
"code": null,
"e": 24998,
"s": 24924,
"text": "SELECT \nAES_DECRYPT(AES_ENCRYPT('ABC123', 'key_string'), 'key_string'); "
},
{
"code": null,
"e": 25008,
"s": 24998,
"text": "Output: "
},
{
"code": null,
"e": 25016,
"s": 25008,
"text": "ABC123 "
},
{
"code": null,
"e": 25082,
"s": 25016,
"text": "Example-3: Implementing AES_DECRYPT function on a bigger string. "
},
{
"code": null,
"e": 25163,
"s": 25082,
"text": "SELECT \nAES_DECRYPT(AES_ENCRYPT('geeksforgeeks', 'key_string'), 'key_string'); "
},
{
"code": null,
"e": 25173,
"s": 25163,
"text": "Output: "
},
{
"code": null,
"e": 25188,
"s": 25173,
"text": "geeksforgeeks "
},
{
"code": null,
"e": 25252,
"s": 25188,
"text": "Example-4: Implementing AES_DECRYPT function on a NULL string. "
},
{
"code": null,
"e": 25322,
"s": 25252,
"text": "SELECT \nAES_DECRYPT(AES_ENCRYPT(NULL, 'key_string'), 'key_string'); "
},
{
"code": null,
"e": 25332,
"s": 25322,
"text": "Output: "
},
{
"code": null,
"e": 25339,
"s": 25332,
"text": "NULL "
},
{
"code": null,
"e": 25349,
"s": 25339,
"text": "nnr223442"
},
{
"code": null,
"e": 25355,
"s": 25349,
"text": "mysql"
},
{
"code": null,
"e": 25364,
"s": 25355,
"text": "SQLmysql"
},
{
"code": null,
"e": 25368,
"s": 25364,
"text": "SQL"
},
{
"code": null,
"e": 25372,
"s": 25368,
"text": "SQL"
},
{
"code": null,
"e": 25470,
"s": 25372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25479,
"s": 25470,
"text": "Comments"
},
{
"code": null,
"e": 25492,
"s": 25479,
"text": "Old Comments"
},
{
"code": null,
"e": 25503,
"s": 25492,
"text": "CTE in SQL"
},
{
"code": null,
"e": 25569,
"s": 25503,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25602,
"s": 25569,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 25626,
"s": 25602,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 25658,
"s": 25626,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25690,
"s": 25658,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 25740,
"s": 25690,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 25818,
"s": 25740,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25835,
"s": 25818,
"text": "SQL using Python"
}
] |
Can I submit form with multiple submit buttons using jQuery?
|
Yes, you can submit form with multiple submit buttons. Attack a custom click handler to all the buttons and the check which button is clicked.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#myform button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "button1") {
alert("First Button is pressed - Form will submit")
$("#myform").submit();
}
if ($(this).attr("value") == "button2") {
alert("Second button is pressed - Form did not submit")
}
});
});
</script>
</head>
<body>
<form id="myform">
<input type="email" name="email" placeholder="Enter email" /><br>
<button type="submit" value="button1">First Button</button>
<button type="submit" value="button2">Second Button</button>
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "Yes, you can submit form with multiple submit buttons. Attack a custom click handler to all the buttons and the check which button is clicked."
},
{
"code": null,
"e": 1215,
"s": 1205,
"text": "Live Demo"
},
{
"code": null,
"e": 2015,
"s": 1215,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"#myform button\").click(function (ev) {\n ev.preventDefault()\n if ($(this).attr(\"value\") == \"button1\") { \n alert(\"First Button is pressed - Form will submit\")\n $(\"#myform\").submit();\n }\n if ($(this).attr(\"value\") == \"button2\") {\n alert(\"Second button is pressed - Form did not submit\")\n }\n });\n});\n</script>\n</head>\n<body>\n\n<form id=\"myform\">\n <input type=\"email\" name=\"email\" placeholder=\"Enter email\" /><br>\n <button type=\"submit\" value=\"button1\">First Button</button>\n <button type=\"submit\" value=\"button2\">Second Button</button>\n</form>\n\n</body>\n</html>"
}
] |
Top 20 Docker Security Tips. AIMing for safety! | by Jeff Hale | Towards Data Science
|
This article is full of tips to help you use Docker safely. If you’re new to Docker I suggest you first check out my previous articles on Docker concepts, the Docker ecosystem, Dockerfiles, slimming down images, popular commands, and data in Docker.
How concerned do you need to be about security in Docker? It depends. Docker comes with sensible security features baked in. If you are using official Docker images and not communicating with other machines, you don’t have much to worry about.
However, if you’re using unofficial images, serving files, or running apps in production, then the story is different. In those cases you need to be considerably more knowledgeable about Docker security.
Your primary security goal is to prevent a malicious user from gaining valuable information or wreaking havoc. Toward that end, I’ll share Docker security best practices in several key areas. By the end of this article you’ll have seen over 20 Docker security tips! 😃
We’ll focus on three areas in the first section:
Access management
Image safety
Management of secrets
Think of the acronym AIM to help you remember them.
First, let’s look at limiting a container’s access.
When you start a container, Docker creates a group of namespaces. Namespaces prevent processes in a container from seeing or affecting processes in the host, including other containers. Namespaces are a primary way Docker cordons off one container from another.
Docker provides private container networking, too. This prevents a container from gaining privileged access to the network interfaces of other containers on the same host.
So a Docker environment comes somewhat isolated, but it might not be isolated enough for your use case.
Good security means following the principle of least privilege. Your container should have the abilities to do what it needs, but no more abilities beyond those. The tricky thing is that once you start limiting what processes can be run in a container, the container might not be able to do something it legitimately needs to do.
There are several ways to adjust a container’s privileges. First, avoid running as root (or re-map if must run as root). Second, adjust capabilities with --cap-drop and --cap-add.
Avoiding root and adjusting capabilities should be all most folks need to do to restrict privileges. More advanced users might want to adjust the default AppArmor and seccomp profiles. I discuss these in my forthcoming book about Docker, but have excluded them here to keep this article from ballooning. 🎈
Docker’s default setting is for the user in an image to run as root. Many people don’t realize how dangerous this is. It means it’s far easier for an attacker to gain access to sensitive information and your kernel.
As a general best practice, don’t let a container run as root.
“The best way to prevent privilege-escalation attacks from within a container is to configure your container’s applications to run as unprivileged users.” — the Docker Docs.
You can specify a userid other than root at build time like this:
docker run -u 1000 my_image
The -- user or -u flag, can specify either a username or a userid. It's fine if the userid doesn't exist.
In the example above 1000 is is an arbitrary, unprivileged userid. In Linux, userids between 0 and 499 are generally reserved. Choose a userid over 500 to avoid running as a default system user.
Rather than set the user from the command line, it’s best to change the user from root in your image. Then folks don’t have to remember to change it at build time. Just include the USER Dockerfile instruction in your image after Dockerfile instructions that require the capabilities that come with root.
In other words, first install the packages you need and then switch the user. For example:
FROM alpine:latestRUN apk update && apk add --no-cache gitUSER 1000...
If you must run a processes in the container as a root user, re-map the root to a less-privileged user on the Docker host. See the Docker docs.
You can grant the privileges the user needs by altering the capabilities.
Capabilities are bundles of allowed processes.
Adjust capabilities through the command line with --cap-drop and --cap-add. A best policy is to drop all a container's privileges with --cap-drop all and add back the ones needed with --cap-add.
You can adjust a container’s capabilities at runtime. For example, to drop the ability to use kill to stop a container, you can remove that default capability like this:
docker run --cap-drop=Kill my_image
Avoid giving SYS_ADMIN and SETUID privileges to processes, as they are give broad swaths of power. Adding this capabilities to a user is similar to giving root permissions (and avoiding that outcome is kind of the whole point of not using root).
It’s safer to not allow a container to use a port number between 1 and 1023 because most network services run in this range. An unauthorized user could listen in on things like logins and run unauthorized server applications. These lower numbered ports require running as root or being explicitly given the CAP_NET_BIND_SERVICE capability.
To find out things like whether a container has privileged port access, you can use inspect. Using docker container inspect my_container_name will show you lots of details about the allocated resources and security profile of your container.
Here’s the Docker reference for more on privileges.
As with most things in Docker, it’s better to configure containers in an automatic, self-documenting file. With Docker Compose you can specify capabilities in a service configuration like this:
cap_drop: ALL
Or you can adjust them in Kubernetes files as discussed here.
The full list of Linux capabilities is here.
If you want more fine grained control over container privileges, check out my discussion of AppArmor and seccomp in my forthcoming book. Subscribe to my email newsletter to be notified when it’s available.
It’s a good idea to restrict a container’s access to system resources such as memory and CPU. Without a resource limit, a container can use up all available memory. If that happens the Linux host kernel will throw an Out of Memory Exception and kill kernel processes. This can lead the whole system to crash. You can imagine how attackers could use this knowledge to try to bring down apps.
If you have multiple containers running on the same machine it’s smart to limit the memory and CPU any one container can use. If your container runs out of memory, then it shut downs. Shutting down your container can cause your app to crash, which isn’t fun. However, this isolation protects the host from running out of memory and all the containers on it from crashing. And that’s a good thing.
Docker Desktop CE for Mac v2.1.0 has default resource restrictions. You can access them under the Docker icon -> Preferences. Then click on the Resources tab. You can use the sliders to adjust the resource constraints.
Alternatively, you can restrict resources from the command line by specifying the --memory flag or -m for short, followed by a number and a unit of measure.
4m means 4 mebibytes, and is the minimum container memory allocation. A mebibyte (MiB) is slightly more than a megabyte (1 MiB = 1.048576 MB). The docs are currently incorrect, but hopefully the maintainers will have accepted my PR to change it by the time you read this.
To see what resources your containers are using, enter the command docker stats in a new terminal window. You'll see running container statistics regularly refreshed.
Behind the scenes, Docker is using Linux Control Groups (cgroups) to implement resource limits. This technology is battle tested.
Learn more about resource constraints on Docker here.
Grabbing an image from Docker Hub is like inviting someone into your home. You might want to be intentional about it.
Rule one of image safety is to only use images you trust. How do you know which images are trustworthy?
It’s a good bet that popular official images are relatively safe. Such images include alpine, ubuntu, python, golang, redis, busybox, and node. Each has over 10M downloads and lots of eyes on them. 🔒
Docker explains:
Docker sponsors a dedicated team that is responsible for reviewing and publishing all content in the Official Images. This team works in collaboration with upstream software maintainers, security experts, and the broader Docker community to ensure the security of these images.
Related to using official base images, you can use a minimal base image.
With less code inside, there’s a lower chance for security vulnerabilities. A smaller, less complicated base image is more transparent.
It’s a lot easier to see what’s going on in an Alpine image than your friend’s image that relies on her friend’s image that relies on another base image. A short thread is easier to untangle.
Similar, only install packages you actually need. This reduces your attack surface and speeds up your image downloads and image builds.
You can ensure that images are signed by using Docker content trust. 🔏
Docker content trust prevents users from working with tagged images unless they contain a signature. Trusted sources include Official Docker Images from Docker Hub and signed images from user trusted sources.
Content trust is disabled by default. To enable it, set the DOCKER_CONTENT_TRUST environment variable to 1. From the command line, run the following:
export DOCKER_CONTENT_TRUST=1
Now when I try to pull down my own unsigned image from Docker Hub it is blocked.
Error: remote trust data does not exist for docker.io/discdiver/frames: notary.docker.io does not have trust data for docker.io/discdiver/frames
Content trust is a way to keep the riffraff out. Learn more about content trust here.
Docker stores and accesses images by the cryptographic checksum of their contents. This prevents attackers from creating image collisions. That’s a cool built-in safety feature.
Your access is restricted, your images are secure, now it’s time to manage your secrets.”
Rule 1 of managing sensitive information: do not bake it into your image. It’s not too tricky to find your unencrypted sensitive info in code repositories, logs, and elsewhere.
Rule 2: don’t use environment variables for your sensitive info, either. Anyone who can run docker inspect or exec into the container can find your secret. So can anyone running as root. Hopefully we've configured things so that users won't be running as root, but redundancy is part of good security. Often logs will dump the environment variable values, too. You don't want your sensitive info spilling out to just anyone.
Docker volumes are better. They are the recommended way to access your sensitive info in the Docker docs. You can use a volume as temporary file system held in memory. Volumes remove the docker inspect and the logging risk. However, root users could still see the secret, as could anyone who can exec into the container. Overall, volumes are a pretty good solution.
Even better than volumes, use Docker secrets. Secrets are encrypted.
Some Docker docs state that you can use secrets with Docker Swarm only. Nevertheless, you can use secrets in Docker without Swarm.
If you just need the secret in your image, you can use BuildKit. BuildKit is a better backend than the current build tool for building Docker images. It cuts build time significantly and has other nice features, including build-time secrets support.
BuildKit is relatively new — Docker Engine 18.09 was the first version shipped with BuildKit support. There are three ways to specify the BuildKit backend so you can use its features now. In the future, it will be the default backend.
Set it as an environment variable with export DOCKER_BUILDKIT=1.Start your build or run command with DOCKER_BUILDKIT=1.Enable BuildKit by default. Set the configuration in /etc/docker/daemon.json to true with: { "features": { "buildkit": true } }. Then restart Docker.Then you can use secrets at build time with the --secret flag like this:
Set it as an environment variable with export DOCKER_BUILDKIT=1.
Start your build or run command with DOCKER_BUILDKIT=1.
Enable BuildKit by default. Set the configuration in /etc/docker/daemon.json to true with: { "features": { "buildkit": true } }. Then restart Docker.
Then you can use secrets at build time with the --secret flag like this:
docker build --secret my_key=my_value ,src=path/to/my_secret_file .
Where your file specifies your secrets as key-value pair.
These secrets are not stored in the final image. They are also excluded from the image build cache. Safety first!
If you need your secret in your running container, and not just when building your image, use Docker Compose or Kubernetes.
With Docker Compose, add the secrets key-value pair to a service and specify the secret file. Hat tip to Stack Exchange answer for the Docker Compose secrets tip that the example below is adapted from.
Example docker-compose.yml with secrets:
version: "3.7"services: my_service: image: centos:7 entrypoint: "cat /run/secrets/my_secret" secrets: - my_secretsecrets: my_secret: file: ./my_secret_file.txt
Then start Compose as usual with docker-compose up --build my_service.
If you’re using Kubernetes, it has support for secrets. Helm-Secrets can help make secrets management in K8s easier. Additionally, K8s has Role Based Access Controls (RBAC) — as does Docker Enterprise. RBAC makes access Secrets management more manageable and more secure for teams.
A best practice with secrets is to use a secrets management service such as Vault. Vault is a service by HashiCorp for managing access to secrets. It also time-limits secrets. More info on Vault’s Docker image can be found here.
AWS Secrets Manager and similar products from other cloud providers can also help you manage your secrets on the cloud.
Just remember, the key to managing your secrets is to keep them secret. Definitely don’t bake them into your image or turn them into environment variables.
As with any code, keep your the languages and libraries in your images up to date to benefit from the latest security fixes.
If you refer to a specific version of a base image in your image, make sure you keep it up to date, too.
Relatedly, you should keep your version of Docker up to date for bug fixes and enhancements that will allow you to implement new security features.
Finally, keep your host server software up to date. If you’re running on a managed service, this should be done for you.
Better security means keeping things updated.
If you have an organization with a bunch of people and a bunch of Docker containers, it’s a good bet you’d benefit from Docker Enterprise. Administrators can set policy restrictions for all users. The provided RBAC, monitoring, and logging capabilities are likely to make security management easier for your team.
With Enterprise you can also host your own images privately in a Docker Trusted Registry. Docker provides built-in security scanning to make sure you don’t have known vulnerabilities in your images.
Kubernetes provides some of this functionality for free, but Docker Enterprise has additional security capabilities for containers and images. Best of all, Docker Enterprise 3.0 was released in July 2019. It includes Docker Kubernetes Service with “sensible security defaults”.
Don’t ever run a container as -- privileged unless you need to for a special circumstance like needing to run Docker inside a Docker container — and you know what you're doing.
In your Dockerfile, favor COPY instead of ADD. ADD automatically extracts zipped files and can copy files from URLs. COPY doesn’t have these capabilities. Whenever possible, avoid using ADD so you aren’t susceptible to attacks through remote URLs and Zip files.
If you run any other processes on the same server, run them in Docker containers.
If you use a web server and API to create containers, check parameters carefully so new containers you don’t want can’t be created.
If you expose a REST API, secure API endpoints with HTTPS or SSH.
Consider a checkup with Docker Bench for Security to see how well your containers follow their security guidelines.
Store sensitive data only in volumes, never in a container.
If using a single-host app with networking, don’t use the default bridge network. It has technical shortcomings and is not recommended for production use. If you publish a port, all containers on the bridge network become accessible.
Use Lets Encrypt for HTTPS certificates for serving. See an example with NGINX here.
Mount volumes as read-only when you only need to read from them. See several ways to do this here.
You’ve seen many of ways to make your Docker containers safer. Security is not set-it and forget it. It requires vigilance to keep your images and containers secure.
Access management
Access management
Avoid running as root. Remap if must use root.
Drop all capabilities and add back those that are needed.
Dig into AppArmor if you need fine-grained privilege tuning.
Restrict resources.
2. Image safety
Use official, popular, minimal base images.
Don’t install things you don’t need.
Require images to be signed.
Keep Docker, Docker images, and other software that touches Docker updated.
3. Management of secrets
Use secrets or volumes.
Consider a secrets manager such as Vault.
Keeping Docker containers secure means AIMing for safety.
Don’t forget to keep Docker, your languages and libraries, your images, and your host software updated. Finally, consider using Docker Enterprise if you’re running Docker as part of a team.
I hope you found this Docker security article helpful. If you did, please share it with others on your favorite forums or social media channels so your friends can find it, too! 👏
Do you have other Docker security suggestions? If so, please share them in the comments or on Twitter @discdiver. 👍
If you’re interested in being notified when my Memorable Docker book with even more Docker goodness is released, sign up for my mailing list.
I write about articles about Python, data science, AI, and other tech topics. Check them out follow me on Medium if you’re into that stuff.
Happy securing! 😃
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
|
[
{
"code": null,
"e": 422,
"s": 172,
"text": "This article is full of tips to help you use Docker safely. If you’re new to Docker I suggest you first check out my previous articles on Docker concepts, the Docker ecosystem, Dockerfiles, slimming down images, popular commands, and data in Docker."
},
{
"code": null,
"e": 666,
"s": 422,
"text": "How concerned do you need to be about security in Docker? It depends. Docker comes with sensible security features baked in. If you are using official Docker images and not communicating with other machines, you don’t have much to worry about."
},
{
"code": null,
"e": 870,
"s": 666,
"text": "However, if you’re using unofficial images, serving files, or running apps in production, then the story is different. In those cases you need to be considerably more knowledgeable about Docker security."
},
{
"code": null,
"e": 1138,
"s": 870,
"text": "Your primary security goal is to prevent a malicious user from gaining valuable information or wreaking havoc. Toward that end, I’ll share Docker security best practices in several key areas. By the end of this article you’ll have seen over 20 Docker security tips! 😃"
},
{
"code": null,
"e": 1187,
"s": 1138,
"text": "We’ll focus on three areas in the first section:"
},
{
"code": null,
"e": 1205,
"s": 1187,
"text": "Access management"
},
{
"code": null,
"e": 1218,
"s": 1205,
"text": "Image safety"
},
{
"code": null,
"e": 1240,
"s": 1218,
"text": "Management of secrets"
},
{
"code": null,
"e": 1292,
"s": 1240,
"text": "Think of the acronym AIM to help you remember them."
},
{
"code": null,
"e": 1344,
"s": 1292,
"text": "First, let’s look at limiting a container’s access."
},
{
"code": null,
"e": 1606,
"s": 1344,
"text": "When you start a container, Docker creates a group of namespaces. Namespaces prevent processes in a container from seeing or affecting processes in the host, including other containers. Namespaces are a primary way Docker cordons off one container from another."
},
{
"code": null,
"e": 1778,
"s": 1606,
"text": "Docker provides private container networking, too. This prevents a container from gaining privileged access to the network interfaces of other containers on the same host."
},
{
"code": null,
"e": 1882,
"s": 1778,
"text": "So a Docker environment comes somewhat isolated, but it might not be isolated enough for your use case."
},
{
"code": null,
"e": 2212,
"s": 1882,
"text": "Good security means following the principle of least privilege. Your container should have the abilities to do what it needs, but no more abilities beyond those. The tricky thing is that once you start limiting what processes can be run in a container, the container might not be able to do something it legitimately needs to do."
},
{
"code": null,
"e": 2392,
"s": 2212,
"text": "There are several ways to adjust a container’s privileges. First, avoid running as root (or re-map if must run as root). Second, adjust capabilities with --cap-drop and --cap-add."
},
{
"code": null,
"e": 2698,
"s": 2392,
"text": "Avoiding root and adjusting capabilities should be all most folks need to do to restrict privileges. More advanced users might want to adjust the default AppArmor and seccomp profiles. I discuss these in my forthcoming book about Docker, but have excluded them here to keep this article from ballooning. 🎈"
},
{
"code": null,
"e": 2914,
"s": 2698,
"text": "Docker’s default setting is for the user in an image to run as root. Many people don’t realize how dangerous this is. It means it’s far easier for an attacker to gain access to sensitive information and your kernel."
},
{
"code": null,
"e": 2977,
"s": 2914,
"text": "As a general best practice, don’t let a container run as root."
},
{
"code": null,
"e": 3151,
"s": 2977,
"text": "“The best way to prevent privilege-escalation attacks from within a container is to configure your container’s applications to run as unprivileged users.” — the Docker Docs."
},
{
"code": null,
"e": 3217,
"s": 3151,
"text": "You can specify a userid other than root at build time like this:"
},
{
"code": null,
"e": 3245,
"s": 3217,
"text": "docker run -u 1000 my_image"
},
{
"code": null,
"e": 3351,
"s": 3245,
"text": "The -- user or -u flag, can specify either a username or a userid. It's fine if the userid doesn't exist."
},
{
"code": null,
"e": 3546,
"s": 3351,
"text": "In the example above 1000 is is an arbitrary, unprivileged userid. In Linux, userids between 0 and 499 are generally reserved. Choose a userid over 500 to avoid running as a default system user."
},
{
"code": null,
"e": 3850,
"s": 3546,
"text": "Rather than set the user from the command line, it’s best to change the user from root in your image. Then folks don’t have to remember to change it at build time. Just include the USER Dockerfile instruction in your image after Dockerfile instructions that require the capabilities that come with root."
},
{
"code": null,
"e": 3941,
"s": 3850,
"text": "In other words, first install the packages you need and then switch the user. For example:"
},
{
"code": null,
"e": 4012,
"s": 3941,
"text": "FROM alpine:latestRUN apk update && apk add --no-cache gitUSER 1000..."
},
{
"code": null,
"e": 4156,
"s": 4012,
"text": "If you must run a processes in the container as a root user, re-map the root to a less-privileged user on the Docker host. See the Docker docs."
},
{
"code": null,
"e": 4230,
"s": 4156,
"text": "You can grant the privileges the user needs by altering the capabilities."
},
{
"code": null,
"e": 4277,
"s": 4230,
"text": "Capabilities are bundles of allowed processes."
},
{
"code": null,
"e": 4472,
"s": 4277,
"text": "Adjust capabilities through the command line with --cap-drop and --cap-add. A best policy is to drop all a container's privileges with --cap-drop all and add back the ones needed with --cap-add."
},
{
"code": null,
"e": 4642,
"s": 4472,
"text": "You can adjust a container’s capabilities at runtime. For example, to drop the ability to use kill to stop a container, you can remove that default capability like this:"
},
{
"code": null,
"e": 4678,
"s": 4642,
"text": "docker run --cap-drop=Kill my_image"
},
{
"code": null,
"e": 4924,
"s": 4678,
"text": "Avoid giving SYS_ADMIN and SETUID privileges to processes, as they are give broad swaths of power. Adding this capabilities to a user is similar to giving root permissions (and avoiding that outcome is kind of the whole point of not using root)."
},
{
"code": null,
"e": 5264,
"s": 4924,
"text": "It’s safer to not allow a container to use a port number between 1 and 1023 because most network services run in this range. An unauthorized user could listen in on things like logins and run unauthorized server applications. These lower numbered ports require running as root or being explicitly given the CAP_NET_BIND_SERVICE capability."
},
{
"code": null,
"e": 5506,
"s": 5264,
"text": "To find out things like whether a container has privileged port access, you can use inspect. Using docker container inspect my_container_name will show you lots of details about the allocated resources and security profile of your container."
},
{
"code": null,
"e": 5558,
"s": 5506,
"text": "Here’s the Docker reference for more on privileges."
},
{
"code": null,
"e": 5752,
"s": 5558,
"text": "As with most things in Docker, it’s better to configure containers in an automatic, self-documenting file. With Docker Compose you can specify capabilities in a service configuration like this:"
},
{
"code": null,
"e": 5766,
"s": 5752,
"text": "cap_drop: ALL"
},
{
"code": null,
"e": 5828,
"s": 5766,
"text": "Or you can adjust them in Kubernetes files as discussed here."
},
{
"code": null,
"e": 5873,
"s": 5828,
"text": "The full list of Linux capabilities is here."
},
{
"code": null,
"e": 6079,
"s": 5873,
"text": "If you want more fine grained control over container privileges, check out my discussion of AppArmor and seccomp in my forthcoming book. Subscribe to my email newsletter to be notified when it’s available."
},
{
"code": null,
"e": 6470,
"s": 6079,
"text": "It’s a good idea to restrict a container’s access to system resources such as memory and CPU. Without a resource limit, a container can use up all available memory. If that happens the Linux host kernel will throw an Out of Memory Exception and kill kernel processes. This can lead the whole system to crash. You can imagine how attackers could use this knowledge to try to bring down apps."
},
{
"code": null,
"e": 6867,
"s": 6470,
"text": "If you have multiple containers running on the same machine it’s smart to limit the memory and CPU any one container can use. If your container runs out of memory, then it shut downs. Shutting down your container can cause your app to crash, which isn’t fun. However, this isolation protects the host from running out of memory and all the containers on it from crashing. And that’s a good thing."
},
{
"code": null,
"e": 7086,
"s": 6867,
"text": "Docker Desktop CE for Mac v2.1.0 has default resource restrictions. You can access them under the Docker icon -> Preferences. Then click on the Resources tab. You can use the sliders to adjust the resource constraints."
},
{
"code": null,
"e": 7243,
"s": 7086,
"text": "Alternatively, you can restrict resources from the command line by specifying the --memory flag or -m for short, followed by a number and a unit of measure."
},
{
"code": null,
"e": 7515,
"s": 7243,
"text": "4m means 4 mebibytes, and is the minimum container memory allocation. A mebibyte (MiB) is slightly more than a megabyte (1 MiB = 1.048576 MB). The docs are currently incorrect, but hopefully the maintainers will have accepted my PR to change it by the time you read this."
},
{
"code": null,
"e": 7682,
"s": 7515,
"text": "To see what resources your containers are using, enter the command docker stats in a new terminal window. You'll see running container statistics regularly refreshed."
},
{
"code": null,
"e": 7812,
"s": 7682,
"text": "Behind the scenes, Docker is using Linux Control Groups (cgroups) to implement resource limits. This technology is battle tested."
},
{
"code": null,
"e": 7866,
"s": 7812,
"text": "Learn more about resource constraints on Docker here."
},
{
"code": null,
"e": 7984,
"s": 7866,
"text": "Grabbing an image from Docker Hub is like inviting someone into your home. You might want to be intentional about it."
},
{
"code": null,
"e": 8088,
"s": 7984,
"text": "Rule one of image safety is to only use images you trust. How do you know which images are trustworthy?"
},
{
"code": null,
"e": 8288,
"s": 8088,
"text": "It’s a good bet that popular official images are relatively safe. Such images include alpine, ubuntu, python, golang, redis, busybox, and node. Each has over 10M downloads and lots of eyes on them. 🔒"
},
{
"code": null,
"e": 8305,
"s": 8288,
"text": "Docker explains:"
},
{
"code": null,
"e": 8583,
"s": 8305,
"text": "Docker sponsors a dedicated team that is responsible for reviewing and publishing all content in the Official Images. This team works in collaboration with upstream software maintainers, security experts, and the broader Docker community to ensure the security of these images."
},
{
"code": null,
"e": 8656,
"s": 8583,
"text": "Related to using official base images, you can use a minimal base image."
},
{
"code": null,
"e": 8792,
"s": 8656,
"text": "With less code inside, there’s a lower chance for security vulnerabilities. A smaller, less complicated base image is more transparent."
},
{
"code": null,
"e": 8984,
"s": 8792,
"text": "It’s a lot easier to see what’s going on in an Alpine image than your friend’s image that relies on her friend’s image that relies on another base image. A short thread is easier to untangle."
},
{
"code": null,
"e": 9120,
"s": 8984,
"text": "Similar, only install packages you actually need. This reduces your attack surface and speeds up your image downloads and image builds."
},
{
"code": null,
"e": 9191,
"s": 9120,
"text": "You can ensure that images are signed by using Docker content trust. 🔏"
},
{
"code": null,
"e": 9400,
"s": 9191,
"text": "Docker content trust prevents users from working with tagged images unless they contain a signature. Trusted sources include Official Docker Images from Docker Hub and signed images from user trusted sources."
},
{
"code": null,
"e": 9550,
"s": 9400,
"text": "Content trust is disabled by default. To enable it, set the DOCKER_CONTENT_TRUST environment variable to 1. From the command line, run the following:"
},
{
"code": null,
"e": 9580,
"s": 9550,
"text": "export DOCKER_CONTENT_TRUST=1"
},
{
"code": null,
"e": 9661,
"s": 9580,
"text": "Now when I try to pull down my own unsigned image from Docker Hub it is blocked."
},
{
"code": null,
"e": 9806,
"s": 9661,
"text": "Error: remote trust data does not exist for docker.io/discdiver/frames: notary.docker.io does not have trust data for docker.io/discdiver/frames"
},
{
"code": null,
"e": 9892,
"s": 9806,
"text": "Content trust is a way to keep the riffraff out. Learn more about content trust here."
},
{
"code": null,
"e": 10070,
"s": 9892,
"text": "Docker stores and accesses images by the cryptographic checksum of their contents. This prevents attackers from creating image collisions. That’s a cool built-in safety feature."
},
{
"code": null,
"e": 10160,
"s": 10070,
"text": "Your access is restricted, your images are secure, now it’s time to manage your secrets.”"
},
{
"code": null,
"e": 10337,
"s": 10160,
"text": "Rule 1 of managing sensitive information: do not bake it into your image. It’s not too tricky to find your unencrypted sensitive info in code repositories, logs, and elsewhere."
},
{
"code": null,
"e": 10762,
"s": 10337,
"text": "Rule 2: don’t use environment variables for your sensitive info, either. Anyone who can run docker inspect or exec into the container can find your secret. So can anyone running as root. Hopefully we've configured things so that users won't be running as root, but redundancy is part of good security. Often logs will dump the environment variable values, too. You don't want your sensitive info spilling out to just anyone."
},
{
"code": null,
"e": 11128,
"s": 10762,
"text": "Docker volumes are better. They are the recommended way to access your sensitive info in the Docker docs. You can use a volume as temporary file system held in memory. Volumes remove the docker inspect and the logging risk. However, root users could still see the secret, as could anyone who can exec into the container. Overall, volumes are a pretty good solution."
},
{
"code": null,
"e": 11197,
"s": 11128,
"text": "Even better than volumes, use Docker secrets. Secrets are encrypted."
},
{
"code": null,
"e": 11328,
"s": 11197,
"text": "Some Docker docs state that you can use secrets with Docker Swarm only. Nevertheless, you can use secrets in Docker without Swarm."
},
{
"code": null,
"e": 11578,
"s": 11328,
"text": "If you just need the secret in your image, you can use BuildKit. BuildKit is a better backend than the current build tool for building Docker images. It cuts build time significantly and has other nice features, including build-time secrets support."
},
{
"code": null,
"e": 11813,
"s": 11578,
"text": "BuildKit is relatively new — Docker Engine 18.09 was the first version shipped with BuildKit support. There are three ways to specify the BuildKit backend so you can use its features now. In the future, it will be the default backend."
},
{
"code": null,
"e": 12154,
"s": 11813,
"text": "Set it as an environment variable with export DOCKER_BUILDKIT=1.Start your build or run command with DOCKER_BUILDKIT=1.Enable BuildKit by default. Set the configuration in /etc/docker/daemon.json to true with: { \"features\": { \"buildkit\": true } }. Then restart Docker.Then you can use secrets at build time with the --secret flag like this:"
},
{
"code": null,
"e": 12219,
"s": 12154,
"text": "Set it as an environment variable with export DOCKER_BUILDKIT=1."
},
{
"code": null,
"e": 12275,
"s": 12219,
"text": "Start your build or run command with DOCKER_BUILDKIT=1."
},
{
"code": null,
"e": 12425,
"s": 12275,
"text": "Enable BuildKit by default. Set the configuration in /etc/docker/daemon.json to true with: { \"features\": { \"buildkit\": true } }. Then restart Docker."
},
{
"code": null,
"e": 12498,
"s": 12425,
"text": "Then you can use secrets at build time with the --secret flag like this:"
},
{
"code": null,
"e": 12566,
"s": 12498,
"text": "docker build --secret my_key=my_value ,src=path/to/my_secret_file ."
},
{
"code": null,
"e": 12624,
"s": 12566,
"text": "Where your file specifies your secrets as key-value pair."
},
{
"code": null,
"e": 12738,
"s": 12624,
"text": "These secrets are not stored in the final image. They are also excluded from the image build cache. Safety first!"
},
{
"code": null,
"e": 12862,
"s": 12738,
"text": "If you need your secret in your running container, and not just when building your image, use Docker Compose or Kubernetes."
},
{
"code": null,
"e": 13064,
"s": 12862,
"text": "With Docker Compose, add the secrets key-value pair to a service and specify the secret file. Hat tip to Stack Exchange answer for the Docker Compose secrets tip that the example below is adapted from."
},
{
"code": null,
"e": 13105,
"s": 13064,
"text": "Example docker-compose.yml with secrets:"
},
{
"code": null,
"e": 13284,
"s": 13105,
"text": "version: \"3.7\"services: my_service: image: centos:7 entrypoint: \"cat /run/secrets/my_secret\" secrets: - my_secretsecrets: my_secret: file: ./my_secret_file.txt"
},
{
"code": null,
"e": 13355,
"s": 13284,
"text": "Then start Compose as usual with docker-compose up --build my_service."
},
{
"code": null,
"e": 13637,
"s": 13355,
"text": "If you’re using Kubernetes, it has support for secrets. Helm-Secrets can help make secrets management in K8s easier. Additionally, K8s has Role Based Access Controls (RBAC) — as does Docker Enterprise. RBAC makes access Secrets management more manageable and more secure for teams."
},
{
"code": null,
"e": 13866,
"s": 13637,
"text": "A best practice with secrets is to use a secrets management service such as Vault. Vault is a service by HashiCorp for managing access to secrets. It also time-limits secrets. More info on Vault’s Docker image can be found here."
},
{
"code": null,
"e": 13986,
"s": 13866,
"text": "AWS Secrets Manager and similar products from other cloud providers can also help you manage your secrets on the cloud."
},
{
"code": null,
"e": 14142,
"s": 13986,
"text": "Just remember, the key to managing your secrets is to keep them secret. Definitely don’t bake them into your image or turn them into environment variables."
},
{
"code": null,
"e": 14267,
"s": 14142,
"text": "As with any code, keep your the languages and libraries in your images up to date to benefit from the latest security fixes."
},
{
"code": null,
"e": 14372,
"s": 14267,
"text": "If you refer to a specific version of a base image in your image, make sure you keep it up to date, too."
},
{
"code": null,
"e": 14520,
"s": 14372,
"text": "Relatedly, you should keep your version of Docker up to date for bug fixes and enhancements that will allow you to implement new security features."
},
{
"code": null,
"e": 14641,
"s": 14520,
"text": "Finally, keep your host server software up to date. If you’re running on a managed service, this should be done for you."
},
{
"code": null,
"e": 14687,
"s": 14641,
"text": "Better security means keeping things updated."
},
{
"code": null,
"e": 15001,
"s": 14687,
"text": "If you have an organization with a bunch of people and a bunch of Docker containers, it’s a good bet you’d benefit from Docker Enterprise. Administrators can set policy restrictions for all users. The provided RBAC, monitoring, and logging capabilities are likely to make security management easier for your team."
},
{
"code": null,
"e": 15200,
"s": 15001,
"text": "With Enterprise you can also host your own images privately in a Docker Trusted Registry. Docker provides built-in security scanning to make sure you don’t have known vulnerabilities in your images."
},
{
"code": null,
"e": 15478,
"s": 15200,
"text": "Kubernetes provides some of this functionality for free, but Docker Enterprise has additional security capabilities for containers and images. Best of all, Docker Enterprise 3.0 was released in July 2019. It includes Docker Kubernetes Service with “sensible security defaults”."
},
{
"code": null,
"e": 15655,
"s": 15478,
"text": "Don’t ever run a container as -- privileged unless you need to for a special circumstance like needing to run Docker inside a Docker container — and you know what you're doing."
},
{
"code": null,
"e": 15917,
"s": 15655,
"text": "In your Dockerfile, favor COPY instead of ADD. ADD automatically extracts zipped files and can copy files from URLs. COPY doesn’t have these capabilities. Whenever possible, avoid using ADD so you aren’t susceptible to attacks through remote URLs and Zip files."
},
{
"code": null,
"e": 15999,
"s": 15917,
"text": "If you run any other processes on the same server, run them in Docker containers."
},
{
"code": null,
"e": 16131,
"s": 15999,
"text": "If you use a web server and API to create containers, check parameters carefully so new containers you don’t want can’t be created."
},
{
"code": null,
"e": 16197,
"s": 16131,
"text": "If you expose a REST API, secure API endpoints with HTTPS or SSH."
},
{
"code": null,
"e": 16313,
"s": 16197,
"text": "Consider a checkup with Docker Bench for Security to see how well your containers follow their security guidelines."
},
{
"code": null,
"e": 16373,
"s": 16313,
"text": "Store sensitive data only in volumes, never in a container."
},
{
"code": null,
"e": 16607,
"s": 16373,
"text": "If using a single-host app with networking, don’t use the default bridge network. It has technical shortcomings and is not recommended for production use. If you publish a port, all containers on the bridge network become accessible."
},
{
"code": null,
"e": 16692,
"s": 16607,
"text": "Use Lets Encrypt for HTTPS certificates for serving. See an example with NGINX here."
},
{
"code": null,
"e": 16791,
"s": 16692,
"text": "Mount volumes as read-only when you only need to read from them. See several ways to do this here."
},
{
"code": null,
"e": 16957,
"s": 16791,
"text": "You’ve seen many of ways to make your Docker containers safer. Security is not set-it and forget it. It requires vigilance to keep your images and containers secure."
},
{
"code": null,
"e": 16975,
"s": 16957,
"text": "Access management"
},
{
"code": null,
"e": 16993,
"s": 16975,
"text": "Access management"
},
{
"code": null,
"e": 17040,
"s": 16993,
"text": "Avoid running as root. Remap if must use root."
},
{
"code": null,
"e": 17098,
"s": 17040,
"text": "Drop all capabilities and add back those that are needed."
},
{
"code": null,
"e": 17159,
"s": 17098,
"text": "Dig into AppArmor if you need fine-grained privilege tuning."
},
{
"code": null,
"e": 17179,
"s": 17159,
"text": "Restrict resources."
},
{
"code": null,
"e": 17195,
"s": 17179,
"text": "2. Image safety"
},
{
"code": null,
"e": 17239,
"s": 17195,
"text": "Use official, popular, minimal base images."
},
{
"code": null,
"e": 17276,
"s": 17239,
"text": "Don’t install things you don’t need."
},
{
"code": null,
"e": 17305,
"s": 17276,
"text": "Require images to be signed."
},
{
"code": null,
"e": 17381,
"s": 17305,
"text": "Keep Docker, Docker images, and other software that touches Docker updated."
},
{
"code": null,
"e": 17406,
"s": 17381,
"text": "3. Management of secrets"
},
{
"code": null,
"e": 17430,
"s": 17406,
"text": "Use secrets or volumes."
},
{
"code": null,
"e": 17472,
"s": 17430,
"text": "Consider a secrets manager such as Vault."
},
{
"code": null,
"e": 17530,
"s": 17472,
"text": "Keeping Docker containers secure means AIMing for safety."
},
{
"code": null,
"e": 17720,
"s": 17530,
"text": "Don’t forget to keep Docker, your languages and libraries, your images, and your host software updated. Finally, consider using Docker Enterprise if you’re running Docker as part of a team."
},
{
"code": null,
"e": 17900,
"s": 17720,
"text": "I hope you found this Docker security article helpful. If you did, please share it with others on your favorite forums or social media channels so your friends can find it, too! 👏"
},
{
"code": null,
"e": 18016,
"s": 17900,
"text": "Do you have other Docker security suggestions? If so, please share them in the comments or on Twitter @discdiver. 👍"
},
{
"code": null,
"e": 18158,
"s": 18016,
"text": "If you’re interested in being notified when my Memorable Docker book with even more Docker goodness is released, sign up for my mailing list."
},
{
"code": null,
"e": 18298,
"s": 18158,
"text": "I write about articles about Python, data science, AI, and other tech topics. Check them out follow me on Medium if you’re into that stuff."
},
{
"code": null,
"e": 18316,
"s": 18298,
"text": "Happy securing! 😃"
}
] |
Clustering algorithms for customer segmentation | by Sowmya Vivek | Towards Data Science
|
ContextIn today’s competitive world, it is crucial to understand customer behavior and categorize customers based on their demography and buying behavior. This is a critical aspect of customer segmentation that allows marketers to better tailor their marketing efforts to various audience subsets in terms of promotional, marketing and product development strategies.
ObjectiveThis article demonstrates the concept of segmentation of a customer data set from an e-commerce site using k-means clustering in python. The data set contains the annual income of ~300 customers and their annual spend on an e-commerce site. We will use the k-means clustering algorithm to derive the optimum number of clusters and understand the underlying customer segments based on the data provided.
About the data setThe dataset consists of Annual income (in $000) of 303 customers and their total spend (in $000) on an e-commerce site for a period of one year. Let us explore the data using numpy and pandas libraries in python.
#Load the required packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt#Plot stylingimport seaborn as sns; sns.set() # for plot styling%matplotlib inlineplt.rcParams['figure.figsize'] = (16, 9)plt.style.use('ggplot')#Read the csv filedataset=pd.read_csv('CLV.csv')#Explore the datasetdataset.head()#top 5 columnslen(dataset) # of rows#descriptive statistics of the datasetdataset.describe().transpose()
The dataset consists of 303 rows. The mean annual income is 245000 and the mean annual spend is 149000. The distribution of the annual income and annual spend has been illustrated with a distplot and violinplot.
Visualizing the dataThe displot and violinplot give an indication of the data distribution of Income and Spend.
#Visualizing the data - displotplot_income = sns.distplot(dataset["INCOME"])plot_spend = sns.distplot(dataset["SPEND"])plt.xlabel('Income / spend')
#Violin plot of Income and Spendf, axes = plt.subplots(1,2, figsize=(12,6), sharex=True, sharey=True)v1 = sns.violinplot(data=dataset, x='INCOME', color="skyblue",ax=axes[0])v2 = sns.violinplot(data=dataset, x='SPEND',color="lightgreen", ax=axes[1])v1.set(xlim=(0,420))
Clustering fundamentalsClustering is an unsupervised machine learning technique, where there are no defined dependent and independent variables. The patterns in the data are used to identify / group similar observations.
The objective of any clustering algorithm is to ensure that the distance between datapoints in a cluster is very low compared to the distance between 2 clusters. In other words, members of a group are very similar, and members of different groups are extremely dissimilar.
We will use are k-means clustering for creating customer segments based on their income and spend data.
K-Means clusteringK-means clustering is an iterative clustering algorithm where the number of clusters K is predetermined and the algorithm iteratively assigns each data point to one of the K clusters based on the feature similarity.
Broad steps of the k-means algorithm
The mathematics of clustering
The mathematics behind clustering, in very simple terms involves minimizing the sum of square of distances between the cluster centroid and its associated data points:
K = number of clusters
N= number of data points
C=centroid of cluster j
(xij — cj)– Distance between data point and centroid to which it is assigned
Deciding on the optimum number of clusters ‘K’The main input for k-means clustering is the number of clusters. This is derived using the concept of minimizing within cluster sum of square (WCSS). A scree plot is created which plots the number of clusters in the X axis and the WCSS for each cluster number in the y-axis.
As the number of clusters increase, the WCSS keeps decreasing. The decrease of WCSS is initially steep and then the rate of decrease slows down resulting in an elbow plot. The number of clusters at the elbow formation usually gives an indication on the optimum number of clusters. This combined with specific knowledge of the business requirement should be used to decide on the optimum number of clusters.
For our dataset, we will arrive at the optimum number of clusters using the elbow method:
#Using the elbow method to find the optimum number of clustersfrom sklearn.cluster import KMeanswcss = []for i in range(1,11): km=KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0) km.fit(X) wcss.append(km.inertia_)plt.plot(range(1,11),wcss)plt.title('Elbow Method')plt.xlabel('Number of clusters')plt.ylabel('wcss')plt.show()
Based on the elbow plot, we could choose 4,5 or 6 clusters. Let us try both the number of clusters and visualize the clusters to decide on the final number of clusters.
Fitting the k-means to the dataset with k=4
##Fitting kmeans to the dataset with k=4km4=KMeans(n_clusters=4,init='k-means++', max_iter=300, n_init=10, random_state=0)y_means = km4.fit_predict(X)#Visualizing the clusters for k=4plt.scatter(X[y_means==0,0],X[y_means==0,1],s=50, c='purple',label='Cluster1')plt.scatter(X[y_means==1,0],X[y_means==1,1],s=50, c='blue',label='Cluster2')plt.scatter(X[y_means==2,0],X[y_means==2,1],s=50, c='green',label='Cluster3')plt.scatter(X[y_means==3,0],X[y_means==3,1],s=50, c='cyan',label='Cluster4')plt.scatter(km4.cluster_centers_[:,0], km4.cluster_centers_[:,1],s=200,marker='s', c='red', alpha=0.7, label='Centroids')plt.title('Customer segments')plt.xlabel('Annual income of customer')plt.ylabel('Annual spend from customer on site')plt.legend()plt.show()
The plot shows the distribution of the 4 clusters. We could interpret them as the following customer segments:
Cluster 1: Customers with medium annual income and low annual spendCluster 2: Customers with high annual income and medium to high annual spendCluster 3: Customers with low annual incomeCluster 4: Customers with medium annual income but high annual spend
Cluster 1: Customers with medium annual income and low annual spend
Cluster 2: Customers with high annual income and medium to high annual spend
Cluster 3: Customers with low annual income
Cluster 4: Customers with medium annual income but high annual spend
Cluster 4 straight away is one potential customer segment. However, Cluster 2 and 3 can be segmented further to arrive at a more specific target customer group. Let us now look at how the clusters are created when k=6:
##Fitting kmeans to the dataset - k=6km4=KMeans(n_clusters=6,init='k-means++', max_iter=300, n_init=10, random_state=0)y_means = km4.fit_predict(X)#Visualizing the clustersplt.scatter(X[y_means==0,0],X[y_means==0,1],s=50, c='purple',label='Cluster1')plt.scatter(X[y_means==1,0],X[y_means==1,1],s=50, c='blue',label='Cluster2')plt.scatter(X[y_means==2,0],X[y_means==2,1],s=50, c='green',label='Cluster3')plt.scatter(X[y_means==3,0],X[y_means==3,1],s=50, c='cyan',label='Cluster4')plt.scatter(X[y_means==4,0],X[y_means==4,1],s=50, c='magenta',label='Cluster5')plt.scatter(X[y_means==5,0],X[y_means==5,1],s=50, c='orange',label='Cluster6')plt.scatter(km.cluster_centers_[:,0], km.cluster_centers_[:,1],s=200,marker='s', c='red', alpha=0.7, label='Centroids')plt.title('Customer segments')plt.xlabel('Annual income of customer')plt.ylabel('Annual spend from customer on site')plt.legend()plt.show()
Setting the number of clusters to 6 seems to provide a more meaningful customer segmentation.
Cluster 1: Medium income, low annual spendCluster 2: Low income, low annual spendCluster 3: High income, high annual spendCluster 4: Low income, high annual spendCluster 5: Medium income, low annual spendCluster 6: Very high income, high annual spend
Cluster 1: Medium income, low annual spend
Cluster 2: Low income, low annual spend
Cluster 3: High income, high annual spend
Cluster 4: Low income, high annual spend
Cluster 5: Medium income, low annual spend
Cluster 6: Very high income, high annual spend
Thus it is evident that 6 clusters provides a more meaningful segmentation of the customers.
Marketing strategies for the customer segmentsBased on the 6 clusters, we could formulate marketing strategies relevant to each cluster:
A typical strategy would focus certain promotional efforts for the high value customers of Cluster 6 & Cluster 3.
Cluster 4 is a unique customer segment, where in spite of their relatively lower annual income, these customers tend to spend more on the site, indicating their loyalty. There could be some discounted pricing based promotional campaigns for this group so as to retain them.
For Cluster 2 where both the income and annual spend are low, further analysis could be needed to find the reasons for the lower spend and price-sensitive strategies could be introduced to increase the spend from this segment.
Customers in clusters 1 and 5 are not spending enough on the site in spite of a good annual income — further analysis of these segments could lead to insights on the satisfaction / dissatisfaction of these customers or lesser visibility of the e-commerce site to these customers. Strategies could be evolved accordingly.
We have thus seen, how we could arrive at meaningful insights and recommendations by using clustering algorithms to generate customer segments. For the sake of simplicity, the dataset used only 2 variables — income and spend. In a typical business scenario, there could be several variables which could possibly generate much more realistic and business-specific insights.
|
[
{
"code": null,
"e": 540,
"s": 172,
"text": "ContextIn today’s competitive world, it is crucial to understand customer behavior and categorize customers based on their demography and buying behavior. This is a critical aspect of customer segmentation that allows marketers to better tailor their marketing efforts to various audience subsets in terms of promotional, marketing and product development strategies."
},
{
"code": null,
"e": 952,
"s": 540,
"text": "ObjectiveThis article demonstrates the concept of segmentation of a customer data set from an e-commerce site using k-means clustering in python. The data set contains the annual income of ~300 customers and their annual spend on an e-commerce site. We will use the k-means clustering algorithm to derive the optimum number of clusters and understand the underlying customer segments based on the data provided."
},
{
"code": null,
"e": 1183,
"s": 952,
"text": "About the data setThe dataset consists of Annual income (in $000) of 303 customers and their total spend (in $000) on an e-commerce site for a period of one year. Let us explore the data using numpy and pandas libraries in python."
},
{
"code": null,
"e": 1611,
"s": 1183,
"text": "#Load the required packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt#Plot stylingimport seaborn as sns; sns.set() # for plot styling%matplotlib inlineplt.rcParams['figure.figsize'] = (16, 9)plt.style.use('ggplot')#Read the csv filedataset=pd.read_csv('CLV.csv')#Explore the datasetdataset.head()#top 5 columnslen(dataset) # of rows#descriptive statistics of the datasetdataset.describe().transpose()"
},
{
"code": null,
"e": 1823,
"s": 1611,
"text": "The dataset consists of 303 rows. The mean annual income is 245000 and the mean annual spend is 149000. The distribution of the annual income and annual spend has been illustrated with a distplot and violinplot."
},
{
"code": null,
"e": 1935,
"s": 1823,
"text": "Visualizing the dataThe displot and violinplot give an indication of the data distribution of Income and Spend."
},
{
"code": null,
"e": 2083,
"s": 1935,
"text": "#Visualizing the data - displotplot_income = sns.distplot(dataset[\"INCOME\"])plot_spend = sns.distplot(dataset[\"SPEND\"])plt.xlabel('Income / spend')"
},
{
"code": null,
"e": 2353,
"s": 2083,
"text": "#Violin plot of Income and Spendf, axes = plt.subplots(1,2, figsize=(12,6), sharex=True, sharey=True)v1 = sns.violinplot(data=dataset, x='INCOME', color=\"skyblue\",ax=axes[0])v2 = sns.violinplot(data=dataset, x='SPEND',color=\"lightgreen\", ax=axes[1])v1.set(xlim=(0,420))"
},
{
"code": null,
"e": 2574,
"s": 2353,
"text": "Clustering fundamentalsClustering is an unsupervised machine learning technique, where there are no defined dependent and independent variables. The patterns in the data are used to identify / group similar observations."
},
{
"code": null,
"e": 2847,
"s": 2574,
"text": "The objective of any clustering algorithm is to ensure that the distance between datapoints in a cluster is very low compared to the distance between 2 clusters. In other words, members of a group are very similar, and members of different groups are extremely dissimilar."
},
{
"code": null,
"e": 2951,
"s": 2847,
"text": "We will use are k-means clustering for creating customer segments based on their income and spend data."
},
{
"code": null,
"e": 3185,
"s": 2951,
"text": "K-Means clusteringK-means clustering is an iterative clustering algorithm where the number of clusters K is predetermined and the algorithm iteratively assigns each data point to one of the K clusters based on the feature similarity."
},
{
"code": null,
"e": 3222,
"s": 3185,
"text": "Broad steps of the k-means algorithm"
},
{
"code": null,
"e": 3252,
"s": 3222,
"text": "The mathematics of clustering"
},
{
"code": null,
"e": 3420,
"s": 3252,
"text": "The mathematics behind clustering, in very simple terms involves minimizing the sum of square of distances between the cluster centroid and its associated data points:"
},
{
"code": null,
"e": 3443,
"s": 3420,
"text": "K = number of clusters"
},
{
"code": null,
"e": 3468,
"s": 3443,
"text": "N= number of data points"
},
{
"code": null,
"e": 3492,
"s": 3468,
"text": "C=centroid of cluster j"
},
{
"code": null,
"e": 3569,
"s": 3492,
"text": "(xij — cj)– Distance between data point and centroid to which it is assigned"
},
{
"code": null,
"e": 3890,
"s": 3569,
"text": "Deciding on the optimum number of clusters ‘K’The main input for k-means clustering is the number of clusters. This is derived using the concept of minimizing within cluster sum of square (WCSS). A scree plot is created which plots the number of clusters in the X axis and the WCSS for each cluster number in the y-axis."
},
{
"code": null,
"e": 4297,
"s": 3890,
"text": "As the number of clusters increase, the WCSS keeps decreasing. The decrease of WCSS is initially steep and then the rate of decrease slows down resulting in an elbow plot. The number of clusters at the elbow formation usually gives an indication on the optimum number of clusters. This combined with specific knowledge of the business requirement should be used to decide on the optimum number of clusters."
},
{
"code": null,
"e": 4387,
"s": 4297,
"text": "For our dataset, we will arrive at the optimum number of clusters using the elbow method:"
},
{
"code": null,
"e": 4751,
"s": 4387,
"text": "#Using the elbow method to find the optimum number of clustersfrom sklearn.cluster import KMeanswcss = []for i in range(1,11): km=KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0) km.fit(X) wcss.append(km.inertia_)plt.plot(range(1,11),wcss)plt.title('Elbow Method')plt.xlabel('Number of clusters')plt.ylabel('wcss')plt.show()"
},
{
"code": null,
"e": 4920,
"s": 4751,
"text": "Based on the elbow plot, we could choose 4,5 or 6 clusters. Let us try both the number of clusters and visualize the clusters to decide on the final number of clusters."
},
{
"code": null,
"e": 4964,
"s": 4920,
"text": "Fitting the k-means to the dataset with k=4"
},
{
"code": null,
"e": 5715,
"s": 4964,
"text": "##Fitting kmeans to the dataset with k=4km4=KMeans(n_clusters=4,init='k-means++', max_iter=300, n_init=10, random_state=0)y_means = km4.fit_predict(X)#Visualizing the clusters for k=4plt.scatter(X[y_means==0,0],X[y_means==0,1],s=50, c='purple',label='Cluster1')plt.scatter(X[y_means==1,0],X[y_means==1,1],s=50, c='blue',label='Cluster2')plt.scatter(X[y_means==2,0],X[y_means==2,1],s=50, c='green',label='Cluster3')plt.scatter(X[y_means==3,0],X[y_means==3,1],s=50, c='cyan',label='Cluster4')plt.scatter(km4.cluster_centers_[:,0], km4.cluster_centers_[:,1],s=200,marker='s', c='red', alpha=0.7, label='Centroids')plt.title('Customer segments')plt.xlabel('Annual income of customer')plt.ylabel('Annual spend from customer on site')plt.legend()plt.show()"
},
{
"code": null,
"e": 5826,
"s": 5715,
"text": "The plot shows the distribution of the 4 clusters. We could interpret them as the following customer segments:"
},
{
"code": null,
"e": 6081,
"s": 5826,
"text": "Cluster 1: Customers with medium annual income and low annual spendCluster 2: Customers with high annual income and medium to high annual spendCluster 3: Customers with low annual incomeCluster 4: Customers with medium annual income but high annual spend"
},
{
"code": null,
"e": 6149,
"s": 6081,
"text": "Cluster 1: Customers with medium annual income and low annual spend"
},
{
"code": null,
"e": 6226,
"s": 6149,
"text": "Cluster 2: Customers with high annual income and medium to high annual spend"
},
{
"code": null,
"e": 6270,
"s": 6226,
"text": "Cluster 3: Customers with low annual income"
},
{
"code": null,
"e": 6339,
"s": 6270,
"text": "Cluster 4: Customers with medium annual income but high annual spend"
},
{
"code": null,
"e": 6558,
"s": 6339,
"text": "Cluster 4 straight away is one potential customer segment. However, Cluster 2 and 3 can be segmented further to arrive at a more specific target customer group. Let us now look at how the clusters are created when k=6:"
},
{
"code": null,
"e": 7453,
"s": 6558,
"text": "##Fitting kmeans to the dataset - k=6km4=KMeans(n_clusters=6,init='k-means++', max_iter=300, n_init=10, random_state=0)y_means = km4.fit_predict(X)#Visualizing the clustersplt.scatter(X[y_means==0,0],X[y_means==0,1],s=50, c='purple',label='Cluster1')plt.scatter(X[y_means==1,0],X[y_means==1,1],s=50, c='blue',label='Cluster2')plt.scatter(X[y_means==2,0],X[y_means==2,1],s=50, c='green',label='Cluster3')plt.scatter(X[y_means==3,0],X[y_means==3,1],s=50, c='cyan',label='Cluster4')plt.scatter(X[y_means==4,0],X[y_means==4,1],s=50, c='magenta',label='Cluster5')plt.scatter(X[y_means==5,0],X[y_means==5,1],s=50, c='orange',label='Cluster6')plt.scatter(km.cluster_centers_[:,0], km.cluster_centers_[:,1],s=200,marker='s', c='red', alpha=0.7, label='Centroids')plt.title('Customer segments')plt.xlabel('Annual income of customer')plt.ylabel('Annual spend from customer on site')plt.legend()plt.show()"
},
{
"code": null,
"e": 7547,
"s": 7453,
"text": "Setting the number of clusters to 6 seems to provide a more meaningful customer segmentation."
},
{
"code": null,
"e": 7798,
"s": 7547,
"text": "Cluster 1: Medium income, low annual spendCluster 2: Low income, low annual spendCluster 3: High income, high annual spendCluster 4: Low income, high annual spendCluster 5: Medium income, low annual spendCluster 6: Very high income, high annual spend"
},
{
"code": null,
"e": 7841,
"s": 7798,
"text": "Cluster 1: Medium income, low annual spend"
},
{
"code": null,
"e": 7881,
"s": 7841,
"text": "Cluster 2: Low income, low annual spend"
},
{
"code": null,
"e": 7923,
"s": 7881,
"text": "Cluster 3: High income, high annual spend"
},
{
"code": null,
"e": 7964,
"s": 7923,
"text": "Cluster 4: Low income, high annual spend"
},
{
"code": null,
"e": 8007,
"s": 7964,
"text": "Cluster 5: Medium income, low annual spend"
},
{
"code": null,
"e": 8054,
"s": 8007,
"text": "Cluster 6: Very high income, high annual spend"
},
{
"code": null,
"e": 8147,
"s": 8054,
"text": "Thus it is evident that 6 clusters provides a more meaningful segmentation of the customers."
},
{
"code": null,
"e": 8284,
"s": 8147,
"text": "Marketing strategies for the customer segmentsBased on the 6 clusters, we could formulate marketing strategies relevant to each cluster:"
},
{
"code": null,
"e": 8398,
"s": 8284,
"text": "A typical strategy would focus certain promotional efforts for the high value customers of Cluster 6 & Cluster 3."
},
{
"code": null,
"e": 8672,
"s": 8398,
"text": "Cluster 4 is a unique customer segment, where in spite of their relatively lower annual income, these customers tend to spend more on the site, indicating their loyalty. There could be some discounted pricing based promotional campaigns for this group so as to retain them."
},
{
"code": null,
"e": 8899,
"s": 8672,
"text": "For Cluster 2 where both the income and annual spend are low, further analysis could be needed to find the reasons for the lower spend and price-sensitive strategies could be introduced to increase the spend from this segment."
},
{
"code": null,
"e": 9220,
"s": 8899,
"text": "Customers in clusters 1 and 5 are not spending enough on the site in spite of a good annual income — further analysis of these segments could lead to insights on the satisfaction / dissatisfaction of these customers or lesser visibility of the e-commerce site to these customers. Strategies could be evolved accordingly."
}
] |
A guide to getting to know ggplot2 visualization in R from zero. | Towards Data Science
|
I am originally a Python user, and I have used Python for all of my analytical tasks. Thus, I did not think it was necessary to know R simultaneously. However, as I am studying for my master’s in Statistics, I’ve been increasingly interested in the R programming language, especially its stunning graphics.
I found R visualization incredibly user-friendly, especially with statistical visualization tasks. And ggplot2 is one of the most helpful packages to which I believe it is worth devoting my effort to learn deeper. I had an article about the overview of basic plots in ggplot2, Guide To Data Visualization With ggplot2, as you can find it here.
Since I want to learn more about ggplot2 for future research, I decided to take the challenge of mastering this visualization package within 7 days. And Medium will be where I keep track of my progress achievement. Hopefully, this will provide me with the motivation to accomplish my challenge while also sharing what I’ve learned with readers.
In my first article, I am going to show you what I have explored in making neat and nice bar charts.
The bar graph is frequently used to depict the distribution of a variable’s values or to compare data from different sub-groups within a data category. I believe that a bar chart is one of the most useful and powerful basic graphs that helps us gain significant insights in a variety of situations. Thus, anytime I learn a new visualization library, I usually begin with a bar chart.
But first, let me show you the dataset that I am going to work on through this article. You can easily get the dataset in R regclass package. I will select dataset EX2.TIPS, which is the record of tip amount in different parties for my practice.
Here is the summary of the dataset:
library(regclass)library("skimr")data(EX2.TIPS)skim(EX2.TIPS)
Let’s start with a simple plot.
Target: I want to find how many females and males are in the dataset. In other words, I want to see the distribution of the variable “Gender”. The plot can be done simply with the call of ggplotand geom_bar.
library(ggplot2)library('dplyr') #Count number of people in each gendercount_gender <- EX2.TIPS%>% group_by(Gender) %>% summarise(count= n())#Plot x = gender, y= gender countggplot(count_gender, aes(x = Gender, y=count)) + geom_bar()
But wait, the graph seems a little simple without a header and color. Don’t worry. You can easily customize your bar chart with different attributes, such as the color, the width of the bars. Here are several contributes you can use to update your chart.
In order to change your bar chart’s color, identify your chosen color with fill attribute in geom_barTo change the color border of bar charts, use color attribute.
To change x,y axes’ names, use ggtitle, xlab, ylab
To customize x, y axes, and title font or color, make changes to theme
To get value number on each bar, add ageom_text
ggplot(count_gender, aes(x = Gender,y=count)) + #customize bars geom_bar(color="black", fill = "pink", width= 0.5, stat='identity') +#adding values numbers geom_text(aes(label = count), vjust = -0.25) +#customize x,y axes and title ggtitle("Distribution of Gender") + xlab("Gender") + ylab("Total")) +#change font theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5 ), axis.title.x = element_text(color="black", size=11, face="bold"), axis.title.y = element_text(color="black", size=11, face="bold"))
In case you do not want a vertical bar chart, but a horizontal one. It’s very simple, just add a coord_flip() element. And here is what we get:
As you can see in the graph, obviously the number of men going to the party is nearly two times as females.
Target: For each day of the week, I want to compare the total of men going to parties compared to women.
I can do this by using a stacked bar chart to observe the difference between these two genders.
A stacked bar chart is achieved by setting position in geom_bar to “stack”. Besides, by getting fill equal “Gender”, ggplot will generate a bar chart where each bar (representing each level of the “Weekday” variable) is contributed by all levels in “Gender” variable.
Here is how my simple stacked bar chart looks like:
ggplot(EX2.TIPS, aes(x = Weekday,fill=Gender)) + geom_bar(position = "stack")
As we can see in the above graph, there are two levels of Gender and four levels of Weekday, and there is a value for the number of people in each gender on each day of the week.
However, in order to compare the ratio of males and females on different days of the week, I prefer to use a segmented bar plot. It is a type of stacked bar chart where the sum of each bar is 100%. By specifying the argument position = "fill" in geom_bar , we can easily have a segmented bar plot as below:
ggplot(EX2.TIPS, aes(x = Weekday,fill=Gender)) + geom_bar(position = "fill")
Now, let’s try to improve this segmented bar chart by adding labels, titles, and customizing the x-axis, y-axis, etc. Besides some of the control elements mentioned above, we also have:
scale_y_continuous control position scale for continuous data (y)
scale_fll_brewer set color fills for bar chart
Installing packages ggthemes for different chart backgrounds.
In detail, you can see the code below:
#Calculating the percentage of both genders in each day of the weekpctdata <- EX2.TIPS %>% group_by(Weekday,Gender ) %>% summarize(count = n()) %>% mutate(pct = count/sum(count), percent_scale = scales::percent(pct))#Plotting ggplot(pctdata, aes(x = Weekday, y=pct, fill=Gender)) + geom_bar(position = "fill", stat = 'identity') +#Adjusting y-axis tick mark scale_y_continuous(breaks = seq(0, 1, .2), label = percent) + #Adding value label geom_text(aes(label = percent_scale), size = 3, position = position_stack(vjust = 0.5)) + #Adusting color fill scale_fill_brewer(palette = "Set3") + #Adjusting title, labels ggtitle("Gender Distribution") + xlab("Days of Week") + ylab("Percentage") +#Changing theme theme_stata() + theme( plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5 ), axis.title.x = element_text(color="black", size=11, face="bold"), axis.title.y = element_text(color="black", size=11, face="bold" ))
Target: I want to track the number of both females and males going to party during different days of the week.
I can use a grouped bar chart to see the trend of both genders during the week.
So, how can I get a grouped bar chart? With ggplot, it is simple as you just have to change the position in geom_bar element to dodge. Meanwhile, every other thing is done similarly as we plotted the simple bar chart.
ggplot(count_day, aes(x = Weekday, y=count, fill=Gender)) + geom_bar(position = "dodge", stat = 'identity') + geom_text(aes(label = count), colour = "black", size = 3, vjust = 1.5, position = position_dodge(.9)) + scale_fill_brewer(palette = "Set3") + ggtitle("Number of females/males by days of the week") + xlab("Days of Week") + ylab("Total number") + theme_stata()+ theme( plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5 ), axis.title.x = element_text(color="black", size=11, face="bold"), axis.title.y = element_text(color="black", size=11, face="bold" ))
Sometimes, we want to put 2 graphs side by side for easier comparison. While searching for a solution that I can use flexibly, I came across this website. I have to say that it is very detailed, and the solution is easy to customize. I will apply their suggestion to my case here by using grid library.
For instance, I want to get my Gender distribution graph (denoted by p) and Number of females/males by days of the week (denoted by m) side by side. Here is how I do it:
library(grid)# Creating a new page grid.newpage()# Create layout: nrow = 1, ncol = 2 pushViewport(viewport(layout = grid.layout(nrow = 1, ncol = 2))) # A helper function to define a region on the layout define_region <- function(row, col){ viewport(layout.pos.row = row, layout.pos.col = col) } # Identify plot positions print(p, vp = define_region(row = 1, col = 1)) print(m, vp = define_region(row = 1, col = 2))
Yeah. That’s what I learned about Bar Graph in ggplot2 for day 1 in my 7-day challenge to master ggplot2. If you have anything interesting to share with me about this cool library. Let me know. I will be back soon with day 2’s topic: Line graph.
|
[
{
"code": null,
"e": 479,
"s": 172,
"text": "I am originally a Python user, and I have used Python for all of my analytical tasks. Thus, I did not think it was necessary to know R simultaneously. However, as I am studying for my master’s in Statistics, I’ve been increasingly interested in the R programming language, especially its stunning graphics."
},
{
"code": null,
"e": 823,
"s": 479,
"text": "I found R visualization incredibly user-friendly, especially with statistical visualization tasks. And ggplot2 is one of the most helpful packages to which I believe it is worth devoting my effort to learn deeper. I had an article about the overview of basic plots in ggplot2, Guide To Data Visualization With ggplot2, as you can find it here."
},
{
"code": null,
"e": 1168,
"s": 823,
"text": "Since I want to learn more about ggplot2 for future research, I decided to take the challenge of mastering this visualization package within 7 days. And Medium will be where I keep track of my progress achievement. Hopefully, this will provide me with the motivation to accomplish my challenge while also sharing what I’ve learned with readers."
},
{
"code": null,
"e": 1269,
"s": 1168,
"text": "In my first article, I am going to show you what I have explored in making neat and nice bar charts."
},
{
"code": null,
"e": 1653,
"s": 1269,
"text": "The bar graph is frequently used to depict the distribution of a variable’s values or to compare data from different sub-groups within a data category. I believe that a bar chart is one of the most useful and powerful basic graphs that helps us gain significant insights in a variety of situations. Thus, anytime I learn a new visualization library, I usually begin with a bar chart."
},
{
"code": null,
"e": 1899,
"s": 1653,
"text": "But first, let me show you the dataset that I am going to work on through this article. You can easily get the dataset in R regclass package. I will select dataset EX2.TIPS, which is the record of tip amount in different parties for my practice."
},
{
"code": null,
"e": 1935,
"s": 1899,
"text": "Here is the summary of the dataset:"
},
{
"code": null,
"e": 1997,
"s": 1935,
"text": "library(regclass)library(\"skimr\")data(EX2.TIPS)skim(EX2.TIPS)"
},
{
"code": null,
"e": 2029,
"s": 1997,
"text": "Let’s start with a simple plot."
},
{
"code": null,
"e": 2237,
"s": 2029,
"text": "Target: I want to find how many females and males are in the dataset. In other words, I want to see the distribution of the variable “Gender”. The plot can be done simply with the call of ggplotand geom_bar."
},
{
"code": null,
"e": 2476,
"s": 2237,
"text": "library(ggplot2)library('dplyr') #Count number of people in each gendercount_gender <- EX2.TIPS%>% group_by(Gender) %>% summarise(count= n())#Plot x = gender, y= gender countggplot(count_gender, aes(x = Gender, y=count)) + geom_bar()"
},
{
"code": null,
"e": 2731,
"s": 2476,
"text": "But wait, the graph seems a little simple without a header and color. Don’t worry. You can easily customize your bar chart with different attributes, such as the color, the width of the bars. Here are several contributes you can use to update your chart."
},
{
"code": null,
"e": 2895,
"s": 2731,
"text": "In order to change your bar chart’s color, identify your chosen color with fill attribute in geom_barTo change the color border of bar charts, use color attribute."
},
{
"code": null,
"e": 2946,
"s": 2895,
"text": "To change x,y axes’ names, use ggtitle, xlab, ylab"
},
{
"code": null,
"e": 3017,
"s": 2946,
"text": "To customize x, y axes, and title font or color, make changes to theme"
},
{
"code": null,
"e": 3065,
"s": 3017,
"text": "To get value number on each bar, add ageom_text"
},
{
"code": null,
"e": 3665,
"s": 3065,
"text": "ggplot(count_gender, aes(x = Gender,y=count)) + #customize bars geom_bar(color=\"black\", fill = \"pink\", width= 0.5, stat='identity') +#adding values numbers geom_text(aes(label = count), vjust = -0.25) +#customize x,y axes and title ggtitle(\"Distribution of Gender\") + xlab(\"Gender\") + ylab(\"Total\")) +#change font theme(plot.title = element_text(color=\"black\", size=14, face=\"bold\", hjust = 0.5 ), axis.title.x = element_text(color=\"black\", size=11, face=\"bold\"), axis.title.y = element_text(color=\"black\", size=11, face=\"bold\"))"
},
{
"code": null,
"e": 3809,
"s": 3665,
"text": "In case you do not want a vertical bar chart, but a horizontal one. It’s very simple, just add a coord_flip() element. And here is what we get:"
},
{
"code": null,
"e": 3917,
"s": 3809,
"text": "As you can see in the graph, obviously the number of men going to the party is nearly two times as females."
},
{
"code": null,
"e": 4022,
"s": 3917,
"text": "Target: For each day of the week, I want to compare the total of men going to parties compared to women."
},
{
"code": null,
"e": 4118,
"s": 4022,
"text": "I can do this by using a stacked bar chart to observe the difference between these two genders."
},
{
"code": null,
"e": 4386,
"s": 4118,
"text": "A stacked bar chart is achieved by setting position in geom_bar to “stack”. Besides, by getting fill equal “Gender”, ggplot will generate a bar chart where each bar (representing each level of the “Weekday” variable) is contributed by all levels in “Gender” variable."
},
{
"code": null,
"e": 4438,
"s": 4386,
"text": "Here is how my simple stacked bar chart looks like:"
},
{
"code": null,
"e": 4518,
"s": 4438,
"text": "ggplot(EX2.TIPS, aes(x = Weekday,fill=Gender)) + geom_bar(position = \"stack\")"
},
{
"code": null,
"e": 4697,
"s": 4518,
"text": "As we can see in the above graph, there are two levels of Gender and four levels of Weekday, and there is a value for the number of people in each gender on each day of the week."
},
{
"code": null,
"e": 5004,
"s": 4697,
"text": "However, in order to compare the ratio of males and females on different days of the week, I prefer to use a segmented bar plot. It is a type of stacked bar chart where the sum of each bar is 100%. By specifying the argument position = \"fill\" in geom_bar , we can easily have a segmented bar plot as below:"
},
{
"code": null,
"e": 5083,
"s": 5004,
"text": "ggplot(EX2.TIPS, aes(x = Weekday,fill=Gender)) + geom_bar(position = \"fill\")"
},
{
"code": null,
"e": 5269,
"s": 5083,
"text": "Now, let’s try to improve this segmented bar chart by adding labels, titles, and customizing the x-axis, y-axis, etc. Besides some of the control elements mentioned above, we also have:"
},
{
"code": null,
"e": 5335,
"s": 5269,
"text": "scale_y_continuous control position scale for continuous data (y)"
},
{
"code": null,
"e": 5382,
"s": 5335,
"text": "scale_fll_brewer set color fills for bar chart"
},
{
"code": null,
"e": 5444,
"s": 5382,
"text": "Installing packages ggthemes for different chart backgrounds."
},
{
"code": null,
"e": 5483,
"s": 5444,
"text": "In detail, you can see the code below:"
},
{
"code": null,
"e": 6519,
"s": 5483,
"text": "#Calculating the percentage of both genders in each day of the weekpctdata <- EX2.TIPS %>% group_by(Weekday,Gender ) %>% summarize(count = n()) %>% mutate(pct = count/sum(count), percent_scale = scales::percent(pct))#Plotting ggplot(pctdata, aes(x = Weekday, y=pct, fill=Gender)) + geom_bar(position = \"fill\", stat = 'identity') +#Adjusting y-axis tick mark scale_y_continuous(breaks = seq(0, 1, .2), label = percent) + #Adding value label geom_text(aes(label = percent_scale), size = 3, position = position_stack(vjust = 0.5)) + #Adusting color fill scale_fill_brewer(palette = \"Set3\") + #Adjusting title, labels ggtitle(\"Gender Distribution\") + xlab(\"Days of Week\") + ylab(\"Percentage\") +#Changing theme theme_stata() + theme( plot.title = element_text(color=\"black\", size=14, face=\"bold\", hjust = 0.5 ), axis.title.x = element_text(color=\"black\", size=11, face=\"bold\"), axis.title.y = element_text(color=\"black\", size=11, face=\"bold\" ))"
},
{
"code": null,
"e": 6630,
"s": 6519,
"text": "Target: I want to track the number of both females and males going to party during different days of the week."
},
{
"code": null,
"e": 6710,
"s": 6630,
"text": "I can use a grouped bar chart to see the trend of both genders during the week."
},
{
"code": null,
"e": 6928,
"s": 6710,
"text": "So, how can I get a grouped bar chart? With ggplot, it is simple as you just have to change the position in geom_bar element to dodge. Meanwhile, every other thing is done similarly as we plotted the simple bar chart."
},
{
"code": null,
"e": 7592,
"s": 6928,
"text": "ggplot(count_day, aes(x = Weekday, y=count, fill=Gender)) + geom_bar(position = \"dodge\", stat = 'identity') + geom_text(aes(label = count), colour = \"black\", size = 3, vjust = 1.5, position = position_dodge(.9)) + scale_fill_brewer(palette = \"Set3\") + ggtitle(\"Number of females/males by days of the week\") + xlab(\"Days of Week\") + ylab(\"Total number\") + theme_stata()+ theme( plot.title = element_text(color=\"black\", size=14, face=\"bold\", hjust = 0.5 ), axis.title.x = element_text(color=\"black\", size=11, face=\"bold\"), axis.title.y = element_text(color=\"black\", size=11, face=\"bold\" )) "
},
{
"code": null,
"e": 7895,
"s": 7592,
"text": "Sometimes, we want to put 2 graphs side by side for easier comparison. While searching for a solution that I can use flexibly, I came across this website. I have to say that it is very detailed, and the solution is easy to customize. I will apply their suggestion to my case here by using grid library."
},
{
"code": null,
"e": 8065,
"s": 7895,
"text": "For instance, I want to get my Gender distribution graph (denoted by p) and Number of females/males by days of the week (denoted by m) side by side. Here is how I do it:"
},
{
"code": null,
"e": 8486,
"s": 8065,
"text": "library(grid)# Creating a new page grid.newpage()# Create layout: nrow = 1, ncol = 2 pushViewport(viewport(layout = grid.layout(nrow = 1, ncol = 2))) # A helper function to define a region on the layout define_region <- function(row, col){ viewport(layout.pos.row = row, layout.pos.col = col) } # Identify plot positions print(p, vp = define_region(row = 1, col = 1)) print(m, vp = define_region(row = 1, col = 2))"
}
] |
Flex - DataGrid Control
|
The DataGrid control displays a row of column headings above a scrollable grid.
Following is the declaration for spark.components.DataGrid class −
public class DataGrid
extends SkinnableContainerBase
implements IFocusManagerComponent, IIMESupport
Following are the Public Properties for DataGrid Control.
columnsLength : int
[read-only] Returns the value of columns.length if the columns IList was specified, otherwise 0.
dataProvider : IList
A list of data items that correspond to the rows in the grid.
dataProviderLength : int
[read-only] Returns the value of dataProvider.length if the dataProvider IList was specified, otherwise 0.
dataTipField : String
The name of the field in the data provider to display as the datatip.
dataTipFunction : Function
Specifies a callback function to run on each item of the data provider to determine its data tip.
editable : Boolean
The default value for the GridColumn editable property, which indicates if a corresponding cell's data provider item can be edited.
editorColumnIndex : int
[read-only] The zero-based column index of the cell that is being edited.
editorRowIndex : int
[read-only] The zero-based row index of the cell that is being edited.
enableIME : Boolean
[read-only] A flag that indicates whether the IME should be enabled when the component receives focus.
imeMode : String
The default value for the GridColumn imeMode property, which specifies the IME (Input Method Editor) mode.
itemEditor : IFactory
The default value for the GridColumn itemEditor property, which specifies the IGridItemEditor class used to create item editor instances.
itemEditorInstance : IGridItemEditor
[read-only] A reference to the currently active instance of the item editor, if it exists.
itemRenderer : IFactory
The item renderer that's used for columns that do not specify one.
preserveSelection : Boolean
If true, the selection is preserved when the data provider refreshes its collection.
requestedColumnCount : int
The measured width of this grid is large enough to display the first requestedColumnCount columns.
requestedMaxRowCount : int
The measured height of the grid is large enough to display no more than requestedMaxRowCount rows.
requestedMinColumnCount : int
The measured width of this grid is large enough to display at least requestedMinColumnCount columns.
requestedMinRowCount : int
The measured height of this grid is large enough to display at least requestedMinRowCount rows.
requestedRowCount : int
The measured height of this grid is large enough to display the first requestedRowCount rows.
requireSelection : Boolean
If true and the selectionMode property is not GridSelectionMode.NONE, an item must always be selected in the grid.
resizableColumns : Boolean
Indicates whether the user can change the size of the columns.
rowHeight : Number
If variableRowHeight is false, then this property specifies the actual height of each row, in pixels.
selectedCell : CellPosition
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns the first selected cell starting at row 0 column 0 and progressing through each column in a row before moving to the next row.
selectedCells : Vector.<CellPosition>
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns a Vector of CellPosition Objects representing the positions of the selected cells in the grid.
selectedIndex : int
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the rowIndex of the first selected row.
selectedIndices : Vector.<int>
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns a Vector of the selected rows indices.
selectedItem : Object
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the item in the the data provider that is currently selected or undefined if no rows are selected.
selectedItems : Vector.<Object>
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns a Vector of the dataProvider items that are currently selected.
selectionLength : int
[read-only] If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the number of selected rows.
selectionMode : String
The selection mode of the control.
showDataTips : Boolean
If true then a dataTip is displayed for all visible cells.
sortableColumns : Boolean
Specifies whether the user can interactively sort columns.
typicalItem : Object
The grid's layout ensures that columns whose width is not specified is wide enough to display an item renderer for this default data provider item.
variableRowHeight : Boolean
If true, each row's height is the maximum of preferred heights of the cells displayed so far.
columns : IList
The list of GridColumn Objects displayed by this grid.
Following are the Public Properties for DataGrid Control.
DataGrid()
Constructor.
addSelectedCell(rowIndex:int, columnIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, adds the cell to the selection and sets the caret position to the cell.
addSelectedIndex(rowIndex:int):Boolean
If selectionMode is GridSelectionMode.MULTIPLE_ROWS, adds this row to the selection and sets the caret position to this row.
clearSelection():Boolean
Removes all of the selected rows and cells, if selectionMode is not GridSelectionMode.NONE.
endItemEditorSession(cancel:Boolean = false):Boolean
Closes the currently active editor and optionally saves the editor's value by calling the item editor's save() method.
ensureCellIsVisible(rowIndex:int, columnIndex:int = -1):void
If necessary, set the verticalScrollPosition and horizontalScrollPosition properties so that the specified cell is completely visible.
invalidateCell(rowIndex:int, columnIndex:int):void
If the specified cell is visible, it is redisplayed.
invalidateTypicalItem():void
removeSelectedCell(rowIndex:int, columnIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, removes the cell from the selection and sets the caret position to the cell.
removeSelectedIndex(rowIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, removes this row from the selection and sets the caret position to this row.
selectAll():Boolean
If selectionMode is GridSelectionMode.MULTIPLE_ROWS, selects all rows and removes the caret or if selectionMode is GridSelectionMode.MULTIPLE_CELLS selects all cells and removes the caret.
selectCellRegion(rowIndex:int, columnIndex:int, rowCount:uint, columnCount:uint):Boolean
If selectionMode is GridSelectionMode.MULTIPLE_CELLS, sets the selection to all the cells in the cell region and the caret position to the last cell in the cell region.
selectIndices(rowIndex:int, rowCount:int):Boolean
If selectionMode is GridSelectionMode.MULTIPLE_ROWS, sets the selection to the specfied rows and the caret position to endRowIndex.
selectionContainsCell(rowIndex:int, columnIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns true if the cell is in the current selection.
selectionContainsCellRegion(rowIndex:int, columnIndex:int, rowCount:int, columnCount:int):Boolean
If selectionMode is GridSelectionMode.MULTIPLE_CELLS, returns true if the cells in the cell region are in the current selection.
selectionContainsIndex(rowIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns true if the row at index is in the current selection.
selectionContainsIndices(rowIndices:Vector.<int>):Boolean
If selectionMode is GridSelectionMode.MULTIPLE_ROWS, returns true if the rows in indices are in the current selection.
setSelectedCell(rowIndex:int, columnIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, sets the selection and the caret position to this cell.
setSelectedIndex(rowIndex:int):Boolean
If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, sets the selection and the caret position to this row.
sortByColumns(columnIndices:Vector.<int>, isInteractive:Boolean = false):Boolean
Sort the DataGrid by one or more columns, and refresh the display.
startItemEditorSession(rowIndex:int, columnIndex:int):Boolean
Starts an editor session on a selected cell in the grid.
commitCaretPosition(newCaretRowIndex:int, newCaretColumnIndex:int):void
Updates the grid's caret position.
commitInteractiveSelection(selectionEventKind:String, rowIndex:int, columnIndex:int, rowCount:int = 1, columnCount:int = 1):Boolean
In response to user input (mouse or keyboard) which changes the selection, this method dispatches the selectionChanging event.
caretChange
Dispatched by the grid skin part when the caret position, size, or visibility has changed due to user interaction or being programmatically set.
gridClick
Dispatched by the grid skin part when the mouse is clicked over a cell.
gridDoubleClick
Dispatched by the grid skin part when the mouse is double-clicked over a cell.
gridItemEditorSessionCancel
Dispatched after the item editor has been closed without saving its data.
gridItemEditorSessionSave
Dispatched after the data in item editor has been saved into the data provider and the editor has been closed.
gridItemEditorSessionStart
Dispatched immediately after an item editor has been opened.
gridItemEditorSessionStarting
Dispatched when a new item editor session has been requested.
gridMouseDown
Dispatched by the grid skin part when the mouse button is pressed over a grid cell.
gridMouseDrag
Dispatched by the grid skin part after a gridMouseDown event if the mouse moves before the button is released.
gridMouseUp
Dispatched by the grid skin part after a gridMouseDown event when the mouse button is released, even if the mouse is no longer within the grid.
gridRollOut
Dispatched by the grid skin part when the mouse leaves a grid cell.
gridRollOver
Dispatched by the grid skin part when the mouse enters a grid cell.
selectionChange
Dispatched when the selection has changed.
selectionChanging
Dispatched when the selection is going to change.
sortChange
Dispatched after the sort has been applied to the data provider's collection.
sortChanging
Dispatched before the sort has been applied to the data provider's collection.
This class inherits methods from the following classes −
spark.components.supportClasses.SkinnableContainerBase
spark.components.supportClasses.SkinnableComponent
mx.core.UIComponent
mx.core.FlexSprite
flash.display.Sprite
flash.display.DisplayObjectContainer
flash.display.InteractiveObject
flash.display.DisplayObject
flash.events.EventDispatcher
Object
Let us follow the following steps to check usage of DataGrid control in a Flex application by creating a test application −
Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml.
<?xml version = "1.0" encoding = "utf-8"?>
<s:Application xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx"
width = "100%" height = "100%" minWidth = "500" minHeight = "500">
<fx:Style source = "/com/tutorialspoint/client/Style.css" />
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
public var data:ArrayCollection = new ArrayCollection ([
{value:"France", code:"FR"},
{value:"Japan", code:"JP"},
{value:"India", code:"IN"},
{value:"Russia", code:"RS"},
{value:"United States", code:"US"}
]);
]]>
</fx:Script>
<s:BorderContainer width = "630" height = "480" id = "mainContainer"
styleName = "container">
<s:VGroup width = "100%" height = "100%" gap = "50"
horizontalAlign = "center" verticalAlign = "middle">
<s:Label id = "lblHeader" text = "Complex Controls Demonstration"
fontSize = "40" color = "0x777777" styleName = "heading" />
<s:Panel id = "dataGridPanel" title = "Using DataGrid"
width = "500" height = "300">
<s:layout>
<s:VerticalLayout gap = "10" verticalAlign = "middle"
horizontalAlign = "center" />
</s:layout>
<s:DataGrid dataProvider = "{data}" id = "dataGrid">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField = "code" width = "100"
headerText = "Code" />
<s:GridColumn dataField = "value" width = "200"
headerText = "Value" />
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:HGroup width = "60%">
<s:Label text = "Code :" />
<s:Label text = "{dataGrid.selectedItem.code}" fontWeight = "bold" />
<s:Label text = "Value :" />
<s:Label text = "{dataGrid.selectedItem.value}" fontWeight = "bold" />
</s:HGroup>
</s:Panel>
</s:VGroup>
</s:BorderContainer>
</s:Application>
Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
12 Lectures
1 hours
Prof. Paul Cline, Ed.D
87 Lectures
11 hours
Code And Create
30 Lectures
1 hours
Faigy Liebermann
11 Lectures
1.5 hours
Prof Krishna N Sharma
32 Lectures
34 mins
Prof Krishna N Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2127,
"s": 2047,
"text": "The DataGrid control displays a row of column headings above a scrollable grid."
},
{
"code": null,
"e": 2194,
"s": 2127,
"text": "Following is the declaration for spark.components.DataGrid class −"
},
{
"code": null,
"e": 2307,
"s": 2194,
"text": "public class DataGrid \n extends SkinnableContainerBase \n implements IFocusManagerComponent, IIMESupport"
},
{
"code": null,
"e": 2365,
"s": 2307,
"text": "Following are the Public Properties for DataGrid Control."
},
{
"code": null,
"e": 2385,
"s": 2365,
"text": "columnsLength : int"
},
{
"code": null,
"e": 2482,
"s": 2385,
"text": "[read-only] Returns the value of columns.length if the columns IList was specified, otherwise 0."
},
{
"code": null,
"e": 2503,
"s": 2482,
"text": "dataProvider : IList"
},
{
"code": null,
"e": 2565,
"s": 2503,
"text": "A list of data items that correspond to the rows in the grid."
},
{
"code": null,
"e": 2590,
"s": 2565,
"text": "dataProviderLength : int"
},
{
"code": null,
"e": 2697,
"s": 2590,
"text": "[read-only] Returns the value of dataProvider.length if the dataProvider IList was specified, otherwise 0."
},
{
"code": null,
"e": 2719,
"s": 2697,
"text": "dataTipField : String"
},
{
"code": null,
"e": 2789,
"s": 2719,
"text": "The name of the field in the data provider to display as the datatip."
},
{
"code": null,
"e": 2816,
"s": 2789,
"text": "dataTipFunction : Function"
},
{
"code": null,
"e": 2914,
"s": 2816,
"text": "Specifies a callback function to run on each item of the data provider to determine its data tip."
},
{
"code": null,
"e": 2933,
"s": 2914,
"text": "editable : Boolean"
},
{
"code": null,
"e": 3065,
"s": 2933,
"text": "The default value for the GridColumn editable property, which indicates if a corresponding cell's data provider item can be edited."
},
{
"code": null,
"e": 3089,
"s": 3065,
"text": "editorColumnIndex : int"
},
{
"code": null,
"e": 3163,
"s": 3089,
"text": "[read-only] The zero-based column index of the cell that is being edited."
},
{
"code": null,
"e": 3184,
"s": 3163,
"text": "editorRowIndex : int"
},
{
"code": null,
"e": 3255,
"s": 3184,
"text": "[read-only] The zero-based row index of the cell that is being edited."
},
{
"code": null,
"e": 3275,
"s": 3255,
"text": "enableIME : Boolean"
},
{
"code": null,
"e": 3378,
"s": 3275,
"text": "[read-only] A flag that indicates whether the IME should be enabled when the component receives focus."
},
{
"code": null,
"e": 3395,
"s": 3378,
"text": "imeMode : String"
},
{
"code": null,
"e": 3502,
"s": 3395,
"text": "The default value for the GridColumn imeMode property, which specifies the IME (Input Method Editor) mode."
},
{
"code": null,
"e": 3524,
"s": 3502,
"text": "itemEditor : IFactory"
},
{
"code": null,
"e": 3662,
"s": 3524,
"text": "The default value for the GridColumn itemEditor property, which specifies the IGridItemEditor class used to create item editor instances."
},
{
"code": null,
"e": 3699,
"s": 3662,
"text": "itemEditorInstance : IGridItemEditor"
},
{
"code": null,
"e": 3791,
"s": 3699,
"text": "[read-only] A reference to the currently active instance of the item editor, if it exists.\n"
},
{
"code": null,
"e": 3815,
"s": 3791,
"text": "itemRenderer : IFactory"
},
{
"code": null,
"e": 3882,
"s": 3815,
"text": "The item renderer that's used for columns that do not specify one."
},
{
"code": null,
"e": 3910,
"s": 3882,
"text": "preserveSelection : Boolean"
},
{
"code": null,
"e": 3995,
"s": 3910,
"text": "If true, the selection is preserved when the data provider refreshes its collection."
},
{
"code": null,
"e": 4022,
"s": 3995,
"text": "requestedColumnCount : int"
},
{
"code": null,
"e": 4121,
"s": 4022,
"text": "The measured width of this grid is large enough to display the first requestedColumnCount columns."
},
{
"code": null,
"e": 4148,
"s": 4121,
"text": "requestedMaxRowCount : int"
},
{
"code": null,
"e": 4247,
"s": 4148,
"text": "The measured height of the grid is large enough to display no more than requestedMaxRowCount rows."
},
{
"code": null,
"e": 4277,
"s": 4247,
"text": "requestedMinColumnCount : int"
},
{
"code": null,
"e": 4378,
"s": 4277,
"text": "The measured width of this grid is large enough to display at least requestedMinColumnCount columns."
},
{
"code": null,
"e": 4405,
"s": 4378,
"text": "requestedMinRowCount : int"
},
{
"code": null,
"e": 4501,
"s": 4405,
"text": "The measured height of this grid is large enough to display at least requestedMinRowCount rows."
},
{
"code": null,
"e": 4525,
"s": 4501,
"text": "requestedRowCount : int"
},
{
"code": null,
"e": 4619,
"s": 4525,
"text": "The measured height of this grid is large enough to display the first requestedRowCount rows."
},
{
"code": null,
"e": 4646,
"s": 4619,
"text": "requireSelection : Boolean"
},
{
"code": null,
"e": 4761,
"s": 4646,
"text": "If true and the selectionMode property is not GridSelectionMode.NONE, an item must always be selected in the grid."
},
{
"code": null,
"e": 4788,
"s": 4761,
"text": "resizableColumns : Boolean"
},
{
"code": null,
"e": 4851,
"s": 4788,
"text": "Indicates whether the user can change the size of the columns."
},
{
"code": null,
"e": 4870,
"s": 4851,
"text": "rowHeight : Number"
},
{
"code": null,
"e": 4972,
"s": 4870,
"text": "If variableRowHeight is false, then this property specifies the actual height of each row, in pixels."
},
{
"code": null,
"e": 5000,
"s": 4972,
"text": "selectedCell : CellPosition"
},
{
"code": null,
"e": 5222,
"s": 5000,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns the first selected cell starting at row 0 column 0 and progressing through each column in a row before moving to the next row."
},
{
"code": null,
"e": 5260,
"s": 5222,
"text": "selectedCells : Vector.<CellPosition>"
},
{
"code": null,
"e": 5450,
"s": 5260,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns a Vector of CellPosition Objects representing the positions of the selected cells in the grid."
},
{
"code": null,
"e": 5470,
"s": 5450,
"text": "selectedIndex : int"
},
{
"code": null,
"e": 5603,
"s": 5470,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the rowIndex of the first selected row."
},
{
"code": null,
"e": 5634,
"s": 5603,
"text": "selectedIndices : Vector.<int>"
},
{
"code": null,
"e": 5766,
"s": 5634,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns a Vector of the selected rows indices."
},
{
"code": null,
"e": 5788,
"s": 5766,
"text": "selectedItem : Object"
},
{
"code": null,
"e": 5980,
"s": 5788,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the item in the the data provider that is currently selected or undefined if no rows are selected."
},
{
"code": null,
"e": 6012,
"s": 5980,
"text": "selectedItems : Vector.<Object>"
},
{
"code": null,
"e": 6169,
"s": 6012,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns a Vector of the dataProvider items that are currently selected."
},
{
"code": null,
"e": 6191,
"s": 6169,
"text": "selectionLength : int"
},
{
"code": null,
"e": 6325,
"s": 6191,
"text": "[read-only] If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns the number of selected rows."
},
{
"code": null,
"e": 6348,
"s": 6325,
"text": "selectionMode : String"
},
{
"code": null,
"e": 6383,
"s": 6348,
"text": "The selection mode of the control."
},
{
"code": null,
"e": 6406,
"s": 6383,
"text": "showDataTips : Boolean"
},
{
"code": null,
"e": 6465,
"s": 6406,
"text": "If true then a dataTip is displayed for all visible cells."
},
{
"code": null,
"e": 6491,
"s": 6465,
"text": "sortableColumns : Boolean"
},
{
"code": null,
"e": 6550,
"s": 6491,
"text": "Specifies whether the user can interactively sort columns."
},
{
"code": null,
"e": 6571,
"s": 6550,
"text": "typicalItem : Object"
},
{
"code": null,
"e": 6719,
"s": 6571,
"text": "The grid's layout ensures that columns whose width is not specified is wide enough to display an item renderer for this default data provider item."
},
{
"code": null,
"e": 6747,
"s": 6719,
"text": "variableRowHeight : Boolean"
},
{
"code": null,
"e": 6841,
"s": 6747,
"text": "If true, each row's height is the maximum of preferred heights of the cells displayed so far."
},
{
"code": null,
"e": 6857,
"s": 6841,
"text": "columns : IList"
},
{
"code": null,
"e": 6912,
"s": 6857,
"text": "The list of GridColumn Objects displayed by this grid."
},
{
"code": null,
"e": 6970,
"s": 6912,
"text": "Following are the Public Properties for DataGrid Control."
},
{
"code": null,
"e": 6981,
"s": 6970,
"text": "DataGrid()"
},
{
"code": null,
"e": 6994,
"s": 6981,
"text": "Constructor."
},
{
"code": null,
"e": 7049,
"s": 6994,
"text": "addSelectedCell(rowIndex:int, columnIndex:int):Boolean"
},
{
"code": null,
"e": 7208,
"s": 7049,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, adds the cell to the selection and sets the caret position to the cell."
},
{
"code": null,
"e": 7247,
"s": 7208,
"text": "addSelectedIndex(rowIndex:int):Boolean"
},
{
"code": null,
"e": 7372,
"s": 7247,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_ROWS, adds this row to the selection and sets the caret position to this row."
},
{
"code": null,
"e": 7397,
"s": 7372,
"text": "clearSelection():Boolean"
},
{
"code": null,
"e": 7489,
"s": 7397,
"text": "Removes all of the selected rows and cells, if selectionMode is not GridSelectionMode.NONE."
},
{
"code": null,
"e": 7542,
"s": 7489,
"text": "endItemEditorSession(cancel:Boolean = false):Boolean"
},
{
"code": null,
"e": 7661,
"s": 7542,
"text": "Closes the currently active editor and optionally saves the editor's value by calling the item editor's save() method."
},
{
"code": null,
"e": 7722,
"s": 7661,
"text": "ensureCellIsVisible(rowIndex:int, columnIndex:int = -1):void"
},
{
"code": null,
"e": 7857,
"s": 7722,
"text": "If necessary, set the verticalScrollPosition and horizontalScrollPosition properties so that the specified cell is completely visible."
},
{
"code": null,
"e": 7908,
"s": 7857,
"text": "invalidateCell(rowIndex:int, columnIndex:int):void"
},
{
"code": null,
"e": 7961,
"s": 7908,
"text": "If the specified cell is visible, it is redisplayed."
},
{
"code": null,
"e": 7990,
"s": 7961,
"text": "invalidateTypicalItem():void"
},
{
"code": null,
"e": 8048,
"s": 7990,
"text": "removeSelectedCell(rowIndex:int, columnIndex:int):Boolean"
},
{
"code": null,
"e": 8212,
"s": 8048,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, removes the cell from the selection and sets the caret position to the cell."
},
{
"code": null,
"e": 8254,
"s": 8212,
"text": "removeSelectedIndex(rowIndex:int):Boolean"
},
{
"code": null,
"e": 8416,
"s": 8254,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, removes this row from the selection and sets the caret position to this row."
},
{
"code": null,
"e": 8436,
"s": 8416,
"text": "selectAll():Boolean"
},
{
"code": null,
"e": 8625,
"s": 8436,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_ROWS, selects all rows and removes the caret or if selectionMode is GridSelectionMode.MULTIPLE_CELLS selects all cells and removes the caret."
},
{
"code": null,
"e": 8714,
"s": 8625,
"text": "selectCellRegion(rowIndex:int, columnIndex:int, rowCount:uint, columnCount:uint):Boolean"
},
{
"code": null,
"e": 8883,
"s": 8714,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_CELLS, sets the selection to all the cells in the cell region and the caret position to the last cell in the cell region."
},
{
"code": null,
"e": 8933,
"s": 8883,
"text": "selectIndices(rowIndex:int, rowCount:int):Boolean"
},
{
"code": null,
"e": 9065,
"s": 8933,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_ROWS, sets the selection to the specfied rows and the caret position to endRowIndex."
},
{
"code": null,
"e": 9126,
"s": 9065,
"text": "selectionContainsCell(rowIndex:int, columnIndex:int):Boolean"
},
{
"code": null,
"e": 9267,
"s": 9126,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, returns true if the cell is in the current selection."
},
{
"code": null,
"e": 9365,
"s": 9267,
"text": "selectionContainsCellRegion(rowIndex:int, columnIndex:int, rowCount:int, columnCount:int):Boolean"
},
{
"code": null,
"e": 9494,
"s": 9365,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_CELLS, returns true if the cells in the cell region are in the current selection."
},
{
"code": null,
"e": 9539,
"s": 9494,
"text": "selectionContainsIndex(rowIndex:int):Boolean"
},
{
"code": null,
"e": 9686,
"s": 9539,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, returns true if the row at index is in the current selection."
},
{
"code": null,
"e": 9744,
"s": 9686,
"text": "selectionContainsIndices(rowIndices:Vector.<int>):Boolean"
},
{
"code": null,
"e": 9863,
"s": 9744,
"text": "If selectionMode is GridSelectionMode.MULTIPLE_ROWS, returns true if the rows in indices are in the current selection."
},
{
"code": null,
"e": 9918,
"s": 9863,
"text": "setSelectedCell(rowIndex:int, columnIndex:int):Boolean"
},
{
"code": null,
"e": 10061,
"s": 9918,
"text": "If selectionMode is GridSelectionMode.SINGLE_CELL or GridSelectionMode.MULTIPLE_CELLS, sets the selection and the caret position to this cell."
},
{
"code": null,
"e": 10100,
"s": 10061,
"text": "setSelectedIndex(rowIndex:int):Boolean"
},
{
"code": null,
"e": 10240,
"s": 10100,
"text": "If selectionMode is GridSelectionMode.SINGLE_ROW or GridSelectionMode.MULTIPLE_ROWS, sets the selection and the caret position to this row."
},
{
"code": null,
"e": 10321,
"s": 10240,
"text": "sortByColumns(columnIndices:Vector.<int>, isInteractive:Boolean = false):Boolean"
},
{
"code": null,
"e": 10388,
"s": 10321,
"text": "Sort the DataGrid by one or more columns, and refresh the display."
},
{
"code": null,
"e": 10450,
"s": 10388,
"text": "startItemEditorSession(rowIndex:int, columnIndex:int):Boolean"
},
{
"code": null,
"e": 10507,
"s": 10450,
"text": "Starts an editor session on a selected cell in the grid."
},
{
"code": null,
"e": 10579,
"s": 10507,
"text": "commitCaretPosition(newCaretRowIndex:int, newCaretColumnIndex:int):void"
},
{
"code": null,
"e": 10614,
"s": 10579,
"text": "Updates the grid's caret position."
},
{
"code": null,
"e": 10746,
"s": 10614,
"text": "commitInteractiveSelection(selectionEventKind:String, rowIndex:int, columnIndex:int, rowCount:int = 1, columnCount:int = 1):Boolean"
},
{
"code": null,
"e": 10873,
"s": 10746,
"text": "In response to user input (mouse or keyboard) which changes the selection, this method dispatches the selectionChanging event."
},
{
"code": null,
"e": 10885,
"s": 10873,
"text": "caretChange"
},
{
"code": null,
"e": 11030,
"s": 10885,
"text": "Dispatched by the grid skin part when the caret position, size, or visibility has changed due to user interaction or being programmatically set."
},
{
"code": null,
"e": 11040,
"s": 11030,
"text": "gridClick"
},
{
"code": null,
"e": 11112,
"s": 11040,
"text": "Dispatched by the grid skin part when the mouse is clicked over a cell."
},
{
"code": null,
"e": 11128,
"s": 11112,
"text": "gridDoubleClick"
},
{
"code": null,
"e": 11207,
"s": 11128,
"text": "Dispatched by the grid skin part when the mouse is double-clicked over a cell."
},
{
"code": null,
"e": 11235,
"s": 11207,
"text": "gridItemEditorSessionCancel"
},
{
"code": null,
"e": 11309,
"s": 11235,
"text": "Dispatched after the item editor has been closed without saving its data."
},
{
"code": null,
"e": 11335,
"s": 11309,
"text": "gridItemEditorSessionSave"
},
{
"code": null,
"e": 11446,
"s": 11335,
"text": "Dispatched after the data in item editor has been saved into the data provider and the editor has been closed."
},
{
"code": null,
"e": 11473,
"s": 11446,
"text": "gridItemEditorSessionStart"
},
{
"code": null,
"e": 11534,
"s": 11473,
"text": "Dispatched immediately after an item editor has been opened."
},
{
"code": null,
"e": 11564,
"s": 11534,
"text": "gridItemEditorSessionStarting"
},
{
"code": null,
"e": 11626,
"s": 11564,
"text": "Dispatched when a new item editor session has been requested."
},
{
"code": null,
"e": 11640,
"s": 11626,
"text": "gridMouseDown"
},
{
"code": null,
"e": 11724,
"s": 11640,
"text": "Dispatched by the grid skin part when the mouse button is pressed over a grid cell."
},
{
"code": null,
"e": 11738,
"s": 11724,
"text": "gridMouseDrag"
},
{
"code": null,
"e": 11849,
"s": 11738,
"text": "Dispatched by the grid skin part after a gridMouseDown event if the mouse moves before the button is released."
},
{
"code": null,
"e": 11861,
"s": 11849,
"text": "gridMouseUp"
},
{
"code": null,
"e": 12005,
"s": 11861,
"text": "Dispatched by the grid skin part after a gridMouseDown event when the mouse button is released, even if the mouse is no longer within the grid."
},
{
"code": null,
"e": 12017,
"s": 12005,
"text": "gridRollOut"
},
{
"code": null,
"e": 12085,
"s": 12017,
"text": "Dispatched by the grid skin part when the mouse leaves a grid cell."
},
{
"code": null,
"e": 12098,
"s": 12085,
"text": "gridRollOver"
},
{
"code": null,
"e": 12166,
"s": 12098,
"text": "Dispatched by the grid skin part when the mouse enters a grid cell."
},
{
"code": null,
"e": 12182,
"s": 12166,
"text": "selectionChange"
},
{
"code": null,
"e": 12225,
"s": 12182,
"text": "Dispatched when the selection has changed."
},
{
"code": null,
"e": 12243,
"s": 12225,
"text": "selectionChanging"
},
{
"code": null,
"e": 12293,
"s": 12243,
"text": "Dispatched when the selection is going to change."
},
{
"code": null,
"e": 12304,
"s": 12293,
"text": "sortChange"
},
{
"code": null,
"e": 12382,
"s": 12304,
"text": "Dispatched after the sort has been applied to the data provider's collection."
},
{
"code": null,
"e": 12395,
"s": 12382,
"text": "sortChanging"
},
{
"code": null,
"e": 12474,
"s": 12395,
"text": "Dispatched before the sort has been applied to the data provider's collection."
},
{
"code": null,
"e": 12531,
"s": 12474,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 12586,
"s": 12531,
"text": "spark.components.supportClasses.SkinnableContainerBase"
},
{
"code": null,
"e": 12637,
"s": 12586,
"text": "spark.components.supportClasses.SkinnableComponent"
},
{
"code": null,
"e": 12657,
"s": 12637,
"text": "mx.core.UIComponent"
},
{
"code": null,
"e": 12676,
"s": 12657,
"text": "mx.core.FlexSprite"
},
{
"code": null,
"e": 12697,
"s": 12676,
"text": "flash.display.Sprite"
},
{
"code": null,
"e": 12734,
"s": 12697,
"text": "flash.display.DisplayObjectContainer"
},
{
"code": null,
"e": 12766,
"s": 12734,
"text": "flash.display.InteractiveObject"
},
{
"code": null,
"e": 12794,
"s": 12766,
"text": "flash.display.DisplayObject"
},
{
"code": null,
"e": 12823,
"s": 12794,
"text": "flash.events.EventDispatcher"
},
{
"code": null,
"e": 12830,
"s": 12823,
"text": "Object"
},
{
"code": null,
"e": 12954,
"s": 12830,
"text": "Let us follow the following steps to check usage of DataGrid control in a Flex application by creating a test application −"
},
{
"code": null,
"e": 13045,
"s": 12954,
"text": "Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml."
},
{
"code": null,
"e": 15338,
"s": 13045,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<s:Application xmlns:fx = \"http://ns.adobe.com/mxml/2009\"\n xmlns:s = \"library://ns.adobe.com/flex/spark\"\n xmlns:mx = \"library://ns.adobe.com/flex/mx\"\n width = \"100%\" height = \"100%\" minWidth = \"500\" minHeight = \"500\">\n \n <fx:Style source = \"/com/tutorialspoint/client/Style.css\" />\t\n <fx:Script>\n <![CDATA[\n import mx.collections.ArrayCollection;\n [Bindable]\n public var data:ArrayCollection = new ArrayCollection ([ \n {value:\"France\", code:\"FR\"},\n {value:\"Japan\", code:\"JP\"},\n {value:\"India\", code:\"IN\"},\n {value:\"Russia\", code:\"RS\"},\n {value:\"United States\", code:\"US\"}\t\t\n ]);\n ]]>\n </fx:Script>\n \n <s:BorderContainer width = \"630\" height = \"480\" id = \"mainContainer\" \n styleName = \"container\">\n <s:VGroup width = \"100%\" height = \"100%\" gap = \"50\" \n horizontalAlign = \"center\" verticalAlign = \"middle\">\n <s:Label id = \"lblHeader\" text = \"Complex Controls Demonstration\" \n fontSize = \"40\" color = \"0x777777\" styleName = \"heading\" />\n \n <s:Panel id = \"dataGridPanel\" title = \"Using DataGrid\" \n width = \"500\" height = \"300\">\n <s:layout>\n <s:VerticalLayout gap = \"10\" verticalAlign = \"middle\" \n horizontalAlign = \"center\" />\n </s:layout>\t\t\t\t\t\n \n <s:DataGrid dataProvider = \"{data}\" id = \"dataGrid\">\n <s:columns>\n <s:ArrayList>\n <s:GridColumn dataField = \"code\" width = \"100\" \n headerText = \"Code\" />\n <s:GridColumn dataField = \"value\" width = \"200\" \n headerText = \"Value\" />\n </s:ArrayList>\n </s:columns>\n </s:DataGrid>\n \n <s:HGroup width = \"60%\">\n <s:Label text = \"Code :\" /> \n <s:Label text = \"{dataGrid.selectedItem.code}\" fontWeight = \"bold\" />\n <s:Label text = \"Value :\" /> \n <s:Label text = \"{dataGrid.selectedItem.value}\" fontWeight = \"bold\" />\n </s:HGroup>\n </s:Panel>\n </s:VGroup>\t \n </s:BorderContainer>\t\n</s:Application>"
},
{
"code": null,
"e": 15587,
"s": 15338,
"text": "Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]"
},
{
"code": null,
"e": 15622,
"s": 15587,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 15653,
"s": 15622,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 15686,
"s": 15653,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 15710,
"s": 15686,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 15744,
"s": 15710,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 15761,
"s": 15744,
"text": " Code And Create"
},
{
"code": null,
"e": 15794,
"s": 15761,
"text": "\n 30 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 15812,
"s": 15794,
"text": " Faigy Liebermann"
},
{
"code": null,
"e": 15847,
"s": 15812,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 15870,
"s": 15847,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 15902,
"s": 15870,
"text": "\n 32 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 15925,
"s": 15902,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 15932,
"s": 15925,
"text": " Print"
},
{
"code": null,
"e": 15943,
"s": 15932,
"text": " Add Notes"
}
] |
AIML - <srai> Tag
|
<srai> Tag is a multipurpose tag. This tag enables AIML to define the different targets for the same template.
<srai> pattern </srai>
Following are the commonly used terms associated with srai −
Symbolic Reduction
Symbolic Reduction
Divide and Conquer
Divide and Conquer
Synonyms resolution
Synonyms resolution
Keywords detection
Keywords detection
The symbolic reduction technique is used to simplify patterns. It helps to reduce complex grammatical patterns with simple pattern(s).
For example, consider the following conversation.
Human: Who was Albert Einstein?
Robot: Albert Einstein was a German physicist.
Human: Who was Isaac Newton?
Robot: Isaac Newton was a English physicist and mathematician.
Now What if questions are raised as
Human: DO YOU KNOW WHO Albert Einstein IS?
Human: DO YOU KNOW WHO Isaac Newton IS?
Here, <srai> tag works. It can take the pattern of the user as a template.
<category>
<pattern>WHO IS ALBERT EINSTEIN?</pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON? </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS?</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
Create srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Do you know who Albert Einstein is
Robot: Albert Einstein was a German physicist.
Divide and Conquer is used to reuse sub sentences in making a complete reply. It helps to reduce defining multiple categories.
For example, consider following conversation.
Human: Bye
Robot: GoodBye!
Human: Bye Alice!
Robot: GoodBye!
Now here robot is expected to reply GoodBye! Whenever a user says Bye in the beginning of the sentence.
Let's put <srai> tag to work here.
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Bye
Robot: GoodBye!
Human: Bye Alice!
Robot: GoodBye!
Synonyms are words with similar meanings. A bot should reply in the same manner for similar words.
For example, consider the following conversation.
Human: Factory
Robot: Development Center!
Human: Industry
Robot: Development Center!
Now here robot is expected to reply Development Center! whenever a user says Factory or Industry.
Let's put <srai> tag to work here.
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
0,FACTORY,*,*,Development Center!,srai.aiml
0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Factory
Robot: Development Center!
Human: Industry
Robot: Development Center!
Using srai, we can return a simple response when the user types a specific keyword, say, School, no matter where "school" is present in the sentence.
For example, consider the following conversation.
Human: I love going to school daily.
Robot: School is an important institution in a child's life.
Human: I like my school.
Robot: School is an important institution in a child's life.
Here, the robot is expected to reply a standard message 'School is an important institution in a child's life.' whenever a user has school in the sentence.
Let's put <srai> tag to work here. We'll use wild-cards here.
<category>
<pattern>SCHOOL</pattern>
<template>School is an important institution in a child's life.</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> WHO IS ALBERT EINSTEIN </pattern>
<template>Albert Einstein was a German physicist.</template>
</category>
<category>
<pattern> WHO IS Isaac NEWTON </pattern>
<template>Isaac Newton was a English physicist and mathematician.</template>
</category>
<category>
<pattern>DO YOU KNOW WHO * IS</pattern>
<template>
<srai>WHO IS <star/></srai>
</template>
</category>
<category>
<pattern>BYE</pattern>
<template>Good Bye!</template>
</category>
<category>
<pattern>BYE *</pattern>
<template>
<srai>BYE</srai>
</template>
</category>
<category>
<pattern>FACTORY</pattern>
<template>Development Center!</template>
</category>
<category>
<pattern>INDUSTRY</pattern>
<template>
<srai>FACTORY</srai>
</template>
</category>
<category>
<pattern>SCHOOL</pattern>
<template>School is an important institution in a child's life.</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
<category>
<pattern>_ SCHOOL *</pattern>
<template>
<srai>SCHOOL</srai>
</template>
</category>
</aiml>
0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml
0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml
0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml
0,BYE,*,*,Good Bye!,srai.aiml
0,BYE *,*,*,<srai>BYE</srai>,srai.aiml
0,FACTORY,*,*,Development Center!,srai.aiml
0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml
0,SCHOOL,*,*,School is an important institution in a child's life.,srai.aiml
0,_ SCHOOL,*,*,<srai>SCHOOL</srai>,srai.aiml
0,SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml
0,_ SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: I love going to school daily.
Robot: School is an important institution in a child's life.
Human: I like my school.
Robot: School is an important institution in a child's life.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1922,
"s": 1811,
"text": "<srai> Tag is a multipurpose tag. This tag enables AIML to define the different targets for the same template."
},
{
"code": null,
"e": 1947,
"s": 1922,
"text": "<srai> pattern </srai> \n"
},
{
"code": null,
"e": 2008,
"s": 1947,
"text": "Following are the commonly used terms associated with srai −"
},
{
"code": null,
"e": 2027,
"s": 2008,
"text": "Symbolic Reduction"
},
{
"code": null,
"e": 2046,
"s": 2027,
"text": "Symbolic Reduction"
},
{
"code": null,
"e": 2065,
"s": 2046,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 2084,
"s": 2065,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 2104,
"s": 2084,
"text": "Synonyms resolution"
},
{
"code": null,
"e": 2124,
"s": 2104,
"text": "Synonyms resolution"
},
{
"code": null,
"e": 2143,
"s": 2124,
"text": "Keywords detection"
},
{
"code": null,
"e": 2162,
"s": 2143,
"text": "Keywords detection"
},
{
"code": null,
"e": 2297,
"s": 2162,
"text": "The symbolic reduction technique is used to simplify patterns. It helps to reduce complex grammatical patterns with simple pattern(s)."
},
{
"code": null,
"e": 2347,
"s": 2297,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 2519,
"s": 2347,
"text": "Human: Who was Albert Einstein?\nRobot: Albert Einstein was a German physicist.\nHuman: Who was Isaac Newton?\nRobot: Isaac Newton was a English physicist and mathematician.\n"
},
{
"code": null,
"e": 2555,
"s": 2519,
"text": "Now What if questions are raised as"
},
{
"code": null,
"e": 2639,
"s": 2555,
"text": "Human: DO YOU KNOW WHO Albert Einstein IS?\nHuman: DO YOU KNOW WHO Isaac Newton IS?\n"
},
{
"code": null,
"e": 2715,
"s": 2639,
"text": "Here, <srai> tag works. It can take the pattern of the user as a template."
},
{
"code": null,
"e": 2997,
"s": 2715,
"text": "<category>\n <pattern>WHO IS ALBERT EINSTEIN?</pattern>\n <template>Albert Einstein was a German physicist.</template>\n</category>\n\n<category>\n <pattern> WHO IS Isaac NEWTON? </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n</category>"
},
{
"code": null,
"e": 3135,
"s": 2997,
"text": "<category>\n <pattern>DO YOU KNOW WHO * IS?</pattern>\n \n <template>\n <srai>WHO IS <star/></srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 3255,
"s": 3135,
"text": "Create srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 3811,
"s": 3255,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n</aiml>"
},
{
"code": null,
"e": 4047,
"s": 3811,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml"
},
{
"code": null,
"e": 4120,
"s": 4047,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 4185,
"s": 4120,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 4221,
"s": 4185,
"text": "You will see the following output −"
},
{
"code": null,
"e": 4311,
"s": 4221,
"text": "Human: Do you know who Albert Einstein is\nRobot: Albert Einstein was a German physicist.\n"
},
{
"code": null,
"e": 4438,
"s": 4311,
"text": "Divide and Conquer is used to reuse sub sentences in making a complete reply. It helps to reduce defining multiple categories."
},
{
"code": null,
"e": 4484,
"s": 4438,
"text": "For example, consider following conversation."
},
{
"code": null,
"e": 4545,
"s": 4484,
"text": "Human: Bye\nRobot: GoodBye!\nHuman: Bye Alice!\nRobot: GoodBye!"
},
{
"code": null,
"e": 4649,
"s": 4545,
"text": "Now here robot is expected to reply GoodBye! Whenever a user says Bye in the beginning of the sentence."
},
{
"code": null,
"e": 4684,
"s": 4649,
"text": "Let's put <srai> tag to work here."
},
{
"code": null,
"e": 4767,
"s": 4684,
"text": "<category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n</category>"
},
{
"code": null,
"e": 4878,
"s": 4767,
"text": "<category>\n <pattern>BYE *</pattern>\n \n <template>\n <srai>BYE</srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 4998,
"s": 4878,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 5780,
"s": 4998,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 6085,
"s": 5780,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml"
},
{
"code": null,
"e": 6158,
"s": 6085,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 6223,
"s": 6158,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 6259,
"s": 6223,
"text": "You will see the following output −"
},
{
"code": null,
"e": 6321,
"s": 6259,
"text": "Human: Bye\nRobot: GoodBye!\nHuman: Bye Alice!\nRobot: GoodBye!\n"
},
{
"code": null,
"e": 6420,
"s": 6321,
"text": "Synonyms are words with similar meanings. A bot should reply in the same manner for similar words."
},
{
"code": null,
"e": 6470,
"s": 6420,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 6556,
"s": 6470,
"text": "Human: Factory\nRobot: Development Center!\nHuman: Industry\nRobot: Development Center!\n"
},
{
"code": null,
"e": 6654,
"s": 6556,
"text": "Now here robot is expected to reply Development Center! whenever a user says Factory or Industry."
},
{
"code": null,
"e": 6689,
"s": 6654,
"text": "Let's put <srai> tag to work here."
},
{
"code": null,
"e": 6786,
"s": 6689,
"text": "<category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n</category>"
},
{
"code": null,
"e": 6904,
"s": 6786,
"text": "<category>\n <pattern>INDUSTRY</pattern>\n \n <template>\n <srai>FACTORY</srai>\n </template>\n \n</category>"
},
{
"code": null,
"e": 7024,
"s": 6904,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 8053,
"s": 7024,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n <category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n </category>\n \n <category>\n <pattern>INDUSTRY</pattern>\n <template>\n <srai>FACTORY</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 8448,
"s": 8053,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml\n0,FACTORY,*,*,Development Center!,srai.aiml\n0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml"
},
{
"code": null,
"e": 8521,
"s": 8448,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 8586,
"s": 8521,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 8622,
"s": 8586,
"text": "You will see the following output −"
},
{
"code": null,
"e": 8708,
"s": 8622,
"text": "Human: Factory\nRobot: Development Center!\nHuman: Industry\nRobot: Development Center!\n"
},
{
"code": null,
"e": 8858,
"s": 8708,
"text": "Using srai, we can return a simple response when the user types a specific keyword, say, School, no matter where \"school\" is present in the sentence."
},
{
"code": null,
"e": 8908,
"s": 8858,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 9093,
"s": 8908,
"text": "Human: I love going to school daily.\nRobot: School is an important institution in a child's life.\nHuman: I like my school.\nRobot: School is an important institution in a child's life.\n"
},
{
"code": null,
"e": 9249,
"s": 9093,
"text": "Here, the robot is expected to reply a standard message 'School is an important institution in a child's life.' whenever a user has school in the sentence."
},
{
"code": null,
"e": 9311,
"s": 9249,
"text": "Let's put <srai> tag to work here. We'll use wild-cards here."
},
{
"code": null,
"e": 9441,
"s": 9311,
"text": "<category>\n <pattern>SCHOOL</pattern>\n <template>School is an important institution in a child's life.</template>\n</category>"
},
{
"code": null,
"e": 9882,
"s": 9441,
"text": "<category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>\n\n<category>\n <pattern>_ SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n</category>"
},
{
"code": null,
"e": 10002,
"s": 9882,
"text": "Update srai.aiml inside C > ab > bots > test > aiml and srai.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 11705,
"s": 10002,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> WHO IS ALBERT EINSTEIN </pattern>\n <template>Albert Einstein was a German physicist.</template>\n </category>\n \n <category>\n <pattern> WHO IS Isaac NEWTON </pattern>\n <template>Isaac Newton was a English physicist and mathematician.</template>\n </category>\n \n <category>\n <pattern>DO YOU KNOW WHO * IS</pattern>\n <template>\n <srai>WHO IS <star/></srai>\n </template>\n </category>\n \n <category>\n <pattern>BYE</pattern>\n <template>Good Bye!</template>\n </category>\n \n <category>\n <pattern>BYE *</pattern>\n <template>\n <srai>BYE</srai>\n </template>\n </category>\n \n <category>\n <pattern>FACTORY</pattern>\n <template>Development Center!</template>\n </category>\n \n <category>\n <pattern>INDUSTRY</pattern>\n <template>\n <srai>FACTORY</srai>\n </template>\n </category>\n \n <category>\n <pattern>SCHOOL</pattern>\n <template>School is an important institution in a child's life.</template>\n </category> \n \n <category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>_ SCHOOL</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n <category>\n <pattern>_ SCHOOL *</pattern>\n <template>\n <srai>SCHOOL</srai>\n </template>\n </category>\n \n</aiml>"
},
{
"code": null,
"e": 12314,
"s": 11705,
"text": "0,WHO IS ALBERT EINSTEIN,*,*,Albert Einstein was a German physicist.,srai.aiml\n0,WHO IS Isaac NEWTON,*,*,Isaac Newton was a English physicist and mathematician.,srai.aiml\n0,DO YOU KNOW WHO * IS,*,*,<srai>WHO IS <star/></srai>,srai.aiml\n0,BYE,*,*,Good Bye!,srai.aiml\n0,BYE *,*,*,<srai>BYE</srai>,srai.aiml\n0,FACTORY,*,*,Development Center!,srai.aiml\n0,INDUSTRY,*,*,<srai>FACTORY</srai>,srai.aiml\n0,SCHOOL,*,*,School is an important institution in a child's life.,srai.aiml\n0,_ SCHOOL,*,*,<srai>SCHOOL</srai>,srai.aiml\n0,SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml\n0,_ SCHOOL *,*,*,<srai>SCHOOL</srai>,srai.aiml"
},
{
"code": null,
"e": 12387,
"s": 12314,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 12452,
"s": 12387,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 12488,
"s": 12452,
"text": "You will see the following output −"
},
{
"code": null,
"e": 12673,
"s": 12488,
"text": "Human: I love going to school daily.\nRobot: School is an important institution in a child's life.\nHuman: I like my school.\nRobot: School is an important institution in a child's life.\n"
},
{
"code": null,
"e": 12680,
"s": 12673,
"text": " Print"
},
{
"code": null,
"e": 12691,
"s": 12680,
"text": " Add Notes"
}
] |
A beginner’s guide to Kaggle’s Titanic problem | by Sumit Mukhija | Towards Data Science
|
Since this is my first post, here’s a brief introduction of what I’ve been doing:
I am a software developer turned data enthusiast. I have recently started learning about the nitty-gritties of Data Science. One of the most prominent challenge when I started learning through videos and courses on websites like Udemy, Coursera etc., it made me passive and I did more of listening and less of, well, doing. I had no practice and even though I could understand most of the theory.
At that point I came across Kaggle, a website with a set of Data Science problems and competitions hosted by multiple mega-technological companies like Google. Over the world, Kaggle is known for its problems being interesting, challenging and very, very addictive. One of these problems is the Titanic Dataset.
So summing it up, the Titanic Problem is based on the sinking of the ‘Unsinkable’ ship Titanic in the early 1912. It gives you information about multiple people like their ages, sexes, sibling counts, embarkment points and whether or not they survived the disaster. Based on these features, you have to predict if an arbitrary passenger on Titanic would survive the sinking.
Sounds easy, right?
Nope.
The problem statement is merely the tip of the iceberg.
PandasSeabornSklearnWordCloud
Pandas
Seaborn
Sklearn
WordCloud
The initial phase dealt with the characteristics of the complete dataset. Here, I did not try to shape or gather from the features and merely observed their qualities.
I initially aggregated the data from the training and test data set. The resulting dataset had 1309 rows and 12 columns. Each row represented a unique traveler on RMS Titanic, and each column described different valued attributes for each commuter.
trd = pd.read_csv('train.csv')tsd = pd.read_csv('test.csv')td = pd.concat([trd, tsd], ignore_index=True, sort = False)
The dataset had a couple of columns that were missing values. The ‘Cabin’ attribute had 1014 missing values. The column ‘Embarked’ that depicted a commuter’s boarding point had a total of 2 missing values. The property ‘Age’ had 263 missing values, and the column ‘Fare’ had one.
td.isnull().sum()sns.heatmap(td.isnull(), cbar = False).set_title("Missing values heatmap")
Further, to understand the categorical and non-categorical features, I had a look at the number of unique values each column had. The attributes ‘Sex’ and ‘Survived’ had two possible values, properties ‘Embarked’ & ‘Pclass’ had three possible values.
td.nunique()PassengerId 1309Survived 2Pclass 3Name 1307Sex 2Age 98SibSp 7Parch 8Ticket 929Fare 281Cabin 186Embarked 3dtype: int64
After getting a better perception of the different aspects of the dataset, I started exploring the features and the part they played in the survival or demise of a traveler.
The first feature reported if a traveler lived or died. A comparison revealed that more than 60% of the passengers had died.
This feature renders the passenger division. The tourists could opt from three distinct sections, namely class-1, class-2, class-3. The third class had the highest number of commuters, followed by class-2 and class-1. The number of tourists in the third class was more than the number of passengers in the first and second class combined. The survival chances of a class-1 traveler were higher than a class-2 and class-3 traveler.
Approximately 65% of the tourists were male while the remaining 35% were female. Nonetheless, the percentage of female survivors was higher than the number of male survivors. More than 80% of male commuters died, as compared to around 70% female commuters.
The youngest traveler onboard was aged around two months and the oldest traveler was 80 years. The average age of tourists onboard was just under 30 years. Clearly, a larger fraction of children under 10 survived than died. or every other age group, the number of casualties was higher than the number of survivors. More than 140 people within the age group 20 and 30 were dead as compared to just around 80 people of the same age range sustained.
SibSp is the number of siblings or spouse of a person onboard. A maximum of 8 siblings and spouses traveled along with one of the traveler. More than 90% of people traveled alone or with one of their sibling or spouse. The chances of survival dropped drastically if someone traveled with more than 2 siblings or spouse.
Similar to the SibSp, this feature contained the number of parents or children each passenger was touring with. A maximum of 9 parents/children traveled along with one of the traveler.
I added the number of ‘Parch’ and ‘SibSp’ values to store in a new column named ‘Family’
td['Family'] = td.Parch + td.SibSp
Moreover, the chances of survival skyrocketed when a traveler traveled alone. Created another column, Is_Alone and assigned True if the value in ‘Family’ column was 0.
td['Is_Alone'] = td.Family == 0
By splitting the fare amount into four categories, it was obvious that there was a strong association between the charge and the survival. The higher a tourist paid, the higher would be his chances to survive.
I stored the segregated fare to a new column Fare_Category
td['Fare_Category'] = pd.cut(td['Fare'], bins=[0,7.90,14.45,31.28,120], labels=['Low','Mid', 'High_Mid','High'])
Embarked implies where the traveler mounted from. There are three possible values for Embark — Southampton, Cherbourg, and Queenstown. More than 70% of the people boarded from Southampton. Just under 20% boarded from Cherbourg and the rest boarded from Queenstown. People who boarded from Cherbourg had a higher chance of survival than people who boarded from Southampton or Queenstown.
It is worth noticing that we did not use the ‘Ticket’ column.
Data imputation is the practice of replacing missing data with some substituted values. There can be a multitude of substitution processes that can be used. I used some of them for the missing values.
Since ‘Embarked’ only had two missing values and the largest number of commuters embarked from Southampton, the probability of boarding from Southampton is higher. So, we fill the missing values with Southampton. However, instead of manually putting in Southampton, we would find the mode of the Embarked column and substitute missing values with it. The mode is the most frequently occurring element in a series.
td.Embarked.fillna(td.Embarked.mode()[0], inplace = True)
As the column ‘Cabin’ had a lot of missing data. I decided to categorize all the missing data as a different class. I named it NA. I assigned all the missing values with this value.
td.Cabin = td.Cabin.fillna('NA')
Age was the most intricate column to be filled. Age had 263 missing values. I initially categorized the people on the basis of their salutations. A basic Python’s string split was enough to extract the title from each name. There were 18 different titles.
td['Salutation'] = td.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
I then grouped the titles with Sex and PClass.
grp = td.groupby(['Sex', 'Pclass'])
The median of the group was then substituted in the missing rows.
grp.Age.apply(lambda x: x.fillna(x.median()))td.Age.fillna(td.Age.median, inplace = True)
Since the string data does not go well with the machine learning algorithms, I needed to convert the non-numeric data to numeric data. I used LabelEncoder to encode the ‘Sex’ column. The label encoder would substitute ‘male’ values with some number and ‘female’ values with some different number.
td['Sex'] = LabelEncoder().fit_transform(td['Sex'])
For the other categorical data, I used Pandas’ dummies. It adds columns corresponding to all the possible values. So, if there could be three embarkment values — Q, C, S, the get_dummies method would create three different columns and assign values 0 or 1 depending on the embarking point.
pd.get_dummies(td.Embarked, prefix="Emb", drop_first = True)
Further, I dropped the columns that I did not need for the prediction and the columns that I had encoded by creating their dummies.
td.drop(['Pclass', 'Fare','Cabin', 'Fare_Category','Name','Salutation', 'Deck', 'Ticket','Embarked', 'Age_Range', 'SibSp', 'Parch', 'Age'], axis=1, inplace=True)
This was a case of classification problem and I tried predicting with two algorithms —
Random ForestGaussian Naive Bayes
Random Forest
Gaussian Naive Bayes
I was surprised at the results. The Gaussian Naive algorithm performed poorly and the Random Forest on the other hand was consistently predicting with an accuracy of more than 80%.
# Data to be predictedX_to_be_predicted = td[td.Survived.isnull()]X_to_be_predicted = X_to_be_predicted.drop(['Survived'], axis = 1)# X_to_be_predicted[X_to_be_predicted.Age.isnull()]# X_to_be_predicted.dropna(inplace = True) # 417 x 27#Training datatrain_data = tdtrain_data = train_data.dropna()feature_train = train_data['Survived']label_train = train_data.drop(['Survived'], axis = 1)##Gaussianclf = GaussianNB()x_train, x_test, y_train, y_test = train_test_split(label_train, feature_train, test_size=0.2)clf.fit(x_train, np.ravel(y_train))print("NB Accuracy: "+repr(round(clf.score(x_test, y_test) * 100, 2)) + "%")result_rf=cross_val_score(clf,x_train,y_train,cv=10,scoring='accuracy')print('The cross validated score for Random forest is:',round(result_rf.mean()*100,2))y_pred = cross_val_predict(clf,x_train,y_train,cv=10)sns.heatmap(confusion_matrix(y_train,y_pred),annot=True,fmt='3.0f',cmap="summer")plt.title('Confusion_matrix for NB', y=1.05, size=15)
##Random forestclf = RandomForestClassifier(criterion='entropy', n_estimators=700, min_samples_split=10, min_samples_leaf=1, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)x_train, x_test, y_train, y_test = train_test_split(label_train, feature_train, test_size=0.2)clf.fit(x_train, np.ravel(y_train))print("RF Accuracy: "+repr(round(clf.score(x_test, y_test) * 100, 2)) + "%")result_rf=cross_val_score(clf,x_train,y_train,cv=10,scoring='accuracy')print('The cross validated score for Random forest is:',round(result_rf.mean()*100,2))y_pred = cross_val_predict(clf,x_train,y_train,cv=10)sns.heatmap(confusion_matrix(y_train,y_pred),annot=True,fmt='3.0f',cmap="summer")plt.title('Confusion_matrix for RF', y=1.05, size=15)
RF Accuracy: 78.77%The cross validated score for Random forest is: 84.56
Lastly, I created a submission file to store the predicted results.
result = clf.predict(X_to_be_predicted)submission = pd.DataFrame({'PassengerId':X_to_be_predicted.PassengerId,'Survived':result})submission.Survived = submission.Survived.astype(int)print(submission.shape)filename = 'Titanic Predictions.csv'submission.to_csv(filename,index=False)print('Saved file: ' + filename)
The line of code below is particularly important as Kaggle would rate the predictions wrong if the Survived value in not of int data type
submission.Survived = submission.Survived.astype(int)
The complete implementation Jupyter Notebook can be found on my GitHub or Kaggle. The submission got me to the top 8% of the contestants. It wasn’t easy and it took me more than 20 attempts to get there. I would say the key is to be analytical, play around with analysis, be intuitive and try everything, no matter how absurd it sounds.
|
[
{
"code": null,
"e": 254,
"s": 172,
"text": "Since this is my first post, here’s a brief introduction of what I’ve been doing:"
},
{
"code": null,
"e": 651,
"s": 254,
"text": "I am a software developer turned data enthusiast. I have recently started learning about the nitty-gritties of Data Science. One of the most prominent challenge when I started learning through videos and courses on websites like Udemy, Coursera etc., it made me passive and I did more of listening and less of, well, doing. I had no practice and even though I could understand most of the theory."
},
{
"code": null,
"e": 963,
"s": 651,
"text": "At that point I came across Kaggle, a website with a set of Data Science problems and competitions hosted by multiple mega-technological companies like Google. Over the world, Kaggle is known for its problems being interesting, challenging and very, very addictive. One of these problems is the Titanic Dataset."
},
{
"code": null,
"e": 1338,
"s": 963,
"text": "So summing it up, the Titanic Problem is based on the sinking of the ‘Unsinkable’ ship Titanic in the early 1912. It gives you information about multiple people like their ages, sexes, sibling counts, embarkment points and whether or not they survived the disaster. Based on these features, you have to predict if an arbitrary passenger on Titanic would survive the sinking."
},
{
"code": null,
"e": 1358,
"s": 1338,
"text": "Sounds easy, right?"
},
{
"code": null,
"e": 1364,
"s": 1358,
"text": "Nope."
},
{
"code": null,
"e": 1420,
"s": 1364,
"text": "The problem statement is merely the tip of the iceberg."
},
{
"code": null,
"e": 1450,
"s": 1420,
"text": "PandasSeabornSklearnWordCloud"
},
{
"code": null,
"e": 1457,
"s": 1450,
"text": "Pandas"
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Seaborn"
},
{
"code": null,
"e": 1473,
"s": 1465,
"text": "Sklearn"
},
{
"code": null,
"e": 1483,
"s": 1473,
"text": "WordCloud"
},
{
"code": null,
"e": 1651,
"s": 1483,
"text": "The initial phase dealt with the characteristics of the complete dataset. Here, I did not try to shape or gather from the features and merely observed their qualities."
},
{
"code": null,
"e": 1900,
"s": 1651,
"text": "I initially aggregated the data from the training and test data set. The resulting dataset had 1309 rows and 12 columns. Each row represented a unique traveler on RMS Titanic, and each column described different valued attributes for each commuter."
},
{
"code": null,
"e": 2020,
"s": 1900,
"text": "trd = pd.read_csv('train.csv')tsd = pd.read_csv('test.csv')td = pd.concat([trd, tsd], ignore_index=True, sort = False)"
},
{
"code": null,
"e": 2300,
"s": 2020,
"text": "The dataset had a couple of columns that were missing values. The ‘Cabin’ attribute had 1014 missing values. The column ‘Embarked’ that depicted a commuter’s boarding point had a total of 2 missing values. The property ‘Age’ had 263 missing values, and the column ‘Fare’ had one."
},
{
"code": null,
"e": 2392,
"s": 2300,
"text": "td.isnull().sum()sns.heatmap(td.isnull(), cbar = False).set_title(\"Missing values heatmap\")"
},
{
"code": null,
"e": 2643,
"s": 2392,
"text": "Further, to understand the categorical and non-categorical features, I had a look at the number of unique values each column had. The attributes ‘Sex’ and ‘Survived’ had two possible values, properties ‘Embarked’ & ‘Pclass’ had three possible values."
},
{
"code": null,
"e": 2896,
"s": 2643,
"text": "td.nunique()PassengerId 1309Survived 2Pclass 3Name 1307Sex 2Age 98SibSp 7Parch 8Ticket 929Fare 281Cabin 186Embarked 3dtype: int64"
},
{
"code": null,
"e": 3070,
"s": 2896,
"text": "After getting a better perception of the different aspects of the dataset, I started exploring the features and the part they played in the survival or demise of a traveler."
},
{
"code": null,
"e": 3195,
"s": 3070,
"text": "The first feature reported if a traveler lived or died. A comparison revealed that more than 60% of the passengers had died."
},
{
"code": null,
"e": 3626,
"s": 3195,
"text": "This feature renders the passenger division. The tourists could opt from three distinct sections, namely class-1, class-2, class-3. The third class had the highest number of commuters, followed by class-2 and class-1. The number of tourists in the third class was more than the number of passengers in the first and second class combined. The survival chances of a class-1 traveler were higher than a class-2 and class-3 traveler."
},
{
"code": null,
"e": 3883,
"s": 3626,
"text": "Approximately 65% of the tourists were male while the remaining 35% were female. Nonetheless, the percentage of female survivors was higher than the number of male survivors. More than 80% of male commuters died, as compared to around 70% female commuters."
},
{
"code": null,
"e": 4331,
"s": 3883,
"text": "The youngest traveler onboard was aged around two months and the oldest traveler was 80 years. The average age of tourists onboard was just under 30 years. Clearly, a larger fraction of children under 10 survived than died. or every other age group, the number of casualties was higher than the number of survivors. More than 140 people within the age group 20 and 30 were dead as compared to just around 80 people of the same age range sustained."
},
{
"code": null,
"e": 4651,
"s": 4331,
"text": "SibSp is the number of siblings or spouse of a person onboard. A maximum of 8 siblings and spouses traveled along with one of the traveler. More than 90% of people traveled alone or with one of their sibling or spouse. The chances of survival dropped drastically if someone traveled with more than 2 siblings or spouse."
},
{
"code": null,
"e": 4836,
"s": 4651,
"text": "Similar to the SibSp, this feature contained the number of parents or children each passenger was touring with. A maximum of 9 parents/children traveled along with one of the traveler."
},
{
"code": null,
"e": 4925,
"s": 4836,
"text": "I added the number of ‘Parch’ and ‘SibSp’ values to store in a new column named ‘Family’"
},
{
"code": null,
"e": 4960,
"s": 4925,
"text": "td['Family'] = td.Parch + td.SibSp"
},
{
"code": null,
"e": 5128,
"s": 4960,
"text": "Moreover, the chances of survival skyrocketed when a traveler traveled alone. Created another column, Is_Alone and assigned True if the value in ‘Family’ column was 0."
},
{
"code": null,
"e": 5160,
"s": 5128,
"text": "td['Is_Alone'] = td.Family == 0"
},
{
"code": null,
"e": 5370,
"s": 5160,
"text": "By splitting the fare amount into four categories, it was obvious that there was a strong association between the charge and the survival. The higher a tourist paid, the higher would be his chances to survive."
},
{
"code": null,
"e": 5429,
"s": 5370,
"text": "I stored the segregated fare to a new column Fare_Category"
},
{
"code": null,
"e": 5624,
"s": 5429,
"text": "td['Fare_Category'] = pd.cut(td['Fare'], bins=[0,7.90,14.45,31.28,120], labels=['Low','Mid', 'High_Mid','High'])"
},
{
"code": null,
"e": 6011,
"s": 5624,
"text": "Embarked implies where the traveler mounted from. There are three possible values for Embark — Southampton, Cherbourg, and Queenstown. More than 70% of the people boarded from Southampton. Just under 20% boarded from Cherbourg and the rest boarded from Queenstown. People who boarded from Cherbourg had a higher chance of survival than people who boarded from Southampton or Queenstown."
},
{
"code": null,
"e": 6073,
"s": 6011,
"text": "It is worth noticing that we did not use the ‘Ticket’ column."
},
{
"code": null,
"e": 6274,
"s": 6073,
"text": "Data imputation is the practice of replacing missing data with some substituted values. There can be a multitude of substitution processes that can be used. I used some of them for the missing values."
},
{
"code": null,
"e": 6688,
"s": 6274,
"text": "Since ‘Embarked’ only had two missing values and the largest number of commuters embarked from Southampton, the probability of boarding from Southampton is higher. So, we fill the missing values with Southampton. However, instead of manually putting in Southampton, we would find the mode of the Embarked column and substitute missing values with it. The mode is the most frequently occurring element in a series."
},
{
"code": null,
"e": 6746,
"s": 6688,
"text": "td.Embarked.fillna(td.Embarked.mode()[0], inplace = True)"
},
{
"code": null,
"e": 6928,
"s": 6746,
"text": "As the column ‘Cabin’ had a lot of missing data. I decided to categorize all the missing data as a different class. I named it NA. I assigned all the missing values with this value."
},
{
"code": null,
"e": 6961,
"s": 6928,
"text": "td.Cabin = td.Cabin.fillna('NA')"
},
{
"code": null,
"e": 7217,
"s": 6961,
"text": "Age was the most intricate column to be filled. Age had 263 missing values. I initially categorized the people on the basis of their salutations. A basic Python’s string split was enough to extract the title from each name. There were 18 different titles."
},
{
"code": null,
"e": 7305,
"s": 7217,
"text": "td['Salutation'] = td.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())"
},
{
"code": null,
"e": 7352,
"s": 7305,
"text": "I then grouped the titles with Sex and PClass."
},
{
"code": null,
"e": 7388,
"s": 7352,
"text": "grp = td.groupby(['Sex', 'Pclass'])"
},
{
"code": null,
"e": 7454,
"s": 7388,
"text": "The median of the group was then substituted in the missing rows."
},
{
"code": null,
"e": 7544,
"s": 7454,
"text": "grp.Age.apply(lambda x: x.fillna(x.median()))td.Age.fillna(td.Age.median, inplace = True)"
},
{
"code": null,
"e": 7841,
"s": 7544,
"text": "Since the string data does not go well with the machine learning algorithms, I needed to convert the non-numeric data to numeric data. I used LabelEncoder to encode the ‘Sex’ column. The label encoder would substitute ‘male’ values with some number and ‘female’ values with some different number."
},
{
"code": null,
"e": 7893,
"s": 7841,
"text": "td['Sex'] = LabelEncoder().fit_transform(td['Sex'])"
},
{
"code": null,
"e": 8183,
"s": 7893,
"text": "For the other categorical data, I used Pandas’ dummies. It adds columns corresponding to all the possible values. So, if there could be three embarkment values — Q, C, S, the get_dummies method would create three different columns and assign values 0 or 1 depending on the embarking point."
},
{
"code": null,
"e": 8244,
"s": 8183,
"text": "pd.get_dummies(td.Embarked, prefix=\"Emb\", drop_first = True)"
},
{
"code": null,
"e": 8376,
"s": 8244,
"text": "Further, I dropped the columns that I did not need for the prediction and the columns that I had encoded by creating their dummies."
},
{
"code": null,
"e": 8538,
"s": 8376,
"text": "td.drop(['Pclass', 'Fare','Cabin', 'Fare_Category','Name','Salutation', 'Deck', 'Ticket','Embarked', 'Age_Range', 'SibSp', 'Parch', 'Age'], axis=1, inplace=True)"
},
{
"code": null,
"e": 8625,
"s": 8538,
"text": "This was a case of classification problem and I tried predicting with two algorithms —"
},
{
"code": null,
"e": 8659,
"s": 8625,
"text": "Random ForestGaussian Naive Bayes"
},
{
"code": null,
"e": 8673,
"s": 8659,
"text": "Random Forest"
},
{
"code": null,
"e": 8694,
"s": 8673,
"text": "Gaussian Naive Bayes"
},
{
"code": null,
"e": 8875,
"s": 8694,
"text": "I was surprised at the results. The Gaussian Naive algorithm performed poorly and the Random Forest on the other hand was consistently predicting with an accuracy of more than 80%."
},
{
"code": null,
"e": 9843,
"s": 8875,
"text": "# Data to be predictedX_to_be_predicted = td[td.Survived.isnull()]X_to_be_predicted = X_to_be_predicted.drop(['Survived'], axis = 1)# X_to_be_predicted[X_to_be_predicted.Age.isnull()]# X_to_be_predicted.dropna(inplace = True) # 417 x 27#Training datatrain_data = tdtrain_data = train_data.dropna()feature_train = train_data['Survived']label_train = train_data.drop(['Survived'], axis = 1)##Gaussianclf = GaussianNB()x_train, x_test, y_train, y_test = train_test_split(label_train, feature_train, test_size=0.2)clf.fit(x_train, np.ravel(y_train))print(\"NB Accuracy: \"+repr(round(clf.score(x_test, y_test) * 100, 2)) + \"%\")result_rf=cross_val_score(clf,x_train,y_train,cv=10,scoring='accuracy')print('The cross validated score for Random forest is:',round(result_rf.mean()*100,2))y_pred = cross_val_predict(clf,x_train,y_train,cv=10)sns.heatmap(confusion_matrix(y_train,y_pred),annot=True,fmt='3.0f',cmap=\"summer\")plt.title('Confusion_matrix for NB', y=1.05, size=15)"
},
{
"code": null,
"e": 10779,
"s": 9843,
"text": "##Random forestclf = RandomForestClassifier(criterion='entropy', n_estimators=700, min_samples_split=10, min_samples_leaf=1, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)x_train, x_test, y_train, y_test = train_test_split(label_train, feature_train, test_size=0.2)clf.fit(x_train, np.ravel(y_train))print(\"RF Accuracy: \"+repr(round(clf.score(x_test, y_test) * 100, 2)) + \"%\")result_rf=cross_val_score(clf,x_train,y_train,cv=10,scoring='accuracy')print('The cross validated score for Random forest is:',round(result_rf.mean()*100,2))y_pred = cross_val_predict(clf,x_train,y_train,cv=10)sns.heatmap(confusion_matrix(y_train,y_pred),annot=True,fmt='3.0f',cmap=\"summer\")plt.title('Confusion_matrix for RF', y=1.05, size=15)"
},
{
"code": null,
"e": 10852,
"s": 10779,
"text": "RF Accuracy: 78.77%The cross validated score for Random forest is: 84.56"
},
{
"code": null,
"e": 10920,
"s": 10852,
"text": "Lastly, I created a submission file to store the predicted results."
},
{
"code": null,
"e": 11233,
"s": 10920,
"text": "result = clf.predict(X_to_be_predicted)submission = pd.DataFrame({'PassengerId':X_to_be_predicted.PassengerId,'Survived':result})submission.Survived = submission.Survived.astype(int)print(submission.shape)filename = 'Titanic Predictions.csv'submission.to_csv(filename,index=False)print('Saved file: ' + filename)"
},
{
"code": null,
"e": 11371,
"s": 11233,
"text": "The line of code below is particularly important as Kaggle would rate the predictions wrong if the Survived value in not of int data type"
},
{
"code": null,
"e": 11425,
"s": 11371,
"text": "submission.Survived = submission.Survived.astype(int)"
}
] |
How to convert data frame values to a vector by rows in R?
|
Data can be supplied to us in any form but it is possible that it is not the appropriate one that should be used for analysis. Sometimes data is recorded in a data frame but we might need it as a vector. In such type of situation, we have to change the values of our data frame in a vector. This can be done by reading the data frame values by reading them as.vector after transposing the data frame with t.
Consider the below data frame −
> x1<-rep(c(1,2,3,4,5),times=4)
> x2<-1:20
> x3<-rep(c(5,10,15,20),each=5)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 1 1 5
2 2 2 5
3 3 3 5
4 4 4 5
5 5 5 5
6 1 6 10
7 2 7 10
8 3 8 10
9 4 9 10
10 5 10 10
11 1 11 15
12 2 12 15
13 3 13 15
14 4 14 15
15 5 15 15
16 1 16 20
17 2 17 20
18 3 18 20
19 4 19 20
20 5 20 20
> as.vector(t(df))
[1] 1 1 5 2 2 5 3 3 5 4 4 5 5 5 5 1 6 10 2 7 10 3 8 10 4 9 10 5 10 10 1 11 15 2 12 15 3 13 15 4 14 15 5 15 15 1 16 20 2 17 20 3 18 20
[55] 4 19 20 5 20 20
> Vector_df<-as.vector(t(df))
> sum(Vector_df)
[1] 520
> mean(Vector_df)
[1] 8.666667
Let’s have a look at another example −
> y1<-20:1
> y2<-rep(c(2,4,6,8,10),times=4)
> y3<-c(22,25,27,21,18,19,28,24,29,15,27,24,16,18,28,17,18,26,23,22)
> df_y<-data.frame(y1,y2,y3)
> df_y
y1 y2 y3
1 20 2 22
2 19 4 25
3 18 6 27
4 17 8 21
5 16 10 18
6 15 2 19
7 14 4 28
8 13 6 24
9 12 8 29
10 11 10 15
11 10 2 27
12 9 4 24
13 8 6 16
14 7 8 18
15 6 10 28
16 5 2 17
17 4 4 18
18 3 6 26
19 2 8 23
20 1 10 22
> Vector_new<-as.vector(t(df_y))
> Vector_new
[1] 20 2 22 19 4 25 18 6 27 17 8 21 16 10 18 15 2 19 14 4 28 13 6 24 12 8 29 11 10 15 10 2 27 9 4 24 8 6 16 7 8 18 6 10 28 5 2 17 4 4 18 3 6 26
[55] 2 8 23 1 10 22
|
[
{
"code": null,
"e": 1470,
"s": 1062,
"text": "Data can be supplied to us in any form but it is possible that it is not the appropriate one that should be used for analysis. Sometimes data is recorded in a data frame but we might need it as a vector. In such type of situation, we have to change the values of our data frame in a vector. This can be done by reading the data frame values by reading them as.vector after transposing the data frame with t."
},
{
"code": null,
"e": 1502,
"s": 1470,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 2101,
"s": 1502,
"text": "> x1<-rep(c(1,2,3,4,5),times=4)\n> x2<-1:20\n> x3<-rep(c(5,10,15,20),each=5)\n> df<-data.frame(x1,x2,x3)\n> df\n x1 x2 x3\n 1 1 1 5\n 2 2 2 5\n 3 3 3 5\n 4 4 4 5\n 5 5 5 5\n 6 1 6 10\n 7 2 7 10\n 8 3 8 10\n 9 4 9 10\n10 5 10 10\n11 1 11 15\n12 2 12 15\n13 3 13 15\n14 4 14 15\n15 5 15 15\n16 1 16 20\n17 2 17 20\n18 3 18 20\n19 4 19 20\n20 5 20 20\n> as.vector(t(df))\n[1] 1 1 5 2 2 5 3 3 5 4 4 5 5 5 5 1 6 10 2 7 10 3 8 10 4 9 10 5 10 10 1 11 15 2 12 15 3 13 15 4 14 15 5 15 15 1 16 20 2 17 20 3 18 20\n[55] 4 19 20 5 20 20\n> Vector_df<-as.vector(t(df))\n> sum(Vector_df)\n[1] 520\n> mean(Vector_df)\n[1] 8.666667"
},
{
"code": null,
"e": 2140,
"s": 2101,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 2751,
"s": 2140,
"text": "> y1<-20:1\n> y2<-rep(c(2,4,6,8,10),times=4)\n> y3<-c(22,25,27,21,18,19,28,24,29,15,27,24,16,18,28,17,18,26,23,22)\n> df_y<-data.frame(y1,y2,y3)\n> df_y\n y1 y2 y3\n 1 20 2 22\n 2 19 4 25\n 3 18 6 27\n 4 17 8 21\n 5 16 10 18\n 6 15 2 19\n 7 14 4 28\n 8 13 6 24\n 9 12 8 29\n10 11 10 15\n11 10 2 27\n12 9 4 24\n13 8 6 16\n14 7 8 18\n15 6 10 28\n16 5 2 17\n17 4 4 18\n18 3 6 26\n19 2 8 23\n20 1 10 22\n> Vector_new<-as.vector(t(df_y))\n> Vector_new\n[1] 20 2 22 19 4 25 18 6 27 17 8 21 16 10 18 15 2 19 14 4 28 13 6 24 12 8 29 11 10 15 10 2 27 9 4 24 8 6 16 7 8 18 6 10 28 5 2 17 4 4 18 3 6 26\n[55] 2 8 23 1 10 22"
}
] |
Go - Variables
|
A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −
byte
Typically a single octet(one byte). This is an byte type.
int
The most natural size of integer for the machine.
float32
A single-precision floating point value.
Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types.
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −
var variable_list optional_data_type;
Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
var i, j, k int;
var c, ch byte;
var f, salary float32;
d = 42;
The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −
variable_name = value;
For example,
d = 3, f = 5; // declaration of d and f. Here d and f are int
For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type.
A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program.
Try the following example, where the variable has been declared with a type and initialized inside the main function −
package main
import "fmt"
func main() {
var x float64
x = 20.0
fmt.Println(x)
fmt.Printf("x is of type %T\n", x)
}
When the above code is compiled and executed, it produces the following result −
20
x is of type float64
A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.
Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator.
package main
import "fmt"
func main() {
var x float64 = 20.0
y := 42
fmt.Println(x)
fmt.Println(y)
fmt.Printf("x is of type %T\n", x)
fmt.Printf("y is of type %T\n", y)
}
When the above code is compiled and executed, it produces the following result −
20
42
x is of type float64
y is of type int
Variables of different types can be declared in one go using type inference.
package main
import "fmt"
func main() {
var a, b, c = 3, 4, "foo"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf("a is of type %T\n", a)
fmt.Printf("b is of type %T\n", b)
fmt.Printf("c is of type %T\n", c)
}
When the above code is compiled and executed, it produces the following result −
3
4
foo
a is of type int
b is of type int
c is of type string
There are two kinds of expressions in Go −
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.
The following statement is valid −
x = 20.0
The following statement is not valid. It would generate compile-time error −
10 = 20
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2254,
"s": 1937,
"text": "A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 2578,
"s": 2254,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −"
},
{
"code": null,
"e": 2583,
"s": 2578,
"text": "byte"
},
{
"code": null,
"e": 2641,
"s": 2583,
"text": "Typically a single octet(one byte). This is an byte type."
},
{
"code": null,
"e": 2645,
"s": 2641,
"text": "int"
},
{
"code": null,
"e": 2695,
"s": 2645,
"text": "The most natural size of integer for the machine."
},
{
"code": null,
"e": 2703,
"s": 2695,
"text": "float32"
},
{
"code": null,
"e": 2744,
"s": 2703,
"text": "A single-precision floating point value."
},
{
"code": null,
"e": 2986,
"s": 2744,
"text": "Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types."
},
{
"code": null,
"e": 3197,
"s": 2986,
"text": "A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −"
},
{
"code": null,
"e": 3236,
"s": 3197,
"text": "var variable_list optional_data_type;\n"
},
{
"code": null,
"e": 3492,
"s": 3236,
"text": "Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −"
},
{
"code": null,
"e": 3561,
"s": 3492,
"text": "var i, j, k int;\nvar c, ch byte;\nvar f, salary float32;\nd = 42;\n"
},
{
"code": null,
"e": 3717,
"s": 3561,
"text": "The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int."
},
{
"code": null,
"e": 3979,
"s": 3717,
"text": "Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −"
},
{
"code": null,
"e": 4003,
"s": 3979,
"text": "variable_name = value;\n"
},
{
"code": null,
"e": 4016,
"s": 4003,
"text": "For example,"
},
{
"code": null,
"e": 4083,
"s": 4016,
"text": "d = 3, f = 5; // declaration of d and f. Here d and f are int \n"
},
{
"code": null,
"e": 4302,
"s": 4083,
"text": "For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type."
},
{
"code": null,
"e": 4712,
"s": 4302,
"text": "A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program."
},
{
"code": null,
"e": 4831,
"s": 4712,
"text": "Try the following example, where the variable has been declared with a type and initialized inside the main function −"
},
{
"code": null,
"e": 4960,
"s": 4831,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var x float64\n x = 20.0\n fmt.Println(x)\n fmt.Printf(\"x is of type %T\\n\", x)\n}"
},
{
"code": null,
"e": 5041,
"s": 4960,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5066,
"s": 5041,
"text": "20\nx is of type float64\n"
},
{
"code": null,
"e": 5288,
"s": 5066,
"text": "A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement."
},
{
"code": null,
"e": 5498,
"s": 5288,
"text": "Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator."
},
{
"code": null,
"e": 5692,
"s": 5498,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var x float64 = 20.0\n\n y := 42 \n fmt.Println(x)\n fmt.Println(y)\n fmt.Printf(\"x is of type %T\\n\", x)\n fmt.Printf(\"y is of type %T\\n\", y)\t\n}"
},
{
"code": null,
"e": 5773,
"s": 5692,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5818,
"s": 5773,
"text": "20\n42\nx is of type float64\ny is of type int\n"
},
{
"code": null,
"e": 5896,
"s": 5818,
"text": "Variables of different types can be declared in one go using type inference. "
},
{
"code": null,
"e": 6141,
"s": 5896,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a, b, c = 3, 4, \"foo\" \n\t\n fmt.Println(a)\n fmt.Println(b)\n fmt.Println(c)\n fmt.Printf(\"a is of type %T\\n\", a)\n fmt.Printf(\"b is of type %T\\n\", b)\n fmt.Printf(\"c is of type %T\\n\", c)\n}"
},
{
"code": null,
"e": 6222,
"s": 6141,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6285,
"s": 6222,
"text": "3\n4\nfoo\na is of type int\nb is of type int\nc is of type string\n"
},
{
"code": null,
"e": 6328,
"s": 6285,
"text": "There are two kinds of expressions in Go −"
},
{
"code": null,
"e": 6495,
"s": 6328,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 6662,
"s": 6495,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 6907,
"s": 6662,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 7152,
"s": 6907,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 7330,
"s": 7152,
"text": "Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side."
},
{
"code": null,
"e": 7365,
"s": 7330,
"text": "The following statement is valid −"
},
{
"code": null,
"e": 7375,
"s": 7365,
"text": "x = 20.0\n"
},
{
"code": null,
"e": 7452,
"s": 7375,
"text": "The following statement is not valid. It would generate compile-time error −"
},
{
"code": null,
"e": 7461,
"s": 7452,
"text": "10 = 20\n"
},
{
"code": null,
"e": 7496,
"s": 7461,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7509,
"s": 7496,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 7544,
"s": 7509,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7558,
"s": 7544,
"text": " Asif Hussain"
},
{
"code": null,
"e": 7591,
"s": 7558,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7610,
"s": 7591,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 7643,
"s": 7610,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7662,
"s": 7643,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7694,
"s": 7662,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7711,
"s": 7694,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 7744,
"s": 7711,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7763,
"s": 7744,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7770,
"s": 7763,
"text": " Print"
},
{
"code": null,
"e": 7781,
"s": 7770,
"text": " Add Notes"
}
] |
ML | XGBoost (eXtreme Gradient Boosting)
|
09 Jun, 2022
XGBoost is an implementation of Gradient Boosted decision trees. This library was written in C++. It is a type of Software library that was designed basically to improve speed and model performance. It has recently been dominating in applied machine learning. XGBoost models majorly dominate in many Kaggle Competitions. In this algorithm, decision trees are created in sequential form. Weights play an important role in XGBoost. Weights are assigned to all the independent variables which are then fed into the decision tree which predicts results. The weight of variables predicted wrong by the tree is increased and the variables are then fed to the second decision tree. These individual classifiers/predictors then ensemble to give a strong and more precise model. It can work on regression, classification, ranking, and user-defined prediction problems.
XGBoost Features The library is laser-focused on computational speed and model performance, as such, there are few frills. Model Features Three main forms of gradient boosting are supported:
Gradient Boosting
Stochastic Gradient Boosting
Regularized Gradient Boosting
System Features
For use of a range of computing environments this library provides-
Parallelization of tree construction
Distributed Computing for training very large models
Cache Optimization of data structures and algorithm
XGBoost enhancements/optimizations
XGBoost features various optimizations built-in to make the training faster when working with large datasets, in addition to its unique method of generating and pruning trees. Here is a handful of the most significant:
Approximate Greedy Algorithm: instead of assessing every candidate split, this algorithm employs weighted quantiles to find the best node split.
Cash-Aware Access: XGBoost stores data in the CPU’s cache memory.
Sparsity: Aware Split Finding calculates Gain by putting observations with missing values onto the left leaf when there is some missing data. It then repeats the process by placing them in the appropriate leaf and selecting the scenario with the highest Gain.
Steps to Install Windows XGBoost uses Git submodules to manage dependencies. So when you clone the repo, remember to specify –recursive option:
git clone --recursive https://github.com/dmlc/xgboost
For Windows users who use Github tools, you can open the git-shell and type the following command:
git submodule init
git submodule update
OSX(Mac) First, obtain gcc-8 with Homebrew (https://brew.sh/) to enable multi-threading (i.e. using multiple CPU threads for training). The default Apple Clang compiler does not support OpenMP, so using the default compiler would have disabled multi-threading.
brew install gcc@8
Then install XGBoost with pip:
pip3 install xgboost
You might need to run the command with –user flag if you run into permission errors.
Example: Code: Python code for XGB Classifier
Python3
# Importing the librariesfrom sklearn.metrics import confusion_matriximport xgboost as xgbfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoder, OneHotEncoderimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Importing the datasetdataset = pd.read_csv('Churn_Modelling.csv')X = dataset.iloc[:, 3:13].valuesy = dataset.iloc[:, 13].values # Encoding categorical datalabelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])onehotencoder = OneHotEncoder(categorical_features=[1]) X = onehotencoder.fit_transform(X).toarray()X = X[:, 1:] # Splitting the dataset into the Training set and Test setX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # Fitting XGBoost to the training datamy_model = xgb.XGBClassifier()my_model.fit(X_train, y_train) # Predicting the Test set resultsy_pred = my_model.predict(X_test) # Making the Confusion Matrixcm = confusion_matrix(y_test, y_pred)
Output:
Accuracy will be about 0.8645
anushkaajitsharma
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 888,
"s": 28,
"text": "XGBoost is an implementation of Gradient Boosted decision trees. This library was written in C++. It is a type of Software library that was designed basically to improve speed and model performance. It has recently been dominating in applied machine learning. XGBoost models majorly dominate in many Kaggle Competitions. In this algorithm, decision trees are created in sequential form. Weights play an important role in XGBoost. Weights are assigned to all the independent variables which are then fed into the decision tree which predicts results. The weight of variables predicted wrong by the tree is increased and the variables are then fed to the second decision tree. These individual classifiers/predictors then ensemble to give a strong and more precise model. It can work on regression, classification, ranking, and user-defined prediction problems."
},
{
"code": null,
"e": 1079,
"s": 888,
"text": "XGBoost Features The library is laser-focused on computational speed and model performance, as such, there are few frills. Model Features Three main forms of gradient boosting are supported:"
},
{
"code": null,
"e": 1097,
"s": 1079,
"text": "Gradient Boosting"
},
{
"code": null,
"e": 1126,
"s": 1097,
"text": "Stochastic Gradient Boosting"
},
{
"code": null,
"e": 1156,
"s": 1126,
"text": "Regularized Gradient Boosting"
},
{
"code": null,
"e": 1172,
"s": 1156,
"text": "System Features"
},
{
"code": null,
"e": 1240,
"s": 1172,
"text": "For use of a range of computing environments this library provides-"
},
{
"code": null,
"e": 1277,
"s": 1240,
"text": "Parallelization of tree construction"
},
{
"code": null,
"e": 1330,
"s": 1277,
"text": "Distributed Computing for training very large models"
},
{
"code": null,
"e": 1382,
"s": 1330,
"text": "Cache Optimization of data structures and algorithm"
},
{
"code": null,
"e": 1417,
"s": 1382,
"text": "XGBoost enhancements/optimizations"
},
{
"code": null,
"e": 1636,
"s": 1417,
"text": "XGBoost features various optimizations built-in to make the training faster when working with large datasets, in addition to its unique method of generating and pruning trees. Here is a handful of the most significant:"
},
{
"code": null,
"e": 1781,
"s": 1636,
"text": "Approximate Greedy Algorithm: instead of assessing every candidate split, this algorithm employs weighted quantiles to find the best node split."
},
{
"code": null,
"e": 1847,
"s": 1781,
"text": "Cash-Aware Access: XGBoost stores data in the CPU’s cache memory."
},
{
"code": null,
"e": 2107,
"s": 1847,
"text": "Sparsity: Aware Split Finding calculates Gain by putting observations with missing values onto the left leaf when there is some missing data. It then repeats the process by placing them in the appropriate leaf and selecting the scenario with the highest Gain."
},
{
"code": null,
"e": 2251,
"s": 2107,
"text": "Steps to Install Windows XGBoost uses Git submodules to manage dependencies. So when you clone the repo, remember to specify –recursive option:"
},
{
"code": null,
"e": 2305,
"s": 2251,
"text": "git clone --recursive https://github.com/dmlc/xgboost"
},
{
"code": null,
"e": 2404,
"s": 2305,
"text": "For Windows users who use Github tools, you can open the git-shell and type the following command:"
},
{
"code": null,
"e": 2444,
"s": 2404,
"text": "git submodule init\ngit submodule update"
},
{
"code": null,
"e": 2705,
"s": 2444,
"text": "OSX(Mac) First, obtain gcc-8 with Homebrew (https://brew.sh/) to enable multi-threading (i.e. using multiple CPU threads for training). The default Apple Clang compiler does not support OpenMP, so using the default compiler would have disabled multi-threading."
},
{
"code": null,
"e": 2724,
"s": 2705,
"text": "brew install gcc@8"
},
{
"code": null,
"e": 2755,
"s": 2724,
"text": "Then install XGBoost with pip:"
},
{
"code": null,
"e": 2776,
"s": 2755,
"text": "pip3 install xgboost"
},
{
"code": null,
"e": 2862,
"s": 2776,
"text": "You might need to run the command with –user flag if you run into permission errors. "
},
{
"code": null,
"e": 2909,
"s": 2862,
"text": "Example: Code: Python code for XGB Classifier "
},
{
"code": null,
"e": 2917,
"s": 2909,
"text": "Python3"
},
{
"code": "# Importing the librariesfrom sklearn.metrics import confusion_matriximport xgboost as xgbfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoder, OneHotEncoderimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Importing the datasetdataset = pd.read_csv('Churn_Modelling.csv')X = dataset.iloc[:, 3:13].valuesy = dataset.iloc[:, 13].values # Encoding categorical datalabelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])onehotencoder = OneHotEncoder(categorical_features=[1]) X = onehotencoder.fit_transform(X).toarray()X = X[:, 1:] # Splitting the dataset into the Training set and Test setX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # Fitting XGBoost to the training datamy_model = xgb.XGBClassifier()my_model.fit(X_train, y_train) # Predicting the Test set resultsy_pred = my_model.predict(X_test) # Making the Confusion Matrixcm = confusion_matrix(y_test, y_pred)",
"e": 4009,
"s": 2917,
"text": null
},
{
"code": null,
"e": 4017,
"s": 4009,
"text": "Output:"
},
{
"code": null,
"e": 4047,
"s": 4017,
"text": "Accuracy will be about 0.8645"
},
{
"code": null,
"e": 4065,
"s": 4047,
"text": "anushkaajitsharma"
},
{
"code": null,
"e": 4082,
"s": 4065,
"text": "Machine Learning"
},
{
"code": null,
"e": 4099,
"s": 4082,
"text": "Machine Learning"
}
] |
JavaScript delete Operator
|
09 Sep, 2020
Below is the example of the delete Operator.
Example:<script> let emp = { firstName: "Raj", lastName: "Kumar", salary: 40000 } console.log(delete emp.salary); console.log(emp);</script>
<script> let emp = { firstName: "Raj", lastName: "Kumar", salary: 40000 } console.log(delete emp.salary); console.log(emp);</script>
Output:true
{"firstName":"Raj","lastName":"Kumar"}
true
{"firstName":"Raj","lastName":"Kumar"}
This article is going to discuss the delete operator available in JavaScript. Delete is comparatively a lesser-known operator in JavaScript. This operator is more specifically used to delete JavaScript object properties.
The JavaScript pop(), shift() or splice() methods are available to delete an element from an array. But because of the key-value pair in an object, the deleting is more complicated. Note that, the delete operator only works on objects and not on variables or functions.
Syntax:
delete object
// or
delete object.property
// or
delete object['property']
This operator returns true if it removes a property. While deleting an object property that doesn’t exist will return a true but it will not affect the object. Though while trying to delete a variable or a function will return a false.
Example: Assuming an object called person has three key-value pairs (i.e. firstName, lastName and phone). Now, using the delete operator to delete the phone property will return true.
<script> let person = { firstName: "John", lastName: "Doe", phone: 12345 } console.log(delete person.phone); console.log(person);</script>
Output:
As the above picture shows, delete person.phone returns true and logging the person object shows that the phone property doesn’t exist anymore.
Let’s try applying the delete operator for deleting a variable and a function.
<script> let num = 5; let sum = (a, b) => { return a + b; } console.log(delete num); //false console.log(delete sum); //false</script>
Output:
false
false
Because the delete operator doesn’t work for variables or function, it returns false and the actual variables and functions remain untouched.
Another thing to keep in mind is that this operator doesn’t delete property value rather the property itself.
Example:
<script> let person = { firstName: "John", lastName: "Doe", phone: 12345 } let phone = person.phone; console.log(delete person.phone); //true console.log(phone); //12345</script>
As objects are reference type, so both the person.phone and phone variable will refer to the same memory address.
Output:
true
12345
The output shows that the delete operator has deleted the property but the value still exists on the memory.
Exception: Global variables can be removed using the delete operator. Because the global variables are properties of the window object and as delete works on objects, it’ll delete the variable.
Example:
<script> toDelete = 5; // true console.log(delete toDelete); // toDelete is not defined console.log(toDelete);</script>
Without using the var, let or const keyword sets the variable as a global variable and it’ll work as an object property.
Output:
true
Uncaught ReferenceError: toDelete is not defined
The delete toDelete returns true and trying to access the variable after deleting it throws a reference error as the variable is not defined anymore.
Deleting Array Values Using delete: JavaScript arrays are after-all objects. So, the delete operator can be used. But it’ll cause a problem because after deleting the element from the array, this operator will show the position as empty and it’ll not update the array length.
Example:
<script> let arr = [1, 2, 3] console.log(delete arr[0]); //true console.log(arr); //[empty, 2, 3]</script>
Output:
So, using pop(), shift() or splice() methods are clearly a better approach to delete array elements.
Conclusion: There are other ways used by developers, such as setting the value of an object property to null or undefined. But the property will still exist on the object and some operators like for in loop will still show the presence of the null or undefined property.
Using the delete property in loops slows down the program significantly. So, this method should only be used when it is absolutely necessary to delete an object property.
javascript-operators
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 73,
"s": 28,
"text": "Below is the example of the delete Operator."
},
{
"code": null,
"e": 256,
"s": 73,
"text": "Example:<script> let emp = { firstName: \"Raj\", lastName: \"Kumar\", salary: 40000 } console.log(delete emp.salary); console.log(emp);</script> "
},
{
"code": "<script> let emp = { firstName: \"Raj\", lastName: \"Kumar\", salary: 40000 } console.log(delete emp.salary); console.log(emp);</script> ",
"e": 431,
"s": 256,
"text": null
},
{
"code": null,
"e": 482,
"s": 431,
"text": "Output:true\n{\"firstName\":\"Raj\",\"lastName\":\"Kumar\"}"
},
{
"code": null,
"e": 526,
"s": 482,
"text": "true\n{\"firstName\":\"Raj\",\"lastName\":\"Kumar\"}"
},
{
"code": null,
"e": 747,
"s": 526,
"text": "This article is going to discuss the delete operator available in JavaScript. Delete is comparatively a lesser-known operator in JavaScript. This operator is more specifically used to delete JavaScript object properties."
},
{
"code": null,
"e": 1017,
"s": 747,
"text": "The JavaScript pop(), shift() or splice() methods are available to delete an element from an array. But because of the key-value pair in an object, the deleting is more complicated. Note that, the delete operator only works on objects and not on variables or functions."
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "Syntax:"
},
{
"code": null,
"e": 1100,
"s": 1025,
"text": "delete object\n// or\ndelete object.property\n// or\ndelete object['property']"
},
{
"code": null,
"e": 1336,
"s": 1100,
"text": "This operator returns true if it removes a property. While deleting an object property that doesn’t exist will return a true but it will not affect the object. Though while trying to delete a variable or a function will return a false."
},
{
"code": null,
"e": 1520,
"s": 1336,
"text": "Example: Assuming an object called person has three key-value pairs (i.e. firstName, lastName and phone). Now, using the delete operator to delete the phone property will return true."
},
{
"code": "<script> let person = { firstName: \"John\", lastName: \"Doe\", phone: 12345 } console.log(delete person.phone); console.log(person);</script>",
"e": 1694,
"s": 1520,
"text": null
},
{
"code": null,
"e": 1702,
"s": 1694,
"text": "Output:"
},
{
"code": null,
"e": 1846,
"s": 1702,
"text": "As the above picture shows, delete person.phone returns true and logging the person object shows that the phone property doesn’t exist anymore."
},
{
"code": null,
"e": 1925,
"s": 1846,
"text": "Let’s try applying the delete operator for deleting a variable and a function."
},
{
"code": "<script> let num = 5; let sum = (a, b) => { return a + b; } console.log(delete num); //false console.log(delete sum); //false</script>",
"e": 2084,
"s": 1925,
"text": null
},
{
"code": null,
"e": 2092,
"s": 2084,
"text": "Output:"
},
{
"code": null,
"e": 2104,
"s": 2092,
"text": "false\nfalse"
},
{
"code": null,
"e": 2246,
"s": 2104,
"text": "Because the delete operator doesn’t work for variables or function, it returns false and the actual variables and functions remain untouched."
},
{
"code": null,
"e": 2356,
"s": 2246,
"text": "Another thing to keep in mind is that this operator doesn’t delete property value rather the property itself."
},
{
"code": null,
"e": 2365,
"s": 2356,
"text": "Example:"
},
{
"code": "<script> let person = { firstName: \"John\", lastName: \"Doe\", phone: 12345 } let phone = person.phone; console.log(delete person.phone); //true console.log(phone); //12345</script>",
"e": 2584,
"s": 2365,
"text": null
},
{
"code": null,
"e": 2698,
"s": 2584,
"text": "As objects are reference type, so both the person.phone and phone variable will refer to the same memory address."
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Output:"
},
{
"code": null,
"e": 2717,
"s": 2706,
"text": "true\n12345"
},
{
"code": null,
"e": 2826,
"s": 2717,
"text": "The output shows that the delete operator has deleted the property but the value still exists on the memory."
},
{
"code": null,
"e": 3020,
"s": 2826,
"text": "Exception: Global variables can be removed using the delete operator. Because the global variables are properties of the window object and as delete works on objects, it’ll delete the variable."
},
{
"code": null,
"e": 3029,
"s": 3020,
"text": "Example:"
},
{
"code": "<script> toDelete = 5; // true console.log(delete toDelete); // toDelete is not defined console.log(toDelete);</script>",
"e": 3168,
"s": 3029,
"text": null
},
{
"code": null,
"e": 3289,
"s": 3168,
"text": "Without using the var, let or const keyword sets the variable as a global variable and it’ll work as an object property."
},
{
"code": null,
"e": 3297,
"s": 3289,
"text": "Output:"
},
{
"code": null,
"e": 3351,
"s": 3297,
"text": "true\nUncaught ReferenceError: toDelete is not defined"
},
{
"code": null,
"e": 3501,
"s": 3351,
"text": "The delete toDelete returns true and trying to access the variable after deleting it throws a reference error as the variable is not defined anymore."
},
{
"code": null,
"e": 3777,
"s": 3501,
"text": "Deleting Array Values Using delete: JavaScript arrays are after-all objects. So, the delete operator can be used. But it’ll cause a problem because after deleting the element from the array, this operator will show the position as empty and it’ll not update the array length."
},
{
"code": null,
"e": 3786,
"s": 3777,
"text": "Example:"
},
{
"code": "<script> let arr = [1, 2, 3] console.log(delete arr[0]); //true console.log(arr); //[empty, 2, 3]</script>",
"e": 3904,
"s": 3786,
"text": null
},
{
"code": null,
"e": 3912,
"s": 3904,
"text": "Output:"
},
{
"code": null,
"e": 4013,
"s": 3912,
"text": "So, using pop(), shift() or splice() methods are clearly a better approach to delete array elements."
},
{
"code": null,
"e": 4284,
"s": 4013,
"text": "Conclusion: There are other ways used by developers, such as setting the value of an object property to null or undefined. But the property will still exist on the object and some operators like for in loop will still show the presence of the null or undefined property."
},
{
"code": null,
"e": 4455,
"s": 4284,
"text": "Using the delete property in loops slows down the program significantly. So, this method should only be used when it is absolutely necessary to delete an object property."
},
{
"code": null,
"e": 4476,
"s": 4455,
"text": "javascript-operators"
},
{
"code": null,
"e": 4487,
"s": 4476,
"text": "JavaScript"
},
{
"code": null,
"e": 4504,
"s": 4487,
"text": "Web Technologies"
}
] |
SQL Query to Get Distinct Records Without Using Distinct Keyword
|
02 Jun, 2021
Here we are going to see how to retrieve unique (distinct) records from a Microsoft SQL Server’s database table without using the DISTINCT clause.
We will be creating an Employee table in a database called “geeks”.
CREATE DATABASE geeks;
USE geeks;
We have the following dup_table table in our geeks database:
CREATE TABLE dup_table(
dup_id int,
dup_name varchar(20));
To view the table schema use the below command:
EXEC SP_COLUMNS dup_table;
Use the below query to add records to the table:
INSERT INTO dup_table
VALUES
(1, 'yogesh'),
(2, 'ashish'),
(3, 'ajit'),
(4, 'vishal'),
(3, 'ajit'),
(2, 'ashish'),
(1, 'yogesh');
Now we will retrieve all the data from dup_table Table:
SELECT * FROM dup_table;
Now let’s retrieve distinct rows without using the DISTINCT clause.
The GROUP BY clause can be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
GROUP BY dup_id, dup_name;
The set UNION operator can also be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
UNION
SELECT dup_id, dup_name FROM dup_table;
The INTERSECT operator can be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
INTERSECT
SELECT dup_id, dup_name FROM dup_table;
CTE stands for Common Table Expressions. It can also be used to query for distinct rows in a table with the row_number() function as shown below:
WITH cte (dup_id, dup_name, dup_count)
AS
(SELECT dup_id, dup_name,
row_number() over (partition BY dup_id,
dup_name ORDER BY dup_id) AS dup_count
FROM dup_table)
SELECT * FROM cte WHERE dup_count = 1;
akshaysingh98088
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "Here we are going to see how to retrieve unique (distinct) records from a Microsoft SQL Server’s database table without using the DISTINCT clause."
},
{
"code": null,
"e": 243,
"s": 175,
"text": "We will be creating an Employee table in a database called “geeks”."
},
{
"code": null,
"e": 266,
"s": 243,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 277,
"s": 266,
"text": "USE geeks;"
},
{
"code": null,
"e": 338,
"s": 277,
"text": "We have the following dup_table table in our geeks database:"
},
{
"code": null,
"e": 401,
"s": 338,
"text": "CREATE TABLE dup_table(\n dup_id int,\n dup_name varchar(20));"
},
{
"code": null,
"e": 449,
"s": 401,
"text": "To view the table schema use the below command:"
},
{
"code": null,
"e": 476,
"s": 449,
"text": "EXEC SP_COLUMNS dup_table;"
},
{
"code": null,
"e": 525,
"s": 476,
"text": "Use the below query to add records to the table:"
},
{
"code": null,
"e": 655,
"s": 525,
"text": "INSERT INTO dup_table\nVALUES\n(1, 'yogesh'),\n(2, 'ashish'),\n(3, 'ajit'),\n(4, 'vishal'),\n(3, 'ajit'),\n(2, 'ashish'),\n(1, 'yogesh');"
},
{
"code": null,
"e": 711,
"s": 655,
"text": "Now we will retrieve all the data from dup_table Table:"
},
{
"code": null,
"e": 736,
"s": 711,
"text": "SELECT * FROM dup_table;"
},
{
"code": null,
"e": 804,
"s": 736,
"text": "Now let’s retrieve distinct rows without using the DISTINCT clause."
},
{
"code": null,
"e": 875,
"s": 804,
"text": "The GROUP BY clause can be used to query for distinct rows in a table:"
},
{
"code": null,
"e": 941,
"s": 875,
"text": "SELECT dup_id, dup_name FROM dup_table\nGROUP BY dup_id, dup_name;"
},
{
"code": null,
"e": 1022,
"s": 943,
"text": "The set UNION operator can also be used to query for distinct rows in a table:"
},
{
"code": null,
"e": 1107,
"s": 1022,
"text": "SELECT dup_id, dup_name FROM dup_table\nUNION\nSELECT dup_id, dup_name FROM dup_table;"
},
{
"code": null,
"e": 1183,
"s": 1109,
"text": "The INTERSECT operator can be used to query for distinct rows in a table:"
},
{
"code": null,
"e": 1272,
"s": 1183,
"text": "SELECT dup_id, dup_name FROM dup_table\nINTERSECT\nSELECT dup_id, dup_name FROM dup_table;"
},
{
"code": null,
"e": 1418,
"s": 1272,
"text": "CTE stands for Common Table Expressions. It can also be used to query for distinct rows in a table with the row_number() function as shown below:"
},
{
"code": null,
"e": 1623,
"s": 1418,
"text": "WITH cte (dup_id, dup_name, dup_count)\nAS\n(SELECT dup_id, dup_name,\n row_number() over (partition BY dup_id,\n dup_name ORDER BY dup_id) AS dup_count\n FROM dup_table)\nSELECT * FROM cte WHERE dup_count = 1;"
},
{
"code": null,
"e": 1640,
"s": 1623,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1647,
"s": 1640,
"text": "Picked"
},
{
"code": null,
"e": 1657,
"s": 1647,
"text": "SQL-Query"
},
{
"code": null,
"e": 1661,
"s": 1657,
"text": "SQL"
},
{
"code": null,
"e": 1665,
"s": 1661,
"text": "SQL"
},
{
"code": null,
"e": 1763,
"s": 1665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1829,
"s": 1763,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1862,
"s": 1829,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1886,
"s": 1862,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1918,
"s": 1886,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1935,
"s": 1918,
"text": "SQL using Python"
},
{
"code": null,
"e": 2013,
"s": 1935,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2049,
"s": 2013,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2079,
"s": 2049,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2110,
"s": 2079,
"text": "SQL Query to Compare Two Dates"
}
] |
iptables-save command in Linux with examples
|
22 May, 2019
The information transfer from a remote computer to your local computer and the vice-versa are viewed as the transfer of data packets by the firewall. The firewall has the control of data packets that are both incoming and outgoing. iptables is a utility to create a rule-based firewall that is pre-installed in most of the Linux computers. iptables command talks to the kernel and helps to control the data packets that use IPv4 protocol as the packet-switching protocol. Since firewall works in kernel level, to use the iptables command, root privilege is required. By default the firewall runs without any rules. The below example shows how to list the rules.
iptables -L -n -v
This example shows how to block all INPUT chain connections from the IP address 10.10.10.10.
iptables -A INPUT -s 10.10.10.10 -j DROP
Whenever the computer is rebooted or restarted, the iptables service and the existing rules are flushed out or reset. Hence, the above rule will be discarded by the computer if the computer gets restarted. To prevent such customized rules from getting scrapped, below command is used. It saves the rules automatically whereas it can also be manually stored in a user-specified file and can be reused later.
iptables-save
Now, even if the computer is restarted, the rules that you saved will be loaded automatically. The screenshot after rebooting the computer.
If the rules are not needed once the computer is restarted or if the purpose is to flush all the rules once the system is rebooted, iptables-save is of no use.
As discussed earlier, the user can use iptables-save command which will save the current iptables rules in a user specified file, that can be used later when the user wants. The following example saves the rules in /etc/iptablesRule.v4 .
iptables-save > /etc/iptablesRule.v4
Even after restarting the computer the following example helps to reload the rules from the saved file.
iptables-restore < /etc/iptablesRule.v4
The following holds the meaning for options.
iptables-save [-c] [-t table]
The -c argument tells iptables-save helps to keep track of the byte and packet counter values when the rule is issued. This helps in resuming the packet transfer from where the rule was previously established. Hence, it is useful in maintaining continuity. The default value is, of course, to not keep the counters intact when issuing this command.
The -t argument tells the iptables-save command which tables to save that contains specific rules and chains. By default, all the tables are saved.
linux-command
Linux-networking-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 690,
"s": 28,
"text": "The information transfer from a remote computer to your local computer and the vice-versa are viewed as the transfer of data packets by the firewall. The firewall has the control of data packets that are both incoming and outgoing. iptables is a utility to create a rule-based firewall that is pre-installed in most of the Linux computers. iptables command talks to the kernel and helps to control the data packets that use IPv4 protocol as the packet-switching protocol. Since firewall works in kernel level, to use the iptables command, root privilege is required. By default the firewall runs without any rules. The below example shows how to list the rules."
},
{
"code": null,
"e": 708,
"s": 690,
"text": "iptables -L -n -v"
},
{
"code": null,
"e": 801,
"s": 708,
"text": "This example shows how to block all INPUT chain connections from the IP address 10.10.10.10."
},
{
"code": null,
"e": 842,
"s": 801,
"text": "iptables -A INPUT -s 10.10.10.10 -j DROP"
},
{
"code": null,
"e": 1249,
"s": 842,
"text": "Whenever the computer is rebooted or restarted, the iptables service and the existing rules are flushed out or reset. Hence, the above rule will be discarded by the computer if the computer gets restarted. To prevent such customized rules from getting scrapped, below command is used. It saves the rules automatically whereas it can also be manually stored in a user-specified file and can be reused later."
},
{
"code": null,
"e": 1263,
"s": 1249,
"text": "iptables-save"
},
{
"code": null,
"e": 1403,
"s": 1263,
"text": "Now, even if the computer is restarted, the rules that you saved will be loaded automatically. The screenshot after rebooting the computer."
},
{
"code": null,
"e": 1563,
"s": 1403,
"text": "If the rules are not needed once the computer is restarted or if the purpose is to flush all the rules once the system is rebooted, iptables-save is of no use."
},
{
"code": null,
"e": 1801,
"s": 1563,
"text": "As discussed earlier, the user can use iptables-save command which will save the current iptables rules in a user specified file, that can be used later when the user wants. The following example saves the rules in /etc/iptablesRule.v4 ."
},
{
"code": null,
"e": 1838,
"s": 1801,
"text": "iptables-save > /etc/iptablesRule.v4"
},
{
"code": null,
"e": 1942,
"s": 1838,
"text": "Even after restarting the computer the following example helps to reload the rules from the saved file."
},
{
"code": null,
"e": 1982,
"s": 1942,
"text": "iptables-restore < /etc/iptablesRule.v4"
},
{
"code": null,
"e": 2027,
"s": 1982,
"text": "The following holds the meaning for options."
},
{
"code": null,
"e": 2057,
"s": 2027,
"text": "iptables-save [-c] [-t table]"
},
{
"code": null,
"e": 2406,
"s": 2057,
"text": "The -c argument tells iptables-save helps to keep track of the byte and packet counter values when the rule is issued. This helps in resuming the packet transfer from where the rule was previously established. Hence, it is useful in maintaining continuity. The default value is, of course, to not keep the counters intact when issuing this command."
},
{
"code": null,
"e": 2554,
"s": 2406,
"text": "The -t argument tells the iptables-save command which tables to save that contains specific rules and chains. By default, all the tables are saved."
},
{
"code": null,
"e": 2568,
"s": 2554,
"text": "linux-command"
},
{
"code": null,
"e": 2594,
"s": 2568,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 2601,
"s": 2594,
"text": "Picked"
},
{
"code": null,
"e": 2612,
"s": 2601,
"text": "Linux-Unix"
}
] |
C# | Removing the specified element from the List
|
01 Feb, 2019
List.Remove(T) Method is used to remove the first occurrence of a specific object from the List.
Properties of List:
It is different from the arrays. A list can be resized dynamically but arrays cannot.
List class can accept null as a valid value for reference types and it also allows duplicate elements.
If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public bool Remove (T item);
Parameter:
item: Specified object which is to be remove from the List.
Return Type: This method returns True if item is successfully removed. Otherwise it returns False.
Note: This method returns False if item was not found in the List.
Below programs illustrate how to remove the specified element from the List:
Example 1:
// C# program to remove the specified// element from the List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Displaying elements of firstlist // by using foreach loop Console.WriteLine("Before Removing"); foreach(int element in firstlist) { Console.WriteLine(element); } // Removing 2 from the firstlist & Displaying // the remaining firstlist elements Console.WriteLine("After Removing"); firstlist.Remove(2); foreach(int element in firstlist) { Console.WriteLine(element); } }}
Output:
Before Removing
1
2
3
4
After Removing
1
3
4
Example 2:
// C# program to remove the specified// element from the List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Adding some duplicate // elements in firstlist firstlist.Add(2); firstlist.Add(4); // Displaying elements of firstlist // by using foreach loop Console.WriteLine("Before Removing"); foreach(int element in firstlist) { Console.WriteLine(element); } // Removing first occurrence of 2 // from the firstlist & Displaying // the remaining firstlist elements Console.WriteLine("After Removing"); firstlist.Remove(2); foreach(int element in firstlist) { Console.WriteLine(element); } }}
Output:
Before Removing
1
2
3
4
2
4
After Removing
1
3
4
2
4
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "List.Remove(T) Method is used to remove the first occurrence of a specific object from the List."
},
{
"code": null,
"e": 145,
"s": 125,
"text": "Properties of List:"
},
{
"code": null,
"e": 231,
"s": 145,
"text": "It is different from the arrays. A list can be resized dynamically but arrays cannot."
},
{
"code": null,
"e": 334,
"s": 231,
"text": "List class can accept null as a valid value for reference types and it also allows duplicate elements."
},
{
"code": null,
"e": 558,
"s": 334,
"text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element."
},
{
"code": null,
"e": 566,
"s": 558,
"text": "Syntax:"
},
{
"code": null,
"e": 595,
"s": 566,
"text": "public bool Remove (T item);"
},
{
"code": null,
"e": 606,
"s": 595,
"text": "Parameter:"
},
{
"code": null,
"e": 666,
"s": 606,
"text": "item: Specified object which is to be remove from the List."
},
{
"code": null,
"e": 765,
"s": 666,
"text": "Return Type: This method returns True if item is successfully removed. Otherwise it returns False."
},
{
"code": null,
"e": 832,
"s": 765,
"text": "Note: This method returns False if item was not found in the List."
},
{
"code": null,
"e": 909,
"s": 832,
"text": "Below programs illustrate how to remove the specified element from the List:"
},
{
"code": null,
"e": 920,
"s": 909,
"text": "Example 1:"
},
{
"code": "// C# program to remove the specified// element from the List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Displaying elements of firstlist // by using foreach loop Console.WriteLine(\"Before Removing\"); foreach(int element in firstlist) { Console.WriteLine(element); } // Removing 2 from the firstlist & Displaying // the remaining firstlist elements Console.WriteLine(\"After Removing\"); firstlist.Remove(2); foreach(int element in firstlist) { Console.WriteLine(element); } }}",
"e": 1834,
"s": 920,
"text": null
},
{
"code": null,
"e": 1842,
"s": 1834,
"text": "Output:"
},
{
"code": null,
"e": 1888,
"s": 1842,
"text": "Before Removing\n1\n2\n3\n4\nAfter Removing\n1\n3\n4\n"
},
{
"code": null,
"e": 1899,
"s": 1888,
"text": "Example 2:"
},
{
"code": "// C# program to remove the specified// element from the List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Adding some duplicate // elements in firstlist firstlist.Add(2); firstlist.Add(4); // Displaying elements of firstlist // by using foreach loop Console.WriteLine(\"Before Removing\"); foreach(int element in firstlist) { Console.WriteLine(element); } // Removing first occurrence of 2 // from the firstlist & Displaying // the remaining firstlist elements Console.WriteLine(\"After Removing\"); firstlist.Remove(2); foreach(int element in firstlist) { Console.WriteLine(element); } }}",
"e": 2959,
"s": 1899,
"text": null
},
{
"code": null,
"e": 2967,
"s": 2959,
"text": "Output:"
},
{
"code": null,
"e": 3021,
"s": 2967,
"text": "Before Removing\n1\n2\n3\n4\n2\n4\nAfter Removing\n1\n3\n4\n2\n4\n"
},
{
"code": null,
"e": 3032,
"s": 3021,
"text": "Reference:"
},
{
"code": null,
"e": 3141,
"s": 3032,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.7.2"
},
{
"code": null,
"e": 3170,
"s": 3141,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 3190,
"s": 3170,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 3215,
"s": 3190,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 3229,
"s": 3215,
"text": "CSharp-method"
},
{
"code": null,
"e": 3232,
"s": 3229,
"text": "C#"
}
] |
PHP mysqli_fetch_row() Function
|
A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries.
The mysqli_fetch_row() function accepts a result object as a parameter, retrieves the contents of its current row as an array of strings.
mysqli_fetch_row($result);
result(Mandatory)
This is an identifier representing a result object.
The PHP mysqli_fetch_row() function returns an array (string) which contains the values in the row to which the data seek is currently pointed.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_fetch_row() function (in procedural style) −
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");
mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created.....\n");
mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')");
mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')");
print("Record Inserted.....\n");
//Retrieving the contents of the table
$res = mysqli_query($con, "SELECT * FROM myplayers");
while ($row = mysqli_fetch_row($res)) {
print("ID: ".$row[0]."\n");
print("First_Name: ".$row[1]."\n");
print("Last_Name: ".$row[2]."\n");
print("Place_Of_Birth: ".$row[3]."\n");
print("Country: ".$row[4]."\n");
}
//Closing the statement
mysqli_free_result($res);
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Table Created.....
Record Inserted.....
ID: 1
First_Name: Sikhar
Last_Name: Dhawan
Place_Of_Birth: Delhi
Country: India
ID: 2
First_Name: Jonathan
Last_Name: Trott
Place_Of_Birth: CapeTown
Country: SouthAfrica
ID: 3
First_Name: Kumara
Last_Name: Sangakkara
Place_Of_Birth: Matale
Country: Srilanka
In object oriented style the syntax of this function is $result->fetch_row(); Following is the example of this function in object oriented style $minus;
<?php
//Creating a connection
$con = new mysqli("localhost", "root", "password", "mydb");
$con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)");
$con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)");
$con -> query("insert into Test values('Mohan', 28),('Raghav', 35),('Devika', 30)");
print("Table Created.....\n");
$stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?, ?, ?)");
$stmt -> bind_param("ssss", $name1, $name2, $name3, $name4);
$name1 = 'Raju';
$name2 = 'Rahman';
$name3 = 'Raghav';
$name4 = 'Devika';
//Executing the statement
$stmt->execute();
//Retrieving the result
$res = $stmt->get_result();
//Fetching the contents of all the row
while ($row = $res->fetch_row()) {
print("Name: ".$row[0]."\n");
print("Age: ".$row[1]."\n");
print("\n");
}
//Closing the statement
$stmt->close();
//Closing the connection
$con->close();
?>
This will produce following result −
|
[
{
"code": null,
"e": 3026,
"s": 2891,
"text": "A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries."
},
{
"code": null,
"e": 3164,
"s": 3026,
"text": "The mysqli_fetch_row() function accepts a result object as a parameter, retrieves the contents of its current row as an array of strings."
},
{
"code": null,
"e": 3192,
"s": 3164,
"text": "mysqli_fetch_row($result);\n"
},
{
"code": null,
"e": 3210,
"s": 3192,
"text": "result(Mandatory)"
},
{
"code": null,
"e": 3262,
"s": 3210,
"text": "This is an identifier representing a result object."
},
{
"code": null,
"e": 3406,
"s": 3262,
"text": "The PHP mysqli_fetch_row() function returns an array (string) which contains the values in the row to which the data seek is currently pointed."
},
{
"code": null,
"e": 3501,
"s": 3406,
"text": "This function was first introduced in PHP Version 5 and works works in all the later versions."
},
{
"code": null,
"e": 3601,
"s": 3501,
"text": "Following example demonstrates the usage of the mysqli_fetch_row() function (in procedural style) −"
},
{
"code": null,
"e": 4671,
"s": 3601,
"text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n mysqli_query($con, \"INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n print(\"Record Inserted.....\\n\");\n\n //Retrieving the contents of the table\n $res = mysqli_query($con, \"SELECT * FROM myplayers\");\n\n while ($row = mysqli_fetch_row($res)) {\n print(\"ID: \".$row[0].\"\\n\");\n print(\"First_Name: \".$row[1].\"\\n\");\n print(\"Last_Name: \".$row[2].\"\\n\");\n print(\"Place_Of_Birth: \".$row[3].\"\\n\");\n print(\"Country: \".$row[4].\"\\n\");\n }\n\n //Closing the statement\n mysqli_free_result($res);\n\n //Closing the connection\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 4708,
"s": 4671,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5007,
"s": 4708,
"text": "Table Created.....\nRecord Inserted.....\nID: 1\nFirst_Name: Sikhar\nLast_Name: Dhawan\nPlace_Of_Birth: Delhi\nCountry: India\nID: 2\nFirst_Name: Jonathan\nLast_Name: Trott\nPlace_Of_Birth: CapeTown\nCountry: SouthAfrica\nID: 3\nFirst_Name: Kumara\nLast_Name: Sangakkara\nPlace_Of_Birth: Matale\nCountry: Srilanka\n"
},
{
"code": null,
"e": 5160,
"s": 5007,
"text": "In object oriented style the syntax of this function is $result->fetch_row(); Following is the example of this function in object oriented style $minus;"
},
{
"code": null,
"e": 6148,
"s": 5160,
"text": "<?php\n //Creating a connection\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n $con -> query(\"CREATE TABLE Test(Name VARCHAR(255), AGE INT)\");\n $con -> query(\"insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)\");\n $con -> query(\"insert into Test values('Mohan', 28),('Raghav', 35),('Devika', 30)\");\n\n print(\"Table Created.....\\n\");\n\n $stmt = $con -> prepare( \"SELECT * FROM Test WHERE Name in(?, ?, ?, ?)\");\n $stmt -> bind_param(\"ssss\", $name1, $name2, $name3, $name4);\n $name1 = 'Raju';\n $name2 = 'Rahman';\n $name3 = 'Raghav';\n $name4 = 'Devika';\n\n //Executing the statement\n $stmt->execute();\n\n //Retrieving the result\n $res = $stmt->get_result();\n\n\n //Fetching the contents of all the row\n while ($row = $res->fetch_row()) {\n print(\"Name: \".$row[0].\"\\n\");\n print(\"Age: \".$row[1].\"\\n\");\n print(\"\\n\");\n }\n\n //Closing the statement\n $stmt->close();\n\n //Closing the connection\n $con->close();\n?>"
}
] |
Python | Pandas dataframe.product()
|
22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.product() function return the value of the product for the requested axis. It multiplies all the element together on the requested axis. By default the index axis is selected.
Syntax: DataFrame.product(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.
Returns : prod : Series or DataFrame (if level specified)
Example #1: Use product() function to find product of all the elements over the column axis in the dataframe.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Print the dataframedf
Let’s use the dataframe.product() function to find the product of each element in the dataframe over the column axis.
# find the product over the column axisdf.product(axis = 1)
Output : Example #2: Use product() function to find the product of any axis in the dataframe. The dataframe contains NaN values.
# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, None, 4, 3, 4], "C":[2, 2, 7, None, 4], "D":[None, 3, 6, 12, 7]}) # using prod() function to raise each element# in df1 to the power of corresponding element in df2df.product(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 435,
"s": 242,
"text": "Pandas dataframe.product() function return the value of the product for the requested axis. It multiplies all the element together on the requested axis. By default the index axis is selected."
},
{
"code": null,
"e": 539,
"s": 435,
"text": "Syntax: DataFrame.product(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)"
},
{
"code": null,
"e": 1048,
"s": 539,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA."
},
{
"code": null,
"e": 1106,
"s": 1048,
"text": "Returns : prod : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1216,
"s": 1106,
"text": "Example #1: Use product() function to find product of all the elements over the column axis in the dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Print the dataframedf",
"e": 1473,
"s": 1216,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1473,
"text": "Let’s use the dataframe.product() function to find the product of each element in the dataframe over the column axis."
},
{
"code": "# find the product over the column axisdf.product(axis = 1)",
"e": 1651,
"s": 1591,
"text": null
},
{
"code": null,
"e": 1780,
"s": 1651,
"text": "Output : Example #2: Use product() function to find the product of any axis in the dataframe. The dataframe contains NaN values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, None, 4, 3, 4], \"C\":[2, 2, 7, None, 4], \"D\":[None, 3, 6, 12, 7]}) # using prod() function to raise each element# in df1 to the power of corresponding element in df2df.product(axis = 1, skipna = True)",
"e": 2160,
"s": 1780,
"text": null
},
{
"code": null,
"e": 2169,
"s": 2160,
"text": "Output :"
},
{
"code": null,
"e": 2193,
"s": 2169,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2225,
"s": 2193,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2239,
"s": 2225,
"text": "Python-pandas"
},
{
"code": null,
"e": 2246,
"s": 2239,
"text": "Python"
}
] |
Scikit Learn - Clustering Methods
|
Here, we will study about the clustering methods in Sklearn which will help in identification of any similarity in the data samples.
Clustering methods, one of the most useful unsupervised ML methods, used to find similarity & relationship patterns among data samples. After that, they cluster those samples into groups having similarity based on features. Clustering determines the intrinsic grouping among the present unlabeled data, that’s why it is important.
The Scikit-learn library have sklearn.cluster to perform clustering of unlabeled data. Under this module scikit-leran have the following clustering methods −
This algorithm computes the centroids and iterates until it finds optimal centroid. It requires the number of clusters to be specified that’s why it assumes that they are already known. The main logic of this algorithm is to cluster the data separating samples in n number of groups of equal variances by minimizing the criteria known as the inertia. The number of clusters identified by algorithm is represented by ‘K.
Scikit-learn have sklearn.cluster.KMeans module to perform K-Means clustering. While computing cluster centers and value of inertia, the parameter named sample_weight allows sklearn.cluster.KMeans module to assign more weight to some samples.
This algorithm is based on the concept of ‘message passing’ between different pairs of samples until convergence. It does not require the number of clusters to be specified before running the algorithm. The algorithm has a time complexity of the order O(N2T), which is the biggest disadvantage of it.
Scikit-learn have sklearn.cluster.AffinityPropagation module to perform Affinity Propagation clustering.
This algorithm mainly discovers blobs in a smooth density of samples. It assigns the datapoints to the clusters iteratively by shifting points towards the highest density of datapoints. Instead of relying on a parameter named bandwidth dictating the size of the region to search through, it automatically sets the number of clusters.
Scikit-learn have sklearn.cluster.MeanShift module to perform Mean Shift clustering.
Before clustering, this algorithm basically uses the eigenvalues i.e. spectrum of the similarity matrix of the data to perform dimensionality reduction in fewer dimensions. The use of this algorithm is not advisable when there are large number of clusters.
Scikit-learn have sklearn.cluster.SpectralClustering module to perform Spectral clustering.
This algorithm builds nested clusters by merging or splitting the clusters successively. This cluster hierarchy is represented as dendrogram i.e. tree. It falls into following two categories −
Agglomerative hierarchical algorithms − In this kind of hierarchical algorithm, every data point is treated like a single cluster. It then successively agglomerates the pairs of clusters. This uses the bottom-up approach.
Divisive hierarchical algorithms − In this hierarchical algorithm, all data points are treated as one big cluster. In this the process of clustering involves dividing, by using top-down approach, the one big cluster into various small clusters.
Scikit-learn have sklearn.cluster.AgglomerativeClustering module to perform Agglomerative Hierarchical clustering.
It stands for “Density-based spatial clustering of applications with noise”. This algorithm is based on the intuitive notion of “clusters” & “noise” that clusters are dense regions of the lower density in the data space, separated by lower density regions of data points.
Scikit-learn have sklearn.cluster.DBSCAN module to perform DBSCAN clustering. There are two important parameters namely min_samples and eps used by this algorithm to define dense.
Higher value of parameter min_samples or lower value of the parameter eps will give an indication about the higher density of data points which is necessary to form a cluster.
It stands for “Ordering points to identify the clustering structure”. This algorithm also finds density-based clusters in spatial data. It’s basic working logic is like DBSCAN.
It addresses a major weakness of DBSCAN algorithm-the problem of detecting meaningful clusters in data of varying density-by ordering the points of the database in such a way that spatially closest points become neighbors in the ordering.
Scikit-learn have sklearn.cluster.OPTICS module to perform OPTICS clustering.
It stands for Balanced iterative reducing and clustering using hierarchies. It is used to perform hierarchical clustering over large data sets. It builds a tree named CFT i.e. Characteristics Feature Tree, for the given data.
The advantage of CFT is that the data nodes called CF (Characteristics Feature) nodes holds the necessary information for clustering which further prevents the need to hold the entire input data in memory.
Scikit-learn have sklearn.cluster.Birch module to perform BIRCH clustering.
Following table will give a comparison (based on parameters, scalability and metric) of the clustering algorithms in scikit-learn.
In this example, we will apply K-means clustering on digits dataset. This algorithm will identify similar digits without using the original label information. Implementation is done on Jupyter notebook.
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
1797, 64)
This output shows that digit dataset is having 1797 samples with 64 features.
Now, perform the K-Means clustering as follows −
kmeans = KMeans(n_clusters = 10, random_state = 0)
clusters = kmeans.fit_predict(digits.data)
kmeans.cluster_centers_.shape
(10, 64)
This output shows that K-means clustering created 10 clusters with 64 features.
fig, ax = plt.subplots(2, 5, figsize = (8, 3))
centers = kmeans.cluster_centers_.reshape(10, 8, 8)
for axi, center in zip(ax.flat, centers):
axi.set(xticks = [], yticks = [])
axi.imshow(center, interpolation = 'nearest', cmap = plt.cm.binary)
The below output has images showing clusters centers learned by K-Means Clustering.
Next, the Python script below will match the learned cluster labels (by K-Means) with the true labels found in them −
from scipy.stats import mode
labels = np.zeros_like(clusters)
for i in range(10):
mask = (clusters == i)
labels[mask] = mode(digits.target[mask])[0]
We can also check the accuracy with the help of the below mentioned command.
from sklearn.metrics import accuracy_score
accuracy_score(digits.target, labels)
0.7935447968836951
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
kmeans = KMeans(n_clusters = 10, random_state = 0)
clusters = kmeans.fit_predict(digits.data)
kmeans.cluster_centers_.shape
fig, ax = plt.subplots(2, 5, figsize = (8, 3))
centers = kmeans.cluster_centers_.reshape(10, 8, 8)
for axi, center in zip(ax.flat, centers):
axi.set(xticks=[], yticks = [])
axi.imshow(center, interpolation = 'nearest', cmap = plt.cm.binary)
from scipy.stats import mode
labels = np.zeros_like(clusters)
for i in range(10):
mask = (clusters == i)
labels[mask] = mode(digits.target[mask])[0]
from sklearn.metrics import accuracy_score
|
[
{
"code": null,
"e": 2488,
"s": 2355,
"text": "Here, we will study about the clustering methods in Sklearn which will help in identification of any similarity in the data samples."
},
{
"code": null,
"e": 2819,
"s": 2488,
"text": "Clustering methods, one of the most useful unsupervised ML methods, used to find similarity & relationship patterns among data samples. After that, they cluster those samples into groups having similarity based on features. Clustering determines the intrinsic grouping among the present unlabeled data, that’s why it is important."
},
{
"code": null,
"e": 2977,
"s": 2819,
"text": "The Scikit-learn library have sklearn.cluster to perform clustering of unlabeled data. Under this module scikit-leran have the following clustering methods −"
},
{
"code": null,
"e": 3397,
"s": 2977,
"text": "This algorithm computes the centroids and iterates until it finds optimal centroid. It requires the number of clusters to be specified that’s why it assumes that they are already known. The main logic of this algorithm is to cluster the data separating samples in n number of groups of equal variances by minimizing the criteria known as the inertia. The number of clusters identified by algorithm is represented by ‘K."
},
{
"code": null,
"e": 3640,
"s": 3397,
"text": "Scikit-learn have sklearn.cluster.KMeans module to perform K-Means clustering. While computing cluster centers and value of inertia, the parameter named sample_weight allows sklearn.cluster.KMeans module to assign more weight to some samples."
},
{
"code": null,
"e": 3941,
"s": 3640,
"text": "This algorithm is based on the concept of ‘message passing’ between different pairs of samples until convergence. It does not require the number of clusters to be specified before running the algorithm. The algorithm has a time complexity of the order O(N2T), which is the biggest disadvantage of it."
},
{
"code": null,
"e": 4046,
"s": 3941,
"text": "Scikit-learn have sklearn.cluster.AffinityPropagation module to perform Affinity Propagation clustering."
},
{
"code": null,
"e": 4380,
"s": 4046,
"text": "This algorithm mainly discovers blobs in a smooth density of samples. It assigns the datapoints to the clusters iteratively by shifting points towards the highest density of datapoints. Instead of relying on a parameter named bandwidth dictating the size of the region to search through, it automatically sets the number of clusters."
},
{
"code": null,
"e": 4465,
"s": 4380,
"text": "Scikit-learn have sklearn.cluster.MeanShift module to perform Mean Shift clustering."
},
{
"code": null,
"e": 4722,
"s": 4465,
"text": "Before clustering, this algorithm basically uses the eigenvalues i.e. spectrum of the similarity matrix of the data to perform dimensionality reduction in fewer dimensions. The use of this algorithm is not advisable when there are large number of clusters."
},
{
"code": null,
"e": 4814,
"s": 4722,
"text": "Scikit-learn have sklearn.cluster.SpectralClustering module to perform Spectral clustering."
},
{
"code": null,
"e": 5007,
"s": 4814,
"text": "This algorithm builds nested clusters by merging or splitting the clusters successively. This cluster hierarchy is represented as dendrogram i.e. tree. It falls into following two categories −"
},
{
"code": null,
"e": 5229,
"s": 5007,
"text": "Agglomerative hierarchical algorithms − In this kind of hierarchical algorithm, every data point is treated like a single cluster. It then successively agglomerates the pairs of clusters. This uses the bottom-up approach."
},
{
"code": null,
"e": 5474,
"s": 5229,
"text": "Divisive hierarchical algorithms − In this hierarchical algorithm, all data points are treated as one big cluster. In this the process of clustering involves dividing, by using top-down approach, the one big cluster into various small clusters."
},
{
"code": null,
"e": 5589,
"s": 5474,
"text": "Scikit-learn have sklearn.cluster.AgglomerativeClustering module to perform Agglomerative Hierarchical clustering."
},
{
"code": null,
"e": 5861,
"s": 5589,
"text": "It stands for “Density-based spatial clustering of applications with noise”. This algorithm is based on the intuitive notion of “clusters” & “noise” that clusters are dense regions of the lower density in the data space, separated by lower density regions of data points."
},
{
"code": null,
"e": 6041,
"s": 5861,
"text": "Scikit-learn have sklearn.cluster.DBSCAN module to perform DBSCAN clustering. There are two important parameters namely min_samples and eps used by this algorithm to define dense."
},
{
"code": null,
"e": 6217,
"s": 6041,
"text": "Higher value of parameter min_samples or lower value of the parameter eps will give an indication about the higher density of data points which is necessary to form a cluster."
},
{
"code": null,
"e": 6394,
"s": 6217,
"text": "It stands for “Ordering points to identify the clustering structure”. This algorithm also finds density-based clusters in spatial data. It’s basic working logic is like DBSCAN."
},
{
"code": null,
"e": 6633,
"s": 6394,
"text": "It addresses a major weakness of DBSCAN algorithm-the problem of detecting meaningful clusters in data of varying density-by ordering the points of the database in such a way that spatially closest points become neighbors in the ordering."
},
{
"code": null,
"e": 6711,
"s": 6633,
"text": "Scikit-learn have sklearn.cluster.OPTICS module to perform OPTICS clustering."
},
{
"code": null,
"e": 6937,
"s": 6711,
"text": "It stands for Balanced iterative reducing and clustering using hierarchies. It is used to perform hierarchical clustering over large data sets. It builds a tree named CFT i.e. Characteristics Feature Tree, for the given data."
},
{
"code": null,
"e": 7143,
"s": 6937,
"text": "The advantage of CFT is that the data nodes called CF (Characteristics Feature) nodes holds the necessary information for clustering which further prevents the need to hold the entire input data in memory."
},
{
"code": null,
"e": 7219,
"s": 7143,
"text": "Scikit-learn have sklearn.cluster.Birch module to perform BIRCH clustering."
},
{
"code": null,
"e": 7350,
"s": 7219,
"text": "Following table will give a comparison (based on parameters, scalability and metric) of the clustering algorithms in scikit-learn."
},
{
"code": null,
"e": 7553,
"s": 7350,
"text": "In this example, we will apply K-means clustering on digits dataset. This algorithm will identify similar digits without using the original label information. Implementation is done on Jupyter notebook."
},
{
"code": null,
"e": 7773,
"s": 7553,
"text": "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import load_digits\ndigits = load_digits()\ndigits.data.shape"
},
{
"code": null,
"e": 7784,
"s": 7773,
"text": "1797, 64)\n"
},
{
"code": null,
"e": 7862,
"s": 7784,
"text": "This output shows that digit dataset is having 1797 samples with 64 features."
},
{
"code": null,
"e": 7911,
"s": 7862,
"text": "Now, perform the K-Means clustering as follows −"
},
{
"code": null,
"e": 8035,
"s": 7911,
"text": "kmeans = KMeans(n_clusters = 10, random_state = 0)\nclusters = kmeans.fit_predict(digits.data)\nkmeans.cluster_centers_.shape"
},
{
"code": null,
"e": 8045,
"s": 8035,
"text": "(10, 64)\n"
},
{
"code": null,
"e": 8125,
"s": 8045,
"text": "This output shows that K-means clustering created 10 clusters with 64 features."
},
{
"code": null,
"e": 8368,
"s": 8125,
"text": "fig, ax = plt.subplots(2, 5, figsize = (8, 3))\ncenters = kmeans.cluster_centers_.reshape(10, 8, 8)\nfor axi, center in zip(ax.flat, centers):\naxi.set(xticks = [], yticks = [])\naxi.imshow(center, interpolation = 'nearest', cmap = plt.cm.binary)"
},
{
"code": null,
"e": 8452,
"s": 8368,
"text": "The below output has images showing clusters centers learned by K-Means Clustering."
},
{
"code": null,
"e": 8570,
"s": 8452,
"text": "Next, the Python script below will match the learned cluster labels (by K-Means) with the true labels found in them −"
},
{
"code": null,
"e": 8719,
"s": 8570,
"text": "from scipy.stats import mode\nlabels = np.zeros_like(clusters)\nfor i in range(10):\nmask = (clusters == i)\nlabels[mask] = mode(digits.target[mask])[0]"
},
{
"code": null,
"e": 8796,
"s": 8719,
"text": "We can also check the accuracy with the help of the below mentioned command."
},
{
"code": null,
"e": 8877,
"s": 8796,
"text": "from sklearn.metrics import accuracy_score\naccuracy_score(digits.target, labels)"
},
{
"code": null,
"e": 8897,
"s": 8877,
"text": "0.7935447968836951\n"
}
] |
Python 3 - String len() Method
|
The len() method returns the length of the string.
Following is the syntax for len() method −
len( str )
NA
This method returns the length of the string.
The following example shows the usage of len() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
When we run above program, it produces the following result −
Length of the string: 32
|
[
{
"code": null,
"e": 2525,
"s": 2474,
"text": "The len() method returns the length of the string."
},
{
"code": null,
"e": 2568,
"s": 2525,
"text": "Following is the syntax for len() method −"
},
{
"code": null,
"e": 2580,
"s": 2568,
"text": "len( str )\n"
},
{
"code": null,
"e": 2583,
"s": 2580,
"text": "NA"
},
{
"code": null,
"e": 2629,
"s": 2583,
"text": "This method returns the length of the string."
},
{
"code": null,
"e": 2684,
"s": 2629,
"text": "The following example shows the usage of len() method."
},
{
"code": null,
"e": 2788,
"s": 2684,
"text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!!\"\nprint (\"Length of the string: \", len(str))"
},
{
"code": null,
"e": 2850,
"s": 2788,
"text": "When we run above program, it produces the following result −"
}
] |
How to load data from JavaScript array using jQuery DataTables plugin ?
|
18 Jan, 2021
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpages. It is a simple-to-use plug-in with a huge range of options for the developer’s custom changes. The common features of the DataTable plugin are paging, multiple column ordering, sorting, and searching.
The pre-compiled files which are needed for code implementation are
CSS :
https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css
JavaScript :
//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
Approach: The approach followed is passing dynamic data to the dataTable rather than passing information from any document. The steps taken are as follows.
Pass a JavaScript array dataSet for user’s data with name, designation, salary, and address as data to be used.
HTML table is used with table id as tableID.
Datatable is initialized with the table id.
In the script part, the JS array is passed by using the data option.
Even the columns are dynamically created using the columns.title option.
Example: The following example demonstrates to load data from JavaScript array in datatables using the plugin.
HTML
<!DOCTYPE html><html> <head> <meta content="initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport" /> <meta name="viewport" content="width=device-width" /> <!-- Datatable plugin CSS file --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" /> <!-- jQuery library file --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- Datatable plugin JS library file --> <script type="text/javascript" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"> </script></head> <body> <h2>load data from JavaScript array using Datatables</h2> <!--HTML table with student data--> <table id="tableID" class="display" style="width:100%"> <thead> <tr> <th>User name</th> <th>Designation</th> <th>Salary</th> <th>Address</th> <th>City</th> </tr> </thead> </table> <script> var dataSet = [ [ "Tina Mukherjee", "BPO member", "300000", "24,chandni chowk", "Pune" ], [ "Gaurav", "Teacher", "100750", "esquare,JM road", "Pune" ], [ "Ashtwini", "Junior engineer", "860000", "Santa cruz", "mumbai" ], [ "Celina", "Javascript Developer", "430060", "crr lake side ville", "tellapur" ], [ "Aisha", "Nurse", "160000", "rk puram", "Delhi" ], [ "Brad henry", "Accountant", "370000", "chaurasi lane", "Kolkatta" ], [ "Harry", "Salesman", "130500", "32, krishna nagar", "Navi mumbai" ], [ "Rhovina", "Amazon supporter", "300900", "Aparna zone", "hyderabad" ], [ "Celina", "Senior Developer", "200000", "23, chandni chowk", "pune" ], [ "Glenny", "Administrator", "200500", "Nagpur", "Maharashtra" ], [ "Brad Pitt", "Engineer", "100000", "sainikpuri", "Delhi" ], [ "Deepa", "Team Leader", "200500", "Annanagar", "Chennai" ], [ "Angelina", "CEO", "1000000", "JM road", "Aundh pune" ] ]; $(document).ready(function() { $('#tableID').DataTable( { data: dataSet, columns: [ { title: "Name" }, { title: "Designation" }, { title: "Salary" }, { title: "Address" }, { title: "City" } ] } ); } );</script></body> </html>
Output:
Before execute:
After execute:
CSS-Misc
HTML-Misc
jQuery-Plugin
HTML
JavaScript
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpages. It is a simple-to-use plug-in with a huge range of options for the developer’s custom changes. The common features of the DataTable plugin are paging, multiple column ordering, sorting, and searching."
},
{
"code": null,
"e": 415,
"s": 345,
"text": "The pre-compiled files which are needed for code implementation are "
},
{
"code": null,
"e": 421,
"s": 415,
"text": "CSS :"
},
{
"code": null,
"e": 486,
"s": 421,
"text": "https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"
},
{
"code": null,
"e": 500,
"s": 486,
"text": "JavaScript : "
},
{
"code": null,
"e": 557,
"s": 500,
"text": "//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"
},
{
"code": null,
"e": 722,
"s": 557,
"text": "Approach: The approach followed is passing dynamic data to the dataTable rather than passing information from any document. The steps taken are as follows. "
},
{
"code": null,
"e": 834,
"s": 722,
"text": "Pass a JavaScript array dataSet for user’s data with name, designation, salary, and address as data to be used."
},
{
"code": null,
"e": 879,
"s": 834,
"text": "HTML table is used with table id as tableID."
},
{
"code": null,
"e": 923,
"s": 879,
"text": "Datatable is initialized with the table id."
},
{
"code": null,
"e": 992,
"s": 923,
"text": "In the script part, the JS array is passed by using the data option."
},
{
"code": null,
"e": 1065,
"s": 992,
"text": "Even the columns are dynamically created using the columns.title option."
},
{
"code": null,
"e": 1176,
"s": 1065,
"text": "Example: The following example demonstrates to load data from JavaScript array in datatables using the plugin."
},
{
"code": null,
"e": 1181,
"s": 1176,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta content=\"initial-scale=1, maximum-scale=1, user-scalable=0\" name=\"viewport\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <!-- Datatable plugin CSS file --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css\" /> <!-- jQuery library file --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- Datatable plugin JS library file --> <script type=\"text/javascript\" src=\"https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js\"> </script></head> <body> <h2>load data from JavaScript array using Datatables</h2> <!--HTML table with student data--> <table id=\"tableID\" class=\"display\" style=\"width:100%\"> <thead> <tr> <th>User name</th> <th>Designation</th> <th>Salary</th> <th>Address</th> <th>City</th> </tr> </thead> </table> <script> var dataSet = [ [ \"Tina Mukherjee\", \"BPO member\", \"300000\", \"24,chandni chowk\", \"Pune\" ], [ \"Gaurav\", \"Teacher\", \"100750\", \"esquare,JM road\", \"Pune\" ], [ \"Ashtwini\", \"Junior engineer\", \"860000\", \"Santa cruz\", \"mumbai\" ], [ \"Celina\", \"Javascript Developer\", \"430060\", \"crr lake side ville\", \"tellapur\" ], [ \"Aisha\", \"Nurse\", \"160000\", \"rk puram\", \"Delhi\" ], [ \"Brad henry\", \"Accountant\", \"370000\", \"chaurasi lane\", \"Kolkatta\" ], [ \"Harry\", \"Salesman\", \"130500\", \"32, krishna nagar\", \"Navi mumbai\" ], [ \"Rhovina\", \"Amazon supporter\", \"300900\", \"Aparna zone\", \"hyderabad\" ], [ \"Celina\", \"Senior Developer\", \"200000\", \"23, chandni chowk\", \"pune\" ], [ \"Glenny\", \"Administrator\", \"200500\", \"Nagpur\", \"Maharashtra\" ], [ \"Brad Pitt\", \"Engineer\", \"100000\", \"sainikpuri\", \"Delhi\" ], [ \"Deepa\", \"Team Leader\", \"200500\", \"Annanagar\", \"Chennai\" ], [ \"Angelina\", \"CEO\", \"1000000\", \"JM road\", \"Aundh pune\" ] ]; $(document).ready(function() { $('#tableID').DataTable( { data: dataSet, columns: [ { title: \"Name\" }, { title: \"Designation\" }, { title: \"Salary\" }, { title: \"Address\" }, { title: \"City\" } ] } ); } );</script></body> </html>",
"e": 4163,
"s": 1181,
"text": null
},
{
"code": null,
"e": 4171,
"s": 4163,
"text": "Output:"
},
{
"code": null,
"e": 4187,
"s": 4171,
"text": "Before execute:"
},
{
"code": null,
"e": 4202,
"s": 4187,
"text": "After execute:"
},
{
"code": null,
"e": 4211,
"s": 4202,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4221,
"s": 4211,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4235,
"s": 4221,
"text": "jQuery-Plugin"
},
{
"code": null,
"e": 4240,
"s": 4235,
"text": "HTML"
},
{
"code": null,
"e": 4251,
"s": 4240,
"text": "JavaScript"
},
{
"code": null,
"e": 4258,
"s": 4251,
"text": "JQuery"
},
{
"code": null,
"e": 4275,
"s": 4258,
"text": "Web Technologies"
},
{
"code": null,
"e": 4280,
"s": 4275,
"text": "HTML"
},
{
"code": null,
"e": 4378,
"s": 4280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4402,
"s": 4378,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4441,
"s": 4402,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4480,
"s": 4441,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4500,
"s": 4480,
"text": "Angular File Upload"
},
{
"code": null,
"e": 4529,
"s": 4500,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4590,
"s": 4529,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4662,
"s": 4590,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4702,
"s": 4662,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4744,
"s": 4702,
"text": "Roadmap to Learn JavaScript For Beginners"
}
] |
HTML | disabled Attribute
|
24 Dec, 2021
The disabled attribute in HTML indicates whether the element is disabled or not. If this attribute is set, the element is disabled. The disabled attribute is usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused. It is a boolean attribute.
Usage: It can be used on the following elements: <button>, <input>, <option>, <select>, <textarea>, <fieldset>, <optgroup> and <keygen>.
Syntax:
<tag disabled></tag>
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled button--> <button type="button" disabled>Click Me!</button> </body> </html>
Output:
<input>: When the disabled attribute is present, it specifies that the input is disabled. A disabled input is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <label>Input: <input type="text" name="value" value = "This input field is disabled" disabled> </label> </body> </html>
Output:
<option>: When the disabled attribute is present, it specifies that the option field is disabled. A disabled option is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <p>Volvo is disabled.</p> <select> <option value="volvo" disabled>Volvo</option> <option value="saab">Saab</option> <option value="vw">VW</option> <option value="audi">Audi</option> </select><br> </body> </html>
Output:
<select>: When the disabled attribute is present, it specifies that the select field is disabled. A disabled select is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <p>This select field is disabled.</p> <select disabled> <option value="binary">Binary Search</option> <option value="linear">Linear Search</option> <option value="interpolation"> Interpolation Search </option> </select> </body> </html>
Output:
<textarea>: When the disabled attribute is present, it specifies that the textarea field is disabled. A disabled textarea is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled textarea--> <textarea disabled> This textarea field is disabled. </textarea> </body> </html>
Output:
<fieldset>: When the disabled attribute is present, it specifies that the fieldset is disabled. A disabled fieldset is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled fieldset--> <p>This field set is disabled.</p> <fieldset disabled> Name: <input type="text"><br> </fieldset> </body> </html>
Output:
<optgroup>: When the disabled attribute is present, it specifies that the optgroup is disabled. A disabled optgroup is unusable and un-clickable.
Example:
HTML
<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled optgroup--> <select> <optgroup label="German Cars" disabled> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </optgroup> </select> </body> </html>
Output:
Supported Browsers: The browser supported by disabled attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
simmytarika5
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 361,
"s": 53,
"text": "The disabled attribute in HTML indicates whether the element is disabled or not. If this attribute is set, the element is disabled. The disabled attribute is usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused. It is a boolean attribute."
},
{
"code": null,
"e": 499,
"s": 361,
"text": "Usage: It can be used on the following elements: <button>, <input>, <option>, <select>, <textarea>, <fieldset>, <optgroup> and <keygen>. "
},
{
"code": null,
"e": 509,
"s": 499,
"text": "Syntax: "
},
{
"code": null,
"e": 530,
"s": 509,
"text": "<tag disabled></tag>"
},
{
"code": null,
"e": 540,
"s": 530,
"text": "Example: "
},
{
"code": null,
"e": 545,
"s": 540,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled button--> <button type=\"button\" disabled>Click Me!</button> </body> </html>",
"e": 905,
"s": 545,
"text": null
},
{
"code": null,
"e": 914,
"s": 905,
"text": "Output: "
},
{
"code": null,
"e": 1051,
"s": 914,
"text": "<input>: When the disabled attribute is present, it specifies that the input is disabled. A disabled input is unusable and un-clickable."
},
{
"code": null,
"e": 1061,
"s": 1051,
"text": "Example: "
},
{
"code": null,
"e": 1066,
"s": 1061,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <label>Input: <input type=\"text\" name=\"value\" value = \"This input field is disabled\" disabled> </label> </body> </html>",
"e": 1506,
"s": 1066,
"text": null
},
{
"code": null,
"e": 1515,
"s": 1506,
"text": "Output: "
},
{
"code": null,
"e": 1661,
"s": 1515,
"text": "<option>: When the disabled attribute is present, it specifies that the option field is disabled. A disabled option is unusable and un-clickable."
},
{
"code": null,
"e": 1671,
"s": 1661,
"text": "Example: "
},
{
"code": null,
"e": 1676,
"s": 1671,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <p>Volvo is disabled.</p> <select> <option value=\"volvo\" disabled>Volvo</option> <option value=\"saab\">Saab</option> <option value=\"vw\">VW</option> <option value=\"audi\">Audi</option> </select><br> </body> </html>",
"e": 2257,
"s": 1676,
"text": null
},
{
"code": null,
"e": 2266,
"s": 2257,
"text": "Output: "
},
{
"code": null,
"e": 2412,
"s": 2266,
"text": "<select>: When the disabled attribute is present, it specifies that the select field is disabled. A disabled select is unusable and un-clickable."
},
{
"code": null,
"e": 2422,
"s": 2412,
"text": "Example: "
},
{
"code": null,
"e": 2427,
"s": 2422,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled input--> <p>This select field is disabled.</p> <select disabled> <option value=\"binary\">Binary Search</option> <option value=\"linear\">Linear Search</option> <option value=\"interpolation\"> Interpolation Search </option> </select> </body> </html> ",
"e": 3039,
"s": 2427,
"text": null
},
{
"code": null,
"e": 3048,
"s": 3039,
"text": "Output: "
},
{
"code": null,
"e": 3200,
"s": 3048,
"text": "<textarea>: When the disabled attribute is present, it specifies that the textarea field is disabled. A disabled textarea is unusable and un-clickable."
},
{
"code": null,
"e": 3210,
"s": 3200,
"text": "Example: "
},
{
"code": null,
"e": 3215,
"s": 3210,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled textarea--> <textarea disabled> This textarea field is disabled. </textarea> </body> </html>",
"e": 3604,
"s": 3215,
"text": null
},
{
"code": null,
"e": 3613,
"s": 3604,
"text": "Output: "
},
{
"code": null,
"e": 3759,
"s": 3613,
"text": "<fieldset>: When the disabled attribute is present, it specifies that the fieldset is disabled. A disabled fieldset is unusable and un-clickable."
},
{
"code": null,
"e": 3769,
"s": 3759,
"text": "Example: "
},
{
"code": null,
"e": 3774,
"s": 3769,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled fieldset--> <p>This field set is disabled.</p> <fieldset disabled> Name: <input type=\"text\"><br> </fieldset> </body> </html>",
"e": 4205,
"s": 3774,
"text": null
},
{
"code": null,
"e": 4214,
"s": 4205,
"text": "Output: "
},
{
"code": null,
"e": 4360,
"s": 4214,
"text": "<optgroup>: When the disabled attribute is present, it specifies that the optgroup is disabled. A disabled optgroup is unusable and un-clickable."
},
{
"code": null,
"e": 4370,
"s": 4360,
"text": "Example: "
},
{
"code": null,
"e": 4375,
"s": 4370,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML disabled Attribute</h2> <!--A disabled optgroup--> <select> <optgroup label=\"German Cars\" disabled> <option value=\"mercedes\">Mercedes</option> <option value=\"audi\">Audi</option> </optgroup> </select> </body> </html>",
"e": 4880,
"s": 4375,
"text": null
},
{
"code": null,
"e": 4889,
"s": 4880,
"text": "Output: "
},
{
"code": null,
"e": 4971,
"s": 4889,
"text": "Supported Browsers: The browser supported by disabled attribute are listed below:"
},
{
"code": null,
"e": 4985,
"s": 4971,
"text": "Google Chrome"
},
{
"code": null,
"e": 5003,
"s": 4985,
"text": "Internet Explorer"
},
{
"code": null,
"e": 5011,
"s": 5003,
"text": "Firefox"
},
{
"code": null,
"e": 5017,
"s": 5011,
"text": "Opera"
},
{
"code": null,
"e": 5024,
"s": 5017,
"text": "Safari"
},
{
"code": null,
"e": 5039,
"s": 5026,
"text": "simmytarika5"
},
{
"code": null,
"e": 5059,
"s": 5039,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 5075,
"s": 5059,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 5080,
"s": 5075,
"text": "HTML"
},
{
"code": null,
"e": 5097,
"s": 5080,
"text": "Web Technologies"
},
{
"code": null,
"e": 5102,
"s": 5097,
"text": "HTML"
}
] |
halt command in Linux with examples
|
21 May, 2019
This command in Linux is used to instruct the hardware to stop all the CPU functions. Basically, it reboots or stops the system. If the system is in runlevel 0 or 6 or using the command with –force option, it results in rebooting of the system otherwise it results in shutdown.
Syntax:
halt [OPTION]...
Options:
Files:
/var/log/wtmp : Consists a new runlevel record for the shutdown time.
/var/run/utmp : Gets updated by a shutdown time record when the current runlevel will be read.
Example 1: To cease all CPU function on the system.
$halt
Output:
Broadcast message from ubuntu@ubuntu
root@ubuntu:/var/log# (/dev/pts/0) at 10:15...
The system is going down for halt NOW.
Example 2: To power off the system using halt command.
$halt -p
Output:
Broadcast message from ubuntu@ubuntu
(/dev/pts/0) at 10:16...
The system is going down for power off NOW.
Example 3: halt command with -w option to write shutdown record.
$halt -w
Note: For this, there will be no output on the screen.
linux-command
Linux-system-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "This command in Linux is used to instruct the hardware to stop all the CPU functions. Basically, it reboots or stops the system. If the system is in runlevel 0 or 6 or using the command with –force option, it results in rebooting of the system otherwise it results in shutdown."
},
{
"code": null,
"e": 314,
"s": 306,
"text": "Syntax:"
},
{
"code": null,
"e": 331,
"s": 314,
"text": "halt [OPTION]..."
},
{
"code": null,
"e": 340,
"s": 331,
"text": "Options:"
},
{
"code": null,
"e": 347,
"s": 340,
"text": "Files:"
},
{
"code": null,
"e": 417,
"s": 347,
"text": "/var/log/wtmp : Consists a new runlevel record for the shutdown time."
},
{
"code": null,
"e": 512,
"s": 417,
"text": "/var/run/utmp : Gets updated by a shutdown time record when the current runlevel will be read."
},
{
"code": null,
"e": 564,
"s": 512,
"text": "Example 1: To cease all CPU function on the system."
},
{
"code": null,
"e": 570,
"s": 564,
"text": "$halt"
},
{
"code": null,
"e": 578,
"s": 570,
"text": "Output:"
},
{
"code": null,
"e": 702,
"s": 578,
"text": "Broadcast message from ubuntu@ubuntu\nroot@ubuntu:/var/log# (/dev/pts/0) at 10:15...\nThe system is going down for halt NOW.\n"
},
{
"code": null,
"e": 757,
"s": 702,
"text": "Example 2: To power off the system using halt command."
},
{
"code": null,
"e": 766,
"s": 757,
"text": "$halt -p"
},
{
"code": null,
"e": 774,
"s": 766,
"text": "Output:"
},
{
"code": null,
"e": 881,
"s": 774,
"text": "Broadcast message from ubuntu@ubuntu\n(/dev/pts/0) at 10:16...\nThe system is going down for power off NOW.\n"
},
{
"code": null,
"e": 946,
"s": 881,
"text": "Example 3: halt command with -w option to write shutdown record."
},
{
"code": null,
"e": 955,
"s": 946,
"text": "$halt -w"
},
{
"code": null,
"e": 1010,
"s": 955,
"text": "Note: For this, there will be no output on the screen."
},
{
"code": null,
"e": 1024,
"s": 1010,
"text": "linux-command"
},
{
"code": null,
"e": 1046,
"s": 1024,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1053,
"s": 1046,
"text": "Picked"
},
{
"code": null,
"e": 1077,
"s": 1053,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1088,
"s": 1077,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1107,
"s": 1088,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1205,
"s": 1107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1240,
"s": 1205,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1276,
"s": 1240,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 1314,
"s": 1276,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1352,
"s": 1314,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1388,
"s": 1352,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1414,
"s": 1388,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1449,
"s": 1414,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1487,
"s": 1449,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 1522,
"s": 1487,
"text": "Cat command in Linux with examples"
}
] |
ViewModel in Android Architecture Components
|
23 Mar, 2021
ViewModel is part of the android architecture component. Android architecture components are the components that are used to build robust, clean, and scalable apps. Android architecture components hold some classes to manage UI components and Data persistence. The ViewModel class is designed to store and manage UI-related data in a lifecycle-conscious way. ViewModel classes are used to store the data even the configuration changes like rotating screen. ViewModel is one of the most critical class of the Android Jetpack Architecture Component that support data for UI components. Its purpose is to hold and manage the UI-related data. Moreover, its main function is to maintain the integrity and allows data to service during configuration changes like screen rotations. Any kind of configuration change in Android devices tends to recreate the whole activity of the application. It means the data will be lost if it has been not saved and restored properly from the activity which was destroyed. To avoid these issues, it is recommended to store all UI data in the ViewModel instead of an activity.
An activity must extend the ViewModel class to create a view model:
class MainActivityViewModel : ViewModel() {
.........
........
}
Android Architecture Components provides the ViewModel helper class for the UI controller that is responsible for preparing data for the UI. ViewModel objects are automatically retained during configuration changes we will see that in the below example. Now let’s get into the code,
Step 1: Add these dependencies in the build.gradle file
def lifecycle_version = “2.3.0”
// ViewModel
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”
implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”
implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version”
implementation “androidx.core:core-ktx:1.3.2”
Also, add the following dependency to the build.gradle(Module:app) file. We are adding these two dependencies because to avoid using findViewById() in our MainActivity.kt file. Try this out otherwise use the normal way like findViewById().
apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.369" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:text="Click" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.0" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var number = 0 textView.text = number.toString() button.setOnClickListener { number++ textView.text = number.toString() } }}
Output:
Now just click on the button 3 to 4 times you will see the incremented number on the screen. Now just try to rotate your emulator or device.
You will see the number becomes 0, the question is why? How it erases the value by rotating the screen. Ok to get the answer we have to get some knowledge about the Lifecycle of a ViewModel.
In the above image when our activity created, the system calls the onCreate() after that onStart() then onResume() but when we rotate the screen our activity is destroyed and after rotation again system calls onCreate() and other functions one after another. As our activity destroyed our activity data has also vanished.
To overcome this problem we use ViewModels which holds the data even after configuration changes like the rotation of the screen. The above image is showing the ViewModel scope, even with any configuration changes the data is persistent. You usually request a ViewModel for the first time when the system calls an activity object’s onCreate() method. The system may call onCreate() several times throughout the life of an activity, such as when a device screen is rotated. The ViewModel exists from when you first request a ViewModel until the activity is finished and destroyed.
Step 1: Create a Kotlin class file MainActivityViewModel.kt. Our MainActivity class file extends the ViewModel class.
Refer to this article: How to Create Classes in Android Studio?
Kotlin
import androidx.lifecycle.ViewModel class MainActivityViewModel : ViewModel() { var number = 0 fun addOne() { number++ }}
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and update the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.ViewModelProviderimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // view model instance var viewModel: MainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java) // setting text view textView.text = viewModel.number.toString() //handling button click event button.setOnClickListener { viewModel.addOne() textView.text = viewModel.number.toString() } }}
Output:
Even after rotating our screen, we get the same value. So that’s it, this is the basic of ViewModel there are many other advanced things of view model we will cover later.
Helps in data management during configuration changes
Reduce UI bugs and crashes
Best practice for software design
Android-Jetpack
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Mar, 2021"
},
{
"code": null,
"e": 1158,
"s": 53,
"text": "ViewModel is part of the android architecture component. Android architecture components are the components that are used to build robust, clean, and scalable apps. Android architecture components hold some classes to manage UI components and Data persistence. The ViewModel class is designed to store and manage UI-related data in a lifecycle-conscious way. ViewModel classes are used to store the data even the configuration changes like rotating screen. ViewModel is one of the most critical class of the Android Jetpack Architecture Component that support data for UI components. Its purpose is to hold and manage the UI-related data. Moreover, its main function is to maintain the integrity and allows data to service during configuration changes like screen rotations. Any kind of configuration change in Android devices tends to recreate the whole activity of the application. It means the data will be lost if it has been not saved and restored properly from the activity which was destroyed. To avoid these issues, it is recommended to store all UI data in the ViewModel instead of an activity. "
},
{
"code": null,
"e": 1226,
"s": 1158,
"text": "An activity must extend the ViewModel class to create a view model:"
},
{
"code": null,
"e": 1270,
"s": 1226,
"text": "class MainActivityViewModel : ViewModel() {"
},
{
"code": null,
"e": 1280,
"s": 1270,
"text": "........."
},
{
"code": null,
"e": 1289,
"s": 1280,
"text": "........"
},
{
"code": null,
"e": 1291,
"s": 1289,
"text": "}"
},
{
"code": null,
"e": 1574,
"s": 1291,
"text": "Android Architecture Components provides the ViewModel helper class for the UI controller that is responsible for preparing data for the UI. ViewModel objects are automatically retained during configuration changes we will see that in the below example. Now let’s get into the code,"
},
{
"code": null,
"e": 1630,
"s": 1574,
"text": "Step 1: Add these dependencies in the build.gradle file"
},
{
"code": null,
"e": 1662,
"s": 1630,
"text": "def lifecycle_version = “2.3.0”"
},
{
"code": null,
"e": 1675,
"s": 1662,
"text": "// ViewModel"
},
{
"code": null,
"e": 1754,
"s": 1675,
"text": "implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 1832,
"s": 1754,
"text": "implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 1909,
"s": 1832,
"text": "implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 1955,
"s": 1909,
"text": "implementation “androidx.core:core-ktx:1.3.2”"
},
{
"code": null,
"e": 2195,
"s": 1955,
"text": "Also, add the following dependency to the build.gradle(Module:app) file. We are adding these two dependencies because to avoid using findViewById() in our MainActivity.kt file. Try this out otherwise use the normal way like findViewById()."
},
{
"code": null,
"e": 2226,
"s": 2195,
"text": "apply plugin: ‘kotlin-android’"
},
{
"code": null,
"e": 2268,
"s": 2226,
"text": "apply plugin: ‘kotlin-android-extensions’"
},
{
"code": null,
"e": 2316,
"s": 2268,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2458,
"s": 2316,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 2462,
"s": 2458,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"0\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.369\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"100dp\" android:text=\"Click\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" app:layout_constraintVertical_bias=\"0.0\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 3824,
"s": 2462,
"text": null
},
{
"code": null,
"e": 3870,
"s": 3824,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 3983,
"s": 3870,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. "
},
{
"code": null,
"e": 3990,
"s": 3983,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var number = 0 textView.text = number.toString() button.setOnClickListener { number++ textView.text = number.toString() } }}",
"e": 4495,
"s": 3990,
"text": null
},
{
"code": null,
"e": 4503,
"s": 4495,
"text": "Output:"
},
{
"code": null,
"e": 4644,
"s": 4503,
"text": "Now just click on the button 3 to 4 times you will see the incremented number on the screen. Now just try to rotate your emulator or device."
},
{
"code": null,
"e": 4835,
"s": 4644,
"text": "You will see the number becomes 0, the question is why? How it erases the value by rotating the screen. Ok to get the answer we have to get some knowledge about the Lifecycle of a ViewModel."
},
{
"code": null,
"e": 5157,
"s": 4835,
"text": "In the above image when our activity created, the system calls the onCreate() after that onStart() then onResume() but when we rotate the screen our activity is destroyed and after rotation again system calls onCreate() and other functions one after another. As our activity destroyed our activity data has also vanished."
},
{
"code": null,
"e": 5737,
"s": 5157,
"text": "To overcome this problem we use ViewModels which holds the data even after configuration changes like the rotation of the screen. The above image is showing the ViewModel scope, even with any configuration changes the data is persistent. You usually request a ViewModel for the first time when the system calls an activity object’s onCreate() method. The system may call onCreate() several times throughout the life of an activity, such as when a device screen is rotated. The ViewModel exists from when you first request a ViewModel until the activity is finished and destroyed."
},
{
"code": null,
"e": 5855,
"s": 5737,
"text": "Step 1: Create a Kotlin class file MainActivityViewModel.kt. Our MainActivity class file extends the ViewModel class."
},
{
"code": null,
"e": 5919,
"s": 5855,
"text": "Refer to this article: How to Create Classes in Android Studio?"
},
{
"code": null,
"e": 5926,
"s": 5919,
"text": "Kotlin"
},
{
"code": "import androidx.lifecycle.ViewModel class MainActivityViewModel : ViewModel() { var number = 0 fun addOne() { number++ }}",
"e": 6075,
"s": 5926,
"text": null
},
{
"code": null,
"e": 6121,
"s": 6075,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 6305,
"s": 6121,
"text": "Go to the MainActivity.kt file and update the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 6312,
"s": 6305,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.ViewModelProviderimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // view model instance var viewModel: MainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java) // setting text view textView.text = viewModel.number.toString() //handling button click event button.setOnClickListener { viewModel.addOne() textView.text = viewModel.number.toString() } }}",
"e": 7070,
"s": 6312,
"text": null
},
{
"code": null,
"e": 7078,
"s": 7070,
"text": "Output:"
},
{
"code": null,
"e": 7250,
"s": 7078,
"text": "Even after rotating our screen, we get the same value. So that’s it, this is the basic of ViewModel there are many other advanced things of view model we will cover later."
},
{
"code": null,
"e": 7304,
"s": 7250,
"text": "Helps in data management during configuration changes"
},
{
"code": null,
"e": 7331,
"s": 7304,
"text": "Reduce UI bugs and crashes"
},
{
"code": null,
"e": 7365,
"s": 7331,
"text": "Best practice for software design"
},
{
"code": null,
"e": 7381,
"s": 7365,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 7396,
"s": 7381,
"text": "Kotlin Android"
},
{
"code": null,
"e": 7403,
"s": 7396,
"text": "Picked"
},
{
"code": null,
"e": 7411,
"s": 7403,
"text": "Android"
},
{
"code": null,
"e": 7418,
"s": 7411,
"text": "Kotlin"
},
{
"code": null,
"e": 7426,
"s": 7418,
"text": "Android"
}
] |
Program to print Kite Pattern
|
21 Apr, 2021
Given task is to draw a KITE pattern using ‘$’ Example:
Output:
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
$$$
$$$$$
Below is the code to implement the above problem:Program:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to print Kite Pattern#include <bits/stdc++.h>#include <stdlib.h> using namespace std;int main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { cout << " "; } // For printing the $ for (j = 1; j <= i; j++) { cout << prt; } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } cout << prt; } cout << "\n"; space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { cout << " "; } for (j = 1; j <= i; j++) { cout << prt; } for (k = 1; k <= (i - 1); k++) { cout << prt; } space++; cout << "\n"; } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { cout << " "; } for (j = 1; j <= i; j++) { cout << prt; } } if ((i % 2) != 0) { cout << "\n"; space--; } } return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// C Program to print Kite Pattern#include <stdio.h>#include <stdlib.h> int main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { printf(" "); } // For printing the $ for (j = 1; j <= i; j++) { printf("%c", prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } printf("%c", prt); } printf("\n"); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { printf(" "); } for (j = 1; j <= i; j++) { printf("%c", prt); } for (k = 1; k <= (i - 1); k++) { printf("%c", prt); } space++; printf("\n"); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { printf(" "); } for (j = 1; j <= i; j++) { printf("%c", prt); } } if ((i % 2) != 0) { printf("\n"); space--; } } return 0;}
// Java Program to print Kite Patternimport java.io.*; class GFG{public static void main(String[] args){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { System.out.print(" "); } // For printing the $ for (j = 1; j <= i; j++) { System.out.print(prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } System.out.print(prt); } System.out.println(); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { System.out.print(" "); } for (j = 1; j <= i; j++) { System.out.print(prt); } for (k = 1; k <= (i - 1); k++) { System.out.print(prt); } space++; System.out.println(); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { System.out.print(" "); } for (j = 1; j <= i; j++) { System.out.print(prt); } } if ((i % 2) != 0) { System.out.println(); space--; } }}} // This code is contributed by inder_verma..
# Python3 Program to print Kite Patternif __name__ == '__main__': space = 4 prt = '$' for i in range(1, 6): # For printing the space for sp in range(space, 0, -1): print(end = " ") # For printing the $ for j in range(1, i + 1): print(prt, end = "") for k in range(1, i): if (i == 1): continue print(prt, end = "") print() space -= 1 space = 1 for i in range(4, 0, -1): for sp in range(space, 0, -1): print(end = " ") for j in range(1, i + 1): print(prt, end = "") for k in range(1, i): print(prt, end = "") space += 1 print() space = 3 for i in range(2, 6): if ((i % 2) != 0): for sp in range(space, 0, -1): print(" ", end = "") for j in range(1, i + 1): print(prt, end = "") if ((i % 2) != 0): print() space -= 1 # This code is contributed by# mohit kumar 29
// C# Program to print Kite Patternusing System; class GFG{public static void Main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { Console.Write(" "); } // For printing the $ for (j = 1; j <= i; j++) { Console.Write(prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } Console.Write(prt); } Console.WriteLine(); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { Console.Write(" "); } for (j = 1; j <= i; j++) { Console.Write(prt); } for (k = 1; k <= (i - 1); k++) { Console.Write(prt); } space++; Console.WriteLine(); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { Console.Write(" "); } for (j = 1; j <= i; j++) { Console.Write(prt); } } if ((i % 2) != 0) { Console.WriteLine(); space--; } }}} // This code is contributed by Soumik
<?php// PHP Program to print Kite Pattern $space = 4;$prt = '$'; for ($i = 1; $i <= 5; $i++){ // For printing the space for ($sp = $space; $sp >= 1; $sp--) { echo (" "); } // For printing the $ for ($j = 1; $j <= $i; $j++) { echo ( $prt); } for ($k = 1; $k <= ($i - 1); $k++) { if ($i == 1) { continue; } echo ( $prt); }echo ("\n");$space--;} $space = 1; for ($i = 4; $i >= 1; $i--){ for ($sp = $space; $sp >= 1; $sp--) { echo (" "); } for ($j = 1; $j <= $i; $j++) { echo ( $prt); } for ($k = 1; $k <= ($i - 1); $k++) { echo ( $prt); } $space++; echo ("\n");} $space = 3; for ($i = 2; $i <= 5; $i++){ if (($i % 2) != 0) { for ($sp = $space; $sp >= 1; $sp--) { echo (" "); } for ($j = 1; $j <= $i; $j++) { echo ( $prt); } } if (($i % 2) != 0) { echo ("\n"); $space--; }} // This code is contributed// by Sach_Code?>
<script> // JavaScript Program to print Kite Pattern var i, j, k, sp, space = 4; var prt = "$"; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { document.write(" "); } // For printing the $ for (j = 1; j <= i; j++) { document.write(prt); } for (k = 1; k <= i - 1; k++) { if (i == 1) { continue; } document.write(prt); } document.write("<br>"); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { document.write(" "); } for (j = 1; j <= i; j++) { document.write(prt); } for (k = 1; k <= i - 1; k++) { document.write(prt); } space++; document.write("<br>"); } space = 3; for (i = 2; i <= 5; i++) { if (i % 2 != 0) { for (sp = space; sp >= 1; sp--) { document.write(" "); } for (j = 1; j <= i; j++) { document.write(prt); } } if (i % 2 != 0) { document.write("<br>"); space--; } } </script>
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
$$$
$$$$$
SoumikMondal
inderDuMCA
Sach_Code
Akanksha_Rai
mohit kumar 29
rdtank
pattern-printing
C Programs
C++ Programs
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 86,
"s": 28,
"text": "Given task is to draw a KITE pattern using ‘$’ Example: "
},
{
"code": null,
"e": 212,
"s": 86,
"text": "Output:\n $\n $$$\n $$$$$\n $$$$$$$\n $$$$$$$$$\n $$$$$$$\n $$$$$\n $$$\n $\n $$$\n $$$$$"
},
{
"code": null,
"e": 272,
"s": 212,
"text": "Below is the code to implement the above problem:Program: "
},
{
"code": null,
"e": 276,
"s": 272,
"text": "C++"
},
{
"code": null,
"e": 278,
"s": 276,
"text": "C"
},
{
"code": null,
"e": 283,
"s": 278,
"text": "Java"
},
{
"code": null,
"e": 291,
"s": 283,
"text": "Python3"
},
{
"code": null,
"e": 294,
"s": 291,
"text": "C#"
},
{
"code": null,
"e": 298,
"s": 294,
"text": "PHP"
},
{
"code": null,
"e": 309,
"s": 298,
"text": "Javascript"
},
{
"code": "// C++ Program to print Kite Pattern#include <bits/stdc++.h>#include <stdlib.h> using namespace std;int main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { cout << \" \"; } // For printing the $ for (j = 1; j <= i; j++) { cout << prt; } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } cout << prt; } cout << \"\\n\"; space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { cout << \" \"; } for (j = 1; j <= i; j++) { cout << prt; } for (k = 1; k <= (i - 1); k++) { cout << prt; } space++; cout << \"\\n\"; } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { cout << \" \"; } for (j = 1; j <= i; j++) { cout << prt; } } if ((i % 2) != 0) { cout << \"\\n\"; space--; } } return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 1698,
"s": 309,
"text": null
},
{
"code": "// C Program to print Kite Pattern#include <stdio.h>#include <stdlib.h> int main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { printf(\" \"); } // For printing the $ for (j = 1; j <= i; j++) { printf(\"%c\", prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } printf(\"%c\", prt); } printf(\"\\n\"); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { printf(\" \"); } for (j = 1; j <= i; j++) { printf(\"%c\", prt); } for (k = 1; k <= (i - 1); k++) { printf(\"%c\", prt); } space++; printf(\"\\n\"); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { printf(\" \"); } for (j = 1; j <= i; j++) { printf(\"%c\", prt); } } if ((i % 2) != 0) { printf(\"\\n\"); space--; } } return 0;}",
"e": 2934,
"s": 1698,
"text": null
},
{
"code": "// Java Program to print Kite Patternimport java.io.*; class GFG{public static void main(String[] args){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { System.out.print(\" \"); } // For printing the $ for (j = 1; j <= i; j++) { System.out.print(prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } System.out.print(prt); } System.out.println(); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { System.out.print(\" \"); } for (j = 1; j <= i; j++) { System.out.print(prt); } for (k = 1; k <= (i - 1); k++) { System.out.print(prt); } space++; System.out.println(); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { System.out.print(\" \"); } for (j = 1; j <= i; j++) { System.out.print(prt); } } if ((i % 2) != 0) { System.out.println(); space--; } }}} // This code is contributed by inder_verma..",
"e": 4393,
"s": 2934,
"text": null
},
{
"code": "# Python3 Program to print Kite Patternif __name__ == '__main__': space = 4 prt = '$' for i in range(1, 6): # For printing the space for sp in range(space, 0, -1): print(end = \" \") # For printing the $ for j in range(1, i + 1): print(prt, end = \"\") for k in range(1, i): if (i == 1): continue print(prt, end = \"\") print() space -= 1 space = 1 for i in range(4, 0, -1): for sp in range(space, 0, -1): print(end = \" \") for j in range(1, i + 1): print(prt, end = \"\") for k in range(1, i): print(prt, end = \"\") space += 1 print() space = 3 for i in range(2, 6): if ((i % 2) != 0): for sp in range(space, 0, -1): print(\" \", end = \"\") for j in range(1, i + 1): print(prt, end = \"\") if ((i % 2) != 0): print() space -= 1 # This code is contributed by# mohit kumar 29",
"e": 5503,
"s": 4393,
"text": null
},
{
"code": "// C# Program to print Kite Patternusing System; class GFG{public static void Main(){ int i, j, k, sp, space = 4; char prt = '$'; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { Console.Write(\" \"); } // For printing the $ for (j = 1; j <= i; j++) { Console.Write(prt); } for (k = 1; k <= (i - 1); k++) { if (i == 1) { continue; } Console.Write(prt); } Console.WriteLine(); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { Console.Write(\" \"); } for (j = 1; j <= i; j++) { Console.Write(prt); } for (k = 1; k <= (i - 1); k++) { Console.Write(prt); } space++; Console.WriteLine(); } space = 3; for (i = 2; i <= 5; i++) { if ((i % 2) != 0) { for (sp = space; sp >= 1; sp--) { Console.Write(\" \"); } for (j = 1; j <= i; j++) { Console.Write(prt); } } if ((i % 2) != 0) { Console.WriteLine(); space--; } }}} // This code is contributed by Soumik",
"e": 6911,
"s": 5503,
"text": null
},
{
"code": "<?php// PHP Program to print Kite Pattern $space = 4;$prt = '$'; for ($i = 1; $i <= 5; $i++){ // For printing the space for ($sp = $space; $sp >= 1; $sp--) { echo (\" \"); } // For printing the $ for ($j = 1; $j <= $i; $j++) { echo ( $prt); } for ($k = 1; $k <= ($i - 1); $k++) { if ($i == 1) { continue; } echo ( $prt); }echo (\"\\n\");$space--;} $space = 1; for ($i = 4; $i >= 1; $i--){ for ($sp = $space; $sp >= 1; $sp--) { echo (\" \"); } for ($j = 1; $j <= $i; $j++) { echo ( $prt); } for ($k = 1; $k <= ($i - 1); $k++) { echo ( $prt); } $space++; echo (\"\\n\");} $space = 3; for ($i = 2; $i <= 5; $i++){ if (($i % 2) != 0) { for ($sp = $space; $sp >= 1; $sp--) { echo (\" \"); } for ($j = 1; $j <= $i; $j++) { echo ( $prt); } } if (($i % 2) != 0) { echo (\"\\n\"); $space--; }} // This code is contributed// by Sach_Code?>",
"e": 7971,
"s": 6911,
"text": null
},
{
"code": "<script> // JavaScript Program to print Kite Pattern var i, j, k, sp, space = 4; var prt = \"$\"; for (i = 1; i <= 5; i++) { // For printing the space for (sp = space; sp >= 1; sp--) { document.write(\" \"); } // For printing the $ for (j = 1; j <= i; j++) { document.write(prt); } for (k = 1; k <= i - 1; k++) { if (i == 1) { continue; } document.write(prt); } document.write(\"<br>\"); space--; } space = 1; for (i = 4; i >= 1; i--) { for (sp = space; sp >= 1; sp--) { document.write(\" \"); } for (j = 1; j <= i; j++) { document.write(prt); } for (k = 1; k <= i - 1; k++) { document.write(prt); } space++; document.write(\"<br>\"); } space = 3; for (i = 2; i <= 5; i++) { if (i % 2 != 0) { for (sp = space; sp >= 1; sp--) { document.write(\" \"); } for (j = 1; j <= i; j++) { document.write(prt); } } if (i % 2 != 0) { document.write(\"<br>\"); space--; } } </script>",
"e": 9249,
"s": 7971,
"text": null
},
{
"code": null,
"e": 9334,
"s": 9249,
"text": " $\n $$$\n $$$$$\n $$$$$$$\n$$$$$$$$$\n $$$$$$$\n $$$$$\n $$$\n $\n $$$\n $$$$$"
},
{
"code": null,
"e": 9349,
"s": 9336,
"text": "SoumikMondal"
},
{
"code": null,
"e": 9360,
"s": 9349,
"text": "inderDuMCA"
},
{
"code": null,
"e": 9370,
"s": 9360,
"text": "Sach_Code"
},
{
"code": null,
"e": 9383,
"s": 9370,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9398,
"s": 9383,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9405,
"s": 9398,
"text": "rdtank"
},
{
"code": null,
"e": 9422,
"s": 9405,
"text": "pattern-printing"
},
{
"code": null,
"e": 9433,
"s": 9422,
"text": "C Programs"
},
{
"code": null,
"e": 9446,
"s": 9433,
"text": "C++ Programs"
},
{
"code": null,
"e": 9465,
"s": 9446,
"text": "School Programming"
},
{
"code": null,
"e": 9482,
"s": 9465,
"text": "pattern-printing"
}
] |
Flutter – Handling videos
|
15 Feb, 2021
A video is an important form of media that can be used in the application. In Flutter, videos are handled through the use of video_player plugin. This performs tasks like playing a video, pausing a video, or muting the same. It can be used to play videos from the internet or the videos stored in the assets of the application. In this article, we will explore the same in detail through an example application.
To build a simple app that can play videos using the below steps:
Add the video_player dependency to pubspec.yaml file.
Give the application permissions to access videos.
Add a VideoPlayerController
Display & play the video.
Now, let’s explore these steps in detail.
To add the video_player plugin to the flutter app, open the pubspec.yaml file and add the video_palyer dependency as shown below:
To stream videos from the internet the app will be needing correct set of configuration. Depending upon the OS of the device we can set the permissions as shown below.
For Android devices, the permission to stream videos from the internet can be added by going into the Androidmanifest.xml file at
<project root>/android/app/src/main/AndroidManifest.xml. And add the below lines write after the <application> definition :
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
Defination of the Flutter Application....
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
For iOS devices, the permissions can be given by adding the following to the Info.plist file which is located at <project root>/ios/Runner/Info.plist as shown:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
The VideoPlayerController facilitates the video playback and control of the video. It establishes the connection to the video and prepare the controller for playback. The Controller that we will be creating here will be a StatefulWidget with a state class. We will initialize the controller using the initState method as shown below:
Dart
class VideoPlayerScreen extends StatefulWidget { VideoPlayerScreen({Key key}) : super(key: key); @override _VideoPlayerScreenState createState() => _VideoPlayerScreenState();} class _VideoPlayerScreenState extends State<VideoPlayerScreen> { VideoPlayerController _controller; Future<void> _initializeVideoPlayerFuture; @override void initState() { _controller = VideoPlayerController.network( 'Video_URL', ); _initializeVideoPlayerFuture = _controller.initialize(); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { }}
The VideoPlayer widget from the video_player plugin is used in flutter to display a video. To control the Aspect ratio of the video, we will wrap it inside a AspectRatio Widget. We will also be adding a FloatingActionButton to control the play and pause of the video as shown below:
Dart
FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ); } else { return Center(child: CircularProgressIndicator()); } },)FloatingActionButton( onPressed: () { setState(() { //pause if (_controller.value.isPlaying) { _controller.pause(); } else { // play _controller.play(); } }); }, child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ),)
Complete Source Code:
Dart
import 'dart:async'; import 'package:flutter/material.dart';import 'package:video_player/video_player.dart'; void main() => runApp(VideoPlayerApp()); class VideoPlayerApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', home: VideoPlayerScreen(), ); }} class VideoPlayerScreen extends StatefulWidget { VideoPlayerScreen({Key key}) : super(key: key); @override _VideoPlayerScreenState createState() => _VideoPlayerScreenState();} class _VideoPlayerScreenState extends State<VideoPlayerScreen> { VideoPlayerController _controller; Future<void> _initializeVideoPlayerFuture; @override void initState() { _controller = VideoPlayerController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', ); _initializeVideoPlayerFuture = _controller.initialize(); _controller.setLooping(true); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ); } else { return Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { // pause if (_controller.value.isPlaying) { _controller.pause(); } else { // play _controller.play(); } }); }, // icon child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), ), ); }}
Output:
android
Flutter
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Stack Widget
Dart Tutorial
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Checkbox Widget
Flutter - Stack Widget
Flutter - Search Bar
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 440,
"s": 28,
"text": "A video is an important form of media that can be used in the application. In Flutter, videos are handled through the use of video_player plugin. This performs tasks like playing a video, pausing a video, or muting the same. It can be used to play videos from the internet or the videos stored in the assets of the application. In this article, we will explore the same in detail through an example application."
},
{
"code": null,
"e": 506,
"s": 440,
"text": "To build a simple app that can play videos using the below steps:"
},
{
"code": null,
"e": 560,
"s": 506,
"text": "Add the video_player dependency to pubspec.yaml file."
},
{
"code": null,
"e": 611,
"s": 560,
"text": "Give the application permissions to access videos."
},
{
"code": null,
"e": 639,
"s": 611,
"text": "Add a VideoPlayerController"
},
{
"code": null,
"e": 665,
"s": 639,
"text": "Display & play the video."
},
{
"code": null,
"e": 707,
"s": 665,
"text": "Now, let’s explore these steps in detail."
},
{
"code": null,
"e": 837,
"s": 707,
"text": "To add the video_player plugin to the flutter app, open the pubspec.yaml file and add the video_palyer dependency as shown below:"
},
{
"code": null,
"e": 1005,
"s": 837,
"text": "To stream videos from the internet the app will be needing correct set of configuration. Depending upon the OS of the device we can set the permissions as shown below."
},
{
"code": null,
"e": 1136,
"s": 1005,
"text": "For Android devices, the permission to stream videos from the internet can be added by going into the Androidmanifest.xml file at "
},
{
"code": null,
"e": 1260,
"s": 1136,
"text": "<project root>/android/app/src/main/AndroidManifest.xml. And add the below lines write after the <application> definition :"
},
{
"code": null,
"e": 1493,
"s": 1260,
"text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <application>\n Defination of the Flutter Application....\n </application>\n\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n</manifest>\n"
},
{
"code": null,
"e": 1653,
"s": 1493,
"text": "For iOS devices, the permissions can be given by adding the following to the Info.plist file which is located at <project root>/ios/Runner/Info.plist as shown:"
},
{
"code": null,
"e": 1749,
"s": 1653,
"text": "<key>NSAppTransportSecurity</key>\n<dict>\n <key>NSAllowsArbitraryLoads</key>\n <true/>\n</dict>\n"
},
{
"code": null,
"e": 2083,
"s": 1749,
"text": "The VideoPlayerController facilitates the video playback and control of the video. It establishes the connection to the video and prepare the controller for playback. The Controller that we will be creating here will be a StatefulWidget with a state class. We will initialize the controller using the initState method as shown below:"
},
{
"code": null,
"e": 2088,
"s": 2083,
"text": "Dart"
},
{
"code": "class VideoPlayerScreen extends StatefulWidget { VideoPlayerScreen({Key key}) : super(key: key); @override _VideoPlayerScreenState createState() => _VideoPlayerScreenState();} class _VideoPlayerScreenState extends State<VideoPlayerScreen> { VideoPlayerController _controller; Future<void> _initializeVideoPlayerFuture; @override void initState() { _controller = VideoPlayerController.network( 'Video_URL', ); _initializeVideoPlayerFuture = _controller.initialize(); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { }}",
"e": 2746,
"s": 2088,
"text": null
},
{
"code": null,
"e": 3029,
"s": 2746,
"text": "The VideoPlayer widget from the video_player plugin is used in flutter to display a video. To control the Aspect ratio of the video, we will wrap it inside a AspectRatio Widget. We will also be adding a FloatingActionButton to control the play and pause of the video as shown below:"
},
{
"code": null,
"e": 3034,
"s": 3029,
"text": "Dart"
},
{
"code": "FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ); } else { return Center(child: CircularProgressIndicator()); } },)FloatingActionButton( onPressed: () { setState(() { //pause if (_controller.value.isPlaying) { _controller.pause(); } else { // play _controller.play(); } }); }, child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ),)",
"e": 3675,
"s": 3034,
"text": null
},
{
"code": null,
"e": 3697,
"s": 3675,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 3702,
"s": 3697,
"text": "Dart"
},
{
"code": "import 'dart:async'; import 'package:flutter/material.dart';import 'package:video_player/video_player.dart'; void main() => runApp(VideoPlayerApp()); class VideoPlayerApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', home: VideoPlayerScreen(), ); }} class VideoPlayerScreen extends StatefulWidget { VideoPlayerScreen({Key key}) : super(key: key); @override _VideoPlayerScreenState createState() => _VideoPlayerScreenState();} class _VideoPlayerScreenState extends State<VideoPlayerScreen> { VideoPlayerController _controller; Future<void> _initializeVideoPlayerFuture; @override void initState() { _controller = VideoPlayerController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', ); _initializeVideoPlayerFuture = _controller.initialize(); _controller.setLooping(true); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ); } else { return Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { // pause if (_controller.value.isPlaying) { _controller.pause(); } else { // play _controller.play(); } }); }, // icon child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), ), ); }}",
"e": 5785,
"s": 3702,
"text": null
},
{
"code": null,
"e": 5793,
"s": 5785,
"text": "Output:"
},
{
"code": null,
"e": 5801,
"s": 5793,
"text": "android"
},
{
"code": null,
"e": 5809,
"s": 5801,
"text": "Flutter"
},
{
"code": null,
"e": 5831,
"s": 5809,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 5836,
"s": 5831,
"text": "Dart"
},
{
"code": null,
"e": 5844,
"s": 5836,
"text": "Flutter"
},
{
"code": null,
"e": 5942,
"s": 5844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5981,
"s": 5942,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6007,
"s": 5981,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 6033,
"s": 6007,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 6056,
"s": 6033,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 6070,
"s": 6056,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 6109,
"s": 6070,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6126,
"s": 6109,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 6152,
"s": 6126,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 6175,
"s": 6152,
"text": "Flutter - Stack Widget"
}
] |
scipy.fftfreq() in Python
|
29 Aug, 2020
With the help of scipy.fftfreq() method, we can compute the fast fourier transformation frequency and return the transformed array by using this method.
Syntax : scipy.fftfreq(n, freq)
Return : Return the transformed array.
Example #1 :
In this example we can see that by using scipy.fftfreq() method, we are able to compute the fast fourier transformation frequency and return the transformed array.
Python3
# import scipy and numpyimport scipyimport numpy as np # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(5, 1.096) print(gfg)
Output :
[ 0. 0.18248175 0.3649635 -0.3649635 -0.18248175]
Example #2 :
Python3
# import scipy and numpyimport scipyimport numpy as np # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(3, 2.4096) print(gfg)
Output :
[ 0. 0.13833555 -0.13833555]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "With the help of scipy.fftfreq() method, we can compute the fast fourier transformation frequency and return the transformed array by using this method."
},
{
"code": null,
"e": 213,
"s": 181,
"text": "Syntax : scipy.fftfreq(n, freq)"
},
{
"code": null,
"e": 253,
"s": 213,
"text": "Return : Return the transformed array."
},
{
"code": null,
"e": 266,
"s": 253,
"text": "Example #1 :"
},
{
"code": null,
"e": 430,
"s": 266,
"text": "In this example we can see that by using scipy.fftfreq() method, we are able to compute the fast fourier transformation frequency and return the transformed array."
},
{
"code": null,
"e": 438,
"s": 430,
"text": "Python3"
},
{
"code": "# import scipy and numpyimport scipyimport numpy as np # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(5, 1.096) print(gfg)",
"e": 570,
"s": 438,
"text": null
},
{
"code": null,
"e": 579,
"s": 570,
"text": "Output :"
},
{
"code": null,
"e": 641,
"s": 579,
"text": "[ 0. 0.18248175 0.3649635 -0.3649635 -0.18248175]"
},
{
"code": null,
"e": 654,
"s": 641,
"text": "Example #2 :"
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Python3"
},
{
"code": "# import scipy and numpyimport scipyimport numpy as np # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(3, 2.4096) print(gfg)",
"e": 795,
"s": 662,
"text": null
},
{
"code": null,
"e": 804,
"s": 795,
"text": "Output :"
},
{
"code": null,
"e": 842,
"s": 804,
"text": "[ 0. 0.13833555 -0.13833555]"
},
{
"code": null,
"e": 871,
"s": 842,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 884,
"s": 871,
"text": "Python-scipy"
},
{
"code": null,
"e": 891,
"s": 884,
"text": "Python"
}
] |
Dynamic initialization of object in C++ - GeeksforGeeks
|
31 Dec, 2021
In this article, we will discuss the Dynamic initialization of objects using Dynamic Constructors.
Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time.
It can be achieved by using constructors and by passing parameters to the constructors.
This comes in really handy when there are multiple constructors of the same class with different inputs.
Dynamic Constructor:
The constructor used for allocating the memory at runtime is known as the dynamic constructor.
The memory is allocated at runtime using a new operator and similarly, memory is deallocated at runtime using the delete operator.
Dynamic Allocation:
Approach:
In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap.The objects of the class geek calls the function and it displays the value of dynamically allocated variable i.e ptr.
In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap.
The objects of the class geek calls the function and it displays the value of dynamically allocated variable i.e ptr.
Below is the program for dynamic initialization of object using new operator:
C++
// C++ program for dynamic allocation#include <iostream>using namespace std; class geeks { int* ptr; public: // Default constructor geeks() { // Dynamically initializing ptr // using new ptr = new int; *ptr = 10; } // Function to display the value // of ptr void display() { cout << *ptr << endl; }}; // Driver Codeint main(){ geeks obj1; // Function Call obj1.display(); return 0;}
10
Dynamic Deallocation:Approach:
In the below code, delete is used to dynamically free the memory.The contents of obj1 are overwritten in the object obj2 using assignment operator, then obj1 is deallocated by using delete operator.
In the below code, delete is used to dynamically free the memory.
The contents of obj1 are overwritten in the object obj2 using assignment operator, then obj1 is deallocated by using delete operator.
Below is the code for dynamic deallocation of the memory using delete operator.
C++
// C++ program to dynamically// deallocating the memory#include <iostream>using namespace std; class geeks { int* ptr; public: // Default constructor geeks() { ptr = new int; *ptr = 10; } // Function to display the value void display() { cout << "Value: " << *ptr << endl; }}; // Driver Codeint main(){ // Dynamically allocating memory // using new operator geeks* obj1 = new geeks(); geeks* obj2 = new geeks(); // Assigning obj1 to obj2 obj2 = obj1; // Function Call obj1->display(); obj2->display(); // Dynamically deleting the memory // allocated to obj1 delete obj1; return 0;}
Value: 10
Value: 10
Below C++ program is demonstrating dynamic initialization of objects and calculating bank deposit:
C++
// C++ program to illustrate the dynamic// initialization as memory is allocated// to the object#include <iostream>using namespace std; class bank { int principal; int years; float interest; float returnvalue; public: // Default constructor bank() {} // Parameterized constructor to // calculate interest(float) bank(int p, int y, float i) { principal = p; years = y; interest = i/100; returnvalue = principal; cout << "\nDeposited amount (float):"; // Finding the interest amount for (int i = 0; i < years; i++) { returnvalue = returnvalue * (1 + interest); } } // Parameterized constructor to // calculate interest(integer) bank(int p, int y, int i) { principal = p; years = y; interest = float(i)/100; returnvalue = principal; cout << "\nDeposited amount" << " (integer):"; // Find the interest amount for (int i = 0; i < years; i++) { returnvalue = returnvalue * (1 + interest); } } // Display function void display(void) { cout << returnvalue << endl; }}; // Driver Codeint main(){ // Variable initialization int p = 200; int y = 2; int I = 5; float i = 2.25; // Object is created with // float parameters bank b1(p, y, i); // Function Call with object // of class b1.display(); // Object is created with // integer parameters bank b2(p, y, I); // Function Call with object // of class b2.display(); return 0;}
Output:
Deposited amount (float):209.101
Deposited amount (integer):220.5
mohsink607
chhabradhanvi
C++-Constructors
cpp-constructor
Dynamic Memory Allocation
new and delete
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
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
C++ program for hashing with chaining
|
[
{
"code": null,
"e": 23733,
"s": 23705,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 23832,
"s": 23733,
"text": "In this article, we will discuss the Dynamic initialization of objects using Dynamic Constructors."
},
{
"code": null,
"e": 23980,
"s": 23832,
"text": "Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time."
},
{
"code": null,
"e": 24068,
"s": 23980,
"text": "It can be achieved by using constructors and by passing parameters to the constructors."
},
{
"code": null,
"e": 24173,
"s": 24068,
"text": "This comes in really handy when there are multiple constructors of the same class with different inputs."
},
{
"code": null,
"e": 24194,
"s": 24173,
"text": "Dynamic Constructor:"
},
{
"code": null,
"e": 24289,
"s": 24194,
"text": "The constructor used for allocating the memory at runtime is known as the dynamic constructor."
},
{
"code": null,
"e": 24420,
"s": 24289,
"text": "The memory is allocated at runtime using a new operator and similarly, memory is deallocated at runtime using the delete operator."
},
{
"code": null,
"e": 24441,
"s": 24420,
"text": "Dynamic Allocation: "
},
{
"code": null,
"e": 24451,
"s": 24441,
"text": "Approach:"
},
{
"code": null,
"e": 24701,
"s": 24451,
"text": "In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap.The objects of the class geek calls the function and it displays the value of dynamically allocated variable i.e ptr."
},
{
"code": null,
"e": 24834,
"s": 24701,
"text": "In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap."
},
{
"code": null,
"e": 24952,
"s": 24834,
"text": "The objects of the class geek calls the function and it displays the value of dynamically allocated variable i.e ptr."
},
{
"code": null,
"e": 25030,
"s": 24952,
"text": "Below is the program for dynamic initialization of object using new operator:"
},
{
"code": null,
"e": 25034,
"s": 25030,
"text": "C++"
},
{
"code": "// C++ program for dynamic allocation#include <iostream>using namespace std; class geeks { int* ptr; public: // Default constructor geeks() { // Dynamically initializing ptr // using new ptr = new int; *ptr = 10; } // Function to display the value // of ptr void display() { cout << *ptr << endl; }}; // Driver Codeint main(){ geeks obj1; // Function Call obj1.display(); return 0;}",
"e": 25497,
"s": 25034,
"text": null
},
{
"code": null,
"e": 25500,
"s": 25497,
"text": "10"
},
{
"code": null,
"e": 25531,
"s": 25500,
"text": "Dynamic Deallocation:Approach:"
},
{
"code": null,
"e": 25730,
"s": 25531,
"text": "In the below code, delete is used to dynamically free the memory.The contents of obj1 are overwritten in the object obj2 using assignment operator, then obj1 is deallocated by using delete operator."
},
{
"code": null,
"e": 25796,
"s": 25730,
"text": "In the below code, delete is used to dynamically free the memory."
},
{
"code": null,
"e": 25930,
"s": 25796,
"text": "The contents of obj1 are overwritten in the object obj2 using assignment operator, then obj1 is deallocated by using delete operator."
},
{
"code": null,
"e": 26010,
"s": 25930,
"text": "Below is the code for dynamic deallocation of the memory using delete operator."
},
{
"code": null,
"e": 26014,
"s": 26010,
"text": "C++"
},
{
"code": "// C++ program to dynamically// deallocating the memory#include <iostream>using namespace std; class geeks { int* ptr; public: // Default constructor geeks() { ptr = new int; *ptr = 10; } // Function to display the value void display() { cout << \"Value: \" << *ptr << endl; }}; // Driver Codeint main(){ // Dynamically allocating memory // using new operator geeks* obj1 = new geeks(); geeks* obj2 = new geeks(); // Assigning obj1 to obj2 obj2 = obj1; // Function Call obj1->display(); obj2->display(); // Dynamically deleting the memory // allocated to obj1 delete obj1; return 0;}",
"e": 26700,
"s": 26014,
"text": null
},
{
"code": null,
"e": 26720,
"s": 26700,
"text": "Value: 10\nValue: 10"
},
{
"code": null,
"e": 26819,
"s": 26720,
"text": "Below C++ program is demonstrating dynamic initialization of objects and calculating bank deposit:"
},
{
"code": null,
"e": 26823,
"s": 26819,
"text": "C++"
},
{
"code": "// C++ program to illustrate the dynamic// initialization as memory is allocated// to the object#include <iostream>using namespace std; class bank { int principal; int years; float interest; float returnvalue; public: // Default constructor bank() {} // Parameterized constructor to // calculate interest(float) bank(int p, int y, float i) { principal = p; years = y; interest = i/100; returnvalue = principal; cout << \"\\nDeposited amount (float):\"; // Finding the interest amount for (int i = 0; i < years; i++) { returnvalue = returnvalue * (1 + interest); } } // Parameterized constructor to // calculate interest(integer) bank(int p, int y, int i) { principal = p; years = y; interest = float(i)/100; returnvalue = principal; cout << \"\\nDeposited amount\" << \" (integer):\"; // Find the interest amount for (int i = 0; i < years; i++) { returnvalue = returnvalue * (1 + interest); } } // Display function void display(void) { cout << returnvalue << endl; }}; // Driver Codeint main(){ // Variable initialization int p = 200; int y = 2; int I = 5; float i = 2.25; // Object is created with // float parameters bank b1(p, y, i); // Function Call with object // of class b1.display(); // Object is created with // integer parameters bank b2(p, y, I); // Function Call with object // of class b2.display(); return 0;}",
"e": 28478,
"s": 26823,
"text": null
},
{
"code": null,
"e": 28486,
"s": 28478,
"text": "Output:"
},
{
"code": null,
"e": 28553,
"s": 28486,
"text": "Deposited amount (float):209.101\n\nDeposited amount (integer):220.5"
},
{
"code": null,
"e": 28564,
"s": 28553,
"text": "mohsink607"
},
{
"code": null,
"e": 28578,
"s": 28564,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 28595,
"s": 28578,
"text": "C++-Constructors"
},
{
"code": null,
"e": 28611,
"s": 28595,
"text": "cpp-constructor"
},
{
"code": null,
"e": 28637,
"s": 28611,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 28652,
"s": 28637,
"text": "new and delete"
},
{
"code": null,
"e": 28676,
"s": 28652,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28680,
"s": 28676,
"text": "C++"
},
{
"code": null,
"e": 28693,
"s": 28680,
"text": "C++ Programs"
},
{
"code": null,
"e": 28712,
"s": 28693,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28716,
"s": 28712,
"text": "CPP"
},
{
"code": null,
"e": 28814,
"s": 28716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28823,
"s": 28814,
"text": "Comments"
},
{
"code": null,
"e": 28836,
"s": 28823,
"text": "Old Comments"
},
{
"code": null,
"e": 28864,
"s": 28836,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28888,
"s": 28864,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28908,
"s": 28888,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28941,
"s": 28908,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28985,
"s": 28941,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29020,
"s": 28985,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29079,
"s": 29020,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29105,
"s": 29079,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29149,
"s": 29105,
"text": "Program to print ASCII Value of a character"
}
] |
Set up Opencv with anaconda environment - GeeksforGeeks
|
22 Apr, 2022
If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the major languages that can be used to process images or videos.
– 32- or a 64-bit computer. – For Miniconda—400 MB disk space. – For Anaconda—A minimum 3 GB disk space to download and install. – Windows, macOS or Linux. – Python 2.7, 3.4, 3.5 or 3.6.
– 32- or a 64-bit computer.
– For Miniconda—400 MB disk space.
– For Anaconda—A minimum 3 GB disk space to download and install.
– Windows, macOS or Linux.
– Python 2.7, 3.4, 3.5 or 3.6.
Anaconda is open-source software that contains jupyter, spyder etc that are used for large data processing, data analytics, and heavy scientific computing. Anaconda works for R and python programming languages. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system conda.
Installing Anaconda : Head over to continuum.io/downloads/ and install the latest version of Anaconda. Make sure to install the “Python 3.6 Version” for the appropriate architecture. Install it with the default settings.
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available in multiple programming languages such as Python, C++ etc.
Steps to import OpenCV on anaconda in windows environmentMinimum
Step 1:- Search Anaconda in your taskbar and select ANACONDA NAVIGATOR.
Step 2:- Now you will see a menu with various options like Jupiter notebook , Spyder etc. This is Anaconda Environment. Step 3:- Select Spyder as it is Anaconda’s IDE for python and OpenCV library will work in it only.
Step 1:- After installing the anaconda open the Anaconda Prompt.
Step 2:- Type the given command, press enter, and let it download the whole package.
Command
conda install -c menpo opencv
Step 3:- Now simply import OpenCV in your python program in which you want to use image processing functions.
Examples: Some basic functions of the OpenCV library (These functions are performed on Windows flavor of Anaconda but it will work on linux flavor too)
img = cv2.imread('LOCATION OF THE IMAGE')
The above function imread stores the image at the given location to the variable img.
Converting an image to greyscale
img = cv2.imread('watch.jpg',cv2.IMREAD_GRAYSCALE)
The above function converts the image to grayscale and then stores it in the variable img.
Showing the stored image
cv2.imshow('image',img)
The above function shows the image stored in img variable.
Save an image to a file
cv2.imwrite(filename, img)
The above function stores the image in the file. The image is stored in the variable of type Mat that is in the form of a matrix.
Reading video directly from the webcam
cap = cv2.VideoCapture(0)
Stores live video from your webcam in the variable cap.
Reading a video from local storage
cap = cv2.VideoCapture('LOCATION OF THE VIDEO')
Stores the video located in the given location to the variable.
To check if the video is successfully stored in the variable
cap.isOpened()
cap is the variable that contains the video. The above function returns true if the video is successfully opened else returns false.
Release the stored video after processing is done
cap.release()
The above function releases the video stored in cap.
aligbashi
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
|
[
{
"code": null,
"e": 24116,
"s": 24088,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 24311,
"s": 24116,
"text": "If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the major languages that can be used to process images or videos. "
},
{
"code": null,
"e": 24499,
"s": 24311,
"text": "– 32- or a 64-bit computer. – For Miniconda—400 MB disk space. – For Anaconda—A minimum 3 GB disk space to download and install. – Windows, macOS or Linux. – Python 2.7, 3.4, 3.5 or 3.6. "
},
{
"code": null,
"e": 24528,
"s": 24499,
"text": "– 32- or a 64-bit computer. "
},
{
"code": null,
"e": 24564,
"s": 24528,
"text": "– For Miniconda—400 MB disk space. "
},
{
"code": null,
"e": 24631,
"s": 24564,
"text": "– For Anaconda—A minimum 3 GB disk space to download and install. "
},
{
"code": null,
"e": 24659,
"s": 24631,
"text": "– Windows, macOS or Linux. "
},
{
"code": null,
"e": 24691,
"s": 24659,
"text": "– Python 2.7, 3.4, 3.5 or 3.6. "
},
{
"code": null,
"e": 25066,
"s": 24691,
"text": "Anaconda is open-source software that contains jupyter, spyder etc that are used for large data processing, data analytics, and heavy scientific computing. Anaconda works for R and python programming languages. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system conda."
},
{
"code": null,
"e": 25290,
"s": 25068,
"text": "Installing Anaconda : Head over to continuum.io/downloads/ and install the latest version of Anaconda. Make sure to install the “Python 3.6 Version” for the appropriate architecture. Install it with the default settings. "
},
{
"code": null,
"e": 25660,
"s": 25290,
"text": "OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available in multiple programming languages such as Python, C++ etc. "
},
{
"code": null,
"e": 25727,
"s": 25662,
"text": "Steps to import OpenCV on anaconda in windows environmentMinimum"
},
{
"code": null,
"e": 25799,
"s": 25727,
"text": "Step 1:- Search Anaconda in your taskbar and select ANACONDA NAVIGATOR."
},
{
"code": null,
"e": 26021,
"s": 25801,
"text": "Step 2:- Now you will see a menu with various options like Jupiter notebook , Spyder etc. This is Anaconda Environment. Step 3:- Select Spyder as it is Anaconda’s IDE for python and OpenCV library will work in it only. "
},
{
"code": null,
"e": 26087,
"s": 26021,
"text": "Step 1:- After installing the anaconda open the Anaconda Prompt. "
},
{
"code": null,
"e": 26173,
"s": 26087,
"text": "Step 2:- Type the given command, press enter, and let it download the whole package. "
},
{
"code": null,
"e": 26182,
"s": 26173,
"text": "Command "
},
{
"code": null,
"e": 26212,
"s": 26182,
"text": "conda install -c menpo opencv"
},
{
"code": null,
"e": 26322,
"s": 26212,
"text": "Step 3:- Now simply import OpenCV in your python program in which you want to use image processing functions."
},
{
"code": null,
"e": 26475,
"s": 26322,
"text": "Examples: Some basic functions of the OpenCV library (These functions are performed on Windows flavor of Anaconda but it will work on linux flavor too) "
},
{
"code": null,
"e": 26517,
"s": 26475,
"text": "img = cv2.imread('LOCATION OF THE IMAGE')"
},
{
"code": null,
"e": 26603,
"s": 26517,
"text": "The above function imread stores the image at the given location to the variable img."
},
{
"code": null,
"e": 26637,
"s": 26603,
"text": "Converting an image to greyscale "
},
{
"code": null,
"e": 26688,
"s": 26637,
"text": "img = cv2.imread('watch.jpg',cv2.IMREAD_GRAYSCALE)"
},
{
"code": null,
"e": 26779,
"s": 26688,
"text": "The above function converts the image to grayscale and then stores it in the variable img."
},
{
"code": null,
"e": 26805,
"s": 26779,
"text": "Showing the stored image "
},
{
"code": null,
"e": 26829,
"s": 26805,
"text": "cv2.imshow('image',img)"
},
{
"code": null,
"e": 26888,
"s": 26829,
"text": "The above function shows the image stored in img variable."
},
{
"code": null,
"e": 26913,
"s": 26888,
"text": "Save an image to a file "
},
{
"code": null,
"e": 26940,
"s": 26913,
"text": "cv2.imwrite(filename, img)"
},
{
"code": null,
"e": 27070,
"s": 26940,
"text": "The above function stores the image in the file. The image is stored in the variable of type Mat that is in the form of a matrix."
},
{
"code": null,
"e": 27110,
"s": 27070,
"text": "Reading video directly from the webcam "
},
{
"code": null,
"e": 27136,
"s": 27110,
"text": "cap = cv2.VideoCapture(0)"
},
{
"code": null,
"e": 27192,
"s": 27136,
"text": "Stores live video from your webcam in the variable cap."
},
{
"code": null,
"e": 27228,
"s": 27192,
"text": "Reading a video from local storage "
},
{
"code": null,
"e": 27276,
"s": 27228,
"text": "cap = cv2.VideoCapture('LOCATION OF THE VIDEO')"
},
{
"code": null,
"e": 27340,
"s": 27276,
"text": "Stores the video located in the given location to the variable."
},
{
"code": null,
"e": 27401,
"s": 27340,
"text": "To check if the video is successfully stored in the variable"
},
{
"code": null,
"e": 27416,
"s": 27401,
"text": "cap.isOpened()"
},
{
"code": null,
"e": 27549,
"s": 27416,
"text": "cap is the variable that contains the video. The above function returns true if the video is successfully opened else returns false."
},
{
"code": null,
"e": 27600,
"s": 27549,
"text": "Release the stored video after processing is done "
},
{
"code": null,
"e": 27614,
"s": 27600,
"text": "cap.release()"
},
{
"code": null,
"e": 27667,
"s": 27614,
"text": "The above function releases the video stored in cap."
},
{
"code": null,
"e": 27677,
"s": 27667,
"text": "aligbashi"
},
{
"code": null,
"e": 27684,
"s": 27677,
"text": "Python"
},
{
"code": null,
"e": 27782,
"s": 27684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27791,
"s": 27782,
"text": "Comments"
},
{
"code": null,
"e": 27804,
"s": 27791,
"text": "Old Comments"
},
{
"code": null,
"e": 27822,
"s": 27804,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27844,
"s": 27822,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27876,
"s": 27844,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27918,
"s": 27876,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27944,
"s": 27918,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27969,
"s": 27944,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28006,
"s": 27969,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28062,
"s": 28006,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28091,
"s": 28062,
"text": "*args and **kwargs in Python"
}
] |
Neo4j CQL - Creating a Relationship
|
In Noe4j, a relationship is an element using which we connect two nodes of a graph. These relationships have direction, type, and the form patterns of data. This chapter teaches you how to −
Create relationships
Create a relationship between the existing nodes
Create a relationship with label and properties
We can create a relationship using the CREATE clause. We will specify relationship within the square braces “[ ]” depending on the direction of the relationship it is placed between hyphen “ - ” and arrow “ → ” as shown in the following syntax.
Following is the syntax to create a relationship using the CREATE clause.
CREATE (node1)-[:RelationshipType]->(node2)
First of all, create two nodes Ind and Dhawan in the database, as shown below.
CREATE (Dhawan:player{name: "Shikar Dhawan", YOB: 1985, POB: "Delhi"})
CREATE (Ind:Country {name: "India"})
Now, create a relationship named BATSMAN_OF between these two nodes as −
CREATE (Dhawan)-[r:BATSMAN_OF]->(Ind)
Finally, return both the nodes to see the created relationship.
RETURN Dhawan, Ind
Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
You can also create a relationship between the existing nodes using the MATCH clause.
Following is the syntax to create a relationship using the MATCH clause.
MATCH (a:LabeofNode1), (b:LabeofNode2)
WHERE a.name = "nameofnode1" AND b.name = " nameofnode2"
CREATE (a)-[: Relation]->(b)
RETURN a,b
Following is a sample Cypher Query which creates a relationship using the match clause.
MATCH (a:player), (b:Country) WHERE a.name = "Shikar Dhawan" AND b.name = "India"
CREATE (a)-[r: BATSMAN_OF]->(b)
RETURN a,b
To execute the above query, carry out the following steps.
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
You can create a relationship with label and properties using the CREATE clause.
Following is the syntax to create a relationship with label and properties using the CREATE clause.
CREATE (node1)-[label:Rel_Type {key1:value1, key2:value2, . . . n}]-> (node2)
Following is a sample Cypher Query which creates a relationship with label and properties.
MATCH (a:player), (b:Country) WHERE a.name = "Shikar Dhawan" AND b.name = "India"
CREATE (a)-[r:BATSMAN_OF {Matches:5, Avg:90.75}]->(b)
RETURN a,b
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
In Neo4j, a path is formed using continuous relationships. A path can be created using the create clause.
Following is the syntax to create a path in Neo4j using the CREATE clause.
CREATE p = (Node1 {properties})-[:Relationship_Type]->
(Node2 {properties})[:Relationship_Type]->(Node3 {properties})
RETURN p
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2530,
"s": 2339,
"text": "In Noe4j, a relationship is an element using which we connect two nodes of a graph. These relationships have direction, type, and the form patterns of data. This chapter teaches you how to −"
},
{
"code": null,
"e": 2551,
"s": 2530,
"text": "Create relationships"
},
{
"code": null,
"e": 2600,
"s": 2551,
"text": "Create a relationship between the existing nodes"
},
{
"code": null,
"e": 2648,
"s": 2600,
"text": "Create a relationship with label and properties"
},
{
"code": null,
"e": 2894,
"s": 2648,
"text": "We can create a relationship using the CREATE clause. We will specify relationship within the square braces “[ ]” depending on the direction of the relationship it is placed between hyphen “ - ” and arrow “ → ” as shown in the following syntax."
},
{
"code": null,
"e": 2968,
"s": 2894,
"text": "Following is the syntax to create a relationship using the CREATE clause."
},
{
"code": null,
"e": 3014,
"s": 2968,
"text": "CREATE (node1)-[:RelationshipType]->(node2) \n"
},
{
"code": null,
"e": 3093,
"s": 3014,
"text": "First of all, create two nodes Ind and Dhawan in the database, as shown below."
},
{
"code": null,
"e": 3202,
"s": 3093,
"text": "CREATE (Dhawan:player{name: \"Shikar Dhawan\", YOB: 1985, POB: \"Delhi\"}) \nCREATE (Ind:Country {name: \"India\"})"
},
{
"code": null,
"e": 3275,
"s": 3202,
"text": "Now, create a relationship named BATSMAN_OF between these two nodes as −"
},
{
"code": null,
"e": 3315,
"s": 3275,
"text": "CREATE (Dhawan)-[r:BATSMAN_OF]->(Ind) \n"
},
{
"code": null,
"e": 3379,
"s": 3315,
"text": "Finally, return both the nodes to see the created relationship."
},
{
"code": null,
"e": 3400,
"s": 3379,
"text": "RETURN Dhawan, Ind \n"
},
{
"code": null,
"e": 3544,
"s": 3400,
"text": "Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 3593,
"s": 3544,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 3679,
"s": 3593,
"text": "You can also create a relationship between the existing nodes using the MATCH clause."
},
{
"code": null,
"e": 3752,
"s": 3679,
"text": "Following is the syntax to create a relationship using the MATCH clause."
},
{
"code": null,
"e": 3896,
"s": 3752,
"text": "MATCH (a:LabeofNode1), (b:LabeofNode2) \n WHERE a.name = \"nameofnode1\" AND b.name = \" nameofnode2\" \nCREATE (a)-[: Relation]->(b) \nRETURN a,b \n"
},
{
"code": null,
"e": 3984,
"s": 3896,
"text": "Following is a sample Cypher Query which creates a relationship using the match clause."
},
{
"code": null,
"e": 4112,
"s": 3984,
"text": "MATCH (a:player), (b:Country) WHERE a.name = \"Shikar Dhawan\" AND b.name = \"India\" \nCREATE (a)-[r: BATSMAN_OF]->(b) \nRETURN a,b "
},
{
"code": null,
"e": 4171,
"s": 4112,
"text": "To execute the above query, carry out the following steps."
},
{
"code": null,
"e": 4349,
"s": 4171,
"text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 4502,
"s": 4349,
"text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 4551,
"s": 4502,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 4632,
"s": 4551,
"text": "You can create a relationship with label and properties using the CREATE clause."
},
{
"code": null,
"e": 4732,
"s": 4632,
"text": "Following is the syntax to create a relationship with label and properties using the CREATE clause."
},
{
"code": null,
"e": 4812,
"s": 4732,
"text": "CREATE (node1)-[label:Rel_Type {key1:value1, key2:value2, . . . n}]-> (node2) \n"
},
{
"code": null,
"e": 4903,
"s": 4812,
"text": "Following is a sample Cypher Query which creates a relationship with label and properties."
},
{
"code": null,
"e": 5054,
"s": 4903,
"text": "MATCH (a:player), (b:Country) WHERE a.name = \"Shikar Dhawan\" AND b.name = \"India\" \nCREATE (a)-[r:BATSMAN_OF {Matches:5, Avg:90.75}]->(b) \nRETURN a,b "
},
{
"code": null,
"e": 5114,
"s": 5054,
"text": "To execute the above query, carry out the following steps −"
},
{
"code": null,
"e": 5292,
"s": 5114,
"text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 5445,
"s": 5292,
"text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 5494,
"s": 5445,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 5600,
"s": 5494,
"text": "In Neo4j, a path is formed using continuous relationships. A path can be created using the create clause."
},
{
"code": null,
"e": 5675,
"s": 5600,
"text": "Following is the syntax to create a path in Neo4j using the CREATE clause."
},
{
"code": null,
"e": 5808,
"s": 5675,
"text": "CREATE p = (Node1 {properties})-[:Relationship_Type]->\n (Node2 {properties})[:Relationship_Type]->(Node3 {properties}) \nRETURN p \n"
},
{
"code": null,
"e": 5868,
"s": 5808,
"text": "To execute the above query, carry out the following steps −"
},
{
"code": null,
"e": 6046,
"s": 5868,
"text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 6199,
"s": 6046,
"text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 6248,
"s": 6199,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 6255,
"s": 6248,
"text": " Print"
},
{
"code": null,
"e": 6266,
"s": 6255,
"text": " Add Notes"
}
] |
PHP Indexed Array
|
A comma separated sequence of values only instead of key=>value pairs. Each element in such collection has a unique positional index starting from 0. Hence, it is called Indexed array.
Indexed Array object can be initialized by array() function as well as assignment by putting elements inside square brackets [].
//Indexed array using array() function
$arr=array(val1, val2,val3,..);
//Indexed array using assignment method
$arr=[val1, val2, val3,..];
An element in the array can be of any PHP type. We can access an element from the array by its index with following syntax −
$arr[index];
Use of square brackets for assignment of array is available since PHP 5.4
Following example uses square brackets to create an indexed array
Live Demo
<?php
$arr=[10, "ten",10.0, 1.0E1];
var_dump($arr);
?>
This will produce following result −
array(4) {
[0]=>
int(10)
[1]=>
string(3) "ten"
[2]=>
float(10)
[3]=>
float(10)
}
This Example uses array() function to create indexed array
Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
var_dump($arr);
?>
This will produce following result −
array(4) {
[0]=>
int(10)
[1]=>
string(3) "ten"
[2]=>
float(10)
[3]=>
float(10)
}
We can traverse the array elements using foreach loop as well as for loop as follows −
Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
//using for loop. Use count() function to determine array size.
for ($i=0;$i < count($arr); $i++){
echo $arr[$i] . " ";
}
echo "\n";
//using foreach loop
foreach($arr as $i){
echo $i . " ";
}
?>
This will produce following result −
10 ten 10 10
10 ten 10 10
This Example shows modify value at certain index using square brackets. To add new element, keep square brackets empty so that next available integer is used as index
Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
//modify existing element using index
$arr[3]="Hello";
//add new element using next index
$arr[]=100;
for ($i=0; $i< count($arr); $i++){
echo $arr[$i];
}
?>
This will produce following result −
10 ten 10 Hello 100
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "A comma separated sequence of values only instead of key=>value pairs. Each element in such collection has a unique positional index starting from 0. Hence, it is called Indexed array."
},
{
"code": null,
"e": 1376,
"s": 1247,
"text": "Indexed Array object can be initialized by array() function as well as assignment by putting elements inside square brackets []."
},
{
"code": null,
"e": 1515,
"s": 1376,
"text": "//Indexed array using array() function\n$arr=array(val1, val2,val3,..);\n//Indexed array using assignment method\n$arr=[val1, val2, val3,..];"
},
{
"code": null,
"e": 1640,
"s": 1515,
"text": "An element in the array can be of any PHP type. We can access an element from the array by its index with following syntax −"
},
{
"code": null,
"e": 1653,
"s": 1640,
"text": "$arr[index];"
},
{
"code": null,
"e": 1727,
"s": 1653,
"text": "Use of square brackets for assignment of array is available since PHP 5.4"
},
{
"code": null,
"e": 1793,
"s": 1727,
"text": "Following example uses square brackets to create an indexed array"
},
{
"code": null,
"e": 1804,
"s": 1793,
"text": " Live Demo"
},
{
"code": null,
"e": 1859,
"s": 1804,
"text": "<?php\n$arr=[10, \"ten\",10.0, 1.0E1];\nvar_dump($arr);\n?>"
},
{
"code": null,
"e": 1896,
"s": 1859,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2001,
"s": 1896,
"text": "array(4) {\n [0]=>\n int(10)\n [1]=>\n string(3) \"ten\"\n [2]=>\n float(10)\n [3]=>\n float(10)\n}"
},
{
"code": null,
"e": 2060,
"s": 2001,
"text": "This Example uses array() function to create indexed array"
},
{
"code": null,
"e": 2071,
"s": 2060,
"text": " Live Demo"
},
{
"code": null,
"e": 2131,
"s": 2071,
"text": "<?php\n$arr=array(10, \"ten\",10.0, 1.0E1);\nvar_dump($arr);\n?>"
},
{
"code": null,
"e": 2168,
"s": 2131,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2273,
"s": 2168,
"text": "array(4) {\n [0]=>\n int(10)\n [1]=>\n string(3) \"ten\"\n [2]=>\n float(10)\n [3]=>\n float(10)\n}"
},
{
"code": null,
"e": 2360,
"s": 2273,
"text": "We can traverse the array elements using foreach loop as well as for loop as follows −"
},
{
"code": null,
"e": 2371,
"s": 2360,
"text": " Live Demo"
},
{
"code": null,
"e": 2613,
"s": 2371,
"text": "<?php\n$arr=array(10, \"ten\",10.0, 1.0E1);\n//using for loop. Use count() function to determine array size.\nfor ($i=0;$i < count($arr); $i++){\n echo $arr[$i] . \" \";\n}\necho \"\\n\";\n//using foreach loop\nforeach($arr as $i){\n echo $i . \" \";\n}\n?>"
},
{
"code": null,
"e": 2650,
"s": 2613,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2676,
"s": 2650,
"text": "10 ten 10 10\n10 ten 10 10"
},
{
"code": null,
"e": 2843,
"s": 2676,
"text": "This Example shows modify value at certain index using square brackets. To add new element, keep square brackets empty so that next available integer is used as index"
},
{
"code": null,
"e": 2854,
"s": 2843,
"text": " Live Demo"
},
{
"code": null,
"e": 3055,
"s": 2854,
"text": "<?php\n$arr=array(10, \"ten\",10.0, 1.0E1);\n//modify existing element using index\n$arr[3]=\"Hello\";\n//add new element using next index\n$arr[]=100;\nfor ($i=0; $i< count($arr); $i++){\n echo $arr[$i];\n}\n?>"
},
{
"code": null,
"e": 3092,
"s": 3055,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3112,
"s": 3092,
"text": "10 ten 10 Hello 100"
}
] |
How to get a string from a tkinter filedialog in Python 3?
|
To interact with the filesystem in a tkinter application, you can use the Tkinter filedialog module. It provides a way to deal with the files in the system. The filedialog module offers many built-in functions to help developers create a variety of file dialogs for the application. You can use any of the filedialog functions in order to implement a dialog in your application.
The most commonly used function is filedialog.askopenfilename() which generally creates a dialog asking the user to open a file in the given program interface.
Suppose we want to get a string or the filename which we open using the filedialog function. We can use the Label widget to display the filename we will open using the function. The following application can be used to open any type of file.
# Import required libraries
from tkinter import *
from tkinter import filedialog
# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")
# Create a dialog using filedialog function
win.filename=filedialog.askopenfilename(initialdir="C:/", title="Select a file")
# Create a label widget
label=Label(win, text="The File you have selected is: " + win.filename, font='Courier 11 bold')
label.pack()
win.mainloop()
Running the above code will display a dialog asking the user to select a file from the C Drive.
Upon selecting a file, it will display the filepath on the window.
|
[
{
"code": null,
"e": 1441,
"s": 1062,
"text": "To interact with the filesystem in a tkinter application, you can use the Tkinter filedialog module. It provides a way to deal with the files in the system. The filedialog module offers many built-in functions to help developers create a variety of file dialogs for the application. You can use any of the filedialog functions in order to implement a dialog in your application."
},
{
"code": null,
"e": 1601,
"s": 1441,
"text": "The most commonly used function is filedialog.askopenfilename() which generally creates a dialog asking the user to open a file in the given program interface."
},
{
"code": null,
"e": 1843,
"s": 1601,
"text": "Suppose we want to get a string or the filename which we open using the filedialog function. We can use the Label widget to display the filename we will open using the function. The following application can be used to open any type of file."
},
{
"code": null,
"e": 2275,
"s": 1843,
"text": "# Import required libraries\nfrom tkinter import *\nfrom tkinter import filedialog\n\n# Create an instance of tkinter window\nwin = Tk()\nwin.geometry(\"700x300\")\n\n# Create a dialog using filedialog function\nwin.filename=filedialog.askopenfilename(initialdir=\"C:/\", title=\"Select a file\")\n\n# Create a label widget\nlabel=Label(win, text=\"The File you have selected is: \" + win.filename, font='Courier 11 bold')\nlabel.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2371,
"s": 2275,
"text": "Running the above code will display a dialog asking the user to select a file from the C Drive."
},
{
"code": null,
"e": 2438,
"s": 2371,
"text": "Upon selecting a file, it will display the filepath on the window."
}
] |
Apex - Database Methods
|
Database class methods is another way of working with DML statements which are more flexible than DML Statements like insert, update, etc.
Inserting new records via database methods is also quite simple and flexible. Let us consider the previous scenario wherein, we have inserted new records using the DML statements. We will be inserting the same using Database methods.
// Insert Operation Using Database methods
// Insert Customer Records First using simple DML Statement. This Customer Record will be
// used when we will create Invoice Records
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';
insert objCust; // Inserting the Customer Records
// Insert Operation Using Database methods
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
List<apex_invoice__c> InvoiceListToInsert = new List<apex_invoice__c>();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Customer__c = objCust.id;
objNewInvoice.APEX_Amount_Paid__c = 1000;
InvoiceListToInsert.add(objNewInvoice);
Database.SaveResult[] srList = Database.insert(InvoiceListToInsert, false);
// Database method to insert the records in List
// Iterate through each returned result by the method
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition will be executed for successful records and will fetch the ids
// of successful records
System.debug('Successfully inserted Invoice. Invoice ID: ' + sr.getId());
// Get the invoice id of inserted Account
} else {
// This condition will be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');
// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are affected by the error:'
+ objErr.getFields());
}
}
}
Let us now consider our business case example using the database methods. Suppose we need to update the status field of Invoice object but at the same time, we also require information like status of records, failed record ids, success count, etc. This is not possible by using DML Statements, hence we must use Database methods to get the status of our operation.
We will be updating the Invoice's 'Status' field if it is in status 'Pending' and date of creation is today.
The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code.
// Code to update the records using the Database methods
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
// fetch the invoice created today
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice); //Adding records to the list
}
}
Database.SaveResult[] srList = Database.update(updatedInvoiceList, false);
// Database method to update the records in List
// Iterate through each returned result by the method
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition will be executed for successful records and will fetch
// the ids of successful records
System.debug('Successfully updated Invoice. Invoice ID is : ' + sr.getId());
} else {
// This condition will be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');
// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are affected by the error:'
+ objErr.getFields());
}
}
}
We will be looking at only the Insert and Update operations in this tutorial. The other operations are quite similar to these operations and what we did in the last chapter.
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2191,
"s": 2052,
"text": "Database class methods is another way of working with DML statements which are more flexible than DML Statements like insert, update, etc."
},
{
"code": null,
"e": 2425,
"s": 2191,
"text": "Inserting new records via database methods is also quite simple and flexible. Let us consider the previous scenario wherein, we have inserted new records using the DML statements. We will be inserting the same using Database methods."
},
{
"code": null,
"e": 4006,
"s": 2425,
"text": "// Insert Operation Using Database methods\n// Insert Customer Records First using simple DML Statement. This Customer Record will be\n// used when we will create Invoice Records\nAPEX_Customer__c objCust = new APEX_Customer__C();\nobjCust.Name = 'Test';\ninsert objCust; // Inserting the Customer Records\n\n// Insert Operation Using Database methods\nAPEX_Invoice__c objNewInvoice = new APEX_Invoice__c();\nList<apex_invoice__c> InvoiceListToInsert = new List<apex_invoice__c>();\nobjNewInvoice.APEX_Status__c = 'Pending';\nobjNewInvoice.APEX_Customer__c = objCust.id;\nobjNewInvoice.APEX_Amount_Paid__c = 1000;\nInvoiceListToInsert.add(objNewInvoice);\nDatabase.SaveResult[] srList = Database.insert(InvoiceListToInsert, false);\n\n// Database method to insert the records in List\n// Iterate through each returned result by the method\n\nfor (Database.SaveResult sr : srList) {\n if (sr.isSuccess()) {\n // This condition will be executed for successful records and will fetch the ids \n // of successful records\n System.debug('Successfully inserted Invoice. Invoice ID: ' + sr.getId());\n // Get the invoice id of inserted Account\n } else {\n // This condition will be executed for failed records\n for(Database.Error objErr : sr.getErrors()) {\n System.debug('The following error has occurred.');\n \n // Printing error message in Debug log\n System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());\n System.debug('Invoice oject field which are affected by the error:' \n + objErr.getFields());\n }\n }\n}"
},
{
"code": null,
"e": 4371,
"s": 4006,
"text": "Let us now consider our business case example using the database methods. Suppose we need to update the status field of Invoice object but at the same time, we also require information like status of records, failed record ids, success count, etc. This is not possible by using DML Statements, hence we must use Database methods to get the status of our operation."
},
{
"code": null,
"e": 4480,
"s": 4371,
"text": "We will be updating the Invoice's 'Status' field if it is in status 'Pending' and date of creation is today."
},
{
"code": null,
"e": 4636,
"s": 4480,
"text": "The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code."
},
{
"code": null,
"e": 6047,
"s": 4636,
"text": "// Code to update the records using the Database methods\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\n createdDate FROM APEX_Invoice__c WHERE createdDate = today];\n\n// fetch the invoice created today\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\nfor (APEX_Invoice__c objInvoice: invoiceList) {\n if (objInvoice.APEX_Status__c == 'Pending') {\n objInvoice.APEX_Status__c = 'Paid';\n updatedInvoiceList.add(objInvoice); //Adding records to the list\n }\n}\n\nDatabase.SaveResult[] srList = Database.update(updatedInvoiceList, false);\n// Database method to update the records in List\n\n// Iterate through each returned result by the method\nfor (Database.SaveResult sr : srList) {\n if (sr.isSuccess()) {\n // This condition will be executed for successful records and will fetch\n // the ids of successful records\n System.debug('Successfully updated Invoice. Invoice ID is : ' + sr.getId());\n } else {\n // This condition will be executed for failed records\n for(Database.Error objErr : sr.getErrors()) {\n System.debug('The following error has occurred.');\n \n // Printing error message in Debug log\n System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());\n System.debug('Invoice oject field which are affected by the error:' \n + objErr.getFields());\n }\n }\n}"
},
{
"code": null,
"e": 6221,
"s": 6047,
"text": "We will be looking at only the Insert and Update operations in this tutorial. The other operations are quite similar to these operations and what we did in the last chapter."
},
{
"code": null,
"e": 6254,
"s": 6221,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6267,
"s": 6254,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 6299,
"s": 6267,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6307,
"s": 6299,
"text": " Uplatz"
},
{
"code": null,
"e": 6340,
"s": 6307,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6365,
"s": 6340,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 6398,
"s": 6365,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6413,
"s": 6398,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 6446,
"s": 6413,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6459,
"s": 6446,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 6494,
"s": 6459,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6506,
"s": 6494,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6513,
"s": 6506,
"text": " Print"
},
{
"code": null,
"e": 6524,
"s": 6513,
"text": " Add Notes"
}
] |
Hashing by Multiplication in Data Structure
|
Here we will discuss about the hashing with multiplication method. For this we use the hash function −
h(x) = ⌊mxA⌋ mod m
Here A is a real-valued constant. The advantage of this method is that the value of m is not so critical. We can take m as power of 2 also. Although any value of A gives the hash function, but some values of A are better than others.
According to Knuth, we can use the golden ratio for A, So A will be
A=5−12=0.61803398
Of course, no matter what value is chosen for A. The pigeonhole principle implies that if u ≥ nm, then there will be one hash value i and some S ⊆ U of size n, such that h(x) = i for all x in S.
So we can say that the worst case hashing by multiplication is as bad as hashing by division.
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Here we will discuss about the hashing with multiplication method. For this we use the hash function −"
},
{
"code": null,
"e": 1184,
"s": 1165,
"text": "h(x) = ⌊mxA⌋ mod m"
},
{
"code": null,
"e": 1418,
"s": 1184,
"text": "Here A is a real-valued constant. The advantage of this method is that the value of m is not so critical. We can take m as power of 2 also. Although any value of A gives the hash function, but some values of A are better than others."
},
{
"code": null,
"e": 1486,
"s": 1418,
"text": "According to Knuth, we can use the golden ratio for A, So A will be"
},
{
"code": null,
"e": 1504,
"s": 1486,
"text": "A=5−12=0.61803398"
},
{
"code": null,
"e": 1699,
"s": 1504,
"text": "Of course, no matter what value is chosen for A. The pigeonhole principle implies that if u ≥ nm, then there will be one hash value i and some S ⊆ U of size n, such that h(x) = i for all x in S."
},
{
"code": null,
"e": 1793,
"s": 1699,
"text": "So we can say that the worst case hashing by multiplication is as bad as hashing by division."
}
] |
Program to find HCF (Highest Common Factor) of 2 Numbers - GeeksforGeeks
|
06 Oct, 2021
HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them.
For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.
A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in both numbers. Finally return product of elements in the intersection.
An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find GCD of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver program to test above functionint main(){ int a = 0, b = 56; cout << "GCD of " << a << " and " << b << " is " << gcd(a, b); return 0;} // This code is contributed by shivanisinghss2110
// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver program to test above functionint main(){ int a = 0, b = 56; printf("GCD of %d and %d is %d ", a, b, gcd(a, b)); return 0;}
// Java program to find GCD of two numbersclass Test { // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println("GCD of " + a + " and " + b + " is " + gcd(a, b)); }}
# Recursive function to return gcd of a and bdef gcd(a, b): # Everything divides 0 if(a == 0 and b == 0): return 0 if(a == 0): return b if(b == 0): return a # base case if(a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza
// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine("GCD of " + a + " and " + b + " is " + gcd(a, b)); }} // This code is contributed by anuj_67.
<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($a==0 && $b==0) return 0 ; if($a == 0) return $b; if($b == 0) return $a; // base case if($a == $b) return $a ; // a is greater if($a > $b) return gcd( $a-$b , $b ) ; return gcd( $a , $b-$a ) ;} // Driver code$a = 98 ;$b = 56 ; echo "GCD of $a and $b is ", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>
<script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver codevar a = 98, b = 56; document.write("GCD of " + a + " and " + b + " is " + gcd(a, b)); // This code is contributed by noob2000 </script>
Output:
GCD of 98 and 56 is 14
A more efficient solution is to use modulo operator in Euclidean algorithm .
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find GCD of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<"GCD of " <<a << " and "<< b << " is " << gcd(a, b); return 0;} // This code is contributed by shivanisinghss2110
// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf("GCD of %d and %d is %d ", a, b, gcd(a, b)); return 0;}
// Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); }}
# Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza
// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} // This code is contributed by anuj_67.
<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($b==0) return $a ; return gcd( $b , $a % $b ) ;} // Driver code$a = 98 ;$b = 56 ; echo "GCD of $a and $b is ", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>
<script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} // Driver codevar a = 98, b = 56; document.write("GCD of " + a +" and " + b + " is " + gcd(a, b)); // This code is contributed by Ankita saini </script>
Output:
GCD of 98 and 56 is 14
Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vigneshbabuvenkatesh
ht50159
noob2000
ankita_saini
shivanisinghss2110
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to add two binary strings
Program to convert a given number to words
Modular multiplicative inverse
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24427,
"s": 24301,
"text": "HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them. "
},
{
"code": null,
"e": 24489,
"s": 24427,
"text": "For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14."
},
{
"code": null,
"e": 24672,
"s": 24489,
"text": "A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in both numbers. Finally return product of elements in the intersection."
},
{
"code": null,
"e": 24877,
"s": 24672,
"text": "An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number. "
},
{
"code": null,
"e": 24881,
"s": 24877,
"text": "C++"
},
{
"code": null,
"e": 24883,
"s": 24881,
"text": "C"
},
{
"code": null,
"e": 24888,
"s": 24883,
"text": "Java"
},
{
"code": null,
"e": 24896,
"s": 24888,
"text": "Python3"
},
{
"code": null,
"e": 24899,
"s": 24896,
"text": "C#"
},
{
"code": null,
"e": 24903,
"s": 24899,
"text": "PHP"
},
{
"code": null,
"e": 24914,
"s": 24903,
"text": "Javascript"
},
{
"code": "// C++ program to find GCD of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver program to test above functionint main(){ int a = 0, b = 56; cout << \"GCD of \" << a << \" and \" << b << \" is \" << gcd(a, b); return 0;} // This code is contributed by shivanisinghss2110",
"e": 25543,
"s": 24914,
"text": null
},
{
"code": "// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver program to test above functionint main(){ int a = 0, b = 56; printf(\"GCD of %d and %d is %d \", a, b, gcd(a, b)); return 0;}",
"e": 26084,
"s": 25543,
"text": null
},
{
"code": "// Java program to find GCD of two numbersclass Test { // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println(\"GCD of \" + a + \" and \" + b + \" is \" + gcd(a, b)); }}",
"e": 26761,
"s": 26084,
"text": null
},
{
"code": "# Recursive function to return gcd of a and bdef gcd(a, b): # Everything divides 0 if(a == 0 and b == 0): return 0 if(a == 0): return b if(b == 0): return a # base case if(a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza",
"e": 27281,
"s": 26761,
"text": null
},
{
"code": "// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine(\"GCD of \" + a + \" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by anuj_67.",
"e": 28005,
"s": 27281,
"text": null
},
{
"code": "<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($a==0 && $b==0) return 0 ; if($a == 0) return $b; if($b == 0) return $a; // base case if($a == $b) return $a ; // a is greater if($a > $b) return gcd( $a-$b , $b ) ; return gcd( $a , $b-$a ) ;} // Driver code$a = 98 ;$b = 56 ; echo \"GCD of $a and $b is \", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>",
"e": 28545,
"s": 28005,
"text": null
},
{
"code": "<script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 && b == 0) return 0; if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Driver codevar a = 98, b = 56; document.write(\"GCD of \" + a + \" and \" + b + \" is \" + gcd(a, b)); // This code is contributed by noob2000 </script>",
"e": 29140,
"s": 28545,
"text": null
},
{
"code": null,
"e": 29149,
"s": 29140,
"text": "Output: "
},
{
"code": null,
"e": 29172,
"s": 29149,
"text": "GCD of 98 and 56 is 14"
},
{
"code": null,
"e": 29250,
"s": 29172,
"text": "A more efficient solution is to use modulo operator in Euclidean algorithm . "
},
{
"code": null,
"e": 29254,
"s": 29250,
"text": "C++"
},
{
"code": null,
"e": 29256,
"s": 29254,
"text": "C"
},
{
"code": null,
"e": 29261,
"s": 29256,
"text": "Java"
},
{
"code": null,
"e": 29269,
"s": 29261,
"text": "Python3"
},
{
"code": null,
"e": 29272,
"s": 29269,
"text": "C#"
},
{
"code": null,
"e": 29276,
"s": 29272,
"text": "PHP"
},
{
"code": null,
"e": 29287,
"s": 29276,
"text": "Javascript"
},
{
"code": "// C++ program to find GCD of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<\"GCD of \" <<a << \" and \"<< b << \" is \" << gcd(a, b); return 0;} // This code is contributed by shivanisinghss2110",
"e": 29696,
"s": 29287,
"text": null
},
{
"code": "// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf(\"GCD of %d and %d is %d \", a, b, gcd(a, b)); return 0;}",
"e": 30025,
"s": 29696,
"text": null
},
{
"code": "// Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }}",
"e": 30447,
"s": 30025,
"text": null
},
{
"code": "# Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza",
"e": 30776,
"s": 30447,
"text": null
},
{
"code": "// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by anuj_67.",
"e": 31254,
"s": 30776,
"text": null
},
{
"code": "<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($b==0) return $a ; return gcd( $b , $a % $b ) ;} // Driver code$a = 98 ;$b = 56 ; echo \"GCD of $a and $b is \", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>",
"e": 31591,
"s": 31254,
"text": null
},
{
"code": "<script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} // Driver codevar a = 98, b = 56; document.write(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); // This code is contributed by Ankita saini </script>",
"e": 31959,
"s": 31591,
"text": null
},
{
"code": null,
"e": 31968,
"s": 31959,
"text": "Output: "
},
{
"code": null,
"e": 31991,
"s": 31968,
"text": "GCD of 98 and 56 is 14"
},
{
"code": null,
"e": 32206,
"s": 31991,
"text": "Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 32227,
"s": 32206,
"text": "vigneshbabuvenkatesh"
},
{
"code": null,
"e": 32235,
"s": 32227,
"text": "ht50159"
},
{
"code": null,
"e": 32244,
"s": 32235,
"text": "noob2000"
},
{
"code": null,
"e": 32257,
"s": 32244,
"text": "ankita_saini"
},
{
"code": null,
"e": 32276,
"s": 32257,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 32284,
"s": 32276,
"text": "GCD-LCM"
},
{
"code": null,
"e": 32297,
"s": 32284,
"text": "Mathematical"
},
{
"code": null,
"e": 32310,
"s": 32297,
"text": "Mathematical"
},
{
"code": null,
"e": 32408,
"s": 32310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32417,
"s": 32408,
"text": "Comments"
},
{
"code": null,
"e": 32430,
"s": 32417,
"text": "Old Comments"
},
{
"code": null,
"e": 32475,
"s": 32430,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 32507,
"s": 32475,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 32551,
"s": 32507,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32576,
"s": 32551,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32609,
"s": 32576,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32644,
"s": 32609,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 32695,
"s": 32644,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 32729,
"s": 32695,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 32772,
"s": 32729,
"text": "Program to convert a given number to words"
}
] |
How to drop table in Android sqlite?
|
Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc.
This example demonstrates How to drop table in Android sqlite.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<EditText
android:id = "@+id/salary"
android:layout_width = "match_parent"
android:inputType = "numberDecimal"
android:hint = "Enter Salary"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite database.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button save;
EditText name, salary;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.insert(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
}
}
Step 4 − Add the following code to src/ DatabaseHelper.java
package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "salaryDatabase3";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(
"create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text )"
);
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", s);
contentValues.put("salary", s1);
db.insert(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
}
To drop use the following code –
db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
Click here to download the project code
|
[
{
"code": null,
"e": 1457,
"s": 1062,
"text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc."
},
{
"code": null,
"e": 1520,
"s": 1457,
"text": "This example demonstrates How to drop table in Android sqlite."
},
{
"code": null,
"e": 1649,
"s": 1520,
"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": 1714,
"s": 1649,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2603,
"s": 1714,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <EditText\n android:id = \"@+id/salary\"\n android:layout_width = \"match_parent\"\n android:inputType = \"numberDecimal\"\n android:hint = \"Enter Salary\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2742,
"s": 2603,
"text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite database."
},
{
"code": null,
"e": 2799,
"s": 2742,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4134,
"s": 2799,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Button save;\n EditText name, salary;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 4194,
"s": 4134,
"text": "Step 4 − Add the following code to src/ DatabaseHelper.java"
},
{
"code": null,
"e": 5634,
"s": 4194,
"text": "package com.example.andy.myapplication;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport java.io.IOException;\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase3\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary text )\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.insert(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n}"
},
{
"code": null,
"e": 5667,
"s": 5634,
"text": "To drop use the following code –"
},
{
"code": null,
"e": 5724,
"s": 5667,
"text": "db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);"
},
{
"code": null,
"e": 5764,
"s": 5724,
"text": "Click here to download the project code"
}
] |
Auto-Sklearn: An AutoML tool based on Bayesian Optimization | by Fernando López | Towards Data Science
|
There is a plenty of alternatives when trying to find the right ML model as well as the right set of hyperparamters, which one is the best option? maybe there is not a unique answer. This time we are going to talk about Auto-Sklearn, the AutoML tool which implements Bayesian Optimization for searching of the optimal pipeline configuration as well as Ensemble Selection for the choosing of the right model. So, this blog will be divided as follows:
What is Auto-Sklearn?
Auto-Sklearn in practice
Auto-Sklearn is an open-source project developed by Matthias Feurer, et al. [1] and made public in 2015 in their paper: “Efficient and Robust Automated Machine Learning”. As an AutoML tool, Auto-Sklearn tries to provide the optimal pipeline for a given dataset, specifically by covering: data transformation, model selection and hyperparameter optimization tasks. Auto-Sklearn is a tool that is mainly made up of scikit-learn models, specifically it is composed of 15 classifiers, 14 preprocessing methods, and 4 data preprocessing methods.
Finding the optimal pipeline is a complex task due to the diversity of models and parameters that must be considered. The “optimal pipeline” can be obtained through exhaustive techniques such as Grid Search, however it is not a suitable solution because the space search is determined by fixed values. Likewise, it has been proposed another techniques based on sophisticated optimization algorithms such as TPOT which aims to find the optimal pipeline configuration through Genetic Algorithms [2] which can find the “optimal pipeline” in a considerable time however, for datasets with specific characteristics, optimization can take even days. In contrast, Auto-Sklearn implements Bayesian Optimization for the searching of the optimal pipeline which can be thought as a slow technique which Auto-Sklearn solves in proper manner.
The Auto-Sklearn architecture is composed of 3 phases: meta-learning, bayesian optimization, ensemble selection. The key idea of the meta-learning phase is to reduce the space search by learning from models that performed well on similar datasets. Right after, the bayesian optimization phase takes the space search created in the meta-learning step and creates bayesian models for finding the optimal pipeline configuration. Finally, an ensemble selection model is created by reusing the most accurate models found in the bayesian optimization step. In Figure 2 it’s described the Auto-Sklearn architecture.
Auto-Sklearn is a robust tool that integrates 3 stages for the search for the optimal pipeline. However, it is important to mention that both phase 1 (meta-learninig) and phase 3 (ensemble selection) can be configured according to different needs, we will see this in detail in the next section.
Great, so far we already know what Auto-Sklearn is, what its components are and how it works, now let’s see how we do this in practice, let’s go for it!
The idea of the following example is to show the usability of the autosklearn library as well as some configurations to manipulate phase 1 (meta-learning) and phase 3 (ensemble selection). For this example, we are going to make use of the “breast cancer” toy dataset.
So first we are going to import some libraries and split the dataset into train and test:
As you can notice, we are importing the extension AutoSklearnClassifier since this is a classification problem. Then, we only need to instantiate the classifier and we will be able to train the model, pretty easy right?
Since we are not passing any argument to the classifier, AutoSklearn uses the default parameters, which is not a good practice. As was mentioned in the previous section, AutoSklearn allows us to manipulate the meta-learning step as well as the ensemble selection.
In order to manipulate the number of instances obtained from the meta-learning step, we need to provide a value to the parameter:
initial_configurations_via_meta_learning : int (default=25)
As we can observe the default value is 25, it means that it will take 25 configurations to be implemented as the starting point in the bayesian optimization step. If you don’t want to take any configuration as starting point (i.e. if you want to start the optimization from scratch), you can set this value equals to zero.
On the other hand, if you want to manipulate the number of models to be considered in the Ensemble Selection, you only need to modify this parameter:
ensemble_size : int (default=50)
As we can observe, the default number of models to be added to the ensemble is 50 (which is a large number, at least for small datasets), you can try different values in order to find the optimal according to your needs (remember that ensemble learning is a good technique for improving the accuracy, however there is a risk of overfitting the model).
So, if we didn’t want to use any configuration as starting point (meta-learning) and only use one model in the ensemble, the initialization will looks like:
Now let’s talk about “time limits”. AutoSklearn provides a set of parameters to control the time to be used for the entire optimization as well as to control the time used for each model evaluation. These flags are:
# Time limit for the entire optimizationtime_left_for_this_task: int (default=3600)# Time limit for each model evaluationper_run_time_limit: int (1/10 of time_left_for_this_task)
If you dataset is small, maybe you should consider to decrease these flags, otherwise the optimization process may take a while. So, say we want to set 300 seconds as the time limit for the entire optimization and only 30 per each model evaluation, the class initialization will looks like:
Finally for testing it is quite simple, exactly as you do with sklearn models:
$ model.score(x_train, y_train)0.960093896713615$ model.score(x_test, y_test)0.965034965034965
If you want to see a summary, you only need to type:
$ print(model.sprint_statistics())auto-sklearn results: Dataset name: ff54bc0cfe4c3dc32e4cbba909d41e5a Metric: accuracy Best validation score: 0.964539 Number of target algorithm runs: 62 Number of successful target algorithm runs: 55 Number of crashed target algorithm runs: 4 Number of target algorithms that exceeded the time limit: 3 Number of target algorithms that exceeded the memory limit: 0
If you want to learn more about the AutoSklearn parameters, it will be worth to take a look a the documentation: https://automl.github.io/auto-sklearn/master/api.html
From my side, that is it!
In this blog we have seen what Auto-Sklearn is, what its components, how it works and a practical example.
In my opinion, Auto-Sklearn works as one more alternative to find the optimal configuration of your pipeline considering the risks that this entails, that is, it is necessary to provide a set of adequate parameters to avoid exploiting the computational time or overfitting the model. If you are working with serious datasets, you can consider these kind of tools as a baseline.
Thank you so much for reading, see you next time!
|
[
{
"code": null,
"e": 622,
"s": 172,
"text": "There is a plenty of alternatives when trying to find the right ML model as well as the right set of hyperparamters, which one is the best option? maybe there is not a unique answer. This time we are going to talk about Auto-Sklearn, the AutoML tool which implements Bayesian Optimization for searching of the optimal pipeline configuration as well as Ensemble Selection for the choosing of the right model. So, this blog will be divided as follows:"
},
{
"code": null,
"e": 644,
"s": 622,
"text": "What is Auto-Sklearn?"
},
{
"code": null,
"e": 669,
"s": 644,
"text": "Auto-Sklearn in practice"
},
{
"code": null,
"e": 1210,
"s": 669,
"text": "Auto-Sklearn is an open-source project developed by Matthias Feurer, et al. [1] and made public in 2015 in their paper: “Efficient and Robust Automated Machine Learning”. As an AutoML tool, Auto-Sklearn tries to provide the optimal pipeline for a given dataset, specifically by covering: data transformation, model selection and hyperparameter optimization tasks. Auto-Sklearn is a tool that is mainly made up of scikit-learn models, specifically it is composed of 15 classifiers, 14 preprocessing methods, and 4 data preprocessing methods."
},
{
"code": null,
"e": 2040,
"s": 1210,
"text": "Finding the optimal pipeline is a complex task due to the diversity of models and parameters that must be considered. The “optimal pipeline” can be obtained through exhaustive techniques such as Grid Search, however it is not a suitable solution because the space search is determined by fixed values. Likewise, it has been proposed another techniques based on sophisticated optimization algorithms such as TPOT which aims to find the optimal pipeline configuration through Genetic Algorithms [2] which can find the “optimal pipeline” in a considerable time however, for datasets with specific characteristics, optimization can take even days. In contrast, Auto-Sklearn implements Bayesian Optimization for the searching of the optimal pipeline which can be thought as a slow technique which Auto-Sklearn solves in proper manner."
},
{
"code": null,
"e": 2649,
"s": 2040,
"text": "The Auto-Sklearn architecture is composed of 3 phases: meta-learning, bayesian optimization, ensemble selection. The key idea of the meta-learning phase is to reduce the space search by learning from models that performed well on similar datasets. Right after, the bayesian optimization phase takes the space search created in the meta-learning step and creates bayesian models for finding the optimal pipeline configuration. Finally, an ensemble selection model is created by reusing the most accurate models found in the bayesian optimization step. In Figure 2 it’s described the Auto-Sklearn architecture."
},
{
"code": null,
"e": 2945,
"s": 2649,
"text": "Auto-Sklearn is a robust tool that integrates 3 stages for the search for the optimal pipeline. However, it is important to mention that both phase 1 (meta-learninig) and phase 3 (ensemble selection) can be configured according to different needs, we will see this in detail in the next section."
},
{
"code": null,
"e": 3098,
"s": 2945,
"text": "Great, so far we already know what Auto-Sklearn is, what its components are and how it works, now let’s see how we do this in practice, let’s go for it!"
},
{
"code": null,
"e": 3366,
"s": 3098,
"text": "The idea of the following example is to show the usability of the autosklearn library as well as some configurations to manipulate phase 1 (meta-learning) and phase 3 (ensemble selection). For this example, we are going to make use of the “breast cancer” toy dataset."
},
{
"code": null,
"e": 3456,
"s": 3366,
"text": "So first we are going to import some libraries and split the dataset into train and test:"
},
{
"code": null,
"e": 3676,
"s": 3456,
"text": "As you can notice, we are importing the extension AutoSklearnClassifier since this is a classification problem. Then, we only need to instantiate the classifier and we will be able to train the model, pretty easy right?"
},
{
"code": null,
"e": 3940,
"s": 3676,
"text": "Since we are not passing any argument to the classifier, AutoSklearn uses the default parameters, which is not a good practice. As was mentioned in the previous section, AutoSklearn allows us to manipulate the meta-learning step as well as the ensemble selection."
},
{
"code": null,
"e": 4070,
"s": 3940,
"text": "In order to manipulate the number of instances obtained from the meta-learning step, we need to provide a value to the parameter:"
},
{
"code": null,
"e": 4130,
"s": 4070,
"text": "initial_configurations_via_meta_learning : int (default=25)"
},
{
"code": null,
"e": 4453,
"s": 4130,
"text": "As we can observe the default value is 25, it means that it will take 25 configurations to be implemented as the starting point in the bayesian optimization step. If you don’t want to take any configuration as starting point (i.e. if you want to start the optimization from scratch), you can set this value equals to zero."
},
{
"code": null,
"e": 4603,
"s": 4453,
"text": "On the other hand, if you want to manipulate the number of models to be considered in the Ensemble Selection, you only need to modify this parameter:"
},
{
"code": null,
"e": 4636,
"s": 4603,
"text": "ensemble_size : int (default=50)"
},
{
"code": null,
"e": 4988,
"s": 4636,
"text": "As we can observe, the default number of models to be added to the ensemble is 50 (which is a large number, at least for small datasets), you can try different values in order to find the optimal according to your needs (remember that ensemble learning is a good technique for improving the accuracy, however there is a risk of overfitting the model)."
},
{
"code": null,
"e": 5145,
"s": 4988,
"text": "So, if we didn’t want to use any configuration as starting point (meta-learning) and only use one model in the ensemble, the initialization will looks like:"
},
{
"code": null,
"e": 5361,
"s": 5145,
"text": "Now let’s talk about “time limits”. AutoSklearn provides a set of parameters to control the time to be used for the entire optimization as well as to control the time used for each model evaluation. These flags are:"
},
{
"code": null,
"e": 5540,
"s": 5361,
"text": "# Time limit for the entire optimizationtime_left_for_this_task: int (default=3600)# Time limit for each model evaluationper_run_time_limit: int (1/10 of time_left_for_this_task)"
},
{
"code": null,
"e": 5831,
"s": 5540,
"text": "If you dataset is small, maybe you should consider to decrease these flags, otherwise the optimization process may take a while. So, say we want to set 300 seconds as the time limit for the entire optimization and only 30 per each model evaluation, the class initialization will looks like:"
},
{
"code": null,
"e": 5910,
"s": 5831,
"text": "Finally for testing it is quite simple, exactly as you do with sklearn models:"
},
{
"code": null,
"e": 6005,
"s": 5910,
"text": "$ model.score(x_train, y_train)0.960093896713615$ model.score(x_test, y_test)0.965034965034965"
},
{
"code": null,
"e": 6058,
"s": 6005,
"text": "If you want to see a summary, you only need to type:"
},
{
"code": null,
"e": 6477,
"s": 6058,
"text": "$ print(model.sprint_statistics())auto-sklearn results: Dataset name: ff54bc0cfe4c3dc32e4cbba909d41e5a Metric: accuracy Best validation score: 0.964539 Number of target algorithm runs: 62 Number of successful target algorithm runs: 55 Number of crashed target algorithm runs: 4 Number of target algorithms that exceeded the time limit: 3 Number of target algorithms that exceeded the memory limit: 0"
},
{
"code": null,
"e": 6644,
"s": 6477,
"text": "If you want to learn more about the AutoSklearn parameters, it will be worth to take a look a the documentation: https://automl.github.io/auto-sklearn/master/api.html"
},
{
"code": null,
"e": 6670,
"s": 6644,
"text": "From my side, that is it!"
},
{
"code": null,
"e": 6777,
"s": 6670,
"text": "In this blog we have seen what Auto-Sklearn is, what its components, how it works and a practical example."
},
{
"code": null,
"e": 7155,
"s": 6777,
"text": "In my opinion, Auto-Sklearn works as one more alternative to find the optimal configuration of your pipeline considering the risks that this entails, that is, it is necessary to provide a set of adequate parameters to avoid exploiting the computational time or overfitting the model. If you are working with serious datasets, you can consider these kind of tools as a baseline."
}
] |
Possible to make a divisible by 3 number using all digits in an array in C++
|
In this problem, we are given an array. Our task is to check whether a number generated by using all digits of the elements of the array is divisible by 3. If possible then print “Yes” otherwise print “No”.
Let’s take an example to understand the problem
Input − arr = {3, 5, 91, }
Output − YES
Explanation − The number 5193 is divisible by 3. So, our answer is YES.
To solve this problem, we will check its divisibility by 3.
Divisibility by 3 − a number is divisible by 3 if the sum of its digits is divisible by 3.
Now, we will have to find the sum of all array elements. If this sum is divisible by 3, then it is possible to print YES. otherwise No.
Program to show the implementation of our solution
Live Demo
#include <iostream>
using namespace std;
bool is3DivisibleArray(int arr[]) {
int n = sizeof(arr) / sizeof(arr[0]);
int rem = 0;
for (int i=0; i<n; i++)
rem = (rem + arr[i]) % 3;
return (rem == 0);
}
int main(){
int arr[] = { 23, 64, 87, 12, 9 };
cout<<"Creating a number from digits of array which is divisible by 3 ";
is3DivisibleArray(arr)?cout<<"is Possible":cout<<"is not Possible";
return 0;
}
Creating a number from digits of array which is divisible by 3 is Possible
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "In this problem, we are given an array. Our task is to check whether a number generated by using all digits of the elements of the array is divisible by 3. If possible then print “Yes” otherwise print “No”."
},
{
"code": null,
"e": 1317,
"s": 1269,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1344,
"s": 1317,
"text": "Input − arr = {3, 5, 91, }"
},
{
"code": null,
"e": 1357,
"s": 1344,
"text": "Output − YES"
},
{
"code": null,
"e": 1429,
"s": 1357,
"text": "Explanation − The number 5193 is divisible by 3. So, our answer is YES."
},
{
"code": null,
"e": 1489,
"s": 1429,
"text": "To solve this problem, we will check its divisibility by 3."
},
{
"code": null,
"e": 1580,
"s": 1489,
"text": "Divisibility by 3 − a number is divisible by 3 if the sum of its digits is divisible by 3."
},
{
"code": null,
"e": 1716,
"s": 1580,
"text": "Now, we will have to find the sum of all array elements. If this sum is divisible by 3, then it is possible to print YES. otherwise No."
},
{
"code": null,
"e": 1767,
"s": 1716,
"text": "Program to show the implementation of our solution"
},
{
"code": null,
"e": 1778,
"s": 1767,
"text": " Live Demo"
},
{
"code": null,
"e": 2207,
"s": 1778,
"text": "#include <iostream>\nusing namespace std;\nbool is3DivisibleArray(int arr[]) {\n int n = sizeof(arr) / sizeof(arr[0]);\n int rem = 0;\n for (int i=0; i<n; i++)\n rem = (rem + arr[i]) % 3;\n return (rem == 0);\n}\nint main(){\n int arr[] = { 23, 64, 87, 12, 9 };\n cout<<\"Creating a number from digits of array which is divisible by 3 \";\n is3DivisibleArray(arr)?cout<<\"is Possible\":cout<<\"is not Possible\";\n return 0;\n}"
},
{
"code": null,
"e": 2282,
"s": 2207,
"text": "Creating a number from digits of array which is divisible by 3 is Possible"
}
] |
How to deserialize a JSON into Javascript object?
|
JSON is literally Javascript Object notation. JS has built in support
using the JSON object to parse JSON strings into JS objects.
You can use it in the following way −
const json = '{"result":true, "count":42}';
// Parse the object
const obj = JSON.parse(json);
console.log(obj.count);
console.log(obj.result);
This will give the output −
42
true
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "JSON is literally Javascript Object notation. JS has built in support\nusing the JSON object to parse JSON strings into JS objects."
},
{
"code": null,
"e": 1231,
"s": 1193,
"text": "You can use it in the following way −"
},
{
"code": null,
"e": 1374,
"s": 1231,
"text": "const json = '{\"result\":true, \"count\":42}';\n// Parse the object\nconst obj = JSON.parse(json);\nconsole.log(obj.count);\nconsole.log(obj.result);"
},
{
"code": null,
"e": 1402,
"s": 1374,
"text": "This will give the output −"
},
{
"code": null,
"e": 1410,
"s": 1402,
"text": "42\ntrue"
}
] |
Longest Prefix Suffix | Practice | GeeksforGeeks
|
Given a string of characters, find the length of the longest proper prefix which is also a proper suffix.
NOTE: Prefix and suffix can be overlapping but they should not be equal to the entire string.
Example 1:
Input: s = "abab"
Output: 2
Explanation: "ab" is the longest proper
prefix and suffix.
Example 2:
Input: s = "aaaa"
Output: 3
Explanation: "aaa" is the longest proper
prefix and suffix.
Your task:
You do not need to read any input or print anything. The task is to complete the function lps(), which takes a string as input and returns an integer.
Expected Time Complexity: O(|s|)
Expected Auxiliary Space: O(|s|)
Constraints:
1 ≤ |s| ≤ 105
s contains lower case English alphabets
-1
sangamchoudhary72 weeks ago
class Solution{
public:
int lps(string str){
vector<int> arr(str.size());
int i = 1, len = 0;
while(i < str.size()){
if(str[i] == str[len]){
arr[i++] = ++len;
}else{
if(len) len = arr[len-1];
else arr[i++] = 0;
}
}
return arr.back();
}
};
0
nityabhanu2 weeks ago
A very simple yet efficient solution ,took almost half the time constraint and no new arrays and map declared
CODE:
int lps(string s) { int count=0; int x=0,y=1; int flag=0; while(y<s.length()) { if(s[x]==s[y]) { x++; y++; } else { x=0; flag++; } if(flag==2) { flag=0; y++; } } return x;}
0
prateek_jakhar2 weeks ago
JAVA SOLUTION (Constant Space Approach)
int lps(String s) {
// code here
int n = s.length();
long p = 31;
long mod = 1000000007;
long pow = 1;
long ph = 0, sh = 0;
int ans = 0;
for(int i = 0; i<n-1; i++){
ph = (ph*p + (s.charAt(i)-'a'+1))%mod;
sh = (sh + ((s.charAt(n-1-i)-'a'+1)*pow)%mod)%mod;
pow=(pow*p)%mod;
if(ph==sh){
ans = i+1;
}
}
return ans;
}
+1
kshitij14103 weeks ago
int lps(string s) { int n=s.size(); vector<int>lps(n,0); for(int i=1;i<n;i++) { int j=lps[i-1]; while(j>0 and s[i]!=s[j]) j=lps[j-1]; if(s[i]==s[j]) j++; lps[i]=j; } return lps[n-1];
0
jswxingyu11 month ago
Python solution
The running time is my bottleneck, I could barely pass it.
class Solution:
def lps(self, s):
# code here
"""
# 该算法因为时间原因不能通过, 难搞哦
# common situation
for L in range(len(s)-1, 0, -1):
if s[0:L] == s[-L:]:
return L
return 0
"""
firstChar = s[0]
indexOfNextF = 0
lenS = len(s)
while indexOfNextF <= lenS-1:
indexOfNextF = s.find(firstChar, indexOfNextF+1)
if indexOfNextF != -1:
if s[:lenS-indexOfNextF] == s[indexOfNextF:]:
return lenS - indexOfNextF
else:
return 0
return 0
0
ravi1010prakash1 month ago
class Solution{ public: int lps(string str) { int n=str.length(),len=0; int lps[n]; lps[0]=0; int i=1; while(i<n){ if(str[i]==str[len]) {len++;lps[i]=len;i++;} else {if(len==0){lps[i]=0;i++;} else{len=lps[len-1];} } } return len;}};
// { Driver Code Starts.
int main() {
ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--) { string str; cin >> str;
Solution ob;
cout << ob.lps(str) << "\n"; }
return 0;} /
-1
forworkonlydude2 months ago
Why is my code giving : Abort signal from abort(3) (SIGABRT)??
Can anyone please help me out on this? The huge test case on which it gives error is running absolutely fine, when I run it individually via custom input. PLEASE HELP GUYS!!!!
I am really really confused here.
class Solution{
public:
map<pair<long long,long long>,long long>mp;
int matchStr(string s1, string s2, long long i, long long j){
if(mp.find({i,j})==mp.end()){
if(j>=s2.size()) mp[{i,j}] = 0;
else if(s1[i]==s2[j]) mp[{i,j}] = 1+matchStr(s1,s2,i+1,j+1);
else{
if(i!=0){
j-=i;
}
mp[{i,j}] = matchStr(s1,s2,0,j+1)-i;
}
}
return mp[{i,j}];
}
int lps(string s) {
// Your code goes here
if(s.size()<=1) return 0;
return matchStr(s.substr(0,s.size()-1),s.substr(1),0,0);
}
};
+3
neeramrutia2 months ago
int i=1; for(i=1;i<s.length();i++) { if(s.substring(0,s.length()-i).equals(s.substring(i))) return s.length()-i; } return 0;
-1
akashkhurana282 months ago
JAVA SOLUTION
class Solution { int lps(String s) { // code here int n=s.length(); int [] lp=new int[n]; int len=0; int i=1; while (i<n){ if(s.charAt(i)==s.charAt(len)){ len++; lp[i]=len; i++; } else { if (len==0) {lp[i]=0;i++;} else { len=lp[len-1]; } } } return len; }}
-1
kumrahulsingh75752 months ago
Easiest C++ soln in 4 lines
int lps(string s) { int m=s.length(); vector<int> lps(m,0); for(int i=1;i<m;i++){ int j=lps[i-1]; while(j>0 && s[i]!=s[j]) j=lps[j-1]; if(s[i]==s[j]) j++; lps[i]=j; } return lps[m-1];}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 344,
"s": 238,
"text": "Given a string of characters, find the length of the longest proper prefix which is also a proper suffix."
},
{
"code": null,
"e": 438,
"s": 344,
"text": "NOTE: Prefix and suffix can be overlapping but they should not be equal to the entire string."
},
{
"code": null,
"e": 449,
"s": 438,
"text": "Example 1:"
},
{
"code": null,
"e": 538,
"s": 449,
"text": "Input: s = \"abab\"\nOutput: 2\nExplanation: \"ab\" is the longest proper \nprefix and suffix. "
},
{
"code": null,
"e": 549,
"s": 538,
"text": "Example 2:"
},
{
"code": null,
"e": 639,
"s": 549,
"text": "Input: s = \"aaaa\"\nOutput: 3\nExplanation: \"aaa\" is the longest proper \nprefix and suffix. "
},
{
"code": null,
"e": 802,
"s": 639,
"text": "Your task:\nYou do not need to read any input or print anything. The task is to complete the function lps(), which takes a string as input and returns an integer. "
},
{
"code": null,
"e": 868,
"s": 802,
"text": "Expected Time Complexity: O(|s|)\nExpected Auxiliary Space: O(|s|)"
},
{
"code": null,
"e": 935,
"s": 868,
"text": "Constraints:\n1 ≤ |s| ≤ 105\ns contains lower case English alphabets"
},
{
"code": null,
"e": 938,
"s": 935,
"text": "-1"
},
{
"code": null,
"e": 966,
"s": 938,
"text": "sangamchoudhary72 weeks ago"
},
{
"code": null,
"e": 1302,
"s": 966,
"text": "class Solution{\n public:\t\t\n\tint lps(string str){\n\t vector<int> arr(str.size());\n\t int i = 1, len = 0;\n\t while(i < str.size()){\n\t if(str[i] == str[len]){\n\t arr[i++] = ++len;\n\t }else{\n\t if(len) len = arr[len-1];\n\t else arr[i++] = 0;\n\t }\n\t }\n\t return arr.back();\n\t}\n};"
},
{
"code": null,
"e": 1304,
"s": 1302,
"text": "0"
},
{
"code": null,
"e": 1326,
"s": 1304,
"text": "nityabhanu2 weeks ago"
},
{
"code": null,
"e": 1436,
"s": 1326,
"text": "A very simple yet efficient solution ,took almost half the time constraint and no new arrays and map declared"
},
{
"code": null,
"e": 1442,
"s": 1436,
"text": "CODE:"
},
{
"code": null,
"e": 1751,
"s": 1442,
"text": "int lps(string s) { int count=0; int x=0,y=1; int flag=0; while(y<s.length()) { if(s[x]==s[y]) { x++; y++; } else { x=0; flag++; } if(flag==2) { flag=0; y++; } } return x;}"
},
{
"code": null,
"e": 1753,
"s": 1751,
"text": "0"
},
{
"code": null,
"e": 1779,
"s": 1753,
"text": "prateek_jakhar2 weeks ago"
},
{
"code": null,
"e": 1819,
"s": 1779,
"text": "JAVA SOLUTION (Constant Space Approach)"
},
{
"code": null,
"e": 2301,
"s": 1819,
"text": "int lps(String s) {\n // code here\n int n = s.length();\n long p = 31;\n long mod = 1000000007;\n long pow = 1;\n \n long ph = 0, sh = 0;\n int ans = 0;\n for(int i = 0; i<n-1; i++){\n ph = (ph*p + (s.charAt(i)-'a'+1))%mod;\n sh = (sh + ((s.charAt(n-1-i)-'a'+1)*pow)%mod)%mod;\n pow=(pow*p)%mod;\n if(ph==sh){\n ans = i+1;\n }\n }\n return ans;\n }"
},
{
"code": null,
"e": 2304,
"s": 2301,
"text": "+1"
},
{
"code": null,
"e": 2327,
"s": 2304,
"text": "kshitij14103 weeks ago"
},
{
"code": null,
"e": 2587,
"s": 2327,
"text": "int lps(string s) { int n=s.size(); vector<int>lps(n,0); for(int i=1;i<n;i++) { int j=lps[i-1]; while(j>0 and s[i]!=s[j]) j=lps[j-1]; if(s[i]==s[j]) j++; lps[i]=j; } return lps[n-1];"
},
{
"code": null,
"e": 2589,
"s": 2587,
"text": "0"
},
{
"code": null,
"e": 2611,
"s": 2589,
"text": "jswxingyu11 month ago"
},
{
"code": null,
"e": 2627,
"s": 2611,
"text": "Python solution"
},
{
"code": null,
"e": 2689,
"s": 2629,
"text": "The running time is my bottleneck, I could barely pass it. "
},
{
"code": null,
"e": 3322,
"s": 2691,
"text": "class Solution:\n def lps(self, s):\n # code here\n \n \t\"\"\"\n \t# 该算法因为时间原因不能通过, 难搞哦\n \t# common situation\n \tfor L in range(len(s)-1, 0, -1):\n \tif s[0:L] == s[-L:]:\n \treturn L\n \treturn 0\n \t\"\"\" \n \n\n\n firstChar = s[0]\n indexOfNextF = 0\n lenS = len(s)\n while indexOfNextF <= lenS-1:\n \n indexOfNextF = s.find(firstChar, indexOfNextF+1)\n if indexOfNextF != -1:\n if s[:lenS-indexOfNextF] == s[indexOfNextF:]:\n return lenS - indexOfNextF\n else:\n return 0\n \n return 0"
},
{
"code": null,
"e": 3324,
"s": 3322,
"text": "0"
},
{
"code": null,
"e": 3351,
"s": 3324,
"text": "ravi1010prakash1 month ago"
},
{
"code": null,
"e": 3647,
"s": 3351,
"text": "class Solution{ public: int lps(string str) { int n=str.length(),len=0; int lps[n]; lps[0]=0; int i=1; while(i<n){ if(str[i]==str[len]) {len++;lps[i]=len;i++;} else {if(len==0){lps[i]=0;i++;} else{len=lps[len-1];} } } return len;}};"
},
{
"code": null,
"e": 3672,
"s": 3647,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 3686,
"s": 3672,
"text": "int main() { "
},
{
"code": null,
"e": 3824,
"s": 3686,
"text": " ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--) { string str; cin >> str;"
},
{
"code": null,
"e": 3841,
"s": 3824,
"text": " Solution ob;"
},
{
"code": null,
"e": 3878,
"s": 3841,
"text": " cout << ob.lps(str) << \"\\n\"; }"
},
{
"code": null,
"e": 3894,
"s": 3878,
"text": " return 0;} /"
},
{
"code": null,
"e": 3897,
"s": 3894,
"text": "-1"
},
{
"code": null,
"e": 3925,
"s": 3897,
"text": "forworkonlydude2 months ago"
},
{
"code": null,
"e": 3988,
"s": 3925,
"text": "Why is my code giving : Abort signal from abort(3) (SIGABRT)??"
},
{
"code": null,
"e": 4164,
"s": 3988,
"text": "Can anyone please help me out on this? The huge test case on which it gives error is running absolutely fine, when I run it individually via custom input. PLEASE HELP GUYS!!!!"
},
{
"code": null,
"e": 4201,
"s": 4166,
"text": "I am really really confused here. "
},
{
"code": null,
"e": 4830,
"s": 4203,
"text": "class Solution{\n public:\t\t\n \n map<pair<long long,long long>,long long>mp;\n \n int matchStr(string s1, string s2, long long i, long long j){\n if(mp.find({i,j})==mp.end()){\n if(j>=s2.size()) mp[{i,j}] = 0;\n else if(s1[i]==s2[j]) mp[{i,j}] = 1+matchStr(s1,s2,i+1,j+1);\n else{\n if(i!=0){\n j-=i;\n }\n mp[{i,j}] = matchStr(s1,s2,0,j+1)-i;\n }\n }\n return mp[{i,j}];\n }\n \n\tint lps(string s) {\n\t // Your code goes here\n\t if(s.size()<=1) return 0;\n\t return matchStr(s.substr(0,s.size()-1),s.substr(1),0,0);\n\t \n\t}\n};"
},
{
"code": null,
"e": 4833,
"s": 4830,
"text": "+3"
},
{
"code": null,
"e": 4857,
"s": 4833,
"text": "neeramrutia2 months ago"
},
{
"code": null,
"e": 5033,
"s": 4857,
"text": "int i=1; for(i=1;i<s.length();i++) { if(s.substring(0,s.length()-i).equals(s.substring(i))) return s.length()-i; } return 0;"
},
{
"code": null,
"e": 5036,
"s": 5033,
"text": "-1"
},
{
"code": null,
"e": 5063,
"s": 5036,
"text": "akashkhurana282 months ago"
},
{
"code": null,
"e": 5077,
"s": 5063,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 5544,
"s": 5077,
"text": "class Solution { int lps(String s) { // code here int n=s.length(); int [] lp=new int[n]; int len=0; int i=1; while (i<n){ if(s.charAt(i)==s.charAt(len)){ len++; lp[i]=len; i++; } else { if (len==0) {lp[i]=0;i++;} else { len=lp[len-1]; } } } return len; }}"
},
{
"code": null,
"e": 5547,
"s": 5544,
"text": "-1"
},
{
"code": null,
"e": 5577,
"s": 5547,
"text": "kumrahulsingh75752 months ago"
},
{
"code": null,
"e": 5605,
"s": 5577,
"text": "Easiest C++ soln in 4 lines"
},
{
"code": null,
"e": 5836,
"s": 5607,
"text": " int lps(string s) { int m=s.length(); vector<int> lps(m,0); for(int i=1;i<m;i++){ int j=lps[i-1]; while(j>0 && s[i]!=s[j]) j=lps[j-1]; if(s[i]==s[j]) j++; lps[i]=j; } return lps[m-1];}"
},
{
"code": null,
"e": 5982,
"s": 5836,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6018,
"s": 5982,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6028,
"s": 6018,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6038,
"s": 6028,
"text": "\nContest\n"
},
{
"code": null,
"e": 6101,
"s": 6038,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6249,
"s": 6101,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6457,
"s": 6249,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6563,
"s": 6457,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Fibonacci Heap - Insertion and Union - GeeksforGeeks
|
24 Nov, 2021
Prerequisites: Fibonacci Heap (Introduction)
Fibonacci Heap is a collection of trees with min-heap or max-heap property. In Fibonacci Heap, trees can have any shape even all trees can be single nodes (This is unlike Binomial Heap where every tree has to be Binomial Tree).In this article, we will discuss Insertion and Union operation on Fibonacci Heap.
Insertion: To insert a node in a Fibonacci heap H, the following algorithm is followed:
Create a new node ‘x’.Check whether heap H is empty or not.If H is empty then: Make x as the only node in the root list.Set H(min) pointer to x.Else: Insert x into root list and update H(min).
Create a new node ‘x’.
Check whether heap H is empty or not.
If H is empty then: Make x as the only node in the root list.Set H(min) pointer to x.
Make x as the only node in the root list.
Set H(min) pointer to x.
Else: Insert x into root list and update H(min).
Insert x into root list and update H(min).
Example:
Union: Union of two Fibonacci heaps H1 and H2 can be accomplished as follows:
Join root lists of Fibonacci heaps H1 and H2 and make a single Fibonacci heap H.If H1(min) < H2(min) then: H(min) = H1(min).Else: H(min) = H2(min).
Join root lists of Fibonacci heaps H1 and H2 and make a single Fibonacci heap H.
If H1(min) < H2(min) then: H(min) = H1(min).
H(min) = H1(min).
Else: H(min) = H2(min).
H(min) = H2(min).
Example:
Following is a program to demonstrate building and inserting in a Fibonacci heap:
C++
// C++ program to demonstrate building// and inserting in a Fibonacci heap#include <cstdlib>#include <iostream>#include <malloc.h>using namespace std; struct node { node* parent; node* child; node* left; node* right; int key;}; // Creating min pointer as "mini"struct node* mini = NULL; // Declare an integer for number of nodes in the heapint no_of_nodes = 0; // Function to insert a node in heapvoid insertion(int val){ struct node* new_node = (struct node*)malloc(sizeof(struct node)); new_node->key = val; new_node->parent = NULL; new_node->child = NULL; new_node->left = new_node; new_node->right = new_node; if (mini != NULL) { (mini->left)->right = new_node; new_node->right = mini; new_node->left = mini->left; mini->left = new_node; if (new_node->key < mini->key) mini = new_node; } else { mini = new_node; }} // Function to display the heapvoid display(struct node* mini){ node* ptr = mini; if (ptr == NULL) cout << "The Heap is Empty" << endl; else { cout << "The root nodes of Heap are: " << endl; do { cout << ptr->key; ptr = ptr->right; if (ptr != mini) { cout << "-->"; } } while (ptr != mini && ptr->right != NULL); cout << endl << "The heap has " << no_of_nodes << " nodes" << endl; }}// Function to find min node in the heapvoid find_min(struct node* mini){ cout << "min of heap is: " << mini->key << endl;} // Driver codeint main(){ no_of_nodes = 7; insertion(4); insertion(3); insertion(7); insertion(5); insertion(2); insertion(1); insertion(10); display(mini); find_min(mini); return 0;}
The root nodes of Heap are:
1-->2-->3-->4-->7-->5-->10
The heap has 7 nodes
Min of heap is: 1
ritik1501
Data Structures-Heap
Fibonacci
Technical Scripter 2018
Advanced Data Structure
Heap
Technical Scripter
Fibonacci
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Segment Tree | Set 1 (Sum of given range)
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
Building Heap from Array
Sliding Window Maximum (Maximum of all subarrays of size k)
|
[
{
"code": null,
"e": 23771,
"s": 23743,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 23816,
"s": 23771,
"text": "Prerequisites: Fibonacci Heap (Introduction)"
},
{
"code": null,
"e": 24126,
"s": 23816,
"text": "Fibonacci Heap is a collection of trees with min-heap or max-heap property. In Fibonacci Heap, trees can have any shape even all trees can be single nodes (This is unlike Binomial Heap where every tree has to be Binomial Tree).In this article, we will discuss Insertion and Union operation on Fibonacci Heap. "
},
{
"code": null,
"e": 24215,
"s": 24126,
"text": "Insertion: To insert a node in a Fibonacci heap H, the following algorithm is followed: "
},
{
"code": null,
"e": 24408,
"s": 24215,
"text": "Create a new node ‘x’.Check whether heap H is empty or not.If H is empty then: Make x as the only node in the root list.Set H(min) pointer to x.Else: Insert x into root list and update H(min)."
},
{
"code": null,
"e": 24431,
"s": 24408,
"text": "Create a new node ‘x’."
},
{
"code": null,
"e": 24469,
"s": 24431,
"text": "Check whether heap H is empty or not."
},
{
"code": null,
"e": 24555,
"s": 24469,
"text": "If H is empty then: Make x as the only node in the root list.Set H(min) pointer to x."
},
{
"code": null,
"e": 24597,
"s": 24555,
"text": "Make x as the only node in the root list."
},
{
"code": null,
"e": 24622,
"s": 24597,
"text": "Set H(min) pointer to x."
},
{
"code": null,
"e": 24671,
"s": 24622,
"text": "Else: Insert x into root list and update H(min)."
},
{
"code": null,
"e": 24714,
"s": 24671,
"text": "Insert x into root list and update H(min)."
},
{
"code": null,
"e": 24724,
"s": 24714,
"text": "Example: "
},
{
"code": null,
"e": 24803,
"s": 24724,
"text": "Union: Union of two Fibonacci heaps H1 and H2 can be accomplished as follows: "
},
{
"code": null,
"e": 24951,
"s": 24803,
"text": "Join root lists of Fibonacci heaps H1 and H2 and make a single Fibonacci heap H.If H1(min) < H2(min) then: H(min) = H1(min).Else: H(min) = H2(min)."
},
{
"code": null,
"e": 25032,
"s": 24951,
"text": "Join root lists of Fibonacci heaps H1 and H2 and make a single Fibonacci heap H."
},
{
"code": null,
"e": 25077,
"s": 25032,
"text": "If H1(min) < H2(min) then: H(min) = H1(min)."
},
{
"code": null,
"e": 25095,
"s": 25077,
"text": "H(min) = H1(min)."
},
{
"code": null,
"e": 25119,
"s": 25095,
"text": "Else: H(min) = H2(min)."
},
{
"code": null,
"e": 25137,
"s": 25119,
"text": "H(min) = H2(min)."
},
{
"code": null,
"e": 25147,
"s": 25137,
"text": "Example: "
},
{
"code": null,
"e": 25231,
"s": 25147,
"text": "Following is a program to demonstrate building and inserting in a Fibonacci heap: "
},
{
"code": null,
"e": 25235,
"s": 25231,
"text": "C++"
},
{
"code": "// C++ program to demonstrate building// and inserting in a Fibonacci heap#include <cstdlib>#include <iostream>#include <malloc.h>using namespace std; struct node { node* parent; node* child; node* left; node* right; int key;}; // Creating min pointer as \"mini\"struct node* mini = NULL; // Declare an integer for number of nodes in the heapint no_of_nodes = 0; // Function to insert a node in heapvoid insertion(int val){ struct node* new_node = (struct node*)malloc(sizeof(struct node)); new_node->key = val; new_node->parent = NULL; new_node->child = NULL; new_node->left = new_node; new_node->right = new_node; if (mini != NULL) { (mini->left)->right = new_node; new_node->right = mini; new_node->left = mini->left; mini->left = new_node; if (new_node->key < mini->key) mini = new_node; } else { mini = new_node; }} // Function to display the heapvoid display(struct node* mini){ node* ptr = mini; if (ptr == NULL) cout << \"The Heap is Empty\" << endl; else { cout << \"The root nodes of Heap are: \" << endl; do { cout << ptr->key; ptr = ptr->right; if (ptr != mini) { cout << \"-->\"; } } while (ptr != mini && ptr->right != NULL); cout << endl << \"The heap has \" << no_of_nodes << \" nodes\" << endl; }}// Function to find min node in the heapvoid find_min(struct node* mini){ cout << \"min of heap is: \" << mini->key << endl;} // Driver codeint main(){ no_of_nodes = 7; insertion(4); insertion(3); insertion(7); insertion(5); insertion(2); insertion(1); insertion(10); display(mini); find_min(mini); return 0;}",
"e": 27015,
"s": 25235,
"text": null
},
{
"code": null,
"e": 27110,
"s": 27015,
"text": "The root nodes of Heap are: \n1-->2-->3-->4-->7-->5-->10\nThe heap has 7 nodes\nMin of heap is: 1"
},
{
"code": null,
"e": 27122,
"s": 27112,
"text": "ritik1501"
},
{
"code": null,
"e": 27143,
"s": 27122,
"text": "Data Structures-Heap"
},
{
"code": null,
"e": 27153,
"s": 27143,
"text": "Fibonacci"
},
{
"code": null,
"e": 27177,
"s": 27153,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27201,
"s": 27177,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 27206,
"s": 27201,
"text": "Heap"
},
{
"code": null,
"e": 27225,
"s": 27206,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27235,
"s": 27225,
"text": "Fibonacci"
},
{
"code": null,
"e": 27240,
"s": 27235,
"text": "Heap"
},
{
"code": null,
"e": 27338,
"s": 27240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27347,
"s": 27338,
"text": "Comments"
},
{
"code": null,
"e": 27360,
"s": 27347,
"text": "Old Comments"
},
{
"code": null,
"e": 27394,
"s": 27360,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 27434,
"s": 27394,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 27462,
"s": 27434,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 27494,
"s": 27462,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 27536,
"s": 27494,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 27567,
"s": 27536,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 27623,
"s": 27567,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 27667,
"s": 27623,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 27692,
"s": 27667,
"text": "Building Heap from Array"
}
] |
A Guide to A/B Testing — How to Formulate, Design and Interpret | by Idil Ismiguzel | Towards Data Science
|
The online world gives us a big opportunity to perform experiments and scientifically evaluate different ideas. Since these experiments are data-driven and providing no room for instincts or gut feelings, we can establish causal relationships between changes and their influence on user behavior. Leveraging on these experiments, many organizations can understand their customers’ liking and preferences by avoiding the so-called HiPPO effect😅
A/B testing is a common methodology to test new products or new features, especially regarding user interface, marketing and eCommerce. The main principle of an A/B test is to split users into two groups; showing the existing product or feature to the control group and the new product or feature to the experiment group. Finally, evaluating how users respond differently in two groups and deciding which version is better. Even though A/B testing is a common practice of online businesses, a lot can easily go wrong from setting up the experiment to interpreting the results correctly.
In this article, you will find how to design a robust A/B test that gives you repeatable results, what are the main pitfalls of A/B testing that require additional attention and how to interpret the results.
You can check out the Jupyter Notebook on my GitHub for the full analysis.
Before getting deeper into A/B testing, let’s answer the following questions.
Both visible and invisible changes can be tested with A/B testing. Examples to visible changes can be new additions to the UI, changes in the design and layout or headline messages. A very popular example is Google’s 41 (yes, not 2) different shades of blue experiment where they randomly showed a shade of blue to each 2.5% of users to understand which color shade earns more clicks. Examples to invisible changes can be page load time or testing different recommendation algorithms. A popular example is Amazon’s A/B test that showed every 100ms increase in page load time decreased the sales by 1%.
New experiences are not suitable for implementing A/B tests. Because a new experience can show change aversion behavior where users don’t like changes and prefer to stick to the old version, or it can show novelty effect where users feel very excited and want to test out everything. In both cases, defining a baseline for comparison and deciding the duration of the test is difficult.
Metric selection needs to consider both sensitivity and robustness. Sensitivity means that metrics should be able to catch the changes and robustness means that metrics shouldn’t change too much from irrelevant effects. As an example, most of the time if the metric is a “mean”, it is sensitive to outliers but not robust. If the metric is a “median”, it is robust but not sensitive for small group changes.
In order to consider both sensitivity and robustness in the metric selection, we can apply filtering and segmentation while creating the control and experiment samples. Filtering and segmentation can be based on user demographics (i.e. age, gender), the language of the platform, internet browser, device type (i.e. iOS or Android), cohort and etc.
Formulate the hypothesis
Design the experiment
Collect the data
Inference/Conclusions
The process of A/B testing starts with a hypothesis. The baseline assumption, or in other words the null hypothesis, assumes that the treatments are equal and any difference between the control and experiment groups is due to chance. The alternative hypothesis assumes that the null hypothesis is wrong and the outcomes of control and experiment groups are more different than what chance might produce. An A/B test is designed to test the hypothesis in such a way that observed difference between the two groups should be either due to random chance or due to a true difference between the groups. After formulating the hypothesis, we collect the data and draw conclusions. Inference of the results reflects the intention of applying the conclusions that are drawn from the experiment samples and applicable for the entire population.
Imagine that you are running a UI experiment where you want to understand the difference between conversion rates of your initial layout vs a new layout. (let’s imagine you want to understand the impact of changing the color of “buy” button from red to blue🔴🔵)
In this experiment, the null hypothesis assumes conversion rates are equal and if there is a difference this is only due to the chance factor. In contrast, the alternative hypothesis assumes there is a statistically significant difference between the conversion rates.
Null hypothesis -> Ho : CR_red = CR_blue
Alternative hypothesis -> H1 : CR_red ≠ CR_blue
After formulating the hypothesis and performing the experiment we collected the following data in the contingency table.
The conversion rate of CG is: 150/150+23567 = 0.632%The conversion rate of EG is: 165/165+23230 = 0.692%From these conversion rates, we can calculate the relative uplift between conversion rates: (0.692%-0.632%)/0.632% = 9.50%
As seen in the code snipped above changing the layout increased the conversion rate by 0.06 percentage points. But is it by chance or the success of the color change❔
We can analyze the results in the following two ways:
Using statistical significance tests we can measure if the collected data shows a result more extreme than the chance might produce. If the result is beyond the chance variation, then it is statistically significant. In this example, we have categorical variables in the contingency data format, which follow a Bernoulli distribution. Bernoulli Distribution has a probability of being 1 and a probability of being 0. In our example, it is conversion=1 and no conversion=0. Considering we are using the conversions as the metric, which is a categorical variable following Bernoulli distribution, we will be using the Chi-Squared test to interpret the results.
The Chi-Squared test assumes observed frequencies for a categorical variable match with the expected frequencies. It calculates a test statistic (Chi) that has a chi-squared distribution and is interpreted to reject or fail to reject the null hypothesis if the expected and observed frequencies are the same. In this article, we will be using scipy.stats package for the statistical functions.
The probability density function of Chi-Squared distribution varies with the degrees of freedom (df) which depends on the size of the contingency table, and calculated as df=(#rows-1)*(#columns-1) In this example df=1.
Key terms we need to know to interpret the test result using Python are p-value and alpha. P-value is the probability of obtaining test results at least as extreme as the results actually observed, under the assumption that the null hypothesis is correct. P-value is is one of the outcomes of the test. Alpha also known as the level of statistical significance is the probability of making type I error (rejecting the null hypothesis when it is actually true). The probability of making a type II error (failing to reject the null hypothesis when it is actually false) is called beta, but it is out of scope for this article. In general, alpha is taken as 0.05 indicating 5% risk of concluding a difference exists between the groups when there is no actual difference.
In terms of a p-value and a chosen significance level (alpha), the test can be interpreted as follows:
If p-value <= alpha: significant result, reject null hypothesis
If p-value > alpha: not significant result, do not reject null hypothesis
We can also interpret the test result by using the test statistic and the critical value:
If test statistic >= critical value: significant result, reject null hypothesis
If test statistic < critical value: not significant result, do not to reject null hypothesis
### chi2 test on contingency tableprint(table)alpha = 0.05stat, p, dof, expected = stats.chi2_contingency(table)### interpret p-valueprint('significance=%.3f, p=%.3f' % (alpha, p))if p <= alpha: print('Reject null hypothesis)')else: print('Do not reject null hypothesis') ### interpret test-statisticprob = 1 - alphacritical = stats.chi2.ppf(prob, dof)print('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))if abs(stat) >= critical: print('Reject null hypothesis)')else: print('Do not reject null hypothesis')
[[ 150 23717] [ 165 23395]]significance=0.050, p=0.365Do not reject null hypothesisprobability=0.950, critical=3.841, stat=0.822Do not reject null hypothesis
As can be seen from the result we do not reject the null hypothesis, in other words, the positive relative difference between the conversion rates is not significant.
The permutation test is one of my favorite techniques because it does not require data to be numeric or binary and sample sizes can be similar or different. Also, assumptions about normally distributed data are not needed.
Permuting means changing the order of a set of values, and what permutation test does is combining results from both groups and testing the null hypothesis by randomly drawing groups (equal to the experiment groups’ sample sizes) from the combined set and analyzing how much they differ from one another. The test repeats doing this as much as decided by the user (say 1000 times). In the end, user should compare the observed difference between experiment and control groups with the set of permuted differences. If the observed difference lies within the set of permuted differences, we do not reject the null hypothesis. But if the observed difference lies outside of the most permutation distribution, we reject the null hypothesis and conclude as the A/B test result is statistically significant and not due to chance.
### Function to perform permutation testdef perm_func(x, nA, nB): n = nA + nB id_B = set(random.sample(range(n), nB)) id_A = set(range(n)) — id_B return x.loc[idx_B].mean() — x.loc[id_A].mean()### Observed difference from experimentobs_pct_diff = 100 * (150 / 23717–165 / 23395)### Aggregated conversion setconversion = [0] * 46797conversion.extend([1] * 315)conversion = pd.Series(conversion)### Permutation testperm_diffs = [100 * perm_fun(conversion, 23717, 23395) for i in range(1000)]### Probabilityprint(np.mean([diff > obs_pct_diff for diff in perm_diffs]))
0.823
This result shows us around 82% of the time we would expect to reach the experiment result by random chance.
Additionally, we can plot a histogram of differences from the permutation test and highlight where the observed difference lies.
fig, ax = plt.subplots(figsize=(5, 5))ax.hist(perm_diffs, rwidth=0.9)ax.axvline(x=obs_pct_diff, lw=2)ax.text(-0.18, 200, ‘Observed\ndifference’, bbox={‘facecolor’:’white’})ax.set_xlabel(‘Conversion rate (in percentage)’)ax.set_ylabel(‘Frequency’)plt.show()
As seen in the plot, the observed difference lies within most of the permuted differences supporting the “do not reject the null hypothesis” result of Chi-Squared test.
Imagine we are using the average session time as our metric to analyze the result of the A/B test. We aim to understand if the new design of the page gets more attention from the users and increase the time they spend on the page. The first few rows representing different user ids look like the following:
### Average difference between control and test samplesmean_cont = np.mean(data[data["Page"] == "Old design"]["Time"])mean_exp = np.mean(data[data["Page"] == "New design"]["Time"])mean_diff = mean_exp - mean_contprint(f"Average difference between experiment and control samples is: {mean_diff}")### Boxplotssns.boxplot(x=data["Page"], y=data["Time"], width=0.4)
Average difference between experiment and control samples is: 22.85
Again we will be analyzing the results in the following two ways:
In this example will use t-Test (or Student’s t-Test) because we have numeric data. t-Test is one of the most commonly used statistical tests where the test statistic follows a Student’s t-distribution under the null hypothesis. t-distribution is used when estimating the mean of a normally distributed population in situations where the sample size is small and the population standard deviation is unknown.
t-distribution is symmetric and bell-shaped like the normal distribution but has thicker and longer tails, meaning that it is more prone to produce values far from its mean. As seen in the plot, the larger the sample size, the more normally shaped the t-distribution becomes.
In this analysis, we will use scipy.stats.mstats.ttest_ind which calculates t-Test for the means of two independent samples. It is a two-sided test for the null hypothesis that two independent samples have (expected) identical average values. As parameter we must set equal_var=False to perform Welch’s t-test, which does not assume equal population variance between control and experiment samples.
### t-Test on the datatest_res = stats.ttest_ind(data[data.Page == "Old design"]["Time"], data[data.Page == "New design"]["Time"], equal_var=False)print(f'p-value for single sided test: {test_res.pvalue / 2:.4f}')if test_res.pvalue <= alpha: print('Reject null hypothesis)')else: print('Do not reject null hypothesis')
p-value for single sided test: 0.1020Do not reject null hypothesis
As seen in the result, we do not reject the null hypothesis, meaning that the positive average difference between experiment and control samples is not significant.
2. Performing permutation tests
As we did in the previous example, we can perform the permutation test by iterating 1000 times.
nA = data[data.Page == 'Old design'].shape[0]nB = data[data.Page == 'New design'].shape[0]perm_diffs = [perm_fun(data.Time, nA, nB) for _ in range(1000)]larger=[i for i in perm_diffs if i > mean_exp-mean_cont]print(len(larger)/len(perm_diffs))
0.102
This result shows us around 10% of the time we would expect to reach the experiment result by random chance.
fig, ax = plt.subplots(figsize=(8, 6))ax.hist(perm_diffs, rwidth=0.9)ax.axvline(x = mean_exp — mean_cont, color=’black’, lw=2)ax.text(25, 190, ‘Observed\ndifference’, bbox={‘facecolor’:’white’})plt.show()
As seen in the plot, the observed difference lies within most of the permuted differences, supporting the “do not reject the null hypothesis” result of t-Test.
To design a robust experiment, it is highly recommended to decide metrics for invariant checking. These metrics shouldn’t change between control and experiment groups and can be used for sanity checking.What is important in an A/B test is to define the sample size for the experiment and control groups that represent the overall population. While doing this, we need to pay attention to two things: randomness and representativeness. Randomness of the sample is necessary to reach unbiased results and representativeness is necessary to capture all different user behaviors.Online tools can be used to calculate the required minimum sample size for the experiment.Before running the experiment, it would be better to decide the desired lift value. Sometimes even the test result is statistically significant, it might not be practically significant. Organizations might not prefer to perform a change if the change is not going to bring a lift as desired.If you are working with a sample dataset, but you are willing to understand the population behavior you can include resampling methods in your analysis. You can read my article Resampling Methods for Inference Analysis (attached below) to learn more ⚡
To design a robust experiment, it is highly recommended to decide metrics for invariant checking. These metrics shouldn’t change between control and experiment groups and can be used for sanity checking.
What is important in an A/B test is to define the sample size for the experiment and control groups that represent the overall population. While doing this, we need to pay attention to two things: randomness and representativeness. Randomness of the sample is necessary to reach unbiased results and representativeness is necessary to capture all different user behaviors.
Online tools can be used to calculate the required minimum sample size for the experiment.
Before running the experiment, it would be better to decide the desired lift value. Sometimes even the test result is statistically significant, it might not be practically significant. Organizations might not prefer to perform a change if the change is not going to bring a lift as desired.
If you are working with a sample dataset, but you are willing to understand the population behavior you can include resampling methods in your analysis. You can read my article Resampling Methods for Inference Analysis (attached below) to learn more ⚡
towardsdatascience.com
I hope you enjoyed reading the article and find it useful!
If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨
Enjoy this article? Become a member for more!
|
[
{
"code": null,
"e": 616,
"s": 172,
"text": "The online world gives us a big opportunity to perform experiments and scientifically evaluate different ideas. Since these experiments are data-driven and providing no room for instincts or gut feelings, we can establish causal relationships between changes and their influence on user behavior. Leveraging on these experiments, many organizations can understand their customers’ liking and preferences by avoiding the so-called HiPPO effect😅"
},
{
"code": null,
"e": 1203,
"s": 616,
"text": "A/B testing is a common methodology to test new products or new features, especially regarding user interface, marketing and eCommerce. The main principle of an A/B test is to split users into two groups; showing the existing product or feature to the control group and the new product or feature to the experiment group. Finally, evaluating how users respond differently in two groups and deciding which version is better. Even though A/B testing is a common practice of online businesses, a lot can easily go wrong from setting up the experiment to interpreting the results correctly."
},
{
"code": null,
"e": 1411,
"s": 1203,
"text": "In this article, you will find how to design a robust A/B test that gives you repeatable results, what are the main pitfalls of A/B testing that require additional attention and how to interpret the results."
},
{
"code": null,
"e": 1486,
"s": 1411,
"text": "You can check out the Jupyter Notebook on my GitHub for the full analysis."
},
{
"code": null,
"e": 1564,
"s": 1486,
"text": "Before getting deeper into A/B testing, let’s answer the following questions."
},
{
"code": null,
"e": 2166,
"s": 1564,
"text": "Both visible and invisible changes can be tested with A/B testing. Examples to visible changes can be new additions to the UI, changes in the design and layout or headline messages. A very popular example is Google’s 41 (yes, not 2) different shades of blue experiment where they randomly showed a shade of blue to each 2.5% of users to understand which color shade earns more clicks. Examples to invisible changes can be page load time or testing different recommendation algorithms. A popular example is Amazon’s A/B test that showed every 100ms increase in page load time decreased the sales by 1%."
},
{
"code": null,
"e": 2552,
"s": 2166,
"text": "New experiences are not suitable for implementing A/B tests. Because a new experience can show change aversion behavior where users don’t like changes and prefer to stick to the old version, or it can show novelty effect where users feel very excited and want to test out everything. In both cases, defining a baseline for comparison and deciding the duration of the test is difficult."
},
{
"code": null,
"e": 2960,
"s": 2552,
"text": "Metric selection needs to consider both sensitivity and robustness. Sensitivity means that metrics should be able to catch the changes and robustness means that metrics shouldn’t change too much from irrelevant effects. As an example, most of the time if the metric is a “mean”, it is sensitive to outliers but not robust. If the metric is a “median”, it is robust but not sensitive for small group changes."
},
{
"code": null,
"e": 3309,
"s": 2960,
"text": "In order to consider both sensitivity and robustness in the metric selection, we can apply filtering and segmentation while creating the control and experiment samples. Filtering and segmentation can be based on user demographics (i.e. age, gender), the language of the platform, internet browser, device type (i.e. iOS or Android), cohort and etc."
},
{
"code": null,
"e": 3334,
"s": 3309,
"text": "Formulate the hypothesis"
},
{
"code": null,
"e": 3356,
"s": 3334,
"text": "Design the experiment"
},
{
"code": null,
"e": 3373,
"s": 3356,
"text": "Collect the data"
},
{
"code": null,
"e": 3395,
"s": 3373,
"text": "Inference/Conclusions"
},
{
"code": null,
"e": 4231,
"s": 3395,
"text": "The process of A/B testing starts with a hypothesis. The baseline assumption, or in other words the null hypothesis, assumes that the treatments are equal and any difference between the control and experiment groups is due to chance. The alternative hypothesis assumes that the null hypothesis is wrong and the outcomes of control and experiment groups are more different than what chance might produce. An A/B test is designed to test the hypothesis in such a way that observed difference between the two groups should be either due to random chance or due to a true difference between the groups. After formulating the hypothesis, we collect the data and draw conclusions. Inference of the results reflects the intention of applying the conclusions that are drawn from the experiment samples and applicable for the entire population."
},
{
"code": null,
"e": 4492,
"s": 4231,
"text": "Imagine that you are running a UI experiment where you want to understand the difference between conversion rates of your initial layout vs a new layout. (let’s imagine you want to understand the impact of changing the color of “buy” button from red to blue🔴🔵)"
},
{
"code": null,
"e": 4761,
"s": 4492,
"text": "In this experiment, the null hypothesis assumes conversion rates are equal and if there is a difference this is only due to the chance factor. In contrast, the alternative hypothesis assumes there is a statistically significant difference between the conversion rates."
},
{
"code": null,
"e": 4802,
"s": 4761,
"text": "Null hypothesis -> Ho : CR_red = CR_blue"
},
{
"code": null,
"e": 4851,
"s": 4802,
"text": "Alternative hypothesis -> H1 : CR_red ≠ CR_blue"
},
{
"code": null,
"e": 4972,
"s": 4851,
"text": "After formulating the hypothesis and performing the experiment we collected the following data in the contingency table."
},
{
"code": null,
"e": 5199,
"s": 4972,
"text": "The conversion rate of CG is: 150/150+23567 = 0.632%The conversion rate of EG is: 165/165+23230 = 0.692%From these conversion rates, we can calculate the relative uplift between conversion rates: (0.692%-0.632%)/0.632% = 9.50%"
},
{
"code": null,
"e": 5366,
"s": 5199,
"text": "As seen in the code snipped above changing the layout increased the conversion rate by 0.06 percentage points. But is it by chance or the success of the color change❔"
},
{
"code": null,
"e": 5420,
"s": 5366,
"text": "We can analyze the results in the following two ways:"
},
{
"code": null,
"e": 6079,
"s": 5420,
"text": "Using statistical significance tests we can measure if the collected data shows a result more extreme than the chance might produce. If the result is beyond the chance variation, then it is statistically significant. In this example, we have categorical variables in the contingency data format, which follow a Bernoulli distribution. Bernoulli Distribution has a probability of being 1 and a probability of being 0. In our example, it is conversion=1 and no conversion=0. Considering we are using the conversions as the metric, which is a categorical variable following Bernoulli distribution, we will be using the Chi-Squared test to interpret the results."
},
{
"code": null,
"e": 6473,
"s": 6079,
"text": "The Chi-Squared test assumes observed frequencies for a categorical variable match with the expected frequencies. It calculates a test statistic (Chi) that has a chi-squared distribution and is interpreted to reject or fail to reject the null hypothesis if the expected and observed frequencies are the same. In this article, we will be using scipy.stats package for the statistical functions."
},
{
"code": null,
"e": 6692,
"s": 6473,
"text": "The probability density function of Chi-Squared distribution varies with the degrees of freedom (df) which depends on the size of the contingency table, and calculated as df=(#rows-1)*(#columns-1) In this example df=1."
},
{
"code": null,
"e": 7461,
"s": 6692,
"text": "Key terms we need to know to interpret the test result using Python are p-value and alpha. P-value is the probability of obtaining test results at least as extreme as the results actually observed, under the assumption that the null hypothesis is correct. P-value is is one of the outcomes of the test. Alpha also known as the level of statistical significance is the probability of making type I error (rejecting the null hypothesis when it is actually true). The probability of making a type II error (failing to reject the null hypothesis when it is actually false) is called beta, but it is out of scope for this article. In general, alpha is taken as 0.05 indicating 5% risk of concluding a difference exists between the groups when there is no actual difference."
},
{
"code": null,
"e": 7564,
"s": 7461,
"text": "In terms of a p-value and a chosen significance level (alpha), the test can be interpreted as follows:"
},
{
"code": null,
"e": 7628,
"s": 7564,
"text": "If p-value <= alpha: significant result, reject null hypothesis"
},
{
"code": null,
"e": 7702,
"s": 7628,
"text": "If p-value > alpha: not significant result, do not reject null hypothesis"
},
{
"code": null,
"e": 7792,
"s": 7702,
"text": "We can also interpret the test result by using the test statistic and the critical value:"
},
{
"code": null,
"e": 7872,
"s": 7792,
"text": "If test statistic >= critical value: significant result, reject null hypothesis"
},
{
"code": null,
"e": 7965,
"s": 7872,
"text": "If test statistic < critical value: not significant result, do not to reject null hypothesis"
},
{
"code": null,
"e": 8511,
"s": 7965,
"text": "### chi2 test on contingency tableprint(table)alpha = 0.05stat, p, dof, expected = stats.chi2_contingency(table)### interpret p-valueprint('significance=%.3f, p=%.3f' % (alpha, p))if p <= alpha: print('Reject null hypothesis)')else: print('Do not reject null hypothesis') ### interpret test-statisticprob = 1 - alphacritical = stats.chi2.ppf(prob, dof)print('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))if abs(stat) >= critical: print('Reject null hypothesis)')else: print('Do not reject null hypothesis')"
},
{
"code": null,
"e": 8669,
"s": 8511,
"text": "[[ 150 23717] [ 165 23395]]significance=0.050, p=0.365Do not reject null hypothesisprobability=0.950, critical=3.841, stat=0.822Do not reject null hypothesis"
},
{
"code": null,
"e": 8836,
"s": 8669,
"text": "As can be seen from the result we do not reject the null hypothesis, in other words, the positive relative difference between the conversion rates is not significant."
},
{
"code": null,
"e": 9059,
"s": 8836,
"text": "The permutation test is one of my favorite techniques because it does not require data to be numeric or binary and sample sizes can be similar or different. Also, assumptions about normally distributed data are not needed."
},
{
"code": null,
"e": 9883,
"s": 9059,
"text": "Permuting means changing the order of a set of values, and what permutation test does is combining results from both groups and testing the null hypothesis by randomly drawing groups (equal to the experiment groups’ sample sizes) from the combined set and analyzing how much they differ from one another. The test repeats doing this as much as decided by the user (say 1000 times). In the end, user should compare the observed difference between experiment and control groups with the set of permuted differences. If the observed difference lies within the set of permuted differences, we do not reject the null hypothesis. But if the observed difference lies outside of the most permutation distribution, we reject the null hypothesis and conclude as the A/B test result is statistically significant and not due to chance."
},
{
"code": null,
"e": 10459,
"s": 9883,
"text": "### Function to perform permutation testdef perm_func(x, nA, nB): n = nA + nB id_B = set(random.sample(range(n), nB)) id_A = set(range(n)) — id_B return x.loc[idx_B].mean() — x.loc[id_A].mean()### Observed difference from experimentobs_pct_diff = 100 * (150 / 23717–165 / 23395)### Aggregated conversion setconversion = [0] * 46797conversion.extend([1] * 315)conversion = pd.Series(conversion)### Permutation testperm_diffs = [100 * perm_fun(conversion, 23717, 23395) for i in range(1000)]### Probabilityprint(np.mean([diff > obs_pct_diff for diff in perm_diffs]))"
},
{
"code": null,
"e": 10465,
"s": 10459,
"text": "0.823"
},
{
"code": null,
"e": 10574,
"s": 10465,
"text": "This result shows us around 82% of the time we would expect to reach the experiment result by random chance."
},
{
"code": null,
"e": 10703,
"s": 10574,
"text": "Additionally, we can plot a histogram of differences from the permutation test and highlight where the observed difference lies."
},
{
"code": null,
"e": 10960,
"s": 10703,
"text": "fig, ax = plt.subplots(figsize=(5, 5))ax.hist(perm_diffs, rwidth=0.9)ax.axvline(x=obs_pct_diff, lw=2)ax.text(-0.18, 200, ‘Observed\\ndifference’, bbox={‘facecolor’:’white’})ax.set_xlabel(‘Conversion rate (in percentage)’)ax.set_ylabel(‘Frequency’)plt.show()"
},
{
"code": null,
"e": 11129,
"s": 10960,
"text": "As seen in the plot, the observed difference lies within most of the permuted differences supporting the “do not reject the null hypothesis” result of Chi-Squared test."
},
{
"code": null,
"e": 11436,
"s": 11129,
"text": "Imagine we are using the average session time as our metric to analyze the result of the A/B test. We aim to understand if the new design of the page gets more attention from the users and increase the time they spend on the page. The first few rows representing different user ids look like the following:"
},
{
"code": null,
"e": 11798,
"s": 11436,
"text": "### Average difference between control and test samplesmean_cont = np.mean(data[data[\"Page\"] == \"Old design\"][\"Time\"])mean_exp = np.mean(data[data[\"Page\"] == \"New design\"][\"Time\"])mean_diff = mean_exp - mean_contprint(f\"Average difference between experiment and control samples is: {mean_diff}\")### Boxplotssns.boxplot(x=data[\"Page\"], y=data[\"Time\"], width=0.4)"
},
{
"code": null,
"e": 11866,
"s": 11798,
"text": "Average difference between experiment and control samples is: 22.85"
},
{
"code": null,
"e": 11932,
"s": 11866,
"text": "Again we will be analyzing the results in the following two ways:"
},
{
"code": null,
"e": 12341,
"s": 11932,
"text": "In this example will use t-Test (or Student’s t-Test) because we have numeric data. t-Test is one of the most commonly used statistical tests where the test statistic follows a Student’s t-distribution under the null hypothesis. t-distribution is used when estimating the mean of a normally distributed population in situations where the sample size is small and the population standard deviation is unknown."
},
{
"code": null,
"e": 12617,
"s": 12341,
"text": "t-distribution is symmetric and bell-shaped like the normal distribution but has thicker and longer tails, meaning that it is more prone to produce values far from its mean. As seen in the plot, the larger the sample size, the more normally shaped the t-distribution becomes."
},
{
"code": null,
"e": 13016,
"s": 12617,
"text": "In this analysis, we will use scipy.stats.mstats.ttest_ind which calculates t-Test for the means of two independent samples. It is a two-sided test for the null hypothesis that two independent samples have (expected) identical average values. As parameter we must set equal_var=False to perform Welch’s t-test, which does not assume equal population variance between control and experiment samples."
},
{
"code": null,
"e": 13385,
"s": 13016,
"text": "### t-Test on the datatest_res = stats.ttest_ind(data[data.Page == \"Old design\"][\"Time\"], data[data.Page == \"New design\"][\"Time\"], equal_var=False)print(f'p-value for single sided test: {test_res.pvalue / 2:.4f}')if test_res.pvalue <= alpha: print('Reject null hypothesis)')else: print('Do not reject null hypothesis')"
},
{
"code": null,
"e": 13452,
"s": 13385,
"text": "p-value for single sided test: 0.1020Do not reject null hypothesis"
},
{
"code": null,
"e": 13617,
"s": 13452,
"text": "As seen in the result, we do not reject the null hypothesis, meaning that the positive average difference between experiment and control samples is not significant."
},
{
"code": null,
"e": 13649,
"s": 13617,
"text": "2. Performing permutation tests"
},
{
"code": null,
"e": 13745,
"s": 13649,
"text": "As we did in the previous example, we can perform the permutation test by iterating 1000 times."
},
{
"code": null,
"e": 13989,
"s": 13745,
"text": "nA = data[data.Page == 'Old design'].shape[0]nB = data[data.Page == 'New design'].shape[0]perm_diffs = [perm_fun(data.Time, nA, nB) for _ in range(1000)]larger=[i for i in perm_diffs if i > mean_exp-mean_cont]print(len(larger)/len(perm_diffs))"
},
{
"code": null,
"e": 13995,
"s": 13989,
"text": "0.102"
},
{
"code": null,
"e": 14104,
"s": 13995,
"text": "This result shows us around 10% of the time we would expect to reach the experiment result by random chance."
},
{
"code": null,
"e": 14309,
"s": 14104,
"text": "fig, ax = plt.subplots(figsize=(8, 6))ax.hist(perm_diffs, rwidth=0.9)ax.axvline(x = mean_exp — mean_cont, color=’black’, lw=2)ax.text(25, 190, ‘Observed\\ndifference’, bbox={‘facecolor’:’white’})plt.show()"
},
{
"code": null,
"e": 14469,
"s": 14309,
"text": "As seen in the plot, the observed difference lies within most of the permuted differences, supporting the “do not reject the null hypothesis” result of t-Test."
},
{
"code": null,
"e": 15677,
"s": 14469,
"text": "To design a robust experiment, it is highly recommended to decide metrics for invariant checking. These metrics shouldn’t change between control and experiment groups and can be used for sanity checking.What is important in an A/B test is to define the sample size for the experiment and control groups that represent the overall population. While doing this, we need to pay attention to two things: randomness and representativeness. Randomness of the sample is necessary to reach unbiased results and representativeness is necessary to capture all different user behaviors.Online tools can be used to calculate the required minimum sample size for the experiment.Before running the experiment, it would be better to decide the desired lift value. Sometimes even the test result is statistically significant, it might not be practically significant. Organizations might not prefer to perform a change if the change is not going to bring a lift as desired.If you are working with a sample dataset, but you are willing to understand the population behavior you can include resampling methods in your analysis. You can read my article Resampling Methods for Inference Analysis (attached below) to learn more ⚡"
},
{
"code": null,
"e": 15881,
"s": 15677,
"text": "To design a robust experiment, it is highly recommended to decide metrics for invariant checking. These metrics shouldn’t change between control and experiment groups and can be used for sanity checking."
},
{
"code": null,
"e": 16254,
"s": 15881,
"text": "What is important in an A/B test is to define the sample size for the experiment and control groups that represent the overall population. While doing this, we need to pay attention to two things: randomness and representativeness. Randomness of the sample is necessary to reach unbiased results and representativeness is necessary to capture all different user behaviors."
},
{
"code": null,
"e": 16345,
"s": 16254,
"text": "Online tools can be used to calculate the required minimum sample size for the experiment."
},
{
"code": null,
"e": 16637,
"s": 16345,
"text": "Before running the experiment, it would be better to decide the desired lift value. Sometimes even the test result is statistically significant, it might not be practically significant. Organizations might not prefer to perform a change if the change is not going to bring a lift as desired."
},
{
"code": null,
"e": 16889,
"s": 16637,
"text": "If you are working with a sample dataset, but you are willing to understand the population behavior you can include resampling methods in your analysis. You can read my article Resampling Methods for Inference Analysis (attached below) to learn more ⚡"
},
{
"code": null,
"e": 16912,
"s": 16889,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 16971,
"s": 16912,
"text": "I hope you enjoyed reading the article and find it useful!"
},
{
"code": null,
"e": 17114,
"s": 16971,
"text": "If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨"
}
] |
Travelling Salesman Problem
|
One sales-person is in a city, he has to visit all other cities those are listed, the cost of traveling from one city to another city is also provided. Find the route where the cost is minimum to visit all of the cities once and return back to his starting city.
The graph must be complete for this case, so the sales-person can go from any city to any city directly.
Here we have to find minimum weighted Hamiltonian Cycle.
Input:
Cost matrix of the matrix.
0 20 42 25 30
20 0 30 34 15
42 30 0 10 10
25 34 10 0 25
30 15 10 25 0
Output:
Distance of Travelling Salesman: 80
travellingSalesman (mask, pos)
There is a table dp, and VISIT_ALL value to mark all nodes are visited
Input − mask value for masking some cities, position.
Output minus; Find the shortest route to visit all the cities.
Begin
if mask = VISIT_ALL, then //when all cities are visited
return cost[pos, 0]
if dp[mask, pos] ≠ -1, then
return dp[mask, pos]
finalCost := ∞
for all cities i, do
tempMask := (shift 1 left side i times)
if mask AND tempMask = 0, then
tempCpst := cost[pos, i] +
travellingSalesman(mask OR tempMask, i)
finalCost := minimum of finalCost and tempCost
done
dp[mask, pos] = finalCost
return finalCost
End
#include<iostream>
#define CITY 5
#define INF 9999
using namespace std;
int cost[CITY][CITY] = {
{0, 20, 42, 25, 30},
{20, 0, 30, 34, 15},
{42, 30, 0, 10, 10},
{25, 34, 10, 0, 25},
{30, 15, 10, 25, 0}
};
int VISIT_ALL = (1 << CITY) - 1;
int dp[16][4]; //make array of size (2^n, n)
int travellingSalesman(int mask, int pos) {
if(mask == VISIT_ALL) //when all cities are marked as visited
return cost[pos][0]; //from current city to origin
if(dp[mask][pos] != -1) //when it is considered
return dp[mask][pos];
int finalCost = INF;
for(int i = 0; i<CITY; i++) {
if((mask & (1 << i)) == 0) { //if the ith bit of the result is 0, then it is unvisited
int tempCost = cost[pos][i] + travellingSalesman(mask | (1 << i), i); //as ith city is visited
finalCost = min(finalCost, tempCost);
}
}
return dp[mask][pos] = finalCost;
}
int main() {
int row = (1 << CITY), col = CITY;
for(int i = 0; i<row; i++)
for(int j = 0; j<col; j++)
dp[i][j] = -1; //initialize dp array to -1
cout << "Distance of Travelling Salesman: ";
cout <<travellingSalesman(1, 0); //initially mask is 0001, as 0th city already visited
}
Distance of Travelling Salesman: 80
|
[
{
"code": null,
"e": 1325,
"s": 1062,
"text": "One sales-person is in a city, he has to visit all other cities those are listed, the cost of traveling from one city to another city is also provided. Find the route where the cost is minimum to visit all of the cities once and return back to his starting city."
},
{
"code": null,
"e": 1430,
"s": 1325,
"text": "The graph must be complete for this case, so the sales-person can go from any city to any city directly."
},
{
"code": null,
"e": 1487,
"s": 1430,
"text": "Here we have to find minimum weighted Hamiltonian Cycle."
},
{
"code": null,
"e": 1641,
"s": 1487,
"text": "Input:\nCost matrix of the matrix.\n0 20 42 25 30\n20 0 30 34 15\n42 30 0 10 10\n25 34 10 0 25\n30 15 10 25 0\n\nOutput:\nDistance of Travelling Salesman: 80"
},
{
"code": null,
"e": 1672,
"s": 1641,
"text": "travellingSalesman (mask, pos)"
},
{
"code": null,
"e": 1743,
"s": 1672,
"text": "There is a table dp, and VISIT_ALL value to mark all nodes are visited"
},
{
"code": null,
"e": 1797,
"s": 1743,
"text": "Input − mask value for masking some cities, position."
},
{
"code": null,
"e": 1860,
"s": 1797,
"text": "Output minus; Find the shortest route to visit all the cities."
},
{
"code": null,
"e": 2339,
"s": 1860,
"text": "Begin\n if mask = VISIT_ALL, then //when all cities are visited\n return cost[pos, 0]\n if dp[mask, pos] ≠ -1, then\n return dp[mask, pos]\n finalCost := ∞\n\n for all cities i, do\n tempMask := (shift 1 left side i times)\n if mask AND tempMask = 0, then\n tempCpst := cost[pos, i] +\n travellingSalesman(mask OR tempMask, i)\n finalCost := minimum of finalCost and tempCost\n done\n\n dp[mask, pos] = finalCost\n return finalCost\nEnd"
},
{
"code": null,
"e": 3632,
"s": 2339,
"text": "#include<iostream>\n#define CITY 5\n#define INF 9999\nusing namespace std;\n\nint cost[CITY][CITY] = {\n {0, 20, 42, 25, 30},\n {20, 0, 30, 34, 15},\n {42, 30, 0, 10, 10},\n {25, 34, 10, 0, 25},\n {30, 15, 10, 25, 0}\n};\n \nint VISIT_ALL = (1 << CITY) - 1;\n\nint dp[16][4]; //make array of size (2^n, n)\n\nint travellingSalesman(int mask, int pos) {\n if(mask == VISIT_ALL) //when all cities are marked as visited\n return cost[pos][0]; //from current city to origin\n \n if(dp[mask][pos] != -1) //when it is considered\n return dp[mask][pos];\n \n int finalCost = INF;\n \n for(int i = 0; i<CITY; i++) {\n if((mask & (1 << i)) == 0) { //if the ith bit of the result is 0, then it is unvisited\n int tempCost = cost[pos][i] + travellingSalesman(mask | (1 << i), i); //as ith city is visited\n finalCost = min(finalCost, tempCost);\n }\n }\n return dp[mask][pos] = finalCost;\n}\n\nint main() { \n int row = (1 << CITY), col = CITY;\n for(int i = 0; i<row; i++)\n for(int j = 0; j<col; j++)\n dp[i][j] = -1; //initialize dp array to -1\n cout << \"Distance of Travelling Salesman: \"; \n cout <<travellingSalesman(1, 0); //initially mask is 0001, as 0th city already visited\n}"
},
{
"code": null,
"e": 3668,
"s": 3632,
"text": "Distance of Travelling Salesman: 80"
}
] |
Fuzzy Search in JavaScript - GeeksforGeeks
|
05 Nov, 2020
Fuzzy searching matches the meaning, not necessarily the precise wording or specified phrases. It performs something the same as full-text search against data to see likely misspellings and approximate string matching. it’s a very powerful tool that takes into consideration the context of the phrase you wish to look.
Fuzzy Search is additionally called as approximate string matching. It’s powerful because often text data is messy. For instance, shorthand and abbreviated text are common in various sorts of data. Additionally, outputs from OCR or voice to text conversions tend to be messy or imperfect. Thus, we want to make the foremost of our data by extrapolating the maximum amount of information as possible.
Fuzzy search is more powerful than exact searching when used for research and investigation. Fuzzy search is very useful when researching unfamiliar, foreign-language, or sophisticated terms, the correct spellings of which don’t seem to be widely known. Fuzzy search can also be used to locate individuals supported incomplete or partially inaccurate identifying information.
Installing the package:
$ npm install --save fuse.js
Example:
Javascript
const Fuse = require('fuse.js')
const people = [
{
name: "John",
city: "New York"
},
{
name: "Steve",
city: "Seattle"
},
{
name: "Bill",
city: "Omaha"
}
]
const fuse = new Fuse(people, {
keys: ['name', 'city']
})
// Search
const result = fuse.search('jon')
console.log(result)
Output:
[ { item: { name: 'John', city: 'New York' }, refIndex: 0 } ]
Some common fuzzy search libraries for JavaScript are:
List.js : https://listjs.com/
Fuse.js : https://fusejs.io/
Fuzzy-search :https://www.npmjs.com/package/fuzzy-search
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24981,
"s": 24950,
"text": " \n05 Nov, 2020\n"
},
{
"code": null,
"e": 25300,
"s": 24981,
"text": "Fuzzy searching matches the meaning, not necessarily the precise wording or specified phrases. It performs something the same as full-text search against data to see likely misspellings and approximate string matching. it’s a very powerful tool that takes into consideration the context of the phrase you wish to look."
},
{
"code": null,
"e": 25700,
"s": 25300,
"text": "Fuzzy Search is additionally called as approximate string matching. It’s powerful because often text data is messy. For instance, shorthand and abbreviated text are common in various sorts of data. Additionally, outputs from OCR or voice to text conversions tend to be messy or imperfect. Thus, we want to make the foremost of our data by extrapolating the maximum amount of information as possible."
},
{
"code": null,
"e": 26076,
"s": 25700,
"text": "Fuzzy search is more powerful than exact searching when used for research and investigation. Fuzzy search is very useful when researching unfamiliar, foreign-language, or sophisticated terms, the correct spellings of which don’t seem to be widely known. Fuzzy search can also be used to locate individuals supported incomplete or partially inaccurate identifying information."
},
{
"code": null,
"e": 26100,
"s": 26076,
"text": "Installing the package:"
},
{
"code": null,
"e": 26129,
"s": 26100,
"text": "$ npm install --save fuse.js"
},
{
"code": null,
"e": 26138,
"s": 26129,
"text": "Example:"
},
{
"code": null,
"e": 26149,
"s": 26138,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\nconst Fuse = require('fuse.js')\n \nconst people = [\n {\n name: \"John\",\n city: \"New York\"\n },\n {\n name: \"Steve\",\n city: \"Seattle\"\n },\n {\n name: \"Bill\",\n city: \"Omaha\"\n }\n]\n \nconst fuse = new Fuse(people, {\n keys: ['name', 'city']\n})\n \n// Search\nconst result = fuse.search('jon')\n \nconsole.log(result)\n\n\n\n\n\n",
"e": 26533,
"s": 26159,
"text": null
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26541,
"text": "[ { item: { name: 'John', city: 'New York' }, refIndex: 0 } ]\n"
},
{
"code": null,
"e": 26659,
"s": 26604,
"text": "Some common fuzzy search libraries for JavaScript are:"
},
{
"code": null,
"e": 26689,
"s": 26659,
"text": "List.js : https://listjs.com/"
},
{
"code": null,
"e": 26718,
"s": 26689,
"text": "Fuse.js : https://fusejs.io/"
},
{
"code": null,
"e": 26775,
"s": 26718,
"text": "Fuzzy-search :https://www.npmjs.com/package/fuzzy-search"
},
{
"code": null,
"e": 26793,
"s": 26775,
"text": "\nJavaScript-Misc\n"
},
{
"code": null,
"e": 26806,
"s": 26793,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 26825,
"s": 26806,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 27030,
"s": 26825,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27091,
"s": 27030,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27132,
"s": 27091,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27172,
"s": 27132,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27226,
"s": 27172,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27288,
"s": 27226,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27344,
"s": 27288,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27377,
"s": 27344,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27439,
"s": 27377,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27482,
"s": 27439,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to query and calculate Google Universal Analytics data in BigQuery | by Johan van de Werken | Towards Data Science
|
When I first started querying Google Analytics data in BigQuery, I had a hard time interpreting the ‘raw’ hit-level data hiding in the ga_sessions_ export tables. Because I could not find a noob-proof guide on how to calculate Google Analytics metrics in BigQuery, I decided to write one myself. I provide lots of example queries so you don’t have to reinvent the wheel and hopefully you can save yourself some valuable time.
Update: do you enjoy this article? Then you’ll also like my new website GA4BigQuery.com: a digital guide with tips, ideas, example queries and tutorials on how to query Google Analytics data in BigQuery & rock your digital marketing analytics.
I’ve migrated most example queries from this article to the new website, as it is easier to maintain all content in one place. This article will stay online to refer you to the right place.
I also published an article about querying Google Analytics 4 (previously App + Web) event data in BigQuery. This content will be migrated to GA4BigQuery.com too.
– Introduction to Google Analytics data in BigQuery– Multiple tables– User– Session– Time– Traffic Sources– Geo Network– Platform or Device– Page Tracking– Event Tracking– Goal Conversions– (Enhanced) Ecommerce (transactions)– Ecommerce (products)– Enhanced Ecommerce (products)– Custom Dimensions & Custom Metrics– Custom Channel Grouping– Intraday table– Realtime tables & view
For those of you wondering why you should use BigQuery to analyze Google Analytics data anyway, read this excellent piece. Some big advantages:
No more sampling. Ever.
Unlimited amount of dimensions
Combining different scopes in one report (not for the faint of heart!)
Calculate goal completions, build your own Channel Grouping and correct data errors, all on past data
Combine Google Analytics data with third party data sources
But let’s not become too excited. Truth is that diving into BigQuery can be quite frustrating, once you figure out a lot of the Google Analytics metrics you are used to are nowhere to be found.
What makes BigQuery interesting for Google Analytics users, specifically Premium customers, is that Google can dump raw Google Analytics data into BigQuery daily. While this enables many types of analysis that can’t be performed within the Google Analytics interface, it also doesn’t provide any basic metrics, e.g. bounce rate, to use. (source)
There are two sides to this: the tough part is that I had to calculate every ‘missing’ Google Analytics metric in my queries. The positive effect: my understanding of the metrics on a conceptual level improved considerably.
The BigQuery cookbook helped me out in some cases, but also seemed incomplete and outdated at times. Since Standard SQL syntax is the preferred BigQuery language nowadays and a lot of old Stackoverflow entries are using the (soon to be deprecated?) Legacy SQL syntax, I spent hours and hours to get my head around the SQL queries I had to write to get the reports I wanted. Apart from the calculated metrics that I needed to take care of, there was another hurdle to cross: nested and repeated fields.
Each row in the Google Analytics BigQuery dump represents a single session and contains many fields, some of which can be repeated and nested, such as the hits, which contains a repeated set of fields within it representing the page views and events during the session, and custom dimensions, which is a single, repeated field . This is one of the main differences between BigQuery and a normal database. (source)
With this article I hope to save you some trouble. I will show you how to create basic reports on session and user level and later on I will show some examples of more advanced queries that involve hit-level data (events, pageviews), combining multiple custom dimensions with different scopes, handling (enhanced) ecommerce data and joining historical data with realtime or intraday data.
No Google Cloud Billing account? Enter the BigQuery Sandbox, which allows you to use the BigQuery web UI without enabling a billing account. To set up a Google Analytics to BigQuery export you need Google Analytics 360 (part of the Google Marketing Platform).
I assume you have a basic understanding of SQL as a querying language and BigQuery as a database tool. If not, I suggest you follow a SQL introduction course first, as I will not go into details about the SQL syntax, but will focus on how to get your (custom) Google Analytics reports out of BigQuery for analysing purposes. All query examples are in Standard SQL.
In this article we will use the Google Analytics Sample dataset for BigQuery, which contains analytics data from the Google Merchandise Store.
However, I recommend you use your own Google Analytics dataset if you want to compare the results of your queries with Google Analytics, because I’ve noticed differences between the Google Merchandise Store data in Google Analytics and the sample BigQuery dataset. I tested the queries on other Google Analytics-accounts and they matched quite well.
To get a good understanding of the ga_sessions_ table in BigQuery, let’s take a look at the BigQuery Export schema, which gives us an idea of the available raw Google Analytics data fields in BigQuery.
Although you probably will recognize a lot of dimensions and metrics from the Google Analytics UI, I know this schema can be a bit overwhelming. To get a better understanding of our data set, we have to know the structure of the (nested) fields. The next picture represents two rows (= 2 sessions) from a ga_sessions_ table.
As you can see our trouble starts if you need custom dimensions, custom metrics or any data on hit-level: i.e. events, pageviews or product data. Let’s query our nested sample set:
SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20170801`LIMIT 2
This gives us 2 rows, which represented as a flat table would look like this:
Remember, only row 2 and 14 in this example are real rows in our table. The other ‘rows’ are in fact nested fields, in most cases NULL values. Only the hits.product columns are populated with values.
To deal with this fields and to be able to query our tables so they meet our needs, we need the UNNEST function.
The problem here is that is essentially an array (actually in BigQuery parlance it’s a “repeated record”, but you can think of it as an array). (...) This is where the UNNEST function comes in. It basically lets you take elements in an array and expand each one of these individual elements. You can then join your original row against each unnested element to add them to your table. (source)
I highly recommend reading this article which explains the UNNEST concept in detail with the Firebase Analytics sample data set as an example.
You only have to UNNEST records that contain ‘repeated fields’. In case of our Google Analytics data set these could involve:
customDimensions
hits
hits.customDimensions
hits.customMetrics
hits.product
hits.product.customDimensions
hits.product.customMetrics
To make sure you understand the structure of the BigQuery export schema, I encourage you to take look at this interactive visual representation.
OK. Enough theoretical blabber. Ready for some action? Let’s query!
Return to table of contents
Google Analytics data in BigQuery is stored per day in a table. If you only need data from one day the FROM clause in your query will look like this:
SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20160801`
In most cases you will need to query a larger period of time. Enter _table_suffix. More details here, but to query multiple tables of Google Analytics data you only need these examples. Note that you can combine static and dynamic dates or use only static dates or just dynamic dates for a rolling period, for the last 90 days or so. It is also possible to include the intraday table in your query.
When you perform an analysis on a static data range you should use fixed start and end dates. In this example we select August 1st 2016 to August 1st 2017.
SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN '20160801' AND '20170801'
In this example we select period today-30 days to yesterday.
SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)) AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
We know we have 366 day tables in our data set, so we could use a fixed end date here (20170801), but usually I prefer a combination of a fixed start date and a dynamic end date (in this case: today minus one). If new data is added to our data set it is automatically included in our query. In this example we select August 1st 2016 to yesterday.
SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN '20160801' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
User TypeCount of Sessions
UsersNew Users% New SessionsNumber of Sessions per UserHits
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the # comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
-
SessionsBouncesBounce RateAvg. Session Duration
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
DateYearISO YearMonth of YearMonth of the yearWeek of YearWeek of the YearISO Week of the YearISO Week of ISO YearDay of the monthDay of WeekDay of Week NameHourMinuteHour of DayDate Hour and Minute
-
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Referral PathFull ReferrerDefault Channel GroupingCampaignSourceMediumSource / MediumKeywordAd ContentSocial NetworkSocial Source ReferralCampaign Code
-
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
ContinentSub ContinentCountryRegionMetroCityLatitudeLongitudeNetwork DomainService ProviderCity ID
-
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
BrowserBrowser VersionOperating SystemOperating System VersionMobile Device BrandingMobile Device ModelMobile Input SelectorMobile Device InfoMobile Device Marketing NameDevice CategoryBrowser SizeData Source
-
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
HostnamePagePrevious Page PathPage path level 1Page path level 2Page path level 3Page path level 4Page TitleLanding PageSecond PageExit Page
EntrancesPageviewsUnique PageviewsPages / SessionExits% ExitAvg. Time on Page
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Event CategoryEvent ActionEvent Label
Total EventsUnique EventsEvent ValueAvg. ValueSessions with EventEvents / Session with Event
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Goal Completion LocationGoal Previous Step-1Goal Previous Step-2Goal Previous Step-3
Goal XX Completions
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Transaction ID
TransactionsEcommerce Conversion RateRevenueAvg. Order ValuePer Session ValueShippingTaxRevenue per UserTransactions per User
www.ga4bigquery.com
Return to table of contents
When entering the product scope you have to verify if enhanced ecommerce is enabled in Google Analytics. If so, you’re safe to use the hits.product fields. If only ‘standard’ ecommerce is measured: use the hits.item fields.
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Product SKUProductProduct Category
QuantityUnique PurchasesAvg. PriceProduct RevenueAvg. QTY
www.ga4bigquery.com
Return to table of contents
When entering the product scope you have to verify if enhanced ecommerce is enabled in Google Analytics. If so, you’re safe to use the hits.product fields. If only ‘standard’ ecommerce is measured: use the hits.item fields.
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Product SKUProductProduct Category (Enhanced Ecommerce)Product BrandProduct Variant
QuantityUnique PurchasesProduct RevenueAvg. PriceAvg. QTYBuy-to-Detail RateCart-to-Detail RateProduct Adds To CartProduct CheckoutsProduct Detail ViewsProduct RefundsProduct Removes From CartRefund Amount
www.ga4bigquery.com
Return to table of contents
This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the # comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly.
Custom Dimension XX (User)Custom Dimension XX (Session)Custom Dimension XX (Hit)Custom Dimension XX (Product)
Custom Metric XX Value (Hit)Custom Metric XX Value (Product)
www.ga4bigquery.com
Return to table of contents
If you need the Default Channel Grouping, just use the channelGrouping dimension. However, there can be various reasons to build your own Channel Grouping. When you use intraday data, for instance, as the channelGrouping dimension is not available there. Or when you need to ‘repair’ data quality issues on historical data, as this is not possible with the Default Channel Grouping dimension in the Google Analytics UI.
I will show you how you can mirror the standard Google Analytics definitions of the Default Channel Grouping in BigQuery. If you use this query as a starting point it’s not so difficult anymore to create your own custom or Default Channel Grouping.
www.ga4bigquery.com
Return to table of contents
For every Google Analytics view that is exported to BigQuery, a ga_sessions_intraday_ table will be exported multiple times a day as well. Let’s see how this works:
Within each dataset, a table is imported for each day of export. Daily tables have the format “ga_sessions_YYYYMMDD”.
Intraday data is imported approximately three times a day. Intraday tables have the format “ga_sessions_intraday_YYYYMMDD”. During the same day, each import of intraday data overwrites the previous import in the same table.
When the daily import is complete, the intraday table from the previous day is deleted. For the current day, until the first intraday import, there is no intraday table. If an intraday-table write fails, then the previous day’s intraday table is preserved.
Data for the current day is not final until the daily import is complete. You may notice differences between intraday and daily data based on active user sessions that cross the time boundary of last intraday import. (source)
The easiest way to include intraday data in your query as well as historical data is use the wildcard in combination with a wider _table_suffix filter. With this condition it will include any table in the data set that starts with ga_sessions_ and contains a date with the format YYYYMMDD.
Note: make sure your data set doesn’t contain any other tables with a title that starts with ga_sessions_!
www.ga4bigquery.com
Return to table of contents
If you don’t see an intraday table, but realtime tables and view, streaming export is enabled for your Google Analytics view. To query this data and join this with historical data from the ga_sessions_ tables, another approach is needed.
For each day, streaming export creates 1 new table and 1 (BigQuery) view of that table:
Table: ga_realtime_sessions_YYYYMMDD is an internal staging table that includes all records of sessions for all activity that took place during the day. Data is exported continuously approximately every 15 minutes. Within this table are multiple records of a session when the session spans multiple export operations.
The ga_realtime_sessions_YYYYMMDD tables should not be used (and are not supported by Google Analytics technical support) for queries. Queries on these tables may yield unexpected results as they may contain duplicate records of some sessions. Query the ga_realtime_sessions_view_YYYYMMDD view instead.
View: ga_realtime_sessions_view_YYYYMMDD sits on top of the exported tables and is there to deduplicate multiple records of repeated sessions that exist across export boundaries. Query this table for deduplicated streaming data. (source)
At the time of writing this daily generated realtime view is only queryable with Legacy SQL. Any Standard SQL query will result in this error:
To be able to use Standard SQL, we have to create our own realtime view.
www.ga4bigquery.com
Return to table of contents
No rights reserved
by the author.
|
[
{
"code": null,
"e": 598,
"s": 172,
"text": "When I first started querying Google Analytics data in BigQuery, I had a hard time interpreting the ‘raw’ hit-level data hiding in the ga_sessions_ export tables. Because I could not find a noob-proof guide on how to calculate Google Analytics metrics in BigQuery, I decided to write one myself. I provide lots of example queries so you don’t have to reinvent the wheel and hopefully you can save yourself some valuable time."
},
{
"code": null,
"e": 842,
"s": 598,
"text": "Update: do you enjoy this article? Then you’ll also like my new website GA4BigQuery.com: a digital guide with tips, ideas, example queries and tutorials on how to query Google Analytics data in BigQuery & rock your digital marketing analytics."
},
{
"code": null,
"e": 1032,
"s": 842,
"text": "I’ve migrated most example queries from this article to the new website, as it is easier to maintain all content in one place. This article will stay online to refer you to the right place."
},
{
"code": null,
"e": 1195,
"s": 1032,
"text": "I also published an article about querying Google Analytics 4 (previously App + Web) event data in BigQuery. This content will be migrated to GA4BigQuery.com too."
},
{
"code": null,
"e": 1575,
"s": 1195,
"text": "– Introduction to Google Analytics data in BigQuery– Multiple tables– User– Session– Time– Traffic Sources– Geo Network– Platform or Device– Page Tracking– Event Tracking– Goal Conversions– (Enhanced) Ecommerce (transactions)– Ecommerce (products)– Enhanced Ecommerce (products)– Custom Dimensions & Custom Metrics– Custom Channel Grouping– Intraday table– Realtime tables & view"
},
{
"code": null,
"e": 1719,
"s": 1575,
"text": "For those of you wondering why you should use BigQuery to analyze Google Analytics data anyway, read this excellent piece. Some big advantages:"
},
{
"code": null,
"e": 1743,
"s": 1719,
"text": "No more sampling. Ever."
},
{
"code": null,
"e": 1774,
"s": 1743,
"text": "Unlimited amount of dimensions"
},
{
"code": null,
"e": 1845,
"s": 1774,
"text": "Combining different scopes in one report (not for the faint of heart!)"
},
{
"code": null,
"e": 1947,
"s": 1845,
"text": "Calculate goal completions, build your own Channel Grouping and correct data errors, all on past data"
},
{
"code": null,
"e": 2007,
"s": 1947,
"text": "Combine Google Analytics data with third party data sources"
},
{
"code": null,
"e": 2201,
"s": 2007,
"text": "But let’s not become too excited. Truth is that diving into BigQuery can be quite frustrating, once you figure out a lot of the Google Analytics metrics you are used to are nowhere to be found."
},
{
"code": null,
"e": 2547,
"s": 2201,
"text": "What makes BigQuery interesting for Google Analytics users, specifically Premium customers, is that Google can dump raw Google Analytics data into BigQuery daily. While this enables many types of analysis that can’t be performed within the Google Analytics interface, it also doesn’t provide any basic metrics, e.g. bounce rate, to use. (source)"
},
{
"code": null,
"e": 2771,
"s": 2547,
"text": "There are two sides to this: the tough part is that I had to calculate every ‘missing’ Google Analytics metric in my queries. The positive effect: my understanding of the metrics on a conceptual level improved considerably."
},
{
"code": null,
"e": 3273,
"s": 2771,
"text": "The BigQuery cookbook helped me out in some cases, but also seemed incomplete and outdated at times. Since Standard SQL syntax is the preferred BigQuery language nowadays and a lot of old Stackoverflow entries are using the (soon to be deprecated?) Legacy SQL syntax, I spent hours and hours to get my head around the SQL queries I had to write to get the reports I wanted. Apart from the calculated metrics that I needed to take care of, there was another hurdle to cross: nested and repeated fields."
},
{
"code": null,
"e": 3687,
"s": 3273,
"text": "Each row in the Google Analytics BigQuery dump represents a single session and contains many fields, some of which can be repeated and nested, such as the hits, which contains a repeated set of fields within it representing the page views and events during the session, and custom dimensions, which is a single, repeated field . This is one of the main differences between BigQuery and a normal database. (source)"
},
{
"code": null,
"e": 4076,
"s": 3687,
"text": "With this article I hope to save you some trouble. I will show you how to create basic reports on session and user level and later on I will show some examples of more advanced queries that involve hit-level data (events, pageviews), combining multiple custom dimensions with different scopes, handling (enhanced) ecommerce data and joining historical data with realtime or intraday data."
},
{
"code": null,
"e": 4336,
"s": 4076,
"text": "No Google Cloud Billing account? Enter the BigQuery Sandbox, which allows you to use the BigQuery web UI without enabling a billing account. To set up a Google Analytics to BigQuery export you need Google Analytics 360 (part of the Google Marketing Platform)."
},
{
"code": null,
"e": 4701,
"s": 4336,
"text": "I assume you have a basic understanding of SQL as a querying language and BigQuery as a database tool. If not, I suggest you follow a SQL introduction course first, as I will not go into details about the SQL syntax, but will focus on how to get your (custom) Google Analytics reports out of BigQuery for analysing purposes. All query examples are in Standard SQL."
},
{
"code": null,
"e": 4844,
"s": 4701,
"text": "In this article we will use the Google Analytics Sample dataset for BigQuery, which contains analytics data from the Google Merchandise Store."
},
{
"code": null,
"e": 5194,
"s": 4844,
"text": "However, I recommend you use your own Google Analytics dataset if you want to compare the results of your queries with Google Analytics, because I’ve noticed differences between the Google Merchandise Store data in Google Analytics and the sample BigQuery dataset. I tested the queries on other Google Analytics-accounts and they matched quite well."
},
{
"code": null,
"e": 5396,
"s": 5194,
"text": "To get a good understanding of the ga_sessions_ table in BigQuery, let’s take a look at the BigQuery Export schema, which gives us an idea of the available raw Google Analytics data fields in BigQuery."
},
{
"code": null,
"e": 5721,
"s": 5396,
"text": "Although you probably will recognize a lot of dimensions and metrics from the Google Analytics UI, I know this schema can be a bit overwhelming. To get a better understanding of our data set, we have to know the structure of the (nested) fields. The next picture represents two rows (= 2 sessions) from a ga_sessions_ table."
},
{
"code": null,
"e": 5902,
"s": 5721,
"text": "As you can see our trouble starts if you need custom dimensions, custom metrics or any data on hit-level: i.e. events, pageviews or product data. Let’s query our nested sample set:"
},
{
"code": null,
"e": 5993,
"s": 5902,
"text": "SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20170801`LIMIT 2"
},
{
"code": null,
"e": 6071,
"s": 5993,
"text": "This gives us 2 rows, which represented as a flat table would look like this:"
},
{
"code": null,
"e": 6271,
"s": 6071,
"text": "Remember, only row 2 and 14 in this example are real rows in our table. The other ‘rows’ are in fact nested fields, in most cases NULL values. Only the hits.product columns are populated with values."
},
{
"code": null,
"e": 6384,
"s": 6271,
"text": "To deal with this fields and to be able to query our tables so they meet our needs, we need the UNNEST function."
},
{
"code": null,
"e": 6778,
"s": 6384,
"text": "The problem here is that is essentially an array (actually in BigQuery parlance it’s a “repeated record”, but you can think of it as an array). (...) This is where the UNNEST function comes in. It basically lets you take elements in an array and expand each one of these individual elements. You can then join your original row against each unnested element to add them to your table. (source)"
},
{
"code": null,
"e": 6921,
"s": 6778,
"text": "I highly recommend reading this article which explains the UNNEST concept in detail with the Firebase Analytics sample data set as an example."
},
{
"code": null,
"e": 7047,
"s": 6921,
"text": "You only have to UNNEST records that contain ‘repeated fields’. In case of our Google Analytics data set these could involve:"
},
{
"code": null,
"e": 7064,
"s": 7047,
"text": "customDimensions"
},
{
"code": null,
"e": 7069,
"s": 7064,
"text": "hits"
},
{
"code": null,
"e": 7091,
"s": 7069,
"text": "hits.customDimensions"
},
{
"code": null,
"e": 7110,
"s": 7091,
"text": "hits.customMetrics"
},
{
"code": null,
"e": 7123,
"s": 7110,
"text": "hits.product"
},
{
"code": null,
"e": 7153,
"s": 7123,
"text": "hits.product.customDimensions"
},
{
"code": null,
"e": 7180,
"s": 7153,
"text": "hits.product.customMetrics"
},
{
"code": null,
"e": 7325,
"s": 7180,
"text": "To make sure you understand the structure of the BigQuery export schema, I encourage you to take look at this interactive visual representation."
},
{
"code": null,
"e": 7393,
"s": 7325,
"text": "OK. Enough theoretical blabber. Ready for some action? Let’s query!"
},
{
"code": null,
"e": 7421,
"s": 7393,
"text": "Return to table of contents"
},
{
"code": null,
"e": 7571,
"s": 7421,
"text": "Google Analytics data in BigQuery is stored per day in a table. If you only need data from one day the FROM clause in your query will look like this:"
},
{
"code": null,
"e": 7654,
"s": 7571,
"text": "SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20160801`"
},
{
"code": null,
"e": 8053,
"s": 7654,
"text": "In most cases you will need to query a larger period of time. Enter _table_suffix. More details here, but to query multiple tables of Google Analytics data you only need these examples. Note that you can combine static and dynamic dates or use only static dates or just dynamic dates for a rolling period, for the last 90 days or so. It is also possible to include the intraday table in your query."
},
{
"code": null,
"e": 8209,
"s": 8053,
"text": "When you perform an analysis on a static data range you should use fixed start and end dates. In this example we select August 1st 2016 to August 1st 2017."
},
{
"code": null,
"e": 8340,
"s": 8209,
"text": "SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN '20160801' AND '20170801'"
},
{
"code": null,
"e": 8401,
"s": 8340,
"text": "In this example we select period today-30 days to yesterday."
},
{
"code": null,
"e": 8637,
"s": 8401,
"text": "SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)) AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))"
},
{
"code": null,
"e": 8984,
"s": 8637,
"text": "We know we have 366 day tables in our data set, so we could use a fixed end date here (20170801), but usually I prefer a combination of a fixed start date and a dynamic end date (in this case: today minus one). If new data is added to our data set it is automatically included in our query. In this example we select August 1st 2016 to yesterday."
},
{
"code": null,
"e": 9167,
"s": 8984,
"text": "SELECT *FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`WHERE _table_suffix BETWEEN '20160801' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))"
},
{
"code": null,
"e": 9195,
"s": 9167,
"text": "Return to table of contents"
},
{
"code": null,
"e": 9569,
"s": 9195,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 9596,
"s": 9569,
"text": "User TypeCount of Sessions"
},
{
"code": null,
"e": 9656,
"s": 9596,
"text": "UsersNew Users% New SessionsNumber of Sessions per UserHits"
},
{
"code": null,
"e": 9676,
"s": 9656,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 9704,
"s": 9676,
"text": "Return to table of contents"
},
{
"code": null,
"e": 10077,
"s": 9704,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the # comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 10079,
"s": 10077,
"text": "-"
},
{
"code": null,
"e": 10127,
"s": 10079,
"text": "SessionsBouncesBounce RateAvg. Session Duration"
},
{
"code": null,
"e": 10147,
"s": 10127,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10175,
"s": 10147,
"text": "Return to table of contents"
},
{
"code": null,
"e": 10549,
"s": 10175,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 10748,
"s": 10549,
"text": "DateYearISO YearMonth of YearMonth of the yearWeek of YearWeek of the YearISO Week of the YearISO Week of ISO YearDay of the monthDay of WeekDay of Week NameHourMinuteHour of DayDate Hour and Minute"
},
{
"code": null,
"e": 10750,
"s": 10748,
"text": "-"
},
{
"code": null,
"e": 10770,
"s": 10750,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10798,
"s": 10770,
"text": "Return to table of contents"
},
{
"code": null,
"e": 11172,
"s": 10798,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 11324,
"s": 11172,
"text": "Referral PathFull ReferrerDefault Channel GroupingCampaignSourceMediumSource / MediumKeywordAd ContentSocial NetworkSocial Source ReferralCampaign Code"
},
{
"code": null,
"e": 11326,
"s": 11324,
"text": "-"
},
{
"code": null,
"e": 11346,
"s": 11326,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 11374,
"s": 11346,
"text": "Return to table of contents"
},
{
"code": null,
"e": 11748,
"s": 11374,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 11847,
"s": 11748,
"text": "ContinentSub ContinentCountryRegionMetroCityLatitudeLongitudeNetwork DomainService ProviderCity ID"
},
{
"code": null,
"e": 11849,
"s": 11847,
"text": "-"
},
{
"code": null,
"e": 11869,
"s": 11849,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 11897,
"s": 11869,
"text": "Return to table of contents"
},
{
"code": null,
"e": 12271,
"s": 11897,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 12480,
"s": 12271,
"text": "BrowserBrowser VersionOperating SystemOperating System VersionMobile Device BrandingMobile Device ModelMobile Input SelectorMobile Device InfoMobile Device Marketing NameDevice CategoryBrowser SizeData Source"
},
{
"code": null,
"e": 12482,
"s": 12480,
"text": "-"
},
{
"code": null,
"e": 12502,
"s": 12482,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 12530,
"s": 12502,
"text": "Return to table of contents"
},
{
"code": null,
"e": 12904,
"s": 12530,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 13045,
"s": 12904,
"text": "HostnamePagePrevious Page PathPage path level 1Page path level 2Page path level 3Page path level 4Page TitleLanding PageSecond PageExit Page"
},
{
"code": null,
"e": 13123,
"s": 13045,
"text": "EntrancesPageviewsUnique PageviewsPages / SessionExits% ExitAvg. Time on Page"
},
{
"code": null,
"e": 13143,
"s": 13123,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 13171,
"s": 13143,
"text": "Return to table of contents"
},
{
"code": null,
"e": 13545,
"s": 13171,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 13583,
"s": 13545,
"text": "Event CategoryEvent ActionEvent Label"
},
{
"code": null,
"e": 13676,
"s": 13583,
"text": "Total EventsUnique EventsEvent ValueAvg. ValueSessions with EventEvents / Session with Event"
},
{
"code": null,
"e": 13696,
"s": 13676,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 13724,
"s": 13696,
"text": "Return to table of contents"
},
{
"code": null,
"e": 14098,
"s": 13724,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 14183,
"s": 14098,
"text": "Goal Completion LocationGoal Previous Step-1Goal Previous Step-2Goal Previous Step-3"
},
{
"code": null,
"e": 14203,
"s": 14183,
"text": "Goal XX Completions"
},
{
"code": null,
"e": 14223,
"s": 14203,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 14251,
"s": 14223,
"text": "Return to table of contents"
},
{
"code": null,
"e": 14625,
"s": 14251,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 14640,
"s": 14625,
"text": "Transaction ID"
},
{
"code": null,
"e": 14766,
"s": 14640,
"text": "TransactionsEcommerce Conversion RateRevenueAvg. Order ValuePer Session ValueShippingTaxRevenue per UserTransactions per User"
},
{
"code": null,
"e": 14786,
"s": 14766,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 14814,
"s": 14786,
"text": "Return to table of contents"
},
{
"code": null,
"e": 15038,
"s": 14814,
"text": "When entering the product scope you have to verify if enhanced ecommerce is enabled in Google Analytics. If so, you’re safe to use the hits.product fields. If only ‘standard’ ecommerce is measured: use the hits.item fields."
},
{
"code": null,
"e": 15412,
"s": 15038,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 15447,
"s": 15412,
"text": "Product SKUProductProduct Category"
},
{
"code": null,
"e": 15505,
"s": 15447,
"text": "QuantityUnique PurchasesAvg. PriceProduct RevenueAvg. QTY"
},
{
"code": null,
"e": 15525,
"s": 15505,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 15553,
"s": 15525,
"text": "Return to table of contents"
},
{
"code": null,
"e": 15777,
"s": 15553,
"text": "When entering the product scope you have to verify if enhanced ecommerce is enabled in Google Analytics. If so, you’re safe to use the hits.product fields. If only ‘standard’ ecommerce is measured: use the hits.item fields."
},
{
"code": null,
"e": 16151,
"s": 15777,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 16235,
"s": 16151,
"text": "Product SKUProductProduct Category (Enhanced Ecommerce)Product BrandProduct Variant"
},
{
"code": null,
"e": 16440,
"s": 16235,
"text": "QuantityUnique PurchasesProduct RevenueAvg. PriceAvg. QTYBuy-to-Detail RateCart-to-Detail RateProduct Adds To CartProduct CheckoutsProduct Detail ViewsProduct RefundsProduct Removes From CartRefund Amount"
},
{
"code": null,
"e": 16460,
"s": 16440,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 16488,
"s": 16460,
"text": "Return to table of contents"
},
{
"code": null,
"e": 16861,
"s": 16488,
"text": "This example query contains all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the # comments in the example query and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (in the FROM, WHERE, GROUP BY and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 16971,
"s": 16861,
"text": "Custom Dimension XX (User)Custom Dimension XX (Session)Custom Dimension XX (Hit)Custom Dimension XX (Product)"
},
{
"code": null,
"e": 17032,
"s": 16971,
"text": "Custom Metric XX Value (Hit)Custom Metric XX Value (Product)"
},
{
"code": null,
"e": 17052,
"s": 17032,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 17080,
"s": 17052,
"text": "Return to table of contents"
},
{
"code": null,
"e": 17500,
"s": 17080,
"text": "If you need the Default Channel Grouping, just use the channelGrouping dimension. However, there can be various reasons to build your own Channel Grouping. When you use intraday data, for instance, as the channelGrouping dimension is not available there. Or when you need to ‘repair’ data quality issues on historical data, as this is not possible with the Default Channel Grouping dimension in the Google Analytics UI."
},
{
"code": null,
"e": 17749,
"s": 17500,
"text": "I will show you how you can mirror the standard Google Analytics definitions of the Default Channel Grouping in BigQuery. If you use this query as a starting point it’s not so difficult anymore to create your own custom or Default Channel Grouping."
},
{
"code": null,
"e": 17769,
"s": 17749,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 17797,
"s": 17769,
"text": "Return to table of contents"
},
{
"code": null,
"e": 17962,
"s": 17797,
"text": "For every Google Analytics view that is exported to BigQuery, a ga_sessions_intraday_ table will be exported multiple times a day as well. Let’s see how this works:"
},
{
"code": null,
"e": 18080,
"s": 17962,
"text": "Within each dataset, a table is imported for each day of export. Daily tables have the format “ga_sessions_YYYYMMDD”."
},
{
"code": null,
"e": 18304,
"s": 18080,
"text": "Intraday data is imported approximately three times a day. Intraday tables have the format “ga_sessions_intraday_YYYYMMDD”. During the same day, each import of intraday data overwrites the previous import in the same table."
},
{
"code": null,
"e": 18561,
"s": 18304,
"text": "When the daily import is complete, the intraday table from the previous day is deleted. For the current day, until the first intraday import, there is no intraday table. If an intraday-table write fails, then the previous day’s intraday table is preserved."
},
{
"code": null,
"e": 18787,
"s": 18561,
"text": "Data for the current day is not final until the daily import is complete. You may notice differences between intraday and daily data based on active user sessions that cross the time boundary of last intraday import. (source)"
},
{
"code": null,
"e": 19077,
"s": 18787,
"text": "The easiest way to include intraday data in your query as well as historical data is use the wildcard in combination with a wider _table_suffix filter. With this condition it will include any table in the data set that starts with ga_sessions_ and contains a date with the format YYYYMMDD."
},
{
"code": null,
"e": 19184,
"s": 19077,
"text": "Note: make sure your data set doesn’t contain any other tables with a title that starts with ga_sessions_!"
},
{
"code": null,
"e": 19204,
"s": 19184,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 19232,
"s": 19204,
"text": "Return to table of contents"
},
{
"code": null,
"e": 19470,
"s": 19232,
"text": "If you don’t see an intraday table, but realtime tables and view, streaming export is enabled for your Google Analytics view. To query this data and join this with historical data from the ga_sessions_ tables, another approach is needed."
},
{
"code": null,
"e": 19558,
"s": 19470,
"text": "For each day, streaming export creates 1 new table and 1 (BigQuery) view of that table:"
},
{
"code": null,
"e": 19876,
"s": 19558,
"text": "Table: ga_realtime_sessions_YYYYMMDD is an internal staging table that includes all records of sessions for all activity that took place during the day. Data is exported continuously approximately every 15 minutes. Within this table are multiple records of a session when the session spans multiple export operations."
},
{
"code": null,
"e": 20179,
"s": 19876,
"text": "The ga_realtime_sessions_YYYYMMDD tables should not be used (and are not supported by Google Analytics technical support) for queries. Queries on these tables may yield unexpected results as they may contain duplicate records of some sessions. Query the ga_realtime_sessions_view_YYYYMMDD view instead."
},
{
"code": null,
"e": 20417,
"s": 20179,
"text": "View: ga_realtime_sessions_view_YYYYMMDD sits on top of the exported tables and is there to deduplicate multiple records of repeated sessions that exist across export boundaries. Query this table for deduplicated streaming data. (source)"
},
{
"code": null,
"e": 20560,
"s": 20417,
"text": "At the time of writing this daily generated realtime view is only queryable with Legacy SQL. Any Standard SQL query will result in this error:"
},
{
"code": null,
"e": 20633,
"s": 20560,
"text": "To be able to use Standard SQL, we have to create our own realtime view."
},
{
"code": null,
"e": 20653,
"s": 20633,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 20681,
"s": 20653,
"text": "Return to table of contents"
},
{
"code": null,
"e": 20700,
"s": 20681,
"text": "No rights reserved"
}
] |
CBSE Class 11 C++ Sample Paper-3 - GeeksforGeeks
|
23 Oct, 2018
Class- XI [Computer Science]Time Duration: 3 HrsM. M. 70General instructions:(i) All questions are compulsory(ii) Programming language : C++
SECTION A
1. Explain any 2 important features of an Operating System. 2There are various features of an Operating System. These are:
Memory Management
File Management
Hardware Interdependence
Process Management
Graphical User Interface
Networking Capability.
Memory Management: Memory management is the functionality of an operating system which handles or manages primary memory and moves processes back and forth between main memory and disk during execution.
File Management : Operating System helps to create new files in computer system and placing them at the specific locations. It helps in easily and quickly locating these files in computer system. It makes the process of sharing of the files among different users very easy and user friendly.
2. What is the difference between GUI and CUI? 2A GUI (Graphic User Interface) is a graphical representation in which the users can interact with software or devices through graphical icons.A CLI (Command Line Interface) is a console or text based representation in which the user types the commands to operate the software or devices.
3. What is the difference between copying and moving a file. 2Copy is to make a copy of the selected file or folder and place the duplicate in another drive or folder, while move is to move the original files from one place to another location. The move command deletes the original files, while copy retains them.
SECTION B
1. Explain the following terms with an example of each. (2 marks each)a. Comments : In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. Comments are statements that are not executed by the compiler and interpreter.In C/C++ there are two types of comments :Single line commentMulti-line commentRefer: Comments in C++
b. IdentifiersIdentifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements.Refer: C++ Tokens
2. What do you mean by Programming Errors? Explain all types of errors. 3Error is an illegal operation performed by the user which results in abnormal working of the program.Type of errors :
Syntax errors : Errors that occur when the rules of writing C/C++ syntax are violated are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors.
Run-time Errors : Errors which occur during program execution(run-time) after successful compilation are called run-time errors. Example: Division by zero error.
Logical Errors : On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors.
Refer: Errors in C++
3. Explain the term LIVEWARE. 1The programmers, systems analysts, operating staff, and other personnel working in a computer system or the organisation related to a computing environment is termed as Liveware.
SECTION C
1. Write a program to read a number from user and check whether the given no. is prime. 5You may Refer : Check if a number is prime or not
// C++ program to check if a// number is prime #include <iostream>using namespace std; int checkprime(int n){ ; int i, flag = 1; // Iterate from 2 to n/2 for (i = 2; i <= n / 2; i++) { // If n is divisible by any number between // 2 and n/2, it is not prime if (n % i == 0) { flag = 0; break; } } if (flag == 1) cout << "prime number"; else cout << "not a prime number"; return 0;} int main(){ int n; // Ask user for input cout << "Enter a number: \n"; // Store input number in a variable cin >> n; checkprime(n); return 0;}
2. Write a function to calculate the following series: 1 + X / X2 + 2X / X3+ 3X / X4 +................. + NX / XN+1
// C++ program to find sum of series// 1 + X / X<sup>2</sup>//+ 2X / X<sup>3</sup>+ ...... + NX / X<sup>N+1#include <iostream>#include <math.h>using namespace std; double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (i * x / pow(x, i + 1)); return total;} // Driver codeint main(){ int x, n; cout << "enter the value of x \n"; cin >> x; cout << "enter the number of terms \n"; cin >> n; cout << "sum of series is:" << sum(x, n); return 0;}
3. Evaluate the following C++ expressions where a, b, c are integers and d, f are floating point numbers. The Value of a = 6, b = 2, d = 1.5 (2 marks each)a) f = a + b/aOutput: 6b) c = ( a++) * d + bOutput: 8.5c) c = a – ( b++ ) * (–a)Output: -5
4. Find out the errors, underline them and correct them 4
Void main(){ int a, b = 2; cout >> “Enter a Value cin << “a”; floating f = a / b; if (a = < b) cout << a <<” Greatest “; else cout << b << “ Greatest”; cout <<”Values of f is : “<< f; f + = 13; cout << Now Value of f is << f;}
Correct code:
#include <iostream.h>void main(){ int a, b = 2; cout << “Enter a Value”; cin >> a; float f = a / b; if (a <= b) cout << a <<” Greatest “; else cout << b << “ Greatest”; cout <<”Values of f is : “<< f; f + = 13; cout << “Now Value of f is” << f;}
5. Write a program to find factorial of a given number. 4
// C++ program to illustrate the// before_begin() function#include <bits/stdc++.h>using namespace std; int factorial(int n){ if (n == 0 || n == 1) return 1; else return n * factorial(n - 1);} int main(){ int n; cout << "enter the number"; cin >> n; cout << "the factorial is: " << factorial(n); return 0;}
6. Write a function to accept a String Str, a character Ch and an integer pos. Now in String ‘Str’ character at position ‘pos’ should be replaced with character ‘Ch’ 4
// C++ program for above implementation#include <iostream>using namespace std; // Function to print the stringvoid printString(string str, char ch, int pos){ // If given count is 0 // print the given string and return if (pos == 0) { cout << str; return; } str[pos - 1] = ch; cout << str;} // Drivers codeint main(){ string str = "geeks for geeks"; char ch = 'x'; int pos = 5; printString(str, ch, pos); return 0;}
7. Write a program to read a Matrix ant print the Transpose of that Matrix . 4
#include <iostream>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int B[N][N], i, j; transpose(A, B); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", B[i][j]); printf("\n"); } return 0;}
8. a. What are the types of selection statements available in C++? Give example of each type. 2Selection statements in programming languages decides the direction of flow of program execution. Decision making statements available in C++ are:
if statement
if..else statements
nested if statements
if-else-if ladder
switch statements
Refer : Decision making in C/C++
b Differentiate between system software and application software. 2
System Software: These are the software that directly allows the user to interact with the hardware components of a computer system. The system software can be called the main software of a computer system as it handles the major portion of running a hardware.Example: Operating System
Application Software: These are the basic software used to run to accomplish a particular action and task. These are the dedicated software, dedicated to performing simple and single tasks.Example: Microsoft Excel – Used to prepare excel sheets.
Refer: Software Concepts
c. Differentiate between compiler and interpreter. 2
A compiler takes entire program and converts it into object code which is typically stored in a file. The object code is also referred as binary code and can be directly executed by the machine after linking.Examples: C and C++.
An Interpreter directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code.Examples: Perl, Python and Matlab.
Refer: Compiler vs Interpreter
d. Explain unary, binary and ternary operators? Give example of each type. 3
Unary Operators: Operators that operates or works with a single operand are unary operators.Example: (++, –)
Binary Operators: Operators that operates or works with two operands are binary operators.Example: +, –, *, /.
Ternary Operator: These operator requires 3 expressions or operands to function.Example: Conditional operator- Expression1 ? Expression2 : Expression3 .Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 else return the result of Expression3.
Refer: Operators in C++
e. What is the difference between break and continue? Give example. 3
Break statement:the break statement terminates the smallest enclosing loop (i. e., while, do-while, for or switch statement)
the break statement terminates the smallest enclosing loop (i. e., while, do-while, for or switch statement)
Continue statement:the continue statement skips the rest of the loop statement and causes the next iteration of the loop to take place.
the continue statement skips the rest of the loop statement and causes the next iteration of the loop to take place.
Refer: Break and Continue statement
SECTION D
1. What are memory devices? Discuss RAM and ROM in detail 4
Random Access Memory (RAM) : It is also called as read write memory or the main memory or the primary memory. The programs and data that the CPU requires during execution of a program are stored in this memory.It is a volatile memory as the data loses when the power is turned off.
Read Only Memory (ROM) : Stores crucial information essential to operate the system, like the program essential to boot the computer.It is not volatile and always retains its data. ROMs are used in embedded systems or where the programming needs no change.
Refer: RAM and ROM
2. Explain the following terms ( 1 mark each)
a. REGISTER :These are the special fast storage devices which are used to store data directly in the CPU. A CPU contains a register file containing several registers to store the data which is currently in execution in CPU.
b. ALU : The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation
c. NON-IMPACT PRINTER : These printers use non-Impact technology such as ink-jet or laser technology. There printers provide better quality of O/P at higher speed.Example: Ink-Jet Printer
3. What is the difference between online and offline UPS? 2Online UPS systems draw their power through power conditioning and charging components during normal operations.Offline UPS are systems where the load is fed directly from the raw mains during normal operations, rather than the inverter outputs, to the extent that power storage components such as chargers, inverters and batteries are offline as the load is concerned.
CBSE - Class 11
school-programming
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Operator Overloading in C++
Polymorphism in C++
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n23 Oct, 2018"
},
{
"code": null,
"e": 25508,
"s": 25367,
"text": "Class- XI [Computer Science]Time Duration: 3 HrsM. M. 70General instructions:(i) All questions are compulsory(ii) Programming language : C++"
},
{
"code": null,
"e": 25518,
"s": 25508,
"text": "SECTION A"
},
{
"code": null,
"e": 25641,
"s": 25518,
"text": "1. Explain any 2 important features of an Operating System. 2There are various features of an Operating System. These are:"
},
{
"code": null,
"e": 25659,
"s": 25641,
"text": "Memory Management"
},
{
"code": null,
"e": 25675,
"s": 25659,
"text": "File Management"
},
{
"code": null,
"e": 25700,
"s": 25675,
"text": "Hardware Interdependence"
},
{
"code": null,
"e": 25719,
"s": 25700,
"text": "Process Management"
},
{
"code": null,
"e": 25744,
"s": 25719,
"text": "Graphical User Interface"
},
{
"code": null,
"e": 25767,
"s": 25744,
"text": "Networking Capability."
},
{
"code": null,
"e": 25970,
"s": 25767,
"text": "Memory Management: Memory management is the functionality of an operating system which handles or manages primary memory and moves processes back and forth between main memory and disk during execution."
},
{
"code": null,
"e": 26262,
"s": 25970,
"text": "File Management : Operating System helps to create new files in computer system and placing them at the specific locations. It helps in easily and quickly locating these files in computer system. It makes the process of sharing of the files among different users very easy and user friendly."
},
{
"code": null,
"e": 26598,
"s": 26262,
"text": "2. What is the difference between GUI and CUI? 2A GUI (Graphic User Interface) is a graphical representation in which the users can interact with software or devices through graphical icons.A CLI (Command Line Interface) is a console or text based representation in which the user types the commands to operate the software or devices."
},
{
"code": null,
"e": 26913,
"s": 26598,
"text": "3. What is the difference between copying and moving a file. 2Copy is to make a copy of the selected file or folder and place the duplicate in another drive or folder, while move is to move the original files from one place to another location. The move command deletes the original files, while copy retains them."
},
{
"code": null,
"e": 26923,
"s": 26913,
"text": "SECTION B"
},
{
"code": null,
"e": 27315,
"s": 26923,
"text": "1. Explain the following terms with an example of each. (2 marks each)a. Comments : In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. Comments are statements that are not executed by the compiler and interpreter.In C/C++ there are two types of comments :Single line commentMulti-line commentRefer: Comments in C++"
},
{
"code": null,
"e": 27932,
"s": 27315,
"text": "b. IdentifiersIdentifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements.Refer: C++ Tokens"
},
{
"code": null,
"e": 28123,
"s": 27932,
"text": "2. What do you mean by Programming Errors? Explain all types of errors. 3Error is an illegal operation performed by the user which results in abnormal working of the program.Type of errors :"
},
{
"code": null,
"e": 28414,
"s": 28123,
"text": "Syntax errors : Errors that occur when the rules of writing C/C++ syntax are violated are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors."
},
{
"code": null,
"e": 28576,
"s": 28414,
"text": "Run-time Errors : Errors which occur during program execution(run-time) after successful compilation are called run-time errors. Example: Division by zero error."
},
{
"code": null,
"e": 28813,
"s": 28576,
"text": "Logical Errors : On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors."
},
{
"code": null,
"e": 28834,
"s": 28813,
"text": "Refer: Errors in C++"
},
{
"code": null,
"e": 29044,
"s": 28834,
"text": "3. Explain the term LIVEWARE. 1The programmers, systems analysts, operating staff, and other personnel working in a computer system or the organisation related to a computing environment is termed as Liveware."
},
{
"code": null,
"e": 29054,
"s": 29044,
"text": "SECTION C"
},
{
"code": null,
"e": 29193,
"s": 29054,
"text": "1. Write a program to read a number from user and check whether the given no. is prime. 5You may Refer : Check if a number is prime or not"
},
{
"code": "// C++ program to check if a// number is prime #include <iostream>using namespace std; int checkprime(int n){ ; int i, flag = 1; // Iterate from 2 to n/2 for (i = 2; i <= n / 2; i++) { // If n is divisible by any number between // 2 and n/2, it is not prime if (n % i == 0) { flag = 0; break; } } if (flag == 1) cout << \"prime number\"; else cout << \"not a prime number\"; return 0;} int main(){ int n; // Ask user for input cout << \"Enter a number: \\n\"; // Store input number in a variable cin >> n; checkprime(n); return 0;}",
"e": 29842,
"s": 29193,
"text": null
},
{
"code": null,
"e": 29958,
"s": 29842,
"text": "2. Write a function to calculate the following series: 1 + X / X2 + 2X / X3+ 3X / X4 +................. + NX / XN+1"
},
{
"code": "// C++ program to find sum of series// 1 + X / X<sup>2</sup>//+ 2X / X<sup>3</sup>+ ...... + NX / X<sup>N+1#include <iostream>#include <math.h>using namespace std; double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (i * x / pow(x, i + 1)); return total;} // Driver codeint main(){ int x, n; cout << \"enter the value of x \\n\"; cin >> x; cout << \"enter the number of terms \\n\"; cin >> n; cout << \"sum of series is:\" << sum(x, n); return 0;}",
"e": 30475,
"s": 29958,
"text": null
},
{
"code": null,
"e": 30721,
"s": 30475,
"text": "3. Evaluate the following C++ expressions where a, b, c are integers and d, f are floating point numbers. The Value of a = 6, b = 2, d = 1.5 (2 marks each)a) f = a + b/aOutput: 6b) c = ( a++) * d + bOutput: 8.5c) c = a – ( b++ ) * (–a)Output: -5"
},
{
"code": null,
"e": 30779,
"s": 30721,
"text": "4. Find out the errors, underline them and correct them 4"
},
{
"code": "Void main(){ int a, b = 2; cout >> “Enter a Value cin << “a”; floating f = a / b; if (a = < b) cout << a <<” Greatest “; else cout << b << “ Greatest”; cout <<”Values of f is : “<< f; f + = 13; cout << Now Value of f is << f;}",
"e": 31078,
"s": 30779,
"text": null
},
{
"code": null,
"e": 31092,
"s": 31078,
"text": "Correct code:"
},
{
"code": "#include <iostream.h>void main(){ int a, b = 2; cout << “Enter a Value”; cin >> a; float f = a / b; if (a <= b) cout << a <<” Greatest “; else cout << b << “ Greatest”; cout <<”Values of f is : “<< f; f + = 13; cout << “Now Value of f is” << f;}",
"e": 31379,
"s": 31092,
"text": null
},
{
"code": null,
"e": 31437,
"s": 31379,
"text": "5. Write a program to find factorial of a given number. 4"
},
{
"code": "// C++ program to illustrate the// before_begin() function#include <bits/stdc++.h>using namespace std; int factorial(int n){ if (n == 0 || n == 1) return 1; else return n * factorial(n - 1);} int main(){ int n; cout << \"enter the number\"; cin >> n; cout << \"the factorial is: \" << factorial(n); return 0;}",
"e": 31780,
"s": 31437,
"text": null
},
{
"code": null,
"e": 31948,
"s": 31780,
"text": "6. Write a function to accept a String Str, a character Ch and an integer pos. Now in String ‘Str’ character at position ‘pos’ should be replaced with character ‘Ch’ 4"
},
{
"code": "// C++ program for above implementation#include <iostream>using namespace std; // Function to print the stringvoid printString(string str, char ch, int pos){ // If given count is 0 // print the given string and return if (pos == 0) { cout << str; return; } str[pos - 1] = ch; cout << str;} // Drivers codeint main(){ string str = \"geeks for geeks\"; char ch = 'x'; int pos = 5; printString(str, ch, pos); return 0;}",
"e": 32416,
"s": 31948,
"text": null
},
{
"code": null,
"e": 32495,
"s": 32416,
"text": "7. Write a program to read a Matrix ant print the Transpose of that Matrix . 4"
},
{
"code": "#include <iostream>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int B[N][N], i, j; transpose(A, B); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", B[i][j]); printf(\"\\n\"); } return 0;}",
"e": 33086,
"s": 32495,
"text": null
},
{
"code": null,
"e": 33328,
"s": 33086,
"text": "8. a. What are the types of selection statements available in C++? Give example of each type. 2Selection statements in programming languages decides the direction of flow of program execution. Decision making statements available in C++ are:"
},
{
"code": null,
"e": 33341,
"s": 33328,
"text": "if statement"
},
{
"code": null,
"e": 33361,
"s": 33341,
"text": "if..else statements"
},
{
"code": null,
"e": 33382,
"s": 33361,
"text": "nested if statements"
},
{
"code": null,
"e": 33400,
"s": 33382,
"text": "if-else-if ladder"
},
{
"code": null,
"e": 33418,
"s": 33400,
"text": "switch statements"
},
{
"code": null,
"e": 33451,
"s": 33418,
"text": "Refer : Decision making in C/C++"
},
{
"code": null,
"e": 33519,
"s": 33451,
"text": "b Differentiate between system software and application software. 2"
},
{
"code": null,
"e": 33805,
"s": 33519,
"text": "System Software: These are the software that directly allows the user to interact with the hardware components of a computer system. The system software can be called the main software of a computer system as it handles the major portion of running a hardware.Example: Operating System"
},
{
"code": null,
"e": 34051,
"s": 33805,
"text": "Application Software: These are the basic software used to run to accomplish a particular action and task. These are the dedicated software, dedicated to performing simple and single tasks.Example: Microsoft Excel – Used to prepare excel sheets."
},
{
"code": null,
"e": 34076,
"s": 34051,
"text": "Refer: Software Concepts"
},
{
"code": null,
"e": 34129,
"s": 34076,
"text": "c. Differentiate between compiler and interpreter. 2"
},
{
"code": null,
"e": 34358,
"s": 34129,
"text": "A compiler takes entire program and converts it into object code which is typically stored in a file. The object code is also referred as binary code and can be directly executed by the machine after linking.Examples: C and C++."
},
{
"code": null,
"e": 34555,
"s": 34358,
"text": "An Interpreter directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code.Examples: Perl, Python and Matlab."
},
{
"code": null,
"e": 34586,
"s": 34555,
"text": "Refer: Compiler vs Interpreter"
},
{
"code": null,
"e": 34663,
"s": 34586,
"text": "d. Explain unary, binary and ternary operators? Give example of each type. 3"
},
{
"code": null,
"e": 34772,
"s": 34663,
"text": "Unary Operators: Operators that operates or works with a single operand are unary operators.Example: (++, –)"
},
{
"code": null,
"e": 34883,
"s": 34772,
"text": "Binary Operators: Operators that operates or works with two operands are binary operators.Example: +, –, *, /."
},
{
"code": null,
"e": 35222,
"s": 34883,
"text": "Ternary Operator: These operator requires 3 expressions or operands to function.Example: Conditional operator- Expression1 ? Expression2 : Expression3 .Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 else return the result of Expression3."
},
{
"code": null,
"e": 35246,
"s": 35222,
"text": "Refer: Operators in C++"
},
{
"code": null,
"e": 35316,
"s": 35246,
"text": "e. What is the difference between break and continue? Give example. 3"
},
{
"code": null,
"e": 35441,
"s": 35316,
"text": "Break statement:the break statement terminates the smallest enclosing loop (i. e., while, do-while, for or switch statement)"
},
{
"code": null,
"e": 35550,
"s": 35441,
"text": "the break statement terminates the smallest enclosing loop (i. e., while, do-while, for or switch statement)"
},
{
"code": null,
"e": 35686,
"s": 35550,
"text": "Continue statement:the continue statement skips the rest of the loop statement and causes the next iteration of the loop to take place."
},
{
"code": null,
"e": 35803,
"s": 35686,
"text": "the continue statement skips the rest of the loop statement and causes the next iteration of the loop to take place."
},
{
"code": null,
"e": 35839,
"s": 35803,
"text": "Refer: Break and Continue statement"
},
{
"code": null,
"e": 35849,
"s": 35839,
"text": "SECTION D"
},
{
"code": null,
"e": 35909,
"s": 35849,
"text": "1. What are memory devices? Discuss RAM and ROM in detail 4"
},
{
"code": null,
"e": 36191,
"s": 35909,
"text": "Random Access Memory (RAM) : It is also called as read write memory or the main memory or the primary memory. The programs and data that the CPU requires during execution of a program are stored in this memory.It is a volatile memory as the data loses when the power is turned off."
},
{
"code": null,
"e": 36448,
"s": 36191,
"text": "Read Only Memory (ROM) : Stores crucial information essential to operate the system, like the program essential to boot the computer.It is not volatile and always retains its data. ROMs are used in embedded systems or where the programming needs no change."
},
{
"code": null,
"e": 36467,
"s": 36448,
"text": "Refer: RAM and ROM"
},
{
"code": null,
"e": 36513,
"s": 36467,
"text": "2. Explain the following terms ( 1 mark each)"
},
{
"code": null,
"e": 36737,
"s": 36513,
"text": "a. REGISTER :These are the special fast storage devices which are used to store data directly in the CPU. A CPU contains a register file containing several registers to store the data which is currently in execution in CPU."
},
{
"code": null,
"e": 36971,
"s": 36737,
"text": "b. ALU : The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation"
},
{
"code": null,
"e": 37159,
"s": 36971,
"text": "c. NON-IMPACT PRINTER : These printers use non-Impact technology such as ink-jet or laser technology. There printers provide better quality of O/P at higher speed.Example: Ink-Jet Printer"
},
{
"code": null,
"e": 37588,
"s": 37159,
"text": "3. What is the difference between online and offline UPS? 2Online UPS systems draw their power through power conditioning and charging components during normal operations.Offline UPS are systems where the load is fed directly from the raw mains during normal operations, rather than the inverter outputs, to the extent that power storage components such as chargers, inverters and batteries are offline as the load is concerned."
},
{
"code": null,
"e": 37604,
"s": 37588,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 37623,
"s": 37604,
"text": "school-programming"
},
{
"code": null,
"e": 37627,
"s": 37623,
"text": "C++"
},
{
"code": null,
"e": 37646,
"s": 37627,
"text": "School Programming"
},
{
"code": null,
"e": 37650,
"s": 37646,
"text": "CPP"
},
{
"code": null,
"e": 37748,
"s": 37650,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37776,
"s": 37748,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 37796,
"s": 37776,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 37829,
"s": 37796,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 37853,
"s": 37829,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 37878,
"s": 37853,
"text": "std::string class in C++"
},
{
"code": null,
"e": 37896,
"s": 37878,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37921,
"s": 37896,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37940,
"s": 37921,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 37968,
"s": 37940,
"text": "Operator Overloading in C++"
}
] |
HATEOAS and Why It's Needed in RESTful API? - GeeksforGeeks
|
11 Sep, 2020
HATEOAS stands for Hypermedia as the Engine of Application State and it is a component of RESTful API architecture and design. With the use of HATEOAS, the client-side needs minimal knowledge about how to interact with a server. This is made possible by the network application responding to the client’s requests with dynamically generated information through the use of hypermedia.
When accessing a webpage through a browser, users have the ability to interact with the webpage by using buttons, inputs, clicking on links, etc. However, traditional API responses have no such functionality present to allow an application to interact with the server through the response. HATEOAS acts as a way to address this. A HATEOAS request allows you to not only send the data but also specify the related actions.
When using HATEOAS architecture, a client will be able to access the API for a network application through a simple, static, RESTful URL call. Now, any further actions, that the client may wish to take, will be enabled by the data, returned by the server, in the original call. This will enable the client to move from one application state to the next just by interacting with the details contained in the responses by the server.
The “data”, within the response, that enables this change of state is simple hypermedia links. This is how HATEOAS manages the change in application states through hypermedia.
As an example, consider that a client wants to interact with a network application to fetch details of employees’ payroll within an organization. The RESTful call to enable this would be as follows:
GET /payroll/employee_123 HTTP/1.1
The server will respond with a JSON containing the required details. Additionally, the response will contain hypermedia links that allow the client to take further actions. As an example, consider the response by the server is as follows.
HTTP/1.1 200 OK
Content-Type: application/+json
Content-Length: ...
{
"payroll": {
"employee_number": "employee_123",
"salary" : 1000,
"links": {
"increment": "/payroll/employee_123/increment",
"decrement": "/payroll/employee_123/decrement",
"close": "/payroll/employee_123/close"
}
}
}
We can observe that, in addition to the expected information being received in the response, additional information is presented in the form of RESTful hypermedia calls under the “links” title. These links allow further interaction with the server by incrementing or decrementing the salary or closing the account. It may be noted that these links correspond to the respective API endpoints to increment, decrement, and close the payroll account. Also, these links are pre-populated with the employee identifier. This means that such content is dynamically generated.
An additional example of how these hypermedia links are dynamically generated can be demonstrated is as follows:
Assume that for a given employee, the account has been closed. Thus, the increment and decrement methods are irrelevant to such an account. Thus, hitting the payroll endpoint for such an employee would result in response as follows:
HTTP/1.1 200 OK
Content-Type: application/+json
Content-Length: ...
{
"payroll": {
"employee_number": "employee_123"
"links": {
"start": "/payroll/employee_123/start"
}
}
}
In this case, the links have changed to include functions that are relevant to the current state only. Thus, the only action made available is to “start” the payroll for such an employee.
With traditional, non-HATEOAS based API systems, the API endpoints need to be hard-coded within the client-side application. Any changes to this endpoint would result in the client application systems breaking down. Thus, such changes would need to be updated in each of the client’s applications. This system is, therefore, tightly coupled.
With HATEOAS, the system becomes loosely coupled as the URLs do not require hard-coding. Instead, the URLs are generated on the fly on the server-side and supplied to the client through the JSON responses. Clients can now use these URLs from the response and be sure that these URLs are the latest versions.
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
How to Start Learning DSA?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26277,
"s": 26249,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 26661,
"s": 26277,
"text": "HATEOAS stands for Hypermedia as the Engine of Application State and it is a component of RESTful API architecture and design. With the use of HATEOAS, the client-side needs minimal knowledge about how to interact with a server. This is made possible by the network application responding to the client’s requests with dynamically generated information through the use of hypermedia."
},
{
"code": null,
"e": 27083,
"s": 26661,
"text": "When accessing a webpage through a browser, users have the ability to interact with the webpage by using buttons, inputs, clicking on links, etc. However, traditional API responses have no such functionality present to allow an application to interact with the server through the response. HATEOAS acts as a way to address this. A HATEOAS request allows you to not only send the data but also specify the related actions."
},
{
"code": null,
"e": 27516,
"s": 27083,
"text": "When using HATEOAS architecture, a client will be able to access the API for a network application through a simple, static, RESTful URL call. Now, any further actions, that the client may wish to take, will be enabled by the data, returned by the server, in the original call. This will enable the client to move from one application state to the next just by interacting with the details contained in the responses by the server. "
},
{
"code": null,
"e": 27692,
"s": 27516,
"text": "The “data”, within the response, that enables this change of state is simple hypermedia links. This is how HATEOAS manages the change in application states through hypermedia."
},
{
"code": null,
"e": 27891,
"s": 27692,
"text": "As an example, consider that a client wants to interact with a network application to fetch details of employees’ payroll within an organization. The RESTful call to enable this would be as follows:"
},
{
"code": null,
"e": 27928,
"s": 27891,
"text": "GET /payroll/employee_123 HTTP/1.1\n\n"
},
{
"code": null,
"e": 28167,
"s": 27928,
"text": "The server will respond with a JSON containing the required details. Additionally, the response will contain hypermedia links that allow the client to take further actions. As an example, consider the response by the server is as follows."
},
{
"code": null,
"e": 28523,
"s": 28167,
"text": "HTTP/1.1 200 OK\nContent-Type: application/+json\nContent-Length: ...\n{\n \"payroll\": {\n \"employee_number\": \"employee_123\",\n \"salary\" : 1000,\n \"links\": {\n \"increment\": \"/payroll/employee_123/increment\",\n \"decrement\": \"/payroll/employee_123/decrement\",\n \"close\": \"/payroll/employee_123/close\"\n }\n }\n}\n\n"
},
{
"code": null,
"e": 29092,
"s": 28523,
"text": "We can observe that, in addition to the expected information being received in the response, additional information is presented in the form of RESTful hypermedia calls under the “links” title. These links allow further interaction with the server by incrementing or decrementing the salary or closing the account. It may be noted that these links correspond to the respective API endpoints to increment, decrement, and close the payroll account. Also, these links are pre-populated with the employee identifier. This means that such content is dynamically generated. "
},
{
"code": null,
"e": 29206,
"s": 29092,
"text": "An additional example of how these hypermedia links are dynamically generated can be demonstrated is as follows: "
},
{
"code": null,
"e": 29439,
"s": 29206,
"text": "Assume that for a given employee, the account has been closed. Thus, the increment and decrement methods are irrelevant to such an account. Thus, hitting the payroll endpoint for such an employee would result in response as follows:"
},
{
"code": null,
"e": 29646,
"s": 29439,
"text": "HTTP/1.1 200 OK\nContent-Type: application/+json\nContent-Length: ...\n{\n \"payroll\": {\n \"employee_number\": \"employee_123\"\n \"links\": {\n \"start\": \"/payroll/employee_123/start\"\n }\n }\n}\n\n"
},
{
"code": null,
"e": 29834,
"s": 29646,
"text": "In this case, the links have changed to include functions that are relevant to the current state only. Thus, the only action made available is to “start” the payroll for such an employee."
},
{
"code": null,
"e": 30176,
"s": 29834,
"text": "With traditional, non-HATEOAS based API systems, the API endpoints need to be hard-coded within the client-side application. Any changes to this endpoint would result in the client application systems breaking down. Thus, such changes would need to be updated in each of the client’s applications. This system is, therefore, tightly coupled."
},
{
"code": null,
"e": 30485,
"s": 30176,
"text": "With HATEOAS, the system becomes loosely coupled as the URLs do not require hard-coding. Instead, the URLs are generated on the fly on the server-side and supplied to the client through the JSON responses. Clients can now use these URLs from the response and be sure that these URLs are the latest versions. "
},
{
"code": null,
"e": 30491,
"s": 30485,
"text": "GBlog"
},
{
"code": null,
"e": 30508,
"s": 30491,
"text": "Web Technologies"
},
{
"code": null,
"e": 30606,
"s": 30508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30631,
"s": 30606,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30666,
"s": 30631,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 30728,
"s": 30666,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30754,
"s": 30728,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 30781,
"s": 30754,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 30821,
"s": 30781,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30854,
"s": 30821,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30899,
"s": 30854,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30942,
"s": 30899,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
JavaScript - Events
|
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Click the following button and see result
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.
The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Bring your mouse inside the division to see the result:
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event.
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2587,
"s": 2466,
"text": "JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page."
},
{
"code": null,
"e": 2785,
"s": 2587,
"text": "When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc."
},
{
"code": null,
"e": 3004,
"s": 2785,
"text": "Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable."
},
{
"code": null,
"e": 3148,
"s": 3004,
"text": "Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code."
},
{
"code": null,
"e": 3323,
"s": 3148,
"text": "Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −"
},
{
"code": null,
"e": 3497,
"s": 3323,
"text": "This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type."
},
{
"code": null,
"e": 3524,
"s": 3497,
"text": "Try the following example."
},
{
"code": null,
"e": 3935,
"s": 3524,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello World\")\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following button and see result</p> \n <form>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 3977,
"s": 3935,
"text": "Click the following button and see result"
},
{
"code": null,
"e": 4099,
"s": 3977,
"text": "onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type."
},
{
"code": null,
"e": 4342,
"s": 4099,
"text": "The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data."
},
{
"code": null,
"e": 4369,
"s": 4342,
"text": "Try the following example."
},
{
"code": null,
"e": 4851,
"s": 4369,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function validation() {\n all validation goes here\n .........\n return either true or false\n }\n //-->\n </script> \n </head>\n \n <body> \n <form method = \"POST\" action = \"t.cgi\" onsubmit = \"return validate()\">\n .......\n <input type = \"submit\" value = \"Submit\" />\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 5123,
"s": 4851,
"text": "These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example."
},
{
"code": null,
"e": 5681,
"s": 5123,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function over() {\n document.write (\"Mouse Over\");\n } \n function out() {\n document.write (\"Mouse Out\");\n } \n //-->\n </script> \n </head>\n \n <body>\n <p>Bring your mouse inside the division to see the result:</p> \n <div onmouseover = \"over()\" onmouseout = \"out()\">\n <h2> This is inside the division </h2>\n </div> \n </body>\n</html>"
},
{
"code": null,
"e": 5737,
"s": 5681,
"text": "Bring your mouse inside the division to see the result:"
},
{
"code": null,
"e": 5879,
"s": 5737,
"text": "The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event."
},
{
"code": null,
"e": 5914,
"s": 5879,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5928,
"s": 5914,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5962,
"s": 5928,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5976,
"s": 5962,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6011,
"s": 5976,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6028,
"s": 6011,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6063,
"s": 6028,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6080,
"s": 6063,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6113,
"s": 6080,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6141,
"s": 6113,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6175,
"s": 6141,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 6203,
"s": 6175,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6210,
"s": 6203,
"text": " Print"
},
{
"code": null,
"e": 6221,
"s": 6210,
"text": " Add Notes"
}
] |
C | Pointer Basics | Question 17 - GeeksforGeeks
|
28 Jun, 2021
Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h> int main(){ float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; printf("%f ", *ptr2); printf("%d", ptr2 - ptr1); return 0;}
(A) 90.5000003
(B) 90.50000012(C) 10.00000012(D) 0.5000003Answer: (A)Explanation: When we add a value x to a pointer p, the value of the resultant expression is p + x*sizeof(*p) where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to point to arr[3] in the above code. Same rule applies for subtraction. Note that only integral values can be added or subtracted from a pointer. We can also subtract or compare two pointers of same type.Quiz of this Question
C-Pointer Basics
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
Substring in C++
std::string class in C++
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
|
[
{
"code": null,
"e": 24466,
"s": 24438,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24540,
"s": 24466,
"text": "Assume that float takes 4 bytes, predict the output of following program."
},
{
"code": "#include <stdio.h> int main(){ float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; printf(\"%f \", *ptr2); printf(\"%d\", ptr2 - ptr1); return 0;}",
"e": 24746,
"s": 24540,
"text": null
},
{
"code": null,
"e": 24761,
"s": 24746,
"text": "(A) 90.5000003"
},
{
"code": null,
"e": 25238,
"s": 24761,
"text": "(B) 90.50000012(C) 10.00000012(D) 0.5000003Answer: (A)Explanation: When we add a value x to a pointer p, the value of the resultant expression is p + x*sizeof(*p) where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to point to arr[3] in the above code. Same rule applies for subtraction. Note that only integral values can be added or subtracted from a pointer. We can also subtract or compare two pointers of same type.Quiz of this Question"
},
{
"code": null,
"e": 25255,
"s": 25238,
"text": "C-Pointer Basics"
},
{
"code": null,
"e": 25266,
"s": 25255,
"text": "C Language"
},
{
"code": null,
"e": 25273,
"s": 25266,
"text": "C Quiz"
},
{
"code": null,
"e": 25371,
"s": 25273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25383,
"s": 25371,
"text": "fork() in C"
},
{
"code": null,
"e": 25405,
"s": 25383,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25422,
"s": 25405,
"text": "Substring in C++"
},
{
"code": null,
"e": 25447,
"s": 25422,
"text": "std::string class in C++"
},
{
"code": null,
"e": 25479,
"s": 25447,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25521,
"s": 25479,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25564,
"s": 25521,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25595,
"s": 25564,
"text": "C | File Handling | Question 1"
},
{
"code": null,
"e": 25619,
"s": 25595,
"text": "C | Arrays | Question 7"
}
] |
Find the sum of series 3, -6, 12, -24 . . . upto N terms - GeeksforGeeks
|
25 Mar, 2021
Given an integer N. The task is to find the sum upto N terms of the given series:
3, -6, 12, -24, ... upto N terms
Examples:
Input : N = 5
Output : Sum = 33
Input : N = 20
Output : Sum = -1048575
On observing the given series, it can be seen that the ratio of every term with their previous term is same which is -2. Hence the given series is a GP(Geometric Progression) series.You can learn more about GP series here.So, when r < 0.In above GP series the first term i:e a = 3 and common ratio i:e r = (-2).Therefore, . Thus, .Below is the implementation of above approach:
C++
Java
Python
C#
PHP
Javascript
//C++ program to find sum upto N term of the series:// 3, -6, 12, -24, ..... #include<iostream>#include<math.h>using namespace std;//calculate sum upto N term of series class gfg{ public: int Sum_upto_nth_Term(int n) { return (1 - pow(-2, n)); }};// Driver codeint main(){ gfg g; int N = 5; cout<<g.Sum_upto_nth_Term(N);}
//Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... import java.util.*;//calculate sum upto N term of series class solution{ static int Sum_upto_nth_Term(int n){ return (1 -(int)Math.pow(-2, n));} // Driver codepublic static void main (String arr[]){ int N = 5; System.out.println(Sum_upto_nth_Term(N));} }
# Python program to find sum upto N term of the series:# 3, -6, 12, -24, ..... # calculate sum upto N term of seriesdef Sum_upto_nth_Term(n): return (1 - pow(-2, n)) # Driver codeN = 5print(Sum_upto_nth_Term(N))
// C# program to find sum upto// N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesclass GFG{ static int Sum_upto_nth_Term(int n){ return (1 -(int)System.Math.Pow(-2, n));} // Driver codepublic static void Main(){ int N = 5; System.Console.WriteLine(Sum_upto_nth_Term(N));}} // This Code is contributed by mits
<?php// PHP program to find sum upto// Nth term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term($n){ return (1 - pow(-2, $n));} // Driver code$N = 5;echo (Sum_upto_nth_Term($N)); // This code is contributed// by Sach_Code?>
<script>// Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term( n) { return (1 - parseInt( Math.pow(-2, n)));} // Driver code let N = 5; document.write(Sum_upto_nth_Term(N)); // This code is contributed by 29AjayKumar</script>
33
SoumikMondal
SURENDRA_GANGWAR
Mithun Kumar
Sach_Code
29AjayKumar
Geometric Progression
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Program to convert a given number to words
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Find first and last digits of a number
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 24775,
"s": 24692,
"text": "Given an integer N. The task is to find the sum upto N terms of the given series: "
},
{
"code": null,
"e": 24808,
"s": 24775,
"text": "3, -6, 12, -24, ... upto N terms"
},
{
"code": null,
"e": 24820,
"s": 24808,
"text": "Examples: "
},
{
"code": null,
"e": 24892,
"s": 24820,
"text": "Input : N = 5\nOutput : Sum = 33\n\nInput : N = 20\nOutput : Sum = -1048575"
},
{
"code": null,
"e": 25274,
"s": 24894,
"text": "On observing the given series, it can be seen that the ratio of every term with their previous term is same which is -2. Hence the given series is a GP(Geometric Progression) series.You can learn more about GP series here.So, when r < 0.In above GP series the first term i:e a = 3 and common ratio i:e r = (-2).Therefore, . Thus, .Below is the implementation of above approach: "
},
{
"code": null,
"e": 25278,
"s": 25274,
"text": "C++"
},
{
"code": null,
"e": 25283,
"s": 25278,
"text": "Java"
},
{
"code": null,
"e": 25290,
"s": 25283,
"text": "Python"
},
{
"code": null,
"e": 25293,
"s": 25290,
"text": "C#"
},
{
"code": null,
"e": 25297,
"s": 25293,
"text": "PHP"
},
{
"code": null,
"e": 25308,
"s": 25297,
"text": "Javascript"
},
{
"code": "//C++ program to find sum upto N term of the series:// 3, -6, 12, -24, ..... #include<iostream>#include<math.h>using namespace std;//calculate sum upto N term of series class gfg{ public: int Sum_upto_nth_Term(int n) { return (1 - pow(-2, n)); }};// Driver codeint main(){ gfg g; int N = 5; cout<<g.Sum_upto_nth_Term(N);}",
"e": 25658,
"s": 25308,
"text": null
},
{
"code": "//Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... import java.util.*;//calculate sum upto N term of series class solution{ static int Sum_upto_nth_Term(int n){ return (1 -(int)Math.pow(-2, n));} // Driver codepublic static void main (String arr[]){ int N = 5; System.out.println(Sum_upto_nth_Term(N));} }",
"e": 26000,
"s": 25658,
"text": null
},
{
"code": "# Python program to find sum upto N term of the series:# 3, -6, 12, -24, ..... # calculate sum upto N term of seriesdef Sum_upto_nth_Term(n): return (1 - pow(-2, n)) # Driver codeN = 5print(Sum_upto_nth_Term(N))",
"e": 26215,
"s": 26000,
"text": null
},
{
"code": "// C# program to find sum upto// N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesclass GFG{ static int Sum_upto_nth_Term(int n){ return (1 -(int)System.Math.Pow(-2, n));} // Driver codepublic static void Main(){ int N = 5; System.Console.WriteLine(Sum_upto_nth_Term(N));}} // This Code is contributed by mits",
"e": 26569,
"s": 26215,
"text": null
},
{
"code": "<?php// PHP program to find sum upto// Nth term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term($n){ return (1 - pow(-2, $n));} // Driver code$N = 5;echo (Sum_upto_nth_Term($N)); // This code is contributed// by Sach_Code?>",
"e": 26852,
"s": 26569,
"text": null
},
{
"code": "<script>// Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term( n) { return (1 - parseInt( Math.pow(-2, n)));} // Driver code let N = 5; document.write(Sum_upto_nth_Term(N)); // This code is contributed by 29AjayKumar</script>",
"e": 27178,
"s": 26852,
"text": null
},
{
"code": null,
"e": 27181,
"s": 27178,
"text": "33"
},
{
"code": null,
"e": 27196,
"s": 27183,
"text": "SoumikMondal"
},
{
"code": null,
"e": 27213,
"s": 27196,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 27226,
"s": 27213,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 27236,
"s": 27226,
"text": "Sach_Code"
},
{
"code": null,
"e": 27248,
"s": 27236,
"text": "29AjayKumar"
},
{
"code": null,
"e": 27270,
"s": 27248,
"text": "Geometric Progression"
},
{
"code": null,
"e": 27277,
"s": 27270,
"text": "series"
},
{
"code": null,
"e": 27288,
"s": 27277,
"text": "series-sum"
},
{
"code": null,
"e": 27301,
"s": 27288,
"text": "Mathematical"
},
{
"code": null,
"e": 27314,
"s": 27301,
"text": "Mathematical"
},
{
"code": null,
"e": 27321,
"s": 27314,
"text": "series"
},
{
"code": null,
"e": 27419,
"s": 27321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27428,
"s": 27419,
"text": "Comments"
},
{
"code": null,
"e": 27441,
"s": 27428,
"text": "Old Comments"
},
{
"code": null,
"e": 27473,
"s": 27441,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 27504,
"s": 27473,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 27537,
"s": 27504,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 27581,
"s": 27537,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 27616,
"s": 27581,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 27659,
"s": 27616,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 27684,
"s": 27659,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 27719,
"s": 27684,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 27751,
"s": 27719,
"text": "Check if a number is Palindrome"
}
] |
atomic.Store() Function in Golang With Examples - GeeksforGeeks
|
01 Apr, 2020
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The Store() function in Go language is used to set the value of the Value to x(i.e, interface).And all the calls to Store method for a stated Value should use values of an identical concrete type. Moreover, Store of a contradictory type will call panic. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func (v *Value) Store(x interface{})
Here, v is the value of any type and x is the interface which is the output result type of Store method.
Note: (*Value) is the pointer to a Value type. And Value type supplied in the sync/atomic standard package is used to atomically store as well as load values of any type.
Return value: It stores the value provided and can be loaded when required.
Example 1:
// Program to illustrate the usage of// Store function in Golang // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Main functionfunc main() { // Defining a struct type L type L struct{ x, y, z int } // Defining a variable to assign // values to the struct type L var r1 = L{9, 10, 11} // Defining Value type to store // values of any type var V atomic.Value // Calling Store function V.Store(r1) // Printed if the value stated is stored fmt.Println("Any type of value is stored!")}
Output:
Any type of value is stored!
In the above example, we have used Value type in order to store the values of any type. And these values are stored at r1 which is the interface stated.
Example 2:
// Program to illustrate the usage of// Store function in Golang // Including main packagepackage main // importing fmt and sync/atomicimport ( "sync/atomic") // Main functionfunc main() { // Defining a struct type L type L struct{ x, y, z int } // Defining a variable to assign // values to the struct type L var r1 = L{9, 10, 11} // Defining Value type to store // values of any type var V atomic.Value // Calling Store function V.Store(r1) // Storing value of // different concrete type V.Store("GeeksforGeeks")}
Output:
panic: sync/atomic: store of inconsistently typed value into Value
goroutine 1 [running]:
sync/atomic.(*Value).Store(0x40c018, 0x99a40, 0xb23e8, 0x40e010)
/usr/local/go/src/sync/atomic/value.go:77 +0x160
main.main()
/tmp/sandbox206117237/prog.go:31 +0xc0
Here, the value stored above is of different concrete type so panic is called.
GoLang-atomic
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Slices in Golang
Golang Maps
Interfaces in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Trim a String in Golang?
|
[
{
"code": null,
"e": 24476,
"s": 24448,
"text": "\n01 Apr, 2020"
},
{
"code": null,
"e": 24986,
"s": 24476,
"text": "In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The Store() function in Go language is used to set the value of the Value to x(i.e, interface).And all the calls to Store method for a stated Value should use values of an identical concrete type. Moreover, Store of a contradictory type will call panic. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions."
},
{
"code": null,
"e": 24994,
"s": 24986,
"text": "Syntax:"
},
{
"code": null,
"e": 25032,
"s": 24994,
"text": "func (v *Value) Store(x interface{})\n"
},
{
"code": null,
"e": 25137,
"s": 25032,
"text": "Here, v is the value of any type and x is the interface which is the output result type of Store method."
},
{
"code": null,
"e": 25308,
"s": 25137,
"text": "Note: (*Value) is the pointer to a Value type. And Value type supplied in the sync/atomic standard package is used to atomically store as well as load values of any type."
},
{
"code": null,
"e": 25384,
"s": 25308,
"text": "Return value: It stores the value provided and can be loaded when required."
},
{
"code": null,
"e": 25395,
"s": 25384,
"text": "Example 1:"
},
{
"code": "// Program to illustrate the usage of// Store function in Golang // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Main functionfunc main() { // Defining a struct type L type L struct{ x, y, z int } // Defining a variable to assign // values to the struct type L var r1 = L{9, 10, 11} // Defining Value type to store // values of any type var V atomic.Value // Calling Store function V.Store(r1) // Printed if the value stated is stored fmt.Println(\"Any type of value is stored!\")}",
"e": 25985,
"s": 25395,
"text": null
},
{
"code": null,
"e": 25993,
"s": 25985,
"text": "Output:"
},
{
"code": null,
"e": 26023,
"s": 25993,
"text": "Any type of value is stored!\n"
},
{
"code": null,
"e": 26176,
"s": 26023,
"text": "In the above example, we have used Value type in order to store the values of any type. And these values are stored at r1 which is the interface stated."
},
{
"code": null,
"e": 26187,
"s": 26176,
"text": "Example 2:"
},
{
"code": "// Program to illustrate the usage of// Store function in Golang // Including main packagepackage main // importing fmt and sync/atomicimport ( \"sync/atomic\") // Main functionfunc main() { // Defining a struct type L type L struct{ x, y, z int } // Defining a variable to assign // values to the struct type L var r1 = L{9, 10, 11} // Defining Value type to store // values of any type var V atomic.Value // Calling Store function V.Store(r1) // Storing value of // different concrete type V.Store(\"GeeksforGeeks\")}",
"e": 26759,
"s": 26187,
"text": null
},
{
"code": null,
"e": 26767,
"s": 26759,
"text": "Output:"
},
{
"code": null,
"e": 27032,
"s": 26767,
"text": "panic: sync/atomic: store of inconsistently typed value into Value\n\ngoroutine 1 [running]:\nsync/atomic.(*Value).Store(0x40c018, 0x99a40, 0xb23e8, 0x40e010)\n /usr/local/go/src/sync/atomic/value.go:77 +0x160\nmain.main()\n /tmp/sandbox206117237/prog.go:31 +0xc0\n"
},
{
"code": null,
"e": 27111,
"s": 27032,
"text": "Here, the value stored above is of different concrete type so panic is called."
},
{
"code": null,
"e": 27125,
"s": 27111,
"text": "GoLang-atomic"
},
{
"code": null,
"e": 27137,
"s": 27125,
"text": "Go Language"
},
{
"code": null,
"e": 27235,
"s": 27137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27286,
"s": 27235,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27299,
"s": 27286,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27332,
"s": 27299,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27379,
"s": 27332,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27396,
"s": 27379,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27408,
"s": 27396,
"text": "Golang Maps"
},
{
"code": null,
"e": 27429,
"s": 27408,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 27451,
"s": 27429,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27505,
"s": 27451,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
How to change the space between bars in a barplot in R?
|
By default, the space between bars is equal irrespective of the number of bars in the plot. If we want to have different space between bars then space arguments need to be used inside the barplot function but the first value does not make an impact because the first space is fixed between Y-axis and the first bar. For example, if we have a vector x that contains three values then the barplot with different space between bars can be created by using the below command −
barplot(x,space=c(0.5,0.1,0.5))
Live Demo
x<-rpois(4,5)
x
[1] 3 8 4 4
barplot(x)
barplot(x,space=c(0.01,0.1,0.5,0.1))
barplot(x,space=c(0.1,0.2,0.2,0.5))
|
[
{
"code": null,
"e": 1535,
"s": 1062,
"text": "By default, the space between bars is equal irrespective of the number of bars in the plot. If we want to have different space between bars then space arguments need to be used inside the barplot function but the first value does not make an impact because the first space is fixed between Y-axis and the first bar. For example, if we have a vector x that contains three values then the barplot with different space between bars can be created by using the below command −"
},
{
"code": null,
"e": 1567,
"s": 1535,
"text": "barplot(x,space=c(0.5,0.1,0.5))"
},
{
"code": null,
"e": 1578,
"s": 1567,
"text": " Live Demo"
},
{
"code": null,
"e": 1594,
"s": 1578,
"text": "x<-rpois(4,5)\nx"
},
{
"code": null,
"e": 1606,
"s": 1594,
"text": "[1] 3 8 4 4"
},
{
"code": null,
"e": 1617,
"s": 1606,
"text": "barplot(x)"
},
{
"code": null,
"e": 1654,
"s": 1617,
"text": "barplot(x,space=c(0.01,0.1,0.5,0.1))"
},
{
"code": null,
"e": 1690,
"s": 1654,
"text": "barplot(x,space=c(0.1,0.2,0.2,0.5))"
}
] |
What is the difference between <html lang="en'> and <html lang="en-US'> ? - GeeksforGeeks
|
08 May, 2020
The lang attribute specifies which language is used to write the content of a web page. It is used to set the language for the whole text of the web page.
The difference between <html lang=”en’> and <html lang=”en-US’> is described below:
<html lang=”en’>The <html lang=”en’> only specifies the language code of the page meaning en or English is used for all the text on the page.
Example:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>lang Attribute</title> <style> body{ text-align: center; } h1{ color: green; } </style></head><body> <h1>GeeksforGeeks</h1> <p>jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document,or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.</p></body></html>
Output:
<html lang=”en-US’>The <html lang=”en-US’> specifies the language code of the page followed by the country code that means US style of English language is used for all the text on the page.
<html lang=”en-GB’> which means the United Kingdom style of English<html lang=”en-IN’> which means the Indian style of English
Example:
<!DOCTYPE html><html lang="en-US"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>lang Attribute</title> <style> body{ text-align: center; } h1{ color: green; } </style></head><body> <h1>GeeksforGeeks</h1> <p>jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.</p></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 26294,
"s": 26139,
"text": "The lang attribute specifies which language is used to write the content of a web page. It is used to set the language for the whole text of the web page."
},
{
"code": null,
"e": 26378,
"s": 26294,
"text": "The difference between <html lang=”en’> and <html lang=”en-US’> is described below:"
},
{
"code": null,
"e": 26520,
"s": 26378,
"text": "<html lang=”en’>The <html lang=”en’> only specifies the language code of the page meaning en or English is used for all the text on the page."
},
{
"code": null,
"e": 26529,
"s": 26520,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>lang Attribute</title> <style> body{ text-align: center; } h1{ color: green; } </style></head><body> <h1>GeeksforGeeks</h1> <p>jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document,or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.</p></body></html>",
"e": 27246,
"s": 26529,
"text": null
},
{
"code": null,
"e": 27254,
"s": 27246,
"text": "Output:"
},
{
"code": null,
"e": 27444,
"s": 27254,
"text": "<html lang=”en-US’>The <html lang=”en-US’> specifies the language code of the page followed by the country code that means US style of English language is used for all the text on the page."
},
{
"code": null,
"e": 27571,
"s": 27444,
"text": "<html lang=”en-GB’> which means the United Kingdom style of English<html lang=”en-IN’> which means the Indian style of English"
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en-US\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>lang Attribute</title> <style> body{ text-align: center; } h1{ color: green; } </style></head><body> <h1>GeeksforGeeks</h1> <p>jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.</p></body></html>",
"e": 28300,
"s": 27580,
"text": null
},
{
"code": null,
"e": 28308,
"s": 28300,
"text": "Output:"
},
{
"code": null,
"e": 28445,
"s": 28308,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28455,
"s": 28445,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28462,
"s": 28455,
"text": "Picked"
},
{
"code": null,
"e": 28467,
"s": 28462,
"text": "HTML"
},
{
"code": null,
"e": 28484,
"s": 28467,
"text": "Web Technologies"
},
{
"code": null,
"e": 28489,
"s": 28484,
"text": "HTML"
},
{
"code": null,
"e": 28587,
"s": 28489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28611,
"s": 28587,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28652,
"s": 28611,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28689,
"s": 28652,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28718,
"s": 28689,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28738,
"s": 28718,
"text": "Angular File Upload"
},
{
"code": null,
"e": 28778,
"s": 28738,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28811,
"s": 28778,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28856,
"s": 28811,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28899,
"s": 28856,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to set the Alignment of the Text in the Label in C#? - GeeksforGeeks
|
30 Jun, 2019
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the alignment of the text present in the Label control using the TextAlign Property in the windows form. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the TextAlign property of the Label control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the TextAlign property of the Label.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the alignment of the text in the Label control programmatically with the help of given syntax:
public virtual System.Drawing.ContentAlignment TextAlign { get; set; }
Here, the ContentAlignment specify the alignment of the text. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to the ContentAlignment values. Following steps are used to set the TextAlign property of the Label:
Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class
Label mylab = new Label();
// Creating label using Label class
Label mylab = new Label();
Step 2: After creating Label, set the TextAlign property of the Label provided by the Label class.// Set TextAlign property of the label
mylab.TextAlign = ContentAlignment.MiddleCenter;
// Set TextAlign property of the label
mylab.TextAlign = ContentAlignment.MiddleCenter;
Step 3: And last add this Label control to form using Add() method.// Add this label to the form
this.Controls.Add(mylab);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font("Calibri", 18); mylab1.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab1); }}}Output:
// Add this label to the form
this.Controls.Add(mylab);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font("Calibri", 18); mylab1.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab1); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Arrays
|
[
{
"code": null,
"e": 25327,
"s": 25299,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 25650,
"s": 25327,
"text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the alignment of the text present in the Label control using the TextAlign Property in the windows form. You can set this property using two different methods:"
},
{
"code": null,
"e": 25769,
"s": 25650,
"text": "1. Design-Time: It is the easiest method to set the TextAlign property of the Label control using the following steps:"
},
{
"code": null,
"e": 25885,
"s": 25769,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26060,
"s": 25885,
"text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 26190,
"s": 26060,
"text": "Step 3: After drag and drop you will go to the properties of the Label control to set the TextAlign property of the Label.Output:"
},
{
"code": null,
"e": 26198,
"s": 26190,
"text": "Output:"
},
{
"code": null,
"e": 26385,
"s": 26198,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the alignment of the text in the Label control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 26456,
"s": 26385,
"text": "public virtual System.Drawing.ContentAlignment TextAlign { get; set; }"
},
{
"code": null,
"e": 26720,
"s": 26456,
"text": "Here, the ContentAlignment specify the alignment of the text. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to the ContentAlignment values. Following steps are used to set the TextAlign property of the Label:"
},
{
"code": null,
"e": 26868,
"s": 26720,
"text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 26932,
"s": 26868,
"text": "// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 27119,
"s": 26932,
"text": "Step 2: After creating Label, set the TextAlign property of the Label provided by the Label class.// Set TextAlign property of the label\nmylab.TextAlign = ContentAlignment.MiddleCenter;\n"
},
{
"code": null,
"e": 27208,
"s": 27119,
"text": "// Set TextAlign property of the label\nmylab.TextAlign = ContentAlignment.MiddleCenter;\n"
},
{
"code": null,
"e": 28711,
"s": 27208,
"text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab1); }}}Output:"
},
{
"code": null,
"e": 28768,
"s": 28711,
"text": "// Add this label to the form\nthis.Controls.Add(mylab);\n"
},
{
"code": null,
"e": 28777,
"s": 28768,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Padding = new Padding(6); mylab.TextAlign = ContentAlignment.MiddleCenter; // Adding this control to the form this.Controls.Add(mylab1); }}}",
"e": 30142,
"s": 28777,
"text": null
},
{
"code": null,
"e": 30150,
"s": 30142,
"text": "Output:"
},
{
"code": null,
"e": 30153,
"s": 30150,
"text": "C#"
},
{
"code": null,
"e": 30251,
"s": 30153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30266,
"s": 30251,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30288,
"s": 30266,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30334,
"s": 30288,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30356,
"s": 30334,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30374,
"s": 30356,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30397,
"s": 30374,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30428,
"s": 30397,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 30468,
"s": 30428,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 30490,
"s": 30468,
"text": "C# | Replace() Method"
}
] |
Data Storage in Docker - GeeksforGeeks
|
06 Oct, 2021
Docker images are built-in form of layers and docker containers store all the data being used, on the container writable layer which is only persisted till the lifespan of the container i.e. it is no longer accessible once the container is removed. This also makes it difficult to get the data out of the container if it is required by some other processes.
To persist the data irrespective of the container’s lifecycle so that the files are available in the host filesystem even if the container is no longer available, Docker provides two options:
Docker volumesBind mounts
Docker volumes
Bind mounts
Though we can also use tmpfs mount if you’re using Docker on Linux and named pipes if using Docker on Windows.
In this article, we’ll be covering the docker volumes and bind mounts with their differences in terms of use cases and effectiveness.
Volumes are the directories or files that exist on the host filesystem and are mounted to the containers for persisting data generated or modified by them. They are stored in the part of the host filesystem managed specifically by Docker and it should not be modified by non-Docker processes. Volumes are the most preferred way to store container data as they provide efficient performance and are isolated from the other functionalities of the Docker host.
We can use the following command to create docker volume -:
docker volume create <volume_name>
We can mount a volume to multiple containers simultaneously and Docker doesn’t remove them even if they’re not being used by any running container. To remove a volume, we can use the following command -:
docker volume prune
In a Linux filesystem, we can find the available volumes at the following path ‘/var/lib/docker/volumes/ ‘, while in Windows, we can get the location of the volume by running the following command in file explorer -:
\\wsl$\docker-desktop-data\version-pack-data\community\docker\volumes
To learn more about volumes and how to mount them to a container click here.
Commands to create volume
This is also a mechanism provided by Docker to store container data on localhost, but the directory or file mounted using bind mounts can be accessed by non-Docker processes as well and it relies on the host machine’s filesystem having a specific directory structure available because it uses absolute path for binding.
Bind mounts have limited functionality and can’t be managed directly through Docker CLI, thus making it less preferable in comparison to volumes. Moreover, it allows the container to modify the host filesystem i.e. it can create, modify or delete important file directories which can impact security and non-Docker processes as well.
When using Docker in Linux, you can also create storage volume for containers using tmpfs mount. But contrary to bind mounts and volumes, this type of mount is temporary and persists on host memory.
Once the container is stopped, the tmpfs mount is removed and files stored using it won’t be available anymore. This type of mount has very limited use and can only be used by Linux users. Moreover, it does not allow sharing of mounted data among containers.
Following are some potential use cases for volumes -:
Volumes can be used to share data among multiple containers in a secure manner without affecting the host filesystem.
They provide convenient backup and data migration from one Docker host to another.
We can easily manage volumes using Docker CLI and Docker APIs, which is a limitation in terms of bind mounts.
The insignificance of host filesystem structure provides decoupling of Docker host configuration from container runtime.
It provides volume drivers which help in storing data to remote hosts or cloud providers.
Volumes are stored in Linux VM thus providing lower latency and higher throughput. They are highly performant on the Docker desktop, thus making them a better choice for write-intensive applications like data storage.
Despite limited functionalities, we can use bind mounts in the following cases -:
It can be used to provide shared configuration files between host and container. Ex- Docker mounts ‘/etc/resolv.conf ‘ to containers for DNS resolution.
In case the host file system is guaranteed to remain consistent and the mounted volume is not accessed by non-Docker processes, we can use bind mounts for storing data.
docker
Picked
Docker
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
Find size of largest subset with bitwise AND greater than their bitwise XOR
Python Raise Keyword
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
|
[
{
"code": null,
"e": 25089,
"s": 25061,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 25447,
"s": 25089,
"text": "Docker images are built-in form of layers and docker containers store all the data being used, on the container writable layer which is only persisted till the lifespan of the container i.e. it is no longer accessible once the container is removed. This also makes it difficult to get the data out of the container if it is required by some other processes."
},
{
"code": null,
"e": 25639,
"s": 25447,
"text": "To persist the data irrespective of the container’s lifecycle so that the files are available in the host filesystem even if the container is no longer available, Docker provides two options:"
},
{
"code": null,
"e": 25665,
"s": 25639,
"text": "Docker volumesBind mounts"
},
{
"code": null,
"e": 25680,
"s": 25665,
"text": "Docker volumes"
},
{
"code": null,
"e": 25692,
"s": 25680,
"text": "Bind mounts"
},
{
"code": null,
"e": 25803,
"s": 25692,
"text": "Though we can also use tmpfs mount if you’re using Docker on Linux and named pipes if using Docker on Windows."
},
{
"code": null,
"e": 25937,
"s": 25803,
"text": "In this article, we’ll be covering the docker volumes and bind mounts with their differences in terms of use cases and effectiveness."
},
{
"code": null,
"e": 26395,
"s": 25937,
"text": "Volumes are the directories or files that exist on the host filesystem and are mounted to the containers for persisting data generated or modified by them. They are stored in the part of the host filesystem managed specifically by Docker and it should not be modified by non-Docker processes. Volumes are the most preferred way to store container data as they provide efficient performance and are isolated from the other functionalities of the Docker host."
},
{
"code": null,
"e": 26455,
"s": 26395,
"text": "We can use the following command to create docker volume -:"
},
{
"code": null,
"e": 26490,
"s": 26455,
"text": "docker volume create <volume_name>"
},
{
"code": null,
"e": 26694,
"s": 26490,
"text": "We can mount a volume to multiple containers simultaneously and Docker doesn’t remove them even if they’re not being used by any running container. To remove a volume, we can use the following command -:"
},
{
"code": null,
"e": 26714,
"s": 26694,
"text": "docker volume prune"
},
{
"code": null,
"e": 26931,
"s": 26714,
"text": "In a Linux filesystem, we can find the available volumes at the following path ‘/var/lib/docker/volumes/ ‘, while in Windows, we can get the location of the volume by running the following command in file explorer -:"
},
{
"code": null,
"e": 27001,
"s": 26931,
"text": "\\\\wsl$\\docker-desktop-data\\version-pack-data\\community\\docker\\volumes"
},
{
"code": null,
"e": 27078,
"s": 27001,
"text": "To learn more about volumes and how to mount them to a container click here."
},
{
"code": null,
"e": 27104,
"s": 27078,
"text": "Commands to create volume"
},
{
"code": null,
"e": 27424,
"s": 27104,
"text": "This is also a mechanism provided by Docker to store container data on localhost, but the directory or file mounted using bind mounts can be accessed by non-Docker processes as well and it relies on the host machine’s filesystem having a specific directory structure available because it uses absolute path for binding."
},
{
"code": null,
"e": 27758,
"s": 27424,
"text": "Bind mounts have limited functionality and can’t be managed directly through Docker CLI, thus making it less preferable in comparison to volumes. Moreover, it allows the container to modify the host filesystem i.e. it can create, modify or delete important file directories which can impact security and non-Docker processes as well."
},
{
"code": null,
"e": 27957,
"s": 27758,
"text": "When using Docker in Linux, you can also create storage volume for containers using tmpfs mount. But contrary to bind mounts and volumes, this type of mount is temporary and persists on host memory."
},
{
"code": null,
"e": 28216,
"s": 27957,
"text": "Once the container is stopped, the tmpfs mount is removed and files stored using it won’t be available anymore. This type of mount has very limited use and can only be used by Linux users. Moreover, it does not allow sharing of mounted data among containers."
},
{
"code": null,
"e": 28270,
"s": 28216,
"text": "Following are some potential use cases for volumes -:"
},
{
"code": null,
"e": 28388,
"s": 28270,
"text": "Volumes can be used to share data among multiple containers in a secure manner without affecting the host filesystem."
},
{
"code": null,
"e": 28471,
"s": 28388,
"text": "They provide convenient backup and data migration from one Docker host to another."
},
{
"code": null,
"e": 28581,
"s": 28471,
"text": "We can easily manage volumes using Docker CLI and Docker APIs, which is a limitation in terms of bind mounts."
},
{
"code": null,
"e": 28702,
"s": 28581,
"text": "The insignificance of host filesystem structure provides decoupling of Docker host configuration from container runtime."
},
{
"code": null,
"e": 28792,
"s": 28702,
"text": "It provides volume drivers which help in storing data to remote hosts or cloud providers."
},
{
"code": null,
"e": 29010,
"s": 28792,
"text": "Volumes are stored in Linux VM thus providing lower latency and higher throughput. They are highly performant on the Docker desktop, thus making them a better choice for write-intensive applications like data storage."
},
{
"code": null,
"e": 29092,
"s": 29010,
"text": "Despite limited functionalities, we can use bind mounts in the following cases -:"
},
{
"code": null,
"e": 29246,
"s": 29092,
"text": "It can be used to provide shared configuration files between host and container. Ex- Docker mounts ‘/etc/resolv.conf ‘ to containers for DNS resolution."
},
{
"code": null,
"e": 29415,
"s": 29246,
"text": "In case the host file system is guaranteed to remain consistent and the mounted volume is not accessed by non-Docker processes, we can use bind mounts for storing data."
},
{
"code": null,
"e": 29422,
"s": 29415,
"text": "docker"
},
{
"code": null,
"e": 29429,
"s": 29422,
"text": "Picked"
},
{
"code": null,
"e": 29436,
"s": 29429,
"text": "Docker"
},
{
"code": null,
"e": 29534,
"s": 29436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29587,
"s": 29534,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29642,
"s": 29587,
"text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?"
},
{
"code": null,
"e": 29718,
"s": 29642,
"text": "Find size of largest subset with bitwise AND greater than their bitwise XOR"
},
{
"code": null,
"e": 29739,
"s": 29718,
"text": "Python Raise Keyword"
},
{
"code": null,
"e": 29797,
"s": 29739,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 29859,
"s": 29797,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29939,
"s": 29859,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29970,
"s": 29939,
"text": "How to Fix: KeyError in Pandas"
},
{
"code": null,
"e": 30011,
"s": 29970,
"text": "C Program to read contents of Whole File"
}
] |
onKeyPress onKeyUp and onKeyDown Events in JavaScript - GeeksforGeeks
|
23 Sep, 2020
In JavaScript, whenever a key is pressed or released, there are certain events that are triggered. Each of these events has a different meaning and can be used for implementing certain functionalities depending upon the current state and the key that is being used.
These events that are triggered when a key is pressed are in the following order:
keydown Event: This event occurs when the user has pressed down the key. It will occur even if the key pressed does not produce a character value.
keypress Event: This event occurs when the user presses a key that produces a character value. These include keys such as the alphabetic, numeric, and punctuation keys. Modifier keys such as ‘Shift’, ‘CapsLock’, ‘Ctrl’ etc. do not produce a character, therefore they have no ‘keypress’ event attached to them.
keyup Event: This event occurs when the user has released the key. It will occur even if the key released does not produce a character value.
Note that different browsers may have different implementations of the above events. The onKeyDown, onKeyPress, and onKeyUp events can be used to detect these events respectively.
The below example shows different events that get triggered when a key is pressed in their respective order.
Example:
HTML
<!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> <b>onKeyPress Vs. onKeyUp and onKeyDown Events</b> </p> <input type="text" id="field" placeholder="Type here"> <p id="status"></p> <script> // Script to test which key // event gets triggered // when a key is pressed var key_pressed = document.getElementById('field'); key_pressed .addEventListener("keydown", onKeyDown); key_pressed .addEventListener("keypress", onKeyPress); key_pressed .addEventListener("keyup", onKeyUp); function onKeyDown(event) { document.getElementById("status") .innerHTML = 'keydown: ' + event.key + '<br>' } function onKeyPress(event) { document.getElementById("status") .innerHTML += 'keypress: ' + event.key + '<br>' } function onKeyUp(event) { document.getElementById("status") .innerHTML += 'keyup: ' + event.key + '<br>' } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
Create a Responsive Navbar using ReactJS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26729,
"s": 26701,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 26995,
"s": 26729,
"text": "In JavaScript, whenever a key is pressed or released, there are certain events that are triggered. Each of these events has a different meaning and can be used for implementing certain functionalities depending upon the current state and the key that is being used."
},
{
"code": null,
"e": 27077,
"s": 26995,
"text": "These events that are triggered when a key is pressed are in the following order:"
},
{
"code": null,
"e": 27224,
"s": 27077,
"text": "keydown Event: This event occurs when the user has pressed down the key. It will occur even if the key pressed does not produce a character value."
},
{
"code": null,
"e": 27534,
"s": 27224,
"text": "keypress Event: This event occurs when the user presses a key that produces a character value. These include keys such as the alphabetic, numeric, and punctuation keys. Modifier keys such as ‘Shift’, ‘CapsLock’, ‘Ctrl’ etc. do not produce a character, therefore they have no ‘keypress’ event attached to them."
},
{
"code": null,
"e": 27676,
"s": 27534,
"text": "keyup Event: This event occurs when the user has released the key. It will occur even if the key released does not produce a character value."
},
{
"code": null,
"e": 27856,
"s": 27676,
"text": "Note that different browsers may have different implementations of the above events. The onKeyDown, onKeyPress, and onKeyUp events can be used to detect these events respectively."
},
{
"code": null,
"e": 27965,
"s": 27856,
"text": "The below example shows different events that get triggered when a key is pressed in their respective order."
},
{
"code": null,
"e": 27974,
"s": 27965,
"text": "Example:"
},
{
"code": null,
"e": 27979,
"s": 27974,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> <b>onKeyPress Vs. onKeyUp and onKeyDown Events</b> </p> <input type=\"text\" id=\"field\" placeholder=\"Type here\"> <p id=\"status\"></p> <script> // Script to test which key // event gets triggered // when a key is pressed var key_pressed = document.getElementById('field'); key_pressed .addEventListener(\"keydown\", onKeyDown); key_pressed .addEventListener(\"keypress\", onKeyPress); key_pressed .addEventListener(\"keyup\", onKeyUp); function onKeyDown(event) { document.getElementById(\"status\") .innerHTML = 'keydown: ' + event.key + '<br>' } function onKeyPress(event) { document.getElementById(\"status\") .innerHTML += 'keypress: ' + event.key + '<br>' } function onKeyUp(event) { document.getElementById(\"status\") .innerHTML += 'keyup: ' + event.key + '<br>' } </script></body> </html>",
"e": 29187,
"s": 27979,
"text": null
},
{
"code": null,
"e": 29195,
"s": 29187,
"text": "Output:"
},
{
"code": null,
"e": 29204,
"s": 29195,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29214,
"s": 29204,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29230,
"s": 29214,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29234,
"s": 29230,
"text": "CSS"
},
{
"code": null,
"e": 29239,
"s": 29234,
"text": "HTML"
},
{
"code": null,
"e": 29250,
"s": 29239,
"text": "JavaScript"
},
{
"code": null,
"e": 29267,
"s": 29250,
"text": "Web Technologies"
},
{
"code": null,
"e": 29272,
"s": 29267,
"text": "HTML"
},
{
"code": null,
"e": 29370,
"s": 29272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29425,
"s": 29370,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29462,
"s": 29425,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29501,
"s": 29462,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29562,
"s": 29501,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29603,
"s": 29562,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29663,
"s": 29603,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29716,
"s": 29663,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29777,
"s": 29716,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29801,
"s": 29777,
"text": "REST API (Introduction)"
}
] |
How to get an object containing parameters of current URL in JavaScript ? - GeeksforGeeks
|
23 Apr, 2021
The purpose of this article is to get an object which contains the parameter of the current URL.
Example:
Input: www.geeksforgeeks.org/search?name=john&age=27
Output: {
name: "john",
age: 27
}
Input: geeksforgeeks.org
Output: {}
To achieve this, we follow the following steps.
Create an empty object.
Using the String.match() method extract all the query params which are separated by ? and &, to achieve this we use the regex /([^?=&]+)(=([^&]*))/g
The String.match() method returns an array containing all the queries.
Using the for...each loop iterates the array and at every iteration split the value at = sign by using the String.split() method. This method returns an array of 2 strings the 0’th string is the left part of the = sign and the 1st string is the right part of the = sign.
Assign the first string as the key and the second string as the value of that key in the newly created object.
Finally, return the newly created object.
Example:
Javascript
<script> function getAllParams(url) { // Create an empty object let obj = {}; // Extract the query params let paramsArray = url.match(/([^?=&]+)(=([^&]*))/g) // Check if there is one or more params if (paramsArray) { // Iterate the params array paramsArray.forEach((query) => { // Split the array let strings = query.split("=") // Assign the values to the object obj[strings[0]] = strings[1] }) } // Return the object return obj; } console.log(getAllParams( "www.geeksforgeeks.org/search?name=john&age=27")) console.log(getAllParams("geeksforgeeks.org"))</script>
Output:
{
age: "27",
name: "john"
}
{}
{}
JavaScript-Methods
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 26642,
"s": 26545,
"text": "The purpose of this article is to get an object which contains the parameter of the current URL."
},
{
"code": null,
"e": 26651,
"s": 26642,
"text": "Example:"
},
{
"code": null,
"e": 26807,
"s": 26651,
"text": "Input: www.geeksforgeeks.org/search?name=john&age=27\nOutput: { \n name: \"john\", \n age: 27\n }\n\nInput: geeksforgeeks.org\nOutput: {}"
},
{
"code": null,
"e": 26855,
"s": 26807,
"text": "To achieve this, we follow the following steps."
},
{
"code": null,
"e": 26879,
"s": 26855,
"text": "Create an empty object."
},
{
"code": null,
"e": 27028,
"s": 26879,
"text": "Using the String.match() method extract all the query params which are separated by ? and &, to achieve this we use the regex /([^?=&]+)(=([^&]*))/g"
},
{
"code": null,
"e": 27099,
"s": 27028,
"text": "The String.match() method returns an array containing all the queries."
},
{
"code": null,
"e": 27370,
"s": 27099,
"text": "Using the for...each loop iterates the array and at every iteration split the value at = sign by using the String.split() method. This method returns an array of 2 strings the 0’th string is the left part of the = sign and the 1st string is the right part of the = sign."
},
{
"code": null,
"e": 27481,
"s": 27370,
"text": "Assign the first string as the key and the second string as the value of that key in the newly created object."
},
{
"code": null,
"e": 27523,
"s": 27481,
"text": "Finally, return the newly created object."
},
{
"code": null,
"e": 27532,
"s": 27523,
"text": "Example:"
},
{
"code": null,
"e": 27543,
"s": 27532,
"text": "Javascript"
},
{
"code": "<script> function getAllParams(url) { // Create an empty object let obj = {}; // Extract the query params let paramsArray = url.match(/([^?=&]+)(=([^&]*))/g) // Check if there is one or more params if (paramsArray) { // Iterate the params array paramsArray.forEach((query) => { // Split the array let strings = query.split(\"=\") // Assign the values to the object obj[strings[0]] = strings[1] }) } // Return the object return obj; } console.log(getAllParams( \"www.geeksforgeeks.org/search?name=john&age=27\")) console.log(getAllParams(\"geeksforgeeks.org\"))</script>",
"e": 28306,
"s": 27543,
"text": null
},
{
"code": null,
"e": 28314,
"s": 28306,
"text": "Output:"
},
{
"code": null,
"e": 28349,
"s": 28314,
"text": "{\n age: \"27\",\n name: \"john\"\n}\n{}"
},
{
"code": null,
"e": 28352,
"s": 28349,
"text": "{}"
},
{
"code": null,
"e": 28373,
"s": 28352,
"text": "\nJavaScript-Methods\n"
},
{
"code": null,
"e": 28393,
"s": 28373,
"text": "\njavascript-object\n"
},
{
"code": null,
"e": 28416,
"s": 28393,
"text": "\nJavaScript-Questions\n"
},
{
"code": null,
"e": 28425,
"s": 28416,
"text": "\nPicked\n"
},
{
"code": null,
"e": 28438,
"s": 28425,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 28457,
"s": 28438,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 28691,
"s": 28457,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n \n "
},
{
"code": null,
"e": 28731,
"s": 28691,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28792,
"s": 28731,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28833,
"s": 28792,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28855,
"s": 28833,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28910,
"s": 28855,
"text": "How to get character array from string in JavaScript?\n"
},
{
"code": null,
"e": 28950,
"s": 28910,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28983,
"s": 28950,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29026,
"s": 28983,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29076,
"s": 29026,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Remove all the child elements of a DOM node in JavaScript - GeeksforGeeks
|
16 Apr, 2019
Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove().Another method to remove all child of a node is to set it’s innerHTML=”” property, it is an empty string which produces the same output. This method is not preferred to use.
Example-1: Using “removeChild()”.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id="btn" type="button" value="Remove Childrens"></body><script> function deleteChild() { var e = document.querySelector("ul"); //e.firstElementChild can be used. var child = e.lastElementChild; while (child) { e.removeChild(child); child = e.lastElementChild; } } var btn = document.getElementById( "btn").onclick = function() { deleteChild(); }</script> </html>
Output:Before Clicking on Button:After Clicking on Button:
Example-2: Using innerHTML=”” property.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Document </title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id="btn" type="button" value="Remove Childrens"></body><script> function deleteChild() { var e = document.querySelector("ul"); e.innerHTML = ""; } var btn = document.getElementById( "btn").onclick = function() { deleteChild(); }</script> </html>
Output:Before Clicking on Button:After Clicking on Button:
Example-3 Using “removeChild()”.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id="btn" type="button" value="Remove Childrens"></body><script> function deleteChild() { var e = document.querySelector("ul"); var first = e.firstElementChild; while (first) { first.remove(); first = e.firstElementChild; } } var btn = document.getElementById( "btn").onclick = function() { deleteChild(); }</script> </html>
Output:Before Clicking on Button:After Clicking on Button:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26299,
"s": 26271,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 26581,
"s": 26299,
"text": "Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove().Another method to remove all child of a node is to set it’s innerHTML=”” property, it is an empty string which produces the same output. This method is not preferred to use."
},
{
"code": null,
"e": 26615,
"s": 26581,
"text": "Example-1: Using “removeChild()”."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Document</title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id=\"btn\" type=\"button\" value=\"Remove Childrens\"></body><script> function deleteChild() { var e = document.querySelector(\"ul\"); //e.firstElementChild can be used. var child = e.lastElementChild; while (child) { e.removeChild(child); child = e.lastElementChild; } } var btn = document.getElementById( \"btn\").onclick = function() { deleteChild(); }</script> </html>",
"e": 27556,
"s": 26615,
"text": null
},
{
"code": null,
"e": 27615,
"s": 27556,
"text": "Output:Before Clicking on Button:After Clicking on Button:"
},
{
"code": null,
"e": 27655,
"s": 27615,
"text": "Example-2: Using innerHTML=”” property."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title> Document </title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id=\"btn\" type=\"button\" value=\"Remove Childrens\"></body><script> function deleteChild() { var e = document.querySelector(\"ul\"); e.innerHTML = \"\"; } var btn = document.getElementById( \"btn\").onclick = function() { deleteChild(); }</script> </html>",
"e": 28434,
"s": 27655,
"text": null
},
{
"code": null,
"e": 28493,
"s": 28434,
"text": "Output:Before Clicking on Button:After Clicking on Button:"
},
{
"code": null,
"e": 28526,
"s": 28493,
"text": "Example-3 Using “removeChild()”."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Document</title></head> <body> <ul> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id=\"btn\" type=\"button\" value=\"Remove Childrens\"></body><script> function deleteChild() { var e = document.querySelector(\"ul\"); var first = e.firstElementChild; while (first) { first.remove(); first = e.firstElementChild; } } var btn = document.getElementById( \"btn\").onclick = function() { deleteChild(); }</script> </html>",
"e": 29410,
"s": 28526,
"text": null
},
{
"code": null,
"e": 29469,
"s": 29410,
"text": "Output:Before Clicking on Button:After Clicking on Button:"
},
{
"code": null,
"e": 29476,
"s": 29469,
"text": "Picked"
},
{
"code": null,
"e": 29487,
"s": 29476,
"text": "JavaScript"
},
{
"code": null,
"e": 29504,
"s": 29487,
"text": "Web Technologies"
},
{
"code": null,
"e": 29531,
"s": 29504,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29629,
"s": 29531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29669,
"s": 29629,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29714,
"s": 29669,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29775,
"s": 29714,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29847,
"s": 29775,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29899,
"s": 29847,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29939,
"s": 29899,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29972,
"s": 29939,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30017,
"s": 29972,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30060,
"s": 30017,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Using Generators for substantial memory savings in Python - GeeksforGeeks
|
10 May, 2020
When memory management and maintaining state between the value generated become a tough job for programmers, Python implemented a friendly solution called Generators.
Generators
With Generators, functions evolve to access and compute data in pieces. Hence functions can return the result to its caller upon request and can maintain its state. Generators maintain the function state by halting the code after producing the value to the caller and upon request, it continues execution from where it is left off.Since Generator access and compute value on-demand, a large chunk of data doesn’t need to be saved in memory entirely and results in substantial memory savings.
yield statement
We can say that a function is a generator when it has a yield statement within the code. Like in a return statement, the yield statement also sends a value to the caller, but it doesn’t exit the function’s execution. Instead, it halts the execution until the next request is received. Upon request, the generator continues executing from where it is left off.
def primeFunction(): prime = None num = 1 while True: num = num + 1 for i in range(2, num): if(num % i) == 0: prime = False break else: prime = True if prime: # yields the value to the caller # and halts the execution yield num def main(): # returns the generator object. prime = primeFunction() # generator executes upon request for i in prime: print(i) if i > 50: break if __name__ == "__main__": main()
Output
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
next, stopIteration and send
How the caller and generator communicate with each other? Here we will discuss 3 in-built functions in python. They are:
next
stopIteration
send
The next function can request a generator for its next value. Upon request, the generator code executes and the yield statement provides the value to the caller. At this point, the generator halts the execution and waits for the next request. Let’s dig deeper by considering a Fibonacci function.
def fibonacci(): values = [] while True: if len(values) < 2: values.append(1) else : # sum up the values and # append the result values.append(sum(values)) # pop the first value in # the list values.pop(0) # yield the latest value to # the caller yield values[-1] continue def main(): fib = fibonacci() print(next(fib)) # 1 print(next(fib)) # 1 print(next(fib)) # 2 print(next(fib)) # 3 print(next(fib)) # 5 if __name__ == "__main__": main()
Output
1
1
2
3
5
Creating the generator object by calling the fibonacci function and saving its returned value to fib. In this case, the code hasn’t run, the python interpreter recognizes the generator and returns the generator object. Since the function has a yield statement the generator object is returned instead of a value.fib = fibonacci()fibOutputgenerator object fibonacci at 0x00000157F8AA87C8
fib = fibonacci()fib
Output
generator object fibonacci at 0x00000157F8AA87C8
Using next function, the caller requests a value to the generator and the execution begins.next(gen)Output1
next(gen)Output
1
Since the values list is empty the code within the ‘if statement’ is executed and `1` is appended to the values list. Next, the value is yielded to the caller using yield statement and the execution halts. The point to note here is that the execution halts before executing the continue statement.# values = []if len(values) < 2: # values = [1] values.append(1) # 1yield values[-1]continue
# values = []if len(values) < 2: # values = [1] values.append(1) # 1yield values[-1]continue
Upon the second request the code continues execution from where it left off. Here it executes from the `continue` statement and passes the control to the while loop.Now the values list contains a value from the first request. Since the length of the ‘values` is 1 and is less than 2 the code within the ‘if statement’ executes.# values = [1]if len(values) < 2: # values = [1, 1] values.append(1) # 1 (latest value is provided # to the caller)yield values[-1]continue
# values = [1]if len(values) < 2: # values = [1, 1] values.append(1) # 1 (latest value is provided # to the caller)yield values[-1]continue
Again, the value is requested using next(fib) and the execution starts from `continue` statement. Now the length of the values is not less than 2. Hence it enters the else statement and sums up the values in the list and appends the result. The pop statement removes the first element from the list and yields the latest result.# values = [1, 1]else: # values = [1, 1, 2] values.append(sum(values)) # values = [1, 2] values.pop(0) # 2yield values[-1]continue
# values = [1, 1]else: # values = [1, 1, 2] values.append(sum(values)) # values = [1, 2] values.pop(0) # 2yield values[-1]continue
Your request for more values will repeat the pattern and yield the latest value
StopIteration is a built-in exception that is used to exit from a Generator. When the generator’s iteration is complete, it signals the caller by raising the StopIteration exception and it exits.
Below code explains the scenario.
def stopIteration(): num = 5 for i in range(1, num): yield i def main(): f = stopIteration() # 1 is generated print(next(f)) # 2 is generated print(next(f)) # 3 is generated print(next(f)) # 4 is generated print(next(f)) # 5th element - raises # StopIteration Exception next(f) if __name__ == "__main__": main()
Output
1234Traceback (most recent call last):File “C:\Users\Sonu George\Documents\GeeksforGeeks\Python Pro\Generators\stopIteration.py”, line 19, inmain()File “C:\Users\Sonu George\Documents\GeeksforGeeks\Python Pro\Generators\stopIteration.py”, line 15, in mainnext(f) # 5th element – raises StopIteration ExceptionStopIteration
The below code explains another scenario, where a programmer can raise StopIteration and exit from the generator.raise StopIteration
def stopIteration(): num = 5 for i in range(1, num): if i == 3: raise StopIteration yield i def main(): f = stopIteration() # 1 is generated print(next(f)) # 2 is generated print(next(f)) # StopIteration raises and # code exits print(next(f)) print(next(f)) if __name__ == "__main__": main()
Output
12Traceback (most recent call last):File “C:\Users\Sonu George\Documents\GeeksforGeeks\Python Pro\Generators\stopIteration.py”, line 5, in stopIterationraise StopIterationStopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):File “C:\Users\Sonu George\Documents\GeeksforGeeks\Python Pro\Generators\stopIteration.py”, line 19, inmain()File “C:\Users\Sonu George\Documents\GeeksforGeeks\Python Pro\Generators\stopIteration.py”, line 13, in mainprint(next(f)) # StopIteration raises and code exitsRuntimeError: generator raised StopIteration
So far, we have seen how generator yield values to the invoking code where the communication is unidirectional. As of now, the generator hasn’t received any data from the caller.In this section, we will discuss the `send` method that allows the caller to communicate with the generator.
def factorial(): num = 1 while True: factorial = 1 for i in range(1, num + 1): # determines the factorial factorial = factorial * i # produce the factorial to the caller response = yield factorial # if the response has value if response: # assigns the response to # num variable num = int(response) else: # num variable is incremented # by 1 num = num + 1 def main(): fact = factorial() print(next(fact)) print(next(fact)) print(next(fact)) print(fact.send(5)) # send print(next(fact)) if __name__ == "__main__": main()
Output
1
2
6
120
720
The generator yields the first three values (1, 2 and 6) based on the request by the caller (using the next method) and the fourth value (120) is produced based on the data (5) provided by the caller (using send method).Let’s consider the 3rd data (6) yielded by the generator. Factorial of 3 = 3*2*1, which is yielded by the generator and the execution halts.
factorial = factorial * i
At this point, the caller uses the `send` method and provide the data ‘5`. Hence generator executes from where it is left off i.e. saves the data sent by the caller to the `response` variable (response = yield factorial). Since the `response` contains a value, the code enters the `if` condition and assigns the response to the `num` variable.
if response: num = int(response)
Now the flow passes to the `while` loop and determines the factorial and is yielded to the caller. Again, the generator halts the execution until the next request.
If we look into the output, we can see that the order got interrupted after the caller uses the `send` method. More precisely, within the first 3 requests the output as follows:Factorial of 1 = 1Factorial of 2 = 2Factorial of 3 = 6
But when the user sends the value 5 the output becomes 120 and the `num` maintains the value 5. On the next request (using `next`) we expect num to get incremented based on last `next` request (i.e. 3+1 = 4) rather than the `send` method. But in this case, the `num` increments to 6 (based on last value using `send`) and produces the output 720.
The below code shows a different approach in handling values sent by the caller.
def factorial(): num = 0 value = None response = None while True: factorial = 1 if response: value = int(response) else: num = num + 1 value = num for i in range(1, value + 1): factorial = factorial * i response = yield factorial def main(): fact = factorial() print(next(fact)) print(next(fact)) print(next(fact)) print(fact.send(5)) # send print(next(fact)) if __name__ == "__main__": main()
Output
1
2
6
120
24
Standard Library
range
dict.items
zip
map
File Objects
Range function returns an iterable range object and its iterator is a generator. It returns the sequential value which starts from the lower limit and continues till the upper limit is reached.
def range_func(): r = range(0, 4) return r def main(): r = range_func() iterator = iter(r) print(next(iterator)) print(next(iterator)) if __name__ == "__main__": main()
Output
0
1
Dictionary class in python provides three iterable methods to iterate the dictionary. They are key, values and items and their iterators are generators.
def dict_func(): dictionary = {'UserName': 'abc', 'Password':'a@123'} return dictionary def main(): d = dict_func() iterator = iter(d.items()) print(next(iterator)) print(next(iterator)) if __name__ == "__main__": main()
Output
('UserName', 'abc')
('Password', 'a@123')
zip is a built-in python function which takes multiple iterable object and iterates all at once. They yield the first element from each iterable, then the second and so on.
def zip_func(): z = zip(['a', 'b', 'c', 'd'], [1, 2, 3, 4]) return z def main(): z = zip_func() print(next(z)) print(next(z)) print(next(z)) if __name__ == "__main__": main()
Output
('a', 1)
('b', 2)
('c', 3)
The map function takes function and iterables as parameters and computes the result of the function to each item of the iterable.
def map_func(): m = map(lambda x, y: max([x, y]), [8, 2, 9], [5, 3, 7]) return m def main(): m = map_func() print(next(m)) # 8 (maximum value among 8 and 5) print(next(m)) # 3 (maximum value among 2 and 3) print(next(m)) # 9 (maximum value among 9 and 7) if __name__ == "__main__": main()
Output
8
3
9
Even though the file object has a readline method to read the file line by line, it supports the generator pattern. One difference is that here the readline method catches the StopIteration exception and returns an empty string once the end of file is reached, which is different while using the next method.
While using next method, file object yields the entire line including the newline (\n) character
def file_func(): f = open('sample.txt') return f def main(): f = file_func() print(next(f)) print(next(f)) if __name__ == "__main__": main()
Input: sample.txt
Rule 1
Rule 2
Rule 3
Rule 4
Output
Rule 1
Rule 2
Generator Use Cases
The Fundamental concept of Generator is determining the value on demand. Below we will discuss two use cases that derive from the above concept.
Accessing Data in Pieces
Computing Data in Pieces
Why do we need to access data in pieces? The question is valid when the programmer has to deal with a large amount of data, say reading a file and so. In this case, making a copy of data and processing it is not a feasible solution. By using generators, programmers can access the data one at a time. When considering file operation, the user can access data line by line and in case of a dictionary, two-tuple at a time.Hence Generator is an essential tool to deal with a large chunk of data that avoids unnecessary storage of the data and results in substantial memory savings.
Another reason to write a Generator is its ability to compute data on request. From the above Fibonacci function, one can understand that the generator produces the value on demand. This process avoids unnecessary computing and storing the values and hence can increase the performance and also results in substantial memory savings.Another point to note is that the generator’s ability to compute an infinite number of data.
yield from
The generator can invoke another generator as a function does. Using ‘yield from’ statement a generator can achieve this, and the process is called Generator Delegation.Since the generator is delegating to another generator, the values sent to the wrapping generator will be available to the current delegate generator.
def gensub1(): yield 'A' yield 'B' def gensub2(): yield '100' yield '200' def main_gen(): yield from gensub1() yield from gensub2() def main(): delg = main_gen() print(next(delg)) print(next(delg)) print(next(delg)) print(next(delg)) if __name__ == "__main__": main()
Output
A
B
100
200
A generator is an essential tool for programmers who deal with large amounts of data. Its ability to compute and access data on-demand results in terms of both increase in performance and memory savings. And also, consider using generators when there is a need to represent an infinite sequence.
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25615,
"s": 25587,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 25782,
"s": 25615,
"text": "When memory management and maintaining state between the value generated become a tough job for programmers, Python implemented a friendly solution called Generators."
},
{
"code": null,
"e": 25793,
"s": 25782,
"text": "Generators"
},
{
"code": null,
"e": 26285,
"s": 25793,
"text": "With Generators, functions evolve to access and compute data in pieces. Hence functions can return the result to its caller upon request and can maintain its state. Generators maintain the function state by halting the code after producing the value to the caller and upon request, it continues execution from where it is left off.Since Generator access and compute value on-demand, a large chunk of data doesn’t need to be saved in memory entirely and results in substantial memory savings."
},
{
"code": null,
"e": 26301,
"s": 26285,
"text": "yield statement"
},
{
"code": null,
"e": 26661,
"s": 26301,
"text": "We can say that a function is a generator when it has a yield statement within the code. Like in a return statement, the yield statement also sends a value to the caller, but it doesn’t exit the function’s execution. Instead, it halts the execution until the next request is received. Upon request, the generator continues executing from where it is left off."
},
{
"code": "def primeFunction(): prime = None num = 1 while True: num = num + 1 for i in range(2, num): if(num % i) == 0: prime = False break else: prime = True if prime: # yields the value to the caller # and halts the execution yield num def main(): # returns the generator object. prime = primeFunction() # generator executes upon request for i in prime: print(i) if i > 50: break if __name__ == \"__main__\": main()",
"e": 27271,
"s": 26661,
"text": null
},
{
"code": null,
"e": 27278,
"s": 27271,
"text": "Output"
},
{
"code": null,
"e": 27321,
"s": 27278,
"text": "3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n53\n"
},
{
"code": null,
"e": 27350,
"s": 27321,
"text": "next, stopIteration and send"
},
{
"code": null,
"e": 27471,
"s": 27350,
"text": "How the caller and generator communicate with each other? Here we will discuss 3 in-built functions in python. They are:"
},
{
"code": null,
"e": 27476,
"s": 27471,
"text": "next"
},
{
"code": null,
"e": 27490,
"s": 27476,
"text": "stopIteration"
},
{
"code": null,
"e": 27495,
"s": 27490,
"text": "send"
},
{
"code": null,
"e": 27792,
"s": 27495,
"text": "The next function can request a generator for its next value. Upon request, the generator code executes and the yield statement provides the value to the caller. At this point, the generator halts the execution and waits for the next request. Let’s dig deeper by considering a Fibonacci function."
},
{
"code": "def fibonacci(): values = [] while True: if len(values) < 2: values.append(1) else : # sum up the values and # append the result values.append(sum(values)) # pop the first value in # the list values.pop(0) # yield the latest value to # the caller yield values[-1] continue def main(): fib = fibonacci() print(next(fib)) # 1 print(next(fib)) # 1 print(next(fib)) # 2 print(next(fib)) # 3 print(next(fib)) # 5 if __name__ == \"__main__\": main()",
"e": 28422,
"s": 27792,
"text": null
},
{
"code": null,
"e": 28429,
"s": 28422,
"text": "Output"
},
{
"code": null,
"e": 28440,
"s": 28429,
"text": "1\n1\n2\n3\n5\n"
},
{
"code": null,
"e": 28827,
"s": 28440,
"text": "Creating the generator object by calling the fibonacci function and saving its returned value to fib. In this case, the code hasn’t run, the python interpreter recognizes the generator and returns the generator object. Since the function has a yield statement the generator object is returned instead of a value.fib = fibonacci()fibOutputgenerator object fibonacci at 0x00000157F8AA87C8"
},
{
"code": "fib = fibonacci()fib",
"e": 28848,
"s": 28827,
"text": null
},
{
"code": null,
"e": 28855,
"s": 28848,
"text": "Output"
},
{
"code": null,
"e": 28904,
"s": 28855,
"text": "generator object fibonacci at 0x00000157F8AA87C8"
},
{
"code": null,
"e": 29012,
"s": 28904,
"text": "Using next function, the caller requests a value to the generator and the execution begins.next(gen)Output1"
},
{
"code": null,
"e": 29028,
"s": 29012,
"text": "next(gen)Output"
},
{
"code": null,
"e": 29030,
"s": 29028,
"text": "1"
},
{
"code": null,
"e": 29429,
"s": 29030,
"text": "Since the values list is empty the code within the ‘if statement’ is executed and `1` is appended to the values list. Next, the value is yielded to the caller using yield statement and the execution halts. The point to note here is that the execution halts before executing the continue statement.# values = []if len(values) < 2: # values = [1] values.append(1) # 1yield values[-1]continue"
},
{
"code": "# values = []if len(values) < 2: # values = [1] values.append(1) # 1yield values[-1]continue",
"e": 29531,
"s": 29429,
"text": null
},
{
"code": null,
"e": 30007,
"s": 29531,
"text": "Upon the second request the code continues execution from where it left off. Here it executes from the `continue` statement and passes the control to the while loop.Now the values list contains a value from the first request. Since the length of the ‘values` is 1 and is less than 2 the code within the ‘if statement’ executes.# values = [1]if len(values) < 2: # values = [1, 1] values.append(1) # 1 (latest value is provided # to the caller)yield values[-1]continue"
},
{
"code": "# values = [1]if len(values) < 2: # values = [1, 1] values.append(1) # 1 (latest value is provided # to the caller)yield values[-1]continue",
"e": 30156,
"s": 30007,
"text": null
},
{
"code": null,
"e": 30644,
"s": 30156,
"text": "Again, the value is requested using next(fib) and the execution starts from `continue` statement. Now the length of the values is not less than 2. Hence it enters the else statement and sums up the values in the list and appends the result. The pop statement removes the first element from the list and yields the latest result.# values = [1, 1]else: # values = [1, 1, 2] values.append(sum(values)) # values = [1, 2] values.pop(0) # 2yield values[-1]continue"
},
{
"code": "# values = [1, 1]else: # values = [1, 1, 2] values.append(sum(values)) # values = [1, 2] values.pop(0) # 2yield values[-1]continue",
"e": 30804,
"s": 30644,
"text": null
},
{
"code": null,
"e": 30884,
"s": 30804,
"text": "Your request for more values will repeat the pattern and yield the latest value"
},
{
"code": null,
"e": 31080,
"s": 30884,
"text": "StopIteration is a built-in exception that is used to exit from a Generator. When the generator’s iteration is complete, it signals the caller by raising the StopIteration exception and it exits."
},
{
"code": null,
"e": 31114,
"s": 31080,
"text": "Below code explains the scenario."
},
{
"code": "def stopIteration(): num = 5 for i in range(1, num): yield i def main(): f = stopIteration() # 1 is generated print(next(f)) # 2 is generated print(next(f)) # 3 is generated print(next(f)) # 4 is generated print(next(f)) # 5th element - raises # StopIteration Exception next(f) if __name__ == \"__main__\": main() ",
"e": 31521,
"s": 31114,
"text": null
},
{
"code": null,
"e": 31528,
"s": 31521,
"text": "Output"
},
{
"code": null,
"e": 31851,
"s": 31528,
"text": "1234Traceback (most recent call last):File “C:\\Users\\Sonu George\\Documents\\GeeksforGeeks\\Python Pro\\Generators\\stopIteration.py”, line 19, inmain()File “C:\\Users\\Sonu George\\Documents\\GeeksforGeeks\\Python Pro\\Generators\\stopIteration.py”, line 15, in mainnext(f) # 5th element – raises StopIteration ExceptionStopIteration"
},
{
"code": null,
"e": 31984,
"s": 31851,
"text": "The below code explains another scenario, where a programmer can raise StopIteration and exit from the generator.raise StopIteration"
},
{
"code": "def stopIteration(): num = 5 for i in range(1, num): if i == 3: raise StopIteration yield i def main(): f = stopIteration() # 1 is generated print(next(f)) # 2 is generated print(next(f)) # StopIteration raises and # code exits print(next(f)) print(next(f)) if __name__ == \"__main__\": main()",
"e": 32378,
"s": 31984,
"text": null
},
{
"code": null,
"e": 32385,
"s": 32378,
"text": "Output"
},
{
"code": null,
"e": 32570,
"s": 32385,
"text": "12Traceback (most recent call last):File “C:\\Users\\Sonu George\\Documents\\GeeksforGeeks\\Python Pro\\Generators\\stopIteration.py”, line 5, in stopIterationraise StopIterationStopIteration"
},
{
"code": null,
"e": 32639,
"s": 32570,
"text": "The above exception was the direct cause of the following exception:"
},
{
"code": null,
"e": 32987,
"s": 32639,
"text": "Traceback (most recent call last):File “C:\\Users\\Sonu George\\Documents\\GeeksforGeeks\\Python Pro\\Generators\\stopIteration.py”, line 19, inmain()File “C:\\Users\\Sonu George\\Documents\\GeeksforGeeks\\Python Pro\\Generators\\stopIteration.py”, line 13, in mainprint(next(f)) # StopIteration raises and code exitsRuntimeError: generator raised StopIteration"
},
{
"code": null,
"e": 33274,
"s": 32987,
"text": "So far, we have seen how generator yield values to the invoking code where the communication is unidirectional. As of now, the generator hasn’t received any data from the caller.In this section, we will discuss the `send` method that allows the caller to communicate with the generator."
},
{
"code": "def factorial(): num = 1 while True: factorial = 1 for i in range(1, num + 1): # determines the factorial factorial = factorial * i # produce the factorial to the caller response = yield factorial # if the response has value if response: # assigns the response to # num variable num = int(response) else: # num variable is incremented # by 1 num = num + 1 def main(): fact = factorial() print(next(fact)) print(next(fact)) print(next(fact)) print(fact.send(5)) # send print(next(fact)) if __name__ == \"__main__\": main()",
"e": 34023,
"s": 33274,
"text": null
},
{
"code": null,
"e": 34030,
"s": 34023,
"text": "Output"
},
{
"code": null,
"e": 34045,
"s": 34030,
"text": "1\n2\n6\n120\n720\n"
},
{
"code": null,
"e": 34406,
"s": 34045,
"text": "The generator yields the first three values (1, 2 and 6) based on the request by the caller (using the next method) and the fourth value (120) is produced based on the data (5) provided by the caller (using send method).Let’s consider the 3rd data (6) yielded by the generator. Factorial of 3 = 3*2*1, which is yielded by the generator and the execution halts."
},
{
"code": null,
"e": 34433,
"s": 34406,
"text": "factorial = factorial * i "
},
{
"code": null,
"e": 34777,
"s": 34433,
"text": "At this point, the caller uses the `send` method and provide the data ‘5`. Hence generator executes from where it is left off i.e. saves the data sent by the caller to the `response` variable (response = yield factorial). Since the `response` contains a value, the code enters the `if` condition and assigns the response to the `num` variable."
},
{
"code": "if response: num = int(response)",
"e": 34813,
"s": 34777,
"text": null
},
{
"code": null,
"e": 34977,
"s": 34813,
"text": "Now the flow passes to the `while` loop and determines the factorial and is yielded to the caller. Again, the generator halts the execution until the next request."
},
{
"code": null,
"e": 35209,
"s": 34977,
"text": "If we look into the output, we can see that the order got interrupted after the caller uses the `send` method. More precisely, within the first 3 requests the output as follows:Factorial of 1 = 1Factorial of 2 = 2Factorial of 3 = 6"
},
{
"code": null,
"e": 35556,
"s": 35209,
"text": "But when the user sends the value 5 the output becomes 120 and the `num` maintains the value 5. On the next request (using `next`) we expect num to get incremented based on last `next` request (i.e. 3+1 = 4) rather than the `send` method. But in this case, the `num` increments to 6 (based on last value using `send`) and produces the output 720."
},
{
"code": null,
"e": 35637,
"s": 35556,
"text": "The below code shows a different approach in handling values sent by the caller."
},
{
"code": "def factorial(): num = 0 value = None response = None while True: factorial = 1 if response: value = int(response) else: num = num + 1 value = num for i in range(1, value + 1): factorial = factorial * i response = yield factorial def main(): fact = factorial() print(next(fact)) print(next(fact)) print(next(fact)) print(fact.send(5)) # send print(next(fact)) if __name__ == \"__main__\": main()",
"e": 36173,
"s": 35637,
"text": null
},
{
"code": null,
"e": 36180,
"s": 36173,
"text": "Output"
},
{
"code": null,
"e": 36194,
"s": 36180,
"text": "1\n2\n6\n120\n24\n"
},
{
"code": null,
"e": 36211,
"s": 36194,
"text": "Standard Library"
},
{
"code": null,
"e": 36217,
"s": 36211,
"text": "range"
},
{
"code": null,
"e": 36228,
"s": 36217,
"text": "dict.items"
},
{
"code": null,
"e": 36232,
"s": 36228,
"text": "zip"
},
{
"code": null,
"e": 36236,
"s": 36232,
"text": "map"
},
{
"code": null,
"e": 36249,
"s": 36236,
"text": "File Objects"
},
{
"code": null,
"e": 36443,
"s": 36249,
"text": "Range function returns an iterable range object and its iterator is a generator. It returns the sequential value which starts from the lower limit and continues till the upper limit is reached."
},
{
"code": "def range_func(): r = range(0, 4) return r def main(): r = range_func() iterator = iter(r) print(next(iterator)) print(next(iterator)) if __name__ == \"__main__\": main()",
"e": 36635,
"s": 36443,
"text": null
},
{
"code": null,
"e": 36642,
"s": 36635,
"text": "Output"
},
{
"code": null,
"e": 36647,
"s": 36642,
"text": "0\n1\n"
},
{
"code": null,
"e": 36800,
"s": 36647,
"text": "Dictionary class in python provides three iterable methods to iterate the dictionary. They are key, values and items and their iterators are generators."
},
{
"code": "def dict_func(): dictionary = {'UserName': 'abc', 'Password':'a@123'} return dictionary def main(): d = dict_func() iterator = iter(d.items()) print(next(iterator)) print(next(iterator)) if __name__ == \"__main__\": main()",
"e": 37044,
"s": 36800,
"text": null
},
{
"code": null,
"e": 37051,
"s": 37044,
"text": "Output"
},
{
"code": null,
"e": 37094,
"s": 37051,
"text": "('UserName', 'abc')\n('Password', 'a@123')\n"
},
{
"code": null,
"e": 37267,
"s": 37094,
"text": "zip is a built-in python function which takes multiple iterable object and iterates all at once. They yield the first element from each iterable, then the second and so on."
},
{
"code": "def zip_func(): z = zip(['a', 'b', 'c', 'd'], [1, 2, 3, 4]) return z def main(): z = zip_func() print(next(z)) print(next(z)) print(next(z)) if __name__ == \"__main__\": main()",
"e": 37465,
"s": 37267,
"text": null
},
{
"code": null,
"e": 37472,
"s": 37465,
"text": "Output"
},
{
"code": null,
"e": 37500,
"s": 37472,
"text": "('a', 1)\n('b', 2)\n('c', 3)\n"
},
{
"code": null,
"e": 37630,
"s": 37500,
"text": "The map function takes function and iterables as parameters and computes the result of the function to each item of the iterable."
},
{
"code": "def map_func(): m = map(lambda x, y: max([x, y]), [8, 2, 9], [5, 3, 7]) return m def main(): m = map_func() print(next(m)) # 8 (maximum value among 8 and 5) print(next(m)) # 3 (maximum value among 2 and 3) print(next(m)) # 9 (maximum value among 9 and 7) if __name__ == \"__main__\": main()",
"e": 37945,
"s": 37630,
"text": null
},
{
"code": null,
"e": 37952,
"s": 37945,
"text": "Output"
},
{
"code": null,
"e": 37959,
"s": 37952,
"text": "8\n3\n9\n"
},
{
"code": null,
"e": 38268,
"s": 37959,
"text": "Even though the file object has a readline method to read the file line by line, it supports the generator pattern. One difference is that here the readline method catches the StopIteration exception and returns an empty string once the end of file is reached, which is different while using the next method."
},
{
"code": null,
"e": 38365,
"s": 38268,
"text": "While using next method, file object yields the entire line including the newline (\\n) character"
},
{
"code": "def file_func(): f = open('sample.txt') return f def main(): f = file_func() print(next(f)) print(next(f)) if __name__ == \"__main__\": main()",
"e": 38530,
"s": 38365,
"text": null
},
{
"code": null,
"e": 38548,
"s": 38530,
"text": "Input: sample.txt"
},
{
"code": null,
"e": 38577,
"s": 38548,
"text": "Rule 1\nRule 2\nRule 3\nRule 4\n"
},
{
"code": null,
"e": 38584,
"s": 38577,
"text": "Output"
},
{
"code": null,
"e": 38600,
"s": 38584,
"text": "Rule 1\n\nRule 2\n"
},
{
"code": null,
"e": 38620,
"s": 38600,
"text": "Generator Use Cases"
},
{
"code": null,
"e": 38765,
"s": 38620,
"text": "The Fundamental concept of Generator is determining the value on demand. Below we will discuss two use cases that derive from the above concept."
},
{
"code": null,
"e": 38790,
"s": 38765,
"text": "Accessing Data in Pieces"
},
{
"code": null,
"e": 38815,
"s": 38790,
"text": "Computing Data in Pieces"
},
{
"code": null,
"e": 39395,
"s": 38815,
"text": "Why do we need to access data in pieces? The question is valid when the programmer has to deal with a large amount of data, say reading a file and so. In this case, making a copy of data and processing it is not a feasible solution. By using generators, programmers can access the data one at a time. When considering file operation, the user can access data line by line and in case of a dictionary, two-tuple at a time.Hence Generator is an essential tool to deal with a large chunk of data that avoids unnecessary storage of the data and results in substantial memory savings."
},
{
"code": null,
"e": 39821,
"s": 39395,
"text": "Another reason to write a Generator is its ability to compute data on request. From the above Fibonacci function, one can understand that the generator produces the value on demand. This process avoids unnecessary computing and storing the values and hence can increase the performance and also results in substantial memory savings.Another point to note is that the generator’s ability to compute an infinite number of data."
},
{
"code": null,
"e": 39832,
"s": 39821,
"text": "yield from"
},
{
"code": null,
"e": 40152,
"s": 39832,
"text": "The generator can invoke another generator as a function does. Using ‘yield from’ statement a generator can achieve this, and the process is called Generator Delegation.Since the generator is delegating to another generator, the values sent to the wrapping generator will be available to the current delegate generator."
},
{
"code": "def gensub1(): yield 'A' yield 'B' def gensub2(): yield '100' yield '200' def main_gen(): yield from gensub1() yield from gensub2() def main(): delg = main_gen() print(next(delg)) print(next(delg)) print(next(delg)) print(next(delg)) if __name__ == \"__main__\": main()",
"e": 40464,
"s": 40152,
"text": null
},
{
"code": null,
"e": 40471,
"s": 40464,
"text": "Output"
},
{
"code": null,
"e": 40484,
"s": 40471,
"text": "A\nB\n100\n200\n"
},
{
"code": null,
"e": 40780,
"s": 40484,
"text": "A generator is an essential tool for programmers who deal with large amounts of data. Its ability to compute and access data on-demand results in terms of both increase in performance and memory savings. And also, consider using generators when there is a need to represent an infinite sequence."
},
{
"code": null,
"e": 40797,
"s": 40780,
"text": "Python-Functions"
},
{
"code": null,
"e": 40804,
"s": 40797,
"text": "Python"
},
{
"code": null,
"e": 40902,
"s": 40804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40920,
"s": 40902,
"text": "Python Dictionary"
},
{
"code": null,
"e": 40955,
"s": 40920,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 40987,
"s": 40955,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 41029,
"s": 40987,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 41055,
"s": 41029,
"text": "Python String | replace()"
},
{
"code": null,
"e": 41099,
"s": 41055,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 41128,
"s": 41099,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 41164,
"s": 41128,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 41201,
"s": 41164,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to set the margins of a paragraph element using CSS ? - GeeksforGeeks
|
25 May, 2021
The CSS margins properties are used to make space around components, outside any characterized borders. With CSS, you have full power over the margins. There are properties for setting the edge for each side of a component (top, right, base, and left).
CSS has properties for indicating the edge for each side of a component.
margin-top
margin-right
margin-bottom
margin-left
All the margin properties can have the following values.
auto: The browser calculates the margin
length: It specifies a margin in px, pt, and cm, etc.
%: It specifies a margin in % of the width of the containing element.
inherit: It specifies that the margin should be inherited from the parent element.
Example 1: In the following example, the HTML div is used for the styling of the paragraph. The border width will be 5px with solid blue color. The margin of the paragraph is according to top margin 50px, right margin 50px, bottom margin 100px, left margin 100px, background-color red.
HTML
<!DOCTYPE html><html> <head> <style> div { border: 5px solid blue; margin: 50px 50px 100px 100px; background-color: red; } </style> </head> <body> <h2 style="color: green">GeeksforGeeks</h2> <b>Set margin of paragraph element</b> <div> When compared with C++, Java codes are generally more maintainable because Java does not allow many things which may lead bad/inefficient programming if used incorrectly. For example, non-primitives are always references in Java. So we cannot pass large objects (like we can do in C++) to functions, we always pass references in Java. One more example, since there are no pointers, bad memory access is also not possible. </div> </body></html>
Output:
Example 2: In the following example, the width is 300px, the margin of the paragraph will be the same, and it will be in the center as it has margin: auto. The border width is 80px with purple color.
HTML
<!DOCTYPE html><html> <head> <style> div { width: 300px; margin: auto; border: 80px solid purple; } </style> </head> <body> <h2 style="color: green">GeeksforGeeks</h2> <b>Use of margin:auto</b> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> <div> This div will be horizontally centered because it has <i>margin:auto;</i> </div> </body></html>
Output:
margin auto
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26874,
"s": 26621,
"text": "The CSS margins properties are used to make space around components, outside any characterized borders. With CSS, you have full power over the margins. There are properties for setting the edge for each side of a component (top, right, base, and left)."
},
{
"code": null,
"e": 26947,
"s": 26874,
"text": "CSS has properties for indicating the edge for each side of a component."
},
{
"code": null,
"e": 26958,
"s": 26947,
"text": "margin-top"
},
{
"code": null,
"e": 26971,
"s": 26958,
"text": "margin-right"
},
{
"code": null,
"e": 26985,
"s": 26971,
"text": "margin-bottom"
},
{
"code": null,
"e": 26997,
"s": 26985,
"text": "margin-left"
},
{
"code": null,
"e": 27054,
"s": 26997,
"text": "All the margin properties can have the following values."
},
{
"code": null,
"e": 27094,
"s": 27054,
"text": "auto: The browser calculates the margin"
},
{
"code": null,
"e": 27148,
"s": 27094,
"text": "length: It specifies a margin in px, pt, and cm, etc."
},
{
"code": null,
"e": 27218,
"s": 27148,
"text": "%: It specifies a margin in % of the width of the containing element."
},
{
"code": null,
"e": 27301,
"s": 27218,
"text": "inherit: It specifies that the margin should be inherited from the parent element."
},
{
"code": null,
"e": 27587,
"s": 27301,
"text": "Example 1: In the following example, the HTML div is used for the styling of the paragraph. The border width will be 5px with solid blue color. The margin of the paragraph is according to top margin 50px, right margin 50px, bottom margin 100px, left margin 100px, background-color red."
},
{
"code": null,
"e": 27592,
"s": 27587,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div { border: 5px solid blue; margin: 50px 50px 100px 100px; background-color: red; } </style> </head> <body> <h2 style=\"color: green\">GeeksforGeeks</h2> <b>Set margin of paragraph element</b> <div> When compared with C++, Java codes are generally more maintainable because Java does not allow many things which may lead bad/inefficient programming if used incorrectly. For example, non-primitives are always references in Java. So we cannot pass large objects (like we can do in C++) to functions, we always pass references in Java. One more example, since there are no pointers, bad memory access is also not possible. </div> </body></html>",
"e": 28371,
"s": 27592,
"text": null
},
{
"code": null,
"e": 28379,
"s": 28371,
"text": "Output:"
},
{
"code": null,
"e": 28593,
"s": 28393,
"text": "Example 2: In the following example, the width is 300px, the margin of the paragraph will be the same, and it will be in the center as it has margin: auto. The border width is 80px with purple color."
},
{
"code": null,
"e": 28598,
"s": 28593,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div { width: 300px; margin: auto; border: 80px solid purple; } </style> </head> <body> <h2 style=\"color: green\">GeeksforGeeks</h2> <b>Use of margin:auto</b> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> <div> This div will be horizontally centered because it has <i>margin:auto;</i> </div> </body></html>",
"e": 29418,
"s": 28598,
"text": null
},
{
"code": null,
"e": 29426,
"s": 29418,
"text": "Output:"
},
{
"code": null,
"e": 29452,
"s": 29440,
"text": "margin auto"
},
{
"code": null,
"e": 29467,
"s": 29452,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29481,
"s": 29467,
"text": "CSS-Questions"
},
{
"code": null,
"e": 29488,
"s": 29481,
"text": "Picked"
},
{
"code": null,
"e": 29492,
"s": 29488,
"text": "CSS"
},
{
"code": null,
"e": 29509,
"s": 29492,
"text": "Web Technologies"
},
{
"code": null,
"e": 29607,
"s": 29509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29644,
"s": 29607,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29683,
"s": 29644,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29712,
"s": 29683,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29754,
"s": 29712,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29789,
"s": 29754,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29829,
"s": 29789,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29862,
"s": 29829,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29907,
"s": 29862,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29950,
"s": 29907,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Role of SemiColon in various Programming Languages - GeeksforGeeks
|
23 Apr, 2020
Semicolon is a punctuation mark (;) indicating a pause, typically between two main clauses, that is more pronounced than that indicated by a comma. In programming, Semicolon symbol plays a vital role. It is used to show the termination of instruction in various programming languages as well, like C, C++, Java, JavaScript and Python.
In this article, let us see the act of Semicolon in different programming languages:
Role of Semicolon in C:
Semicolons are end statements in C.The Semicolon tells that the current statement has been terminated and other statements following are new statements.Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.They are not used in between the control flow statements but are used in separating the conditions in looping.for(initialization/declaration;
condition;
increment/decrements)
{
// body
}
Semicolons are end statements in C.
The Semicolon tells that the current statement has been terminated and other statements following are new statements.
Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.
They are not used in between the control flow statements but are used in separating the conditions in looping.for(initialization/declaration;
condition;
increment/decrements)
{
// body
}
for(initialization/declaration;
condition;
increment/decrements)
{
// body
}
Role of Semicolon in C++:
Semicolon is a command in C++.The Semicolon lets the compiler know that it’s reached the end of a command.Semicolon is often used to delimit one bit of C++ source code, indicating it’s intentionally separated from the respective code.Usage of Semicolon in C++ is after class and structure definitions, variable declarations, function declarations, after each statement generally.
Semicolon is a command in C++.
The Semicolon lets the compiler know that it’s reached the end of a command.
Semicolon is often used to delimit one bit of C++ source code, indicating it’s intentionally separated from the respective code.
Usage of Semicolon in C++ is after class and structure definitions, variable declarations, function declarations, after each statement generally.
Role of Semicolon in Java:
Java uses Semicolon similar to C.Semicolon is a part of syntax in Java.It shows the compiler where an instruction ends and where the next instruction begins.Semicolon allows the java program to be written in one line or multiple lines, by letting the compiler know where to end the instructions.
Java uses Semicolon similar to C.
Semicolon is a part of syntax in Java.
It shows the compiler where an instruction ends and where the next instruction begins.
Semicolon allows the java program to be written in one line or multiple lines, by letting the compiler know where to end the instructions.
Role of Semicolon in JavaScript:
Semicolons in JavaScript are optional.In JavaScript, there is a process called Automatic Semicolon Insertion (ASI) which inserts a Semicolon whenever needed but not placed.Semicolons are also used to terminate the statements.Placing the new line next to the previous line will result in valid JavaScript which will not trigger ASI to correct it.So in conditional statements like if ..else and looping statements like while, for, do-while, doesn’t require Semicolon.
Semicolons in JavaScript are optional.
In JavaScript, there is a process called Automatic Semicolon Insertion (ASI) which inserts a Semicolon whenever needed but not placed.
Semicolons are also used to terminate the statements.
Placing the new line next to the previous line will result in valid JavaScript which will not trigger ASI to correct it.
So in conditional statements like if ..else and looping statements like while, for, do-while, doesn’t require Semicolon.
Role of Semicolon in Python:
Python doesn’t use Semicolons but it is not restricted.In Python, Semicolon is not used to denote the end of the line.Python is called the simple coding language because there is no need to use Semicolon and if we even forget to place, it doesn’t throw an error.Sometimes Python makes use of Semicolon as line terminator where it is used as a separator to separate multiple lines.
Python doesn’t use Semicolons but it is not restricted.
In Python, Semicolon is not used to denote the end of the line.
Python is called the simple coding language because there is no need to use Semicolon and if we even forget to place, it doesn’t throw an error.
Sometimes Python makes use of Semicolon as line terminator where it is used as a separator to separate multiple lines.
Role of Semicolon in Perl:
Perl language employs Semicolon after every line, except at the end of the block.Perl lets us omit the Semicolon because it can be used as a separator rather than a terminator.Every statement in Perl is terminated with Semicolon unless it is the last line of the program.
Perl language employs Semicolon after every line, except at the end of the block.
Perl lets us omit the Semicolon because it can be used as a separator rather than a terminator.
Every statement in Perl is terminated with Semicolon unless it is the last line of the program.
Role of Semicolon in SQL:
Semicolon in SQL allows the user to execute the program in the same call by separating the statements in the database.SQL has a unique feature of adding Semicolon by default to terminate the statements.Semicolon is a statement terminator which is purely used to identify the end of a statement.Generally, by looking at the syntax, we can identify but using a Semicolon makes it more clear.
Semicolon in SQL allows the user to execute the program in the same call by separating the statements in the database.
SQL has a unique feature of adding Semicolon by default to terminate the statements.
Semicolon is a statement terminator which is purely used to identify the end of a statement.
Generally, by looking at the syntax, we can identify but using a Semicolon makes it more clear.
Role of Semicolon in Go language:
Semicolon in Go language is used to separate the initializer, condition, and continuation elements.Semicolon is added as a terminator when the line’s last token is:An integer, floating-point, imaginary or string literalone of the keywords (eg. break, continue, return etc..,)an identifier.one of the operators and delimiters like ++, –, ), ], or }
Semicolon in Go language is used to separate the initializer, condition, and continuation elements.
Semicolon is added as a terminator when the line’s last token is:An integer, floating-point, imaginary or string literalone of the keywords (eg. break, continue, return etc..,)an identifier.one of the operators and delimiters like ++, –, ), ], or }
An integer, floating-point, imaginary or string literal
one of the keywords (eg. break, continue, return etc..,)
an identifier.
one of the operators and delimiters like ++, –, ), ], or }
Role of Semicolon in C#:
C# makes use of Semicolon to get rid of ambiguity and confusion as its usage makes the code clear, structured and organised.Like other languages especially C and C++, C# also follows the same rules in the Semicolon application.The absence of Semicolon throws an error by the compiler which has to be rectified.It also lets the compiler know the end of the statement.
C# makes use of Semicolon to get rid of ambiguity and confusion as its usage makes the code clear, structured and organised.
Like other languages especially C and C++, C# also follows the same rules in the Semicolon application.
The absence of Semicolon throws an error by the compiler which has to be rectified.
It also lets the compiler know the end of the statement.
Role of Semicolon in Scala:
Semicolon plays a vital role in all the programming language by marking the end of the statement.But Semicolon in Scala, not only marks the end of the statement but also the end of the expression.Scala’s syntax encourages clear and concise code, so it is necessary to use Semicolon properly whenever needed.Scala adapts different syntaxes like dot syntax, syntax using braces, syntax using parenthesis and syntax using empty line separator which replaces the use of Semicolon.
Semicolon plays a vital role in all the programming language by marking the end of the statement.
But Semicolon in Scala, not only marks the end of the statement but also the end of the expression.
Scala’s syntax encourages clear and concise code, so it is necessary to use Semicolon properly whenever needed.
Scala adapts different syntaxes like dot syntax, syntax using braces, syntax using parenthesis and syntax using empty line separator which replaces the use of Semicolon.
Role of Semicolon in PL/I:
PL/I is a language which is a series of declarations and statements. So Semicolon is necessary to separate the statements to avoid ambiguity.Statements in PL/I should be placed in separate lines with Semicolon to improve the readability.In multi-line statements, Semicolon is used to separate the lines and in a single-line statement, Semicolon is used to terminate.
PL/I is a language which is a series of declarations and statements. So Semicolon is necessary to separate the statements to avoid ambiguity.
Statements in PL/I should be placed in separate lines with Semicolon to improve the readability.
In multi-line statements, Semicolon is used to separate the lines and in a single-line statement, Semicolon is used to terminate.
Role of Semicolon in Pascal:
Semicolon in Pascal acts as statement separator i.e it separates two or more statements.Exactly one Semicolon should be used in separating two statements. But using more than one Semicolon (extra Semicolon) will raise an error.Unlike other languages, Pascal makes use of Semicolon in a different way. There is no need for a direct Semicolon before else in Pascal. Also, the last statement before the end of the code/program doesn’t need a Semicolon.Pascal needs Semicolon when statements are written in a sequence.Pascal doesn’t need Semicolon for a case or a block and also before the keyword.
Semicolon in Pascal acts as statement separator i.e it separates two or more statements.
Exactly one Semicolon should be used in separating two statements. But using more than one Semicolon (extra Semicolon) will raise an error.
Unlike other languages, Pascal makes use of Semicolon in a different way. There is no need for a direct Semicolon before else in Pascal. Also, the last statement before the end of the code/program doesn’t need a Semicolon.
Pascal needs Semicolon when statements are written in a sequence.
Pascal doesn’t need Semicolon for a case or a block and also before the keyword.
Algorithms
C Language
C#
C++
Go Language
Java
JavaScript
Perl
Programming Language
Python
Scala
SQL
Write From Home
Java
Algorithms
SQL
Perl
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Taking String input with space in C (4 Different Methods)
Arrays in C/C++
A nested loop puzzle
C program to Insert an element in an Array
std::sort() in C++ STL
|
[
{
"code": null,
"e": 25829,
"s": 25801,
"text": "\n23 Apr, 2020"
},
{
"code": null,
"e": 26164,
"s": 25829,
"text": "Semicolon is a punctuation mark (;) indicating a pause, typically between two main clauses, that is more pronounced than that indicated by a comma. In programming, Semicolon symbol plays a vital role. It is used to show the termination of instruction in various programming languages as well, like C, C++, Java, JavaScript and Python."
},
{
"code": null,
"e": 26249,
"s": 26164,
"text": "In this article, let us see the act of Semicolon in different programming languages:"
},
{
"code": null,
"e": 26273,
"s": 26249,
"text": "Role of Semicolon in C:"
},
{
"code": null,
"e": 26712,
"s": 26273,
"text": "Semicolons are end statements in C.The Semicolon tells that the current statement has been terminated and other statements following are new statements.Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.They are not used in between the control flow statements but are used in separating the conditions in looping.for(initialization/declaration;\n condition; \n increment/decrements)\n{\n // body\n}\n"
},
{
"code": null,
"e": 26748,
"s": 26712,
"text": "Semicolons are end statements in C."
},
{
"code": null,
"e": 26866,
"s": 26748,
"text": "The Semicolon tells that the current statement has been terminated and other statements following are new statements."
},
{
"code": null,
"e": 26953,
"s": 26866,
"text": "Usage of Semicolon in C will remove ambiguity and confusion while looking at the code."
},
{
"code": null,
"e": 27154,
"s": 26953,
"text": "They are not used in between the control flow statements but are used in separating the conditions in looping.for(initialization/declaration;\n condition; \n increment/decrements)\n{\n // body\n}\n"
},
{
"code": null,
"e": 27245,
"s": 27154,
"text": "for(initialization/declaration;\n condition; \n increment/decrements)\n{\n // body\n}\n"
},
{
"code": null,
"e": 27271,
"s": 27245,
"text": "Role of Semicolon in C++:"
},
{
"code": null,
"e": 27651,
"s": 27271,
"text": "Semicolon is a command in C++.The Semicolon lets the compiler know that it’s reached the end of a command.Semicolon is often used to delimit one bit of C++ source code, indicating it’s intentionally separated from the respective code.Usage of Semicolon in C++ is after class and structure definitions, variable declarations, function declarations, after each statement generally."
},
{
"code": null,
"e": 27682,
"s": 27651,
"text": "Semicolon is a command in C++."
},
{
"code": null,
"e": 27759,
"s": 27682,
"text": "The Semicolon lets the compiler know that it’s reached the end of a command."
},
{
"code": null,
"e": 27888,
"s": 27759,
"text": "Semicolon is often used to delimit one bit of C++ source code, indicating it’s intentionally separated from the respective code."
},
{
"code": null,
"e": 28034,
"s": 27888,
"text": "Usage of Semicolon in C++ is after class and structure definitions, variable declarations, function declarations, after each statement generally."
},
{
"code": null,
"e": 28061,
"s": 28034,
"text": "Role of Semicolon in Java:"
},
{
"code": null,
"e": 28357,
"s": 28061,
"text": "Java uses Semicolon similar to C.Semicolon is a part of syntax in Java.It shows the compiler where an instruction ends and where the next instruction begins.Semicolon allows the java program to be written in one line or multiple lines, by letting the compiler know where to end the instructions."
},
{
"code": null,
"e": 28391,
"s": 28357,
"text": "Java uses Semicolon similar to C."
},
{
"code": null,
"e": 28430,
"s": 28391,
"text": "Semicolon is a part of syntax in Java."
},
{
"code": null,
"e": 28517,
"s": 28430,
"text": "It shows the compiler where an instruction ends and where the next instruction begins."
},
{
"code": null,
"e": 28656,
"s": 28517,
"text": "Semicolon allows the java program to be written in one line or multiple lines, by letting the compiler know where to end the instructions."
},
{
"code": null,
"e": 28689,
"s": 28656,
"text": "Role of Semicolon in JavaScript:"
},
{
"code": null,
"e": 29155,
"s": 28689,
"text": "Semicolons in JavaScript are optional.In JavaScript, there is a process called Automatic Semicolon Insertion (ASI) which inserts a Semicolon whenever needed but not placed.Semicolons are also used to terminate the statements.Placing the new line next to the previous line will result in valid JavaScript which will not trigger ASI to correct it.So in conditional statements like if ..else and looping statements like while, for, do-while, doesn’t require Semicolon."
},
{
"code": null,
"e": 29194,
"s": 29155,
"text": "Semicolons in JavaScript are optional."
},
{
"code": null,
"e": 29329,
"s": 29194,
"text": "In JavaScript, there is a process called Automatic Semicolon Insertion (ASI) which inserts a Semicolon whenever needed but not placed."
},
{
"code": null,
"e": 29383,
"s": 29329,
"text": "Semicolons are also used to terminate the statements."
},
{
"code": null,
"e": 29504,
"s": 29383,
"text": "Placing the new line next to the previous line will result in valid JavaScript which will not trigger ASI to correct it."
},
{
"code": null,
"e": 29625,
"s": 29504,
"text": "So in conditional statements like if ..else and looping statements like while, for, do-while, doesn’t require Semicolon."
},
{
"code": null,
"e": 29654,
"s": 29625,
"text": "Role of Semicolon in Python:"
},
{
"code": null,
"e": 30035,
"s": 29654,
"text": "Python doesn’t use Semicolons but it is not restricted.In Python, Semicolon is not used to denote the end of the line.Python is called the simple coding language because there is no need to use Semicolon and if we even forget to place, it doesn’t throw an error.Sometimes Python makes use of Semicolon as line terminator where it is used as a separator to separate multiple lines."
},
{
"code": null,
"e": 30091,
"s": 30035,
"text": "Python doesn’t use Semicolons but it is not restricted."
},
{
"code": null,
"e": 30155,
"s": 30091,
"text": "In Python, Semicolon is not used to denote the end of the line."
},
{
"code": null,
"e": 30300,
"s": 30155,
"text": "Python is called the simple coding language because there is no need to use Semicolon and if we even forget to place, it doesn’t throw an error."
},
{
"code": null,
"e": 30419,
"s": 30300,
"text": "Sometimes Python makes use of Semicolon as line terminator where it is used as a separator to separate multiple lines."
},
{
"code": null,
"e": 30446,
"s": 30419,
"text": "Role of Semicolon in Perl:"
},
{
"code": null,
"e": 30718,
"s": 30446,
"text": "Perl language employs Semicolon after every line, except at the end of the block.Perl lets us omit the Semicolon because it can be used as a separator rather than a terminator.Every statement in Perl is terminated with Semicolon unless it is the last line of the program."
},
{
"code": null,
"e": 30800,
"s": 30718,
"text": "Perl language employs Semicolon after every line, except at the end of the block."
},
{
"code": null,
"e": 30896,
"s": 30800,
"text": "Perl lets us omit the Semicolon because it can be used as a separator rather than a terminator."
},
{
"code": null,
"e": 30992,
"s": 30896,
"text": "Every statement in Perl is terminated with Semicolon unless it is the last line of the program."
},
{
"code": null,
"e": 31018,
"s": 30992,
"text": "Role of Semicolon in SQL:"
},
{
"code": null,
"e": 31408,
"s": 31018,
"text": "Semicolon in SQL allows the user to execute the program in the same call by separating the statements in the database.SQL has a unique feature of adding Semicolon by default to terminate the statements.Semicolon is a statement terminator which is purely used to identify the end of a statement.Generally, by looking at the syntax, we can identify but using a Semicolon makes it more clear."
},
{
"code": null,
"e": 31527,
"s": 31408,
"text": "Semicolon in SQL allows the user to execute the program in the same call by separating the statements in the database."
},
{
"code": null,
"e": 31612,
"s": 31527,
"text": "SQL has a unique feature of adding Semicolon by default to terminate the statements."
},
{
"code": null,
"e": 31705,
"s": 31612,
"text": "Semicolon is a statement terminator which is purely used to identify the end of a statement."
},
{
"code": null,
"e": 31801,
"s": 31705,
"text": "Generally, by looking at the syntax, we can identify but using a Semicolon makes it more clear."
},
{
"code": null,
"e": 31835,
"s": 31801,
"text": "Role of Semicolon in Go language:"
},
{
"code": null,
"e": 32183,
"s": 31835,
"text": "Semicolon in Go language is used to separate the initializer, condition, and continuation elements.Semicolon is added as a terminator when the line’s last token is:An integer, floating-point, imaginary or string literalone of the keywords (eg. break, continue, return etc..,)an identifier.one of the operators and delimiters like ++, –, ), ], or }"
},
{
"code": null,
"e": 32283,
"s": 32183,
"text": "Semicolon in Go language is used to separate the initializer, condition, and continuation elements."
},
{
"code": null,
"e": 32532,
"s": 32283,
"text": "Semicolon is added as a terminator when the line’s last token is:An integer, floating-point, imaginary or string literalone of the keywords (eg. break, continue, return etc..,)an identifier.one of the operators and delimiters like ++, –, ), ], or }"
},
{
"code": null,
"e": 32588,
"s": 32532,
"text": "An integer, floating-point, imaginary or string literal"
},
{
"code": null,
"e": 32645,
"s": 32588,
"text": "one of the keywords (eg. break, continue, return etc..,)"
},
{
"code": null,
"e": 32660,
"s": 32645,
"text": "an identifier."
},
{
"code": null,
"e": 32719,
"s": 32660,
"text": "one of the operators and delimiters like ++, –, ), ], or }"
},
{
"code": null,
"e": 32744,
"s": 32719,
"text": "Role of Semicolon in C#:"
},
{
"code": null,
"e": 33111,
"s": 32744,
"text": "C# makes use of Semicolon to get rid of ambiguity and confusion as its usage makes the code clear, structured and organised.Like other languages especially C and C++, C# also follows the same rules in the Semicolon application.The absence of Semicolon throws an error by the compiler which has to be rectified.It also lets the compiler know the end of the statement."
},
{
"code": null,
"e": 33236,
"s": 33111,
"text": "C# makes use of Semicolon to get rid of ambiguity and confusion as its usage makes the code clear, structured and organised."
},
{
"code": null,
"e": 33340,
"s": 33236,
"text": "Like other languages especially C and C++, C# also follows the same rules in the Semicolon application."
},
{
"code": null,
"e": 33424,
"s": 33340,
"text": "The absence of Semicolon throws an error by the compiler which has to be rectified."
},
{
"code": null,
"e": 33481,
"s": 33424,
"text": "It also lets the compiler know the end of the statement."
},
{
"code": null,
"e": 33509,
"s": 33481,
"text": "Role of Semicolon in Scala:"
},
{
"code": null,
"e": 33986,
"s": 33509,
"text": "Semicolon plays a vital role in all the programming language by marking the end of the statement.But Semicolon in Scala, not only marks the end of the statement but also the end of the expression.Scala’s syntax encourages clear and concise code, so it is necessary to use Semicolon properly whenever needed.Scala adapts different syntaxes like dot syntax, syntax using braces, syntax using parenthesis and syntax using empty line separator which replaces the use of Semicolon."
},
{
"code": null,
"e": 34084,
"s": 33986,
"text": "Semicolon plays a vital role in all the programming language by marking the end of the statement."
},
{
"code": null,
"e": 34184,
"s": 34084,
"text": "But Semicolon in Scala, not only marks the end of the statement but also the end of the expression."
},
{
"code": null,
"e": 34296,
"s": 34184,
"text": "Scala’s syntax encourages clear and concise code, so it is necessary to use Semicolon properly whenever needed."
},
{
"code": null,
"e": 34466,
"s": 34296,
"text": "Scala adapts different syntaxes like dot syntax, syntax using braces, syntax using parenthesis and syntax using empty line separator which replaces the use of Semicolon."
},
{
"code": null,
"e": 34493,
"s": 34466,
"text": "Role of Semicolon in PL/I:"
},
{
"code": null,
"e": 34860,
"s": 34493,
"text": "PL/I is a language which is a series of declarations and statements. So Semicolon is necessary to separate the statements to avoid ambiguity.Statements in PL/I should be placed in separate lines with Semicolon to improve the readability.In multi-line statements, Semicolon is used to separate the lines and in a single-line statement, Semicolon is used to terminate."
},
{
"code": null,
"e": 35002,
"s": 34860,
"text": "PL/I is a language which is a series of declarations and statements. So Semicolon is necessary to separate the statements to avoid ambiguity."
},
{
"code": null,
"e": 35099,
"s": 35002,
"text": "Statements in PL/I should be placed in separate lines with Semicolon to improve the readability."
},
{
"code": null,
"e": 35229,
"s": 35099,
"text": "In multi-line statements, Semicolon is used to separate the lines and in a single-line statement, Semicolon is used to terminate."
},
{
"code": null,
"e": 35258,
"s": 35229,
"text": "Role of Semicolon in Pascal:"
},
{
"code": null,
"e": 35853,
"s": 35258,
"text": "Semicolon in Pascal acts as statement separator i.e it separates two or more statements.Exactly one Semicolon should be used in separating two statements. But using more than one Semicolon (extra Semicolon) will raise an error.Unlike other languages, Pascal makes use of Semicolon in a different way. There is no need for a direct Semicolon before else in Pascal. Also, the last statement before the end of the code/program doesn’t need a Semicolon.Pascal needs Semicolon when statements are written in a sequence.Pascal doesn’t need Semicolon for a case or a block and also before the keyword."
},
{
"code": null,
"e": 35942,
"s": 35853,
"text": "Semicolon in Pascal acts as statement separator i.e it separates two or more statements."
},
{
"code": null,
"e": 36082,
"s": 35942,
"text": "Exactly one Semicolon should be used in separating two statements. But using more than one Semicolon (extra Semicolon) will raise an error."
},
{
"code": null,
"e": 36305,
"s": 36082,
"text": "Unlike other languages, Pascal makes use of Semicolon in a different way. There is no need for a direct Semicolon before else in Pascal. Also, the last statement before the end of the code/program doesn’t need a Semicolon."
},
{
"code": null,
"e": 36371,
"s": 36305,
"text": "Pascal needs Semicolon when statements are written in a sequence."
},
{
"code": null,
"e": 36452,
"s": 36371,
"text": "Pascal doesn’t need Semicolon for a case or a block and also before the keyword."
},
{
"code": null,
"e": 36463,
"s": 36452,
"text": "Algorithms"
},
{
"code": null,
"e": 36474,
"s": 36463,
"text": "C Language"
},
{
"code": null,
"e": 36477,
"s": 36474,
"text": "C#"
},
{
"code": null,
"e": 36481,
"s": 36477,
"text": "C++"
},
{
"code": null,
"e": 36493,
"s": 36481,
"text": "Go Language"
},
{
"code": null,
"e": 36498,
"s": 36493,
"text": "Java"
},
{
"code": null,
"e": 36509,
"s": 36498,
"text": "JavaScript"
},
{
"code": null,
"e": 36514,
"s": 36509,
"text": "Perl"
},
{
"code": null,
"e": 36535,
"s": 36514,
"text": "Programming Language"
},
{
"code": null,
"e": 36542,
"s": 36535,
"text": "Python"
},
{
"code": null,
"e": 36548,
"s": 36542,
"text": "Scala"
},
{
"code": null,
"e": 36552,
"s": 36548,
"text": "SQL"
},
{
"code": null,
"e": 36568,
"s": 36552,
"text": "Write From Home"
},
{
"code": null,
"e": 36573,
"s": 36568,
"text": "Java"
},
{
"code": null,
"e": 36584,
"s": 36573,
"text": "Algorithms"
},
{
"code": null,
"e": 36588,
"s": 36584,
"text": "SQL"
},
{
"code": null,
"e": 36593,
"s": 36588,
"text": "Perl"
},
{
"code": null,
"e": 36597,
"s": 36593,
"text": "CPP"
},
{
"code": null,
"e": 36695,
"s": 36597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36744,
"s": 36695,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 36769,
"s": 36744,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36797,
"s": 36769,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 36848,
"s": 36797,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 36875,
"s": 36848,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 36933,
"s": 36875,
"text": "Taking String input with space in C (4 Different Methods)"
},
{
"code": null,
"e": 36949,
"s": 36933,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 36970,
"s": 36949,
"text": "A nested loop puzzle"
},
{
"code": null,
"e": 37013,
"s": 36970,
"text": "C program to Insert an element in an Array"
}
] |
Number of Unique BST with a given key | Dynamic Programming - GeeksforGeeks
|
08 Apr, 2022
Given N, Find the total number of unique BSTs that can be made using values from 1 to N. Examples:
Input: n = 3
Output: 5
For n = 3, preorder traversal of Unique BSTs are:
1. 1 2 3
2. 1 3 2
3. 2 1 3
4. 3 1 2
5. 3 2 1
Input: 4
Output: 14
In the previous post a O(n) solution has been discussed. In this post we will discuss a solution based on Dynamic Programming. For all possible values of i, consider i as root, then [1....i-1] numbers will fall in the left subtree and [i+1....n] numbers will fall in the right subtree. So, add (i-1)*(n-i) to the answer. The summation of the products will be the answer to the number of unique BST. Below is the implementation for above approach:
C++
C
Java
Python3
C#
PHP
// C++ code to find number of unique BSTs// Dynamic Programming solution#include <bits/stdc++.h>using namespace std; // Function to find number of unique BSTint numberOfBST(int n){ // DP to store the number of unique BST with key i int dp[n + 1]; fill_n(dp, n + 1, 0); // Base case dp[0] = 1; dp[1] = 1; // fill the dp table in bottom-up approach. for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { // n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]); } } return dp[n];} // Driver Codeint main(){ int n = 3; cout << "Number of structurally Unique BST with " << n << " keys are : " << numberOfBST(n) << "\n"; return 0;}// This code is contributed by Aditya kumar (adityakumar129)
// C code to find number of unique BSTs// Dynamic Programming solution#include <stdio.h> // DP to store the number of unique BST with key iint dp[20]; // Function to find number of unique BSTint numberOfBST(int n){ // Base case if (n <= 1) return 1; // In case if the value is already present in the array // just return it and no need to calculate it if (dp[n]) return dp[n]; for (int i = 1; i <= n; i++) dp[n] += numberOfBST(i - 1) * numberOfBST(n - i); return dp[n];} // Driver Codeint main(){ int n = 3; printf("Number of structurally Unique BST with %d keys are %d", n, numberOfBST(n)); return 0;} // This code is contributed by Aditya kumar (adityakumar129)
// Java code to find number// of unique BSTs Dynamic// Programming solutionimport java.io.*;import java.util.Arrays; class GFG { public static int dp[] = new int[20]; static int numberOfBST(int n) { // Base case if (n <= 1) return 1; // In case if the value is already present in the // array just return it and no need to calculate it if (dp[n]>0) return dp[n]; for (int i = 1; i <= n; i++) dp[n] += numberOfBST(i - 1) * numberOfBST(n - i); return dp[n]; } // Driver Code public static void main(String[] args) { int n = 3; System.out.println("Number of structurally " + "Unique BST with " + n + " keys are : " + numberOfBST(n)); }} // This code is contributed by Aditya kumar (adityakumar129)
# Python3 code to find number of unique# BSTs Dynamic Programming solution # Function to find number of unique BSTdef numberOfBST(n): # DP to store the number of unique # BST with key i dp = [0] * (n + 1) # Base case dp[0], dp[1] = 1, 1 # fill the dp table in top-down # approach. for i in range(2, n + 1): for j in range(1, i + 1): # n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]) return dp[n] # Driver Codeif __name__ == "__main__": n = 3 print("Number of structurally Unique BST with", n, "keys are :", numberOfBST(n)) # This code is contributed# by Rituraj Jain
// C# code to find number// of unique BSTs Dynamic// Programming solutionusing System; class GFG{ static int numberOfBST(int n) { // DP to store the number // of unique BST with key i int []dp = new int[n + 1]; // Base case dp[0] = 1; dp[1] = 1; // fill the dp table in // top-down approach. for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { // n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]); } } return dp[n];} // Driver Codepublic static void Main (){ int n = 3; Console.Write("Number of structurally " + "Unique BST with "+ n + " keys are : " + numberOfBST(n));}} // This code is contributed// by shiv_bhakt.
<?php// PHP code to find number// of unique BSTs Dynamic// Programming solution // Function to find number// of unique BSTfunction numberOfBST($n){ // DP to store the number // of unique BST with key i $dp = array($n + 1); for($i = 0; $i <= $n + 1; $i++) $dp[$i] = 0; // Base case $dp[0] = 1; $dp[1] = 1; // fill the dp table // in top-down approach. for ($i = 2; $i <= $n; $i++) { for ($j = 1; $j <= $i; $j++) { // n-i in right * // i-1 in left $dp[$i] += (($dp[$i - $j]) * ($dp[$j - 1])); } } return $dp[$n];} // Driver Code$n = 3;echo "Number of structurally ". "Unique BST with " , $n , " keys are : " , numberOfBST($n) ; // This code is contributed// by shiv_bhakt.?>
Number of structurally Unique BST with 3 keys are : 5
Time Complexity: O(n2)
Vishal_Khoda
rituraj_jain
Gaurav Raj 1
adityakumar129
Algorithms-Dynamic Programming
BST
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Maximum sum such that no two elements are adjacent
Gold Mine Problem
Count All Palindrome Sub-Strings in a String | Set 1
3 Different ways to print Fibonacci series in Java
Optimal Binary Search Tree | DP-24
Word Break Problem | DP-32
Binomial Coefficient | DP-9
|
[
{
"code": null,
"e": 24307,
"s": 24279,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 24408,
"s": 24307,
"text": "Given N, Find the total number of unique BSTs that can be made using values from 1 to N. Examples: "
},
{
"code": null,
"e": 24549,
"s": 24408,
"text": "Input: n = 3 \nOutput: 5\nFor n = 3, preorder traversal of Unique BSTs are:\n1. 1 2 3\n2. 1 3 2\n3. 2 1 3\n4. 3 1 2\n5. 3 2 1\n\nInput: 4 \nOutput: 14"
},
{
"code": null,
"e": 25000,
"s": 24551,
"text": "In the previous post a O(n) solution has been discussed. In this post we will discuss a solution based on Dynamic Programming. For all possible values of i, consider i as root, then [1....i-1] numbers will fall in the left subtree and [i+1....n] numbers will fall in the right subtree. So, add (i-1)*(n-i) to the answer. The summation of the products will be the answer to the number of unique BST. Below is the implementation for above approach: "
},
{
"code": null,
"e": 25004,
"s": 25000,
"text": "C++"
},
{
"code": null,
"e": 25006,
"s": 25004,
"text": "C"
},
{
"code": null,
"e": 25011,
"s": 25006,
"text": "Java"
},
{
"code": null,
"e": 25019,
"s": 25011,
"text": "Python3"
},
{
"code": null,
"e": 25022,
"s": 25019,
"text": "C#"
},
{
"code": null,
"e": 25026,
"s": 25022,
"text": "PHP"
},
{
"code": "// C++ code to find number of unique BSTs// Dynamic Programming solution#include <bits/stdc++.h>using namespace std; // Function to find number of unique BSTint numberOfBST(int n){ // DP to store the number of unique BST with key i int dp[n + 1]; fill_n(dp, n + 1, 0); // Base case dp[0] = 1; dp[1] = 1; // fill the dp table in bottom-up approach. for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { // n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]); } } return dp[n];} // Driver Codeint main(){ int n = 3; cout << \"Number of structurally Unique BST with \" << n << \" keys are : \" << numberOfBST(n) << \"\\n\"; return 0;}// This code is contributed by Aditya kumar (adityakumar129)",
"e": 25818,
"s": 25026,
"text": null
},
{
"code": "// C code to find number of unique BSTs// Dynamic Programming solution#include <stdio.h> // DP to store the number of unique BST with key iint dp[20]; // Function to find number of unique BSTint numberOfBST(int n){ // Base case if (n <= 1) return 1; // In case if the value is already present in the array // just return it and no need to calculate it if (dp[n]) return dp[n]; for (int i = 1; i <= n; i++) dp[n] += numberOfBST(i - 1) * numberOfBST(n - i); return dp[n];} // Driver Codeint main(){ int n = 3; printf(\"Number of structurally Unique BST with %d keys are %d\", n, numberOfBST(n)); return 0;} // This code is contributed by Aditya kumar (adityakumar129)",
"e": 26539,
"s": 25818,
"text": null
},
{
"code": "// Java code to find number// of unique BSTs Dynamic// Programming solutionimport java.io.*;import java.util.Arrays; class GFG { public static int dp[] = new int[20]; static int numberOfBST(int n) { // Base case if (n <= 1) return 1; // In case if the value is already present in the // array just return it and no need to calculate it if (dp[n]>0) return dp[n]; for (int i = 1; i <= n; i++) dp[n] += numberOfBST(i - 1) * numberOfBST(n - i); return dp[n]; } // Driver Code public static void main(String[] args) { int n = 3; System.out.println(\"Number of structurally \" + \"Unique BST with \" + n + \" keys are : \" + numberOfBST(n)); }} // This code is contributed by Aditya kumar (adityakumar129)",
"e": 27380,
"s": 26539,
"text": null
},
{
"code": "# Python3 code to find number of unique# BSTs Dynamic Programming solution # Function to find number of unique BSTdef numberOfBST(n): # DP to store the number of unique # BST with key i dp = [0] * (n + 1) # Base case dp[0], dp[1] = 1, 1 # fill the dp table in top-down # approach. for i in range(2, n + 1): for j in range(1, i + 1): # n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]) return dp[n] # Driver Codeif __name__ == \"__main__\": n = 3 print(\"Number of structurally Unique BST with\", n, \"keys are :\", numberOfBST(n)) # This code is contributed# by Rituraj Jain",
"e": 28080,
"s": 27380,
"text": null
},
{
"code": "// C# code to find number// of unique BSTs Dynamic// Programming solutionusing System; class GFG{ static int numberOfBST(int n) { // DP to store the number // of unique BST with key i int []dp = new int[n + 1]; // Base case dp[0] = 1; dp[1] = 1; // fill the dp table in // top-down approach. for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { // n-i in right * i-1 in left dp[i] = dp[i] + (dp[i - j] * dp[j - 1]); } } return dp[n];} // Driver Codepublic static void Main (){ int n = 3; Console.Write(\"Number of structurally \" + \"Unique BST with \"+ n + \" keys are : \" + numberOfBST(n));}} // This code is contributed// by shiv_bhakt.",
"e": 28928,
"s": 28080,
"text": null
},
{
"code": "<?php// PHP code to find number// of unique BSTs Dynamic// Programming solution // Function to find number// of unique BSTfunction numberOfBST($n){ // DP to store the number // of unique BST with key i $dp = array($n + 1); for($i = 0; $i <= $n + 1; $i++) $dp[$i] = 0; // Base case $dp[0] = 1; $dp[1] = 1; // fill the dp table // in top-down approach. for ($i = 2; $i <= $n; $i++) { for ($j = 1; $j <= $i; $j++) { // n-i in right * // i-1 in left $dp[$i] += (($dp[$i - $j]) * ($dp[$j - 1])); } } return $dp[$n];} // Driver Code$n = 3;echo \"Number of structurally \". \"Unique BST with \" , $n , \" keys are : \" , numberOfBST($n) ; // This code is contributed// by shiv_bhakt.?>",
"e": 29757,
"s": 28928,
"text": null
},
{
"code": null,
"e": 29811,
"s": 29757,
"text": "Number of structurally Unique BST with 3 keys are : 5"
},
{
"code": null,
"e": 29838,
"s": 29813,
"text": "Time Complexity: O(n2) "
},
{
"code": null,
"e": 29851,
"s": 29838,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 29864,
"s": 29851,
"text": "rituraj_jain"
},
{
"code": null,
"e": 29877,
"s": 29864,
"text": "Gaurav Raj 1"
},
{
"code": null,
"e": 29892,
"s": 29877,
"text": "adityakumar129"
},
{
"code": null,
"e": 29923,
"s": 29892,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 29927,
"s": 29923,
"text": "BST"
},
{
"code": null,
"e": 29947,
"s": 29927,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 29967,
"s": 29947,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 30065,
"s": 29967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30074,
"s": 30065,
"text": "Comments"
},
{
"code": null,
"e": 30087,
"s": 30074,
"text": "Old Comments"
},
{
"code": null,
"e": 30147,
"s": 30087,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 30168,
"s": 30147,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 30224,
"s": 30168,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 30275,
"s": 30224,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 30293,
"s": 30275,
"text": "Gold Mine Problem"
},
{
"code": null,
"e": 30346,
"s": 30293,
"text": "Count All Palindrome Sub-Strings in a String | Set 1"
},
{
"code": null,
"e": 30397,
"s": 30346,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 30432,
"s": 30397,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 30459,
"s": 30432,
"text": "Word Break Problem | DP-32"
}
] |
Prediction & Calibration Techniques to Optimize Performance of Machine Learning Models | by Sarit Maitra | Towards Data Science
|
CALIBRATION is a post-processing technique to improve error distribution of a predictive model.
The evaluation of machine learning (ML) models is a crucial step before deployment. Therefore, it is essential to go through a behavior analysis of a ML model. In many real-life applications, along with mean error of the model, it is also important to know how this error is distributed and how well probability estimations are made. To my experience, many current ML techniques are good in overall results but have a bad distribution assessment of the error. I will discuss common calibration techniques and calibration measures using classification.
From the scientific context, the primary goal of ML methods is to build a hypothesis (model) from a given data set. After the learning process, the quality of the hypothesis must be evaluated as precisely as possible.
The common measures are accuracy (the inverse of error), f-measure, or macro-average for classification based model. In probabilistic classification, besides the percentage of correctly classified instances, other measures such as logloss, mean squared error (MSE) (or Brier’s score) or area under the ROC curve (AUROC) are used. If the outputs are not binary but are floating numbers between 0 and 1, then the scores can be used for ranking. But floating numbers between 0 and 1 leads to probabilities, and how do we know if we can trust them as probabilities?
We want a good classifier to identify between true positives and true negatives. We are going to deal with telecom customer data here; so in “Churn” analysis we would expect the classifier to trigger a flag between “Churn” and “NoChurn”, which allows us to calibrate the sensitivity of this model by adjusting the threshold. This means, if the classifier can detect 90% possibility of “Churn”, business should see that as true label. Moreover, most of the classification related data is highly imbalanced where number of “Churn” is quite less than “NoChurn”. So, we might want to re-sample the data to balance them, and that way we may induce some bias to our model by making it too aggressive.
When dealing with two class classification problems we can always label one class as a positive and the other one as a negative class. The test set consists of P positive and N negative examples. A classifier assigns a class to each of them, but some of the assignments are wrong. To assess the classification results we count the number of true positive (TP), true negative (TN), false positive (FP) (actually negative, but classified as positive) and false negative (FN) (actually positive, but classified as negative) examples. It holds
TP + FN = P and
TN + FP = N
The classifier assigned TP + FP examples to the positive class and TN + FN examples to the negative class. Let us define a few well-known and widely used measures:
FPrate = FP /N
TPrate = TP /P = Recall
Yrate = (TP + FP) /(P + N)
Precision = TP/ (TP + FP)
Accuracy = (TP + TN)/ (P + N).
Precision and Accuracy are often used to measure the classification quality of binary classifiers. Several other measures used for special purposes can also be defined. We describe them in the following sections
A probabilistic classifier is a function f : X → [0, 1] that maps each example x to a real number f(x). Normally, a threshold t is selected for which the examples where f(x) ≥ t are considered positive and the others are considered negative. This implies that each pair of a probabilistic classifier and threshold t defines a binary classifier. Measures defined in the section above can therefore also be used for probabilistic classifiers, but they are always a function of the threshold t. Note that TP(t) and FP(t) are always monotonic descending functions. For a finite example set, they are step-wise, not continuous. By varying t we get a family of binary classifiers.
Let’s experiment on the telecom data that we have.
# Loading the CSV with pandasdata = pd.read_csv(‘Telco_Customer_Churn.csv’)data.dtypes # types of data in data set
#Removing customer IDs from the data set the columns not used in the predictive model.df = data.drop(“customerID”, axis=1)df.info()
We will covert the categorical variables (‘Yes’,’No’,etc.) into numeric values. Also, need to convert “Total Charges” to a numerical data type. Moreover, there are 11 missing values for “Total Charges”. So it will replace 11 rows from the data set. The predictor variable here is “Churn”. Therefore, it is necessary to convert the predictor variable in binary numeric variables too.
df.dropna(inplace = True)df[‘Churn’].replace(to_replace=’Yes’, value=1, inplace=True)df[‘Churn’].replace(to_replace=’No’, value=0, inplace=True)# converting all the categorical variables into dummy variablesdf_dummies = pd.get_dummies(df)df_dummies.info()
We will consider Logistics Regression and Random Forest Classifier to predict customer churn. It is important to scale the variables in regression so that all of them are within a range of 0 to 1.
df_dummies = df_dummies.drop(“TotalCharges”, axis=1) # removing Total Charges to avoid multi-colinearity.# Using the data frame where we had created dummy variablesy = df_dummies[‘Churn’].valuesX = df_dummies.drop(columns = [‘Churn’])# Scaling all the variables to a range of 0 to 1features = X.columns.valuesscaler = MinMaxScaler(feature_range = (0,1))scaler.fit(X)X = pd.DataFrame(scaler.transform(X))X.columns = features
Our first step was to split our data into training and test sets using train-test-split, which would allow us to cross-validate our results later. We also stratified the train-test-split, to ensure that the same proportion of our target variable was found in both our training and test sets.
X is the data with the independent variables, y is the data with the dependent variable. The test size variable determines in which ratio the data will be split. It is quite common to do this in a 90 Training/10 Test ratio. Also, need to stratify the train-test-split to have a balanced split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=101)print(‘length of X_train and x_test: ‘, len(X_train), len(X_test))print(‘length of y_train and y_test: ‘, len(y_train), len(y_test))
Using ML algorithm and the dependent variable here churn 1 or churn 0 is categorical. The trained model can be used to predict if a customer churned or not for the test data set. The results are saved in “prediction_test” and afterward the accuracy score is measured and printed.
lr_model = LogisticRegression(solver=’lbfgs’).fit(X_train, y_train)lr_prediction = lr_model.predict_proba(X_test)prediction_test = lr_model.predict(X_test)lr_pred = lr_model.predict(X_test)print(classification_report(y_test, prediction_test))
Out of 557 points in the first class ( NoChurn) the model was successful in identifying 502 of those correctly
Out of 147 points in class 1, model predicted 77 of them correctly
Out of 704 total, model predicted 579 of them correctly.
Accuracy is 82% (precisely 82.24%). However, it may not be the right measure considering the data is skewed and target class is not balanced. So, we look into the Precision, Recall, F score.
The confusion matrix clearly shows the model performance broken down into true positives, true negatives, false positives, and false negatives.
Precision is the ability of a classifier not to label an instance positive that is actually negative. For each class, it is defined as the ratio of true positives to the sum of true and false positives.
Recall is the ability of a classifier to find all positive instances. For each class, it is defined as the ratio of true positives to the sum of true positives and false negatives.
The F1 score is a weighted harmonic mean of precision and recall such that the best score is 1.0 and the worst is 0.0.
CC is the degree of approximation of the true class distribution with the estimated class distribution. The standard way to calibrate a model in this way is by changing the threshold that determines when the model predicts “Churn” or “NoChurn”, making this threshold stricter with class “Churn” and milder with class “NoChurn” to balance the proportion.
y_scores=lr_predictionprec, rec, tre = precision_recall_curve(y_test, y_scores[:,1], )def plot_prec_recall_vs_tresh(precisions, recalls, thresholds): fig, ax = plt.subplots(figsize=(10,6)) plt.plot(thresholds, precisions[:-1], “r — “, label=”Precisions”) plt.plot(thresholds, recalls[:-1], “#424242”, label=”Recalls”) plt.ylabel(“Level of Precision and Recall”, fontsize=12) plt.title(“Precision and Recall Scores as a function of the decision threshold”, fontsize=12) plt.xlabel(‘Thresholds’, fontsize=12) plt.legend(loc=”best”, fontsize=12) plt.ylim([0,1]) plt.axvline(x=0.47, linewidth=3, color=”#0B3861") plot_prec_recall_vs_tresh(prec, rec, tre)plt.show()
The precision (58.33%) and recall (52.38%) for predictions in the positive class (“Churn”) are relatively low. The area above the intersection point is the area of good performance levels. The other area below is the area of poor performance. In principle, this type of calibration might produce more error. In fact, it is usually the case when we want to obtain a useful model for problems with very imbalanced class distribution, i.e. the minority class has very few examples.
A more visual way to measure the performance of a binary classifier is the area under the receiver operating characteristic (AUROC) curve. It tells how much the model is capable of distinguishing between Churn and NoChurn.
lr_prediction = lr_model.predict_proba(X_test)skplt.metrics.plot_roc(y_test, lr_prediction)
AUROC curves are known to show little effect from class distribution variations (up-scaling has very minor effect on FP, while we can see some effect on TP).
Macro-average computes the metric independently for each class and then take the average (hence treating all classes equally), whereas a micro-average aggregates the contributions of all classes to compute the average metric. If we want to know how the system performs overall across the sets of data, we will consider macro average. We should not come up with any specific decision with this average. On the other hand, micro-average is useful measure when our data set varies in size.
So, we see here that, the ROC curves fail to explicitly show the difference between balanced and imbalanced cases. Moreover, the AUROC scores are inadequate to evaluate the early retrieval performance especially when curves are crossing each other.
We will check with RandomForest Classifier; however, we won’t go into the details again. A similar set of processes like Logistic Regression can be done to compare.
Similarly, train a random forest model and predict on the validation set.
rf_model = RandomForestClassifier(random_state=101, n_estimators=100).fit(X_train, y_train)rf_prediction = rf_model.predict_proba(X_test)rf_model.score(X_test, y_test)
# 0.7798295454545454
PC accompanies each prediction with a probability estimation. If we predict that we are 99% sure, and if we are only right 50% of the time, this is not calibrated because our estimation was too optimistic. Similarly, if we predict that we are only 60% sure, and we are right 80% of the time, this is not calibrated because our estimation was too pessimistic. In both cases, the expected value of the number or proportion of right guesses (in this case the probability or the confidence assessment) does not match the actual value. Calibration is then defined as the degree of approximation of the predicted probabilities to the actual probabilities. Accuracy and calibration, although dependent, are very different things.
Here, we have the class probabilities and labels to compute the bins for the calibration plot.
lr_y, lr_x = calibration_curve(y_test, lr_prediction[:,1], n_bins=20)rf_y, rf_x = calibration_curve(y_test, rf_prediction[:,1], n_bins=20)fig, ax = plt.subplots()# only these two lines are calibration curvesplt.plot(lr_x,lr_y, marker=’o’, linewidth=1, label=’lr’)plt.plot(rf_x, rf_y, marker=’o’, linewidth=1, label=’rf’)# reference line, legends, and axis labelsline = mlines.Line2D([0, 1], [0, 1], color=’black’)transform = ax.transAxesline.set_transform(transform)ax.add_line(line)fig.suptitle(‘Calibration plot for Telecom data’)ax.set_xlabel(‘Predicted probability’)ax.set_ylabel(‘True probability in each bin’)plt.legend(); plt.show()
def bin_total(y_true, y_prob, n_bins): bins = np.linspace(0., 1. + 1e-8, n_bins + 1)# In sklearn.calibration.calibration_curve the last value in the array is always 0. binids = np.digitize(y_prob, bins) — 1return np.bincount(binids, minlength=len(bins))bin_total(y_test, lr_prediction[:,1], n_bins=20)
# array([191, 88, 47, 58, 46, 32, 30, 32, 24, 24, 25, 22, 22, 19, 24, 17, 2, 1, 0, 0, 0])
bin_total(y_test, rf_prediction[:,1], n_bins=20)
# array([213, 70, 59, 47, 39, 42, 27, 27, 22, 18, 26, 21, 22, 18, 7, 12, 10, 6, 7, 11, 0])
The missing bins have endpoint values of 75%, 85%, and 95%. We want our predictions to avoid those empty bins and become discriminative. Discrimination goes side-by-side with calibration in classification problems. Sometimes it comes before calibration if the goal in building a model is to make automatic decisions rather than provide statistical estimates. Here looking at the number of points in the bin, random forest (orange line) seems better than Logistic Regression (blue line).
An interesting article on model calibration can be found here for additional reading.
Calibration techniques are usually based on deriving a transformation that converts the values or the probabilities to better estimates. Most of the transformation techniques usually include binning or sorting in case of classification. I will recommend a goodness-of-fit test (Hosmer-Lemeshow) for the model fit assessment. If you are interested, you may read this article to know more.
I can be reached here .
|
[
{
"code": null,
"e": 268,
"s": 172,
"text": "CALIBRATION is a post-processing technique to improve error distribution of a predictive model."
},
{
"code": null,
"e": 820,
"s": 268,
"text": "The evaluation of machine learning (ML) models is a crucial step before deployment. Therefore, it is essential to go through a behavior analysis of a ML model. In many real-life applications, along with mean error of the model, it is also important to know how this error is distributed and how well probability estimations are made. To my experience, many current ML techniques are good in overall results but have a bad distribution assessment of the error. I will discuss common calibration techniques and calibration measures using classification."
},
{
"code": null,
"e": 1038,
"s": 820,
"text": "From the scientific context, the primary goal of ML methods is to build a hypothesis (model) from a given data set. After the learning process, the quality of the hypothesis must be evaluated as precisely as possible."
},
{
"code": null,
"e": 1600,
"s": 1038,
"text": "The common measures are accuracy (the inverse of error), f-measure, or macro-average for classification based model. In probabilistic classification, besides the percentage of correctly classified instances, other measures such as logloss, mean squared error (MSE) (or Brier’s score) or area under the ROC curve (AUROC) are used. If the outputs are not binary but are floating numbers between 0 and 1, then the scores can be used for ranking. But floating numbers between 0 and 1 leads to probabilities, and how do we know if we can trust them as probabilities?"
},
{
"code": null,
"e": 2295,
"s": 1600,
"text": "We want a good classifier to identify between true positives and true negatives. We are going to deal with telecom customer data here; so in “Churn” analysis we would expect the classifier to trigger a flag between “Churn” and “NoChurn”, which allows us to calibrate the sensitivity of this model by adjusting the threshold. This means, if the classifier can detect 90% possibility of “Churn”, business should see that as true label. Moreover, most of the classification related data is highly imbalanced where number of “Churn” is quite less than “NoChurn”. So, we might want to re-sample the data to balance them, and that way we may induce some bias to our model by making it too aggressive."
},
{
"code": null,
"e": 2835,
"s": 2295,
"text": "When dealing with two class classification problems we can always label one class as a positive and the other one as a negative class. The test set consists of P positive and N negative examples. A classifier assigns a class to each of them, but some of the assignments are wrong. To assess the classification results we count the number of true positive (TP), true negative (TN), false positive (FP) (actually negative, but classified as positive) and false negative (FN) (actually positive, but classified as negative) examples. It holds"
},
{
"code": null,
"e": 2851,
"s": 2835,
"text": "TP + FN = P and"
},
{
"code": null,
"e": 2863,
"s": 2851,
"text": "TN + FP = N"
},
{
"code": null,
"e": 3027,
"s": 2863,
"text": "The classifier assigned TP + FP examples to the positive class and TN + FN examples to the negative class. Let us define a few well-known and widely used measures:"
},
{
"code": null,
"e": 3042,
"s": 3027,
"text": "FPrate = FP /N"
},
{
"code": null,
"e": 3066,
"s": 3042,
"text": "TPrate = TP /P = Recall"
},
{
"code": null,
"e": 3093,
"s": 3066,
"text": "Yrate = (TP + FP) /(P + N)"
},
{
"code": null,
"e": 3119,
"s": 3093,
"text": "Precision = TP/ (TP + FP)"
},
{
"code": null,
"e": 3150,
"s": 3119,
"text": "Accuracy = (TP + TN)/ (P + N)."
},
{
"code": null,
"e": 3362,
"s": 3150,
"text": "Precision and Accuracy are often used to measure the classification quality of binary classifiers. Several other measures used for special purposes can also be defined. We describe them in the following sections"
},
{
"code": null,
"e": 4037,
"s": 3362,
"text": "A probabilistic classifier is a function f : X → [0, 1] that maps each example x to a real number f(x). Normally, a threshold t is selected for which the examples where f(x) ≥ t are considered positive and the others are considered negative. This implies that each pair of a probabilistic classifier and threshold t defines a binary classifier. Measures defined in the section above can therefore also be used for probabilistic classifiers, but they are always a function of the threshold t. Note that TP(t) and FP(t) are always monotonic descending functions. For a finite example set, they are step-wise, not continuous. By varying t we get a family of binary classifiers."
},
{
"code": null,
"e": 4088,
"s": 4037,
"text": "Let’s experiment on the telecom data that we have."
},
{
"code": null,
"e": 4203,
"s": 4088,
"text": "# Loading the CSV with pandasdata = pd.read_csv(‘Telco_Customer_Churn.csv’)data.dtypes # types of data in data set"
},
{
"code": null,
"e": 4335,
"s": 4203,
"text": "#Removing customer IDs from the data set the columns not used in the predictive model.df = data.drop(“customerID”, axis=1)df.info()"
},
{
"code": null,
"e": 4718,
"s": 4335,
"text": "We will covert the categorical variables (‘Yes’,’No’,etc.) into numeric values. Also, need to convert “Total Charges” to a numerical data type. Moreover, there are 11 missing values for “Total Charges”. So it will replace 11 rows from the data set. The predictor variable here is “Churn”. Therefore, it is necessary to convert the predictor variable in binary numeric variables too."
},
{
"code": null,
"e": 4974,
"s": 4718,
"text": "df.dropna(inplace = True)df[‘Churn’].replace(to_replace=’Yes’, value=1, inplace=True)df[‘Churn’].replace(to_replace=’No’, value=0, inplace=True)# converting all the categorical variables into dummy variablesdf_dummies = pd.get_dummies(df)df_dummies.info()"
},
{
"code": null,
"e": 5171,
"s": 4974,
"text": "We will consider Logistics Regression and Random Forest Classifier to predict customer churn. It is important to scale the variables in regression so that all of them are within a range of 0 to 1."
},
{
"code": null,
"e": 5595,
"s": 5171,
"text": "df_dummies = df_dummies.drop(“TotalCharges”, axis=1) # removing Total Charges to avoid multi-colinearity.# Using the data frame where we had created dummy variablesy = df_dummies[‘Churn’].valuesX = df_dummies.drop(columns = [‘Churn’])# Scaling all the variables to a range of 0 to 1features = X.columns.valuesscaler = MinMaxScaler(feature_range = (0,1))scaler.fit(X)X = pd.DataFrame(scaler.transform(X))X.columns = features"
},
{
"code": null,
"e": 5887,
"s": 5595,
"text": "Our first step was to split our data into training and test sets using train-test-split, which would allow us to cross-validate our results later. We also stratified the train-test-split, to ensure that the same proportion of our target variable was found in both our training and test sets."
},
{
"code": null,
"e": 6180,
"s": 5887,
"text": "X is the data with the independent variables, y is the data with the dependent variable. The test size variable determines in which ratio the data will be split. It is quite common to do this in a 90 Training/10 Test ratio. Also, need to stratify the train-test-split to have a balanced split"
},
{
"code": null,
"e": 6403,
"s": 6180,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=101)print(‘length of X_train and x_test: ‘, len(X_train), len(X_test))print(‘length of y_train and y_test: ‘, len(y_train), len(y_test))"
},
{
"code": null,
"e": 6683,
"s": 6403,
"text": "Using ML algorithm and the dependent variable here churn 1 or churn 0 is categorical. The trained model can be used to predict if a customer churned or not for the test data set. The results are saved in “prediction_test” and afterward the accuracy score is measured and printed."
},
{
"code": null,
"e": 6926,
"s": 6683,
"text": "lr_model = LogisticRegression(solver=’lbfgs’).fit(X_train, y_train)lr_prediction = lr_model.predict_proba(X_test)prediction_test = lr_model.predict(X_test)lr_pred = lr_model.predict(X_test)print(classification_report(y_test, prediction_test))"
},
{
"code": null,
"e": 7037,
"s": 6926,
"text": "Out of 557 points in the first class ( NoChurn) the model was successful in identifying 502 of those correctly"
},
{
"code": null,
"e": 7104,
"s": 7037,
"text": "Out of 147 points in class 1, model predicted 77 of them correctly"
},
{
"code": null,
"e": 7161,
"s": 7104,
"text": "Out of 704 total, model predicted 579 of them correctly."
},
{
"code": null,
"e": 7352,
"s": 7161,
"text": "Accuracy is 82% (precisely 82.24%). However, it may not be the right measure considering the data is skewed and target class is not balanced. So, we look into the Precision, Recall, F score."
},
{
"code": null,
"e": 7496,
"s": 7352,
"text": "The confusion matrix clearly shows the model performance broken down into true positives, true negatives, false positives, and false negatives."
},
{
"code": null,
"e": 7699,
"s": 7496,
"text": "Precision is the ability of a classifier not to label an instance positive that is actually negative. For each class, it is defined as the ratio of true positives to the sum of true and false positives."
},
{
"code": null,
"e": 7880,
"s": 7699,
"text": "Recall is the ability of a classifier to find all positive instances. For each class, it is defined as the ratio of true positives to the sum of true positives and false negatives."
},
{
"code": null,
"e": 7999,
"s": 7880,
"text": "The F1 score is a weighted harmonic mean of precision and recall such that the best score is 1.0 and the worst is 0.0."
},
{
"code": null,
"e": 8353,
"s": 7999,
"text": "CC is the degree of approximation of the true class distribution with the estimated class distribution. The standard way to calibrate a model in this way is by changing the threshold that determines when the model predicts “Churn” or “NoChurn”, making this threshold stricter with class “Churn” and milder with class “NoChurn” to balance the proportion."
},
{
"code": null,
"e": 9014,
"s": 8353,
"text": "y_scores=lr_predictionprec, rec, tre = precision_recall_curve(y_test, y_scores[:,1], )def plot_prec_recall_vs_tresh(precisions, recalls, thresholds): fig, ax = plt.subplots(figsize=(10,6)) plt.plot(thresholds, precisions[:-1], “r — “, label=”Precisions”) plt.plot(thresholds, recalls[:-1], “#424242”, label=”Recalls”) plt.ylabel(“Level of Precision and Recall”, fontsize=12) plt.title(“Precision and Recall Scores as a function of the decision threshold”, fontsize=12) plt.xlabel(‘Thresholds’, fontsize=12) plt.legend(loc=”best”, fontsize=12) plt.ylim([0,1]) plt.axvline(x=0.47, linewidth=3, color=”#0B3861\") plot_prec_recall_vs_tresh(prec, rec, tre)plt.show()"
},
{
"code": null,
"e": 9493,
"s": 9014,
"text": "The precision (58.33%) and recall (52.38%) for predictions in the positive class (“Churn”) are relatively low. The area above the intersection point is the area of good performance levels. The other area below is the area of poor performance. In principle, this type of calibration might produce more error. In fact, it is usually the case when we want to obtain a useful model for problems with very imbalanced class distribution, i.e. the minority class has very few examples."
},
{
"code": null,
"e": 9716,
"s": 9493,
"text": "A more visual way to measure the performance of a binary classifier is the area under the receiver operating characteristic (AUROC) curve. It tells how much the model is capable of distinguishing between Churn and NoChurn."
},
{
"code": null,
"e": 9808,
"s": 9716,
"text": "lr_prediction = lr_model.predict_proba(X_test)skplt.metrics.plot_roc(y_test, lr_prediction)"
},
{
"code": null,
"e": 9966,
"s": 9808,
"text": "AUROC curves are known to show little effect from class distribution variations (up-scaling has very minor effect on FP, while we can see some effect on TP)."
},
{
"code": null,
"e": 10453,
"s": 9966,
"text": "Macro-average computes the metric independently for each class and then take the average (hence treating all classes equally), whereas a micro-average aggregates the contributions of all classes to compute the average metric. If we want to know how the system performs overall across the sets of data, we will consider macro average. We should not come up with any specific decision with this average. On the other hand, micro-average is useful measure when our data set varies in size."
},
{
"code": null,
"e": 10702,
"s": 10453,
"text": "So, we see here that, the ROC curves fail to explicitly show the difference between balanced and imbalanced cases. Moreover, the AUROC scores are inadequate to evaluate the early retrieval performance especially when curves are crossing each other."
},
{
"code": null,
"e": 10867,
"s": 10702,
"text": "We will check with RandomForest Classifier; however, we won’t go into the details again. A similar set of processes like Logistic Regression can be done to compare."
},
{
"code": null,
"e": 10941,
"s": 10867,
"text": "Similarly, train a random forest model and predict on the validation set."
},
{
"code": null,
"e": 11109,
"s": 10941,
"text": "rf_model = RandomForestClassifier(random_state=101, n_estimators=100).fit(X_train, y_train)rf_prediction = rf_model.predict_proba(X_test)rf_model.score(X_test, y_test)"
},
{
"code": null,
"e": 11130,
"s": 11109,
"text": "# 0.7798295454545454"
},
{
"code": null,
"e": 11853,
"s": 11130,
"text": "PC accompanies each prediction with a probability estimation. If we predict that we are 99% sure, and if we are only right 50% of the time, this is not calibrated because our estimation was too optimistic. Similarly, if we predict that we are only 60% sure, and we are right 80% of the time, this is not calibrated because our estimation was too pessimistic. In both cases, the expected value of the number or proportion of right guesses (in this case the probability or the confidence assessment) does not match the actual value. Calibration is then defined as the degree of approximation of the predicted probabilities to the actual probabilities. Accuracy and calibration, although dependent, are very different things."
},
{
"code": null,
"e": 11948,
"s": 11853,
"text": "Here, we have the class probabilities and labels to compute the bins for the calibration plot."
},
{
"code": null,
"e": 12588,
"s": 11948,
"text": "lr_y, lr_x = calibration_curve(y_test, lr_prediction[:,1], n_bins=20)rf_y, rf_x = calibration_curve(y_test, rf_prediction[:,1], n_bins=20)fig, ax = plt.subplots()# only these two lines are calibration curvesplt.plot(lr_x,lr_y, marker=’o’, linewidth=1, label=’lr’)plt.plot(rf_x, rf_y, marker=’o’, linewidth=1, label=’rf’)# reference line, legends, and axis labelsline = mlines.Line2D([0, 1], [0, 1], color=’black’)transform = ax.transAxesline.set_transform(transform)ax.add_line(line)fig.suptitle(‘Calibration plot for Telecom data’)ax.set_xlabel(‘Predicted probability’)ax.set_ylabel(‘True probability in each bin’)plt.legend(); plt.show()"
},
{
"code": null,
"e": 12890,
"s": 12588,
"text": "def bin_total(y_true, y_prob, n_bins): bins = np.linspace(0., 1. + 1e-8, n_bins + 1)# In sklearn.calibration.calibration_curve the last value in the array is always 0. binids = np.digitize(y_prob, bins) — 1return np.bincount(binids, minlength=len(bins))bin_total(y_test, lr_prediction[:,1], n_bins=20)"
},
{
"code": null,
"e": 12980,
"s": 12890,
"text": "# array([191, 88, 47, 58, 46, 32, 30, 32, 24, 24, 25, 22, 22, 19, 24, 17, 2, 1, 0, 0, 0])"
},
{
"code": null,
"e": 13029,
"s": 12980,
"text": "bin_total(y_test, rf_prediction[:,1], n_bins=20)"
},
{
"code": null,
"e": 13120,
"s": 13029,
"text": "# array([213, 70, 59, 47, 39, 42, 27, 27, 22, 18, 26, 21, 22, 18, 7, 12, 10, 6, 7, 11, 0])"
},
{
"code": null,
"e": 13607,
"s": 13120,
"text": "The missing bins have endpoint values of 75%, 85%, and 95%. We want our predictions to avoid those empty bins and become discriminative. Discrimination goes side-by-side with calibration in classification problems. Sometimes it comes before calibration if the goal in building a model is to make automatic decisions rather than provide statistical estimates. Here looking at the number of points in the bin, random forest (orange line) seems better than Logistic Regression (blue line)."
},
{
"code": null,
"e": 13693,
"s": 13607,
"text": "An interesting article on model calibration can be found here for additional reading."
},
{
"code": null,
"e": 14081,
"s": 13693,
"text": "Calibration techniques are usually based on deriving a transformation that converts the values or the probabilities to better estimates. Most of the transformation techniques usually include binning or sorting in case of classification. I will recommend a goodness-of-fit test (Hosmer-Lemeshow) for the model fit assessment. If you are interested, you may read this article to know more."
}
] |
Print all possible paths in a DAG from vertex whose indegree is 0
|
13 Oct, 2021
Given a Directed Acyclic Graph (DAG), having N vertices and M edges, The task is to print all path starting from vertex whose in-degree is zero.
Indegree of a vertex is the total number of incoming edges to a vertex.
Example:
Input: N = 6, edges[] = {{5, 0}, {5, 2}, {4, 0}, {4, 1}, {2, 3}, {3, 1}} Output: All possible paths: 4 0 4 1 5 0 5 2 3 1 Explanation: The given graph can be represented as:
There are two vertices whose indegree are zero i.e vertex 5 and 4, after exploring these vertices we got the fallowing path: 4 -> 0 4 -> 1 5 -> 0 5 -> 2 -> 3 -> 1
Input: N = 6, edges[] = {{0, 5}} Output: All possible paths: 0 5 Explanation: There will be only one possible path in the graph.
Approach:
Create a boolean array indeg0 which store a true value for all those vertex whose indegree is zero.Apply DFS on all those vertex whose indegree is 0.Print all path starting from a vertex whose indegree is 0 to a vertex whose outdegrees are zero.
Create a boolean array indeg0 which store a true value for all those vertex whose indegree is zero.
Apply DFS on all those vertex whose indegree is 0.
Print all path starting from a vertex whose indegree is 0 to a vertex whose outdegrees are zero.
Illustration: For the above graph: indeg0[] = {False, False, False, False, True, True} Since indeg[4] = True, so applying DFS on vertex 4 and printing all path terminating to 0 outdegree vertex are as follow: 4 -> 0 4 -> 1 Also indeg[5] = True, so applying DFS on vertex 5 and printing all path terminating to 0 outdegree vertex are as follow: 5 -> 0 5 -> 2 -> 3 -> 1
Here is the implementation of the above approach:
C++
Python3
// C++ program to print// all possible paths in a DAG #include <bits/stdc++.h>using namespace std; vector<int> path; vector<bool> indeg0, outdeg0; vector<vector<int> > adj; vector<bool> visited; // Recursive function to print all pathsvoid dfs(int s){ // Append the node in path // and set visited path.push_back(s); visited[s] = true; // Path started with a node // having in-degree 0 and // current node has out-degree 0, // print current path if (outdeg0[s] && indeg0[path[0]]) { for (auto x : path) cout << x << " "; cout << '\n'; } for (auto node : adj[s]) { if (!visited[node]) dfs(node); } path.pop_back(); visited[s] = false;} void print_all_paths(int n){ for (int i = 0; i < n; i++) { // for each node with in-degree 0 // print all possible paths if (indeg0[i] && !adj[i].empty()) { dfs(i); } }} // Driver Codeint main(){ int n; n = 6; // set all nodes unvisited visited = vector<bool>(n, false); // adjacency list for nodes adj = vector<vector<int> >(n); // indeg0 and outdeg0 arrays indeg0 = vector<bool>(n, true); outdeg0 = vector<bool>(n, true); // edges vector<pair<int, int> > edges = { { 5, 0 }, { 5, 2 }, { 2, 3 }, { 4, 0 }, { 4, 1 }, { 3, 1 } }; for (int i = 0; i < edges.size(); i++) { int u = edges[i].first; int v = edges[i].second; adj[u].push_back(v); // set indeg0[v] <- false indeg0[v] = false; // set outdeg0[u] <- false outdeg0[u] = false; } cout << "All possible paths:\n"; print_all_paths(n); return 0;}
# Python program to print all# possible paths in a DAG # Recursive function to print all pathsdef dfs(s): # Append the node in path # and set visited path.append(s) visited[s] = True # Path started with a node # having in-degree 0 and # current node has out-degree 0, # print current path if outdeg0[s] and indeg0[path[0]]: print(*path) # Recursive call to print all paths for node in adj[s]: if not visited[node]: dfs(node) # Remove node from path # and set unvisited path.pop() visited[s] = False def print_all_paths(n): for i in range(n): # for each node with in-degree 0 # print all possible paths if indeg0[i] and adj[i]: path = [] visited = [False] * (n + 1) dfs(i) # Driver codefrom collections import defaultdict n = 6# set all nodes unvisitedvisited = [False] * (n + 1)path = [] # edges = (a, b): a -> bedges = [(5, 0), (5, 2), (2, 3), (4, 0), (4, 1), (3, 1)] # adjacency list for nodesadj = defaultdict(list) # indeg0 and outdeg0 arraysindeg0 = [True]*noutdeg0 = [True]*n for edge in edges: u, v = edge[0], edge[1] # u -> v adj[u].append(v) # set indeg0[v] <- false indeg0[v] = False # set outdeg0[u] <- false outdeg0[u] = False print('All possible paths:')print_all_paths(n)
All possible paths:
4 0
4 1
5 0
5 2 3 1
Time Complexity: O (N + E)2 Auxiliary Space: O (N)
surindertarika1234
simmytarika5
ashutoshsinghgeeksforgeeks
DFS
Algorithms
Data Structures
Graph
Data Structures
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
CPU Scheduling in Operating Systems
Understanding Time Complexity with Simple Examples
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
What is Priority Queue | Introduction to Priority Queue
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "Given a Directed Acyclic Graph (DAG), having N vertices and M edges, The task is to print all path starting from vertex whose in-degree is zero. "
},
{
"code": null,
"e": 248,
"s": 174,
"text": "Indegree of a vertex is the total number of incoming edges to a vertex. "
},
{
"code": null,
"e": 259,
"s": 248,
"text": "Example: "
},
{
"code": null,
"e": 434,
"s": 259,
"text": "Input: N = 6, edges[] = {{5, 0}, {5, 2}, {4, 0}, {4, 1}, {2, 3}, {3, 1}} Output: All possible paths: 4 0 4 1 5 0 5 2 3 1 Explanation: The given graph can be represented as: "
},
{
"code": null,
"e": 598,
"s": 434,
"text": "There are two vertices whose indegree are zero i.e vertex 5 and 4, after exploring these vertices we got the fallowing path: 4 -> 0 4 -> 1 5 -> 0 5 -> 2 -> 3 -> 1 "
},
{
"code": null,
"e": 728,
"s": 598,
"text": "Input: N = 6, edges[] = {{0, 5}} Output: All possible paths: 0 5 Explanation: There will be only one possible path in the graph. "
},
{
"code": null,
"e": 740,
"s": 728,
"text": "Approach: "
},
{
"code": null,
"e": 986,
"s": 740,
"text": "Create a boolean array indeg0 which store a true value for all those vertex whose indegree is zero.Apply DFS on all those vertex whose indegree is 0.Print all path starting from a vertex whose indegree is 0 to a vertex whose outdegrees are zero."
},
{
"code": null,
"e": 1086,
"s": 986,
"text": "Create a boolean array indeg0 which store a true value for all those vertex whose indegree is zero."
},
{
"code": null,
"e": 1137,
"s": 1086,
"text": "Apply DFS on all those vertex whose indegree is 0."
},
{
"code": null,
"e": 1234,
"s": 1137,
"text": "Print all path starting from a vertex whose indegree is 0 to a vertex whose outdegrees are zero."
},
{
"code": null,
"e": 1604,
"s": 1234,
"text": "Illustration: For the above graph: indeg0[] = {False, False, False, False, True, True} Since indeg[4] = True, so applying DFS on vertex 4 and printing all path terminating to 0 outdegree vertex are as follow: 4 -> 0 4 -> 1 Also indeg[5] = True, so applying DFS on vertex 5 and printing all path terminating to 0 outdegree vertex are as follow: 5 -> 0 5 -> 2 -> 3 -> 1 "
},
{
"code": null,
"e": 1655,
"s": 1604,
"text": "Here is the implementation of the above approach: "
},
{
"code": null,
"e": 1659,
"s": 1655,
"text": "C++"
},
{
"code": null,
"e": 1667,
"s": 1659,
"text": "Python3"
},
{
"code": "// C++ program to print// all possible paths in a DAG #include <bits/stdc++.h>using namespace std; vector<int> path; vector<bool> indeg0, outdeg0; vector<vector<int> > adj; vector<bool> visited; // Recursive function to print all pathsvoid dfs(int s){ // Append the node in path // and set visited path.push_back(s); visited[s] = true; // Path started with a node // having in-degree 0 and // current node has out-degree 0, // print current path if (outdeg0[s] && indeg0[path[0]]) { for (auto x : path) cout << x << \" \"; cout << '\\n'; } for (auto node : adj[s]) { if (!visited[node]) dfs(node); } path.pop_back(); visited[s] = false;} void print_all_paths(int n){ for (int i = 0; i < n; i++) { // for each node with in-degree 0 // print all possible paths if (indeg0[i] && !adj[i].empty()) { dfs(i); } }} // Driver Codeint main(){ int n; n = 6; // set all nodes unvisited visited = vector<bool>(n, false); // adjacency list for nodes adj = vector<vector<int> >(n); // indeg0 and outdeg0 arrays indeg0 = vector<bool>(n, true); outdeg0 = vector<bool>(n, true); // edges vector<pair<int, int> > edges = { { 5, 0 }, { 5, 2 }, { 2, 3 }, { 4, 0 }, { 4, 1 }, { 3, 1 } }; for (int i = 0; i < edges.size(); i++) { int u = edges[i].first; int v = edges[i].second; adj[u].push_back(v); // set indeg0[v] <- false indeg0[v] = false; // set outdeg0[u] <- false outdeg0[u] = false; } cout << \"All possible paths:\\n\"; print_all_paths(n); return 0;}",
"e": 3360,
"s": 1667,
"text": null
},
{
"code": "# Python program to print all# possible paths in a DAG # Recursive function to print all pathsdef dfs(s): # Append the node in path # and set visited path.append(s) visited[s] = True # Path started with a node # having in-degree 0 and # current node has out-degree 0, # print current path if outdeg0[s] and indeg0[path[0]]: print(*path) # Recursive call to print all paths for node in adj[s]: if not visited[node]: dfs(node) # Remove node from path # and set unvisited path.pop() visited[s] = False def print_all_paths(n): for i in range(n): # for each node with in-degree 0 # print all possible paths if indeg0[i] and adj[i]: path = [] visited = [False] * (n + 1) dfs(i) # Driver codefrom collections import defaultdict n = 6# set all nodes unvisitedvisited = [False] * (n + 1)path = [] # edges = (a, b): a -> bedges = [(5, 0), (5, 2), (2, 3), (4, 0), (4, 1), (3, 1)] # adjacency list for nodesadj = defaultdict(list) # indeg0 and outdeg0 arraysindeg0 = [True]*noutdeg0 = [True]*n for edge in edges: u, v = edge[0], edge[1] # u -> v adj[u].append(v) # set indeg0[v] <- false indeg0[v] = False # set outdeg0[u] <- false outdeg0[u] = False print('All possible paths:')print_all_paths(n)",
"e": 4710,
"s": 3360,
"text": null
},
{
"code": null,
"e": 4750,
"s": 4710,
"text": "All possible paths:\n4 0\n4 1\n5 0\n5 2 3 1"
},
{
"code": null,
"e": 4804,
"s": 4752,
"text": "Time Complexity: O (N + E)2 Auxiliary Space: O (N) "
},
{
"code": null,
"e": 4823,
"s": 4804,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4836,
"s": 4823,
"text": "simmytarika5"
},
{
"code": null,
"e": 4863,
"s": 4836,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 4867,
"s": 4863,
"text": "DFS"
},
{
"code": null,
"e": 4878,
"s": 4867,
"text": "Algorithms"
},
{
"code": null,
"e": 4894,
"s": 4878,
"text": "Data Structures"
},
{
"code": null,
"e": 4900,
"s": 4894,
"text": "Graph"
},
{
"code": null,
"e": 4916,
"s": 4900,
"text": "Data Structures"
},
{
"code": null,
"e": 4920,
"s": 4916,
"text": "DFS"
},
{
"code": null,
"e": 4926,
"s": 4920,
"text": "Graph"
},
{
"code": null,
"e": 4937,
"s": 4926,
"text": "Algorithms"
},
{
"code": null,
"e": 5035,
"s": 4937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5060,
"s": 5035,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 5109,
"s": 5060,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 5147,
"s": 5109,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 5183,
"s": 5147,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 5234,
"s": 5183,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 5259,
"s": 5234,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 5308,
"s": 5259,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 5340,
"s": 5308,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5396,
"s": 5340,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
How to Convert Datetime to Date in Pandas ?
|
09 Dec, 2021
DateTime is a collection of dates and times in the format of “yyyy-mm-dd HH:MM:SS” where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time.
yyyy stands for year
mm stands for month
dd stands for date
HH stands for hours
MM stands for minutes
SS stands for seconds.
In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime using Pandas Python module.
Syntax:
pd.DataFrame(data)
where data is the input DateTime data.
Example: Python program to create the pandas dataframe with 5 datetime values and display
Python3
# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) # displayprint(df)
Output:
DateTime
0 2021-01-15 20:02:11
1 1989-05-24 20:34:11
2 2020-01-18 14:43:24
3 2021-01-15 20:02:10
4 1999-04-04 20:34:11
By using date method along with pandas we can get date.
Syntax:
dataframe[‘Date’] = pd.to_datetime(dataframe[‘DateTime’]).dt.date
where,
dataframe is the input dataframe
to_datetime is the function used to convert datetime string to datetime
DateTime is the datetime column in the dataframe
dt.date is used to convert datetime to date
Date column is the new column to get the date from the datetime
Example: Python program to convert datetime to date using pandas through date function
Python3
# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print("Original data")print(df) # convert datetime column to just datedf['Date'] = pd.to_datetime(df['DateTime']).dt.date # displayprint("Only date")print(df)
Output:
we can also get the datatypes by using dtypes
Example: Python program to get the datatypes
Python3
# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print("---------Original data------------")print(df.dtypes) # convert datetime column to just datedf['Date'] = pd.to_datetime(df['DateTime']).dt.date # displayprint("--------Only date---------")print(df.dtypes)
Output:
we can get by also using normalize() method, this method is used to normalize the data by extracting the date from DateTime. We are using normalize() method to get the data through pandas
Syntax:
dataframe[‘Date’] = pd.to_datetime(dataframe[‘DateTime’]).dt.normalize()
where,
dataframe is the input dataframe
to_datetime is the function used to convert datetime string to datetime
DateTime is the datetime column in the dataframe
dt.normalize() is the function which is used to convert datetime to date
Date column is the new column to get the date from the datetime
Example: Python code to convert datetime to date using pandas normalize() method.
Python3
# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print("Original data")print(df) # convert datetime column to just date using normalize()# methoddf['Date'] = pd.to_datetime(df['DateTime']).dt.normalize() # displayprint("date extracted")print(df)
Output:
simmytarika5
Picked
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "DateTime is a collection of dates and times in the format of “yyyy-mm-dd HH:MM:SS” where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time."
},
{
"code": null,
"e": 213,
"s": 192,
"text": "yyyy stands for year"
},
{
"code": null,
"e": 234,
"s": 213,
"text": "mm stands for month"
},
{
"code": null,
"e": 253,
"s": 234,
"text": "dd stands for date"
},
{
"code": null,
"e": 273,
"s": 253,
"text": "HH stands for hours"
},
{
"code": null,
"e": 295,
"s": 273,
"text": "MM stands for minutes"
},
{
"code": null,
"e": 318,
"s": 295,
"text": "SS stands for seconds."
},
{
"code": null,
"e": 481,
"s": 318,
"text": "In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime using Pandas Python module. "
},
{
"code": null,
"e": 489,
"s": 481,
"text": "Syntax:"
},
{
"code": null,
"e": 508,
"s": 489,
"text": "pd.DataFrame(data)"
},
{
"code": null,
"e": 547,
"s": 508,
"text": "where data is the input DateTime data."
},
{
"code": null,
"e": 637,
"s": 547,
"text": "Example: Python program to create the pandas dataframe with 5 datetime values and display"
},
{
"code": null,
"e": 645,
"s": 637,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) # displayprint(df)",
"e": 1071,
"s": 645,
"text": null
},
{
"code": null,
"e": 1079,
"s": 1071,
"text": "Output:"
},
{
"code": null,
"e": 1088,
"s": 1079,
"text": "DateTime"
},
{
"code": null,
"e": 1111,
"s": 1088,
"text": "0 2021-01-15 20:02:11"
},
{
"code": null,
"e": 1134,
"s": 1111,
"text": "1 1989-05-24 20:34:11"
},
{
"code": null,
"e": 1157,
"s": 1134,
"text": "2 2020-01-18 14:43:24"
},
{
"code": null,
"e": 1180,
"s": 1157,
"text": "3 2021-01-15 20:02:10"
},
{
"code": null,
"e": 1203,
"s": 1180,
"text": "4 1999-04-04 20:34:11"
},
{
"code": null,
"e": 1259,
"s": 1203,
"text": "By using date method along with pandas we can get date."
},
{
"code": null,
"e": 1267,
"s": 1259,
"text": "Syntax:"
},
{
"code": null,
"e": 1333,
"s": 1267,
"text": "dataframe[‘Date’] = pd.to_datetime(dataframe[‘DateTime’]).dt.date"
},
{
"code": null,
"e": 1340,
"s": 1333,
"text": "where,"
},
{
"code": null,
"e": 1373,
"s": 1340,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 1445,
"s": 1373,
"text": "to_datetime is the function used to convert datetime string to datetime"
},
{
"code": null,
"e": 1494,
"s": 1445,
"text": "DateTime is the datetime column in the dataframe"
},
{
"code": null,
"e": 1538,
"s": 1494,
"text": "dt.date is used to convert datetime to date"
},
{
"code": null,
"e": 1602,
"s": 1538,
"text": "Date column is the new column to get the date from the datetime"
},
{
"code": null,
"e": 1689,
"s": 1602,
"text": "Example: Python program to convert datetime to date using pandas through date function"
},
{
"code": null,
"e": 1697,
"s": 1689,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print(\"Original data\")print(df) # convert datetime column to just datedf['Date'] = pd.to_datetime(df['DateTime']).dt.date # displayprint(\"Only date\")print(df)",
"e": 2263,
"s": 1697,
"text": null
},
{
"code": null,
"e": 2271,
"s": 2263,
"text": "Output:"
},
{
"code": null,
"e": 2317,
"s": 2271,
"text": "we can also get the datatypes by using dtypes"
},
{
"code": null,
"e": 2362,
"s": 2317,
"text": "Example: Python program to get the datatypes"
},
{
"code": null,
"e": 2370,
"s": 2362,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print(\"---------Original data------------\")print(df.dtypes) # convert datetime column to just datedf['Date'] = pd.to_datetime(df['DateTime']).dt.date # displayprint(\"--------Only date---------\")print(df.dtypes)",
"e": 2988,
"s": 2370,
"text": null
},
{
"code": null,
"e": 2996,
"s": 2988,
"text": "Output:"
},
{
"code": null,
"e": 3184,
"s": 2996,
"text": "we can get by also using normalize() method, this method is used to normalize the data by extracting the date from DateTime. We are using normalize() method to get the data through pandas"
},
{
"code": null,
"e": 3192,
"s": 3184,
"text": "Syntax:"
},
{
"code": null,
"e": 3265,
"s": 3192,
"text": "dataframe[‘Date’] = pd.to_datetime(dataframe[‘DateTime’]).dt.normalize()"
},
{
"code": null,
"e": 3272,
"s": 3265,
"text": "where,"
},
{
"code": null,
"e": 3305,
"s": 3272,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 3377,
"s": 3305,
"text": "to_datetime is the function used to convert datetime string to datetime"
},
{
"code": null,
"e": 3426,
"s": 3377,
"text": "DateTime is the datetime column in the dataframe"
},
{
"code": null,
"e": 3500,
"s": 3426,
"text": "dt.normalize() is the function which is used to convert datetime to date"
},
{
"code": null,
"e": 3564,
"s": 3500,
"text": "Date column is the new column to get the date from the datetime"
},
{
"code": null,
"e": 3646,
"s": 3564,
"text": "Example: Python code to convert datetime to date using pandas normalize() method."
},
{
"code": null,
"e": 3654,
"s": 3646,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # create pandas DataFrame with one column with five# datetime values through a dictionarydf = pd.DataFrame({'DateTime': ['2021-01-15 20:02:11', '1989-05-24 20:34:11', '2020-01-18 14:43:24', '2021-01-15 20:02:10', '1999-04-04 20:34:11']}) print(\"Original data\")print(df) # convert datetime column to just date using normalize()# methoddf['Date'] = pd.to_datetime(df['DateTime']).dt.normalize() # displayprint(\"date extracted\")print(df)",
"e": 4258,
"s": 3654,
"text": null
},
{
"code": null,
"e": 4266,
"s": 4258,
"text": "Output:"
},
{
"code": null,
"e": 4279,
"s": 4266,
"text": "simmytarika5"
},
{
"code": null,
"e": 4286,
"s": 4279,
"text": "Picked"
},
{
"code": null,
"e": 4309,
"s": 4286,
"text": "Python pandas-datetime"
},
{
"code": null,
"e": 4323,
"s": 4309,
"text": "Python-pandas"
},
{
"code": null,
"e": 4330,
"s": 4323,
"text": "Python"
}
] |
Python | winfo_ismapped() and winfo_exists() in Tkinter
|
29 Nov, 2021
Tkinter provides numerous of universal widget methods or basic widget methods which works almost with all the available widgets.
This method is used to check whether the specified widget is visible or not.
Syntax: widget.winfo_ismapped()Return Value: Returns True if widget is visible (or mapped), otherwise returns False.Exception: If widget is destroyed, then it throws error.
Puython
# Imports tkinter and ttk modulefrom tkinter import * from tkinter.ttk import * import time # toplevel windowroot = Tk() def forget(widget): widget.forget() print("After Forget method called. Is widget mapped? = ", bool(widget.winfo_ismapped())) def retrieve(widget): widget.pack() print("After retrieval of widget. Is widget mapped? = ", bool(widget.winfo_exists())) # Button widgetsb1 = Button(root, text = "Btn 1")b1.pack() # This is used to make widget invisibleb2 = Button(root, text = "Btn 2", command = lambda : forget(b1))b2.pack() # This will retrieve widgetb3 = Button(root, text = "Btn 3", command = lambda : retrieve(b1))b3.pack() # infinite loop, interrupted by keyboard or mousemainloop()
Output:
This method is used to check if the specified widget exists or not i.e if the widget is destroyed or not.
Syntax: widget.winfo_exists()Return value: Returns True if widget exists, False otherwise.
Python
# Imports tkinter and ttk modulefrom tkinter import * from tkinter.ttk import * # toplevel windowroot = Tk() def dest(widget): widget.destroy() print("Destroy method called. Widget exists? = ", bool(widget.winfo_exists())) def exist(widget): print("Checking for existence = ", bool(widget.winfo_exists())) # Button widgetsb1 = Button(root, text = "Btn 1")b1.pack() # This is used to destroy widgetb2 = Button(root, text = "Btn 2", command = lambda : dest(b1))b2.pack() # This is used to check existence of the widgetb3 = Button(root, text = "Btn 3", command = lambda : exist(b1))b3.pack() # infinite loop, interrupted by keyboard or mousemainloop()
Output:
Note: If a widget is destroyed it cannot be retrieved again.
shubham_singh
bloominator
clintra
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "Tkinter provides numerous of universal widget methods or basic widget methods which works almost with all the available widgets. "
},
{
"code": null,
"e": 236,
"s": 158,
"text": "This method is used to check whether the specified widget is visible or not. "
},
{
"code": null,
"e": 409,
"s": 236,
"text": "Syntax: widget.winfo_ismapped()Return Value: Returns True if widget is visible (or mapped), otherwise returns False.Exception: If widget is destroyed, then it throws error."
},
{
"code": null,
"e": 419,
"s": 411,
"text": "Puython"
},
{
"code": "# Imports tkinter and ttk modulefrom tkinter import * from tkinter.ttk import * import time # toplevel windowroot = Tk() def forget(widget): widget.forget() print(\"After Forget method called. Is widget mapped? = \", bool(widget.winfo_ismapped())) def retrieve(widget): widget.pack() print(\"After retrieval of widget. Is widget mapped? = \", bool(widget.winfo_exists())) # Button widgetsb1 = Button(root, text = \"Btn 1\")b1.pack() # This is used to make widget invisibleb2 = Button(root, text = \"Btn 2\", command = lambda : forget(b1))b2.pack() # This will retrieve widgetb3 = Button(root, text = \"Btn 3\", command = lambda : retrieve(b1))b3.pack() # infinite loop, interrupted by keyboard or mousemainloop()",
"e": 1203,
"s": 419,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1203,
"text": "Output: "
},
{
"code": null,
"e": 1323,
"s": 1216,
"text": "This method is used to check if the specified widget exists or not i.e if the widget is destroyed or not. "
},
{
"code": null,
"e": 1414,
"s": 1323,
"text": "Syntax: widget.winfo_exists()Return value: Returns True if widget exists, False otherwise."
},
{
"code": null,
"e": 1423,
"s": 1416,
"text": "Python"
},
{
"code": "# Imports tkinter and ttk modulefrom tkinter import * from tkinter.ttk import * # toplevel windowroot = Tk() def dest(widget): widget.destroy() print(\"Destroy method called. Widget exists? = \", bool(widget.winfo_exists())) def exist(widget): print(\"Checking for existence = \", bool(widget.winfo_exists())) # Button widgetsb1 = Button(root, text = \"Btn 1\")b1.pack() # This is used to destroy widgetb2 = Button(root, text = \"Btn 2\", command = lambda : dest(b1))b2.pack() # This is used to check existence of the widgetb3 = Button(root, text = \"Btn 3\", command = lambda : exist(b1))b3.pack() # infinite loop, interrupted by keyboard or mousemainloop()",
"e": 2118,
"s": 1423,
"text": null
},
{
"code": null,
"e": 2127,
"s": 2118,
"text": "Output: "
},
{
"code": null,
"e": 2193,
"s": 2131,
"text": "Note: If a widget is destroyed it cannot be retrieved again. "
},
{
"code": null,
"e": 2207,
"s": 2193,
"text": "shubham_singh"
},
{
"code": null,
"e": 2219,
"s": 2207,
"text": "bloominator"
},
{
"code": null,
"e": 2227,
"s": 2219,
"text": "clintra"
},
{
"code": null,
"e": 2238,
"s": 2227,
"text": "Python-gui"
},
{
"code": null,
"e": 2253,
"s": 2238,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2260,
"s": 2253,
"text": "Python"
},
{
"code": null,
"e": 2358,
"s": 2260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2390,
"s": 2358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2417,
"s": 2390,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2438,
"s": 2417,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2461,
"s": 2438,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2517,
"s": 2461,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2548,
"s": 2517,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2590,
"s": 2548,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2632,
"s": 2590,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2671,
"s": 2632,
"text": "Python | Get unique values from a list"
}
] |
Deploy an NLP pipeline. Flask+Heroku+Bert. | by Galina Blokh | Towards Data Science
|
Very often, as a data scientist, you may be faced with a task that includes a complete pipeline: from the data collection up to deploy the app on the server. I bumped into such an odd job in the interview process during the job search. The focus was not to develop the most accurate or most complex model but to show a good grasp of Machine Learning and the NLP concept.In this article, I will show you how to deploy a Bert model and preprocessing pipeline. To deploy the application, I used the Heroku server and the Flask Python framework.
The task base is on the paper “Identifying Nuances in Fake News vs. Satire: Using Semantic and Linguistic Cues”. The paper introduces two models to classify textual content as “satire” or “fake news” — one model based on Google’s BERT and one model based on coherence metrics.
The goal for this task is:
to develop a new model to classify “satire” or “fake news” ;
to build a demo web application to serve the model predictions;
to deploy it to a cloud service Heroku.
The model can be any of your choices and will have the following features:
1. BERT embeddings (vectors) — using Sentence Transformers library representing each text.
2. Sentiment & Modality of each text — using patternen library.
Here the naive structure of the project :
/web-app||--data/| |--model_for_prediction.pkl|--static/| |--style.css|--templates/| |--home.html| |--result.html|--.gitignore|--app.py|--nltk.txt|--requirements.txt|--runtime.txt|--Procfile
Assuming you already have a labeled data set with an article/article paragraph in each cell. Label ‘1’ represents Satire and ‘0’ — Fake news.
Sentence Transformers documentation recommends several pre-trained models and a variety of tasks where we may apply them. Even if you see this library for the first time, the documentation with great clear examples will save your time substantially. So let’s begin!
BERT embeddings. I took a Tiny Bert model from the Hugging Face/Sentence Transformers library. The size is crucial in our task. Heroku has time and size limits — the size of the app should be less than 500Mb, and for each operation given a maximum of 30 seconds; thus, we don’t want to crash our web app. I chose a light 57.4Mb model and a PyTorch version for CPU (not GPU).
When I tried to install the sentence-transformers library and deploy the application, my web app crashed with Error H12 (Request timeout). I decided to implement this part in the handle way to decrease the runtime complexity. The PyTorch version for CPU reduced the app size significantly as well. It is possible to use sentence embeddings models without installing the whole library. Such a trick saved my time, and the web application didn’t crash again.
The sentiment of each text. Any text we can broadly categorize into two types: facts and opinions. Opinions carry people’s sentiments, appraisals, and feelings toward the world. The pattern.en module bundles a lexicon of adjectives (e.g., good, bad, amazing, irritating, etc.) that frequently occur in articles/reviews, annotated with scores for sentiment polarity (positive-negative) and subjectivity (objective ↔ subjective). Polarity is a value between -1.0 and +1.0 and subjectivity between 0.0 and 1.0. Let’s extract these values:
The modality of each text. The modality() function from the pattern library returns the degree of certainty as a value between -1.0 and +1.0, where values >+0.5 represent facts.
Last step in feature engineering — concatenation into one data set:
Model training. As written above, we can choose any model. I took a Logistic Regression from sklearn. You free to chose any you like. First, we create a model. Then save it into /data folder in a pickle format for future use:
Important notice. In this POC, I use Pandas Python library just for convenience. Pandas is not always the best library for running production code. It is good for analysis and data exploration, but it is slow because it does a bunch of stuff in the background.
It’s time to create a web application. The home.html file we place in the /templates folder. It looks like this:
Page to show the prediction result I made in a separate result.html file and put into the same /templates folder:
UI design is simple, and it is in /static/style.css:
Important: mark folders /data and /static as Resources. In PyCharm for Linux, you can do it in File-->Settings-->Project Structure. The /templates folder mark as Templates. Nice to exclude some folders from Heroku upload and reduce application size(virtual environment folder). Don’t forget to add a .gitignorefile in your project:
Since we use Flask for deployment, we need to point a template language:
Finally, in the project’s directory, we may create our app.py file. First, we put there all needed imports and preprocessing pipeline functions. Then we create a Flask app instance (line 50) and add functionality with home and resulting pages. In the predict() function, we open a saved before model and predict the input text.
Run the app in main. Congratulations! Now you can check your app work on the localhost http://127.0.0.1:5000/.
For the beginning, let’s create a requirements.txt file. There are two convenient ways to do it:
Via Pycharm IDE. Right-click on the project name→New →File→name the file requirements.txt. When you open an empty just created requirements.txt file, PyCharm IDE will offer you to write down all imports automatically. Very convenient way :)Via command line and 'pip freeze > requirements.txt’ inside your project directory.
Via Pycharm IDE. Right-click on the project name→New →File→name the file requirements.txt. When you open an empty just created requirements.txt file, PyCharm IDE will offer you to write down all imports automatically. Very convenient way :)
Via command line and 'pip freeze > requirements.txt’ inside your project directory.
Don’t forget to change a PyTorch version for CPU :
torch @ https://download.pytorch.org/whl/cpu/torch-1.6.0%2Bcpu-cp36-cp36m-linux_x86_64.whl
I got a pretty long list of libraries in the current project: 63. For those who faced such a task for the first time, I want to notice: the last line in requirements.txt should be empty.
An important note about Heroku and NLTK library: if your app uses the NLTK library, you should create an additional nltk.txt file with inner imports. In our case, pattern.text.en use NLTK and nltk.txt should contain two lines:
wordnetpros_cons
runtime.txt we need for pointing which Python version to use on the server. You may create it in the same way as a requirements.txt file: via IDE or the command line. Inside it should contain one line:
python-3.6.13
Procfile. This file tells the Heroku what to do when the application is deployed and contains one line as well:
web: gunicorn app:app
Make sure that you have a Heroku CLI (and Git CLI). Since now there are only command-line actions:
heroku loginheroku create your_application_name
The following steps are almost the same as for Git CLI:
git initgit add .git commit -m 'initial commit'git push heroku master
That’s all, folks! You deployed a WEB app on the Heroku server. The access link looks like https://your_application_name.herokuapp.com/
In this tutorial, you learned how to create an NLP pipeline, including Bert-based and additional feature engineering. You get familiar, as well, with how to create a demo WEB application with Flask and how to deploy it on the Heroku server.
Github repo. Code from the article.
My WEB app URL deployed on Heroku.
The article for inspiration.
Special acknowledgments to Mordechai Worch.
|
[
{
"code": null,
"e": 713,
"s": 171,
"text": "Very often, as a data scientist, you may be faced with a task that includes a complete pipeline: from the data collection up to deploy the app on the server. I bumped into such an odd job in the interview process during the job search. The focus was not to develop the most accurate or most complex model but to show a good grasp of Machine Learning and the NLP concept.In this article, I will show you how to deploy a Bert model and preprocessing pipeline. To deploy the application, I used the Heroku server and the Flask Python framework."
},
{
"code": null,
"e": 990,
"s": 713,
"text": "The task base is on the paper “Identifying Nuances in Fake News vs. Satire: Using Semantic and Linguistic Cues”. The paper introduces two models to classify textual content as “satire” or “fake news” — one model based on Google’s BERT and one model based on coherence metrics."
},
{
"code": null,
"e": 1017,
"s": 990,
"text": "The goal for this task is:"
},
{
"code": null,
"e": 1078,
"s": 1017,
"text": "to develop a new model to classify “satire” or “fake news” ;"
},
{
"code": null,
"e": 1142,
"s": 1078,
"text": "to build a demo web application to serve the model predictions;"
},
{
"code": null,
"e": 1182,
"s": 1142,
"text": "to deploy it to a cloud service Heroku."
},
{
"code": null,
"e": 1257,
"s": 1182,
"text": "The model can be any of your choices and will have the following features:"
},
{
"code": null,
"e": 1348,
"s": 1257,
"text": "1. BERT embeddings (vectors) — using Sentence Transformers library representing each text."
},
{
"code": null,
"e": 1412,
"s": 1348,
"text": "2. Sentiment & Modality of each text — using patternen library."
},
{
"code": null,
"e": 1454,
"s": 1412,
"text": "Here the naive structure of the project :"
},
{
"code": null,
"e": 1653,
"s": 1454,
"text": "/web-app||--data/| |--model_for_prediction.pkl|--static/| |--style.css|--templates/| |--home.html| |--result.html|--.gitignore|--app.py|--nltk.txt|--requirements.txt|--runtime.txt|--Procfile"
},
{
"code": null,
"e": 1795,
"s": 1653,
"text": "Assuming you already have a labeled data set with an article/article paragraph in each cell. Label ‘1’ represents Satire and ‘0’ — Fake news."
},
{
"code": null,
"e": 2061,
"s": 1795,
"text": "Sentence Transformers documentation recommends several pre-trained models and a variety of tasks where we may apply them. Even if you see this library for the first time, the documentation with great clear examples will save your time substantially. So let’s begin!"
},
{
"code": null,
"e": 2436,
"s": 2061,
"text": "BERT embeddings. I took a Tiny Bert model from the Hugging Face/Sentence Transformers library. The size is crucial in our task. Heroku has time and size limits — the size of the app should be less than 500Mb, and for each operation given a maximum of 30 seconds; thus, we don’t want to crash our web app. I chose a light 57.4Mb model and a PyTorch version for CPU (not GPU)."
},
{
"code": null,
"e": 2893,
"s": 2436,
"text": "When I tried to install the sentence-transformers library and deploy the application, my web app crashed with Error H12 (Request timeout). I decided to implement this part in the handle way to decrease the runtime complexity. The PyTorch version for CPU reduced the app size significantly as well. It is possible to use sentence embeddings models without installing the whole library. Such a trick saved my time, and the web application didn’t crash again."
},
{
"code": null,
"e": 3429,
"s": 2893,
"text": "The sentiment of each text. Any text we can broadly categorize into two types: facts and opinions. Opinions carry people’s sentiments, appraisals, and feelings toward the world. The pattern.en module bundles a lexicon of adjectives (e.g., good, bad, amazing, irritating, etc.) that frequently occur in articles/reviews, annotated with scores for sentiment polarity (positive-negative) and subjectivity (objective ↔ subjective). Polarity is a value between -1.0 and +1.0 and subjectivity between 0.0 and 1.0. Let’s extract these values:"
},
{
"code": null,
"e": 3607,
"s": 3429,
"text": "The modality of each text. The modality() function from the pattern library returns the degree of certainty as a value between -1.0 and +1.0, where values >+0.5 represent facts."
},
{
"code": null,
"e": 3675,
"s": 3607,
"text": "Last step in feature engineering — concatenation into one data set:"
},
{
"code": null,
"e": 3901,
"s": 3675,
"text": "Model training. As written above, we can choose any model. I took a Logistic Regression from sklearn. You free to chose any you like. First, we create a model. Then save it into /data folder in a pickle format for future use:"
},
{
"code": null,
"e": 4162,
"s": 3901,
"text": "Important notice. In this POC, I use Pandas Python library just for convenience. Pandas is not always the best library for running production code. It is good for analysis and data exploration, but it is slow because it does a bunch of stuff in the background."
},
{
"code": null,
"e": 4275,
"s": 4162,
"text": "It’s time to create a web application. The home.html file we place in the /templates folder. It looks like this:"
},
{
"code": null,
"e": 4389,
"s": 4275,
"text": "Page to show the prediction result I made in a separate result.html file and put into the same /templates folder:"
},
{
"code": null,
"e": 4442,
"s": 4389,
"text": "UI design is simple, and it is in /static/style.css:"
},
{
"code": null,
"e": 4774,
"s": 4442,
"text": "Important: mark folders /data and /static as Resources. In PyCharm for Linux, you can do it in File-->Settings-->Project Structure. The /templates folder mark as Templates. Nice to exclude some folders from Heroku upload and reduce application size(virtual environment folder). Don’t forget to add a .gitignorefile in your project:"
},
{
"code": null,
"e": 4847,
"s": 4774,
"text": "Since we use Flask for deployment, we need to point a template language:"
},
{
"code": null,
"e": 5175,
"s": 4847,
"text": "Finally, in the project’s directory, we may create our app.py file. First, we put there all needed imports and preprocessing pipeline functions. Then we create a Flask app instance (line 50) and add functionality with home and resulting pages. In the predict() function, we open a saved before model and predict the input text."
},
{
"code": null,
"e": 5286,
"s": 5175,
"text": "Run the app in main. Congratulations! Now you can check your app work on the localhost http://127.0.0.1:5000/."
},
{
"code": null,
"e": 5383,
"s": 5286,
"text": "For the beginning, let’s create a requirements.txt file. There are two convenient ways to do it:"
},
{
"code": null,
"e": 5707,
"s": 5383,
"text": "Via Pycharm IDE. Right-click on the project name→New →File→name the file requirements.txt. When you open an empty just created requirements.txt file, PyCharm IDE will offer you to write down all imports automatically. Very convenient way :)Via command line and 'pip freeze > requirements.txt’ inside your project directory."
},
{
"code": null,
"e": 5948,
"s": 5707,
"text": "Via Pycharm IDE. Right-click on the project name→New →File→name the file requirements.txt. When you open an empty just created requirements.txt file, PyCharm IDE will offer you to write down all imports automatically. Very convenient way :)"
},
{
"code": null,
"e": 6032,
"s": 5948,
"text": "Via command line and 'pip freeze > requirements.txt’ inside your project directory."
},
{
"code": null,
"e": 6083,
"s": 6032,
"text": "Don’t forget to change a PyTorch version for CPU :"
},
{
"code": null,
"e": 6174,
"s": 6083,
"text": "torch @ https://download.pytorch.org/whl/cpu/torch-1.6.0%2Bcpu-cp36-cp36m-linux_x86_64.whl"
},
{
"code": null,
"e": 6361,
"s": 6174,
"text": "I got a pretty long list of libraries in the current project: 63. For those who faced such a task for the first time, I want to notice: the last line in requirements.txt should be empty."
},
{
"code": null,
"e": 6588,
"s": 6361,
"text": "An important note about Heroku and NLTK library: if your app uses the NLTK library, you should create an additional nltk.txt file with inner imports. In our case, pattern.text.en use NLTK and nltk.txt should contain two lines:"
},
{
"code": null,
"e": 6605,
"s": 6588,
"text": "wordnetpros_cons"
},
{
"code": null,
"e": 6807,
"s": 6605,
"text": "runtime.txt we need for pointing which Python version to use on the server. You may create it in the same way as a requirements.txt file: via IDE or the command line. Inside it should contain one line:"
},
{
"code": null,
"e": 6821,
"s": 6807,
"text": "python-3.6.13"
},
{
"code": null,
"e": 6933,
"s": 6821,
"text": "Procfile. This file tells the Heroku what to do when the application is deployed and contains one line as well:"
},
{
"code": null,
"e": 6955,
"s": 6933,
"text": "web: gunicorn app:app"
},
{
"code": null,
"e": 7054,
"s": 6955,
"text": "Make sure that you have a Heroku CLI (and Git CLI). Since now there are only command-line actions:"
},
{
"code": null,
"e": 7102,
"s": 7054,
"text": "heroku loginheroku create your_application_name"
},
{
"code": null,
"e": 7158,
"s": 7102,
"text": "The following steps are almost the same as for Git CLI:"
},
{
"code": null,
"e": 7228,
"s": 7158,
"text": "git initgit add .git commit -m 'initial commit'git push heroku master"
},
{
"code": null,
"e": 7364,
"s": 7228,
"text": "That’s all, folks! You deployed a WEB app on the Heroku server. The access link looks like https://your_application_name.herokuapp.com/"
},
{
"code": null,
"e": 7605,
"s": 7364,
"text": "In this tutorial, you learned how to create an NLP pipeline, including Bert-based and additional feature engineering. You get familiar, as well, with how to create a demo WEB application with Flask and how to deploy it on the Heroku server."
},
{
"code": null,
"e": 7641,
"s": 7605,
"text": "Github repo. Code from the article."
},
{
"code": null,
"e": 7676,
"s": 7641,
"text": "My WEB app URL deployed on Heroku."
},
{
"code": null,
"e": 7705,
"s": 7676,
"text": "The article for inspiration."
}
] |
Predicting the Survival of Titanic Passengers | by Niklas Donges | Towards Data Science
|
In this blog-post, I will go through the whole process of creating a machine learning model on the famous Titanic dataset, which is used by many people all over the world. It provides information on the fate of passengers on the Titanic, summarized according to economic status (class), sex, age and survival.
I initially wrote this post on kaggle.com, as part of the “Titanic: Machine Learning from Disaster” Competition. In this challenge, we are asked to predict whether a passenger on the titanic would have been survived or not.
The RMS Titanic was a British passenger liner that sank in the North Atlantic Ocean in the early morning hours of 15 April 1912, after it collided with an iceberg during its maiden voyage from Southampton to New York City. There were an estimated 2,224 passengers and crew aboard the ship, and more than 1,500 died, making it one of the deadliest commercial peacetime maritime disasters in modern history. The RMS Titanic was the largest ship afloat at the time it entered service and was the second of three Olympic-class ocean liners operated by the White Star Line. The Titanic was built by the Harland and Wolff shipyard in Belfast. Thomas Andrews, her architect, died in the disaster.
# linear algebraimport numpy as np # data processingimport pandas as pd # data visualizationimport seaborn as sns%matplotlib inlinefrom matplotlib import pyplot as pltfrom matplotlib import style# Algorithmsfrom sklearn import linear_modelfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import Perceptronfrom sklearn.linear_model import SGDClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC, LinearSVCfrom sklearn.naive_bayes import GaussianNB
test_df = pd.read_csv("test.csv")train_df = pd.read_csv("train.csv")
train_df.info()
The training-set has 891 examples and 11 features + the target variable (survived). 2 of the features are floats, 5 are integers and 5 are objects. Below I have listed the features with a short description:
survival: Survival PassengerId: Unique Id of a passenger. pclass: Ticket class sex: Sex Age: Age in years sibsp: # of siblings / spouses aboard the Titanic parch: # of parents / children aboard the Titanic ticket: Ticket number fare: Passenger fare cabin: Cabin number embarked: Port of Embarkationtrain_df.describe()
Above we can see that 38% out of the training-set survived the Titanic. We can also see that the passenger ages range from 0.4 to 80. On top of that we can already detect some features, that contain missing values, like the ‘Age’ feature.
train_df.head(8)
From the table above, we can note a few things. First of all, that we need to convert a lot of features into numeric ones later on, so that the machine learning algorithms can process them. Furthermore, we can see that the features have widely different ranges, that we will need to convert into roughly the same scale. We can also spot some more features, that contain missing values (NaN = not a number), that wee need to deal with.
Let’s take a more detailed look at what data is actually missing:
total = train_df.isnull().sum().sort_values(ascending=False)percent_1 = train_df.isnull().sum()/train_df.isnull().count()*100percent_2 = (round(percent_1, 1)).sort_values(ascending=False)missing_data = pd.concat([total, percent_2], axis=1, keys=['Total', '%'])missing_data.head(5)
The Embarked feature has only 2 missing values, which can easily be filled. It will be much more tricky, to deal with the ‘Age’ feature, which has 177 missing values. The ‘Cabin’ feature needs further investigation, but it looks like that we might want to drop it from the dataset, since 77 % of it are missing.
train_df.columns.values
Above you can see the 11 features + the target variable (survived). What features could contribute to a high survival rate ?
To me it would make sense if everything except ‘PassengerId’, ‘Ticket’ and ‘Name’ would be correlated with a high survival rate.
1. Age and Sex:
survived = 'survived'not_survived = 'not survived'fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10, 4))women = train_df[train_df['Sex']=='female']men = train_df[train_df['Sex']=='male']ax = sns.distplot(women[women['Survived']==1].Age.dropna(), bins=18, label = survived, ax = axes[0], kde =False)ax = sns.distplot(women[women['Survived']==0].Age.dropna(), bins=40, label = not_survived, ax = axes[0], kde =False)ax.legend()ax.set_title('Female')ax = sns.distplot(men[men['Survived']==1].Age.dropna(), bins=18, label = survived, ax = axes[1], kde = False)ax = sns.distplot(men[men['Survived']==0].Age.dropna(), bins=40, label = not_survived, ax = axes[1], kde = False)ax.legend()_ = ax.set_title('Male')
You can see that men have a high probability of survival when they are between 18 and 30 years old, which is also a little bit true for women but not fully. For women the survival chances are higher between 14 and 40.
For men the probability of survival is very low between the age of 5 and 18, but that isn’t true for women. Another thing to note is that infants also have a little bit higher probability of survival.
Since there seem to be certain ages, which have increased odds of survival and because I want every feature to be roughly on the same scale, I will create age groups later on.
3. Embarked, Pclass and Sex:
FacetGrid = sns.FacetGrid(train_df, row='Embarked', size=4.5, aspect=1.6)FacetGrid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette=None, order=None, hue_order=None )FacetGrid.add_legend()
Embarked seems to be correlated with survival, depending on the gender.
Women on port Q and on port S have a higher chance of survival. The inverse is true, if they are at port C. Men have a high survival probability if they are on port C, but a low probability if they are on port Q or S.
Pclass also seems to be correlated with survival. We will generate another plot of it below.
4. Pclass:
sns.barplot(x='Pclass', y='Survived', data=train_df)
Here we see clearly, that Pclass is contributing to a persons chance of survival, especially if this person is in class 1. We will create another pclass plot below.
grid = sns.FacetGrid(train_df, col='Survived', row='Pclass', size=2.2, aspect=1.6)grid.map(plt.hist, 'Age', alpha=.5, bins=20)grid.add_legend();
The plot above confirms our assumption about pclass 1, but we can also spot a high probability that a person in pclass 3 will not survive.
5. SibSp and Parch:
SibSp and Parch would make more sense as a combined feature, that shows the total number of relatives, a person has on the Titanic. I will create it below and also a feature that sows if someone is not alone.
data = [train_df, test_df]for dataset in data: dataset['relatives'] = dataset['SibSp'] + dataset['Parch'] dataset.loc[dataset['relatives'] > 0, 'not_alone'] = 0 dataset.loc[dataset['relatives'] == 0, 'not_alone'] = 1 dataset['not_alone'] = dataset['not_alone'].astype(int)train_df['not_alone'].value_counts()
axes = sns.factorplot('relatives','Survived', data=train_df, aspect = 2.5, )
Here we can see that you had a high probabilty of survival with 1 to 3 realitves, but a lower one if you had less than 1 or more than 3 (except for some cases with 6 relatives).
First, I will drop ‘PassengerId’ from the train set, because it does not contribute to a persons survival probability. I will not drop it from the test set, since it is required there for the submission.
train_df = train_df.drop(['PassengerId'], axis=1)
Cabin:As a reminder, we have to deal with Cabin (687), Embarked (2) and Age (177). First I thought, we have to delete the ‘Cabin’ variable but then I found something interesting. A cabin number looks like ‘C123’ and the letter refers to the deck. Therefore we’re going to extract these and create a new feature, that contains a persons deck. Afterwords we will convert the feature into a numeric variable. The missing values will be converted to zero. In the picture below you can see the actual decks of the titanic, ranging from A to G.
import redeck = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}data = [train_df, test_df]for dataset in data: dataset['Cabin'] = dataset['Cabin'].fillna("U0") dataset['Deck'] = dataset['Cabin'].map(lambda x: re.compile("([a-zA-Z]+)").search(x).group()) dataset['Deck'] = dataset['Deck'].map(deck) dataset['Deck'] = dataset['Deck'].fillna(0) dataset['Deck'] = dataset['Deck'].astype(int)# we can now drop the cabin featuretrain_df = train_df.drop(['Cabin'], axis=1)test_df = test_df.drop(['Cabin'], axis=1)
Age:Now we can tackle the issue with the age features missing values. I will create an array that contains random numbers, which are computed based on the mean age value in regards to the standard deviation and is_null.
data = [train_df, test_df]for dataset in data: mean = train_df["Age"].mean() std = test_df["Age"].std() is_null = dataset["Age"].isnull().sum() # compute random numbers between the mean, std and is_null rand_age = np.random.randint(mean - std, mean + std, size = is_null) # fill NaN values in Age column with random values generated age_slice = dataset["Age"].copy() age_slice[np.isnan(age_slice)] = rand_age dataset["Age"] = age_slice dataset["Age"] = train_df["Age"].astype(int)train_df["Age"].isnull().sum()
Embarked:
Since the Embarked feature has only 2 missing values, we will just fill these with the most common one.
train_df['Embarked'].describe()
common_value = 'S'data = [train_df, test_df]for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value)
train_df.info()
Above you can see that ‘Fare’ is a float and we have to deal with 4 categorical features: Name, Sex, Ticket and Embarked. Lets investigate and transfrom one after another.
Fare:Converting “Fare” from float to int64, using the “astype()” function pandas provides:
data = [train_df, test_df]for dataset in data: dataset['Fare'] = dataset['Fare'].fillna(0) dataset['Fare'] = dataset['Fare'].astype(int)
Name:We will use the Name feature to extract the Titles from the Name, so that we can build a new feature out of that.
data = [train_df, test_df]titles = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5}for dataset in data: # extract titles dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False) # replace titles with a more common title or as Rare dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr',\ 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') # convert titles into numbers dataset['Title'] = dataset['Title'].map(titles) # filling NaN with 0, to get safe dataset['Title'] = dataset['Title'].fillna(0)train_df = train_df.drop(['Name'], axis=1)test_df = test_df.drop(['Name'], axis=1)
Sex:Convert ‘Sex’ feature into numeric.
genders = {"male": 0, "female": 1}data = [train_df, test_df]for dataset in data: dataset['Sex'] = dataset['Sex'].map(genders)
Ticket:
train_df['Ticket'].describe()
Since the Ticket attribute has 681 unique tickets, it will be a bit tricky to convert them into useful categories. So we will drop it from the dataset.
train_df = train_df.drop(['Ticket'], axis=1)test_df = test_df.drop(['Ticket'], axis=1)
Embarked:Convert ‘Embarked’ feature into numeric.
ports = {"S": 0, "C": 1, "Q": 2}data = [train_df, test_df]for dataset in data: dataset['Embarked'] = dataset['Embarked'].map(ports)
We will now create categories within the following features:
Age:Now we need to convert the ‘age’ feature. First we will convert it from float into integer. Then we will create the new ‘AgeGroup” variable, by categorizing every age into a group. Note that it is important to place attention on how you form these groups, since you don’t want for example that 80% of your data falls into group 1.
data = [train_df, test_df]for dataset in data: dataset['Age'] = dataset['Age'].astype(int) dataset.loc[ dataset['Age'] <= 11, 'Age'] = 0 dataset.loc[(dataset['Age'] > 11) & (dataset['Age'] <= 18), 'Age'] = 1 dataset.loc[(dataset['Age'] > 18) & (dataset['Age'] <= 22), 'Age'] = 2 dataset.loc[(dataset['Age'] > 22) & (dataset['Age'] <= 27), 'Age'] = 3 dataset.loc[(dataset['Age'] > 27) & (dataset['Age'] <= 33), 'Age'] = 4 dataset.loc[(dataset['Age'] > 33) & (dataset['Age'] <= 40), 'Age'] = 5 dataset.loc[(dataset['Age'] > 40) & (dataset['Age'] <= 66), 'Age'] = 6 dataset.loc[ dataset['Age'] > 66, 'Age'] = 6# let's see how it's distributed train_df['Age'].value_counts()
Fare:For the ‘Fare’ feature, we need to do the same as with the ‘Age’ feature. But it isn’t that easy, because if we cut the range of the fare values into a few equally big categories, 80% of the values would fall into the first category. Fortunately, we can use sklearn “qcut()” function, that we can use to see, how we can form the categories.
train_df.head(10)
data = [train_df, test_df]for dataset in data: dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0 dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1 dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2 dataset.loc[(dataset['Fare'] > 31) & (dataset['Fare'] <= 99), 'Fare'] = 3 dataset.loc[(dataset['Fare'] > 99) & (dataset['Fare'] <= 250), 'Fare'] = 4 dataset.loc[ dataset['Fare'] > 250, 'Fare'] = 5 dataset['Fare'] = dataset['Fare'].astype(int)
I will add two new features to the dataset, that I compute out of other features.
1. Age times Class
data = [train_df, test_df]for dataset in data: dataset['Age_Class']= dataset['Age']* dataset['Pclass']
2. Fare per Person
for dataset in data: dataset['Fare_Per_Person'] = dataset['Fare']/(dataset['relatives']+1) dataset['Fare_Per_Person'] = dataset['Fare_Per_Person'].astype(int)# Let's take a last look at the training set, before we start training the models.train_df.head(10)
Now we will train several Machine Learning models and compare their results. Note that because the dataset does not provide labels for their testing-set, we need to use the predictions on the training set to compare the algorithms with each other. Later on, we will use cross validation.
X_train = train_df.drop("Survived", axis=1)Y_train = train_df["Survived"]X_test = test_df.drop("PassengerId", axis=1).copy()
Stochastic Gradient Descent (SGD):
sgd = linear_model.SGDClassifier(max_iter=5, tol=None)sgd.fit(X_train, Y_train)Y_pred = sgd.predict(X_test)sgd.score(X_train, Y_train)acc_sgd = round(sgd.score(X_train, Y_train) * 100, 2)
Random Forest:
random_forest = RandomForestClassifier(n_estimators=100)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
Logistic Regression:
logreg = LogisticRegression()logreg.fit(X_train, Y_train)Y_pred = logreg.predict(X_test)acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
K Nearest Neighbor:
# KNN knn = KNeighborsClassifier(n_neighbors = 3) knn.fit(X_train, Y_train) Y_pred = knn.predict(X_test) acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
Gaussian Naive Bayes:
gaussian = GaussianNB() gaussian.fit(X_train, Y_train) Y_pred = gaussian.predict(X_test) acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
Perceptron:
perceptron = Perceptron(max_iter=5)perceptron.fit(X_train, Y_train)Y_pred = perceptron.predict(X_test)acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)
Linear Support Vector Machine:
linear_svc = LinearSVC()linear_svc.fit(X_train, Y_train)Y_pred = linear_svc.predict(X_test)acc_linear_svc = round(linear_svc.score(X_train, Y_train) * 100, 2)
Decision Tree
decision_tree = DecisionTreeClassifier() decision_tree.fit(X_train, Y_train) Y_pred = decision_tree.predict(X_test) acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
results = pd.DataFrame({ 'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron', 'Stochastic Gradient Decent', 'Decision Tree'], 'Score': [acc_linear_svc, acc_knn, acc_log, acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd, acc_decision_tree]})result_df = results.sort_values(by='Score', ascending=False)result_df = result_df.set_index('Score')result_df.head(9)
As we can see, the Random Forest classifier goes on the first place. But first, let us check, how random-forest performs, when we use cross validation.
K-Fold Cross Validation randomly splits the training data into K subsets called folds. Let’s image we would split our data into 4 folds (K = 4). Our random forest model would be trained and evaluated 4 times, using a different fold for evaluation everytime, while it would be trained on the remaining 3 folds.
The image below shows the process, using 4 folds (K = 4). Every row represents one training + evaluation process. In the first row, the model get’s trained on the first, second and third subset and evaluated on the fourth. In the second row, the model get’s trained on the second, third and fourth subset and evaluated on the first. K-Fold Cross Validation repeats this process till every fold acted once as an evaluation fold.
The result of our K-Fold Cross Validation example would be an array that contains 4 different scores. We then need to compute the mean and the standard deviation for these scores.
The code below perform K-Fold Cross Validation on our random forest model, using 10 folds (K = 10). Therefore it outputs an array with 10 different scores.
from sklearn.model_selection import cross_val_scorerf = RandomForestClassifier(n_estimators=100)scores = cross_val_score(rf, X_train, Y_train, cv=10, scoring = "accuracy")print("Scores:", scores)print("Mean:", scores.mean())print("Standard Deviation:", scores.std())
This looks much more realistic than before. Our model has a average accuracy of 82% with a standard deviation of 4 %. The standard deviation shows us, how precise the estimates are .
This means in our case that the accuracy of our model can differ + — 4%.
I think the accuracy is still really good and since random forest is an easy to use model, we will try to increase it’s performance even further in the following section.
Random Forest is a supervised learning algorithm. Like you can already see from it’s name, it creates a forest and makes it somehow random. The „forest“ it builds, is an ensemble of Decision Trees, most of the time trained with the “bagging” method. The general idea of the bagging method is that a combination of learning models increases the overall result.
To say it in simple words: Random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction.
One big advantage of random forest is, that it can be used for both classification and regression problems, which form the majority of current machine learning systems. With a few exceptions a random-forest classifier has all the hyperparameters of a decision-tree classifier and also all the hyperparameters of a bagging classifier, to control the ensemble itself.
The random-forest algorithm brings extra randomness into the model, when it is growing the trees. Instead of searching for the best feature while splitting a node, it searches for the best feature among a random subset of features. This process creates a wide diversity, which generally results in a better model. Therefore when you are growing a tree in random forest, only a random subset of the features is considered for splitting a node. You can even make trees more random, by using random thresholds on top of it, for each feature rather than searching for the best possible thresholds (like a normal decision tree does).
Below you can see how a random forest would look like with two trees:
Another great quality of random forest is that they make it very easy to measure the relative importance of each feature. Sklearn measure a features importance by looking at how much the treee nodes, that use that feature, reduce impurity on average (across all trees in the forest). It computes this score automaticall for each feature after training and scales the results so that the sum of all importances is equal to 1. We will acces this below:
importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(random_forest.feature_importances_,3)})importances = importances.sort_values('importance',ascending=False).set_index('feature')importances.head(15)
importances.plot.bar()
not_alone and Parch doesn’t play a significant role in our random forest classifiers prediction process. Because of that I will drop them from the dataset and train the classifier again. We could also remove more or less features, but this would need a more detailed investigation of the features effect on our model. But I think it’s just fine to remove only Alone and Parch.
train_df = train_df.drop("not_alone", axis=1)test_df = test_df.drop("not_alone", axis=1)train_df = train_df.drop("Parch", axis=1)test_df = test_df.drop("Parch", axis=1)
Training random forest again:
# Random Forestrandom_forest = RandomForestClassifier(n_estimators=100, oob_score = True)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)print(round(acc_random_forest,2,), "%")
92.82%
Our random forest model predicts as good as it did before. A general rule is that, the more features you have, the more likely your model will suffer from overfitting and vice versa. But I think our data looks fine for now and hasn't too much features.
There is also another way to evaluate a random-forest classifier, which is probably much more accurate than the score we used before. What I am talking about is the out-of-bag samples to estimate the generalization accuracy. I will not go into details here about how it works. Just note that out-of-bag estimate is as accurate as using a test set of the same size as the training set. Therefore, using the out-of-bag error estimate removes the need for a set aside test set.
print("oob score:", round(random_forest.oob_score_, 4)*100, "%")
oob score: 81.82 %
Now we can start tuning the hyperameters of random forest.
Below you can see the code of the hyperparamter tuning for the parameters criterion, min_samples_leaf, min_samples_split and n_estimators.
I put this code into a markdown cell and not into a code cell, because it takes a long time to run it. Directly underneeth it, I put a screenshot of the gridsearch's output.
param_grid = { "criterion" : ["gini", "entropy"], "min_samples_leaf" : [1, 5, 10, 25, 50, 70], "min_samples_split" : [2, 4, 10, 12, 16, 18, 25, 35], "n_estimators": [100, 400, 700, 1000, 1500]}from sklearn.model_selection import GridSearchCV, cross_val_scorerf = RandomForestClassifier(n_estimators=100, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)clf = GridSearchCV(estimator=rf, param_grid=param_grid, n_jobs=-1)clf.fit(X_train, Y_train)clf.bestparams
Test new Parameters:
# Random Forestrandom_forest = RandomForestClassifier(criterion = "gini", min_samples_leaf = 1, min_samples_split = 10, n_estimators=100, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)print("oob score:", round(random_forest.oob_score_, 4)*100, "%")
oob score: 83.05 %
Now that we have a proper model, we can start evaluating it’s performace in a more accurate way. Previously we only used accuracy and the oob score, which is just another form of accuracy. The problem is just, that it’s more complicated to evaluate a classification model than a regression model. We will talk about this in the following section.
from sklearn.model_selection import cross_val_predictfrom sklearn.metrics import confusion_matrixpredictions = cross_val_predict(random_forest, X_train, Y_train, cv=3)confusion_matrix(Y_train, predictions)
The first row is about the not-survived-predictions: 493 passengers were correctly classified as not survived (called true negatives) and 56 where wrongly classified as not survived (false positives).
The second row is about the survived-predictions: 93 passengers where wrongly classified as survived (false negatives) and 249 where correctly classified as survived (true positives).
A confusion matrix gives you a lot of information about how well your model does, but theres a way to get even more, like computing the classifiers precision.
from sklearn.metrics import precision_score, recall_scoreprint("Precision:", precision_score(Y_train, predictions))print("Recall:",recall_score(Y_train, predictions))
Precision: 0.801948051948Recall: 0.722222222222
Our model predicts 81% of the time, a passengers survival correctly (precision). The recall tells us that it predicted the survival of 73 % of the people who actually survived.
You can combine precision and recall into one score, which is called the F-score. The F-score is computed with the harmonic mean of precision and recall. Note that it assigns much more weight to low values. As a result of that, the classifier will only get a high F-score, if both recall and precision are high.
from sklearn.metrics import f1_scoref1_score(Y_train, predictions)
0.7599999999999
There we have it, a 77 % F-score. The score is not that high, because we have a recall of 73%. But unfortunately the F-score is not perfect, because it favors classifiers that have a similar precision and recall. This is a problem, because you sometimes want a high precision and sometimes a high recall. The thing is that an increasing precision, sometimes results in an decreasing recall and vice versa (depending on the threshold). This is called the precision/recall tradeoff. We will discuss this in the following section.
For each person the Random Forest algorithm has to classify, it computes a probability based on a function and it classifies the person as survived (when the score is bigger the than threshold) or as not survived (when the score is smaller than the threshold). That’s why the threshold plays an important part.
We will plot the precision and recall with the threshold using matplotlib:
from sklearn.metrics import precision_recall_curve# getting the probabilities of our predictionsy_scores = random_forest.predict_proba(X_train)y_scores = y_scores[:,1]precision, recall, threshold = precision_recall_curve(Y_train, y_scores)def plot_precision_and_recall(precision, recall, threshold): plt.plot(threshold, precision[:-1], "r-", label="precision", linewidth=5) plt.plot(threshold, recall[:-1], "b", label="recall", linewidth=5) plt.xlabel("threshold", fontsize=19) plt.legend(loc="upper right", fontsize=19) plt.ylim([0, 1])plt.figure(figsize=(14, 7))plot_precision_and_recall(precision, recall, threshold)plt.show()
Above you can clearly see that the recall is falling of rapidly at a precision of around 85%. Because of that you may want to select the precision/recall tradeoff before that — maybe at around 75 %.
You are now able to choose a threshold, that gives you the best precision/recall tradeoff for your current machine learning problem. If you want for example a precision of 80%, you can easily look at the plots and see that you would need a threshold of around 0.4. Then you could train a model with exactly that threshold and would get the desired accuracy.
Another way is to plot the precision and recall against each other:
def plot_precision_vs_recall(precision, recall): plt.plot(recall, precision, "g--", linewidth=2.5) plt.ylabel("recall", fontsize=19) plt.xlabel("precision", fontsize=19) plt.axis([0, 1.5, 0, 1.5])plt.figure(figsize=(14, 7))plot_precision_vs_recall(precision, recall)plt.show()
Another way to evaluate and compare your binary classifier is provided by the ROC AUC Curve. This curve plots the true positive rate (also called recall) against the false positive rate (ratio of incorrectly classified negative instances), instead of plotting the precision versus the recall.
from sklearn.metrics import roc_curve# compute true positive rate and false positive ratefalse_positive_rate, true_positive_rate, thresholds = roc_curve(Y_train, y_scores)# plotting them against each otherdef plot_roc_curve(false_positive_rate, true_positive_rate, label=None): plt.plot(false_positive_rate, true_positive_rate, linewidth=2, label=label) plt.plot([0, 1], [0, 1], 'r', linewidth=4) plt.axis([0, 1, 0, 1]) plt.xlabel('False Positive Rate (FPR)', fontsize=16) plt.ylabel('True Positive Rate (TPR)', fontsize=16)plt.figure(figsize=(14, 7))plot_roc_curve(false_positive_rate, true_positive_rate)plt.show()
The red line in the middel represents a purely random classifier (e.g a coin flip) and therefore your classifier should be as far away from it as possible. Our Random Forest model seems to do a good job.
Of course we also have a tradeoff here, because the classifier produces more false positives, the higher the true positive rate is.
The ROC AUC Score is the corresponding score to the ROC AUC Curve. It is simply computed by measuring the area under the curve, which is called AUC.
A classifiers that is 100% correct, would have a ROC AUC Score of 1 and a completely random classiffier would have a score of 0.5.
from sklearn.metrics import roc_auc_scorer_a_score = roc_auc_score(Y_train, y_scores)print("ROC-AUC-Score:", r_a_score)
ROC_AUC_SCORE: 0.945067587
Nice ! I think that score is good enough to submit the predictions for the test-set to the Kaggle leaderboard.
We started with the data exploration where we got a feeling for the dataset, checked about missing data and learned which features are important. During this process we used seaborn and matplotlib to do the visualizations. During the data preprocessing part, we computed missing values, converted features into numeric ones, grouped values into categories and created a few new features. Afterwards we started training 8 different machine learning models, picked one of them (random forest) and applied cross validation on it. Then we discussed how random forest works, took a look at the importance it assigns to the different features and tuned it’s performace through optimizing it’s hyperparameter values. Lastly, we looked at it’s confusion matrix and computed the models precision, recall and f-score.
Below you can see a before and after picture of the “train_df” dataframe:
Of course there is still room for improvement, like doing a more extensive feature engineering, by comparing and plotting the features against each other and identifying and removing the noisy features. Another thing that can improve the overall result on the kaggle leaderboard would be a more extensive hyperparameter tuning on several machine learning models. You could also do some ensemble learning.
|
[
{
"code": null,
"e": 482,
"s": 172,
"text": "In this blog-post, I will go through the whole process of creating a machine learning model on the famous Titanic dataset, which is used by many people all over the world. It provides information on the fate of passengers on the Titanic, summarized according to economic status (class), sex, age and survival."
},
{
"code": null,
"e": 706,
"s": 482,
"text": "I initially wrote this post on kaggle.com, as part of the “Titanic: Machine Learning from Disaster” Competition. In this challenge, we are asked to predict whether a passenger on the titanic would have been survived or not."
},
{
"code": null,
"e": 1396,
"s": 706,
"text": "The RMS Titanic was a British passenger liner that sank in the North Atlantic Ocean in the early morning hours of 15 April 1912, after it collided with an iceberg during its maiden voyage from Southampton to New York City. There were an estimated 2,224 passengers and crew aboard the ship, and more than 1,500 died, making it one of the deadliest commercial peacetime maritime disasters in modern history. The RMS Titanic was the largest ship afloat at the time it entered service and was the second of three Olympic-class ocean liners operated by the White Star Line. The Titanic was built by the Harland and Wolff shipyard in Belfast. Thomas Andrews, her architect, died in the disaster."
},
{
"code": null,
"e": 2004,
"s": 1396,
"text": "# linear algebraimport numpy as np # data processingimport pandas as pd # data visualizationimport seaborn as sns%matplotlib inlinefrom matplotlib import pyplot as pltfrom matplotlib import style# Algorithmsfrom sklearn import linear_modelfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import Perceptronfrom sklearn.linear_model import SGDClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC, LinearSVCfrom sklearn.naive_bayes import GaussianNB"
},
{
"code": null,
"e": 2073,
"s": 2004,
"text": "test_df = pd.read_csv(\"test.csv\")train_df = pd.read_csv(\"train.csv\")"
},
{
"code": null,
"e": 2089,
"s": 2073,
"text": "train_df.info()"
},
{
"code": null,
"e": 2296,
"s": 2089,
"text": "The training-set has 891 examples and 11 features + the target variable (survived). 2 of the features are floats, 5 are integers and 5 are objects. Below I have listed the features with a short description:"
},
{
"code": null,
"e": 2676,
"s": 2296,
"text": "survival: Survival PassengerId: Unique Id of a passenger. pclass: Ticket class sex: Sex Age: Age in years sibsp: # of siblings / spouses aboard the Titanic parch: # of parents / children aboard the Titanic ticket: Ticket number fare: Passenger fare cabin: Cabin number embarked: Port of Embarkationtrain_df.describe()"
},
{
"code": null,
"e": 2915,
"s": 2676,
"text": "Above we can see that 38% out of the training-set survived the Titanic. We can also see that the passenger ages range from 0.4 to 80. On top of that we can already detect some features, that contain missing values, like the ‘Age’ feature."
},
{
"code": null,
"e": 2932,
"s": 2915,
"text": "train_df.head(8)"
},
{
"code": null,
"e": 3367,
"s": 2932,
"text": "From the table above, we can note a few things. First of all, that we need to convert a lot of features into numeric ones later on, so that the machine learning algorithms can process them. Furthermore, we can see that the features have widely different ranges, that we will need to convert into roughly the same scale. We can also spot some more features, that contain missing values (NaN = not a number), that wee need to deal with."
},
{
"code": null,
"e": 3433,
"s": 3367,
"text": "Let’s take a more detailed look at what data is actually missing:"
},
{
"code": null,
"e": 3714,
"s": 3433,
"text": "total = train_df.isnull().sum().sort_values(ascending=False)percent_1 = train_df.isnull().sum()/train_df.isnull().count()*100percent_2 = (round(percent_1, 1)).sort_values(ascending=False)missing_data = pd.concat([total, percent_2], axis=1, keys=['Total', '%'])missing_data.head(5)"
},
{
"code": null,
"e": 4026,
"s": 3714,
"text": "The Embarked feature has only 2 missing values, which can easily be filled. It will be much more tricky, to deal with the ‘Age’ feature, which has 177 missing values. The ‘Cabin’ feature needs further investigation, but it looks like that we might want to drop it from the dataset, since 77 % of it are missing."
},
{
"code": null,
"e": 4050,
"s": 4026,
"text": "train_df.columns.values"
},
{
"code": null,
"e": 4175,
"s": 4050,
"text": "Above you can see the 11 features + the target variable (survived). What features could contribute to a high survival rate ?"
},
{
"code": null,
"e": 4304,
"s": 4175,
"text": "To me it would make sense if everything except ‘PassengerId’, ‘Ticket’ and ‘Name’ would be correlated with a high survival rate."
},
{
"code": null,
"e": 4320,
"s": 4304,
"text": "1. Age and Sex:"
},
{
"code": null,
"e": 5029,
"s": 4320,
"text": "survived = 'survived'not_survived = 'not survived'fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10, 4))women = train_df[train_df['Sex']=='female']men = train_df[train_df['Sex']=='male']ax = sns.distplot(women[women['Survived']==1].Age.dropna(), bins=18, label = survived, ax = axes[0], kde =False)ax = sns.distplot(women[women['Survived']==0].Age.dropna(), bins=40, label = not_survived, ax = axes[0], kde =False)ax.legend()ax.set_title('Female')ax = sns.distplot(men[men['Survived']==1].Age.dropna(), bins=18, label = survived, ax = axes[1], kde = False)ax = sns.distplot(men[men['Survived']==0].Age.dropna(), bins=40, label = not_survived, ax = axes[1], kde = False)ax.legend()_ = ax.set_title('Male')"
},
{
"code": null,
"e": 5247,
"s": 5029,
"text": "You can see that men have a high probability of survival when they are between 18 and 30 years old, which is also a little bit true for women but not fully. For women the survival chances are higher between 14 and 40."
},
{
"code": null,
"e": 5448,
"s": 5247,
"text": "For men the probability of survival is very low between the age of 5 and 18, but that isn’t true for women. Another thing to note is that infants also have a little bit higher probability of survival."
},
{
"code": null,
"e": 5624,
"s": 5448,
"text": "Since there seem to be certain ages, which have increased odds of survival and because I want every feature to be roughly on the same scale, I will create age groups later on."
},
{
"code": null,
"e": 5653,
"s": 5624,
"text": "3. Embarked, Pclass and Sex:"
},
{
"code": null,
"e": 5850,
"s": 5653,
"text": "FacetGrid = sns.FacetGrid(train_df, row='Embarked', size=4.5, aspect=1.6)FacetGrid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette=None, order=None, hue_order=None )FacetGrid.add_legend()"
},
{
"code": null,
"e": 5922,
"s": 5850,
"text": "Embarked seems to be correlated with survival, depending on the gender."
},
{
"code": null,
"e": 6140,
"s": 5922,
"text": "Women on port Q and on port S have a higher chance of survival. The inverse is true, if they are at port C. Men have a high survival probability if they are on port C, but a low probability if they are on port Q or S."
},
{
"code": null,
"e": 6233,
"s": 6140,
"text": "Pclass also seems to be correlated with survival. We will generate another plot of it below."
},
{
"code": null,
"e": 6244,
"s": 6233,
"text": "4. Pclass:"
},
{
"code": null,
"e": 6297,
"s": 6244,
"text": "sns.barplot(x='Pclass', y='Survived', data=train_df)"
},
{
"code": null,
"e": 6462,
"s": 6297,
"text": "Here we see clearly, that Pclass is contributing to a persons chance of survival, especially if this person is in class 1. We will create another pclass plot below."
},
{
"code": null,
"e": 6607,
"s": 6462,
"text": "grid = sns.FacetGrid(train_df, col='Survived', row='Pclass', size=2.2, aspect=1.6)grid.map(plt.hist, 'Age', alpha=.5, bins=20)grid.add_legend();"
},
{
"code": null,
"e": 6746,
"s": 6607,
"text": "The plot above confirms our assumption about pclass 1, but we can also spot a high probability that a person in pclass 3 will not survive."
},
{
"code": null,
"e": 6766,
"s": 6746,
"text": "5. SibSp and Parch:"
},
{
"code": null,
"e": 6975,
"s": 6766,
"text": "SibSp and Parch would make more sense as a combined feature, that shows the total number of relatives, a person has on the Titanic. I will create it below and also a feature that sows if someone is not alone."
},
{
"code": null,
"e": 7296,
"s": 6975,
"text": "data = [train_df, test_df]for dataset in data: dataset['relatives'] = dataset['SibSp'] + dataset['Parch'] dataset.loc[dataset['relatives'] > 0, 'not_alone'] = 0 dataset.loc[dataset['relatives'] == 0, 'not_alone'] = 1 dataset['not_alone'] = dataset['not_alone'].astype(int)train_df['not_alone'].value_counts()"
},
{
"code": null,
"e": 7395,
"s": 7296,
"text": "axes = sns.factorplot('relatives','Survived', data=train_df, aspect = 2.5, )"
},
{
"code": null,
"e": 7573,
"s": 7395,
"text": "Here we can see that you had a high probabilty of survival with 1 to 3 realitves, but a lower one if you had less than 1 or more than 3 (except for some cases with 6 relatives)."
},
{
"code": null,
"e": 7777,
"s": 7573,
"text": "First, I will drop ‘PassengerId’ from the train set, because it does not contribute to a persons survival probability. I will not drop it from the test set, since it is required there for the submission."
},
{
"code": null,
"e": 7827,
"s": 7777,
"text": "train_df = train_df.drop(['PassengerId'], axis=1)"
},
{
"code": null,
"e": 8366,
"s": 7827,
"text": "Cabin:As a reminder, we have to deal with Cabin (687), Embarked (2) and Age (177). First I thought, we have to delete the ‘Cabin’ variable but then I found something interesting. A cabin number looks like ‘C123’ and the letter refers to the deck. Therefore we’re going to extract these and create a new feature, that contains a persons deck. Afterwords we will convert the feature into a numeric variable. The missing values will be converted to zero. In the picture below you can see the actual decks of the titanic, ranging from A to G."
},
{
"code": null,
"e": 8904,
"s": 8366,
"text": "import redeck = {\"A\": 1, \"B\": 2, \"C\": 3, \"D\": 4, \"E\": 5, \"F\": 6, \"G\": 7, \"U\": 8}data = [train_df, test_df]for dataset in data: dataset['Cabin'] = dataset['Cabin'].fillna(\"U0\") dataset['Deck'] = dataset['Cabin'].map(lambda x: re.compile(\"([a-zA-Z]+)\").search(x).group()) dataset['Deck'] = dataset['Deck'].map(deck) dataset['Deck'] = dataset['Deck'].fillna(0) dataset['Deck'] = dataset['Deck'].astype(int)# we can now drop the cabin featuretrain_df = train_df.drop(['Cabin'], axis=1)test_df = test_df.drop(['Cabin'], axis=1)"
},
{
"code": null,
"e": 9124,
"s": 8904,
"text": "Age:Now we can tackle the issue with the age features missing values. I will create an array that contains random numbers, which are computed based on the mean age value in regards to the standard deviation and is_null."
},
{
"code": null,
"e": 9665,
"s": 9124,
"text": "data = [train_df, test_df]for dataset in data: mean = train_df[\"Age\"].mean() std = test_df[\"Age\"].std() is_null = dataset[\"Age\"].isnull().sum() # compute random numbers between the mean, std and is_null rand_age = np.random.randint(mean - std, mean + std, size = is_null) # fill NaN values in Age column with random values generated age_slice = dataset[\"Age\"].copy() age_slice[np.isnan(age_slice)] = rand_age dataset[\"Age\"] = age_slice dataset[\"Age\"] = train_df[\"Age\"].astype(int)train_df[\"Age\"].isnull().sum()"
},
{
"code": null,
"e": 9675,
"s": 9665,
"text": "Embarked:"
},
{
"code": null,
"e": 9779,
"s": 9675,
"text": "Since the Embarked feature has only 2 missing values, we will just fill these with the most common one."
},
{
"code": null,
"e": 9811,
"s": 9779,
"text": "train_df['Embarked'].describe()"
},
{
"code": null,
"e": 9942,
"s": 9811,
"text": "common_value = 'S'data = [train_df, test_df]for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value)"
},
{
"code": null,
"e": 9958,
"s": 9942,
"text": "train_df.info()"
},
{
"code": null,
"e": 10130,
"s": 9958,
"text": "Above you can see that ‘Fare’ is a float and we have to deal with 4 categorical features: Name, Sex, Ticket and Embarked. Lets investigate and transfrom one after another."
},
{
"code": null,
"e": 10221,
"s": 10130,
"text": "Fare:Converting “Fare” from float to int64, using the “astype()” function pandas provides:"
},
{
"code": null,
"e": 10364,
"s": 10221,
"text": "data = [train_df, test_df]for dataset in data: dataset['Fare'] = dataset['Fare'].fillna(0) dataset['Fare'] = dataset['Fare'].astype(int)"
},
{
"code": null,
"e": 10483,
"s": 10364,
"text": "Name:We will use the Name feature to extract the Titles from the Name, so that we can build a new feature out of that."
},
{
"code": null,
"e": 11375,
"s": 10483,
"text": "data = [train_df, test_df]titles = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}for dataset in data: # extract titles dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\\.', expand=False) # replace titles with a more common title or as Rare dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr',\\ 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') # convert titles into numbers dataset['Title'] = dataset['Title'].map(titles) # filling NaN with 0, to get safe dataset['Title'] = dataset['Title'].fillna(0)train_df = train_df.drop(['Name'], axis=1)test_df = test_df.drop(['Name'], axis=1)"
},
{
"code": null,
"e": 11415,
"s": 11375,
"text": "Sex:Convert ‘Sex’ feature into numeric."
},
{
"code": null,
"e": 11544,
"s": 11415,
"text": "genders = {\"male\": 0, \"female\": 1}data = [train_df, test_df]for dataset in data: dataset['Sex'] = dataset['Sex'].map(genders)"
},
{
"code": null,
"e": 11552,
"s": 11544,
"text": "Ticket:"
},
{
"code": null,
"e": 11582,
"s": 11552,
"text": "train_df['Ticket'].describe()"
},
{
"code": null,
"e": 11734,
"s": 11582,
"text": "Since the Ticket attribute has 681 unique tickets, it will be a bit tricky to convert them into useful categories. So we will drop it from the dataset."
},
{
"code": null,
"e": 11821,
"s": 11734,
"text": "train_df = train_df.drop(['Ticket'], axis=1)test_df = test_df.drop(['Ticket'], axis=1)"
},
{
"code": null,
"e": 11871,
"s": 11821,
"text": "Embarked:Convert ‘Embarked’ feature into numeric."
},
{
"code": null,
"e": 12006,
"s": 11871,
"text": "ports = {\"S\": 0, \"C\": 1, \"Q\": 2}data = [train_df, test_df]for dataset in data: dataset['Embarked'] = dataset['Embarked'].map(ports)"
},
{
"code": null,
"e": 12067,
"s": 12006,
"text": "We will now create categories within the following features:"
},
{
"code": null,
"e": 12402,
"s": 12067,
"text": "Age:Now we need to convert the ‘age’ feature. First we will convert it from float into integer. Then we will create the new ‘AgeGroup” variable, by categorizing every age into a group. Note that it is important to place attention on how you form these groups, since you don’t want for example that 80% of your data falls into group 1."
},
{
"code": null,
"e": 13100,
"s": 12402,
"text": "data = [train_df, test_df]for dataset in data: dataset['Age'] = dataset['Age'].astype(int) dataset.loc[ dataset['Age'] <= 11, 'Age'] = 0 dataset.loc[(dataset['Age'] > 11) & (dataset['Age'] <= 18), 'Age'] = 1 dataset.loc[(dataset['Age'] > 18) & (dataset['Age'] <= 22), 'Age'] = 2 dataset.loc[(dataset['Age'] > 22) & (dataset['Age'] <= 27), 'Age'] = 3 dataset.loc[(dataset['Age'] > 27) & (dataset['Age'] <= 33), 'Age'] = 4 dataset.loc[(dataset['Age'] > 33) & (dataset['Age'] <= 40), 'Age'] = 5 dataset.loc[(dataset['Age'] > 40) & (dataset['Age'] <= 66), 'Age'] = 6 dataset.loc[ dataset['Age'] > 66, 'Age'] = 6# let's see how it's distributed train_df['Age'].value_counts()"
},
{
"code": null,
"e": 13446,
"s": 13100,
"text": "Fare:For the ‘Fare’ feature, we need to do the same as with the ‘Age’ feature. But it isn’t that easy, because if we cut the range of the fare values into a few equally big categories, 80% of the values would fall into the first category. Fortunately, we can use sklearn “qcut()” function, that we can use to see, how we can form the categories."
},
{
"code": null,
"e": 13464,
"s": 13446,
"text": "train_df.head(10)"
},
{
"code": null,
"e": 13989,
"s": 13464,
"text": "data = [train_df, test_df]for dataset in data: dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0 dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1 dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2 dataset.loc[(dataset['Fare'] > 31) & (dataset['Fare'] <= 99), 'Fare'] = 3 dataset.loc[(dataset['Fare'] > 99) & (dataset['Fare'] <= 250), 'Fare'] = 4 dataset.loc[ dataset['Fare'] > 250, 'Fare'] = 5 dataset['Fare'] = dataset['Fare'].astype(int)"
},
{
"code": null,
"e": 14071,
"s": 13989,
"text": "I will add two new features to the dataset, that I compute out of other features."
},
{
"code": null,
"e": 14090,
"s": 14071,
"text": "1. Age times Class"
},
{
"code": null,
"e": 14196,
"s": 14090,
"text": "data = [train_df, test_df]for dataset in data: dataset['Age_Class']= dataset['Age']* dataset['Pclass']"
},
{
"code": null,
"e": 14215,
"s": 14196,
"text": "2. Fare per Person"
},
{
"code": null,
"e": 14479,
"s": 14215,
"text": "for dataset in data: dataset['Fare_Per_Person'] = dataset['Fare']/(dataset['relatives']+1) dataset['Fare_Per_Person'] = dataset['Fare_Per_Person'].astype(int)# Let's take a last look at the training set, before we start training the models.train_df.head(10)"
},
{
"code": null,
"e": 14767,
"s": 14479,
"text": "Now we will train several Machine Learning models and compare their results. Note that because the dataset does not provide labels for their testing-set, we need to use the predictions on the training set to compare the algorithms with each other. Later on, we will use cross validation."
},
{
"code": null,
"e": 14893,
"s": 14767,
"text": "X_train = train_df.drop(\"Survived\", axis=1)Y_train = train_df[\"Survived\"]X_test = test_df.drop(\"PassengerId\", axis=1).copy()"
},
{
"code": null,
"e": 14928,
"s": 14893,
"text": "Stochastic Gradient Descent (SGD):"
},
{
"code": null,
"e": 15116,
"s": 14928,
"text": "sgd = linear_model.SGDClassifier(max_iter=5, tol=None)sgd.fit(X_train, Y_train)Y_pred = sgd.predict(X_test)sgd.score(X_train, Y_train)acc_sgd = round(sgd.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 15131,
"s": 15116,
"text": "Random Forest:"
},
{
"code": null,
"e": 15377,
"s": 15131,
"text": "random_forest = RandomForestClassifier(n_estimators=100)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 15398,
"s": 15377,
"text": "Logistic Regression:"
},
{
"code": null,
"e": 15543,
"s": 15398,
"text": "logreg = LogisticRegression()logreg.fit(X_train, Y_train)Y_pred = logreg.predict(X_test)acc_log = round(logreg.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 15563,
"s": 15543,
"text": "K Nearest Neighbor:"
},
{
"code": null,
"e": 15724,
"s": 15563,
"text": "# KNN knn = KNeighborsClassifier(n_neighbors = 3) knn.fit(X_train, Y_train) Y_pred = knn.predict(X_test) acc_knn = round(knn.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 15746,
"s": 15724,
"text": "Gaussian Naive Bayes:"
},
{
"code": null,
"e": 15901,
"s": 15746,
"text": "gaussian = GaussianNB() gaussian.fit(X_train, Y_train) Y_pred = gaussian.predict(X_test) acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 15913,
"s": 15901,
"text": "Perceptron:"
},
{
"code": null,
"e": 16083,
"s": 15913,
"text": "perceptron = Perceptron(max_iter=5)perceptron.fit(X_train, Y_train)Y_pred = perceptron.predict(X_test)acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 16114,
"s": 16083,
"text": "Linear Support Vector Machine:"
},
{
"code": null,
"e": 16273,
"s": 16114,
"text": "linear_svc = LinearSVC()linear_svc.fit(X_train, Y_train)Y_pred = linear_svc.predict(X_test)acc_linear_svc = round(linear_svc.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 16287,
"s": 16273,
"text": "Decision Tree"
},
{
"code": null,
"e": 16479,
"s": 16287,
"text": "decision_tree = DecisionTreeClassifier() decision_tree.fit(X_train, Y_train) Y_pred = decision_tree.predict(X_test) acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)"
},
{
"code": null,
"e": 16981,
"s": 16479,
"text": "results = pd.DataFrame({ 'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron', 'Stochastic Gradient Decent', 'Decision Tree'], 'Score': [acc_linear_svc, acc_knn, acc_log, acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd, acc_decision_tree]})result_df = results.sort_values(by='Score', ascending=False)result_df = result_df.set_index('Score')result_df.head(9)"
},
{
"code": null,
"e": 17133,
"s": 16981,
"text": "As we can see, the Random Forest classifier goes on the first place. But first, let us check, how random-forest performs, when we use cross validation."
},
{
"code": null,
"e": 17443,
"s": 17133,
"text": "K-Fold Cross Validation randomly splits the training data into K subsets called folds. Let’s image we would split our data into 4 folds (K = 4). Our random forest model would be trained and evaluated 4 times, using a different fold for evaluation everytime, while it would be trained on the remaining 3 folds."
},
{
"code": null,
"e": 17871,
"s": 17443,
"text": "The image below shows the process, using 4 folds (K = 4). Every row represents one training + evaluation process. In the first row, the model get’s trained on the first, second and third subset and evaluated on the fourth. In the second row, the model get’s trained on the second, third and fourth subset and evaluated on the first. K-Fold Cross Validation repeats this process till every fold acted once as an evaluation fold."
},
{
"code": null,
"e": 18051,
"s": 17871,
"text": "The result of our K-Fold Cross Validation example would be an array that contains 4 different scores. We then need to compute the mean and the standard deviation for these scores."
},
{
"code": null,
"e": 18207,
"s": 18051,
"text": "The code below perform K-Fold Cross Validation on our random forest model, using 10 folds (K = 10). Therefore it outputs an array with 10 different scores."
},
{
"code": null,
"e": 18474,
"s": 18207,
"text": "from sklearn.model_selection import cross_val_scorerf = RandomForestClassifier(n_estimators=100)scores = cross_val_score(rf, X_train, Y_train, cv=10, scoring = \"accuracy\")print(\"Scores:\", scores)print(\"Mean:\", scores.mean())print(\"Standard Deviation:\", scores.std())"
},
{
"code": null,
"e": 18657,
"s": 18474,
"text": "This looks much more realistic than before. Our model has a average accuracy of 82% with a standard deviation of 4 %. The standard deviation shows us, how precise the estimates are ."
},
{
"code": null,
"e": 18730,
"s": 18657,
"text": "This means in our case that the accuracy of our model can differ + — 4%."
},
{
"code": null,
"e": 18901,
"s": 18730,
"text": "I think the accuracy is still really good and since random forest is an easy to use model, we will try to increase it’s performance even further in the following section."
},
{
"code": null,
"e": 19261,
"s": 18901,
"text": "Random Forest is a supervised learning algorithm. Like you can already see from it’s name, it creates a forest and makes it somehow random. The „forest“ it builds, is an ensemble of Decision Trees, most of the time trained with the “bagging” method. The general idea of the bagging method is that a combination of learning models increases the overall result."
},
{
"code": null,
"e": 19404,
"s": 19261,
"text": "To say it in simple words: Random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction."
},
{
"code": null,
"e": 19770,
"s": 19404,
"text": "One big advantage of random forest is, that it can be used for both classification and regression problems, which form the majority of current machine learning systems. With a few exceptions a random-forest classifier has all the hyperparameters of a decision-tree classifier and also all the hyperparameters of a bagging classifier, to control the ensemble itself."
},
{
"code": null,
"e": 20399,
"s": 19770,
"text": "The random-forest algorithm brings extra randomness into the model, when it is growing the trees. Instead of searching for the best feature while splitting a node, it searches for the best feature among a random subset of features. This process creates a wide diversity, which generally results in a better model. Therefore when you are growing a tree in random forest, only a random subset of the features is considered for splitting a node. You can even make trees more random, by using random thresholds on top of it, for each feature rather than searching for the best possible thresholds (like a normal decision tree does)."
},
{
"code": null,
"e": 20469,
"s": 20399,
"text": "Below you can see how a random forest would look like with two trees:"
},
{
"code": null,
"e": 20920,
"s": 20469,
"text": "Another great quality of random forest is that they make it very easy to measure the relative importance of each feature. Sklearn measure a features importance by looking at how much the treee nodes, that use that feature, reduce impurity on average (across all trees in the forest). It computes this score automaticall for each feature after training and scales the results so that the sum of all importances is equal to 1. We will acces this below:"
},
{
"code": null,
"e": 21144,
"s": 20920,
"text": "importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(random_forest.feature_importances_,3)})importances = importances.sort_values('importance',ascending=False).set_index('feature')importances.head(15)"
},
{
"code": null,
"e": 21167,
"s": 21144,
"text": "importances.plot.bar()"
},
{
"code": null,
"e": 21544,
"s": 21167,
"text": "not_alone and Parch doesn’t play a significant role in our random forest classifiers prediction process. Because of that I will drop them from the dataset and train the classifier again. We could also remove more or less features, but this would need a more detailed investigation of the features effect on our model. But I think it’s just fine to remove only Alone and Parch."
},
{
"code": null,
"e": 21717,
"s": 21544,
"text": "train_df = train_df.drop(\"not_alone\", axis=1)test_df = test_df.drop(\"not_alone\", axis=1)train_df = train_df.drop(\"Parch\", axis=1)test_df = test_df.drop(\"Parch\", axis=1)"
},
{
"code": null,
"e": 21747,
"s": 21717,
"text": "Training random forest again:"
},
{
"code": null,
"e": 22065,
"s": 21747,
"text": "# Random Forestrandom_forest = RandomForestClassifier(n_estimators=100, oob_score = True)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)print(round(acc_random_forest,2,), \"%\")"
},
{
"code": null,
"e": 22072,
"s": 22065,
"text": "92.82%"
},
{
"code": null,
"e": 22325,
"s": 22072,
"text": "Our random forest model predicts as good as it did before. A general rule is that, the more features you have, the more likely your model will suffer from overfitting and vice versa. But I think our data looks fine for now and hasn't too much features."
},
{
"code": null,
"e": 22800,
"s": 22325,
"text": "There is also another way to evaluate a random-forest classifier, which is probably much more accurate than the score we used before. What I am talking about is the out-of-bag samples to estimate the generalization accuracy. I will not go into details here about how it works. Just note that out-of-bag estimate is as accurate as using a test set of the same size as the training set. Therefore, using the out-of-bag error estimate removes the need for a set aside test set."
},
{
"code": null,
"e": 22865,
"s": 22800,
"text": "print(\"oob score:\", round(random_forest.oob_score_, 4)*100, \"%\")"
},
{
"code": null,
"e": 22884,
"s": 22865,
"text": "oob score: 81.82 %"
},
{
"code": null,
"e": 22943,
"s": 22884,
"text": "Now we can start tuning the hyperameters of random forest."
},
{
"code": null,
"e": 23082,
"s": 22943,
"text": "Below you can see the code of the hyperparamter tuning for the parameters criterion, min_samples_leaf, min_samples_split and n_estimators."
},
{
"code": null,
"e": 23256,
"s": 23082,
"text": "I put this code into a markdown cell and not into a code cell, because it takes a long time to run it. Directly underneeth it, I put a screenshot of the gridsearch's output."
},
{
"code": null,
"e": 23729,
"s": 23256,
"text": "param_grid = { \"criterion\" : [\"gini\", \"entropy\"], \"min_samples_leaf\" : [1, 5, 10, 25, 50, 70], \"min_samples_split\" : [2, 4, 10, 12, 16, 18, 25, 35], \"n_estimators\": [100, 400, 700, 1000, 1500]}from sklearn.model_selection import GridSearchCV, cross_val_scorerf = RandomForestClassifier(n_estimators=100, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)clf = GridSearchCV(estimator=rf, param_grid=param_grid, n_jobs=-1)clf.fit(X_train, Y_train)clf.bestparams"
},
{
"code": null,
"e": 23750,
"s": 23729,
"text": "Test new Parameters:"
},
{
"code": null,
"e": 24407,
"s": 23750,
"text": "# Random Forestrandom_forest = RandomForestClassifier(criterion = \"gini\", min_samples_leaf = 1, min_samples_split = 10, n_estimators=100, max_features='auto', oob_score=True, random_state=1, n_jobs=-1)random_forest.fit(X_train, Y_train)Y_prediction = random_forest.predict(X_test)random_forest.score(X_train, Y_train)print(\"oob score:\", round(random_forest.oob_score_, 4)*100, \"%\")"
},
{
"code": null,
"e": 24426,
"s": 24407,
"text": "oob score: 83.05 %"
},
{
"code": null,
"e": 24773,
"s": 24426,
"text": "Now that we have a proper model, we can start evaluating it’s performace in a more accurate way. Previously we only used accuracy and the oob score, which is just another form of accuracy. The problem is just, that it’s more complicated to evaluate a classification model than a regression model. We will talk about this in the following section."
},
{
"code": null,
"e": 24979,
"s": 24773,
"text": "from sklearn.model_selection import cross_val_predictfrom sklearn.metrics import confusion_matrixpredictions = cross_val_predict(random_forest, X_train, Y_train, cv=3)confusion_matrix(Y_train, predictions)"
},
{
"code": null,
"e": 25180,
"s": 24979,
"text": "The first row is about the not-survived-predictions: 493 passengers were correctly classified as not survived (called true negatives) and 56 where wrongly classified as not survived (false positives)."
},
{
"code": null,
"e": 25364,
"s": 25180,
"text": "The second row is about the survived-predictions: 93 passengers where wrongly classified as survived (false negatives) and 249 where correctly classified as survived (true positives)."
},
{
"code": null,
"e": 25523,
"s": 25364,
"text": "A confusion matrix gives you a lot of information about how well your model does, but theres a way to get even more, like computing the classifiers precision."
},
{
"code": null,
"e": 25690,
"s": 25523,
"text": "from sklearn.metrics import precision_score, recall_scoreprint(\"Precision:\", precision_score(Y_train, predictions))print(\"Recall:\",recall_score(Y_train, predictions))"
},
{
"code": null,
"e": 25738,
"s": 25690,
"text": "Precision: 0.801948051948Recall: 0.722222222222"
},
{
"code": null,
"e": 25915,
"s": 25738,
"text": "Our model predicts 81% of the time, a passengers survival correctly (precision). The recall tells us that it predicted the survival of 73 % of the people who actually survived."
},
{
"code": null,
"e": 26227,
"s": 25915,
"text": "You can combine precision and recall into one score, which is called the F-score. The F-score is computed with the harmonic mean of precision and recall. Note that it assigns much more weight to low values. As a result of that, the classifier will only get a high F-score, if both recall and precision are high."
},
{
"code": null,
"e": 26294,
"s": 26227,
"text": "from sklearn.metrics import f1_scoref1_score(Y_train, predictions)"
},
{
"code": null,
"e": 26310,
"s": 26294,
"text": "0.7599999999999"
},
{
"code": null,
"e": 26838,
"s": 26310,
"text": "There we have it, a 77 % F-score. The score is not that high, because we have a recall of 73%. But unfortunately the F-score is not perfect, because it favors classifiers that have a similar precision and recall. This is a problem, because you sometimes want a high precision and sometimes a high recall. The thing is that an increasing precision, sometimes results in an decreasing recall and vice versa (depending on the threshold). This is called the precision/recall tradeoff. We will discuss this in the following section."
},
{
"code": null,
"e": 27149,
"s": 26838,
"text": "For each person the Random Forest algorithm has to classify, it computes a probability based on a function and it classifies the person as survived (when the score is bigger the than threshold) or as not survived (when the score is smaller than the threshold). That’s why the threshold plays an important part."
},
{
"code": null,
"e": 27224,
"s": 27149,
"text": "We will plot the precision and recall with the threshold using matplotlib:"
},
{
"code": null,
"e": 27869,
"s": 27224,
"text": "from sklearn.metrics import precision_recall_curve# getting the probabilities of our predictionsy_scores = random_forest.predict_proba(X_train)y_scores = y_scores[:,1]precision, recall, threshold = precision_recall_curve(Y_train, y_scores)def plot_precision_and_recall(precision, recall, threshold): plt.plot(threshold, precision[:-1], \"r-\", label=\"precision\", linewidth=5) plt.plot(threshold, recall[:-1], \"b\", label=\"recall\", linewidth=5) plt.xlabel(\"threshold\", fontsize=19) plt.legend(loc=\"upper right\", fontsize=19) plt.ylim([0, 1])plt.figure(figsize=(14, 7))plot_precision_and_recall(precision, recall, threshold)plt.show()"
},
{
"code": null,
"e": 28068,
"s": 27869,
"text": "Above you can clearly see that the recall is falling of rapidly at a precision of around 85%. Because of that you may want to select the precision/recall tradeoff before that — maybe at around 75 %."
},
{
"code": null,
"e": 28426,
"s": 28068,
"text": "You are now able to choose a threshold, that gives you the best precision/recall tradeoff for your current machine learning problem. If you want for example a precision of 80%, you can easily look at the plots and see that you would need a threshold of around 0.4. Then you could train a model with exactly that threshold and would get the desired accuracy."
},
{
"code": null,
"e": 28494,
"s": 28426,
"text": "Another way is to plot the precision and recall against each other:"
},
{
"code": null,
"e": 28783,
"s": 28494,
"text": "def plot_precision_vs_recall(precision, recall): plt.plot(recall, precision, \"g--\", linewidth=2.5) plt.ylabel(\"recall\", fontsize=19) plt.xlabel(\"precision\", fontsize=19) plt.axis([0, 1.5, 0, 1.5])plt.figure(figsize=(14, 7))plot_precision_vs_recall(precision, recall)plt.show()"
},
{
"code": null,
"e": 29076,
"s": 28783,
"text": "Another way to evaluate and compare your binary classifier is provided by the ROC AUC Curve. This curve plots the true positive rate (also called recall) against the false positive rate (ratio of incorrectly classified negative instances), instead of plotting the precision versus the recall."
},
{
"code": null,
"e": 29708,
"s": 29076,
"text": "from sklearn.metrics import roc_curve# compute true positive rate and false positive ratefalse_positive_rate, true_positive_rate, thresholds = roc_curve(Y_train, y_scores)# plotting them against each otherdef plot_roc_curve(false_positive_rate, true_positive_rate, label=None): plt.plot(false_positive_rate, true_positive_rate, linewidth=2, label=label) plt.plot([0, 1], [0, 1], 'r', linewidth=4) plt.axis([0, 1, 0, 1]) plt.xlabel('False Positive Rate (FPR)', fontsize=16) plt.ylabel('True Positive Rate (TPR)', fontsize=16)plt.figure(figsize=(14, 7))plot_roc_curve(false_positive_rate, true_positive_rate)plt.show()"
},
{
"code": null,
"e": 29912,
"s": 29708,
"text": "The red line in the middel represents a purely random classifier (e.g a coin flip) and therefore your classifier should be as far away from it as possible. Our Random Forest model seems to do a good job."
},
{
"code": null,
"e": 30044,
"s": 29912,
"text": "Of course we also have a tradeoff here, because the classifier produces more false positives, the higher the true positive rate is."
},
{
"code": null,
"e": 30193,
"s": 30044,
"text": "The ROC AUC Score is the corresponding score to the ROC AUC Curve. It is simply computed by measuring the area under the curve, which is called AUC."
},
{
"code": null,
"e": 30324,
"s": 30193,
"text": "A classifiers that is 100% correct, would have a ROC AUC Score of 1 and a completely random classiffier would have a score of 0.5."
},
{
"code": null,
"e": 30444,
"s": 30324,
"text": "from sklearn.metrics import roc_auc_scorer_a_score = roc_auc_score(Y_train, y_scores)print(\"ROC-AUC-Score:\", r_a_score)"
},
{
"code": null,
"e": 30471,
"s": 30444,
"text": "ROC_AUC_SCORE: 0.945067587"
},
{
"code": null,
"e": 30582,
"s": 30471,
"text": "Nice ! I think that score is good enough to submit the predictions for the test-set to the Kaggle leaderboard."
},
{
"code": null,
"e": 31390,
"s": 30582,
"text": "We started with the data exploration where we got a feeling for the dataset, checked about missing data and learned which features are important. During this process we used seaborn and matplotlib to do the visualizations. During the data preprocessing part, we computed missing values, converted features into numeric ones, grouped values into categories and created a few new features. Afterwards we started training 8 different machine learning models, picked one of them (random forest) and applied cross validation on it. Then we discussed how random forest works, took a look at the importance it assigns to the different features and tuned it’s performace through optimizing it’s hyperparameter values. Lastly, we looked at it’s confusion matrix and computed the models precision, recall and f-score."
},
{
"code": null,
"e": 31464,
"s": 31390,
"text": "Below you can see a before and after picture of the “train_df” dataframe:"
}
] |
How to get day of month, day of year and day of week in android using offset date time API class?
|
This example demonstrate about How to get day of month, day of year and day of week in android using offset date time API class.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show day of month, day of year and day of the week.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
OffsetDateTime offset = OffsetDateTime.now();
textView.setText(String.valueOf(offset.getDayOfWeek() + " : " + offset.getDayOfMonth() + " : " + offset.getDayOfYear()));
}
}
}
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 −
In the above result, it is showing the current day, month and year.
Click here to download the project code
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "This example demonstrate about How to get day of month, day of year and day of week in android using offset date time API class."
},
{
"code": null,
"e": 1320,
"s": 1191,
"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": 1385,
"s": 1320,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2162,
"s": 1385,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2259,
"s": 2162,
"text": "In the above code, we have taken textview to show day of month, day of year and day of the week."
},
{
"code": null,
"e": 2316,
"s": 2259,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3068,
"s": 2316,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.time.OffsetDateTime;\nimport java.time.OffsetTime;\n\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 textView = findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n OffsetDateTime offset = OffsetDateTime.now();\n textView.setText(String.valueOf(offset.getDayOfWeek() + \" : \" + offset.getDayOfMonth() + \" : \" + offset.getDayOfYear()));\n }\n }\n}"
},
{
"code": null,
"e": 3415,
"s": 3068,
"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": 3483,
"s": 3415,
"text": "In the above result, it is showing the current day, month and year."
},
{
"code": null,
"e": 3523,
"s": 3483,
"text": "Click here to download the project code"
}
] |
Support Vector Machines(SVM) — An Overview | by Rushikesh Pupale | Towards Data Science
|
Machine learning involves predicting and classifying data and to do so we employ various machine learning algorithms according to the dataset.
SVM or Support Vector Machine is a linear model for classification and regression problems. It can solve linear and non-linear problems and work well for many practical problems. The idea of SVM is simple: The algorithm creates a line or a hyperplane which separates the data into classes.
In this blog post I plan on offering a high-level overview of SVMs. I will talk about the theory behind SVMs, it’s application for non-linearly separable datasets and a quick example of implementation of SVMs in Python as well. In the upcoming articles I will explore the maths behind the algorithm and dig under the hood.
THEORY
At first approximation what SVMs do is to find a separating line(or hyperplane) between data of two classes. SVM is an algorithm that takes the data as an input and outputs a line that separates those classes if possible.
Lets begin with a problem. Suppose you have a dataset as shown below and you need to classify the red rectangles from the blue ellipses(let’s say positives from the negatives). So your task is to find an ideal line that separates this dataset in two classes (say red and blue).
Not a big task, right?
But, as you notice there isn’t a unique line that does the job. In fact, we have an infinite lines that can separate these two classes. So how does SVM find the ideal one???
Let’s take some probable candidates and figure it out ourselves.
We have two candidates here, the green colored line and the yellow colored line. Which line according to you best separates the data?
If you selected the yellow line then congrats, because thats the line we are looking for. It’s visually quite intuitive in this case that the yellow line classifies better. But, we need something concrete to fix our line.
The green line in the image above is quite close to the red class. Though it classifies the current datasets it is not a generalized line and in machine learning our goal is to get a more generalized separator.
SVM’s way to find the best line
According to the SVM algorithm we find the points closest to the line from both the classes.These points are called support vectors. Now, we compute the distance between the line and the support vectors. This distance is called the margin. Our goal is to maximize the margin. The hyperplane for which the margin is maximum is the optimal hyperplane.
Thus SVM tries to make a decision boundary in such a way that the separation between the two classes(that street) is as wide as possible.
Simple, ain’t it? Let’s consider a bit complex dataset, which is not linearly separable.
This data is clearly not linearly separable. We cannot draw a straight line that can classify this data. But, this data can be converted to linearly separable data in higher dimension. Lets add one more dimension and call it z-axis. Let the co-ordinates on z-axis be governed by the constraint,
z = x2+y2
So, basically z co-ordinate is the square of distance of the point from origin. Let’s plot the data on z-axis.
Now the data is clearly linearly separable. Let the purple line separating the data in higher dimension be z=k, where k is a constant. Since, z=x2+y2 we get x2 + y2 = k; which is an equation of a circle. So, we can project this linear separator in higher dimension back in original dimensions using this transformation.
Thus we can classify data by adding an extra dimension to it so that it becomes linearly separable and then projecting the decision boundary back to original dimensions using mathematical transformation. But finding the correct transformation for any given dataset isn’t that easy. Thankfully, we can use kernels in sklearn’s SVM implementation to do this job.
HYPERPLANE
Now that we understand the SVM logic lets formally define the hyperplane .
A hyperplane in an n-dimensional Euclidean space is a flat, n-1 dimensional subset of that space that divides the space into two disconnected parts.
For example let’s assume a line to be our one dimensional Euclidean space(i.e. let’s say our datasets lie on a line). Now pick a point on the line, this point divides the line into two parts. The line has 1 dimension, while the point has 0 dimensions. So a point is a hyperplane of the line.
For two dimensions we saw that the separating line was the hyperplane. Similarly, for three dimensions a plane with two dimensions divides the 3d space into two parts and thus act as a hyperplane. Thus for a space of n dimensions we have a hyperplane of n-1 dimensions separating it into two parts
CODE
import numpy as npX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])y = np.array([1, 1, 2, 2])
We have our points in X and the classes they belong to in Y.
Now we train our SVM model with the above dataset.For this example I have used a linear kernel.
from sklearn.svm import SVCclf = SVC(kernel='linear')clf.fit(X, y)
To predict the class of new dataset
prediction = clf.predict([[0,6]])
TUNING PARAMETERS
Parameters are arguments that you pass when you create your classifier. Following are the important parameters for SVM-
1]C:
It controls the trade off between smooth decision boundary and classifying training points correctly. A large value of c means you will get more training points correctly.
Consider an example as shown in the figure above. There are a number of decision boundaries that we can draw for this dataset. Consider a straight (green colored) decision boundary which is quite simple but it comes at the cost of a few points being misclassified. These misclassified points are called outliers. We can also make something that is considerably more wiggly(sky blue colored decision boundary) but where we get potentially all of the training points correct. Of course the trade off having something that is very intricate, very complicated like this is that chances are it is not going to generalize quite as well to our test set. So something that is simple, more straight maybe actually the better choice if you look at the accuracy. Large value of c means you will get more intricate decision curves trying to fit in all the points. Figuring out how much you want to have a smooth decision boundary vs one that gets things correct is part of artistry of machine learning. So try different values of c for your dataset to get the perfectly balanced curve and avoid over fitting.
2]Gamma:
It defines how far the influence of a single training example reaches. If it has a low value it means that every point has a far reach and conversely high value of gamma means that every point has close reach.
If gamma has a very high value, then the decision boundary is just going to be dependent upon the points that are very close to the line which effectively results in ignoring some of the points that are very far from the decision boundary. This is because the closer points get more weight and it results in a wiggly curve as shown in previous graph.On the other hand, if the gamma value is low even the far away points get considerable weight and we get a more linear curve.
In the upcoming article
I will explore the math behind the SVM algorithm and the optimization problem.
Conclusion
I hope this blog post helped in understanding SVMs. Comment down your thoughts, feedback or suggestions if any below.
|
[
{
"code": null,
"e": 315,
"s": 172,
"text": "Machine learning involves predicting and classifying data and to do so we employ various machine learning algorithms according to the dataset."
},
{
"code": null,
"e": 605,
"s": 315,
"text": "SVM or Support Vector Machine is a linear model for classification and regression problems. It can solve linear and non-linear problems and work well for many practical problems. The idea of SVM is simple: The algorithm creates a line or a hyperplane which separates the data into classes."
},
{
"code": null,
"e": 928,
"s": 605,
"text": "In this blog post I plan on offering a high-level overview of SVMs. I will talk about the theory behind SVMs, it’s application for non-linearly separable datasets and a quick example of implementation of SVMs in Python as well. In the upcoming articles I will explore the maths behind the algorithm and dig under the hood."
},
{
"code": null,
"e": 935,
"s": 928,
"text": "THEORY"
},
{
"code": null,
"e": 1157,
"s": 935,
"text": "At first approximation what SVMs do is to find a separating line(or hyperplane) between data of two classes. SVM is an algorithm that takes the data as an input and outputs a line that separates those classes if possible."
},
{
"code": null,
"e": 1435,
"s": 1157,
"text": "Lets begin with a problem. Suppose you have a dataset as shown below and you need to classify the red rectangles from the blue ellipses(let’s say positives from the negatives). So your task is to find an ideal line that separates this dataset in two classes (say red and blue)."
},
{
"code": null,
"e": 1458,
"s": 1435,
"text": "Not a big task, right?"
},
{
"code": null,
"e": 1632,
"s": 1458,
"text": "But, as you notice there isn’t a unique line that does the job. In fact, we have an infinite lines that can separate these two classes. So how does SVM find the ideal one???"
},
{
"code": null,
"e": 1697,
"s": 1632,
"text": "Let’s take some probable candidates and figure it out ourselves."
},
{
"code": null,
"e": 1831,
"s": 1697,
"text": "We have two candidates here, the green colored line and the yellow colored line. Which line according to you best separates the data?"
},
{
"code": null,
"e": 2053,
"s": 1831,
"text": "If you selected the yellow line then congrats, because thats the line we are looking for. It’s visually quite intuitive in this case that the yellow line classifies better. But, we need something concrete to fix our line."
},
{
"code": null,
"e": 2264,
"s": 2053,
"text": "The green line in the image above is quite close to the red class. Though it classifies the current datasets it is not a generalized line and in machine learning our goal is to get a more generalized separator."
},
{
"code": null,
"e": 2296,
"s": 2264,
"text": "SVM’s way to find the best line"
},
{
"code": null,
"e": 2646,
"s": 2296,
"text": "According to the SVM algorithm we find the points closest to the line from both the classes.These points are called support vectors. Now, we compute the distance between the line and the support vectors. This distance is called the margin. Our goal is to maximize the margin. The hyperplane for which the margin is maximum is the optimal hyperplane."
},
{
"code": null,
"e": 2784,
"s": 2646,
"text": "Thus SVM tries to make a decision boundary in such a way that the separation between the two classes(that street) is as wide as possible."
},
{
"code": null,
"e": 2873,
"s": 2784,
"text": "Simple, ain’t it? Let’s consider a bit complex dataset, which is not linearly separable."
},
{
"code": null,
"e": 3168,
"s": 2873,
"text": "This data is clearly not linearly separable. We cannot draw a straight line that can classify this data. But, this data can be converted to linearly separable data in higher dimension. Lets add one more dimension and call it z-axis. Let the co-ordinates on z-axis be governed by the constraint,"
},
{
"code": null,
"e": 3178,
"s": 3168,
"text": "z = x2+y2"
},
{
"code": null,
"e": 3289,
"s": 3178,
"text": "So, basically z co-ordinate is the square of distance of the point from origin. Let’s plot the data on z-axis."
},
{
"code": null,
"e": 3609,
"s": 3289,
"text": "Now the data is clearly linearly separable. Let the purple line separating the data in higher dimension be z=k, where k is a constant. Since, z=x2+y2 we get x2 + y2 = k; which is an equation of a circle. So, we can project this linear separator in higher dimension back in original dimensions using this transformation."
},
{
"code": null,
"e": 3970,
"s": 3609,
"text": "Thus we can classify data by adding an extra dimension to it so that it becomes linearly separable and then projecting the decision boundary back to original dimensions using mathematical transformation. But finding the correct transformation for any given dataset isn’t that easy. Thankfully, we can use kernels in sklearn’s SVM implementation to do this job."
},
{
"code": null,
"e": 3981,
"s": 3970,
"text": "HYPERPLANE"
},
{
"code": null,
"e": 4056,
"s": 3981,
"text": "Now that we understand the SVM logic lets formally define the hyperplane ."
},
{
"code": null,
"e": 4205,
"s": 4056,
"text": "A hyperplane in an n-dimensional Euclidean space is a flat, n-1 dimensional subset of that space that divides the space into two disconnected parts."
},
{
"code": null,
"e": 4497,
"s": 4205,
"text": "For example let’s assume a line to be our one dimensional Euclidean space(i.e. let’s say our datasets lie on a line). Now pick a point on the line, this point divides the line into two parts. The line has 1 dimension, while the point has 0 dimensions. So a point is a hyperplane of the line."
},
{
"code": null,
"e": 4795,
"s": 4497,
"text": "For two dimensions we saw that the separating line was the hyperplane. Similarly, for three dimensions a plane with two dimensions divides the 3d space into two parts and thus act as a hyperplane. Thus for a space of n dimensions we have a hyperplane of n-1 dimensions separating it into two parts"
},
{
"code": null,
"e": 4800,
"s": 4795,
"text": "CODE"
},
{
"code": null,
"e": 4895,
"s": 4800,
"text": "import numpy as npX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])y = np.array([1, 1, 2, 2])"
},
{
"code": null,
"e": 4956,
"s": 4895,
"text": "We have our points in X and the classes they belong to in Y."
},
{
"code": null,
"e": 5052,
"s": 4956,
"text": "Now we train our SVM model with the above dataset.For this example I have used a linear kernel."
},
{
"code": null,
"e": 5119,
"s": 5052,
"text": "from sklearn.svm import SVCclf = SVC(kernel='linear')clf.fit(X, y)"
},
{
"code": null,
"e": 5155,
"s": 5119,
"text": "To predict the class of new dataset"
},
{
"code": null,
"e": 5189,
"s": 5155,
"text": "prediction = clf.predict([[0,6]])"
},
{
"code": null,
"e": 5207,
"s": 5189,
"text": "TUNING PARAMETERS"
},
{
"code": null,
"e": 5327,
"s": 5207,
"text": "Parameters are arguments that you pass when you create your classifier. Following are the important parameters for SVM-"
},
{
"code": null,
"e": 5332,
"s": 5327,
"text": "1]C:"
},
{
"code": null,
"e": 5504,
"s": 5332,
"text": "It controls the trade off between smooth decision boundary and classifying training points correctly. A large value of c means you will get more training points correctly."
},
{
"code": null,
"e": 6601,
"s": 5504,
"text": "Consider an example as shown in the figure above. There are a number of decision boundaries that we can draw for this dataset. Consider a straight (green colored) decision boundary which is quite simple but it comes at the cost of a few points being misclassified. These misclassified points are called outliers. We can also make something that is considerably more wiggly(sky blue colored decision boundary) but where we get potentially all of the training points correct. Of course the trade off having something that is very intricate, very complicated like this is that chances are it is not going to generalize quite as well to our test set. So something that is simple, more straight maybe actually the better choice if you look at the accuracy. Large value of c means you will get more intricate decision curves trying to fit in all the points. Figuring out how much you want to have a smooth decision boundary vs one that gets things correct is part of artistry of machine learning. So try different values of c for your dataset to get the perfectly balanced curve and avoid over fitting."
},
{
"code": null,
"e": 6610,
"s": 6601,
"text": "2]Gamma:"
},
{
"code": null,
"e": 6820,
"s": 6610,
"text": "It defines how far the influence of a single training example reaches. If it has a low value it means that every point has a far reach and conversely high value of gamma means that every point has close reach."
},
{
"code": null,
"e": 7296,
"s": 6820,
"text": "If gamma has a very high value, then the decision boundary is just going to be dependent upon the points that are very close to the line which effectively results in ignoring some of the points that are very far from the decision boundary. This is because the closer points get more weight and it results in a wiggly curve as shown in previous graph.On the other hand, if the gamma value is low even the far away points get considerable weight and we get a more linear curve."
},
{
"code": null,
"e": 7320,
"s": 7296,
"text": "In the upcoming article"
},
{
"code": null,
"e": 7399,
"s": 7320,
"text": "I will explore the math behind the SVM algorithm and the optimization problem."
},
{
"code": null,
"e": 7410,
"s": 7399,
"text": "Conclusion"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.