title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
C++ program to find the smallest element among three elements
|
In this tutorial, we will be discussing a program to find the smallest element among the provided three elements.
We will be provided with three elements/ integers and our task is to compare them and find the smallest element/ integer among them.
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 45, b = 72, c = 10;
if (a <= b && a <= c)
cout << a << " is smallest" << endl;
else if (b <= a && b <= c)
cout << b << " is smallest" << endl;
else
cout << c << " is smallest" << endl;
return 0;
}
10 is smallest
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to find the smallest element among the provided three elements."
},
{
"code": null,
"e": 1309,
"s": 1176,
"text": "We will be provided with three elements/ integers and our task is to compare them and find the smallest element/ integer among them."
},
{
"code": null,
"e": 1609,
"s": 1309,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int a = 45, b = 72, c = 10;\n if (a <= b && a <= c)\n cout << a << \" is smallest\" << endl;\n else if (b <= a && b <= c)\n cout << b << \" is smallest\" << endl;\n else\n cout << c << \" is smallest\" << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1624,
"s": 1609,
"text": "10 is smallest"
}
] |
Frequency of each character in a String using unordered_map in C++ - GeeksforGeeks
|
26 Oct, 2020
Given a string str, the task is to find the frequency of each character of a string using an unordered_map in C++ STL.
Examples:
Input: str = “geeksforgeeks” Output: r 1 e 4 s 2 g 2 k 2 f 1 o 1
Input: str = “programming” Output: n 1 i 1 p 1 o 1 r 2 a 1 g 2 m 2
Approach:
Traverse each character of the given string str.Check whether the current character is present in unordered_map or not.If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below:
Traverse each character of the given string str.
Check whether the current character is present in unordered_map or not.
If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below:
if(M.find(s[i])==M.end()) {
M.insert(make_pair{s[i], 1});
}
else {
M[s[i]]++;
}
4. Traverse the unordered_map and print the frequency of each characters stored as a mapped value.
Below is the implementation of the above approach:
CPP
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; void printFrequency(string str){ // Define an unordered_map unordered_map<char, int> M; // Traverse string str check if // current character is present // or not for (int i = 0; str[i]; i++) { // If the current characters // is not found then insert // current characters with // frequency 1 if (M.find(str[i]) == M.end()) { M.insert(make_pair(str[i], 1)); } // Else update the frequency else { M[str[i]]++; } } // Traverse the map to print the // frequency for (auto& it : M) { cout << it.first << ' ' << it.second << '\n'; }} // Driver Codeint main(){ string str = "geeksforgeeks"; // Function call printFrequency(str); return 0;}
r 1
e 4
s 2
g 2
k 2
f 1
o 1
rajahimanshu
cpp-strings
cpp-unordered_map
frequency-counting
STL
C++
cpp-strings
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Iterators in C++ STL
std::string class in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 24124,
"s": 24096,
"text": "\n26 Oct, 2020"
},
{
"code": null,
"e": 24243,
"s": 24124,
"text": "Given a string str, the task is to find the frequency of each character of a string using an unordered_map in C++ STL."
},
{
"code": null,
"e": 24254,
"s": 24243,
"text": "Examples: "
},
{
"code": null,
"e": 24319,
"s": 24254,
"text": "Input: str = “geeksforgeeks” Output: r 1 e 4 s 2 g 2 k 2 f 1 o 1"
},
{
"code": null,
"e": 24387,
"s": 24319,
"text": "Input: str = “programming” Output: n 1 i 1 p 1 o 1 r 2 a 1 g 2 m 2 "
},
{
"code": null,
"e": 24398,
"s": 24387,
"text": "Approach: "
},
{
"code": null,
"e": 24648,
"s": 24398,
"text": "Traverse each character of the given string str.Check whether the current character is present in unordered_map or not.If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: "
},
{
"code": null,
"e": 24697,
"s": 24648,
"text": "Traverse each character of the given string str."
},
{
"code": null,
"e": 24769,
"s": 24697,
"text": "Check whether the current character is present in unordered_map or not."
},
{
"code": null,
"e": 24900,
"s": 24769,
"text": "If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: "
},
{
"code": null,
"e": 24989,
"s": 24900,
"text": "if(M.find(s[i])==M.end()) {\n M.insert(make_pair{s[i], 1});\n}\nelse {\n M[s[i]]++;\n}\n"
},
{
"code": null,
"e": 25096,
"s": 24989,
"text": " 4. Traverse the unordered_map and print the frequency of each characters stored as a mapped value."
},
{
"code": null,
"e": 25147,
"s": 25096,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25151,
"s": 25147,
"text": "CPP"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; void printFrequency(string str){ // Define an unordered_map unordered_map<char, int> M; // Traverse string str check if // current character is present // or not for (int i = 0; str[i]; i++) { // If the current characters // is not found then insert // current characters with // frequency 1 if (M.find(str[i]) == M.end()) { M.insert(make_pair(str[i], 1)); } // Else update the frequency else { M[str[i]]++; } } // Traverse the map to print the // frequency for (auto& it : M) { cout << it.first << ' ' << it.second << '\\n'; }} // Driver Codeint main(){ string str = \"geeksforgeeks\"; // Function call printFrequency(str); return 0;}",
"e": 26024,
"s": 25151,
"text": null
},
{
"code": null,
"e": 26053,
"s": 26024,
"text": "r 1\ne 4\ns 2\ng 2\nk 2\nf 1\no 1\n"
},
{
"code": null,
"e": 26066,
"s": 26053,
"text": "rajahimanshu"
},
{
"code": null,
"e": 26078,
"s": 26066,
"text": "cpp-strings"
},
{
"code": null,
"e": 26096,
"s": 26078,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 26115,
"s": 26096,
"text": "frequency-counting"
},
{
"code": null,
"e": 26119,
"s": 26115,
"text": "STL"
},
{
"code": null,
"e": 26123,
"s": 26119,
"text": "C++"
},
{
"code": null,
"e": 26135,
"s": 26123,
"text": "cpp-strings"
},
{
"code": null,
"e": 26139,
"s": 26135,
"text": "STL"
},
{
"code": null,
"e": 26143,
"s": 26139,
"text": "CPP"
},
{
"code": null,
"e": 26241,
"s": 26143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26269,
"s": 26241,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26289,
"s": 26269,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26313,
"s": 26289,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26346,
"s": 26313,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26390,
"s": 26346,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26426,
"s": 26390,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26470,
"s": 26426,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26491,
"s": 26470,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26516,
"s": 26491,
"text": "std::string class in C++"
}
] |
How to hide a soft keyboard on android after clicking outside EditText using Kotlin?
|
This example demonstrates how to hide a soft keyboard on android after clicking outside EditText 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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="Enter text here"
android:textColor="@android:color/background_dark"
android:textSize="20sp" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="setText"
android:text="Set Text"
android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText = findViewById(R.id.editText)
textView = findViewById(R.id.textView)
title = "KotlinApp"
}
fun setText(view: View) {
val newText = editText.text.toString()
textView.text = newText
closeKeyBoard()
}
private fun closeKeyBoard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "This example demonstrates how to hide a soft keyboard on android after clicking outside EditText using Kotlin."
},
{
"code": null,
"e": 1302,
"s": 1173,
"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": 1367,
"s": 1302,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2399,
"s": 1367,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\"MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_horizontal\"\n android:hint=\"Enter text here\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"20sp\" />\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_horizontal\"\n android:onClick=\"setText\"\n android:text=\"Set Text\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2454,
"s": 2399,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3458,
"s": 2454,
"text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.View\nimport android.view.inputmethod.InputMethodManager\nimport android.widget.EditText\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n editText = findViewById(R.id.editText)\n textView = findViewById(R.id.textView)\n title = \"KotlinApp\"\n }\n fun setText(view: View) {\n val newText = editText.text.toString()\n textView.text = newText\n closeKeyBoard()\n }\n private fun closeKeyBoard() {\n val view = this.currentFocus\n if (view != null) {\n val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager\n imm.hideSoftInputFromWindow(view.windowToken, 0)\n }\n }\n}"
},
{
"code": null,
"e": 3513,
"s": 3458,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4141,
"s": 3513,
"text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.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": 4489,
"s": 4141,
"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"
}
] |
ConcurrentHashMap get() Method in Java - GeeksforGeeks
|
14 Sep, 2018
The get() method of java.util.concurrent.ConcurrentHashMap is an in-built function in Java which accepts a key as parameter and returns the value mapped to it. It returns null if no mapping exists for the key passed as parameter.
Syntax:
Concurrent.get(Object key_element)
Parameters: The method accepts a single parameter key_element of object type which refers to the key whose associated value is supposed to be returned.
Return Value: The method returns the value associated with the key_element in the parameter.
Exception: The function throws NullPointerException when the specified key_element is null.
Below programs illustrate the use of java.util.concurrent.ConcurrentHashMap.get() method :
Program 1: This program involves mapping String Values to Integer Keys.
// Java Program Demonstrate get()// method of ConcurrentHashMap import java.util.concurrent.*; class GFG { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); chm.put(100, "Geeks"); chm.put(101, "for"); chm.put(102, "Geeks"); chm.put(103, "Contribute"); // Displaying the HashMap System.out.println("The Mappings are: "); System.out.println(chm); // Display the value of 100 System.out.println("The Value associated to " + "100 is : " + chm.get(100)); // Getting the value of 103 System.out.println("The Value associated to " + "103 is : " + chm.get(103)); }}
The Mappings are:
{100=Geeks, 101=for, 102=Geeks, 103=Contribute}
The Value associated to 100 is : Geeks
The Value associated to 103 is : Contribute
Program 2: This program involves mapping Integer Values to String Keys.
// Java Program Demonstrate get()// method of ConcurrentHashMap import java.util.concurrent.*; class GFG { public static void main(String[] args) { ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<String, Integer>(); chm.put("Geeks", 100); chm.put("GFG", 10); chm.put("GeeksforGeeks", 25); chm.put("Contribute", 102); // Displaying the HashMap System.out.println("The Mappings are: "); System.out.println(chm); // Display the value of Geeks System.out.println("The Value associated to " + "Geeks is : " + chm.get("Geeks")); // Getting the value of Contribute System.out.println("The Value associated to " + "Contribute is : " + chm.get("Contribute")); }}
The Mappings are:
{GeeksforGeeks=25, Geeks=100, GFG=10, Contribute=102}
The Value associated to Geeks is : 100
The Value associated to Contribute is : 102
Reference : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#get()
Java - util package
Java-ConcurrentHashMap
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
|
[
{
"code": null,
"e": 24088,
"s": 24060,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 24318,
"s": 24088,
"text": "The get() method of java.util.concurrent.ConcurrentHashMap is an in-built function in Java which accepts a key as parameter and returns the value mapped to it. It returns null if no mapping exists for the key passed as parameter."
},
{
"code": null,
"e": 24326,
"s": 24318,
"text": "Syntax:"
},
{
"code": null,
"e": 24361,
"s": 24326,
"text": "Concurrent.get(Object key_element)"
},
{
"code": null,
"e": 24513,
"s": 24361,
"text": "Parameters: The method accepts a single parameter key_element of object type which refers to the key whose associated value is supposed to be returned."
},
{
"code": null,
"e": 24606,
"s": 24513,
"text": "Return Value: The method returns the value associated with the key_element in the parameter."
},
{
"code": null,
"e": 24698,
"s": 24606,
"text": "Exception: The function throws NullPointerException when the specified key_element is null."
},
{
"code": null,
"e": 24789,
"s": 24698,
"text": "Below programs illustrate the use of java.util.concurrent.ConcurrentHashMap.get() method :"
},
{
"code": null,
"e": 24861,
"s": 24789,
"text": "Program 1: This program involves mapping String Values to Integer Keys."
},
{
"code": "// Java Program Demonstrate get()// method of ConcurrentHashMap import java.util.concurrent.*; class GFG { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); chm.put(100, \"Geeks\"); chm.put(101, \"for\"); chm.put(102, \"Geeks\"); chm.put(103, \"Contribute\"); // Displaying the HashMap System.out.println(\"The Mappings are: \"); System.out.println(chm); // Display the value of 100 System.out.println(\"The Value associated to \" + \"100 is : \" + chm.get(100)); // Getting the value of 103 System.out.println(\"The Value associated to \" + \"103 is : \" + chm.get(103)); }}",
"e": 25661,
"s": 24861,
"text": null
},
{
"code": null,
"e": 25812,
"s": 25661,
"text": "The Mappings are: \n{100=Geeks, 101=for, 102=Geeks, 103=Contribute}\nThe Value associated to 100 is : Geeks\nThe Value associated to 103 is : Contribute\n"
},
{
"code": null,
"e": 25884,
"s": 25812,
"text": "Program 2: This program involves mapping Integer Values to String Keys."
},
{
"code": "// Java Program Demonstrate get()// method of ConcurrentHashMap import java.util.concurrent.*; class GFG { public static void main(String[] args) { ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<String, Integer>(); chm.put(\"Geeks\", 100); chm.put(\"GFG\", 10); chm.put(\"GeeksforGeeks\", 25); chm.put(\"Contribute\", 102); // Displaying the HashMap System.out.println(\"The Mappings are: \"); System.out.println(chm); // Display the value of Geeks System.out.println(\"The Value associated to \" + \"Geeks is : \" + chm.get(\"Geeks\")); // Getting the value of Contribute System.out.println(\"The Value associated to \" + \"Contribute is : \" + chm.get(\"Contribute\")); }}",
"e": 26721,
"s": 25884,
"text": null
},
{
"code": null,
"e": 26878,
"s": 26721,
"text": "The Mappings are: \n{GeeksforGeeks=25, Geeks=100, GFG=10, Contribute=102}\nThe Value associated to Geeks is : 100\nThe Value associated to Contribute is : 102\n"
},
{
"code": null,
"e": 26982,
"s": 26878,
"text": "Reference : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#get()"
},
{
"code": null,
"e": 27002,
"s": 26982,
"text": "Java - util package"
},
{
"code": null,
"e": 27025,
"s": 27002,
"text": "Java-ConcurrentHashMap"
},
{
"code": null,
"e": 27040,
"s": 27025,
"text": "Java-Functions"
},
{
"code": null,
"e": 27045,
"s": 27040,
"text": "Java"
},
{
"code": null,
"e": 27050,
"s": 27045,
"text": "Java"
},
{
"code": null,
"e": 27148,
"s": 27050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27163,
"s": 27148,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27207,
"s": 27163,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27229,
"s": 27207,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 27265,
"s": 27229,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27290,
"s": 27265,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27322,
"s": 27290,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27352,
"s": 27322,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27371,
"s": 27352,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27422,
"s": 27371,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
ASP.NET Core - Setup MVC
|
In this chapter, we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs.
To setup MVC framework in our empty project, follow these steps −
Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.
Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.
Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the ConfigureServices method.
Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the ConfigureServices method.
Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write.
Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write.
Step 1 − Let us go to the NuGet package manager by right-clicking on the Manage NuGet Packages. Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.
Step 2 − Once the Microsoft.AspNet.Mvc package is installed, we need to register all the services that ASP.NET Core MVC requires at runtime. We will do this with the ConfigureServices method. We will also add a simple controller and we will see some output from that controller.
Let us add a new folder to this project and call it Controllers. In this folder, we can place multiple controllers as shown below in the Solution Explorer.
Now right-click on the Controllers folder and select on the Add → Class menu option.
Step 3 − Here we want to add a simple C# class, and call this class HomeController and then Click on the Add button as in the above screenshot.
This will be our default page.
Step 4 − Let us define a single public method that returns a string and call that method Index as shown in the following program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstAppdemo.Controllers {
public class HomeController {
public string Index() {
return "Hello, World! this message is from Home Controller...";
}
}
}
Step 5 − When you go to the root of the website, you want to see the controller response. As of now, we will be serving our index.html file.
Let us go into the root of the website and delete index.html. We want the controller to respond instead of index.html file.
Step 6 − Now go to the Configure method in the Startup class and add the UseMvcWithDefaultRoute piece of middleware.
Step 7 − Now refresh the application at the root of the website.
You will encounter a 500 error. The error says that the framework was unable to find the required ASP.NET Core MVC services.
The ASP.NET Core Framework itself is made up of different small components that have very focused responsibilities.
For example, there is a component that has to locate and instantiate the controller.
That component needs to be in the service collection for ASP.NET Core MVC to function correctly.
Step 8 − In addition to adding the NuGet package and the middleware, we also need to add the AddMvc service in the ConfigureServices. Here is the complete implementation of the Startup class.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace FirstAppDemo {
public class Startup {
public Startup() {
var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app) {
app.UseIISPlatformHandler();
app.UseDeveloperExceptionPage();
app.UseRuntimeInfoPage();
app.UseFileServer();
app.UseMvcWithDefaultRoute();
app.Run(async (context) => {
var msg = Configuration["message"];
await context.Response.WriteAsync(msg);
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
Step 9 − Save the Startup.cs file and go to the browser and refresh it. You will now receive a response from our home controller.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2851,
"s": 2461,
"text": "In this chapter, we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs."
},
{
"code": null,
"e": 2917,
"s": 2851,
"text": "To setup MVC framework in our empty project, follow these steps −"
},
{
"code": null,
"e": 3038,
"s": 2917,
"text": "Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework."
},
{
"code": null,
"e": 3159,
"s": 3038,
"text": "Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework."
},
{
"code": null,
"e": 3321,
"s": 3159,
"text": "Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the ConfigureServices method."
},
{
"code": null,
"e": 3483,
"s": 3321,
"text": "Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the ConfigureServices method."
},
{
"code": null,
"e": 3681,
"s": 3483,
"text": "Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write."
},
{
"code": null,
"e": 3879,
"s": 3681,
"text": "Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write."
},
{
"code": null,
"e": 4096,
"s": 3879,
"text": "Step 1 − Let us go to the NuGet package manager by right-clicking on the Manage NuGet Packages. Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework."
},
{
"code": null,
"e": 4375,
"s": 4096,
"text": "Step 2 − Once the Microsoft.AspNet.Mvc package is installed, we need to register all the services that ASP.NET Core MVC requires at runtime. We will do this with the ConfigureServices method. We will also add a simple controller and we will see some output from that controller."
},
{
"code": null,
"e": 4531,
"s": 4375,
"text": "Let us add a new folder to this project and call it Controllers. In this folder, we can place multiple controllers as shown below in the Solution Explorer."
},
{
"code": null,
"e": 4616,
"s": 4531,
"text": "Now right-click on the Controllers folder and select on the Add → Class menu option."
},
{
"code": null,
"e": 4760,
"s": 4616,
"text": "Step 3 − Here we want to add a simple C# class, and call this class HomeController and then Click on the Add button as in the above screenshot."
},
{
"code": null,
"e": 4791,
"s": 4760,
"text": "This will be our default page."
},
{
"code": null,
"e": 4921,
"s": 4791,
"text": "Step 4 − Let us define a single public method that returns a string and call that method Index as shown in the following program."
},
{
"code": null,
"e": 5218,
"s": 4921,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppdemo.Controllers { \n public class HomeController { \n public string Index() { \n return \"Hello, World! this message is from Home Controller...\"; \n } \n } \n}"
},
{
"code": null,
"e": 5359,
"s": 5218,
"text": "Step 5 − When you go to the root of the website, you want to see the controller response. As of now, we will be serving our index.html file."
},
{
"code": null,
"e": 5483,
"s": 5359,
"text": "Let us go into the root of the website and delete index.html. We want the controller to respond instead of index.html file."
},
{
"code": null,
"e": 5600,
"s": 5483,
"text": "Step 6 − Now go to the Configure method in the Startup class and add the UseMvcWithDefaultRoute piece of middleware."
},
{
"code": null,
"e": 5665,
"s": 5600,
"text": "Step 7 − Now refresh the application at the root of the website."
},
{
"code": null,
"e": 5790,
"s": 5665,
"text": "You will encounter a 500 error. The error says that the framework was unable to find the required ASP.NET Core MVC services."
},
{
"code": null,
"e": 5906,
"s": 5790,
"text": "The ASP.NET Core Framework itself is made up of different small components that have very focused responsibilities."
},
{
"code": null,
"e": 5991,
"s": 5906,
"text": "For example, there is a component that has to locate and instantiate the controller."
},
{
"code": null,
"e": 6088,
"s": 5991,
"text": "That component needs to be in the service collection for ASP.NET Core MVC to function correctly."
},
{
"code": null,
"e": 6280,
"s": 6088,
"text": "Step 8 − In addition to adding the NuGet package and the middleware, we also need to add the AddMvc service in the ConfigureServices. Here is the complete implementation of the Startup class."
},
{
"code": null,
"e": 7817,
"s": 6280,
"text": "using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http; \n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; }\n \n // This method gets called by the runtime. \n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n }\n \n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n \n app.UseFileServer(); \n app.UseMvcWithDefaultRoute(); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n });\n } \n \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run<Startup>(args); \n } \n} "
},
{
"code": null,
"e": 7947,
"s": 7817,
"text": "Step 9 − Save the Startup.cs file and go to the browser and refresh it. You will now receive a response from our home controller."
},
{
"code": null,
"e": 7982,
"s": 7947,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7996,
"s": 7982,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8031,
"s": 7996,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8054,
"s": 8031,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 8088,
"s": 8054,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 8108,
"s": 8088,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 8143,
"s": 8108,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8160,
"s": 8143,
"text": " University Code"
},
{
"code": null,
"e": 8195,
"s": 8160,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8212,
"s": 8195,
"text": " University Code"
},
{
"code": null,
"e": 8246,
"s": 8212,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8261,
"s": 8246,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 8268,
"s": 8261,
"text": " Print"
},
{
"code": null,
"e": 8279,
"s": 8268,
"text": " Add Notes"
}
] |
Number of Ways to Paint N × 3 Grid in C++
|
Suppose we have grid of size n x 3 and we want to paint each cell of the grid with exactly one of the three colors. The colors are Red, Yellow or Green. Now there is a constraint that is no two adjacent cells have the same color. We have n the number of rows of the grid. We have to find the number of ways we can paint this grid. The answer may be very large so return it modulo 10^9 + 7.
So, if the input is like 1, then the output will be 12
To solve this, we will follow these steps −
m = 1^9 + 7
m = 1^9 + 7
Define a function add(), this will take a, b,
Define a function add(), this will take a, b,
return ((a mod m) + (b mod m)) mod m
return ((a mod m) + (b mod m)) mod m
From the main method do the following −
From the main method do the following −
a123 := 6, a121 = 6
a123 := 6, a121 = 6
for initialize i := 2, when i <= n, update (increase i by 1), do −b121 := add(3 * a121, 2 * a123)b123 := add(2 * a121, 2 * a123)a121 := b121a123 := b123
for initialize i := 2, when i <= n, update (increase i by 1), do −
b121 := add(3 * a121, 2 * a123)
b121 := add(3 * a121, 2 * a123)
b123 := add(2 * a121, 2 * a123)
b123 := add(2 * a121, 2 * a123)
a121 := b121
a121 := b121
a123 := b123
a123 := b123
return add(a123, a121)
return add(a123, a121)
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli mod = 1e9 + 7;
class Solution {
public:
lli add(lli a, lli b){
return ((a % mod) + (b % mod)) % mod;
}
int numOfWays(int n){
lli a123 = 6, a121 = 6;
lli b123, b121;
for (int i = 2; i <= n; i++) {
b121 = add(3 * a121, 2 * a123);
b123 = add(2 * a121, 2 * a123);
a121 = b121;
a123 = b123;
}
return add(a123, a121);
}
};
main(){
Solution ob;
cout << (ob.numOfWays(3));
}
3
246
|
[
{
"code": null,
"e": 1452,
"s": 1062,
"text": "Suppose we have grid of size n x 3 and we want to paint each cell of the grid with exactly one of the three colors. The colors are Red, Yellow or Green. Now there is a constraint that is no two adjacent cells have the same color. We have n the number of rows of the grid. We have to find the number of ways we can paint this grid. The answer may be very large so return it modulo 10^9 + 7."
},
{
"code": null,
"e": 1507,
"s": 1452,
"text": "So, if the input is like 1, then the output will be 12"
},
{
"code": null,
"e": 1551,
"s": 1507,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1563,
"s": 1551,
"text": "m = 1^9 + 7"
},
{
"code": null,
"e": 1575,
"s": 1563,
"text": "m = 1^9 + 7"
},
{
"code": null,
"e": 1621,
"s": 1575,
"text": "Define a function add(), this will take a, b,"
},
{
"code": null,
"e": 1667,
"s": 1621,
"text": "Define a function add(), this will take a, b,"
},
{
"code": null,
"e": 1704,
"s": 1667,
"text": "return ((a mod m) + (b mod m)) mod m"
},
{
"code": null,
"e": 1741,
"s": 1704,
"text": "return ((a mod m) + (b mod m)) mod m"
},
{
"code": null,
"e": 1781,
"s": 1741,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 1821,
"s": 1781,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 1841,
"s": 1821,
"text": "a123 := 6, a121 = 6"
},
{
"code": null,
"e": 1861,
"s": 1841,
"text": "a123 := 6, a121 = 6"
},
{
"code": null,
"e": 2014,
"s": 1861,
"text": "for initialize i := 2, when i <= n, update (increase i by 1), do −b121 := add(3 * a121, 2 * a123)b123 := add(2 * a121, 2 * a123)a121 := b121a123 := b123"
},
{
"code": null,
"e": 2081,
"s": 2014,
"text": "for initialize i := 2, when i <= n, update (increase i by 1), do −"
},
{
"code": null,
"e": 2113,
"s": 2081,
"text": "b121 := add(3 * a121, 2 * a123)"
},
{
"code": null,
"e": 2145,
"s": 2113,
"text": "b121 := add(3 * a121, 2 * a123)"
},
{
"code": null,
"e": 2177,
"s": 2145,
"text": "b123 := add(2 * a121, 2 * a123)"
},
{
"code": null,
"e": 2209,
"s": 2177,
"text": "b123 := add(2 * a121, 2 * a123)"
},
{
"code": null,
"e": 2222,
"s": 2209,
"text": "a121 := b121"
},
{
"code": null,
"e": 2235,
"s": 2222,
"text": "a121 := b121"
},
{
"code": null,
"e": 2248,
"s": 2235,
"text": "a123 := b123"
},
{
"code": null,
"e": 2261,
"s": 2248,
"text": "a123 := b123"
},
{
"code": null,
"e": 2284,
"s": 2261,
"text": "return add(a123, a121)"
},
{
"code": null,
"e": 2307,
"s": 2284,
"text": "return add(a123, a121)"
},
{
"code": null,
"e": 2377,
"s": 2307,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2388,
"s": 2377,
"text": " Live Demo"
},
{
"code": null,
"e": 2931,
"s": 2388,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nconst lli mod = 1e9 + 7;\nclass Solution {\n public:\n lli add(lli a, lli b){\n return ((a % mod) + (b % mod)) % mod;\n }\n int numOfWays(int n){\n lli a123 = 6, a121 = 6;\n lli b123, b121;\n for (int i = 2; i <= n; i++) {\n b121 = add(3 * a121, 2 * a123);\n b123 = add(2 * a121, 2 * a123);\n a121 = b121;\n a123 = b123;\n }\n return add(a123, a121);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.numOfWays(3));\n}"
},
{
"code": null,
"e": 2933,
"s": 2931,
"text": "3"
},
{
"code": null,
"e": 2937,
"s": 2933,
"text": "246"
}
] |
SharePoint - REST APIs
|
In this chapter, we will be covering the REST APIs. This is not a traditional API, where we have a set of libraries that contain types and those types contain properties and methods.
The REST API is implemented as Data-centric web service based on the Open Data Protocol or OData. The way these web services work, use each resource in the system is addressable by a specific URL that you pass off to the server.
Let us look at this in Internet Explorer in which SharePoint site is open.
Step 1 − If you are using Internet Explorer, go to Internet Explorer settings and on Content tab, select the settings for Feeds and Web Slices as shown in the screenshot below.
You will see the following dialog box. Make sure feed reading view is off and click OK.
Step 2 − Now let us change the URL to the site URL +/_api/web and press Enter.
Now you should get a view that looks like the following screenshot.
We want information about the current web or the current site. Therefore, the site URL +/_api is the base URL for the SharePoint 2013 REST API and web is our query. We want information about the current web.
We get an XML document back and if we scroll down, we will get information about our current web.
Next, if you want to know about the lists in the web, you can append the lists to your URL. Instead of information about an individual object, we will get a collection of information about all of the lists in the current site.
When we were using the browser, we were issuing get requests to the server, which means we want to retrieve information. However, we can also do the rest of the standard CRUD operations.
The SharePoint 2013 REST API does not expose metadata. Therefore, when we are working with it in Managed Code, we cannot use Visual Studio to generate a service proxy using the service reference dialog. Instead, we can use a type like the web client of the http web request object to send a request up to the server and just get the raw results back.
Whether those results are returned as XML or JSON are determined by the accept header we send along with the request.
If we get back XML then we can use LINQ to XML to retrieve the information out of the response we need for our application.
If we get back XML then we can use LINQ to XML to retrieve the information out of the response we need for our application.
If we get back JSON, then we can use one of the various JSON serializes to parse the JSON into .NET objects and then use that to retrieve the information we need.
If we get back JSON, then we can use one of the various JSON serializes to parse the JSON into .NET objects and then use that to retrieve the information we need.
When working with the REST API in JavaScript, we can use jQuery or the SP.RequestExecutor object to make the call up to the service. Just as in the Managed Code example, we can control whether we get back XML or JSON using the accept header. Since, we are working in JavaScript majority of times, we are going to want to get back JSON.
The one other thing to note is when you are building the URL to the service, we can use the _spPageContextInfo object to get the absolute URL from the site and then just append the service URL plus the query to it. This is because the REST API service does not expose metadata and you cannot create a service reference in Visual Studio, using the REST API in Managed Code is really a non-starter.
Let us take a look at calling the REST API from JavaScript by creating a new project.
Step 1 − Select App for SharePoint in middle pane and enter name for your project. Click OK.
Step 2 − Enter your site URL and select the SharePoint – hosted option and click Next. Click Finish.
Step 3 − Once the project is created, let us open the Default.aspx page, which is under Pages in Solution Explorer and add one button.
Here is the complete implementation of the Default.aspx file.
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint
components --%>
<%@ Page Inherits = ”Microsoft.SharePoint.WebPartPages.WebPartPage,
Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c” MasterPageFile = ”~masterurl/default.master”
Language = ”C#” %>
<%@ Register TagPrefix = ”Utilities” Namespace = ”Microsoft.SharePoint.Utilities”
Assembly = ”Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c” %>
<%@ Register TagPrefix = ”WebPartPages”
Namespace = ”Microsoft.SharePoint.WebPartPages” Assembly = ”Microsoft.SharePoint,
Version = 15.0.0.0, Culture = neutral, PublicKeyToken = 71e9bce111e9429c” %>
<%@ Register TagPrefix = ”SharePoint” Namespace = ”Microsoft.SharePoint.WebControls”
Assembly = ”Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c” %>
<%-- The markup and script in the following Content element will be placed in
the <head> of the page --%>
<asp:Content ContentPlaceHolderID = ”PlaceHolderAdditionalPageHead”
runat = ”server”>
<script type = ”text/javascript” src = ”../Scripts/jquery-1.9.1.min.js”></script>
<SharePoint:ScriptLink name = ”sp.js” runat = ”server” OnDemand = ”true”
LoadAfterUI = ”true” Localizable = ”false” />
<meta name = ”WebPartPageExpansion” content = ”full” />
<!–Add your CSS styles to the following file ->
<link rel = ”Stylesheet” type = ”text/css” href = ”../Content/App.css” />
<!–Add your JavaScript to the following file ->
<script type = ”text/javascript” src = ”../Scripts/App.js”></script>
</asp:Content>
<%-- The markup in the following Content element will be placed in the TitleArea
of the page --%>
<asp:Content ContentPlaceHolderID = ”PlaceHolderPageTitleInTitleArea”
runat = ”server”>
Page Title
</asp:Content>
<%-- The markup and script in the following Content element will be placed in
the <body> of the page --%>
<asp:Content ContentPlaceHolderID = ”PlaceHolderMain” runat = ”server”>
<div>
<p id = ”message”>
<!–The following content will be replaced with the user name when
you run the app – see App.js -> initializing...
</p>
<input id = ”loadButton” type = ”button” value = ”Load” />
</div>
</asp:Content>
Step 4 − Open the App.js file, which is under Script in Solution Explorer and replace it with the following code.
JQuery(document).ready(function () {
JQuery("#loadButton").click(usingLoad)
});
function usingLoad() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
context.load(web);
context.executeQueryAsync(success, fail);
function success() {
var message = jQuery("#message");
message.text(web.get_title());
message.append("<br/>");
message.append(lists.get_count());
}
function fail(sender, args) {
alert("Call failed. Error: " + args.get_message());
}
}
We are using jQuery to create the document.ready function. Here, we just want to attach the click event handler to the button. Hence, we have used the selector to get the loadButton and then we have added the click event-handler using Load.
So when we click the button, we want to do the same thing we did in the managed version of the demo, we want to show the Title of the web.
Step 5 − Publish your application and you will see the following file −
Step 6 − Drag this file to your SharePoint site apps page.
You will see the file JavaScriptDemo in the list.
Step 7 − Click on the Site Contents in the left pane and then select add an app. Click the JavaScriptDemo icon.
Step 8 − Click Trust it.
Step 9 − Now you will see your app. Click the app icon.
Step 10 − When you click the Load button, it will update the text.
You can see the updated text.
13 Lectures
3 hours
Darwish
124 Lectures
6.5 hours
JM Ekhteyari
44 Lectures
3.5 hours
Simon Sez IT
23 Lectures
1.5 hours
Sonic Performance
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2498,
"s": 2315,
"text": "In this chapter, we will be covering the REST APIs. This is not a traditional API, where we have a set of libraries that contain types and those types contain properties and methods."
},
{
"code": null,
"e": 2727,
"s": 2498,
"text": "The REST API is implemented as Data-centric web service based on the Open Data Protocol or OData. The way these web services work, use each resource in the system is addressable by a specific URL that you pass off to the server."
},
{
"code": null,
"e": 2802,
"s": 2727,
"text": "Let us look at this in Internet Explorer in which SharePoint site is open."
},
{
"code": null,
"e": 2979,
"s": 2802,
"text": "Step 1 − If you are using Internet Explorer, go to Internet Explorer settings and on Content tab, select the settings for Feeds and Web Slices as shown in the screenshot below."
},
{
"code": null,
"e": 3067,
"s": 2979,
"text": "You will see the following dialog box. Make sure feed reading view is off and click OK."
},
{
"code": null,
"e": 3146,
"s": 3067,
"text": "Step 2 − Now let us change the URL to the site URL +/_api/web and press Enter."
},
{
"code": null,
"e": 3214,
"s": 3146,
"text": "Now you should get a view that looks like the following screenshot."
},
{
"code": null,
"e": 3422,
"s": 3214,
"text": "We want information about the current web or the current site. Therefore, the site URL +/_api is the base URL for the SharePoint 2013 REST API and web is our query. We want information about the current web."
},
{
"code": null,
"e": 3520,
"s": 3422,
"text": "We get an XML document back and if we scroll down, we will get information about our current web."
},
{
"code": null,
"e": 3747,
"s": 3520,
"text": "Next, if you want to know about the lists in the web, you can append the lists to your URL. Instead of information about an individual object, we will get a collection of information about all of the lists in the current site."
},
{
"code": null,
"e": 3934,
"s": 3747,
"text": "When we were using the browser, we were issuing get requests to the server, which means we want to retrieve information. However, we can also do the rest of the standard CRUD operations."
},
{
"code": null,
"e": 4285,
"s": 3934,
"text": "The SharePoint 2013 REST API does not expose metadata. Therefore, when we are working with it in Managed Code, we cannot use Visual Studio to generate a service proxy using the service reference dialog. Instead, we can use a type like the web client of the http web request object to send a request up to the server and just get the raw results back."
},
{
"code": null,
"e": 4403,
"s": 4285,
"text": "Whether those results are returned as XML or JSON are determined by the accept header we send along with the request."
},
{
"code": null,
"e": 4527,
"s": 4403,
"text": "If we get back XML then we can use LINQ to XML to retrieve the information out of the response we need for our application."
},
{
"code": null,
"e": 4651,
"s": 4527,
"text": "If we get back XML then we can use LINQ to XML to retrieve the information out of the response we need for our application."
},
{
"code": null,
"e": 4814,
"s": 4651,
"text": "If we get back JSON, then we can use one of the various JSON serializes to parse the JSON into .NET objects and then use that to retrieve the information we need."
},
{
"code": null,
"e": 4977,
"s": 4814,
"text": "If we get back JSON, then we can use one of the various JSON serializes to parse the JSON into .NET objects and then use that to retrieve the information we need."
},
{
"code": null,
"e": 5313,
"s": 4977,
"text": "When working with the REST API in JavaScript, we can use jQuery or the SP.RequestExecutor object to make the call up to the service. Just as in the Managed Code example, we can control whether we get back XML or JSON using the accept header. Since, we are working in JavaScript majority of times, we are going to want to get back JSON."
},
{
"code": null,
"e": 5710,
"s": 5313,
"text": "The one other thing to note is when you are building the URL to the service, we can use the _spPageContextInfo object to get the absolute URL from the site and then just append the service URL plus the query to it. This is because the REST API service does not expose metadata and you cannot create a service reference in Visual Studio, using the REST API in Managed Code is really a non-starter."
},
{
"code": null,
"e": 5796,
"s": 5710,
"text": "Let us take a look at calling the REST API from JavaScript by creating a new project."
},
{
"code": null,
"e": 5889,
"s": 5796,
"text": "Step 1 − Select App for SharePoint in middle pane and enter name for your project. Click OK."
},
{
"code": null,
"e": 5990,
"s": 5889,
"text": "Step 2 − Enter your site URL and select the SharePoint – hosted option and click Next. Click Finish."
},
{
"code": null,
"e": 6125,
"s": 5990,
"text": "Step 3 − Once the project is created, let us open the Default.aspx page, which is under Pages in Solution Explorer and add one button."
},
{
"code": null,
"e": 6189,
"s": 6127,
"text": "Here is the complete implementation of the Default.aspx file."
},
{
"code": null,
"e": 8549,
"s": 6189,
"text": "<%-- The following 4 lines are ASP.NET directives needed when using SharePoint\n components --%>\n\n<%@ Page Inherits = ”Microsoft.SharePoint.WebPartPages.WebPartPage,\n Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,\n PublicKeyToken = 71e9bce111e9429c” MasterPageFile = ”~masterurl/default.master”\n Language = ”C#” %>\n\n<%@ Register TagPrefix = ”Utilities” Namespace = ”Microsoft.SharePoint.Utilities”\n Assembly = ”Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,\n PublicKeyToken = 71e9bce111e9429c” %>\n\n<%@ Register TagPrefix = ”WebPartPages”\n Namespace = ”Microsoft.SharePoint.WebPartPages” Assembly = ”Microsoft.SharePoint,\n Version = 15.0.0.0, Culture = neutral, PublicKeyToken = 71e9bce111e9429c” %>\n\n<%@ Register TagPrefix = ”SharePoint” Namespace = ”Microsoft.SharePoint.WebControls”\n Assembly = ”Microsoft.SharePoint, Version = 15.0.0.0, Culture = neutral,\n PublicKeyToken = 71e9bce111e9429c” %>\n\n<%-- The markup and script in the following Content element will be placed in\n the <head> of the page --%>\n\n<asp:Content ContentPlaceHolderID = ”PlaceHolderAdditionalPageHead”\n runat = ”server”>\n <script type = ”text/javascript” src = ”../Scripts/jquery-1.9.1.min.js”></script>\n <SharePoint:ScriptLink name = ”sp.js” runat = ”server” OnDemand = ”true”\n LoadAfterUI = ”true” Localizable = ”false” />\n <meta name = ”WebPartPageExpansion” content = ”full” />\n <!–Add your CSS styles to the following file ->\n <link rel = ”Stylesheet” type = ”text/css” href = ”../Content/App.css” />\n <!–Add your JavaScript to the following file ->\n <script type = ”text/javascript” src = ”../Scripts/App.js”></script>\n</asp:Content>\n\n<%-- The markup in the following Content element will be placed in the TitleArea\n of the page --%>\n\n<asp:Content ContentPlaceHolderID = ”PlaceHolderPageTitleInTitleArea”\n runat = ”server”>\n Page Title\n</asp:Content>\n\n<%-- The markup and script in the following Content element will be placed in\n the <body> of the page --%>\n\n<asp:Content ContentPlaceHolderID = ”PlaceHolderMain” runat = ”server”>\n <div>\n <p id = ”message”>\n <!–The following content will be replaced with the user name when\n you run the app – see App.js -> initializing...\n </p>\n <input id = ”loadButton” type = ”button” value = ”Load” />\n </div>\n</asp:Content>"
},
{
"code": null,
"e": 8663,
"s": 8549,
"text": "Step 4 − Open the App.js file, which is under Script in Solution Explorer and replace it with the following code."
},
{
"code": null,
"e": 9198,
"s": 8663,
"text": "JQuery(document).ready(function () {\n JQuery(\"#loadButton\").click(usingLoad)\n});\n\nfunction usingLoad() {\n var context = SP.ClientContext.get_current();\n var web = context.get_web();\n context.load(web);\n context.executeQueryAsync(success, fail);\n \n function success() {\n var message = jQuery(\"#message\");\n message.text(web.get_title());\n message.append(\"<br/>\");\n message.append(lists.get_count());\n }\n function fail(sender, args) {\n alert(\"Call failed. Error: \" + args.get_message());\n }\n}"
},
{
"code": null,
"e": 9439,
"s": 9198,
"text": "We are using jQuery to create the document.ready function. Here, we just want to attach the click event handler to the button. Hence, we have used the selector to get the loadButton and then we have added the click event-handler using Load."
},
{
"code": null,
"e": 9578,
"s": 9439,
"text": "So when we click the button, we want to do the same thing we did in the managed version of the demo, we want to show the Title of the web."
},
{
"code": null,
"e": 9650,
"s": 9578,
"text": "Step 5 − Publish your application and you will see the following file −"
},
{
"code": null,
"e": 9709,
"s": 9650,
"text": "Step 6 − Drag this file to your SharePoint site apps page."
},
{
"code": null,
"e": 9759,
"s": 9709,
"text": "You will see the file JavaScriptDemo in the list."
},
{
"code": null,
"e": 9871,
"s": 9759,
"text": "Step 7 − Click on the Site Contents in the left pane and then select add an app. Click the JavaScriptDemo icon."
},
{
"code": null,
"e": 9896,
"s": 9871,
"text": "Step 8 − Click Trust it."
},
{
"code": null,
"e": 9952,
"s": 9896,
"text": "Step 9 − Now you will see your app. Click the app icon."
},
{
"code": null,
"e": 10019,
"s": 9952,
"text": "Step 10 − When you click the Load button, it will update the text."
},
{
"code": null,
"e": 10049,
"s": 10019,
"text": "You can see the updated text."
},
{
"code": null,
"e": 10082,
"s": 10049,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 10091,
"s": 10082,
"text": " Darwish"
},
{
"code": null,
"e": 10127,
"s": 10091,
"text": "\n 124 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 10141,
"s": 10127,
"text": " JM Ekhteyari"
},
{
"code": null,
"e": 10176,
"s": 10141,
"text": "\n 44 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10190,
"s": 10176,
"text": " Simon Sez IT"
},
{
"code": null,
"e": 10225,
"s": 10190,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10244,
"s": 10225,
"text": " Sonic Performance"
},
{
"code": null,
"e": 10251,
"s": 10244,
"text": " Print"
},
{
"code": null,
"e": 10262,
"s": 10251,
"text": " Add Notes"
}
] |
Alternate casing a string in JavaScript
|
We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters from the original string converted to lowercase and all the lowercase characters converted to uppercase from the original string.
For example: If the string is −
const str = 'The Case OF tHis StrinG Will Be FLiPped';
Then the output should be −
const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';
The code for this will be −
const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
const flipCase = str => {
let newStr = '';
const margin = 32;
for(let i = 0; i < str.length; i++){
const curr = str[i];
if(isLowerCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
}else if(isUpperCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
}else{
newStr += curr;
};
};
return newStr;
};
console.log(flipCase(str));
The output in the console −
tHE cASE of ThIS sTRINg wILL bE flipped
|
[
{
"code": null,
"e": 1324,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters from the original string converted to lowercase and all the lowercase characters converted to uppercase from the original string."
},
{
"code": null,
"e": 1356,
"s": 1324,
"text": "For example: If the string is −"
},
{
"code": null,
"e": 1411,
"s": 1356,
"text": "const str = 'The Case OF tHis StrinG Will Be FLiPped';"
},
{
"code": null,
"e": 1439,
"s": 1411,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1497,
"s": 1439,
"text": "const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';"
},
{
"code": null,
"e": 1525,
"s": 1497,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2183,
"s": 1525,
"text": "const str = 'The Case OF tHis StrinG Will Be FLiPped';\nconst isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)<= 90;\nconst isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;\nconst flipCase = str => {\n let newStr = '';\n const margin = 32;\n for(let i = 0; i < str.length; i++){\n const curr = str[i];\n if(isLowerCase(curr)){\n newStr += String.fromCharCode(curr.charCodeAt(0) - margin);\n }else if(isUpperCase(curr)){\n newStr += String.fromCharCode(curr.charCodeAt(0) + margin);\n }else{\n newStr += curr;\n };\n };\n return newStr;\n};\nconsole.log(flipCase(str));"
},
{
"code": null,
"e": 2211,
"s": 2183,
"text": "The output in the console −"
},
{
"code": null,
"e": 2251,
"s": 2211,
"text": "tHE cASE of ThIS sTRINg wILL bE flipped"
}
] |
How to Visualize Multivariate Trajectory Confidence Intervals using Plotly R | by Marcus Richards Ph.D. | Towards Data Science
|
Any probabilistic regression approach in statistics or machine learning will result in a line chart together with associated confidence intervals, usually defined as two standard deviations around the mean. Although Plotly has many powerful charting tools for rendering charts in 2 or 3 dimensions, and can draw error bars or confidence intervals for 2D line charts, it does not have an option for rendering confidence intervals in 3D line or surface plots.
Many interesting probabilistic regression tasks are multivariate by nature; for example forecasting a data value z, over time t across a positional coordinate, x. The outcome of this forecast will be a 3D surface representing the expected value z at each point x at time t, together with an estimation of the associated error at every value point. This type of surface plot would be common in surface topology exploration where a grid of sensors captures data at every grid point within the target space. This grid would be well visualized in Plotly as a 3D surface plot of data value across all x, y coordinates, however Plotly does not render the confidence boundary across this surface.
Often the domain of the problem is limited to a trajectory through the target space, rather than a complete exploration of the entire domain. For example, imagine a rocket trajectory plotted with measurements of engine temperature at each latitude and longitude of flight. Temperature data is captured at each point against position, but the positional data is a subset of the entire space of meridians, being only measured along the trajectory of the rocket. This when modelled and visualised graphically shows as a line, as opposed to a surface, of temperature traversing through a trajectory in a 3D space of temperature, altitude and longitude. Plotly allows us to draw this trajectory, but it does not allow us easily to draw the upper and lower confidence intervals on this line. We could refactor the calculation to show temperature against altitude, as a 2D chart, but then we lose the spatial resolution and for example will not be able to distinguish the outbound rocket direction from the inbound, earthward, trajectory, crossing the same altitudes but at different times, and this will create problems with our regression analysis.
The chart shown is a rendering of simulated data representing three trajectories of sample data across the x, y plane, with z showing the data value at each point, together with a ribbon showing the upper and lower confidence limits. Looking directly down the z axis it can be seen that the confidence bands lie in the z plane, since errors are shown against data value, with the observed x and y observation points assumed to be known without error. This is the normal approach taken in regression analysis, where it is generally assumed that we can precisely obtain the measurement coordinates.
The R code used to create these plots uses the Plotly mesh3D chart type to build a surface of upward and downward pointing interlaced triangles that link together to form a continuous surface in the plane of the data values.
The method described is completely general and could be used to create any form of surface, for example to construct upper and lower bound surfaces on a 3D Plotly surface. The only limitation to the use of this is the complexity of the overlapping of surfaces which can become confusing to the eye when rendered in a flat image, rather that as a Plotly dynamic visualization.
#R code for 3D confidence error intervalsinstall.packages("plotly")library(plotly) # Generate Simulated Data Pointsx <- seq(-5,5, .1)y <- seq(0, 10, .1)y <- cbind(y, sin(y), cos(y)) # Generate Simulated Data Valuesz1 = sin(x+y[,1])z2 = sin((x+y[,1])/2.)z3 = sin((x+y[,1])/3.) z <- cbind(z1, z2, z3)# Generate Simulated Standard Deviationssd <- sqrt(abs(z) * .05) n = length(x)i = seq(0,n-1)# Create Plots for each of three simulated trajectoriesp <- plot_ly(type = 'scatter3d')for (index in 1:3){ p <- add_trace(p, x = x, y = y[,index], z = z[,index], mode = 'lines', line = list(width = 8, color=index)) p <- add_trace(p, type = 'mesh3d', # Setup triangle vertices x = c(x, x), y = c(y[,index], y[,index]), z = c(z[,index] - 2 * sd[,index], z[,index] + 2 * sd[,index]), # Create triangles i = c(i[1:n - 1], i[1:n - 1]), j = c(n + i[1:n - 1], n + i[2:n]) , k = c(n + i[2:n], i[2:n]), color = index )} #END
|
[
{
"code": null,
"e": 630,
"s": 172,
"text": "Any probabilistic regression approach in statistics or machine learning will result in a line chart together with associated confidence intervals, usually defined as two standard deviations around the mean. Although Plotly has many powerful charting tools for rendering charts in 2 or 3 dimensions, and can draw error bars or confidence intervals for 2D line charts, it does not have an option for rendering confidence intervals in 3D line or surface plots."
},
{
"code": null,
"e": 1320,
"s": 630,
"text": "Many interesting probabilistic regression tasks are multivariate by nature; for example forecasting a data value z, over time t across a positional coordinate, x. The outcome of this forecast will be a 3D surface representing the expected value z at each point x at time t, together with an estimation of the associated error at every value point. This type of surface plot would be common in surface topology exploration where a grid of sensors captures data at every grid point within the target space. This grid would be well visualized in Plotly as a 3D surface plot of data value across all x, y coordinates, however Plotly does not render the confidence boundary across this surface."
},
{
"code": null,
"e": 2464,
"s": 1320,
"text": "Often the domain of the problem is limited to a trajectory through the target space, rather than a complete exploration of the entire domain. For example, imagine a rocket trajectory plotted with measurements of engine temperature at each latitude and longitude of flight. Temperature data is captured at each point against position, but the positional data is a subset of the entire space of meridians, being only measured along the trajectory of the rocket. This when modelled and visualised graphically shows as a line, as opposed to a surface, of temperature traversing through a trajectory in a 3D space of temperature, altitude and longitude. Plotly allows us to draw this trajectory, but it does not allow us easily to draw the upper and lower confidence intervals on this line. We could refactor the calculation to show temperature against altitude, as a 2D chart, but then we lose the spatial resolution and for example will not be able to distinguish the outbound rocket direction from the inbound, earthward, trajectory, crossing the same altitudes but at different times, and this will create problems with our regression analysis."
},
{
"code": null,
"e": 3061,
"s": 2464,
"text": "The chart shown is a rendering of simulated data representing three trajectories of sample data across the x, y plane, with z showing the data value at each point, together with a ribbon showing the upper and lower confidence limits. Looking directly down the z axis it can be seen that the confidence bands lie in the z plane, since errors are shown against data value, with the observed x and y observation points assumed to be known without error. This is the normal approach taken in regression analysis, where it is generally assumed that we can precisely obtain the measurement coordinates."
},
{
"code": null,
"e": 3286,
"s": 3061,
"text": "The R code used to create these plots uses the Plotly mesh3D chart type to build a surface of upward and downward pointing interlaced triangles that link together to form a continuous surface in the plane of the data values."
},
{
"code": null,
"e": 3662,
"s": 3286,
"text": "The method described is completely general and could be used to create any form of surface, for example to construct upper and lower bound surfaces on a 3D Plotly surface. The only limitation to the use of this is the complexity of the overlapping of surfaces which can become confusing to the eye when rendered in a flat image, rather that as a Plotly dynamic visualization."
}
] |
Tryit Editor v3.7
|
Tryit: HTML base element
|
[] |
Get value for key from nested JSON object in JavaScript
|
Suppose, we have a nested JSON object like this −
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};
We are required to write a JavaScript function that takes in one such object as the first argument, and a key string as the second argument.
Our function should then return the value for the "value" property to which that particular key property belongs.
The code for this will be −
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};
const findByKey = (obj, key) => {
const arr = obj['prop'];
if(arr.length){
const result = arr.filter(el => {
return el['key'] === key;
});
if(result && result.length){
return result[0].value;
}
else{
return '';
}
}
}
console.log(findByKey(obj, 'BAR'));
And the output in the console will be −
Bar is bad, really bad
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "Suppose, we have a nested JSON object like this −"
},
{
"code": null,
"e": 1321,
"s": 1112,
"text": "const obj = {\n \"prop\": [\n {\n \"key\": \"FOO\",\n \"value\": \"Foo is wonderfull, foo is great\"\n },\n {\n \"key\": \"BAR\",\n \"value\": \"Bar is bad, really bad\"\n }\n ]\n};"
},
{
"code": null,
"e": 1462,
"s": 1321,
"text": "We are required to write a JavaScript function that takes in one such object as the first argument, and a key string as the second argument."
},
{
"code": null,
"e": 1576,
"s": 1462,
"text": "Our function should then return the value for the \"value\" property to which that particular key property belongs."
},
{
"code": null,
"e": 1604,
"s": 1576,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2138,
"s": 1604,
"text": "const obj = {\n \"prop\": [\n {\n \"key\": \"FOO\",\n \"value\": \"Foo is wonderfull, foo is great\"\n },\n {\n \"key\": \"BAR\",\n \"value\": \"Bar is bad, really bad\"\n }\n ]\n};\nconst findByKey = (obj, key) => {\n const arr = obj['prop'];\n if(arr.length){\n const result = arr.filter(el => {\n return el['key'] === key;\n });\n if(result && result.length){\n return result[0].value;\n }\n else{\n return '';\n }\n }\n}\nconsole.log(findByKey(obj, 'BAR'));"
},
{
"code": null,
"e": 2178,
"s": 2138,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2201,
"s": 2178,
"text": "Bar is bad, really bad"
}
] |
Spring Boot JdbcTemplate CRUD Operations Mysql - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials I am going to show you how to work with Spring Boot JdbcTemplate using MySql Database.
Technologies :
Spring Boot-1.5.10
Spring-Boot-Starter-jdbc
Java 8
MySql 5.5
Project Structure :
As part of this tutorials, I am going to implement a complete CRUD operations using Spring Boot JdbcTemplate.
Recommended : Spring JDBCTemplate Example
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>SpringBoot-JDBC-MySQL</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot-JDBC-MySQL</name>
<description>Demo project for Spring Boot JdbcTemplate</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Defining all necessary data source, authentication credentials.
# Database
server.port=8080
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.url: jdbc:mysql://localhost:3306/otp
spring.datasource.username: root
spring.datasource.password: 123456
Database Preparation :
Create your mysql database (otp) and create below item table under otp database.
CREATE TABLE `item` (
`id` INT(11) NULL DEFAULT NULL,
`name` VARCHAR(50) NULL DEFAULT NULL,
`category` VARCHAR(50) NULL DEFAULT NULL
)
ENGINE=InnoDB;
Created an item table, which represents all items and I am going to do all CRUD operations on this table.
Create Item Model to represent the above table.
package com.onlinetutorialspoint.model;
public class Item {
private int id;
private String name;
private String category;
public Item() {
}
public Item(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Creating Item Repository :
This is the key class of our example, under which all CRUD operations are happening.
package com.onlinetutorialspoint.repo;
import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class ItemRepository {
@Autowired
JdbcTemplate template;
/*Getting all Items from table*/
public List<Item> getAllItems(){
List<Item> items = template.query("select id, name,category from item",(result,rowNum)->new Item(result.getInt("id"),
result.getString("name"),result.getString("category")));
return items;
}
/*Getting a specific item by item id from table*/
public Item getItem(int itemId){
String query = "SELECT * FROM ITEM WHERE ID=?";
Item item = template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));
return item;
}
/*Adding an item into database table*/
public int addItem(int id,String name,String category){
String query = "INSERT INTO ITEM VALUES(?,?,?)";
return template.update(query,id,name,category);
}
/*delete an item from database*/
public int deleteItem(int id){
String query = "DELETE FROM ITEM WHERE ID =?";
return template.update(query,id);
}
}
Create RestController to provide an endpoint to access from outside.
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repo.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ItemController {
@Autowired
ItemRepository itemRepo;
@RequestMapping("/getAllItems")
@ResponseBody
public List<Item> getAllItems(){
return itemRepo.getAllItems();
}
@RequestMapping("/getItem")
@ResponseBody
public Item getItem(@RequestParam("itemId") int itemId){
return itemRepo.getItem(itemId);
}
@RequestMapping("/addItem")
@ResponseBody
public String addItem(@RequestParam("id") int id,@RequestParam("name") String name,
@RequestParam("category") String category){
if(itemRepo.addItem(id,name,category) >= 1){
return "Item Added Successfully";
}else{
return "Something went wrong !";
}
}
@RequestMapping("/deteteItem")
@ResponseBody
public String deteteItem(@RequestParam("itemId") int itemId){
if(itemRepo.deleteItem(itemId) >= 1){
return "Item Deleted Successfully";
}else{
return "Something went wrong !";
}
}
}
Application.java
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
mvn clean install
mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-21 07:08:32.553 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 5416 (E:\work\SpringBoot-JDBC-MyS
QL\target\classes started by Lenovo in E:\work\SpringBoot-JDBC-MySQL)
2018-02-21 07:08:32.559 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default
2018-02-21 07:08:32.644 INFO 5416 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebAp
plicationContext@1ac73b13: startup date [Wed Feb 21 07:08:32 IST 2018]; root of context hierarchy
2018-02-21 07:08:35.791 INFO 5416 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-21 07:08:35.818 INFO 5416 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-21 07:08:35.820 INFO 5416 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-21 07:08:36.100 INFO 5416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-21 07:08:36.101 INFO 5416 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3463 ms
2018-02-21 07:08:36.440 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-21 07:08:36.450 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-21 07:08:36.451 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-21 07:08:36.452 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-21 07:08:36.453 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-21 07:08:37.674 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotatio
nConfigEmbeddedWebApplicationContext@1ac73b13: startup date [Wed Feb 21 07:08:32 IST 2018]; root of context hierarchy
2018-02-21 07:08:37.814 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getItem]}" onto public com.onlinetutorialspoint.model.Item com.onlinetu
torialspoint.controller.ItemController.getItem(int)
2018-02-21 07:08:37.816 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getAllItems]}" onto public java.util.List<com.onlinetutorialspoint.mode
l.Item> com.onlinetutorialspoint.controller.ItemController.getAllItems()
2018-02-21 07:08:37.817 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/addItem]}" onto public java.lang.String com.onlinetutorialspoint.contro
ller.ItemController.addItem(int,java.lang.String,java.lang.String)
2018-02-21 07:08:37.818 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/deteteItem]}" onto public java.lang.String com.onlinetutorialspoint.con
troller.ItemController.deteteItem(int)
2018-02-21 07:08:37.824 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.
Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-02-21 07:08:37.826 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servl
et.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-02-21 07:08:37.898 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.
servlet.resource.ResourceHttpRequestHandler]
2018-02-21 07:08:37.899 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.
resource.ResourceHttpRequestHandler]
2018-02-21 07:08:37.988 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.
web.servlet.resource.ResourceHttpRequestHandler]
2018-02-21 07:08:38.393 INFO 5416 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-21 07:08:38.520 INFO 5416 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-21 07:08:38.528 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : Started Application in 6.638 seconds (JVM running for 16.176)
Access the Application :
Getting All Items :
http://localhost:8080/getAllItems
Add an Item :
http://localhost:8080/addItem?id=4&name=Refrigerator&category=Refrigerator
Getting All Items After adding :
http://localhost:8080/getAllItems
Delete an Item from the list :
References :
Spring JDBC Template Example
JDBC Template Docs
Happy Learning 🙂
SpringBoot JDBCTemplate MySQL
File size: 88 KB
Downloads: 3360
Spring Boot Redis Data Example CRUD Operations
Spring boot exception handling rest service (CRUD) operations
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot How to change the Tomcat to Jetty Server
Spring JdbcTemplate CRUD Application
Spring Boot In Memory Basic Authentication Security
How to Create own Spring Boot Error Page
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot Hazelcast Cache Example
Spring Boot Security MySQL Database Integration Example
Spring Boot H2 Database + JDBC Template Example
Spring Boot Batch Example Csv to Database
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
Spring boot exception handling rest service (CRUD) operations
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot How to change the Tomcat to Jetty Server
Spring JdbcTemplate CRUD Application
Spring Boot In Memory Basic Authentication Security
How to Create own Spring Boot Error Page
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot Hazelcast Cache Example
Spring Boot Security MySQL Database Integration Example
Spring Boot H2 Database + JDBC Template Example
Spring Boot Batch Example Csv to Database
Spring Boot MongoDB + Spring Data Example
sanoj
July 17, 2018 at 8:14 pm - Reply
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jul 17 20:13:58 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Required int parameter ‘itemId’ is not present
sanoj
July 17, 2018 at 8:14 pm - Reply
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jul 17 20:13:58 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Required int parameter ‘itemId’ is not present
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jul 17 20:13:58 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Required int parameter ‘itemId’ is not present
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 503,
"s": 398,
"text": "In this tutorials I am going to show you how to work with Spring Boot JdbcTemplate using MySql Database."
},
{
"code": null,
"e": 518,
"s": 503,
"text": "Technologies :"
},
{
"code": null,
"e": 537,
"s": 518,
"text": "Spring Boot-1.5.10"
},
{
"code": null,
"e": 562,
"s": 537,
"text": "Spring-Boot-Starter-jdbc"
},
{
"code": null,
"e": 569,
"s": 562,
"text": "Java 8"
},
{
"code": null,
"e": 579,
"s": 569,
"text": "MySql 5.5"
},
{
"code": null,
"e": 599,
"s": 579,
"text": "Project Structure :"
},
{
"code": null,
"e": 709,
"s": 599,
"text": "As part of this tutorials, I am going to implement a complete CRUD operations using Spring Boot JdbcTemplate."
},
{
"code": null,
"e": 751,
"s": 709,
"text": "Recommended : Spring JDBCTemplate Example"
},
{
"code": null,
"e": 2413,
"s": 751,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot-JDBC-MySQL</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>SpringBoot-JDBC-MySQL</name>\n <description>Demo project for Spring Boot JdbcTemplate</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.10.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-jdbc</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n"
},
{
"code": null,
"e": 2477,
"s": 2413,
"text": "Defining all necessary data source, authentication credentials."
},
{
"code": null,
"e": 2687,
"s": 2477,
"text": "# Database\nserver.port=8080\nspring.datasource.driver-class-name: com.mysql.jdbc.Driver\nspring.datasource.url: jdbc:mysql://localhost:3306/otp\nspring.datasource.username: root\nspring.datasource.password: 123456"
},
{
"code": null,
"e": 2710,
"s": 2687,
"text": "Database Preparation :"
},
{
"code": null,
"e": 2791,
"s": 2710,
"text": "Create your mysql database (otp) and create below item table under otp database."
},
{
"code": null,
"e": 2948,
"s": 2791,
"text": "CREATE TABLE `item` (\n `id` INT(11) NULL DEFAULT NULL,\n `name` VARCHAR(50) NULL DEFAULT NULL,\n `category` VARCHAR(50) NULL DEFAULT NULL\n)\nENGINE=InnoDB;\n"
},
{
"code": null,
"e": 3054,
"s": 2948,
"text": "Created an item table, which represents all items and I am going to do all CRUD operations on this table."
},
{
"code": null,
"e": 3102,
"s": 3054,
"text": "Create Item Model to represent the above table."
},
{
"code": null,
"e": 3808,
"s": 3102,
"text": "package com.onlinetutorialspoint.model;\n\npublic class Item {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n"
},
{
"code": null,
"e": 3835,
"s": 3808,
"text": "Creating Item Repository :"
},
{
"code": null,
"e": 3920,
"s": 3835,
"text": "This is the key class of our example, under which all CRUD operations are happening."
},
{
"code": null,
"e": 5328,
"s": 3920,
"text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n@Repository\npublic class ItemRepository {\n\n @Autowired\n JdbcTemplate template;\n\n /*Getting all Items from table*/\n public List<Item> getAllItems(){\n List<Item> items = template.query(\"select id, name,category from item\",(result,rowNum)->new Item(result.getInt(\"id\"),\n result.getString(\"name\"),result.getString(\"category\")));\n return items;\n }\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n String query = \"SELECT * FROM ITEM WHERE ID=?\";\n Item item = template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));\n\n return item;\n }\n /*Adding an item into database table*/\n public int addItem(int id,String name,String category){\n String query = \"INSERT INTO ITEM VALUES(?,?,?)\";\n return template.update(query,id,name,category);\n }\n /*delete an item from database*/\n public int deleteItem(int id){\n String query = \"DELETE FROM ITEM WHERE ID =?\";\n return template.update(query,id);\n }\n}\n"
},
{
"code": null,
"e": 5397,
"s": 5328,
"text": "Create RestController to provide an endpoint to access from outside."
},
{
"code": null,
"e": 6744,
"s": 5397,
"text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n@RestController\npublic class ItemController {\n @Autowired\n ItemRepository itemRepo;\n\n @RequestMapping(\"/getAllItems\")\n @ResponseBody\n public List<Item> getAllItems(){\n return itemRepo.getAllItems();\n }\n\n @RequestMapping(\"/getItem\")\n @ResponseBody\n public Item getItem(@RequestParam(\"itemId\") int itemId){\n return itemRepo.getItem(itemId);\n }\n\n @RequestMapping(\"/addItem\")\n @ResponseBody\n public String addItem(@RequestParam(\"id\") int id,@RequestParam(\"name\") String name,\n @RequestParam(\"category\") String category){\n if(itemRepo.addItem(id,name,category) >= 1){\n return \"Item Added Successfully\";\n }else{\n return \"Something went wrong !\";\n }\n }\n @RequestMapping(\"/deteteItem\")\n @ResponseBody\n public String deteteItem(@RequestParam(\"itemId\") int itemId){\n if(itemRepo.deleteItem(itemId) >= 1){\n return \"Item Deleted Successfully\";\n }else{\n return \"Something went wrong !\";\n }\n }\n}\n"
},
{
"code": null,
"e": 6761,
"s": 6744,
"text": "Application.java"
},
{
"code": null,
"e": 7070,
"s": 6761,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n"
},
{
"code": null,
"e": 12655,
"s": 7070,
"text": "mvn clean install\nmvn spring-boot:run\n\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v1.5.10.RELEASE)\n\n2018-02-21 07:08:32.553 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 5416 (E:\\work\\SpringBoot-JDBC-MyS\nQL\\target\\classes started by Lenovo in E:\\work\\SpringBoot-JDBC-MySQL)\n2018-02-21 07:08:32.559 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default\n2018-02-21 07:08:32.644 INFO 5416 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebAp\nplicationContext@1ac73b13: startup date [Wed Feb 21 07:08:32 IST 2018]; root of context hierarchy\n2018-02-21 07:08:35.791 INFO 5416 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)\n2018-02-21 07:08:35.818 INFO 5416 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2018-02-21 07:08:35.820 INFO 5416 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27\n2018-02-21 07:08:36.100 INFO 5416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2018-02-21 07:08:36.101 INFO 5416 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3463 ms\n2018-02-21 07:08:36.440 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]\n2018-02-21 07:08:36.450 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]\n2018-02-21 07:08:36.451 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]\n2018-02-21 07:08:36.452 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]\n2018-02-21 07:08:36.453 INFO 5416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]\n2018-02-21 07:08:37.674 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotatio\nnConfigEmbeddedWebApplicationContext@1ac73b13: startup date [Wed Feb 21 07:08:32 IST 2018]; root of context hierarchy\n2018-02-21 07:08:37.814 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/getItem]}\" onto public com.onlinetutorialspoint.model.Item com.onlinetu\ntorialspoint.controller.ItemController.getItem(int)\n2018-02-21 07:08:37.816 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/getAllItems]}\" onto public java.util.List<com.onlinetutorialspoint.mode\nl.Item> com.onlinetutorialspoint.controller.ItemController.getAllItems()\n2018-02-21 07:08:37.817 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/addItem]}\" onto public java.lang.String com.onlinetutorialspoint.contro\nller.ItemController.addItem(int,java.lang.String,java.lang.String)\n2018-02-21 07:08:37.818 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/deteteItem]}\" onto public java.lang.String com.onlinetutorialspoint.con\ntroller.ItemController.deteteItem(int)\n2018-02-21 07:08:37.824 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.\nMap<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n2018-02-21 07:08:37.826 INFO 5416 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error],produces=[text/html]}\" onto public org.springframework.web.servl\net.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)\n2018-02-21 07:08:37.898 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.\nservlet.resource.ResourceHttpRequestHandler]\n2018-02-21 07:08:37.899 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.\nresource.ResourceHttpRequestHandler]\n2018-02-21 07:08:37.988 INFO 5416 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.\nweb.servlet.resource.ResourceHttpRequestHandler]\n2018-02-21 07:08:38.393 INFO 5416 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup\n2018-02-21 07:08:38.520 INFO 5416 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)\n2018-02-21 07:08:38.528 INFO 5416 --- [ main] com.onlinetutorialspoint.Application : Started Application in 6.638 seconds (JVM running for 16.176)\n"
},
{
"code": null,
"e": 12680,
"s": 12655,
"text": "Access the Application :"
},
{
"code": null,
"e": 12700,
"s": 12680,
"text": "Getting All Items :"
},
{
"code": null,
"e": 12734,
"s": 12700,
"text": "http://localhost:8080/getAllItems"
},
{
"code": null,
"e": 12748,
"s": 12734,
"text": "Add an Item :"
},
{
"code": null,
"e": 12823,
"s": 12748,
"text": "http://localhost:8080/addItem?id=4&name=Refrigerator&category=Refrigerator"
},
{
"code": null,
"e": 12856,
"s": 12823,
"text": "Getting All Items After adding :"
},
{
"code": null,
"e": 12890,
"s": 12856,
"text": "http://localhost:8080/getAllItems"
},
{
"code": null,
"e": 12921,
"s": 12890,
"text": "Delete an Item from the list :"
},
{
"code": null,
"e": 12934,
"s": 12921,
"text": "References :"
},
{
"code": null,
"e": 12963,
"s": 12934,
"text": "Spring JDBC Template Example"
},
{
"code": null,
"e": 12982,
"s": 12963,
"text": "JDBC Template Docs"
},
{
"code": null,
"e": 12999,
"s": 12982,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 13066,
"s": 12999,
"text": "\n\nSpringBoot JDBCTemplate MySQL\n\nFile size: 88 KB\nDownloads: 3360\n"
},
{
"code": null,
"e": 13768,
"s": 13066,
"text": "\nSpring Boot Redis Data Example CRUD Operations\nSpring boot exception handling rest service (CRUD) operations\nHow to use Spring Boot Random Port\nHow to set Spring Boot SetTimeZone\nSpring Boot How to change the Tomcat to Jetty Server\nSpring JdbcTemplate CRUD Application\nSpring Boot In Memory Basic Authentication Security\nHow to Create own Spring Boot Error Page\nSpring Boot Environment Properties reading based on activeprofile\nMicroServices Spring Boot Eureka Server Example\nSpring Boot Hazelcast Cache Example\nSpring Boot Security MySQL Database Integration Example\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot Batch Example Csv to Database\nSpring Boot MongoDB + Spring Data Example\n"
},
{
"code": null,
"e": 13815,
"s": 13768,
"text": "Spring Boot Redis Data Example CRUD Operations"
},
{
"code": null,
"e": 13877,
"s": 13815,
"text": "Spring boot exception handling rest service (CRUD) operations"
},
{
"code": null,
"e": 13912,
"s": 13877,
"text": "How to use Spring Boot Random Port"
},
{
"code": null,
"e": 13947,
"s": 13912,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 14000,
"s": 13947,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 14037,
"s": 14000,
"text": "Spring JdbcTemplate CRUD Application"
},
{
"code": null,
"e": 14089,
"s": 14037,
"text": "Spring Boot In Memory Basic Authentication Security"
},
{
"code": null,
"e": 14130,
"s": 14089,
"text": "How to Create own Spring Boot Error Page"
},
{
"code": null,
"e": 14196,
"s": 14130,
"text": "Spring Boot Environment Properties reading based on activeprofile"
},
{
"code": null,
"e": 14244,
"s": 14196,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 14280,
"s": 14244,
"text": "Spring Boot Hazelcast Cache Example"
},
{
"code": null,
"e": 14336,
"s": 14280,
"text": "Spring Boot Security MySQL Database Integration Example"
},
{
"code": null,
"e": 14384,
"s": 14336,
"text": "Spring Boot H2 Database + JDBC Template Example"
},
{
"code": null,
"e": 14426,
"s": 14384,
"text": "Spring Boot Batch Example Csv to Database"
},
{
"code": null,
"e": 14468,
"s": 14426,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 14771,
"s": 14468,
"text": "\n\n\n\n\n\nsanoj\nJuly 17, 2018 at 8:14 pm - Reply \n\nWhitelabel Error Page\nThis application has no explicit mapping for /error, so you are seeing this as a fallback.\nTue Jul 17 20:13:58 IST 2018\nThere was an unexpected error (type=Bad Request, status=400).\nRequired int parameter ‘itemId’ is not present\n\n\n\n\n"
},
{
"code": null,
"e": 15072,
"s": 14771,
"text": "\n\n\n\n\nsanoj\nJuly 17, 2018 at 8:14 pm - Reply \n\nWhitelabel Error Page\nThis application has no explicit mapping for /error, so you are seeing this as a fallback.\nTue Jul 17 20:13:58 IST 2018\nThere was an unexpected error (type=Bad Request, status=400).\nRequired int parameter ‘itemId’ is not present\n\n\n\n"
},
{
"code": null,
"e": 15185,
"s": 15072,
"text": "Whitelabel Error Page\nThis application has no explicit mapping for /error, so you are seeing this as a fallback."
},
{
"code": null,
"e": 15323,
"s": 15185,
"text": "Tue Jul 17 20:13:58 IST 2018\nThere was an unexpected error (type=Bad Request, status=400).\nRequired int parameter ‘itemId’ is not present"
},
{
"code": null,
"e": 15329,
"s": 15327,
"text": "Δ"
},
{
"code": null,
"e": 15356,
"s": 15329,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 15383,
"s": 15356,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 15417,
"s": 15383,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 15458,
"s": 15417,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 15503,
"s": 15458,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 15541,
"s": 15503,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 15575,
"s": 15541,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 15606,
"s": 15575,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 15640,
"s": 15606,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 15673,
"s": 15640,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 15706,
"s": 15673,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 15746,
"s": 15706,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 15771,
"s": 15746,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 15802,
"s": 15771,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 15826,
"s": 15802,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 15872,
"s": 15826,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 15895,
"s": 15872,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 15922,
"s": 15895,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 15968,
"s": 15922,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 16008,
"s": 15968,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 16037,
"s": 16008,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 16071,
"s": 16037,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 16101,
"s": 16071,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 16137,
"s": 16101,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 16170,
"s": 16137,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 16203,
"s": 16170,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 16247,
"s": 16203,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 16281,
"s": 16247,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 16313,
"s": 16281,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 16341,
"s": 16313,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 16372,
"s": 16341,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 16413,
"s": 16372,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 16447,
"s": 16413,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 16472,
"s": 16447,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 16506,
"s": 16472,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 16542,
"s": 16506,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 16588,
"s": 16542,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 16639,
"s": 16588,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 16681,
"s": 16639,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 16712,
"s": 16681,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 16735,
"s": 16712,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 16765,
"s": 16735,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 16795,
"s": 16765,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 16844,
"s": 16795,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 16878,
"s": 16844,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 16911,
"s": 16878,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 16940,
"s": 16911,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 16972,
"s": 16940,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 17009,
"s": 16972,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 17038,
"s": 17009,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 17067,
"s": 17038,
"text": " Spring Boot – MockMvc JUnit"
}
] |
Create a fully fledged, professional API with Flask in Python — Part 1 | by Mike Huls | Towards Data Science
|
An application without an API is much like a restaurant without waiters. In restaurants you don’t have to communicate with the kitchen and wait for your order to enjoy a meal. In the same way a website doesn’t have to know how to communicate with your database for example. Like a waiter, our API receives an order from our website: ‘I’d like some user statistics with a side of meta data”. The API then checks the order (are you allowed to have that data?), convinces our database (the chef) to cook him up some tasty information, waits for the database to finish and finally returns the data to the website.
An API allows two (or more) services to talk to each other in a decoupled way. The most common example is an API that handles communication between a website and a database. It provides access, convenience, security and extra functionalities. Let’s take a look at look a short example of each of these points.
Imagine you’ve created a Python program called pixelcounter.py. It reads an image file and counts the number of pixels. At the moment you put your image file on a USB, walk to the computer that pixelcounter.py is on, put the image on the computer and load it up in pixelcounter.py to finally start counting.This works, only thing is: we’re programmers. We don’t have time to put stuff on USB sticks, let alone walk to something other than the coffee machine! A nice solution would be to put the API and pixelcounter.py on a server. That way people can send images to be counted.. Easy!
API’s also provide a lot of convenience. In order to send an email just send the receiver, subject and message to an API. You don’t need to understand how and SMTP works if you can just send your data to the API.
Using an API can also provide extra functionality. One example is that you can count which user requested what data. That way you can limit usage, check out which functionalities people are most interested in, what functionalities don’t get used at all or charge users per request.
An API allows two programs to talk to each other in a secure way. For a website like Facebook to retrieves your friends it needs to get that data from a database. You don’t want another person to get your personal data. That’s where an API comes in; it checks who makes the request and whether that person is allowed to get that data.
In this article we’ll start creating an API that’ll allows us to do all the thing described above. In this part we’ll focus on setting up our project, getting some basic functionality working and testing our routes. If you see any terms you’re unfamiliar with, check out the glossary at the bottom of this page.
Follow along these steps to create a project with all the necessary dependencies, Then we’ll create a controller that will handle requests on a route.
Create your root folder: the folder that will contain the project. In this example we’ll use c:/my_root_folder
Creating a virtual environment can help you keep your installed packages in a neat bundle. More information about understanding and creating venvs in this article. Here’s how to do it for this proejct:
Navigate to your root folder and execute this code. python -m venv c:/my_root_folder/venvThis will create a folder that will house all of your installed packages. Don’t forget:
activate your environment before installing packages by navigating to c:/my_root_folder/venv/scripts and executing activate. Now you are in your environment and can install packages in here
execute your script by calling c:/my_root_folder/venv/Scripts/python.exe. We’ll get into it more later
We’re going to need two packages so we’ll need to install Flask and flask-restful. pip install Flask flask-restful
Next step: create some folders in which we can put our different parts of te API, namely our config, routes and controllers: mkdir config routes controllers
Our project is set up, time to build our API! create a file called main.py in our root folder and give it the following content
from flask import Flaskfrom flask_restful import Apiapp = Flask(__name__)api = Api(app)if __name__ == "__main__": # start up api app.run(port=5000, debug=True)
What’s happening here?:This script imports all the required packages and instantiates an app and api. It then runs the app on localhost port 5000. Execute your script:c:/my_root_folder/venv/Scripts/python.exe c:/my_root_folder/main.py`You’ll notice that your script is running but is not stopping. The server we’ve created is continuously listening for requests. Lets give it something to listen to.
We’d like to go to localhost:5000/test and have the API do something when we navigate to that page or POST something to that location. In order to to this we need our API to listen to a route, namely /test.
from flask import Flaskfrom flask_restful import Apifrom controllers.testController import TestControllerapp = Flask(__name__)api = Api(app)api.add_resource(TestController, '/test')if __name__ == "__main__": # start up api app.run(port=5000, debug=True)
The code above is almost identical to the first piece of code. As you can see it’s easy to listen to a route. This happens in line 7: api.add_resource(TestController, ‘/test’)It listens to requests at /test and passes the request to our TestController, which is a class that we import on line 3. Let’s create this controller. Create c:/my_root_folder/controllers/testController.py with this content:
from flask_restful import Resource, requestclass TestController(Resource): def get(self): return { "message": "get: hello from the testcontroller" }
There are multiple ways of requesting data from an API. You can send GET request of POST requests. A GET is for retrieving data, like retrieving my profile picture. POST requests are for submitting data like submitting a comment. There are many more types, which we’ll get into in the next part. First let’s test a simple API.
The TestController above implements a get method that handles get request that has been passed to the controller. Right now we’ll just return a simple message.
Open a browser and navigate to localhost:5000/test. If all went well you’ll see the message we’ve define in our controller.
Congratulations on creating your first API! Our new API is up and running but it’s pretty dumb. In the next part we’ll implement some more functionalities like different types of request, security with JSON web tokens and a connection to a database. Follow me to stay tuned!
— Mike
Some terms, explained
API = Application Programming Interface. Allows you to connect two programs
request = A command you send to an API. You’re requesting it to do something
response = Something the API gives back; data, an error or a status
route = A path on a website. It’s the bold part in www.medium.com/@mikehuls or test.com/this/is/a/path
status code = A code that represents a stat of the api. Everybody has heard of 404: not found!
|
[
{
"code": null,
"e": 782,
"s": 172,
"text": "An application without an API is much like a restaurant without waiters. In restaurants you don’t have to communicate with the kitchen and wait for your order to enjoy a meal. In the same way a website doesn’t have to know how to communicate with your database for example. Like a waiter, our API receives an order from our website: ‘I’d like some user statistics with a side of meta data”. The API then checks the order (are you allowed to have that data?), convinces our database (the chef) to cook him up some tasty information, waits for the database to finish and finally returns the data to the website."
},
{
"code": null,
"e": 1092,
"s": 782,
"text": "An API allows two (or more) services to talk to each other in a decoupled way. The most common example is an API that handles communication between a website and a database. It provides access, convenience, security and extra functionalities. Let’s take a look at look a short example of each of these points."
},
{
"code": null,
"e": 1678,
"s": 1092,
"text": "Imagine you’ve created a Python program called pixelcounter.py. It reads an image file and counts the number of pixels. At the moment you put your image file on a USB, walk to the computer that pixelcounter.py is on, put the image on the computer and load it up in pixelcounter.py to finally start counting.This works, only thing is: we’re programmers. We don’t have time to put stuff on USB sticks, let alone walk to something other than the coffee machine! A nice solution would be to put the API and pixelcounter.py on a server. That way people can send images to be counted.. Easy!"
},
{
"code": null,
"e": 1891,
"s": 1678,
"text": "API’s also provide a lot of convenience. In order to send an email just send the receiver, subject and message to an API. You don’t need to understand how and SMTP works if you can just send your data to the API."
},
{
"code": null,
"e": 2173,
"s": 1891,
"text": "Using an API can also provide extra functionality. One example is that you can count which user requested what data. That way you can limit usage, check out which functionalities people are most interested in, what functionalities don’t get used at all or charge users per request."
},
{
"code": null,
"e": 2508,
"s": 2173,
"text": "An API allows two programs to talk to each other in a secure way. For a website like Facebook to retrieves your friends it needs to get that data from a database. You don’t want another person to get your personal data. That’s where an API comes in; it checks who makes the request and whether that person is allowed to get that data."
},
{
"code": null,
"e": 2820,
"s": 2508,
"text": "In this article we’ll start creating an API that’ll allows us to do all the thing described above. In this part we’ll focus on setting up our project, getting some basic functionality working and testing our routes. If you see any terms you’re unfamiliar with, check out the glossary at the bottom of this page."
},
{
"code": null,
"e": 2971,
"s": 2820,
"text": "Follow along these steps to create a project with all the necessary dependencies, Then we’ll create a controller that will handle requests on a route."
},
{
"code": null,
"e": 3082,
"s": 2971,
"text": "Create your root folder: the folder that will contain the project. In this example we’ll use c:/my_root_folder"
},
{
"code": null,
"e": 3284,
"s": 3082,
"text": "Creating a virtual environment can help you keep your installed packages in a neat bundle. More information about understanding and creating venvs in this article. Here’s how to do it for this proejct:"
},
{
"code": null,
"e": 3461,
"s": 3284,
"text": "Navigate to your root folder and execute this code. python -m venv c:/my_root_folder/venvThis will create a folder that will house all of your installed packages. Don’t forget:"
},
{
"code": null,
"e": 3651,
"s": 3461,
"text": "activate your environment before installing packages by navigating to c:/my_root_folder/venv/scripts and executing activate. Now you are in your environment and can install packages in here"
},
{
"code": null,
"e": 3754,
"s": 3651,
"text": "execute your script by calling c:/my_root_folder/venv/Scripts/python.exe. We’ll get into it more later"
},
{
"code": null,
"e": 3869,
"s": 3754,
"text": "We’re going to need two packages so we’ll need to install Flask and flask-restful. pip install Flask flask-restful"
},
{
"code": null,
"e": 4026,
"s": 3869,
"text": "Next step: create some folders in which we can put our different parts of te API, namely our config, routes and controllers: mkdir config routes controllers"
},
{
"code": null,
"e": 4154,
"s": 4026,
"text": "Our project is set up, time to build our API! create a file called main.py in our root folder and give it the following content"
},
{
"code": null,
"e": 4320,
"s": 4154,
"text": "from flask import Flaskfrom flask_restful import Apiapp = Flask(__name__)api = Api(app)if __name__ == \"__main__\": # start up api app.run(port=5000, debug=True)"
},
{
"code": null,
"e": 4720,
"s": 4320,
"text": "What’s happening here?:This script imports all the required packages and instantiates an app and api. It then runs the app on localhost port 5000. Execute your script:c:/my_root_folder/venv/Scripts/python.exe c:/my_root_folder/main.py`You’ll notice that your script is running but is not stopping. The server we’ve created is continuously listening for requests. Lets give it something to listen to."
},
{
"code": null,
"e": 4927,
"s": 4720,
"text": "We’d like to go to localhost:5000/test and have the API do something when we navigate to that page or POST something to that location. In order to to this we need our API to listen to a route, namely /test."
},
{
"code": null,
"e": 5187,
"s": 4927,
"text": "from flask import Flaskfrom flask_restful import Apifrom controllers.testController import TestControllerapp = Flask(__name__)api = Api(app)api.add_resource(TestController, '/test')if __name__ == \"__main__\": # start up api app.run(port=5000, debug=True)"
},
{
"code": null,
"e": 5587,
"s": 5187,
"text": "The code above is almost identical to the first piece of code. As you can see it’s easy to listen to a route. This happens in line 7: api.add_resource(TestController, ‘/test’)It listens to requests at /test and passes the request to our TestController, which is a class that we import on line 3. Let’s create this controller. Create c:/my_root_folder/controllers/testController.py with this content:"
},
{
"code": null,
"e": 5764,
"s": 5587,
"text": "from flask_restful import Resource, requestclass TestController(Resource): def get(self): return { \"message\": \"get: hello from the testcontroller\" }"
},
{
"code": null,
"e": 6091,
"s": 5764,
"text": "There are multiple ways of requesting data from an API. You can send GET request of POST requests. A GET is for retrieving data, like retrieving my profile picture. POST requests are for submitting data like submitting a comment. There are many more types, which we’ll get into in the next part. First let’s test a simple API."
},
{
"code": null,
"e": 6251,
"s": 6091,
"text": "The TestController above implements a get method that handles get request that has been passed to the controller. Right now we’ll just return a simple message."
},
{
"code": null,
"e": 6375,
"s": 6251,
"text": "Open a browser and navigate to localhost:5000/test. If all went well you’ll see the message we’ve define in our controller."
},
{
"code": null,
"e": 6650,
"s": 6375,
"text": "Congratulations on creating your first API! Our new API is up and running but it’s pretty dumb. In the next part we’ll implement some more functionalities like different types of request, security with JSON web tokens and a connection to a database. Follow me to stay tuned!"
},
{
"code": null,
"e": 6657,
"s": 6650,
"text": "— Mike"
},
{
"code": null,
"e": 6679,
"s": 6657,
"text": "Some terms, explained"
},
{
"code": null,
"e": 6755,
"s": 6679,
"text": "API = Application Programming Interface. Allows you to connect two programs"
},
{
"code": null,
"e": 6832,
"s": 6755,
"text": "request = A command you send to an API. You’re requesting it to do something"
},
{
"code": null,
"e": 6900,
"s": 6832,
"text": "response = Something the API gives back; data, an error or a status"
},
{
"code": null,
"e": 7003,
"s": 6900,
"text": "route = A path on a website. It’s the bold part in www.medium.com/@mikehuls or test.com/this/is/a/path"
}
] |
Count Inversions in an array
|
The inversions of an array indicate; how many changes are required to convert the array into its sorted form. When an array is already sorted, it needs 0 inversions, and in another case, the number of inversions will be maximum, if the array is reversed.
To solve this problem, we will follow the Merge sort approach to reduce the time complexity, and make it in Divide and Conquer algorithm.
Input:
A sequence of numbers. (1, 5, 6, 4, 20).
Output:
The number of inversions required to arrange the numbers into ascending order.
Here the number of inversions are 2.
First inversion: (1, 5, 4, 6, 20)
Second inversion: (1, 4, 5, 6, 20)
merge(array, tempArray, left, mid, right)
Input: Two arrays, who have merged, the left, right and the mid indexes.
Output: The merged array in sorted order.
Begin
i := left, j := mid, k := right
count := 0
while i <= mid -1 and j <= right, do
if array[i] <= array[j], then
tempArray[k] := array[i]
increase i and k by 1
else
tempArray[k] := array[j]
increase j and k by 1
count := count + (mid - i)
done
while left part of the array has some extra element, do
tempArray[k] := array[i]
increase i and k by 1
done
while right part of the array has some extra element, do
tempArray[k] := array[j]
increase j and k by 1
done
return count
End
mergeSort(array, tempArray, left, right)
Input: Given an array and temporary array, left and right index of the array.
Output − Number of inversions after sorting.
Begin
count := 0
if right > left, then
mid := (right + left)/2
count := mergeSort(array, tempArray, left, mid)
count := count + mergeSort(array, tempArray, mid+1, right)
count := count + merge(array, tempArray, left, mid+1, right)
return count
End
#include <iostream>
using namespace std;
int merge(intarr[], int temp[], int left, int mid, int right) {
int i, j, k;
int count = 0;
i = left; //i to locate first array location
j = mid; //i to locate second array location
k = left; //i to locate merged array location
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) { //when left item is less than right item
temp[k++] = arr[i++];
}else{
temp[k++] = arr[j++];
count += (mid - i); //find how many convertion is performed
}
}
while (i <= mid - 1) //if first list has remaining item, add them in the list
temp[k++] = arr[i++];
while (j <= right) //if second list has remaining item, add them in the list
temp[k++] = arr[j++];
for (i=left; i <= right; i++)
arr[i] = temp[i]; //store temp Array to main array
return count;
}
intmergeSort(intarr[], int temp[], int left, int right) {
int mid, count = 0;
if (right > left) {
mid = (right + left)/2; //find mid index of the array
count = mergeSort(arr, temp, left, mid); //merge sort left sub array
count += mergeSort(arr, temp, mid+1, right); //merge sort right sub array
count += merge(arr, temp, left, mid+1, right); //merge two sub arrays
}
return count;
}
intarrInversion(intarr[], int n) {
int temp[n];
return mergeSort(arr, temp, 0, n - 1);
}
int main() {
intarr[] = {1, 5, 6, 4, 20};
int n = 5;
cout<< "Number of inversions are "<<arrInversion(arr, n);
}
Number of inversions are 2
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "The inversions of an array indicate; how many changes are required to convert the array into its sorted form. When an array is already sorted, it needs 0 inversions, and in another case, the number of inversions will be maximum, if the array is reversed."
},
{
"code": null,
"e": 1455,
"s": 1317,
"text": "To solve this problem, we will follow the Merge sort approach to reduce the time complexity, and make it in Divide and Conquer algorithm."
},
{
"code": null,
"e": 1696,
"s": 1455,
"text": "Input:\nA sequence of numbers. (1, 5, 6, 4, 20).\nOutput:\nThe number of inversions required to arrange the numbers into ascending order.\nHere the number of inversions are 2.\nFirst inversion: (1, 5, 4, 6, 20)\nSecond inversion: (1, 4, 5, 6, 20)"
},
{
"code": null,
"e": 1738,
"s": 1696,
"text": "merge(array, tempArray, left, mid, right)"
},
{
"code": null,
"e": 1811,
"s": 1738,
"text": "Input: Two arrays, who have merged, the left, right and the mid indexes."
},
{
"code": null,
"e": 1853,
"s": 1811,
"text": "Output: The merged array in sorted order."
},
{
"code": null,
"e": 2445,
"s": 1853,
"text": "Begin\n i := left, j := mid, k := right\n count := 0\n while i <= mid -1 and j <= right, do\n if array[i] <= array[j], then\n tempArray[k] := array[i]\n increase i and k by 1\n else\n tempArray[k] := array[j]\n increase j and k by 1\n count := count + (mid - i)\n done\n\n while left part of the array has some extra element, do\n tempArray[k] := array[i]\n increase i and k by 1\n done\n\n while right part of the array has some extra element, do\n tempArray[k] := array[j]\n increase j and k by 1\n done\n\n return count\nEnd"
},
{
"code": null,
"e": 2486,
"s": 2445,
"text": "mergeSort(array, tempArray, left, right)"
},
{
"code": null,
"e": 2564,
"s": 2486,
"text": "Input: Given an array and temporary array, left and right index of the array."
},
{
"code": null,
"e": 2609,
"s": 2564,
"text": "Output − Number of inversions after sorting."
},
{
"code": null,
"e": 2890,
"s": 2609,
"text": "Begin\n count := 0\n if right > left, then\n mid := (right + left)/2\n count := mergeSort(array, tempArray, left, mid)\n count := count + mergeSort(array, tempArray, mid+1, right)\n count := count + merge(array, tempArray, left, mid+1, right)\n return count\nEnd"
},
{
"code": null,
"e": 4479,
"s": 2890,
"text": "#include <iostream>\nusing namespace std;\n\nint merge(intarr[], int temp[], int left, int mid, int right) {\n int i, j, k;\n int count = 0;\n \n i = left; //i to locate first array location\n j = mid; //i to locate second array location\n k = left; //i to locate merged array location\n\n while ((i <= mid - 1) && (j <= right)) {\n if (arr[i] <= arr[j]) { //when left item is less than right item\n temp[k++] = arr[i++];\n }else{\n temp[k++] = arr[j++];\n count += (mid - i); //find how many convertion is performed\n }\n }\n\n while (i <= mid - 1) //if first list has remaining item, add them in the list\n temp[k++] = arr[i++];\n\n while (j <= right) //if second list has remaining item, add them in the list\n temp[k++] = arr[j++];\n \n for (i=left; i <= right; i++)\n arr[i] = temp[i]; //store temp Array to main array\n return count;\n}\n\nintmergeSort(intarr[], int temp[], int left, int right) {\n int mid, count = 0;\n\n if (right > left) {\n mid = (right + left)/2; //find mid index of the array\n count = mergeSort(arr, temp, left, mid); //merge sort left sub array\n count += mergeSort(arr, temp, mid+1, right); //merge sort right sub array\n \n count += merge(arr, temp, left, mid+1, right); //merge two sub arrays\n }\n return count;\n}\n\nintarrInversion(intarr[], int n) {\n int temp[n];\n return mergeSort(arr, temp, 0, n - 1);\n}\n\nint main() {\n intarr[] = {1, 5, 6, 4, 20};\n int n = 5;\n cout<< \"Number of inversions are \"<<arrInversion(arr, n);\n}"
},
{
"code": null,
"e": 4506,
"s": 4479,
"text": "Number of inversions are 2"
}
] |
How to get the nth percentile of a Pandas series?
|
A percentile is a term used in statistics to express how a score compares to other scores in the same set. In this program, we have to find nth percentile of a Pandas series.
Step 1: Define a Pandas series.
Step 2: Input percentile value.
Step 3: Calculate the percentile.
Step 4: Print the percentile.
import pandas as pd
series = pd.Series([10,20,30,40,50])
print("Series:\n", series)
n = int(input("Enter the percentile you want to calculate: "))
n = n/100
percentile = series.quantile(n)
print("The {} percentile of the given series is: {}".format(n*100, percentile))
Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Enter the percentile you want to calculate: 50
The 50.0 percentile of the given series is: 30.0
The quantile function in the Pandas library takes values only between 0 and 1 as parameters. Therefore, we have to divide the percentile value by 100 before passing it to the quantile function.
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "A percentile is a term used in statistics to express how a score compares to other scores in the same set. In this program, we have to find nth percentile of a Pandas series."
},
{
"code": null,
"e": 1365,
"s": 1237,
"text": "Step 1: Define a Pandas series.\nStep 2: Input percentile value.\nStep 3: Calculate the percentile.\nStep 4: Print the percentile."
},
{
"code": null,
"e": 1637,
"s": 1365,
"text": "import pandas as pd\n\nseries = pd.Series([10,20,30,40,50])\nprint(\"Series:\\n\", series)\n\nn = int(input(\"Enter the percentile you want to calculate: \"))\nn = n/100\n\npercentile = series.quantile(n)\nprint(\"The {} percentile of the given series is: {}\".format(n*100, percentile))"
},
{
"code": null,
"e": 1794,
"s": 1637,
"text": "Series:\n0 10\n1 20\n2 30\n3 40\n4 50\ndtype: int64\nEnter the percentile you want to calculate: 50\nThe 50.0 percentile of the given series is: 30.0"
},
{
"code": null,
"e": 1988,
"s": 1794,
"text": "The quantile function in the Pandas library takes values only between 0 and 1 as parameters. Therefore, we have to divide the percentile value by 100 before passing it to the quantile function."
}
] |
Quick and Easy Explanation of Logistic Regression | by Renu Khandelwal | Towards Data Science
|
It is a predictive algorithm using independent variables to predict the dependent variable, just like Linear Regression, but with a difference that the dependent variable should be categorical variable.
Independent variables can be numeric or categorical variables, but the dependent variable will always be categorical
Logistic regression is a statistical model that uses Logistic function to model the conditional probability.
For binary regression, we calculate the conditional probability of the dependent variable Y, given independent variable X
It can be written as P(Y=1|X) or P(Y=0|X)
This is read as the conditional probability of Y=1, given X or conditional probability of Y=0, given X.
P(Y |X) is approximated as a sigmoid function applied to a linear combination of input features
An example of logistic regression can be to find if a person will default their credit card payment or not. The probability of a person defaulting their credit card payment can be based on the pending credit card balance and income etc.
hence, we can write P(default=yes|balance)
when the P(default=yes)≥0.5, then we say the person will default their payment.
When the P(default=yes)<0.4, then we say the person will NOT default their payment.
The probability will always range between 0 and 1. In the case of binary classification, the probability of defaulting payment and not defaulting payment will sum up to 1
Logistic Regression can be used for binary classification or multi-class classification.
Binary classification is when we have two possible outcomes like a person is infected with COVID-19 or is not infected with COVID-19. In multi-class classification, we have multiple outcomes like the person may have the flu or an allergy, or cold or COVID-19.
No outliers in the data. An outlier can be identified by analyzing the independent variables
No correlation (multi-collinearity) between the independent variables.
Logistic regression uses logit function, also referred to as log-odds; it is the logarithm of odds. The odds ratio is the ratio of odds of an event A in the presence of the event B and the odds of event A in the absence of event B.
P is the probability that event Y occurs. P(Y=1)
P/(1-P) is the odds ratio
θ is a parameters of length m
Logit function estimates probabilities between 0 and 1, and hence logistic regression is a non-linear transformation that looks like S- function shown below.
The parameter “θ” of the logistic function can be estimated using the maximum likelihood estimation(MLE) framework. MLE searches for the parameters that best fit the joint probability if the independent variables X.
MLE will give us values for parameter “θ” that would maximize the probability close to 1 for the person who would default their payment and a number close to 0 for all individuals who would not default their payment.
A confusion matrix is a table that tells us how many actual values and predicted values exist for different classes predicted by the model. Also referred to as the Error matrix.
Explaining the key terms
True Positive: When a female is pregnant, and we predicted that she is pregnant
True Negative: When a male is not pregnant, and we predicted that he is not pregnant
False Negative: When a female is pregnant, but we predict that she is not pregnant. Also called Type 2 error.
False Positive: A male cannot be pregnant, but we predict he is pregnant. Also called Type 1 error
Data can be downloaded from here
Importing required libraries
import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_split%matplotlib inline
Reading the data
Download the data from the link and save it in a CSV file and add the headers.
dataset=pd.read_csv("iris.csv")dataset.info()
displaying a few rows from the dataset
dataset.head(5)
Data analysis using visualization
Visualize the data to get a better understanding of the independent and dependent variables
sns.boxplot(x="class",y="petal length",data=dataset)plt.show()
Scatterplot of different classes of iris using petal length and petal width
sns.scatterplot(x='petal length', y='petal width', hue="class", data=dataset)
Scatterplot of different classes of iris using sepal length and sepal width
sns.scatterplot(x='sepal length', y='sepal width', hue="class", data=dataset)
Encode the class of the iris from categorical to a numeric value
The target variable is a string representing the class of the iris plant. We encode the categorical string data to the numeric value for the model to understand
from sklearn.preprocessing import LabelEncoderle= LabelEncoder()y_encoded=le.fit_transform(y)
Printing the encoded value for the target variable.
y_encoded
We have a multi-class classification problem as we have three distinct values for the class of iris plant
Split dataset into train and test dataset
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test= train_test_split(X,y_encoded,test_size=0.2)
We are training the dataset for multi-class classification using logistic regression
from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state=0).fit(X_train, y_train)
Predict the class of the iris for the test data
y_pred=clf.predict(X_test)
Evaluate the performance of the Logistic Regression Model
Use the confusion matrix to evaluate the performance for the multi-class classification
from sklearn.metrics import confusion_matrixcnf_matrix=confusion_matrix(y_test, y_pred, labels=[0,1,2])cnf_matrix
Ths output does not help much, so we inverse transform the numeric target variable back to the original class name
y_pred_orig= le.inverse_transform(y_pred)
We also write a function to display the confusion matrix in a more readable format
def plot_confusion_matrix(cm, classes, title='Confusion Matrix', cmap=plt.cm.Greens): import itertools print('Confusion Matrix') plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) fmt = '.2f' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")plt.ylabel('Actual label') plt.xlabel('Predicted label') plt.tight_layout()
Displaying the confusion matrix
plt.figure()plot_confusion_matrix(cnf_matrix, classes=le.classes_, title='Confusion matrixfor Iris test data')
Logistic regression is used for binary or multi-class classification, and the target variable always has to be categorical.
|
[
{
"code": null,
"e": 374,
"s": 171,
"text": "It is a predictive algorithm using independent variables to predict the dependent variable, just like Linear Regression, but with a difference that the dependent variable should be categorical variable."
},
{
"code": null,
"e": 491,
"s": 374,
"text": "Independent variables can be numeric or categorical variables, but the dependent variable will always be categorical"
},
{
"code": null,
"e": 600,
"s": 491,
"text": "Logistic regression is a statistical model that uses Logistic function to model the conditional probability."
},
{
"code": null,
"e": 722,
"s": 600,
"text": "For binary regression, we calculate the conditional probability of the dependent variable Y, given independent variable X"
},
{
"code": null,
"e": 764,
"s": 722,
"text": "It can be written as P(Y=1|X) or P(Y=0|X)"
},
{
"code": null,
"e": 868,
"s": 764,
"text": "This is read as the conditional probability of Y=1, given X or conditional probability of Y=0, given X."
},
{
"code": null,
"e": 964,
"s": 868,
"text": "P(Y |X) is approximated as a sigmoid function applied to a linear combination of input features"
},
{
"code": null,
"e": 1201,
"s": 964,
"text": "An example of logistic regression can be to find if a person will default their credit card payment or not. The probability of a person defaulting their credit card payment can be based on the pending credit card balance and income etc."
},
{
"code": null,
"e": 1244,
"s": 1201,
"text": "hence, we can write P(default=yes|balance)"
},
{
"code": null,
"e": 1324,
"s": 1244,
"text": "when the P(default=yes)≥0.5, then we say the person will default their payment."
},
{
"code": null,
"e": 1408,
"s": 1324,
"text": "When the P(default=yes)<0.4, then we say the person will NOT default their payment."
},
{
"code": null,
"e": 1579,
"s": 1408,
"text": "The probability will always range between 0 and 1. In the case of binary classification, the probability of defaulting payment and not defaulting payment will sum up to 1"
},
{
"code": null,
"e": 1668,
"s": 1579,
"text": "Logistic Regression can be used for binary classification or multi-class classification."
},
{
"code": null,
"e": 1928,
"s": 1668,
"text": "Binary classification is when we have two possible outcomes like a person is infected with COVID-19 or is not infected with COVID-19. In multi-class classification, we have multiple outcomes like the person may have the flu or an allergy, or cold or COVID-19."
},
{
"code": null,
"e": 2021,
"s": 1928,
"text": "No outliers in the data. An outlier can be identified by analyzing the independent variables"
},
{
"code": null,
"e": 2092,
"s": 2021,
"text": "No correlation (multi-collinearity) between the independent variables."
},
{
"code": null,
"e": 2324,
"s": 2092,
"text": "Logistic regression uses logit function, also referred to as log-odds; it is the logarithm of odds. The odds ratio is the ratio of odds of an event A in the presence of the event B and the odds of event A in the absence of event B."
},
{
"code": null,
"e": 2373,
"s": 2324,
"text": "P is the probability that event Y occurs. P(Y=1)"
},
{
"code": null,
"e": 2399,
"s": 2373,
"text": "P/(1-P) is the odds ratio"
},
{
"code": null,
"e": 2429,
"s": 2399,
"text": "θ is a parameters of length m"
},
{
"code": null,
"e": 2587,
"s": 2429,
"text": "Logit function estimates probabilities between 0 and 1, and hence logistic regression is a non-linear transformation that looks like S- function shown below."
},
{
"code": null,
"e": 2803,
"s": 2587,
"text": "The parameter “θ” of the logistic function can be estimated using the maximum likelihood estimation(MLE) framework. MLE searches for the parameters that best fit the joint probability if the independent variables X."
},
{
"code": null,
"e": 3020,
"s": 2803,
"text": "MLE will give us values for parameter “θ” that would maximize the probability close to 1 for the person who would default their payment and a number close to 0 for all individuals who would not default their payment."
},
{
"code": null,
"e": 3198,
"s": 3020,
"text": "A confusion matrix is a table that tells us how many actual values and predicted values exist for different classes predicted by the model. Also referred to as the Error matrix."
},
{
"code": null,
"e": 3223,
"s": 3198,
"text": "Explaining the key terms"
},
{
"code": null,
"e": 3303,
"s": 3223,
"text": "True Positive: When a female is pregnant, and we predicted that she is pregnant"
},
{
"code": null,
"e": 3388,
"s": 3303,
"text": "True Negative: When a male is not pregnant, and we predicted that he is not pregnant"
},
{
"code": null,
"e": 3498,
"s": 3388,
"text": "False Negative: When a female is pregnant, but we predict that she is not pregnant. Also called Type 2 error."
},
{
"code": null,
"e": 3597,
"s": 3498,
"text": "False Positive: A male cannot be pregnant, but we predict he is pregnant. Also called Type 1 error"
},
{
"code": null,
"e": 3630,
"s": 3597,
"text": "Data can be downloaded from here"
},
{
"code": null,
"e": 3659,
"s": 3630,
"text": "Importing required libraries"
},
{
"code": null,
"e": 3824,
"s": 3659,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_split%matplotlib inline"
},
{
"code": null,
"e": 3841,
"s": 3824,
"text": "Reading the data"
},
{
"code": null,
"e": 3920,
"s": 3841,
"text": "Download the data from the link and save it in a CSV file and add the headers."
},
{
"code": null,
"e": 3966,
"s": 3920,
"text": "dataset=pd.read_csv(\"iris.csv\")dataset.info()"
},
{
"code": null,
"e": 4005,
"s": 3966,
"text": "displaying a few rows from the dataset"
},
{
"code": null,
"e": 4021,
"s": 4005,
"text": "dataset.head(5)"
},
{
"code": null,
"e": 4055,
"s": 4021,
"text": "Data analysis using visualization"
},
{
"code": null,
"e": 4147,
"s": 4055,
"text": "Visualize the data to get a better understanding of the independent and dependent variables"
},
{
"code": null,
"e": 4210,
"s": 4147,
"text": "sns.boxplot(x=\"class\",y=\"petal length\",data=dataset)plt.show()"
},
{
"code": null,
"e": 4286,
"s": 4210,
"text": "Scatterplot of different classes of iris using petal length and petal width"
},
{
"code": null,
"e": 4364,
"s": 4286,
"text": "sns.scatterplot(x='petal length', y='petal width', hue=\"class\", data=dataset)"
},
{
"code": null,
"e": 4440,
"s": 4364,
"text": "Scatterplot of different classes of iris using sepal length and sepal width"
},
{
"code": null,
"e": 4518,
"s": 4440,
"text": "sns.scatterplot(x='sepal length', y='sepal width', hue=\"class\", data=dataset)"
},
{
"code": null,
"e": 4583,
"s": 4518,
"text": "Encode the class of the iris from categorical to a numeric value"
},
{
"code": null,
"e": 4744,
"s": 4583,
"text": "The target variable is a string representing the class of the iris plant. We encode the categorical string data to the numeric value for the model to understand"
},
{
"code": null,
"e": 4838,
"s": 4744,
"text": "from sklearn.preprocessing import LabelEncoderle= LabelEncoder()y_encoded=le.fit_transform(y)"
},
{
"code": null,
"e": 4890,
"s": 4838,
"text": "Printing the encoded value for the target variable."
},
{
"code": null,
"e": 4900,
"s": 4890,
"text": "y_encoded"
},
{
"code": null,
"e": 5006,
"s": 4900,
"text": "We have a multi-class classification problem as we have three distinct values for the class of iris plant"
},
{
"code": null,
"e": 5048,
"s": 5006,
"text": "Split dataset into train and test dataset"
},
{
"code": null,
"e": 5178,
"s": 5048,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test= train_test_split(X,y_encoded,test_size=0.2)"
},
{
"code": null,
"e": 5263,
"s": 5178,
"text": "We are training the dataset for multi-class classification using logistic regression"
},
{
"code": null,
"e": 5377,
"s": 5263,
"text": "from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state=0).fit(X_train, y_train)"
},
{
"code": null,
"e": 5425,
"s": 5377,
"text": "Predict the class of the iris for the test data"
},
{
"code": null,
"e": 5452,
"s": 5425,
"text": "y_pred=clf.predict(X_test)"
},
{
"code": null,
"e": 5510,
"s": 5452,
"text": "Evaluate the performance of the Logistic Regression Model"
},
{
"code": null,
"e": 5598,
"s": 5510,
"text": "Use the confusion matrix to evaluate the performance for the multi-class classification"
},
{
"code": null,
"e": 5712,
"s": 5598,
"text": "from sklearn.metrics import confusion_matrixcnf_matrix=confusion_matrix(y_test, y_pred, labels=[0,1,2])cnf_matrix"
},
{
"code": null,
"e": 5827,
"s": 5712,
"text": "Ths output does not help much, so we inverse transform the numeric target variable back to the original class name"
},
{
"code": null,
"e": 5869,
"s": 5827,
"text": "y_pred_orig= le.inverse_transform(y_pred)"
},
{
"code": null,
"e": 5952,
"s": 5869,
"text": "We also write a function to display the confusion matrix in a more readable format"
},
{
"code": null,
"e": 6694,
"s": 5952,
"text": "def plot_confusion_matrix(cm, classes, title='Confusion Matrix', cmap=plt.cm.Greens): import itertools print('Confusion Matrix') plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) fmt = '.2f' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")plt.ylabel('Actual label') plt.xlabel('Predicted label') plt.tight_layout()"
},
{
"code": null,
"e": 6726,
"s": 6694,
"text": "Displaying the confusion matrix"
},
{
"code": null,
"e": 6858,
"s": 6726,
"text": "plt.figure()plot_confusion_matrix(cnf_matrix, classes=le.classes_, title='Confusion matrixfor Iris test data')"
}
] |
Count of subarrays of size K with average at least M - GeeksforGeeks
|
14 Sep, 2021
Given an array arr[] consisting of N integers and two positive integers K and M, the task is to find the number of subarrays of size K whose average is at least M.
Examples:
Input: arr[] = {2, 3, 3, 4, 4, 4, 5, 6, 6}, K = 3, M = 4Output: 4Explanation:Below are the subarrays of size K(= 3) whose average is at least M(= 4) as:
arr[3, 5]: The average is 4 which is at least M(= 4).arr[4, 6]: The average is 4.33 which is at least M(= 4).arr[5, 7]: The average is 5 which is at least M(= 4).arr[6, 8]: The average is 5.66 which is at least M(= 4).
arr[3, 5]: The average is 4 which is at least M(= 4).
arr[4, 6]: The average is 4.33 which is at least M(= 4).
arr[5, 7]: The average is 5 which is at least M(= 4).
arr[6, 8]: The average is 5.66 which is at least M(= 4).
Therefore, the count of the subarray is given by 4.
Input: arr[] = {3, 6, 3, 2, 1, 3, 9] K = 2, M = 4Output: 3
Approach: The given problem can be solved by using the Two Pointers and Sliding Window Technique. Follow the steps below to solve the given problem:
Initialize a variable, say count as 0 that stores the count of all possible subarrays.
Initialize a variable, say sum as 0 that stores the sum of elements of the subarray of size K.
Find the sum of the first K array elements and store it in the variable sum. If the value of sum is at least M*K, then increment the value of count by 1.
Traverse the given array arr[] over the range [K, N – 1] using the variable i and perform the following steps:Add the value of arr[i] to the variable sum and subtract the value of arr[i – K] from the sum.If the value of sum is at least M*K, then increment the value of count by 1.
Add the value of arr[i] to the variable sum and subtract the value of arr[i – K] from the sum.
If the value of sum is at least M*K, then increment the value of count by 1.
After completing the above steps, print the value of count as the resultant count of subarrays.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <iostream>using namespace std; // Function to count the subarrays of// size K having average at least Mint countSubArrays(int arr[], int N, int K, int M){ // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < N; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count;} // Driver Codeint main(){ int arr[] = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; int N = sizeof(arr) / sizeof(arr[0]); cout << countSubArrays(arr, N, K, M); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Driver Code public static void main(String[] args) { int[] arr = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; System.out.println(countSubArrays(arr, K, M)); } // Function to count the subarrays of // size K having average at least M public static int countSubArrays(int[] arr, int K, int M) { // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < arr.length; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; }} // This code is contributed by Kdheeraj.
# Python 3 code for the above approach # Function to count the subarrays of# size K having average at least Mdef countSubArrays(arr, N, K, M): # Stores the resultant count of # subarray count = 0 # Stores the sum of subarrays of # size K sum = 0 # Add the values of first K elements # to the sum for i in range(K): sum += arr[i] # Increment the count if the # current subarray is valid if sum >= K*M: count += 1 # Traverse the given array for i in range(K, N): # Find the updated sum sum += (arr[i] - arr[i - K]) # Check if current subarray # is valid or not if sum >= K*M: count += 1 # Return the count of subarrays return count # Driver Codeif __name__ == '__main__': arr = [3, 6, 3, 2, 1, 3, 9] K = 2 M = 4 N = len(arr) count = countSubArrays(arr, N, K, M) print(count) # This code is contributed by Kdheeraj.
// C# program for the above approach using System; public class GFG{ // Driver Code public static void Main(String[] args) { int[] arr = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; Console.WriteLine(countSubArrays(arr, K, M)); } // Function to count the subarrays of // size K having average at least M public static int countSubArrays(int[] arr, int K, int M) { // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < arr.Length; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; }} // This code is contributed by AnkThon
<script> // JavaScript Program to implement // the above approach // Function to count the subarrays of // size K having average at least M function countSubArrays(arr, N, K, M) { // Stores the resultant count of // subarray let count = 0; // Stores the sum of subarrays of // size K let sum = 0; // Add the values of first K elements // to the sum for (let i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (let i = K; i < N; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; } // Driver Code let arr = [3, 6, 3, 2, 1, 3, 9]; let K = 2, M = 4; let N = arr.length; document.write(countSubArrays(arr, N, K, M)); // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(N)Auxiliary Space: O(1)
Kdheeraj
lokeshpotta20
ankthon
sliding-window
subarray
subarray-sum
two-pointer-algorithm
Arrays
Mathematical
sliding-window
two-pointer-algorithm
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Window Sliding Technique
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24593,
"s": 24429,
"text": "Given an array arr[] consisting of N integers and two positive integers K and M, the task is to find the number of subarrays of size K whose average is at least M."
},
{
"code": null,
"e": 24603,
"s": 24593,
"text": "Examples:"
},
{
"code": null,
"e": 24756,
"s": 24603,
"text": "Input: arr[] = {2, 3, 3, 4, 4, 4, 5, 6, 6}, K = 3, M = 4Output: 4Explanation:Below are the subarrays of size K(= 3) whose average is at least M(= 4) as:"
},
{
"code": null,
"e": 24975,
"s": 24756,
"text": "arr[3, 5]: The average is 4 which is at least M(= 4).arr[4, 6]: The average is 4.33 which is at least M(= 4).arr[5, 7]: The average is 5 which is at least M(= 4).arr[6, 8]: The average is 5.66 which is at least M(= 4)."
},
{
"code": null,
"e": 25029,
"s": 24975,
"text": "arr[3, 5]: The average is 4 which is at least M(= 4)."
},
{
"code": null,
"e": 25086,
"s": 25029,
"text": "arr[4, 6]: The average is 4.33 which is at least M(= 4)."
},
{
"code": null,
"e": 25140,
"s": 25086,
"text": "arr[5, 7]: The average is 5 which is at least M(= 4)."
},
{
"code": null,
"e": 25197,
"s": 25140,
"text": "arr[6, 8]: The average is 5.66 which is at least M(= 4)."
},
{
"code": null,
"e": 25249,
"s": 25197,
"text": "Therefore, the count of the subarray is given by 4."
},
{
"code": null,
"e": 25308,
"s": 25249,
"text": "Input: arr[] = {3, 6, 3, 2, 1, 3, 9] K = 2, M = 4Output: 3"
},
{
"code": null,
"e": 25457,
"s": 25308,
"text": "Approach: The given problem can be solved by using the Two Pointers and Sliding Window Technique. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 25544,
"s": 25457,
"text": "Initialize a variable, say count as 0 that stores the count of all possible subarrays."
},
{
"code": null,
"e": 25639,
"s": 25544,
"text": "Initialize a variable, say sum as 0 that stores the sum of elements of the subarray of size K."
},
{
"code": null,
"e": 25793,
"s": 25639,
"text": "Find the sum of the first K array elements and store it in the variable sum. If the value of sum is at least M*K, then increment the value of count by 1."
},
{
"code": null,
"e": 26074,
"s": 25793,
"text": "Traverse the given array arr[] over the range [K, N – 1] using the variable i and perform the following steps:Add the value of arr[i] to the variable sum and subtract the value of arr[i – K] from the sum.If the value of sum is at least M*K, then increment the value of count by 1."
},
{
"code": null,
"e": 26169,
"s": 26074,
"text": "Add the value of arr[i] to the variable sum and subtract the value of arr[i – K] from the sum."
},
{
"code": null,
"e": 26246,
"s": 26169,
"text": "If the value of sum is at least M*K, then increment the value of count by 1."
},
{
"code": null,
"e": 26342,
"s": 26246,
"text": "After completing the above steps, print the value of count as the resultant count of subarrays."
},
{
"code": null,
"e": 26393,
"s": 26342,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26397,
"s": 26393,
"text": "C++"
},
{
"code": null,
"e": 26402,
"s": 26397,
"text": "Java"
},
{
"code": null,
"e": 26410,
"s": 26402,
"text": "Python3"
},
{
"code": null,
"e": 26413,
"s": 26410,
"text": "C#"
},
{
"code": null,
"e": 26424,
"s": 26413,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to count the subarrays of// size K having average at least Mint countSubArrays(int arr[], int N, int K, int M){ // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < N; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count;} // Driver Codeint main(){ int arr[] = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; int N = sizeof(arr) / sizeof(arr[0]); cout << countSubArrays(arr, N, K, M); return 0;}",
"e": 27489,
"s": 26424,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Driver Code public static void main(String[] args) { int[] arr = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; System.out.println(countSubArrays(arr, K, M)); } // Function to count the subarrays of // size K having average at least M public static int countSubArrays(int[] arr, int K, int M) { // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < arr.length; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; }} // This code is contributed by Kdheeraj.",
"e": 28765,
"s": 27489,
"text": null
},
{
"code": "# Python 3 code for the above approach # Function to count the subarrays of# size K having average at least Mdef countSubArrays(arr, N, K, M): # Stores the resultant count of # subarray count = 0 # Stores the sum of subarrays of # size K sum = 0 # Add the values of first K elements # to the sum for i in range(K): sum += arr[i] # Increment the count if the # current subarray is valid if sum >= K*M: count += 1 # Traverse the given array for i in range(K, N): # Find the updated sum sum += (arr[i] - arr[i - K]) # Check if current subarray # is valid or not if sum >= K*M: count += 1 # Return the count of subarrays return count # Driver Codeif __name__ == '__main__': arr = [3, 6, 3, 2, 1, 3, 9] K = 2 M = 4 N = len(arr) count = countSubArrays(arr, N, K, M) print(count) # This code is contributed by Kdheeraj.",
"e": 29718,
"s": 28765,
"text": null
},
{
"code": "// C# program for the above approach using System; public class GFG{ // Driver Code public static void Main(String[] args) { int[] arr = { 3, 6, 3, 2, 1, 3, 9 }; int K = 2, M = 4; Console.WriteLine(countSubArrays(arr, K, M)); } // Function to count the subarrays of // size K having average at least M public static int countSubArrays(int[] arr, int K, int M) { // Stores the resultant count of // subarray int count = 0; // Stores the sum of subarrays of // size K int sum = 0; // Add the values of first K elements // to the sum for (int i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (int i = K; i < arr.Length; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; }} // This code is contributed by AnkThon",
"e": 30991,
"s": 29718,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Function to count the subarrays of // size K having average at least M function countSubArrays(arr, N, K, M) { // Stores the resultant count of // subarray let count = 0; // Stores the sum of subarrays of // size K let sum = 0; // Add the values of first K elements // to the sum for (let i = 0; i < K; i++) { sum += arr[i]; } // Increment the count if the // current subarray is valid if (sum >= K * M) count++; // Traverse the given array for (let i = K; i < N; i++) { // Find the updated sum sum += (arr[i] - arr[i - K]); // Check if current subarray // is valid or not if (sum >= K * M) count++; } // Return the count of subarrays return count; } // Driver Code let arr = [3, 6, 3, 2, 1, 3, 9]; let K = 2, M = 4; let N = arr.length; document.write(countSubArrays(arr, N, K, M)); // This code is contributed by Potta Lokesh </script>",
"e": 32292,
"s": 30991,
"text": null
},
{
"code": null,
"e": 32294,
"s": 32292,
"text": "3"
},
{
"code": null,
"e": 32340,
"s": 32296,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32349,
"s": 32340,
"text": "Kdheeraj"
},
{
"code": null,
"e": 32363,
"s": 32349,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32371,
"s": 32363,
"text": "ankthon"
},
{
"code": null,
"e": 32386,
"s": 32371,
"text": "sliding-window"
},
{
"code": null,
"e": 32395,
"s": 32386,
"text": "subarray"
},
{
"code": null,
"e": 32408,
"s": 32395,
"text": "subarray-sum"
},
{
"code": null,
"e": 32430,
"s": 32408,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 32437,
"s": 32430,
"text": "Arrays"
},
{
"code": null,
"e": 32450,
"s": 32437,
"text": "Mathematical"
},
{
"code": null,
"e": 32465,
"s": 32450,
"text": "sliding-window"
},
{
"code": null,
"e": 32487,
"s": 32465,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 32494,
"s": 32487,
"text": "Arrays"
},
{
"code": null,
"e": 32507,
"s": 32494,
"text": "Mathematical"
},
{
"code": null,
"e": 32605,
"s": 32507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32614,
"s": 32605,
"text": "Comments"
},
{
"code": null,
"e": 32627,
"s": 32614,
"text": "Old Comments"
},
{
"code": null,
"e": 32676,
"s": 32627,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32696,
"s": 32676,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32734,
"s": 32696,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32819,
"s": 32734,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32844,
"s": 32819,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32874,
"s": 32844,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32934,
"s": 32874,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32949,
"s": 32934,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32992,
"s": 32949,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Ideal Python environment setup for Data Science | by Harshit Tyagi | Towards Data Science
|
Got a data science project at hand to start off? Not sure what would be the right Python establishment to smooth the process? You need not go any further as this post will resolve all the hiccups around the data science environment to work locally. We’ll cover the tools, packages or software you might need to install before you start beating the sh*t out of that data.
The three elements you need to start off with your project are:
A UNIX shell on your machine and some familiarity with it.Anaconda — your package and environment manager, a Python data science distribution with a collection of over 7500 open-source packages.Git and GitHub — Version your projects with the most amazing version control system for tracking changes, and optimizing collaborative development.
A UNIX shell on your machine and some familiarity with it.
Anaconda — your package and environment manager, a Python data science distribution with a collection of over 7500 open-source packages.
Git and GitHub — Version your projects with the most amazing version control system for tracking changes, and optimizing collaborative development.
Hardly a day goes by when a data scientist or software engineer does not use UNIX shell to accomplish their plethora of analysis tasks.
Importance of UNIX shell for a data scientist:
After a certain stage, your project will have to go into production. You’ll be working on one of the cloud computing platforms like Google Cloud Platform or Amazon Web Services. Almost all platforms are Linux based and require you to work with the UNIX shell. Here’s a cheatsheet for shell scripting.
We’ll be using the command-line interface to install anaconda, git and perform other operations like starting jupyter notebook local server, committing and pushing our changes to the remote repository.
MacOS Users: Your systems already have a Unix shell(bash). If not, you can use Homebrew to install.
Windows Users: Windows doesn’t come with a UNIX shell. You can install Cygwin which provides a collection of GNU and open source tools and other functionalities on Windows.
To set up your python environment, you’ll first need to have a python on your machine. There are various python distributions available and we need the one that works best for data science. Anaconda comes with its own Python distribution which will be installed along with it.
Why Anaconda?
Data Science often requires you to work with a lot of scientific packages like scipy and numpy, data manipulation packages like pandas and IDEs and interactive Jupyter Notebook. Anaconda comes with Conda(for Command Line Interface) and Navigator(for Graphical User Interface). It works as a flawless manager for all these package versions and dependencies.
Now, you don’t need to worry about any python package most of them come pre-installed and if you want to install a new package, you can do that simply by using conda or pip.
Here is the step-by-step guide for Anaconda installation for MacOS:
docs.anaconda.com
Anaconda installation for Windows.
Anaconda installation for Linux.
Environment Management with Conda
As you’ll progress, you will find yourself working on multiple applications/projects. These applications will be dependent on different versions of Python/packages. You’ll be working with a team/partner and might want to standardize the configuration so that all of them are able to run the project.
In that case, you need to create and configure different environments.
And Conda has come to our rescue which allows us to create separate environments containing files, packages and their dependencies that are isolated from other environments.
Creating a new environment named dswh_envusing conda:
Creating a new environment named dswh_envusing conda:
conda create --name dswh_env
Your environment is now created but you’re not using it as of now.
2. Using or Activating the environment:
conda activate dswh_env
3. If you want to see all the environments in your systems, type:
conda info --envs
4. To deactivate the environment, use:
conda deactivate
Version control has been a blessing for programmers and Git is the most widely used version control system. It permits us to track our progress. We have a log of what we did when we did it and allows us to go back to a previous state of our project.
GitHub is a cloud-based code hosting service that helps you track your source code history. If we want to keep track of our project locally, we don’t need to use GitHub. But if you’re working with a team or if you want to showcase your project and skills, you can build a strong profile on GitHub by putting out your projects in the form of repositories.
Here’s the link to install Git for your respective machines:
Here’s the link to install Git for your respective machines:
git-scm.com
2. Create an account on GitHub if you don’t have one.
With the familiarity gained over each component, you should now be able to set up your environment using UNIX shell, Python & Anaconda, and Git.
With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:
The series would cover all the required/demanded quality tutorials on each of the topics and subtopics.
Explained Mathematics and derivations of why we do what we do in ML and Deep Learning.
Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.
Projects and instructions to implement the topics learned so far.
www.youtube.com
You can connect with me on LinkedIn, Twitter or Instagram(where I talk about health and wellness.)
Note: During these dark times, self-isolation has made some room for self-improvement which we can utilize to develop new skills, hobbies, and help our future-selves.
|
[
{
"code": null,
"e": 543,
"s": 172,
"text": "Got a data science project at hand to start off? Not sure what would be the right Python establishment to smooth the process? You need not go any further as this post will resolve all the hiccups around the data science environment to work locally. We’ll cover the tools, packages or software you might need to install before you start beating the sh*t out of that data."
},
{
"code": null,
"e": 607,
"s": 543,
"text": "The three elements you need to start off with your project are:"
},
{
"code": null,
"e": 949,
"s": 607,
"text": "A UNIX shell on your machine and some familiarity with it.Anaconda — your package and environment manager, a Python data science distribution with a collection of over 7500 open-source packages.Git and GitHub — Version your projects with the most amazing version control system for tracking changes, and optimizing collaborative development."
},
{
"code": null,
"e": 1008,
"s": 949,
"text": "A UNIX shell on your machine and some familiarity with it."
},
{
"code": null,
"e": 1145,
"s": 1008,
"text": "Anaconda — your package and environment manager, a Python data science distribution with a collection of over 7500 open-source packages."
},
{
"code": null,
"e": 1293,
"s": 1145,
"text": "Git and GitHub — Version your projects with the most amazing version control system for tracking changes, and optimizing collaborative development."
},
{
"code": null,
"e": 1429,
"s": 1293,
"text": "Hardly a day goes by when a data scientist or software engineer does not use UNIX shell to accomplish their plethora of analysis tasks."
},
{
"code": null,
"e": 1476,
"s": 1429,
"text": "Importance of UNIX shell for a data scientist:"
},
{
"code": null,
"e": 1777,
"s": 1476,
"text": "After a certain stage, your project will have to go into production. You’ll be working on one of the cloud computing platforms like Google Cloud Platform or Amazon Web Services. Almost all platforms are Linux based and require you to work with the UNIX shell. Here’s a cheatsheet for shell scripting."
},
{
"code": null,
"e": 1979,
"s": 1777,
"text": "We’ll be using the command-line interface to install anaconda, git and perform other operations like starting jupyter notebook local server, committing and pushing our changes to the remote repository."
},
{
"code": null,
"e": 2079,
"s": 1979,
"text": "MacOS Users: Your systems already have a Unix shell(bash). If not, you can use Homebrew to install."
},
{
"code": null,
"e": 2252,
"s": 2079,
"text": "Windows Users: Windows doesn’t come with a UNIX shell. You can install Cygwin which provides a collection of GNU and open source tools and other functionalities on Windows."
},
{
"code": null,
"e": 2529,
"s": 2252,
"text": "To set up your python environment, you’ll first need to have a python on your machine. There are various python distributions available and we need the one that works best for data science. Anaconda comes with its own Python distribution which will be installed along with it."
},
{
"code": null,
"e": 2543,
"s": 2529,
"text": "Why Anaconda?"
},
{
"code": null,
"e": 2900,
"s": 2543,
"text": "Data Science often requires you to work with a lot of scientific packages like scipy and numpy, data manipulation packages like pandas and IDEs and interactive Jupyter Notebook. Anaconda comes with Conda(for Command Line Interface) and Navigator(for Graphical User Interface). It works as a flawless manager for all these package versions and dependencies."
},
{
"code": null,
"e": 3074,
"s": 2900,
"text": "Now, you don’t need to worry about any python package most of them come pre-installed and if you want to install a new package, you can do that simply by using conda or pip."
},
{
"code": null,
"e": 3142,
"s": 3074,
"text": "Here is the step-by-step guide for Anaconda installation for MacOS:"
},
{
"code": null,
"e": 3160,
"s": 3142,
"text": "docs.anaconda.com"
},
{
"code": null,
"e": 3195,
"s": 3160,
"text": "Anaconda installation for Windows."
},
{
"code": null,
"e": 3228,
"s": 3195,
"text": "Anaconda installation for Linux."
},
{
"code": null,
"e": 3262,
"s": 3228,
"text": "Environment Management with Conda"
},
{
"code": null,
"e": 3562,
"s": 3262,
"text": "As you’ll progress, you will find yourself working on multiple applications/projects. These applications will be dependent on different versions of Python/packages. You’ll be working with a team/partner and might want to standardize the configuration so that all of them are able to run the project."
},
{
"code": null,
"e": 3633,
"s": 3562,
"text": "In that case, you need to create and configure different environments."
},
{
"code": null,
"e": 3807,
"s": 3633,
"text": "And Conda has come to our rescue which allows us to create separate environments containing files, packages and their dependencies that are isolated from other environments."
},
{
"code": null,
"e": 3861,
"s": 3807,
"text": "Creating a new environment named dswh_envusing conda:"
},
{
"code": null,
"e": 3915,
"s": 3861,
"text": "Creating a new environment named dswh_envusing conda:"
},
{
"code": null,
"e": 3944,
"s": 3915,
"text": "conda create --name dswh_env"
},
{
"code": null,
"e": 4011,
"s": 3944,
"text": "Your environment is now created but you’re not using it as of now."
},
{
"code": null,
"e": 4051,
"s": 4011,
"text": "2. Using or Activating the environment:"
},
{
"code": null,
"e": 4075,
"s": 4051,
"text": "conda activate dswh_env"
},
{
"code": null,
"e": 4141,
"s": 4075,
"text": "3. If you want to see all the environments in your systems, type:"
},
{
"code": null,
"e": 4159,
"s": 4141,
"text": "conda info --envs"
},
{
"code": null,
"e": 4198,
"s": 4159,
"text": "4. To deactivate the environment, use:"
},
{
"code": null,
"e": 4215,
"s": 4198,
"text": "conda deactivate"
},
{
"code": null,
"e": 4465,
"s": 4215,
"text": "Version control has been a blessing for programmers and Git is the most widely used version control system. It permits us to track our progress. We have a log of what we did when we did it and allows us to go back to a previous state of our project."
},
{
"code": null,
"e": 4820,
"s": 4465,
"text": "GitHub is a cloud-based code hosting service that helps you track your source code history. If we want to keep track of our project locally, we don’t need to use GitHub. But if you’re working with a team or if you want to showcase your project and skills, you can build a strong profile on GitHub by putting out your projects in the form of repositories."
},
{
"code": null,
"e": 4881,
"s": 4820,
"text": "Here’s the link to install Git for your respective machines:"
},
{
"code": null,
"e": 4942,
"s": 4881,
"text": "Here’s the link to install Git for your respective machines:"
},
{
"code": null,
"e": 4954,
"s": 4942,
"text": "git-scm.com"
},
{
"code": null,
"e": 5008,
"s": 4954,
"text": "2. Create an account on GitHub if you don’t have one."
},
{
"code": null,
"e": 5153,
"s": 5008,
"text": "With the familiarity gained over each component, you should now be able to set up your environment using UNIX shell, Python & Anaconda, and Git."
},
{
"code": null,
"e": 5311,
"s": 5153,
"text": "With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:"
},
{
"code": null,
"e": 5415,
"s": 5311,
"text": "The series would cover all the required/demanded quality tutorials on each of the topics and subtopics."
},
{
"code": null,
"e": 5502,
"s": 5415,
"text": "Explained Mathematics and derivations of why we do what we do in ML and Deep Learning."
},
{
"code": null,
"e": 5620,
"s": 5502,
"text": "Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies."
},
{
"code": null,
"e": 5686,
"s": 5620,
"text": "Projects and instructions to implement the topics learned so far."
},
{
"code": null,
"e": 5702,
"s": 5686,
"text": "www.youtube.com"
},
{
"code": null,
"e": 5801,
"s": 5702,
"text": "You can connect with me on LinkedIn, Twitter or Instagram(where I talk about health and wellness.)"
}
] |
How to change the tick size using ggplot2 in R?
|
To change the tick size using ggplot2, we can use theme function with argument axis.ticks.length. For example, if we have a data frame called df that contains two columns say x and y then the scatterplot between x and y with larger size of tick marks can be created by using the below command −
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.8,"inch"))
Consider the below data frame −
Live Demo
x<-rnorm(20)
y<-rnorm(20)
df<-data.frame(x,y)
df
x y
1 2.5494830 -0.587904992
2 -0.5864972 0.006669457
3 0.9554755 -3.925291145
4 0.6686948 -2.326550523
5 -0.3267310 0.738981444
6 -0.8751193 -0.438232843
7 0.5477108 0.214512133
8 -0.4767738 0.451001999
9 -0.5364709 0.335897135
10 0.5853087 -0.665692002
11 -1.7818255 0.944527193
12 -0.9670748 0.639372414
13 0.4873353 0.466036727
14 0.3669196 2.732934553
15 0.9450203 -0.201909686
16 -1.1646289 -0.533447384
17 -1.8637459 1.186856615
18 -1.5751590 -1.154048208
19 -0.2266776 1.813758654
20 -0.7125976 0.251823020
Loading ggplot2 package and creating scatterplot between x and y with default size of tick marks −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating scatterplot between x and y with larger size of tick marks −
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.2,"inch"))
ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.50,"cm"))
|
[
{
"code": null,
"e": 1357,
"s": 1062,
"text": "To change the tick size using ggplot2, we can use theme function with argument axis.ticks.length. For example, if we have a data frame called df that contains two columns say x and y then the scatterplot between x and y with larger size of tick marks can be created by using the below command −"
},
{
"code": null,
"e": 1432,
"s": 1357,
"text": "ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.8,\"inch\"))"
},
{
"code": null,
"e": 1464,
"s": 1432,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1475,
"s": 1464,
"text": " Live Demo"
},
{
"code": null,
"e": 1524,
"s": 1475,
"text": "x<-rnorm(20)\ny<-rnorm(20)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 2107,
"s": 1524,
"text": " x y\n1 2.5494830 -0.587904992\n2 -0.5864972 0.006669457\n3 0.9554755 -3.925291145\n4 0.6686948 -2.326550523\n5 -0.3267310 0.738981444\n6 -0.8751193 -0.438232843\n7 0.5477108 0.214512133\n8 -0.4767738 0.451001999\n9 -0.5364709 0.335897135\n10 0.5853087 -0.665692002\n11 -1.7818255 0.944527193\n12 -0.9670748 0.639372414\n13 0.4873353 0.466036727\n14 0.3669196 2.732934553\n15 0.9450203 -0.201909686\n16 -1.1646289 -0.533447384\n17 -1.8637459 1.186856615\n18 -1.5751590 -1.154048208\n19 -0.2266776 1.813758654\n20 -0.7125976 0.251823020"
},
{
"code": null,
"e": 2206,
"s": 2107,
"text": "Loading ggplot2 package and creating scatterplot between x and y with default size of tick marks −"
},
{
"code": null,
"e": 2256,
"s": 2206,
"text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()"
},
{
"code": null,
"e": 2326,
"s": 2256,
"text": "Creating scatterplot between x and y with larger size of tick marks −"
},
{
"code": null,
"e": 2401,
"s": 2326,
"text": "ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.2,\"inch\"))"
},
{
"code": null,
"e": 2475,
"s": 2401,
"text": "ggplot(df,aes(x,y))+geom_point()+theme(axis.ticks.length=unit(0.50,\"cm\"))"
}
] |
Bit Algorithms - GeeksforGeeks
|
01 Jun, 2021
# include <iostream>
using namespace std;
int fun(int arr[], int n)
{
int x = arr[0];
for (int i = 1; i < n; i++)
x = x ^ arr[i];
return x;
}
int main()
{
int arr[] = {9, 12, 2, 11, 10, 9, 12, 10, 9, 11, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << fun(arr, n) << endl;
return 0;
}
x = x & (x-1)
Since there are total n elements, maximum sum is n for both arrays.Difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum.
Since there are total n elements, maximum sum is n for both arrays.
Difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.
If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum.
Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)Initialize starting points of all differences as -1.Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0Traverse both arrays from i = 0 to n-1.Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLenReturn maxLen
Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)
Initialize starting points of all differences as -1.
Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0
Traverse both arrays from i = 0 to n-1.Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen
Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen
Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]
Compute difference of current prefix sums: curr_diff = preSum1 – preSum2
Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n
If curr_diff is 0, then i+1 is maxLen so far
Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i
Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen
Return maxLen
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
SQL Query to Convert VARCHAR to INT
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
|
[
{
"code": null,
"e": 27530,
"s": 27502,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 27845,
"s": 27530,
"text": "# include <iostream>\nusing namespace std;\n\nint fun(int arr[], int n)\n{\n int x = arr[0];\n for (int i = 1; i < n; i++)\n x = x ^ arr[i];\n return x;\n}\n\nint main()\n{\n int arr[] = {9, 12, 2, 11, 10, 9, 12, 10, 9, 11, 2};\n int n = sizeof(arr)/sizeof(arr[0]);\n cout << fun(arr, n) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 27861,
"s": 27845,
"text": " x = x & (x-1) "
},
{
"code": null,
"e": 28164,
"s": 27861,
"text": "Since there are total n elements, maximum sum is n for both arrays.Difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum."
},
{
"code": null,
"e": 28232,
"s": 28164,
"text": "Since there are total n elements, maximum sum is n for both arrays."
},
{
"code": null,
"e": 28338,
"s": 28232,
"text": "Difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference."
},
{
"code": null,
"e": 28469,
"s": 28338,
"text": "If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum."
},
{
"code": null,
"e": 29407,
"s": 28469,
"text": "Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)Initialize starting points of all differences as -1.Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0Traverse both arrays from i = 0 to n-1.Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLenReturn maxLen"
},
{
"code": null,
"e": 29614,
"s": 29407,
"text": "Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)"
},
{
"code": null,
"e": 29667,
"s": 29614,
"text": "Initialize starting points of all differences as -1."
},
{
"code": null,
"e": 29752,
"s": 29667,
"text": "Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0"
},
{
"code": null,
"e": 30335,
"s": 29752,
"text": "Traverse both arrays from i = 0 to n-1.Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen"
},
{
"code": null,
"e": 30879,
"s": 30335,
"text": "Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen"
},
{
"code": null,
"e": 30938,
"s": 30879,
"text": "Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]"
},
{
"code": null,
"e": 31011,
"s": 30938,
"text": "Compute difference of current prefix sums: curr_diff = preSum1 – preSum2"
},
{
"code": null,
"e": 31111,
"s": 31011,
"text": "Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n"
},
{
"code": null,
"e": 31156,
"s": 31111,
"text": "If curr_diff is 0, then i+1 is maxLen so far"
},
{
"code": null,
"e": 31270,
"s": 31156,
"text": "Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i"
},
{
"code": null,
"e": 31428,
"s": 31270,
"text": "Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen"
},
{
"code": null,
"e": 31442,
"s": 31428,
"text": "Return maxLen"
},
{
"code": null,
"e": 31540,
"s": 31442,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 31549,
"s": 31540,
"text": "Comments"
},
{
"code": null,
"e": 31562,
"s": 31549,
"text": "Old Comments"
},
{
"code": null,
"e": 31615,
"s": 31562,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 31651,
"s": 31615,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 31717,
"s": 31651,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 31778,
"s": 31717,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31816,
"s": 31778,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 31878,
"s": 31816,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 31958,
"s": 31878,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 31999,
"s": 31958,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 32034,
"s": 31999,
"text": "Insert Image in a Jupyter Notebook"
}
] |
How to toggle text with JavaScript?
|
To toggle text with JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.textDiv {
font-size: 20px;
background-color: rgb(199, 228, 157);
width: 100%;
padding: 15px;
font-weight: bold;
}
.toggleBtn {
padding: 15px;
border: none;
background-color: rgb(106, 41, 153);
color: white;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Toggle Text example</h1>
<button class="toggleBtn">Click Me</button>
<h2>Click on the above button to toggle below text</h2>
<div class="textDiv">Old Text</div>
<script>
document .querySelector(".toggleBtn") .addEventListener("click", toggleText);
function toggleText() {
var x = document.querySelector(".textDiv");
if (x.innerHTML === "Old Text") {
x.innerHTML = "New Text";
} else {
x.innerHTML = "Old Text";
}
}
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Click Me” button −
|
[
{
"code": null,
"e": 1119,
"s": 1062,
"text": "To toggle text with JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1130,
"s": 1119,
"text": " Live Demo"
},
{
"code": null,
"e": 2141,
"s": 1130,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .textDiv {\n font-size: 20px;\n background-color: rgb(199, 228, 157);\n width: 100%;\n padding: 15px;\n font-weight: bold;\n }\n .toggleBtn {\n padding: 15px;\n border: none;\n background-color: rgb(106, 41, 153);\n color: white;\n font-size: 18px;\n }\n</style>\n</head>\n<body>\n<h1>Toggle Text example</h1>\n<button class=\"toggleBtn\">Click Me</button>\n<h2>Click on the above button to toggle below text</h2>\n<div class=\"textDiv\">Old Text</div>\n<script>\n document .querySelector(\".toggleBtn\") .addEventListener(\"click\", toggleText);\n function toggleText() {\n var x = document.querySelector(\".textDiv\");\n if (x.innerHTML === \"Old Text\") {\n x.innerHTML = \"New Text\";\n } else {\n x.innerHTML = \"Old Text\";\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2192,
"s": 2141,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2228,
"s": 2192,
"text": "On clicking the “Click Me” button −"
}
] |
Print Pattern | Practice | GeeksforGeeks
|
Print a sequence of numbers starting with N where A[0] = N, without using loop, in which A[i+1] = A[i] - 5, until A[i] > 0. After that A[i+1] = A[i] + 5 repeat it until A[i] = N.
Example 1:
Input: N = 16
Output: 16 11 6 1 -4 1 6 11 16
Explaination: The value decreses until it
is greater than 0. After that it increases
and stops when it becomes 16 again.
Example 2:
Input: N = 10
Output: 10 5 0 5 10
Explaination: It follows the same logic as
per the above example.
Your Task:
You do not need to read input or print anything. Your task is to complete the function pattern() which takes N as input parameters and returns a list containing the pattern.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 104
0
lumosmaxima000001 week ago
Can anybody please let me know, where is the problem in this code -
public:
vector<int> res;
vector<int> check(int n, int M)
{
res.push_back(n);
if(n == M)
return res;
if(n <= 0)
n += 5;
else if(n > 0)
n -= 5;
return check(n,M);
}
vector<int> pattern(int N){
// code here
res.push_back(N);
N -= 5;
return check(N,N+5);
}
I am getting infinite loop error.
0
miniaditi021 week ago
why is this code not working
class Solution: def pattern(self, N): if N==0 or N<0: print(N, end=",") return print(N, end=",") pattern(N-5) print(N, end=",")
0
miniaditi02
This comment was deleted.
0
rohansarna0712011 week ago
class Solution{
public:
vector<int>v ;
vector<int> pattern(int N){
if(N <=0 ){
if(v[v.size()-1] > 0 ){
v.push_back(N);
}
return v ;
}
v.push_back(N);
pattern(N-5);
v.push_back(N);
return v ;
}
};
+1
badgujarsachin832 weeks ago
vector<int> pattern(int N){
// code here
int n=N;
vector<int> v;
while(n>0){
v.push_back(n);
n-=5;
}
while(n!=N){
v.push_back(n);
n+=5;
}
v.push_back(n);
return v;
}
0
shuklarishabh8903 weeks ago
def pattern(self, N): if N==0 or N<0: print(N,end=', ') return print(N,end=", ") pattern(N-5)
print(N,end=", ") can anyBody tell me why this code is not working.
0
subhajitghosh19973 weeks ago
// JAVA // ALL TEST CASES PASS
class Solution{ static List<Integer> pattern(int N){ // code here List<Integer> n1 = new ArrayList<>(); List<Integer> n2 = new ArrayList<>(); n1 = generate1(N , n1); int x = n1.size(); int p = n1.get(x-1); if(p > 0){ n1.add(p-5); n1 = generate2(N , p-5 , n1); }else{ n1 = generate2(N , p , n1); } return n1; } public static List<Integer> generate1(int N , List<Integer> n1){ if(N < 0){ return n1; } n1.add(N); generate1(N-5 , n1); return n1; } public static List<Integer> generate2(int N , int N2 , List<Integer> n1){ if(N2 == N){ return n1; } n1.add(N2+5); generate2(N,N2+5 , n1); return n1; } }
0
sourabhgharad19064 weeks ago
JAVA EASIEST SOLUTION!!!
class Solution{ static List<Integer> helper(int N,ArrayList<Integer> list){ if(N<=0){ list.add(N); return list; } list.add(N); helper(N-5,list); list.add(N); return list; } static List<Integer> pattern(int N){ ArrayList<Integer> list = new ArrayList<>(); return helper(N,list); }}
0
debasishtewary54 weeks ago
class Solution{ public static List<Integer> pat(int n,List<Integer> l){if(n<=0) { return l;}else { l.add(n); return pat(n-5,l);}}public static int pat0(int n){if(n<=0) { return n;}else { return pat0(n-5);}}public static List<Integer> pat1(int k,int n,List<Integer> l){if(n==k){ l.add(n); return l;}else { l.add(n); return pat1(k,n+5,l);}} static List<Integer> pattern(int N){ // code here int n=N; int k=n; List<Integer> l=new ArrayList<Integer>(); Solution.pat(n,l);Solution.pat1(k,Solution.pat0(n),l);return l; } }
0
kashyapjhon4 weeks ago
C++ Without Recursion Code:
vector<int> pattern(int N){ // code here vector<int> ans; int n=N,x=N; while(n>0){ ans.push_back(n); n=n-5; } while(n!=N){ ans.push_back(n); n=n+5; } ans.push_back(n); return ans; }
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": 408,
"s": 226,
"text": "Print a sequence of numbers starting with N where A[0] = N, without using loop, in which A[i+1] = A[i] - 5, until A[i] > 0. After that A[i+1] = A[i] + 5 repeat it until A[i] = N."
},
{
"code": null,
"e": 419,
"s": 408,
"text": "Example 1:"
},
{
"code": null,
"e": 587,
"s": 419,
"text": "Input: N = 16\nOutput: 16 11 6 1 -4 1 6 11 16\nExplaination: The value decreses until it \nis greater than 0. After that it increases \nand stops when it becomes 16 again."
},
{
"code": null,
"e": 598,
"s": 587,
"text": "Example 2:"
},
{
"code": null,
"e": 699,
"s": 598,
"text": "Input: N = 10\nOutput: 10 5 0 5 10\nExplaination: It follows the same logic as \nper the above example."
},
{
"code": null,
"e": 884,
"s": 699,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function pattern() which takes N as input parameters and returns a list containing the pattern."
},
{
"code": null,
"e": 946,
"s": 884,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 972,
"s": 946,
"text": "Constraints:\n1 ≤ N ≤ 104 "
},
{
"code": null,
"e": 974,
"s": 972,
"text": "0"
},
{
"code": null,
"e": 1001,
"s": 974,
"text": "lumosmaxima000001 week ago"
},
{
"code": null,
"e": 1070,
"s": 1001,
"text": "Can anybody please let me know, where is the problem in this code - "
},
{
"code": null,
"e": 1512,
"s": 1072,
"text": "public:\n \n vector<int> res;\n \n vector<int> check(int n, int M)\n {\n res.push_back(n);\n \n if(n == M)\n return res;\n if(n <= 0)\n n += 5;\n else if(n > 0)\n n -= 5;\n \n return check(n,M);\n }\n \n vector<int> pattern(int N){\n // code here\n res.push_back(N);\n \n N -= 5;\n \n return check(N,N+5);\n }"
},
{
"code": null,
"e": 1546,
"s": 1512,
"text": "I am getting infinite loop error."
},
{
"code": null,
"e": 1548,
"s": 1546,
"text": "0"
},
{
"code": null,
"e": 1570,
"s": 1548,
"text": "miniaditi021 week ago"
},
{
"code": null,
"e": 1599,
"s": 1570,
"text": "why is this code not working"
},
{
"code": null,
"e": 1792,
"s": 1599,
"text": "class Solution: def pattern(self, N): if N==0 or N<0: print(N, end=\",\") return print(N, end=\",\") pattern(N-5) print(N, end=\",\")"
},
{
"code": null,
"e": 1794,
"s": 1792,
"text": "0"
},
{
"code": null,
"e": 1806,
"s": 1794,
"text": "miniaditi02"
},
{
"code": null,
"e": 1832,
"s": 1806,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1834,
"s": 1832,
"text": "0"
},
{
"code": null,
"e": 1861,
"s": 1834,
"text": "rohansarna0712011 week ago"
},
{
"code": null,
"e": 2224,
"s": 1861,
"text": "class Solution{\npublic:\nvector<int>v ;\n vector<int> pattern(int N){\n if(N <=0 ){\n if(v[v.size()-1] > 0 ){\n v.push_back(N); \n \n }\n return v ; \n \n }\n \n \n v.push_back(N); \n pattern(N-5);\n v.push_back(N);\n return v ; \n \n }\n};"
},
{
"code": null,
"e": 2227,
"s": 2224,
"text": "+1"
},
{
"code": null,
"e": 2255,
"s": 2227,
"text": "badgujarsachin832 weeks ago"
},
{
"code": null,
"e": 2546,
"s": 2255,
"text": " vector<int> pattern(int N){\n // code here\n int n=N;\n vector<int> v;\n while(n>0){\n v.push_back(n);\n n-=5;\n }\n while(n!=N){\n v.push_back(n);\n n+=5;\n }\n v.push_back(n);\n return v;\n }"
},
{
"code": null,
"e": 2548,
"s": 2546,
"text": "0"
},
{
"code": null,
"e": 2576,
"s": 2548,
"text": "shuklarishabh8903 weeks ago"
},
{
"code": null,
"e": 2708,
"s": 2576,
"text": "def pattern(self, N): if N==0 or N<0: print(N,end=', ') return print(N,end=\", \") pattern(N-5)"
},
{
"code": null,
"e": 2789,
"s": 2708,
"text": " print(N,end=\", \") can anyBody tell me why this code is not working."
},
{
"code": null,
"e": 2791,
"s": 2789,
"text": "0"
},
{
"code": null,
"e": 2820,
"s": 2791,
"text": "subhajitghosh19973 weeks ago"
},
{
"code": null,
"e": 2851,
"s": 2820,
"text": "// JAVA // ALL TEST CASES PASS"
},
{
"code": null,
"e": 3646,
"s": 2851,
"text": "class Solution{ static List<Integer> pattern(int N){ // code here List<Integer> n1 = new ArrayList<>(); List<Integer> n2 = new ArrayList<>(); n1 = generate1(N , n1); int x = n1.size(); int p = n1.get(x-1); if(p > 0){ n1.add(p-5); n1 = generate2(N , p-5 , n1); }else{ n1 = generate2(N , p , n1); } return n1; } public static List<Integer> generate1(int N , List<Integer> n1){ if(N < 0){ return n1; } n1.add(N); generate1(N-5 , n1); return n1; } public static List<Integer> generate2(int N , int N2 , List<Integer> n1){ if(N2 == N){ return n1; } n1.add(N2+5); generate2(N,N2+5 , n1); return n1; } }"
},
{
"code": null,
"e": 3648,
"s": 3646,
"text": "0"
},
{
"code": null,
"e": 3677,
"s": 3648,
"text": "sourabhgharad19064 weeks ago"
},
{
"code": null,
"e": 3702,
"s": 3677,
"text": "JAVA EASIEST SOLUTION!!!"
},
{
"code": null,
"e": 4059,
"s": 3702,
"text": "class Solution{ static List<Integer> helper(int N,ArrayList<Integer> list){ if(N<=0){ list.add(N); return list; } list.add(N); helper(N-5,list); list.add(N); return list; } static List<Integer> pattern(int N){ ArrayList<Integer> list = new ArrayList<>(); return helper(N,list); }}"
},
{
"code": null,
"e": 4065,
"s": 4063,
"text": "0"
},
{
"code": null,
"e": 4092,
"s": 4065,
"text": "debasishtewary54 weeks ago"
},
{
"code": null,
"e": 4650,
"s": 4092,
"text": "class Solution{ public static List<Integer> pat(int n,List<Integer> l){if(n<=0) { return l;}else { l.add(n); return pat(n-5,l);}}public static int pat0(int n){if(n<=0) { return n;}else { return pat0(n-5);}}public static List<Integer> pat1(int k,int n,List<Integer> l){if(n==k){ l.add(n); return l;}else { l.add(n); return pat1(k,n+5,l);}} static List<Integer> pattern(int N){ // code here int n=N; int k=n; List<Integer> l=new ArrayList<Integer>(); Solution.pat(n,l);Solution.pat1(k,Solution.pat0(n),l);return l; } }"
},
{
"code": null,
"e": 4652,
"s": 4650,
"text": "0"
},
{
"code": null,
"e": 4675,
"s": 4652,
"text": "kashyapjhon4 weeks ago"
},
{
"code": null,
"e": 4703,
"s": 4675,
"text": "C++ Without Recursion Code:"
},
{
"code": null,
"e": 4981,
"s": 4703,
"text": "vector<int> pattern(int N){ // code here vector<int> ans; int n=N,x=N; while(n>0){ ans.push_back(n); n=n-5; } while(n!=N){ ans.push_back(n); n=n+5; } ans.push_back(n); return ans; }"
},
{
"code": null,
"e": 5127,
"s": 4981,
"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": 5163,
"s": 5127,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5173,
"s": 5163,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5183,
"s": 5173,
"text": "\nContest\n"
},
{
"code": null,
"e": 5246,
"s": 5183,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5394,
"s": 5246,
"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": 5602,
"s": 5394,
"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": 5708,
"s": 5602,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Cross Validation: A Beginner’s Guide | by Caleb Neale | Towards Data Science
|
By: Caleb Neale, Demetri Workman, Abhinay Dommalapati
In beginning your journey into the world of machine learning and data science, there is often a temptation to jump into algorithms and model creation, without gaining an understanding of how to test the effectiveness of a generated model on real world data. Cross validation is a form of model validation which attempts to improve on the basic methods of hold-out validation by leveraging subsets of our data and an understanding of the bias/variance trade-off in order to gain a better understanding of how our models will actually perform when applied outside of the data it was trained on. Don’t worry, it’ll all be explained!
This article seeks to be a beginning to execution guide for three methods of model validation (hold out, k-fold, and LOOCV) and the concepts behind them, with links and references to guide you to further reading. We make use of scikit learn, pandas, numpy and other python libraries in the given examples.
What will be addressed in this article:
What is model validation?
Why is it important?
What are bias and variance in the context of model validation?
What is cross validation?
What are common methods?
Where, and when should different methods be implemented?
How do various methods of cross validation work?
How can we leverage cross validation to create better models?
Model validation is the process by which we ensure that our models can perform acceptable in “the real world.” In more technical terms, model validation allows you to predict how your model will perform on datasets not used in the training (model validation is a big part of why preventing data leakage is so important). Model validation is important because we don’t actually care how well the model predicts data we trained it on. We already know the target values for the data we used to train a model, and as such it is much more important to consider how robust and capable a model is when tasked to model new datasets of the same distribution and characteristics, but with different individual values from our training set. The first form of model validation introduced is usually what is known as holdout validation, often considered to be the simplest form of cross validation and thus the easiest to implement. Let’s work through an example below.
For this example, we’ll use a linear regression on the scikit-learn database of California housing data.
# import scikit learn databasesfrom sklearn import datasets# import california housing data from sklearn and store data into a variablecalihouses = datasets.fetch_california_housing()calidata = calihouses.data
Once the data is stored into a variable we can more easily work with, we’ll convert in into a pandas dataframe so we can more easily view and work with the data.
# import pandas and numpyimport pandas as pdimport numpy as np# define the columns names of the data then convert to dataframeheaders = calihouses.feature_namesdf = pd.DataFrame(calidata, columns=headers)# print the df and shape to get a better understanding of the dataprint(df.shape)print(df)
Now that we’ve seen the data we’re working with, we can begin the process of generating a model and cross validation. In holdout validation, we split the data into a training and testing set. The training set will be what the model is created on and the testing data will be used to validate the generated model. Though there are (fairly easy) ways to do this using pandas methods, we can make use of scikit-learns “train_test_split” method to accomplish this.
# first store all target data to a variabley = calihouses.target# create testing and training sets for hold-out verification using scikit learn methodfrom sklearn import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.25)# validate set shapesprint(X_train.shape, y_train.shape)print(X_test.shape, y_test.shape)
As you can see, we use the “train_test_split” with three parameters: the input (X) data, the target (y) data, and the percentage of data we’d like to remove and put into the test dataset, in this case 25% (common split is usually 70–30, depending on a multitude of factors about your data). We then assign the split X and y data to a set of new variables to work with later.
Your output should appear at this point as:
(15480, 8) (15480,)(5160, 8) (5160,)
Now that we’ve created our test/train split we can create a model and generate some predictions based on the train data. Though there are other methods of creating a model which show more of the nitty gritty, we’ll use scikit learn to make our lives a little easier. I’ve included a few lines to time the runtime of the function, which we will use for later comparison.
# time function using .time methods for later comparisonfrom timeit import default_timer as timerstart_ho = timer()# fit a model using linear model method from sklearnfrom sklearn import linear_modellm = linear_model.LinearRegression()model = lm.fit(X_train, y_train)# generate predictionspredictions = lm.predict(X_test)end_ho = timer()# calcualte function runtimetime_ho = (end_ho - start_ho)# show predictionsprint(predictions)
Let’s pause here for a moment and look at what we’ve done. Everything up to this point is just setup in creating a linear model and using it to make predictions on a dataset. This is how far you get without model validation. In other words, we have yet to look at how the model performs on its predictions of the test data when compared to the actual target values in the test data. The test/train split we did earlier was necessary to divide the data such that we can now test the model on data that was not used in training (see: data leakage). Now that we have a model, and have created some predictions, let’s go though with our holdout validation.
We’ll start by graphing our given target data vs our predicted target data to give us a visualization of how our model performs.
# import seaborn and plotlymport matplotlibfrom matplotlib import pyplot as pltimport seaborn as sns# set viz stylesns.set_style('dark')# plot the modelplot = sns.scatterplot(y_test, predictions)plot.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')
Output:
In a perfect model (overfit maybe), all our data points would be on that red line, but as our data points approximate that trend, we can see the model is roughly appropriate for the test data.
Now, lets get a score for the model to evaluate it against later methods.
start_ho_score = timer()# model score (neg_mean_squared_error)from sklearn import metricsho_score = -1*metrics.mean_squared_error(y_test, predictions)print(ho_score)end_ho_score = timer()ho_score_time = (end_ho_score - start_ho_score)
Output:
-0.5201754311947533
That’s model validation! We created a model using training data, used it to predict outcomes on a split segment of test data then used a scoring method to determine a measure of effectiveness (negative mean squared error) of the model on the testing data. This gives us an approximation of how well the model will perform on other similar datasets.
Now, a few things to consider. We validated our model once. What if the split we made just happened to be very conducive to this model? What if the split we made introduced a large skew into the date? Didn’t we significantly reduce the size of our training dataset by splitting it like that? These are a few questions we’ll consider as we move into cross validation, but first a few background concepts.
To understand bias and variance, let’s first address over and under fit models. On overfit model is generated when the model is so tightly fit to the training data that it may account for random noise or unwanted trends which will not be present or useful in predicting targets for subsequent datasets. Underfit occurs when the model is not complex enough to account for general trends in the data which would be useful in predicting targets in subsequent datasets, such as using a linear fit on a polynomial trend(An awesome visualization and further explanation of this concept from AWS can be found here).
When creating a model, we account for a few types of error: validation error, testing error, error due to bias, and error due to variance in a relationship known as the bias variance trade-off (another great visual here).
As mentioned earlier, we want to know how the model will perform “in the real world.” Part of that is validation error, which is comprised of error due to bias and error due to variance (training error does not provide information on how the model will perform on future datasets, and can be set aside for now).
Minimizing model validation error requires finding the point of model complexity where the combination of bias and variance error is minimized, as shown in the linked visual. As model complexity increases, error due to bias decreases, while error due to variance increases, creating the bias-variance trade-off, which we will seek to address later with various methods of cross validation.
Now let’s define bias and variance:
Bias
Bias is the error resulting from the difference between the expected value(s) of a model and the actual (or “correct”) value(s) for which we want to predict over multiple iterations. In the scientific concepts of accuracy and precision, bias is very similar to accuracy.
Variance
Variance is defined as the error resulting from the variability between different data predictions in a model. In variance, the correct value(s) don’t matter as much as the range of differences in value between the predictions. Variance also comes into play more when we run multiple model creation trials.
More complete definitions and visuals here.
In machine learning, bias and variance are often discussed together as a “bias-variance tradeoff,” saying that minimizing one error effectively makes the one more likely to be present when creating and assessing a model. Ideally, we would seek a model whose tradeoff results in both low bias and low variance, and we would look to achieve this by using cross validation. Depending on characteristics of the dataset, one method of cross validation is likely to be more ideal to achieving the bias-variance tradeoff when creating and assessing a model.
What if the split we made just happened to be very conducive to this model? What if the split we made introduced a large skew into the date? Didn’t we significantly reduce the size of our training dataset by splitting it like that?
Cross validation is a method of model validation which splits the data in creative ways in order to obtain the better estimates of “real world” model performance, and minimize validation error.
Remember those questions we asked about hold out validation? Cross validation is our answer.
K-Fold Cross Validation
K-fold validation is a popular method of cross validation which shuffles the data and splits it into k number of folds (groups). In general K-fold validation is performed by taking one group as the test data set, and the other k-1 groups as the training data, fitting and evaluating a model, and recording the chosen score. This process is then repeated with each fold (group) as the test data and all the scores averaged to obtain a more comprehensive model validation score. (More reading and a helpful visualization here).
When choosing a value for k each fold(group) should be large enough to be representative of the model (commonly k=10 or k=5) and small enough to be computed in a reasonable amount of time. Depending on the dataset size, different k values can sometimes be experimented with. As a general rule, as k increases, bias decreases and variance increases.
Lets work though an example with our dataset from earlier.
We’ll make use of a linear model again, but this time do model validation with scikit learn’s cross_val_predict method which will do most of the heavy lifting in generating K-Fold predictions. In this case, I chose to set k=10.
# store data as an arrayX = np.array(df)# again, timing the function for comparisonstart_kfold = timer()# use cross_val_predict to generate K-Fold predictionslm_k = linear_model.LinearRegression()k_predictions = cross_val_predict(lm_k, X, y, cv=10)print(k_predictions)end_kfold = timer()kfold_time = (end_kfold - start_kfold)
Output (or approximate):
[4.22358985 4.04800271 3.75534521 ... 0.14474758 0.29600522 0.49525933]
‘cross_val_predict’ takes the model used on the data, the input and target data, as well as a ‘cv’ argument — which is essentially our k value — and returns the predicted values for each input. Now we can plot the predictions as we did with the hold out method.
# plot k-fold predictions against actualplot_k = sns.scatterplot(y, k_predictions)plot_k.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')
Output:
Now let’s get the scores of the 10 generated models and plot them into a visualization.
kfold_score_start = timer()# find the mean score from the k-fold models usinf cross_val_scorekfold_scores = cross_val_score(lm_k, X, y, cv=10, scoring='neg_mean_squared_error')print(kfold_scores.mean())kfold_score_end = timer()kfold_score_time = (kfold_score_end - kfold_score_start)# plot scoressns.distplot(kfold_scores, bins=5)
Output:
-0.5509524296956634
You’ll notice that the score is a little farther from zero than the holdout method (not good). We’ll discuss that later.
Leave One Out Cross Validation
Leave One Out Cross Validation (LOOCV) can be considered a type of K-Fold validation where k=n given n is the number of rows in the dataset. Other than that the methods are quire similar. You will notice, however, that running the following code will take much longer than previous methods. We’ll dig into that later.
Let’s work an example with the same dataset, following the same process and modifying k:
Generate predictions:
start_LOO = timer()# generate LOO predictionsLOO_predictions = cross_val_predict(lm_k, X, y, cv=(len(X)))end_LOO = timer()LOO_time = (end_LOO - start_LOO)
Plot the predictions:
# plot LOO predictions against actualplot_LOO = sns.scatterplot(y, LOO_predictions)plot_LOO.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')
Output:
Generate and average scores:
LOO_score_start = timer()# find the mean score from the LOO models using cross_val_score LOO_score = cross_val_score(lm_k, X, y, cv=(len(X)), scoring='neg_mean_squared_error').mean()print(LOO_score)LOO_score_end = timer()LOO_score_time = (LOO_score_end - LOO_score_start)
Now lets compare the run times and scores of our three methods:
print("Hold out method took", time_ho, "seconds to generate a model and", ho_score_time ,"seconds to generate a MSE of", ho_score)print("K-Fold method took", kfold_time, 'seconds to generate a model and', kfold_score_time, 'seconds to generate a MSE of', kfold_scores.mean())print("Leave One Out Cross Validation method took", LOO_time, 'seconds to generate a model and', LOO_score_time, 'seconds to generate a MSE of', LOO_score)
Output:
Hold out method took 0.03958953900000495 seconds to generate a model and 0.002666198000042641 seconds to generate a MSE of -0.5201754311947533
K-Fold method took 0.07809067700000583 seconds to generate a model and 0.1253743699999177 seconds to generate a MSE of -0.5509524296956634
Leave One Out Cross Validation method took 152.00629317099992 seconds to generate a model and 161.83364986200013 seconds to generate a MSE of -0.5282462043712458
Let’s dig into these results a little, as well as some of the points raised earlier.
As we noticed in the results of our comparison, we can see that the LOOCV method takes way longer to complete than our other two. This is because that method creates and evaluates a model for each row in the dataset, in this case over 20,000. Even though our MSE is a little lower, this may not be worth it given the additional computational requirements. Here are some heuristics which can help in choosing a method.
Hold out method
The hold out method can be effective and computationally inexpensive on very large datasets, or on limited computational resources. It is also often easier to implement and understand for beginners. However, it is very rarely good to apply to small datasets as it can significantly reduce the training data available and hurt model performance.
K-Fold Cross Validation
K-Fold can be very effective on medium sized datasets, though by adjusting the K value can significantly alter the results of the validation. Let’s add to our rule from earlier; as k increases, bias decreases, and variance and computational requirements increase. K-Fold cross validation is likely the most common of the three methods due to the versatility of adjusting K-values.
LOOCV
LOOCV is most useful in small datasets as it allows for the smallest amount of data to be removed from the training data in each iteration. However, in large datasets the process of generating a model for each row in the dataset can be incredibly computationally expensive and thus prohibitive for larger datasets.
Holdout Validation
In holdout validation, we are doing nothing more than performing a simple train/test split in which we fit our model to our training data and apply it to our testing data to generate predicted values. We “hold out” the testing data to be strictly used for prediction purposes only. Holdout validation is NOT a cross validation technique. But we must discuss the standard method of model evaluation so that we can compare its attributes with the actual cross validation techniques.
When it comes to code, holdout validation is easy to use. The implementation is simple and doesn’t require large dedications to computational power and time complexity. Moreover, we can interpret and understand the results of holdout validation better as they don’t require us to figure out how the iterations are performing in the grand scheme of things.
However, holdout validation does not preserve the statistical integrity of the dataset in many cases. For instance, a holdout validation that splits the data into training and testing segments causes bias by not incorporating the testing data into the model. The testing data could contain some important observations. This would result in a detriment to the accuracy of the model. Furthermore, this will cause an underfitting and overfitting of the data in addition to an introduction of validation and/or training error.K-fold
In K-fold cross validation, we answer many of the problems inherent in holdout validation such as underfitting/overfitting and validation and training error. This is done by using all of the observations in our validation set at some iteration. We compute an average accuracy score of all the accuracy scores that are calculated in each k iteration. By doing so, we minimize bias and variation that may be present in our initial model evaluation technique, holdout validation. However, in terms of computational power, k-fold cross validation is very costly. The computer has to perform several iterations to generate a proper accuracy score. The accuracy score of the model will in theory increase with each added k iteration. This will decrease bias while increasing variation. We will see an example of this later in this article when we attempt to apply k-fold validation to a very large dataset that contains about 580,000 observations.
LOOCV
LOOCV is very similar to K-fold, with a special case in which k is equal to the length (or number of samples/rows) of the whole dataset. Thus the training set will be of length k-1, and the testing set will be a single sample of the data. LOOCV is particularly useful in the case that our data set is not large enough to sensibly do Kfold. LOOCV is also less computationally expensive in general, although it is usually due to the inherently smaller datasets that tend utilize it.
However, LOOCV tends to yield high variance due to the fact that the method would pick up on all of the possible noise and outlier values in the data through the individual testing values. LOOCV would be very computationally expensive for very large data sets; in this case, it would be better to use regular k-fold.
Cross validation becomes a computationally expensive and taxing method of model evaluation when dealing with large datasets. Generating prediction values ends up taking a very long time because the validation method have to run k times in K-Fold strategy, iterating through the entire dataset. Thus cross validation becomes a very costly model evaluation strategy in terms of time complexity. We will examine this phenomenon by performing a normal holdout validation and a K-Fold cross validation on a very large dataset with approximately 580,000 rows. See if you can figure it out, why it works the way it does (and the new data visualizations), and comment any questions. Good luck!
# upload dataset from kaggle (we're using google colab here, adapt to your IDE)from google.colab import filesuploaded = files.upload()# initialize data framedf = pd.read_csv("covtype.csv")print(df.head())print(df.tail())# that's a lot of rows!# notice that we use all features of our dataset so that we can illustrate how taxing cross validation will beX=df.loc[:,'Elevation':'Soil_Type40']y=df['Cover_Type']# some nan values happen to sneak into our dataset so we will fill them upX = X.fillna(method='ffill')y = y.fillna(method='ffill')# use a K-nearest neighbhors machine learning algorithmneigh = KNeighborsClassifier(n_neighbors=5)# only with 200 folds are we able to generate an accuracy of 80%neigh.fit(X,y)kFoldStart = time.time()y_pred = cross_val_predict(neigh, X, y, cv = 200)kFoldEnd = time.time()kFoldTime = kFoldEnd - kFoldStartprint("K Fold Validation Accuracy is ", accuracy_score(y, y_pred))# it takes 16 minutes to run the K-Fold cross validation!!!!print(kFoldTime)
Output:
K Fold Validation Accuracy is 0.8016822371999202K-Fold Validation takes 1001.0495188236237 seconds
# generate a heatmap of a confusion matrix with predicted and true values of the type of treeslabels = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]cm = confusion_matrix(y_pred, y, labels)print(cm)fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(cm, vmin=0, vmax=19000)fig.colorbar(cax)ax.set_xticklabels([''] + labels)ax.set_yticklabels([''] + labels)plt.xlabel('Predicted')plt.ylabel('True')plt.show()
Output:
[[166004 46040 27 0 243 43 1902] [ 41396 225886 1919 4 1808 1156 293] [ 59 3704 31832 442 143 1591 0] [ 0 7 267 2119 0 124 0] [ 539 4504 208 0 7251 68 5] [ 50 2434 1501 182 44 14385 0] [ 3792 726 0 0 4 0 18310]]
Holdout validation:
# split our dataset into training and testing dataX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=101)# some nan values happen to sneak into our dataset so we will fill them upX_train = X_train.fillna(method='ffill')y_train = y_train.fillna(method='ffill')# run the holdout validation and make predictions# it takes only 30 seconds for a normal validation which is still pretty longneigh.fit(X_train, y_train)holdOutStart = time.time()holdOutPredictions = neigh.predict(X_test)holdOutEnd = time.time()holdOutTime = holdOutEnd - holdOutStartprint("Hold Out Validation takes ", holdOutTime, " seconds")print(accuracy_score(y_test, holdOutPredictions))# notice how much more accurate the holdout validation is compared to the k-fold cross validation# generate a heatmap of a confusion matrix with predicted and true values of the type of treeslabels = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]cm = confusion_matrix(holdOutPredictions, y_test, labels)print(cm)fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(cm, vmin=0, vmax=8000)fig.colorbar(cax)ax.set_xticklabels([''] + labels)ax.set_yticklabels([''] + labels)plt.xlabel('Predicted')plt.ylabel('True')plt.show()
Model Validation: Any process by which a generated model is verified against additional data not used in the process of generating the model. E.g. cross validation, K-Fold validation, hold out validation, etc.Cross Validation: A type of model validation where multiple subsets of a given dataset are created and verified against each-other, usually in an iterative approach requiring the generation of a number of separate models equivalent to the number of groups generated.K-Fold Cross Validation: A type of cross validation where a given dataset is split into k number of groups and k number of models are generated. One of the groups is chosen as the test data, and the other k-1 groups are used as training data, and model generated and scored. This process is repeated k times such that each k-fold (group) serves as the testing group once.LOOCV: A type of cross validation similar to K-Fold validation, where k is equal to the length of the dataset which the validation is being performed on. Bias: The error resulting from the difference between the expected value(s) of a model and the actual (or “correct”) value(s) for which we want to predict over multiple iterations. In the scientific concepts of accuracy and precision, bias is very similar to accuracy.Variance: The error resulting from the variability between different data predictions in a model. In variance, the correct value(s) don’t matter as much as the range of differences in value between the predictions. Variance also comes into play more when we run multiple model creation trials.Under fit: Occurs when the model is so tightly fit to the training data that it may account for random noise or unwanted trends which will not be present or useful in predicting targets for subsequent datasets.Over fit: Occurs when the model is not complex enough to account for general trends in the data which would be useful in predicting targets in subsequent datasets, such as using a linear fit on a polynomial trend.Bias-Variance Trade-off: The idea that as error due to bias decreases error due to variance increases, creating a trade-off which should be minimized in model validation, and other circumstances.
|
[
{
"code": null,
"e": 226,
"s": 172,
"text": "By: Caleb Neale, Demetri Workman, Abhinay Dommalapati"
},
{
"code": null,
"e": 856,
"s": 226,
"text": "In beginning your journey into the world of machine learning and data science, there is often a temptation to jump into algorithms and model creation, without gaining an understanding of how to test the effectiveness of a generated model on real world data. Cross validation is a form of model validation which attempts to improve on the basic methods of hold-out validation by leveraging subsets of our data and an understanding of the bias/variance trade-off in order to gain a better understanding of how our models will actually perform when applied outside of the data it was trained on. Don’t worry, it’ll all be explained!"
},
{
"code": null,
"e": 1162,
"s": 856,
"text": "This article seeks to be a beginning to execution guide for three methods of model validation (hold out, k-fold, and LOOCV) and the concepts behind them, with links and references to guide you to further reading. We make use of scikit learn, pandas, numpy and other python libraries in the given examples."
},
{
"code": null,
"e": 1202,
"s": 1162,
"text": "What will be addressed in this article:"
},
{
"code": null,
"e": 1228,
"s": 1202,
"text": "What is model validation?"
},
{
"code": null,
"e": 1249,
"s": 1228,
"text": "Why is it important?"
},
{
"code": null,
"e": 1312,
"s": 1249,
"text": "What are bias and variance in the context of model validation?"
},
{
"code": null,
"e": 1338,
"s": 1312,
"text": "What is cross validation?"
},
{
"code": null,
"e": 1363,
"s": 1338,
"text": "What are common methods?"
},
{
"code": null,
"e": 1420,
"s": 1363,
"text": "Where, and when should different methods be implemented?"
},
{
"code": null,
"e": 1469,
"s": 1420,
"text": "How do various methods of cross validation work?"
},
{
"code": null,
"e": 1531,
"s": 1469,
"text": "How can we leverage cross validation to create better models?"
},
{
"code": null,
"e": 2488,
"s": 1531,
"text": "Model validation is the process by which we ensure that our models can perform acceptable in “the real world.” In more technical terms, model validation allows you to predict how your model will perform on datasets not used in the training (model validation is a big part of why preventing data leakage is so important). Model validation is important because we don’t actually care how well the model predicts data we trained it on. We already know the target values for the data we used to train a model, and as such it is much more important to consider how robust and capable a model is when tasked to model new datasets of the same distribution and characteristics, but with different individual values from our training set. The first form of model validation introduced is usually what is known as holdout validation, often considered to be the simplest form of cross validation and thus the easiest to implement. Let’s work through an example below."
},
{
"code": null,
"e": 2593,
"s": 2488,
"text": "For this example, we’ll use a linear regression on the scikit-learn database of California housing data."
},
{
"code": null,
"e": 2803,
"s": 2593,
"text": "# import scikit learn databasesfrom sklearn import datasets# import california housing data from sklearn and store data into a variablecalihouses = datasets.fetch_california_housing()calidata = calihouses.data"
},
{
"code": null,
"e": 2965,
"s": 2803,
"text": "Once the data is stored into a variable we can more easily work with, we’ll convert in into a pandas dataframe so we can more easily view and work with the data."
},
{
"code": null,
"e": 3260,
"s": 2965,
"text": "# import pandas and numpyimport pandas as pdimport numpy as np# define the columns names of the data then convert to dataframeheaders = calihouses.feature_namesdf = pd.DataFrame(calidata, columns=headers)# print the df and shape to get a better understanding of the dataprint(df.shape)print(df)"
},
{
"code": null,
"e": 3721,
"s": 3260,
"text": "Now that we’ve seen the data we’re working with, we can begin the process of generating a model and cross validation. In holdout validation, we split the data into a training and testing set. The training set will be what the model is created on and the testing data will be used to validate the generated model. Though there are (fairly easy) ways to do this using pandas methods, we can make use of scikit-learns “train_test_split” method to accomplish this."
},
{
"code": null,
"e": 4073,
"s": 3721,
"text": "# first store all target data to a variabley = calihouses.target# create testing and training sets for hold-out verification using scikit learn methodfrom sklearn import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.25)# validate set shapesprint(X_train.shape, y_train.shape)print(X_test.shape, y_test.shape)"
},
{
"code": null,
"e": 4448,
"s": 4073,
"text": "As you can see, we use the “train_test_split” with three parameters: the input (X) data, the target (y) data, and the percentage of data we’d like to remove and put into the test dataset, in this case 25% (common split is usually 70–30, depending on a multitude of factors about your data). We then assign the split X and y data to a set of new variables to work with later."
},
{
"code": null,
"e": 4492,
"s": 4448,
"text": "Your output should appear at this point as:"
},
{
"code": null,
"e": 4529,
"s": 4492,
"text": "(15480, 8) (15480,)(5160, 8) (5160,)"
},
{
"code": null,
"e": 4899,
"s": 4529,
"text": "Now that we’ve created our test/train split we can create a model and generate some predictions based on the train data. Though there are other methods of creating a model which show more of the nitty gritty, we’ll use scikit learn to make our lives a little easier. I’ve included a few lines to time the runtime of the function, which we will use for later comparison."
},
{
"code": null,
"e": 5330,
"s": 4899,
"text": "# time function using .time methods for later comparisonfrom timeit import default_timer as timerstart_ho = timer()# fit a model using linear model method from sklearnfrom sklearn import linear_modellm = linear_model.LinearRegression()model = lm.fit(X_train, y_train)# generate predictionspredictions = lm.predict(X_test)end_ho = timer()# calcualte function runtimetime_ho = (end_ho - start_ho)# show predictionsprint(predictions)"
},
{
"code": null,
"e": 5983,
"s": 5330,
"text": "Let’s pause here for a moment and look at what we’ve done. Everything up to this point is just setup in creating a linear model and using it to make predictions on a dataset. This is how far you get without model validation. In other words, we have yet to look at how the model performs on its predictions of the test data when compared to the actual target values in the test data. The test/train split we did earlier was necessary to divide the data such that we can now test the model on data that was not used in training (see: data leakage). Now that we have a model, and have created some predictions, let’s go though with our holdout validation."
},
{
"code": null,
"e": 6112,
"s": 5983,
"text": "We’ll start by graphing our given target data vs our predicted target data to give us a visualization of how our model performs."
},
{
"code": null,
"e": 6463,
"s": 6112,
"text": "# import seaborn and plotlymport matplotlibfrom matplotlib import pyplot as pltimport seaborn as sns# set viz stylesns.set_style('dark')# plot the modelplot = sns.scatterplot(y_test, predictions)plot.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')"
},
{
"code": null,
"e": 6471,
"s": 6463,
"text": "Output:"
},
{
"code": null,
"e": 6664,
"s": 6471,
"text": "In a perfect model (overfit maybe), all our data points would be on that red line, but as our data points approximate that trend, we can see the model is roughly appropriate for the test data."
},
{
"code": null,
"e": 6738,
"s": 6664,
"text": "Now, lets get a score for the model to evaluate it against later methods."
},
{
"code": null,
"e": 6973,
"s": 6738,
"text": "start_ho_score = timer()# model score (neg_mean_squared_error)from sklearn import metricsho_score = -1*metrics.mean_squared_error(y_test, predictions)print(ho_score)end_ho_score = timer()ho_score_time = (end_ho_score - start_ho_score)"
},
{
"code": null,
"e": 6981,
"s": 6973,
"text": "Output:"
},
{
"code": null,
"e": 7001,
"s": 6981,
"text": "-0.5201754311947533"
},
{
"code": null,
"e": 7350,
"s": 7001,
"text": "That’s model validation! We created a model using training data, used it to predict outcomes on a split segment of test data then used a scoring method to determine a measure of effectiveness (negative mean squared error) of the model on the testing data. This gives us an approximation of how well the model will perform on other similar datasets."
},
{
"code": null,
"e": 7754,
"s": 7350,
"text": "Now, a few things to consider. We validated our model once. What if the split we made just happened to be very conducive to this model? What if the split we made introduced a large skew into the date? Didn’t we significantly reduce the size of our training dataset by splitting it like that? These are a few questions we’ll consider as we move into cross validation, but first a few background concepts."
},
{
"code": null,
"e": 8363,
"s": 7754,
"text": "To understand bias and variance, let’s first address over and under fit models. On overfit model is generated when the model is so tightly fit to the training data that it may account for random noise or unwanted trends which will not be present or useful in predicting targets for subsequent datasets. Underfit occurs when the model is not complex enough to account for general trends in the data which would be useful in predicting targets in subsequent datasets, such as using a linear fit on a polynomial trend(An awesome visualization and further explanation of this concept from AWS can be found here)."
},
{
"code": null,
"e": 8585,
"s": 8363,
"text": "When creating a model, we account for a few types of error: validation error, testing error, error due to bias, and error due to variance in a relationship known as the bias variance trade-off (another great visual here)."
},
{
"code": null,
"e": 8897,
"s": 8585,
"text": "As mentioned earlier, we want to know how the model will perform “in the real world.” Part of that is validation error, which is comprised of error due to bias and error due to variance (training error does not provide information on how the model will perform on future datasets, and can be set aside for now)."
},
{
"code": null,
"e": 9287,
"s": 8897,
"text": "Minimizing model validation error requires finding the point of model complexity where the combination of bias and variance error is minimized, as shown in the linked visual. As model complexity increases, error due to bias decreases, while error due to variance increases, creating the bias-variance trade-off, which we will seek to address later with various methods of cross validation."
},
{
"code": null,
"e": 9323,
"s": 9287,
"text": "Now let’s define bias and variance:"
},
{
"code": null,
"e": 9328,
"s": 9323,
"text": "Bias"
},
{
"code": null,
"e": 9599,
"s": 9328,
"text": "Bias is the error resulting from the difference between the expected value(s) of a model and the actual (or “correct”) value(s) for which we want to predict over multiple iterations. In the scientific concepts of accuracy and precision, bias is very similar to accuracy."
},
{
"code": null,
"e": 9608,
"s": 9599,
"text": "Variance"
},
{
"code": null,
"e": 9915,
"s": 9608,
"text": "Variance is defined as the error resulting from the variability between different data predictions in a model. In variance, the correct value(s) don’t matter as much as the range of differences in value between the predictions. Variance also comes into play more when we run multiple model creation trials."
},
{
"code": null,
"e": 9959,
"s": 9915,
"text": "More complete definitions and visuals here."
},
{
"code": null,
"e": 10510,
"s": 9959,
"text": "In machine learning, bias and variance are often discussed together as a “bias-variance tradeoff,” saying that minimizing one error effectively makes the one more likely to be present when creating and assessing a model. Ideally, we would seek a model whose tradeoff results in both low bias and low variance, and we would look to achieve this by using cross validation. Depending on characteristics of the dataset, one method of cross validation is likely to be more ideal to achieving the bias-variance tradeoff when creating and assessing a model."
},
{
"code": null,
"e": 10742,
"s": 10510,
"text": "What if the split we made just happened to be very conducive to this model? What if the split we made introduced a large skew into the date? Didn’t we significantly reduce the size of our training dataset by splitting it like that?"
},
{
"code": null,
"e": 10936,
"s": 10742,
"text": "Cross validation is a method of model validation which splits the data in creative ways in order to obtain the better estimates of “real world” model performance, and minimize validation error."
},
{
"code": null,
"e": 11029,
"s": 10936,
"text": "Remember those questions we asked about hold out validation? Cross validation is our answer."
},
{
"code": null,
"e": 11053,
"s": 11029,
"text": "K-Fold Cross Validation"
},
{
"code": null,
"e": 11579,
"s": 11053,
"text": "K-fold validation is a popular method of cross validation which shuffles the data and splits it into k number of folds (groups). In general K-fold validation is performed by taking one group as the test data set, and the other k-1 groups as the training data, fitting and evaluating a model, and recording the chosen score. This process is then repeated with each fold (group) as the test data and all the scores averaged to obtain a more comprehensive model validation score. (More reading and a helpful visualization here)."
},
{
"code": null,
"e": 11928,
"s": 11579,
"text": "When choosing a value for k each fold(group) should be large enough to be representative of the model (commonly k=10 or k=5) and small enough to be computed in a reasonable amount of time. Depending on the dataset size, different k values can sometimes be experimented with. As a general rule, as k increases, bias decreases and variance increases."
},
{
"code": null,
"e": 11987,
"s": 11928,
"text": "Lets work though an example with our dataset from earlier."
},
{
"code": null,
"e": 12215,
"s": 11987,
"text": "We’ll make use of a linear model again, but this time do model validation with scikit learn’s cross_val_predict method which will do most of the heavy lifting in generating K-Fold predictions. In this case, I chose to set k=10."
},
{
"code": null,
"e": 12541,
"s": 12215,
"text": "# store data as an arrayX = np.array(df)# again, timing the function for comparisonstart_kfold = timer()# use cross_val_predict to generate K-Fold predictionslm_k = linear_model.LinearRegression()k_predictions = cross_val_predict(lm_k, X, y, cv=10)print(k_predictions)end_kfold = timer()kfold_time = (end_kfold - start_kfold)"
},
{
"code": null,
"e": 12566,
"s": 12541,
"text": "Output (or approximate):"
},
{
"code": null,
"e": 12638,
"s": 12566,
"text": "[4.22358985 4.04800271 3.75534521 ... 0.14474758 0.29600522 0.49525933]"
},
{
"code": null,
"e": 12900,
"s": 12638,
"text": "‘cross_val_predict’ takes the model used on the data, the input and target data, as well as a ‘cv’ argument — which is essentially our k value — and returns the predicted values for each input. Now we can plot the predictions as we did with the hold out method."
},
{
"code": null,
"e": 13140,
"s": 12900,
"text": "# plot k-fold predictions against actualplot_k = sns.scatterplot(y, k_predictions)plot_k.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')"
},
{
"code": null,
"e": 13148,
"s": 13140,
"text": "Output:"
},
{
"code": null,
"e": 13236,
"s": 13148,
"text": "Now let’s get the scores of the 10 generated models and plot them into a visualization."
},
{
"code": null,
"e": 13567,
"s": 13236,
"text": "kfold_score_start = timer()# find the mean score from the k-fold models usinf cross_val_scorekfold_scores = cross_val_score(lm_k, X, y, cv=10, scoring='neg_mean_squared_error')print(kfold_scores.mean())kfold_score_end = timer()kfold_score_time = (kfold_score_end - kfold_score_start)# plot scoressns.distplot(kfold_scores, bins=5)"
},
{
"code": null,
"e": 13575,
"s": 13567,
"text": "Output:"
},
{
"code": null,
"e": 13595,
"s": 13575,
"text": "-0.5509524296956634"
},
{
"code": null,
"e": 13716,
"s": 13595,
"text": "You’ll notice that the score is a little farther from zero than the holdout method (not good). We’ll discuss that later."
},
{
"code": null,
"e": 13747,
"s": 13716,
"text": "Leave One Out Cross Validation"
},
{
"code": null,
"e": 14065,
"s": 13747,
"text": "Leave One Out Cross Validation (LOOCV) can be considered a type of K-Fold validation where k=n given n is the number of rows in the dataset. Other than that the methods are quire similar. You will notice, however, that running the following code will take much longer than previous methods. We’ll dig into that later."
},
{
"code": null,
"e": 14154,
"s": 14065,
"text": "Let’s work an example with the same dataset, following the same process and modifying k:"
},
{
"code": null,
"e": 14176,
"s": 14154,
"text": "Generate predictions:"
},
{
"code": null,
"e": 14331,
"s": 14176,
"text": "start_LOO = timer()# generate LOO predictionsLOO_predictions = cross_val_predict(lm_k, X, y, cv=(len(X)))end_LOO = timer()LOO_time = (end_LOO - start_LOO)"
},
{
"code": null,
"e": 14353,
"s": 14331,
"text": "Plot the predictions:"
},
{
"code": null,
"e": 14596,
"s": 14353,
"text": "# plot LOO predictions against actualplot_LOO = sns.scatterplot(y, LOO_predictions)plot_LOO.set(xlabel='Given', ylabel='Prediction')# generate and graph y = x linex_plot = np.linspace(0,5,100)y_plot = x_plotplt.plot(x_plot, y_plot, color='r')"
},
{
"code": null,
"e": 14604,
"s": 14596,
"text": "Output:"
},
{
"code": null,
"e": 14633,
"s": 14604,
"text": "Generate and average scores:"
},
{
"code": null,
"e": 14905,
"s": 14633,
"text": "LOO_score_start = timer()# find the mean score from the LOO models using cross_val_score LOO_score = cross_val_score(lm_k, X, y, cv=(len(X)), scoring='neg_mean_squared_error').mean()print(LOO_score)LOO_score_end = timer()LOO_score_time = (LOO_score_end - LOO_score_start)"
},
{
"code": null,
"e": 14969,
"s": 14905,
"text": "Now lets compare the run times and scores of our three methods:"
},
{
"code": null,
"e": 15400,
"s": 14969,
"text": "print(\"Hold out method took\", time_ho, \"seconds to generate a model and\", ho_score_time ,\"seconds to generate a MSE of\", ho_score)print(\"K-Fold method took\", kfold_time, 'seconds to generate a model and', kfold_score_time, 'seconds to generate a MSE of', kfold_scores.mean())print(\"Leave One Out Cross Validation method took\", LOO_time, 'seconds to generate a model and', LOO_score_time, 'seconds to generate a MSE of', LOO_score)"
},
{
"code": null,
"e": 15408,
"s": 15400,
"text": "Output:"
},
{
"code": null,
"e": 15551,
"s": 15408,
"text": "Hold out method took 0.03958953900000495 seconds to generate a model and 0.002666198000042641 seconds to generate a MSE of -0.5201754311947533"
},
{
"code": null,
"e": 15690,
"s": 15551,
"text": "K-Fold method took 0.07809067700000583 seconds to generate a model and 0.1253743699999177 seconds to generate a MSE of -0.5509524296956634"
},
{
"code": null,
"e": 15852,
"s": 15690,
"text": "Leave One Out Cross Validation method took 152.00629317099992 seconds to generate a model and 161.83364986200013 seconds to generate a MSE of -0.5282462043712458"
},
{
"code": null,
"e": 15937,
"s": 15852,
"text": "Let’s dig into these results a little, as well as some of the points raised earlier."
},
{
"code": null,
"e": 16355,
"s": 15937,
"text": "As we noticed in the results of our comparison, we can see that the LOOCV method takes way longer to complete than our other two. This is because that method creates and evaluates a model for each row in the dataset, in this case over 20,000. Even though our MSE is a little lower, this may not be worth it given the additional computational requirements. Here are some heuristics which can help in choosing a method."
},
{
"code": null,
"e": 16371,
"s": 16355,
"text": "Hold out method"
},
{
"code": null,
"e": 16716,
"s": 16371,
"text": "The hold out method can be effective and computationally inexpensive on very large datasets, or on limited computational resources. It is also often easier to implement and understand for beginners. However, it is very rarely good to apply to small datasets as it can significantly reduce the training data available and hurt model performance."
},
{
"code": null,
"e": 16740,
"s": 16716,
"text": "K-Fold Cross Validation"
},
{
"code": null,
"e": 17121,
"s": 16740,
"text": "K-Fold can be very effective on medium sized datasets, though by adjusting the K value can significantly alter the results of the validation. Let’s add to our rule from earlier; as k increases, bias decreases, and variance and computational requirements increase. K-Fold cross validation is likely the most common of the three methods due to the versatility of adjusting K-values."
},
{
"code": null,
"e": 17127,
"s": 17121,
"text": "LOOCV"
},
{
"code": null,
"e": 17442,
"s": 17127,
"text": "LOOCV is most useful in small datasets as it allows for the smallest amount of data to be removed from the training data in each iteration. However, in large datasets the process of generating a model for each row in the dataset can be incredibly computationally expensive and thus prohibitive for larger datasets."
},
{
"code": null,
"e": 17461,
"s": 17442,
"text": "Holdout Validation"
},
{
"code": null,
"e": 17942,
"s": 17461,
"text": "In holdout validation, we are doing nothing more than performing a simple train/test split in which we fit our model to our training data and apply it to our testing data to generate predicted values. We “hold out” the testing data to be strictly used for prediction purposes only. Holdout validation is NOT a cross validation technique. But we must discuss the standard method of model evaluation so that we can compare its attributes with the actual cross validation techniques."
},
{
"code": null,
"e": 18298,
"s": 17942,
"text": "When it comes to code, holdout validation is easy to use. The implementation is simple and doesn’t require large dedications to computational power and time complexity. Moreover, we can interpret and understand the results of holdout validation better as they don’t require us to figure out how the iterations are performing in the grand scheme of things."
},
{
"code": null,
"e": 18827,
"s": 18298,
"text": "However, holdout validation does not preserve the statistical integrity of the dataset in many cases. For instance, a holdout validation that splits the data into training and testing segments causes bias by not incorporating the testing data into the model. The testing data could contain some important observations. This would result in a detriment to the accuracy of the model. Furthermore, this will cause an underfitting and overfitting of the data in addition to an introduction of validation and/or training error.K-fold"
},
{
"code": null,
"e": 19769,
"s": 18827,
"text": "In K-fold cross validation, we answer many of the problems inherent in holdout validation such as underfitting/overfitting and validation and training error. This is done by using all of the observations in our validation set at some iteration. We compute an average accuracy score of all the accuracy scores that are calculated in each k iteration. By doing so, we minimize bias and variation that may be present in our initial model evaluation technique, holdout validation. However, in terms of computational power, k-fold cross validation is very costly. The computer has to perform several iterations to generate a proper accuracy score. The accuracy score of the model will in theory increase with each added k iteration. This will decrease bias while increasing variation. We will see an example of this later in this article when we attempt to apply k-fold validation to a very large dataset that contains about 580,000 observations."
},
{
"code": null,
"e": 19775,
"s": 19769,
"text": "LOOCV"
},
{
"code": null,
"e": 20256,
"s": 19775,
"text": "LOOCV is very similar to K-fold, with a special case in which k is equal to the length (or number of samples/rows) of the whole dataset. Thus the training set will be of length k-1, and the testing set will be a single sample of the data. LOOCV is particularly useful in the case that our data set is not large enough to sensibly do Kfold. LOOCV is also less computationally expensive in general, although it is usually due to the inherently smaller datasets that tend utilize it."
},
{
"code": null,
"e": 20573,
"s": 20256,
"text": "However, LOOCV tends to yield high variance due to the fact that the method would pick up on all of the possible noise and outlier values in the data through the individual testing values. LOOCV would be very computationally expensive for very large data sets; in this case, it would be better to use regular k-fold."
},
{
"code": null,
"e": 21259,
"s": 20573,
"text": "Cross validation becomes a computationally expensive and taxing method of model evaluation when dealing with large datasets. Generating prediction values ends up taking a very long time because the validation method have to run k times in K-Fold strategy, iterating through the entire dataset. Thus cross validation becomes a very costly model evaluation strategy in terms of time complexity. We will examine this phenomenon by performing a normal holdout validation and a K-Fold cross validation on a very large dataset with approximately 580,000 rows. See if you can figure it out, why it works the way it does (and the new data visualizations), and comment any questions. Good luck!"
},
{
"code": null,
"e": 22244,
"s": 21259,
"text": "# upload dataset from kaggle (we're using google colab here, adapt to your IDE)from google.colab import filesuploaded = files.upload()# initialize data framedf = pd.read_csv(\"covtype.csv\")print(df.head())print(df.tail())# that's a lot of rows!# notice that we use all features of our dataset so that we can illustrate how taxing cross validation will beX=df.loc[:,'Elevation':'Soil_Type40']y=df['Cover_Type']# some nan values happen to sneak into our dataset so we will fill them upX = X.fillna(method='ffill')y = y.fillna(method='ffill')# use a K-nearest neighbhors machine learning algorithmneigh = KNeighborsClassifier(n_neighbors=5)# only with 200 folds are we able to generate an accuracy of 80%neigh.fit(X,y)kFoldStart = time.time()y_pred = cross_val_predict(neigh, X, y, cv = 200)kFoldEnd = time.time()kFoldTime = kFoldEnd - kFoldStartprint(\"K Fold Validation Accuracy is \", accuracy_score(y, y_pred))# it takes 16 minutes to run the K-Fold cross validation!!!!print(kFoldTime)"
},
{
"code": null,
"e": 22252,
"s": 22244,
"text": "Output:"
},
{
"code": null,
"e": 22351,
"s": 22252,
"text": "K Fold Validation Accuracy is 0.8016822371999202K-Fold Validation takes 1001.0495188236237 seconds"
},
{
"code": null,
"e": 22756,
"s": 22351,
"text": "# generate a heatmap of a confusion matrix with predicted and true values of the type of treeslabels = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]cm = confusion_matrix(y_pred, y, labels)print(cm)fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(cm, vmin=0, vmax=19000)fig.colorbar(cax)ax.set_xticklabels([''] + labels)ax.set_yticklabels([''] + labels)plt.xlabel('Predicted')plt.ylabel('True')plt.show()"
},
{
"code": null,
"e": 22764,
"s": 22756,
"text": "Output:"
},
{
"code": null,
"e": 22976,
"s": 22764,
"text": "[[166004 46040 27 0 243 43 1902] [ 41396 225886 1919 4 1808 1156 293] [ 59 3704 31832 442 143 1591 0] [ 0 7 267 2119 0 124 0] [ 539 4504 208 0 7251 68 5] [ 50 2434 1501 182 44 14385 0] [ 3792 726 0 0 4 0 18310]]"
},
{
"code": null,
"e": 22996,
"s": 22976,
"text": "Holdout validation:"
},
{
"code": null,
"e": 24200,
"s": 22996,
"text": "# split our dataset into training and testing dataX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=101)# some nan values happen to sneak into our dataset so we will fill them upX_train = X_train.fillna(method='ffill')y_train = y_train.fillna(method='ffill')# run the holdout validation and make predictions# it takes only 30 seconds for a normal validation which is still pretty longneigh.fit(X_train, y_train)holdOutStart = time.time()holdOutPredictions = neigh.predict(X_test)holdOutEnd = time.time()holdOutTime = holdOutEnd - holdOutStartprint(\"Hold Out Validation takes \", holdOutTime, \" seconds\")print(accuracy_score(y_test, holdOutPredictions))# notice how much more accurate the holdout validation is compared to the k-fold cross validation# generate a heatmap of a confusion matrix with predicted and true values of the type of treeslabels = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]cm = confusion_matrix(holdOutPredictions, y_test, labels)print(cm)fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(cm, vmin=0, vmax=8000)fig.colorbar(cax)ax.set_xticklabels([''] + labels)ax.set_yticklabels([''] + labels)plt.xlabel('Predicted')plt.ylabel('True')plt.show()"
}
] |
C++ Atomic Library - Compare Exchange
|
It atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not.
Following is the declaration for std::atomic_compare_exchange_weak.
template< class T >
bool atomic_compare_exchange_weak( volatile std::atomic<T>* obj,
T* expected, T desired );
template< class T <
bool atomic_compare_exchange_weak( std::atomic<T>* obj,
T* expected, T desired );
Following is the declaration for std::atomic_compare_exchange_strong.
template< class T >
bool atomic_compare_exchange_strong( volatile std::atomic<T>* obj,
T* expected, T desired );
template< class T >
bool atomic_compare_exchange_strong( std::atomic<T>* obj,
T* expected, T desired );
Following is the declaration for std::atomic_compare_exchange_weak_explicit.
template< class T >
bool atomic_compare_exchange_weak_explicit( volatile std::atomic<T>* obj,
T* expected, T desired,
std::memory_order succ,
std::memory_order fail );
template< class T >
bool atomic_compare_exchange_weak_explicit( std::atomic<T>* obj,
T* expected, T desired,
std::memory_order succ,
std::memory_order fail );
Following is the declaration for std::atomic_compare_exchange_strong_explicit.
template< class T >
bool atomic_compare_exchange_strong_explicit( std::atomic<T>* obj,
T* expected, T desired,
std::memory_order succ,
std::memory_order fail );
template< class T >
bool atomic_compare_exchange_strong_explicit( volatile std::atomic<T>* obj,
T* expected, T desired,
std::memory_order succ,
std::memory_order fail );
obj − It is used in pointer to the atomic object to modify.
obj − It is used in pointer to the atomic object to modify.
desr − It is used to store the value in the atomic object.
desr − It is used to store the value in the atomic object.
order − It is used to synchronise the memory ordering for this operation.
order − It is used to synchronise the memory ordering for this operation.
succ − It is used in the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted.
succ − It is used in the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted.
fail − It is used in the memory synchronization ordering for the load operation if the comparison fails. Cannot be std::memory_order_release or std::memory_order_acq_rel and cannot specify stronger ordering than succ.
fail − It is used in the memory synchronization ordering for the load operation if the comparison fails. Cannot be std::memory_order_release or std::memory_order_acq_rel and cannot specify stronger ordering than succ.
It returns the result of the comparison: true if *obj was equal to *expected, false otherwise.
No-noexcept − this member function never throws exceptions.
In below example for std::atomic_compare_exchange.
#include <atomic>
template<class T>
struct node {
T data;
node* next;
node(const T& data) : data(data), next(nullptr) {}
};
template<class T>
class stack {
std::atomic<node<T>*> head;
public:
void push(const T& data) {
node<T>* new_node = new node<T>(data);
new_node->next = head.load(std::memory_order_relaxed);
while(!std::atomic_compare_exchange_weak_explicit(&head, &new_node->next,
new_node, std::memory_order_release, std::memory_order_relaxed))
;
}
};
int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2743,
"s": 2603,
"text": "It atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not."
},
{
"code": null,
"e": 2811,
"s": 2743,
"text": "Following is the declaration for std::atomic_compare_exchange_weak."
},
{
"code": null,
"e": 2958,
"s": 2811,
"text": "template< class T >\nbool atomic_compare_exchange_weak( volatile std::atomic<T>* obj, \n T* expected, T desired );"
},
{
"code": null,
"e": 3096,
"s": 2958,
"text": "template< class T <\nbool atomic_compare_exchange_weak( std::atomic<T>* obj, \n T* expected, T desired );"
},
{
"code": null,
"e": 3166,
"s": 3096,
"text": "Following is the declaration for std::atomic_compare_exchange_strong."
},
{
"code": null,
"e": 3316,
"s": 3166,
"text": "template< class T >\nbool atomic_compare_exchange_strong( volatile std::atomic<T>* obj,\n T* expected, T desired );"
},
{
"code": null,
"e": 3457,
"s": 3316,
"text": "template< class T >\nbool atomic_compare_exchange_strong( std::atomic<T>* obj,\n T* expected, T desired );"
},
{
"code": null,
"e": 3534,
"s": 3457,
"text": "Following is the declaration for std::atomic_compare_exchange_weak_explicit."
},
{
"code": null,
"e": 3835,
"s": 3534,
"text": "template< class T >\nbool atomic_compare_exchange_weak_explicit( volatile std::atomic<T>* obj,\n T* expected, T desired,\n std::memory_order succ, \n std::memory_order fail );"
},
{
"code": null,
"e": 4127,
"s": 3835,
"text": "template< class T >\nbool atomic_compare_exchange_weak_explicit( std::atomic<T>* obj,\n T* expected, T desired,\n std::memory_order succ, \n std::memory_order fail );"
},
{
"code": null,
"e": 4206,
"s": 4127,
"text": "Following is the declaration for std::atomic_compare_exchange_strong_explicit."
},
{
"code": null,
"e": 4506,
"s": 4206,
"text": "template< class T >\nbool atomic_compare_exchange_strong_explicit( std::atomic<T>* obj,\n T* expected, T desired,\n std::memory_order succ, \n std::memory_order fail );"
},
{
"code": null,
"e": 4816,
"s": 4506,
"text": "template< class T >\nbool atomic_compare_exchange_strong_explicit( volatile std::atomic<T>* obj, \n T* expected, T desired,\n std::memory_order succ, \n std::memory_order fail );"
},
{
"code": null,
"e": 4876,
"s": 4816,
"text": "obj − It is used in pointer to the atomic object to modify."
},
{
"code": null,
"e": 4936,
"s": 4876,
"text": "obj − It is used in pointer to the atomic object to modify."
},
{
"code": null,
"e": 4995,
"s": 4936,
"text": "desr − It is used to store the value in the atomic object."
},
{
"code": null,
"e": 5054,
"s": 4995,
"text": "desr − It is used to store the value in the atomic object."
},
{
"code": null,
"e": 5128,
"s": 5054,
"text": "order − It is used to synchronise the memory ordering for this operation."
},
{
"code": null,
"e": 5202,
"s": 5128,
"text": "order − It is used to synchronise the memory ordering for this operation."
},
{
"code": null,
"e": 5349,
"s": 5202,
"text": "succ − It is used in the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted."
},
{
"code": null,
"e": 5496,
"s": 5349,
"text": "succ − It is used in the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted."
},
{
"code": null,
"e": 5714,
"s": 5496,
"text": "fail − It is used in the memory synchronization ordering for the load operation if the comparison fails. Cannot be std::memory_order_release or std::memory_order_acq_rel and cannot specify stronger ordering than succ."
},
{
"code": null,
"e": 5932,
"s": 5714,
"text": "fail − It is used in the memory synchronization ordering for the load operation if the comparison fails. Cannot be std::memory_order_release or std::memory_order_acq_rel and cannot specify stronger ordering than succ."
},
{
"code": null,
"e": 6027,
"s": 5932,
"text": "It returns the result of the comparison: true if *obj was equal to *expected, false otherwise."
},
{
"code": null,
"e": 6087,
"s": 6027,
"text": "No-noexcept − this member function never throws exceptions."
},
{
"code": null,
"e": 6138,
"s": 6087,
"text": "In below example for std::atomic_compare_exchange."
},
{
"code": null,
"e": 6752,
"s": 6138,
"text": "#include <atomic>\n\ntemplate<class T>\nstruct node {\n T data;\n node* next;\n node(const T& data) : data(data), next(nullptr) {}\n};\n\ntemplate<class T>\nclass stack {\n std::atomic<node<T>*> head;\n public:\n void push(const T& data) {\n node<T>* new_node = new node<T>(data);\n new_node->next = head.load(std::memory_order_relaxed);\n while(!std::atomic_compare_exchange_weak_explicit(&head, &new_node->next,\n new_node, std::memory_order_release, std::memory_order_relaxed))\n ;\n }\n};\n\nint main() {\n stack<int> s;\n s.push(1);\n s.push(2);\n s.push(3);\n}"
},
{
"code": null,
"e": 6759,
"s": 6752,
"text": " Print"
},
{
"code": null,
"e": 6770,
"s": 6759,
"text": " Add Notes"
}
] |
Converting images to a Base64 data URL using Javascript
|
To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.
This will return the base64 encoded data URI of the image. For example,
if you have an image with id my-image, you can use the following −
function getDataUrl(img) {
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set width and height
canvas.width = img.width;
canvas.height = img.height;
// Draw the image
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
const dataUrl = getDataUrl(event.currentTarget);
console.log(dataUrl);
});
This will give the output −
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it."
},
{
"code": null,
"e": 1434,
"s": 1295,
"text": "This will return the base64 encoded data URI of the image. For example,\nif you have an image with id my-image, you can use the following −"
},
{
"code": null,
"e": 1952,
"s": 1434,
"text": "function getDataUrl(img) {\n // Create canvas\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n // Set width and height\n canvas.width = img.width;\n canvas.height = img.height;\n // Draw the image\n ctx.drawImage(img, 0, 0);\n return canvas.toDataURL('image/jpeg');\n}\n// Select the image\nconst img = document.querySelector('#my-image');\nimg.addEventListener('load', function (event) {\n const dataUrl = getDataUrl(event.currentTarget);\n console.log(dataUrl);\n});"
},
{
"code": null,
"e": 1980,
"s": 1952,
"text": "This will give the output −"
},
{
"code": null,
"e": 2054,
"s": 1980,
"text": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB"
}
] |
ctype_upper() function in PHP
|
The ctype_upper() function in PHP check for uppercase character(s). It returns TRUE if every character in text is an uppercase letter in the current locale.
ctype_upper(str)
str − The tested string
str − The tested string
The ctype_upper() function returns TRUE if every character in text is an uppercase letter in the current locale.
The following is an example −
Live Demo
<?php
$arr = array('9898jjhh', 'PQR', 'Amit');
foreach ($arr as $demo) {
if (ctype_upper($demo)) {
echo "$demo has all uppercase letters. \n";
} else {
echo "$demo does not have all uppercase letters. \n";
}
}
?>
The following is the output −
9898jjhh does not have all uppercase letters.
PQR has all uppercase letters.
Amit does not have all uppercase letters.
Let us see another example −
Live Demo
<?php
$str = 'AUSTRALIA';
if (ctype_upper($str)) {
echo "Word has all uppercase characters!\n";
} else {
// if False then return No
echo "Word does not have all uppercase characters!\n";
}
?>
The following is the output −
Word has all uppercase characters!
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "The ctype_upper() function in PHP check for uppercase character(s). It returns TRUE if every character in text is an uppercase letter in the current locale."
},
{
"code": null,
"e": 1236,
"s": 1219,
"text": "ctype_upper(str)"
},
{
"code": null,
"e": 1260,
"s": 1236,
"text": "str − The tested string"
},
{
"code": null,
"e": 1284,
"s": 1260,
"text": "str − The tested string"
},
{
"code": null,
"e": 1397,
"s": 1284,
"text": "The ctype_upper() function returns TRUE if every character in text is an uppercase letter in the current locale."
},
{
"code": null,
"e": 1427,
"s": 1397,
"text": "The following is an example −"
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": " Live Demo"
},
{
"code": null,
"e": 1697,
"s": 1438,
"text": "<?php\n $arr = array('9898jjhh', 'PQR', 'Amit');\n\n foreach ($arr as $demo) {\n if (ctype_upper($demo)) {\n echo \"$demo has all uppercase letters. \\n\";\n } else {\n echo \"$demo does not have all uppercase letters. \\n\";\n }\n }\n?>"
},
{
"code": null,
"e": 1727,
"s": 1697,
"text": "The following is the output −"
},
{
"code": null,
"e": 1846,
"s": 1727,
"text": "9898jjhh does not have all uppercase letters.\nPQR has all uppercase letters.\nAmit does not have all uppercase letters."
},
{
"code": null,
"e": 1875,
"s": 1846,
"text": "Let us see another example −"
},
{
"code": null,
"e": 1886,
"s": 1875,
"text": " Live Demo"
},
{
"code": null,
"e": 2109,
"s": 1886,
"text": "<?php\n $str = 'AUSTRALIA';\n\n if (ctype_upper($str)) {\n echo \"Word has all uppercase characters!\\n\";\n } else {\n // if False then return No\n echo \"Word does not have all uppercase characters!\\n\";\n }\n?>"
},
{
"code": null,
"e": 2139,
"s": 2109,
"text": "The following is the output −"
},
{
"code": null,
"e": 2174,
"s": 2139,
"text": "Word has all uppercase characters!"
}
] |
How to get the list of all versions of the object from S3 present in AWS Resource
|
In this article, we will see how to get the list of all versions of the object from S3 those are present in AWS Resource.
List out all the versions of test.zip from Bucket_1/testfolder of S3.
Problem Statement: Use boto3 library in Python to get list of all versions of the object from S3.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: bucket_name is the required parameter.
Step 2: bucket_name is the required parameter.
Step 3: Create an AWS session using boto3 lib
Step 3: Create an AWS session using boto3 lib
Step 4: Create an AWS client for s3
Step 4: Create an AWS client for s3
Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any.
Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any.
Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket.
Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket.
Step 7: Return the list of all versions of the object.
Step 7: Return the list of all versions of the object.
Use the following code get the list of all versions of the object from AWS S3 −
import boto3
from botocore.exceptions import ClientError
def list_all_objects_version(bucket_name, prefix_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
result = s3_client.list_object_versions(Bucket=bucket_name, Prefix=prefix_name)
except ClientError as e:
raise Exception("boto3 client error in list_all_objects_version function: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in list_all_objects_version function of s3 helper: " + e.__str__())
print(list_all_objects_version("Bucket_1","testfolder"))
{'ResponseMetadata': {'RequestId': 'H4VAGM3YP6', 'HostId': ***********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': ***************', 'x-amz-request-id': 'H4VAGM3YP6', 'date': 'Sat, 03 Apr 2021 08:04:08 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': False, 'KeyMarker': '', 'VersionIdMarker': '',
'Versions': [{'ETag': '"705e2e674b04ca71"', 'Size': 1773, 'StorageClass': 'STANDARD', 'Key': 'testfolder/test.zip', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 12, 18, 14, 13, 18, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928*******************************'}}], 'Name': 'Bucket_1', 'Prefix': 'testfolder', 'MaxKeys': 1000, 'EncodingType': 'url'}
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "In this article, we will see how to get the list of all versions of the object from S3 those are present in AWS Resource."
},
{
"code": null,
"e": 1254,
"s": 1184,
"text": "List out all the versions of test.zip from Bucket_1/testfolder of S3."
},
{
"code": null,
"e": 1352,
"s": 1254,
"text": "Problem Statement: Use boto3 library in Python to get list of all versions of the object from S3."
},
{
"code": null,
"e": 1419,
"s": 1352,
"text": "Step 1: Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1486,
"s": 1419,
"text": "Step 1: Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1533,
"s": 1486,
"text": "Step 2: bucket_name is the required parameter."
},
{
"code": null,
"e": 1580,
"s": 1533,
"text": "Step 2: bucket_name is the required parameter."
},
{
"code": null,
"e": 1626,
"s": 1580,
"text": "Step 3: Create an AWS session using boto3 lib"
},
{
"code": null,
"e": 1672,
"s": 1626,
"text": "Step 3: Create an AWS session using boto3 lib"
},
{
"code": null,
"e": 1708,
"s": 1672,
"text": "Step 4: Create an AWS client for s3"
},
{
"code": null,
"e": 1744,
"s": 1708,
"text": "Step 4: Create an AWS client for s3"
},
{
"code": null,
"e": 1887,
"s": 1744,
"text": "Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any."
},
{
"code": null,
"e": 2030,
"s": 1887,
"text": "Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any."
},
{
"code": null,
"e": 2152,
"s": 2030,
"text": "Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket."
},
{
"code": null,
"e": 2274,
"s": 2152,
"text": "Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket."
},
{
"code": null,
"e": 2329,
"s": 2274,
"text": "Step 7: Return the list of all versions of the object."
},
{
"code": null,
"e": 2384,
"s": 2329,
"text": "Step 7: Return the list of all versions of the object."
},
{
"code": null,
"e": 2464,
"s": 2384,
"text": "Use the following code get the list of all versions of the object from AWS S3 −"
},
{
"code": null,
"e": 3063,
"s": 2464,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef list_all_objects_version(bucket_name, prefix_name): \n session = boto3.session.Session()\n s3_client = session.client('s3')\n try:\n result = s3_client.list_object_versions(Bucket=bucket_name, Prefix=prefix_name)\n except ClientError as e:\n raise Exception(\"boto3 client error in list_all_objects_version function: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in list_all_objects_version function of s3 helper: \" + e.__str__())\nprint(list_all_objects_version(\"Bucket_1\",\"testfolder\"))"
},
{
"code": null,
"e": 3862,
"s": 3063,
"text": "{'ResponseMetadata': {'RequestId': 'H4VAGM3YP6', 'HostId': ***********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': ***************', 'x-amz-request-id': 'H4VAGM3YP6', 'date': 'Sat, 03 Apr 2021 08:04:08 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': False, 'KeyMarker': '', 'VersionIdMarker': '',\n'Versions': [{'ETag': '\"705e2e674b04ca71\"', 'Size': 1773, 'StorageClass': 'STANDARD', 'Key': 'testfolder/test.zip', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 12, 18, 14, 13, 18, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928*******************************'}}], 'Name': 'Bucket_1', 'Prefix': 'testfolder', 'MaxKeys': 1000, 'EncodingType': 'url'}"
}
] |
Format Date and Time in Perl
|
You can use localtime() function in Perl to get a list of 9-elements and later you can use the printf() function to format date and time based on your requirements as follows −
Live Demo
#!/usr/local/bin/perl
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
printf("Time Format - HH:MM:SS\n");
printf("%02d:%02d:%02d", $hour, $min, $sec);
When the above code is executed, it produces the following result −
Time Format - HH:MM:SS
06:58:52
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "You can use localtime() function in Perl to get a list of 9-elements and later you can use the printf() function to format date and time based on your requirements as follows −"
},
{
"code": null,
"e": 1250,
"s": 1239,
"text": " Live Demo"
},
{
"code": null,
"e": 1422,
"s": 1250,
"text": "#!/usr/local/bin/perl\n($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();\nprintf(\"Time Format - HH:MM:SS\\n\");\nprintf(\"%02d:%02d:%02d\", $hour, $min, $sec);"
},
{
"code": null,
"e": 1490,
"s": 1422,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1522,
"s": 1490,
"text": "Time Format - HH:MM:SS\n06:58:52"
}
] |
HTML | Div Tag - GeeksforGeeks
|
17 Mar, 2022
The div tag is known as Division tag. The div tag is used in HTML to make divisions of content in the web page like (text, images, header, footer, navigation bar, etc). Div tag has both open(<div>) and closing (</div>) tag and it is mandatory to close the tag. The Div is the most usable tag in web development because it helps us to separate out data in the web page and we can create a particular section for particular data or function in the web pages.
Div tag is Block level tag
It is a generic container tag
It is used to the group of various tags of HTML so that sections can be created and style can be applied to them.
As we know Div tag is block-level tag in this example div tag contain entire width. It will be displayed div tag each time on a new line, not on the same line.Example 1:
<html> <head> <title>gfg</title><style type=text/css> p{ background-color:gray; margin: 10px;} div{ color: white; background-color: 009900; margin: 2px; font-size: 25px;}</style> </head> <body> <div > div tag </div> <div > div tag </div> <div > div tag </div> <div > div tag </div> </body></html>
Output:
As we know div tag is used for grouping HTML elements together and is to apply CSS and web layout on them Lets see below example without using div tag. we need to applying CSS for each tag (in the example using H1 H2 and two paragraphs p tags)
Example 2:
<html> <head> <title>gfg</title> <style type=text/css> p{ color: white; background-color: 009900; width: 400px; } h1 { color: white; background-color: 009900; width: 400px; } h2 { color: white; background-color: 009900; width: 400px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom program by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </body></html>
Output:
Creating Web Layout using Div TagThe div tag is a container tag inside div tag we can put more than one HTML element and can group together and can apply CSS for them.div tag can be used for creating a layout of web pages in the below examples shows creating a web layoutwe can also create web layout using tables tag but table tags are very complex to modify the layoutThe div tag is very flexible in creating web layouts and easy to modify. in below example will show grouping of HTML element using div tag and create block-wise web layout.Example:
<html> <head> <title>gfg</title> <style type=text/css> .leftdiv { float: left; } .middlediv { float: left; background-color:gray } .rightdiv { float: left; } div{ padding : 1%; color: white; background-color: 009900; width: 30%; border: solid black; } </style> </head> <body> <div class="leftdiv"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </div> <div class="middlediv"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </div> <div class="rightdiv"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> </div> </body></html>
Using Div tag we can cover gap between heading tag and paragraph tag in this example will display three blocks web layout.
Output:
we can use CSS in any divisions using the following methods:
1. Using class:we can use Class on that particular div either in internal CSS or external CSS
In case of internal CSS: we need to define Class in the <head> section of HTML within <style> element.
In case of External CSS: we need to create a separate .css file and include it in HTML code in <head> section using <link> element.The class name should be different from other class names in other div otherwise the CSS used in one div can affect another division.
The class name should be different from other class names in other div otherwise the CSS used in one div can affect another division.
Code:<html> <head> <link rel="stylesheet" href="color.css"> <title> gfg </title> </head> <body> <center> <div class="color"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is not USED in THIS method. </h1> </div> <!--closing tag of Div!--> </center> </body></html>
<html> <head> <link rel="stylesheet" href="color.css"> <title> gfg </title> </head> <body> <center> <div class="color"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is not USED in THIS method. </h1> </div> <!--closing tag of Div!--> </center> </body></html>
CSS for color class: File name color.css.color{height:400px;width:600px;border:1px solid;background-color: 009900;}In this example, we used a class to that particular Div. with name color.css which properties of div. It is a separate file which is linked by link tag in this HTML code
.color{height:400px;width:600px;border:1px solid;background-color: 009900;}
In this example, we used a class to that particular Div. with name color.css which properties of div. It is a separate file which is linked by link tag in this HTML code
Output:
2. Inline CSS:we can directly use CSS in div also this method does not require of CLASS. Div in HTML coding is used as a container tag also because it is the one that can contain all other tags.
Code:<html> <head> <title> gfg </title> </head> <body> <center> <div style="height:300px; width:500px; color:white; border:1px solid; background-color: 009900;"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is USED in THIS method. In this div no class is used. </h1> </div> <!--closing tag of Div!--> </center> </body></html>In this method, we applying inline CSS in the div tag. By using style attribute this style will apply to that particular div.
<html> <head> <title> gfg </title> </head> <body> <center> <div style="height:300px; width:500px; color:white; border:1px solid; background-color: 009900;"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is USED in THIS method. In this div no class is used. </h1> </div> <!--closing tag of Div!--> </center> </body></html>
In this method, we applying inline CSS in the div tag. By using style attribute this style will apply to that particular div.
Output:
Difference Between Div tag and span tag
The div and span tag are two common tags when creating pages using HTML and perform different functionality on themwhile div tag is a block level element and span is inline element The div tag creates a line break and by default creates a division between the text that comes after the tag as begun and until the tag ends with </div>. div tag creates separate boxes or containers for all elements inside this tag like text, images, paragraphs.
The span tag does not create a line break similar to a div tag, but rather allows the user to separate things from other elements around them on a page within the same line. avoiding of line break, results only that selected text to change, keeping all the other elements around them same.Below example will display the difference between span and div tag while div tag contains whole width and span tag contain only required width and rest parts are free for another element.Code:
<html> <head> <title>gfg</title> <style type=text/css> p{ background-color:gray; margin: 10px; } div { color: white; background-color: 009900; margin: 2px; font-size: 25px; } span { color: black; background-color: gray; margin: 5px; font-size: 25px; } </style> </head> <body><!-- below some div tags --> <div > div tag </div> <div > div tag </div> <div > div tag </div> <div > div tag </div> <!-- below some span tags --> <span>span-tag</span> <span>span-tag</span> <span>span-tag</span> <span>span-tag</span> </body></html>
Output:
Supported Browser: The browser supported by <div> tag are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 23150,
"s": 23122,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 23607,
"s": 23150,
"text": "The div tag is known as Division tag. The div tag is used in HTML to make divisions of content in the web page like (text, images, header, footer, navigation bar, etc). Div tag has both open(<div>) and closing (</div>) tag and it is mandatory to close the tag. The Div is the most usable tag in web development because it helps us to separate out data in the web page and we can create a particular section for particular data or function in the web pages."
},
{
"code": null,
"e": 23634,
"s": 23607,
"text": "Div tag is Block level tag"
},
{
"code": null,
"e": 23664,
"s": 23634,
"text": "It is a generic container tag"
},
{
"code": null,
"e": 23778,
"s": 23664,
"text": "It is used to the group of various tags of HTML so that sections can be created and style can be applied to them."
},
{
"code": null,
"e": 23948,
"s": 23778,
"text": "As we know Div tag is block-level tag in this example div tag contain entire width. It will be displayed div tag each time on a new line, not on the same line.Example 1:"
},
{
"code": "<html> <head> <title>gfg</title><style type=text/css> p{ background-color:gray; margin: 10px;} div{ color: white; background-color: 009900; margin: 2px; font-size: 25px;}</style> </head> <body> <div > div tag </div> <div > div tag </div> <div > div tag </div> <div > div tag </div> </body></html>",
"e": 24285,
"s": 23948,
"text": null
},
{
"code": null,
"e": 24293,
"s": 24285,
"text": "Output:"
},
{
"code": null,
"e": 24537,
"s": 24293,
"text": "As we know div tag is used for grouping HTML elements together and is to apply CSS and web layout on them Lets see below example without using div tag. we need to applying CSS for each tag (in the example using H1 H2 and two paragraphs p tags)"
},
{
"code": null,
"e": 24548,
"s": 24537,
"text": "Example 2:"
},
{
"code": "<html> <head> <title>gfg</title> <style type=text/css> p{ color: white; background-color: 009900; width: 400px; } h1 { color: white; background-color: 009900; width: 400px; } h2 { color: white; background-color: 009900; width: 400px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom program by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </body></html>",
"e": 25680,
"s": 24548,
"text": null
},
{
"code": null,
"e": 25688,
"s": 25680,
"text": "Output:"
},
{
"code": null,
"e": 26239,
"s": 25688,
"text": "Creating Web Layout using Div TagThe div tag is a container tag inside div tag we can put more than one HTML element and can group together and can apply CSS for them.div tag can be used for creating a layout of web pages in the below examples shows creating a web layoutwe can also create web layout using tables tag but table tags are very complex to modify the layoutThe div tag is very flexible in creating web layouts and easy to modify. in below example will show grouping of HTML element using div tag and create block-wise web layout.Example:"
},
{
"code": "<html> <head> <title>gfg</title> <style type=text/css> .leftdiv { float: left; } .middlediv { float: left; background-color:gray } .rightdiv { float: left; } div{ padding : 1%; color: white; background-color: 009900; width: 30%; border: solid black; } </style> </head> <body> <div class=\"leftdiv\"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </div> <div class=\"middlediv\"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>GCET is an entrance test for the extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts, mentored by Sandeep Jain (Founder & CEO, GeeksforGeeks).He has 7 years of teaching experience and 6 years of industry experience. </p> </div> <div class=\"rightdiv\"> <h1>GeeksforGeeks</h1> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> <h2>GeeksforGeeks</h2> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well-explained solutions for selected questions. </p> </div> </body></html>",
"e": 29068,
"s": 26239,
"text": null
},
{
"code": null,
"e": 29191,
"s": 29068,
"text": "Using Div tag we can cover gap between heading tag and paragraph tag in this example will display three blocks web layout."
},
{
"code": null,
"e": 29199,
"s": 29191,
"text": "Output:"
},
{
"code": null,
"e": 29260,
"s": 29199,
"text": "we can use CSS in any divisions using the following methods:"
},
{
"code": null,
"e": 29354,
"s": 29260,
"text": "1. Using class:we can use Class on that particular div either in internal CSS or external CSS"
},
{
"code": null,
"e": 29457,
"s": 29354,
"text": "In case of internal CSS: we need to define Class in the <head> section of HTML within <style> element."
},
{
"code": null,
"e": 29722,
"s": 29457,
"text": "In case of External CSS: we need to create a separate .css file and include it in HTML code in <head> section using <link> element.The class name should be different from other class names in other div otherwise the CSS used in one div can affect another division."
},
{
"code": null,
"e": 29856,
"s": 29722,
"text": "The class name should be different from other class names in other div otherwise the CSS used in one div can affect another division."
},
{
"code": null,
"e": 30292,
"s": 29856,
"text": "Code:<html> <head> <link rel=\"stylesheet\" href=\"color.css\"> <title> gfg </title> </head> <body> <center> <div class=\"color\"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is not USED in THIS method. </h1> </div> <!--closing tag of Div!--> </center> </body></html>"
},
{
"code": "<html> <head> <link rel=\"stylesheet\" href=\"color.css\"> <title> gfg </title> </head> <body> <center> <div class=\"color\"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is not USED in THIS method. </h1> </div> <!--closing tag of Div!--> </center> </body></html>",
"e": 30723,
"s": 30292,
"text": null
},
{
"code": null,
"e": 31008,
"s": 30723,
"text": "CSS for color class: File name color.css.color{height:400px;width:600px;border:1px solid;background-color: 009900;}In this example, we used a class to that particular Div. with name color.css which properties of div. It is a separate file which is linked by link tag in this HTML code"
},
{
"code": ".color{height:400px;width:600px;border:1px solid;background-color: 009900;}",
"e": 31084,
"s": 31008,
"text": null
},
{
"code": null,
"e": 31254,
"s": 31084,
"text": "In this example, we used a class to that particular Div. with name color.css which properties of div. It is a separate file which is linked by link tag in this HTML code"
},
{
"code": null,
"e": 31262,
"s": 31254,
"text": "Output:"
},
{
"code": null,
"e": 31457,
"s": 31262,
"text": "2. Inline CSS:we can directly use CSS in div also this method does not require of CLASS. Div in HTML coding is used as a container tag also because it is the one that can contain all other tags."
},
{
"code": null,
"e": 32100,
"s": 31457,
"text": "Code:<html> <head> <title> gfg </title> </head> <body> <center> <div style=\"height:300px; width:500px; color:white; border:1px solid; background-color: 009900;\"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is USED in THIS method. In this div no class is used. </h1> </div> <!--closing tag of Div!--> </center> </body></html>In this method, we applying inline CSS in the div tag. By using style attribute this style will apply to that particular div."
},
{
"code": "<html> <head> <title> gfg </title> </head> <body> <center> <div style=\"height:300px; width:500px; color:white; border:1px solid; background-color: 009900;\"> <!--open tag of Div!--> <caption> <h1>GEEKSFORGEEKS</h1> </caption> <h1>Inline CSS is USED in THIS method. In this div no class is used. </h1> </div> <!--closing tag of Div!--> </center> </body></html>",
"e": 32613,
"s": 32100,
"text": null
},
{
"code": null,
"e": 32739,
"s": 32613,
"text": "In this method, we applying inline CSS in the div tag. By using style attribute this style will apply to that particular div."
},
{
"code": null,
"e": 32747,
"s": 32739,
"text": "Output:"
},
{
"code": null,
"e": 32787,
"s": 32747,
"text": "Difference Between Div tag and span tag"
},
{
"code": null,
"e": 33231,
"s": 32787,
"text": "The div and span tag are two common tags when creating pages using HTML and perform different functionality on themwhile div tag is a block level element and span is inline element The div tag creates a line break and by default creates a division between the text that comes after the tag as begun and until the tag ends with </div>. div tag creates separate boxes or containers for all elements inside this tag like text, images, paragraphs."
},
{
"code": null,
"e": 33713,
"s": 33231,
"text": "The span tag does not create a line break similar to a div tag, but rather allows the user to separate things from other elements around them on a page within the same line. avoiding of line break, results only that selected text to change, keeping all the other elements around them same.Below example will display the difference between span and div tag while div tag contains whole width and span tag contain only required width and rest parts are free for another element.Code:"
},
{
"code": "<html> <head> <title>gfg</title> <style type=text/css> p{ background-color:gray; margin: 10px; } div { color: white; background-color: 009900; margin: 2px; font-size: 25px; } span { color: black; background-color: gray; margin: 5px; font-size: 25px; } </style> </head> <body><!-- below some div tags --> <div > div tag </div> <div > div tag </div> <div > div tag </div> <div > div tag </div> <!-- below some span tags --> <span>span-tag</span> <span>span-tag</span> <span>span-tag</span> <span>span-tag</span> </body></html>",
"e": 34496,
"s": 33713,
"text": null
},
{
"code": null,
"e": 34504,
"s": 34496,
"text": "Output:"
},
{
"code": null,
"e": 34576,
"s": 34504,
"text": "Supported Browser: The browser supported by <div> tag are listed below:"
},
{
"code": null,
"e": 34590,
"s": 34576,
"text": "Google Chrome"
},
{
"code": null,
"e": 34608,
"s": 34590,
"text": "Internet Explorer"
},
{
"code": null,
"e": 34616,
"s": 34608,
"text": "Firefox"
},
{
"code": null,
"e": 34622,
"s": 34616,
"text": "Opera"
},
{
"code": null,
"e": 34629,
"s": 34622,
"text": "Safari"
},
{
"code": null,
"e": 34823,
"s": 34629,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 35009,
"s": 34823,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 35146,
"s": 35009,
"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": 35156,
"s": 35146,
"text": "HTML-Tags"
},
{
"code": null,
"e": 35161,
"s": 35156,
"text": "HTML"
},
{
"code": null,
"e": 35166,
"s": 35161,
"text": "HTML"
},
{
"code": null,
"e": 35264,
"s": 35166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35314,
"s": 35264,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35376,
"s": 35314,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35436,
"s": 35376,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35484,
"s": 35436,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35545,
"s": 35484,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 35598,
"s": 35545,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 35648,
"s": 35598,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 35698,
"s": 35648,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 35722,
"s": 35698,
"text": "REST API (Introduction)"
}
] |
HTML - Fonts Reference
|
Fonts are specific to platform. You will have different look and feel of a web page on different machines running different operating systems like Windows, Linux or Mac iOS. Here we are giving a list of fonts which are available in various operating systems.
HTML <font> tag is deprecated in version 4.0 onwards and now all fonts are set by using CSS. Here is the simple syntax of setting font of a body of web page.
body {
font-family: "new century schoolbook";
}
or
<body style = "font-family:new century schoolbook;">
<!DOCTYPE html>
<html>
<head>
<title>Font Setting Using CSS</title>
</head>
<body>
<p>Change any of the style and try it.</p>
<div style = "font-family:verdana;">This is demo for font family</div>
<br />
<div style = "font-size:120%;">This is demo for font size</div>
<br />
<div style = "font-size:14pt;">This is demo for font size</div>
</body>
</html>
This will produce the following result −
Change any of the style and try it.
You can check example fonts here − Microsoft Fonts Examples
Following is the list of fonts supported by Macintosh System 7 and higher versions
You can check example fonts here − Mac Fonts Examples
Following is the list of fonts supported by most Unix System variants
You can check example fonts here − Unix Fonts Examples
There are 27 = 128 printable characters which can be represented by different 7-BIT ASCII codes. Another set of characters are not for HTML representation but they are devised to control hardware.
Following tables list down all the 7-BIT ASCII codes and their equivalent HTML Entity Codes.
If you want to see equivalent HEX, OCT and extended set of ASCII codes then check next chapter.
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2633,
"s": 2374,
"text": "Fonts are specific to platform. You will have different look and feel of a web page on different machines running different operating systems like Windows, Linux or Mac iOS. Here we are giving a list of fonts which are available in various operating systems."
},
{
"code": null,
"e": 2791,
"s": 2633,
"text": "HTML <font> tag is deprecated in version 4.0 onwards and now all fonts are set by using CSS. Here is the simple syntax of setting font of a body of web page."
},
{
"code": null,
"e": 2903,
"s": 2791,
"text": "body {\n font-family: \"new century schoolbook\";\n} \nor \n<body style = \"font-family:new century schoolbook;\">\n"
},
{
"code": null,
"e": 3329,
"s": 2903,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Font Setting Using CSS</title>\n </head>\n\n <body>\n <p>Change any of the style and try it.</p>\n <div style = \"font-family:verdana;\">This is demo for font family</div>\n <br />\n \n <div style = \"font-size:120%;\">This is demo for font size</div>\n <br />\n \n <div style = \"font-size:14pt;\">This is demo for font size</div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 3370,
"s": 3329,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3406,
"s": 3370,
"text": "Change any of the style and try it."
},
{
"code": null,
"e": 3466,
"s": 3406,
"text": "You can check example fonts here − Microsoft Fonts Examples"
},
{
"code": null,
"e": 3549,
"s": 3466,
"text": "Following is the list of fonts supported by Macintosh System 7 and higher versions"
},
{
"code": null,
"e": 3603,
"s": 3549,
"text": "You can check example fonts here − Mac Fonts Examples"
},
{
"code": null,
"e": 3673,
"s": 3603,
"text": "Following is the list of fonts supported by most Unix System variants"
},
{
"code": null,
"e": 3728,
"s": 3673,
"text": "You can check example fonts here − Unix Fonts Examples"
},
{
"code": null,
"e": 3925,
"s": 3728,
"text": "There are 27 = 128 printable characters which can be represented by different 7-BIT ASCII codes. Another set of characters are not for HTML representation but they are devised to control hardware."
},
{
"code": null,
"e": 4018,
"s": 3925,
"text": "Following tables list down all the 7-BIT ASCII codes and their equivalent HTML Entity Codes."
},
{
"code": null,
"e": 4114,
"s": 4018,
"text": "If you want to see equivalent HEX, OCT and extended set of ASCII codes then check next chapter."
},
{
"code": null,
"e": 4147,
"s": 4114,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4161,
"s": 4147,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4196,
"s": 4161,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4210,
"s": 4196,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4245,
"s": 4210,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4262,
"s": 4245,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4297,
"s": 4262,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4328,
"s": 4297,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4361,
"s": 4328,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4392,
"s": 4361,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4427,
"s": 4392,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4458,
"s": 4427,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4465,
"s": 4458,
"text": " Print"
},
{
"code": null,
"e": 4476,
"s": 4465,
"text": " Add Notes"
}
] |
MongoDB - Java
|
In this chapter, we will learn how to set up MongoDB CLIENT.
Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT.
You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files.
You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files.
You need to include the downloaded jar files into your classpath.
You need to include the downloaded jar files into your classpath.
To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically.
Following is the code snippet to connect to the database −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ConnectToDB {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
}
}
Now, let's compile and run the above program to create our database myDb as shown below.
$javac ConnectToDB.java
$java ConnectToDB
On executing, the above program gives you the following output.
Connected to the database successfully
Credentials ::MongoCredential{
mechanism = null,
userName = 'sampleUser',
source = 'myDb',
password = <hidden>,
mechanismProperties = {}
}
To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.
Following is the code snippet to create a collection −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
//Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully
To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used.
Following is the program to get/select a collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class selectingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("myCollection");
System.out.println("Collection myCollection selected successfully");
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully
Collection myCollection selected successfully
To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used.
Following is the code snippet to insert a document −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
//Inserting document into the collection
collection.insertOne(document);
System.out.println("Document inserted successfully");
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Document inserted successfully
To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor.
Following is the program to select all documents −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
Document document1 = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorialspoint.com/mongodb/")
.append("by", "tutorials point");
Document document2 = new Document("title", "RethinkDB")
.append("description", "database")
.append("likes", 200)
.append("url", "http://www.tutorialspoint.com/rethinkdb/")
.append("by", "tutorials point");
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
collection.insertMany(list);
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used.
Following is the program to select the first document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class UpdatingDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection myCollection selected successfully");
collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));
System.out.println("Document update successfully...");
// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection myCollection selected successfully
Document update successfully...
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
To delete a document from the collection, you need to use the deleteOne() method of the com.mongodb.client.MongoCollection class.
Following is the program to delete a document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DeletingDocuments {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
// Deleting the documents
collection.deleteOne(Filters.eq("title", "MongoDB"));
System.out.println("Document deleted successfully...");
// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Document deleted successfully...
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}
To drop a collection from a database, you need to use the drop() method of the com.mongodb.client.MongoCollection class.
Following is the program to delete a collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DropingCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collections created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// Dropping a Collection
collection.drop();
System.out.println("Collection dropped successfully");
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Collection dropped successfully
To list all the collections in a database, you need to use the listCollectionNames() method of the com.mongodb.client.MongoDatabase class.
Following is the program to list all the collections of a database −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ListOfCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Collection created successfully");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully
myCollection
myCollection1
myCollection5
Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial.
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2614,
"s": 2553,
"text": "In this chapter, we will learn how to set up MongoDB CLIENT."
},
{
"code": null,
"e": 2866,
"s": 2614,
"text": "Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT."
},
{
"code": null,
"e": 3034,
"s": 2866,
"text": "You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files."
},
{
"code": null,
"e": 3202,
"s": 3034,
"text": "You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files."
},
{
"code": null,
"e": 3268,
"s": 3202,
"text": "You need to include the downloaded jar files into your classpath."
},
{
"code": null,
"e": 3334,
"s": 3268,
"text": "You need to include the downloaded jar files into your classpath."
},
{
"code": null,
"e": 3463,
"s": 3334,
"text": "To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically."
},
{
"code": null,
"e": 3522,
"s": 3463,
"text": "Following is the code snippet to connect to the database −"
},
{
"code": null,
"e": 4243,
"s": 3522,
"text": "import com.mongodb.client.MongoDatabase; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class ConnectToDB { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n System.out.println(\"Credentials ::\"+ credential); \n } \n}"
},
{
"code": null,
"e": 4332,
"s": 4243,
"text": "Now, let's compile and run the above program to create our database myDb as shown below."
},
{
"code": null,
"e": 4376,
"s": 4332,
"text": "$javac ConnectToDB.java \n$java ConnectToDB\n"
},
{
"code": null,
"e": 4440,
"s": 4376,
"text": "On executing, the above program gives you the following output."
},
{
"code": null,
"e": 4639,
"s": 4440,
"text": "Connected to the database successfully \nCredentials ::MongoCredential{\n mechanism = null, \n userName = 'sampleUser', \n source = 'myDb', \n password = <hidden>, \n mechanismProperties = {}\n}\n"
},
{
"code": null,
"e": 4740,
"s": 4639,
"text": "To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used."
},
{
"code": null,
"e": 4795,
"s": 4740,
"text": "Following is the code snippet to create a collection −"
},
{
"code": null,
"e": 5619,
"s": 4795,
"text": "import com.mongodb.client.MongoDatabase; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class CreatingCollection { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n //Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n \n //Creating a collection \n database.createCollection(\"sampleCollection\"); \n System.out.println(\"Collection created successfully\"); \n } \n} "
},
{
"code": null,
"e": 5684,
"s": 5619,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 5757,
"s": 5684,
"text": "Connected to the database successfully \nCollection created successfully\n"
},
{
"code": null,
"e": 5877,
"s": 5757,
"text": "To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used."
},
{
"code": null,
"e": 5931,
"s": 5877,
"text": "Following is the program to get/select a collection −"
},
{
"code": null,
"e": 6968,
"s": 5931,
"text": "import com.mongodb.client.MongoCollection; \nimport com.mongodb.client.MongoDatabase; \nimport org.bson.Document; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class selectingCollection { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n \n // Creating a collection \n System.out.println(\"Collection created successfully\"); \n // Retrieving a collection\n MongoCollection<Document> collection = database.getCollection(\"myCollection\"); \n System.out.println(\"Collection myCollection selected successfully\"); \n }\n}"
},
{
"code": null,
"e": 7033,
"s": 6968,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 7153,
"s": 7033,
"text": "Connected to the database successfully \nCollection created successfully \nCollection myCollection selected successfully\n"
},
{
"code": null,
"e": 7257,
"s": 7153,
"text": "To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used."
},
{
"code": null,
"e": 7310,
"s": 7257,
"text": "Following is the code snippet to insert a document −"
},
{
"code": null,
"e": 8362,
"s": 7310,
"text": "import com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\npublic class InsertingDocument {\n\tpublic static void main( String args[] ) {\n\t\n\t// Creating a Mongo client\n\tMongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n\t\n\t// Accessing the database\n\tMongoDatabase database = mongo.getDatabase(\"myDb\");\n\t\n\t// Creating a collection\n\tdatabase.createCollection(\"sampleCollection\");\n\tSystem.out.println(\"Collection created successfully\");\n\t\n\t// Retrieving a collection\n\tMongoCollection<Document> collection = database.getCollection(\"sampleCollection\");\n\tSystem.out.println(\"Collection sampleCollection selected successfully\");\n\tDocument document = new Document(\"title\", \"MongoDB\")\n\t.append(\"description\", \"database\")\n\t.append(\"likes\", 100)\n\t.append(\"url\", \"http://www.tutorialspoint.com/mongodb/\")\n\t.append(\"by\", \"tutorials point\");\n\t\n\t//Inserting document into the collection\n\tcollection.insertOne(document);\n\tSystem.out.println(\"Document inserted successfully\");\n}"
},
{
"code": null,
"e": 8427,
"s": 8362,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 8550,
"s": 8427,
"text": "Connected to the database successfully \nCollection sampleCollection selected successfully \nDocument inserted successfully\n"
},
{
"code": null,
"e": 8728,
"s": 8550,
"text": "To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor."
},
{
"code": null,
"e": 8779,
"s": 8728,
"text": "Following is the program to select all documents −"
},
{
"code": null,
"e": 10541,
"s": 8779,
"text": "import com.mongodb.client.FindIterable;\nimport com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\nimport com.mongodb.MongoCredential;\npublic class RetrievingAllDocuments {\n\tpublic static void main( String args[] ) {\n\t\n\t\t// Creating a Mongo client\n\t\tMongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n\t\t\n\t\t// Creating Credentials\n\t\tMongoCredential credential;\n\t\tcredential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \"password\".toCharArray());\n\t\tSystem.out.println(\"Connected to the database successfully\");\n\t\t\n\t\t// Accessing the database\n\t\tMongoDatabase database = mongo.getDatabase(\"myDb\");\n\t\t\n\t\t// Retrieving a collection\n\t\tMongoCollection<Document> collection = database.getCollection(\"sampleCollection\");\n\t\tSystem.out.println(\"Collection sampleCollection selected successfully\");\n\t\tDocument document1 = new Document(\"title\", \"MongoDB\")\n\t\t.append(\"description\", \"database\")\n\t\t.append(\"likes\", 100)\n\t\t.append(\"url\", \"http://www.tutorialspoint.com/mongodb/\")\n\t\t.append(\"by\", \"tutorials point\");\n\t\tDocument document2 = new Document(\"title\", \"RethinkDB\")\n\t\t.append(\"description\", \"database\")\n\t\t.append(\"likes\", 200)\n\t\t.append(\"url\", \"http://www.tutorialspoint.com/rethinkdb/\")\n\t\t.append(\"by\", \"tutorials point\");\n\t\tList<Document> list = new ArrayList<Document>();\n\t\tlist.add(document1);\n\t\tlist.add(document2);\n\t\tcollection.insertMany(list);\n\t\t// Getting the iterable object\n\t\tFindIterable<Document> iterDoc = collection.find();\n\t\tint i = 1;\n\t\t// Getting the iterator\n\t\tIterator it = iterDoc.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tSystem.out.println(it.next());\n\t\t\ti++;\n\t\t}\n\t}\n}"
},
{
"code": null,
"e": 10606,
"s": 10541,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 11006,
"s": 10606,
"text": "Connected to the database successfully\nCollection sampleCollection selected successfully\nDocument{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}\nDocument{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}\n"
},
{
"code": null,
"e": 11120,
"s": 11006,
"text": "To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used."
},
{
"code": null,
"e": 11176,
"s": 11120,
"text": "Following is the program to select the first document −"
},
{
"code": null,
"e": 12762,
"s": 11176,
"text": "import com.mongodb.client.FindIterable; \nimport com.mongodb.client.MongoCollection; \nimport com.mongodb.client.MongoDatabase; \nimport com.mongodb.client.model.Filters; \nimport com.mongodb.client.model.Updates; \nimport java.util.Iterator; \nimport org.bson.Document; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class UpdatingDocuments { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n // Retrieving a collection \n MongoCollection<Document> collection = database.getCollection(\"sampleCollection\");\n System.out.println(\"Collection myCollection selected successfully\"); \n collection.updateOne(Filters.eq(\"title\", 1), Updates.set(\"likes\", 150)); \n System.out.println(\"Document update successfully...\"); \n \n // Retrieving the documents after updation \n // Getting the iterable object\n FindIterable<Document> iterDoc = collection.find(); \n int i = 1; \n // Getting the iterator \n Iterator it = iterDoc.iterator(); \n while (it.hasNext()) { \n System.out.println(it.next()); \n i++; \n } \n } \n}"
},
{
"code": null,
"e": 12827,
"s": 12762,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 13255,
"s": 12827,
"text": "Connected to the database successfully\nCollection myCollection selected successfully\nDocument update successfully...\nDocument{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}}\nDocument{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}\n"
},
{
"code": null,
"e": 13385,
"s": 13255,
"text": "To delete a document from the collection, you need to use the deleteOne() method of the com.mongodb.client.MongoCollection class."
},
{
"code": null,
"e": 13433,
"s": 13385,
"text": "Following is the program to delete a document −"
},
{
"code": null,
"e": 14988,
"s": 13433,
"text": "import com.mongodb.client.FindIterable; \nimport com.mongodb.client.MongoCollection; \nimport com.mongodb.client.MongoDatabase; \nimport com.mongodb.client.model.Filters; \nimport java.util.Iterator; \nimport org.bson.Document; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class DeletingDocuments { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n // Retrieving a collection\n MongoCollection<Document> collection = database.getCollection(\"sampleCollection\");\n System.out.println(\"Collection sampleCollection selected successfully\"); \n // Deleting the documents \n collection.deleteOne(Filters.eq(\"title\", \"MongoDB\")); \n System.out.println(\"Document deleted successfully...\"); \n \n // Retrieving the documents after updation \n // Getting the iterable object \n FindIterable<Document> iterDoc = collection.find(); \n int i = 1; \n // Getting the iterator \n Iterator it = iterDoc.iterator(); \n while (it.hasNext()) { \n System.out.println(it.next()); \n i++; \n } \n } \n}"
},
{
"code": null,
"e": 15053,
"s": 14988,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 15335,
"s": 15053,
"text": "Connected to the database successfully \nCollection sampleCollection selected successfully \nDocument deleted successfully...\nDocument{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}\n"
},
{
"code": null,
"e": 15456,
"s": 15335,
"text": "To drop a collection from a database, you need to use the drop() method of the com.mongodb.client.MongoCollection class."
},
{
"code": null,
"e": 15506,
"s": 15456,
"text": "Following is the program to delete a collection −"
},
{
"code": null,
"e": 16578,
"s": 15506,
"text": "import com.mongodb.client.MongoCollection; \nimport com.mongodb.client.MongoDatabase; \nimport org.bson.Document; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class DropingCollection { \n \n public static void main( String args[] ) { \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n \n // Creating a collection \n System.out.println(\"Collections created successfully\"); \n // Retrieving a collection\n MongoCollection<Document> collection = database.getCollection(\"sampleCollection\");\n // Dropping a Collection \n collection.drop(); \n System.out.println(\"Collection dropped successfully\");\n } \n}"
},
{
"code": null,
"e": 16643,
"s": 16578,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 16767,
"s": 16643,
"text": "Connected to the database successfully \nCollection sampleCollection selected successfully \nCollection dropped successfully\n"
},
{
"code": null,
"e": 16907,
"s": 16767,
"text": "To list all the collections in a database, you need to use the listCollectionNames() method of the com.mongodb.client.MongoDatabase class."
},
{
"code": null,
"e": 16976,
"s": 16907,
"text": "Following is the program to list all the collections of a database −"
},
{
"code": null,
"e": 17804,
"s": 16976,
"text": "import com.mongodb.client.MongoDatabase; \nimport com.mongodb.MongoClient; \nimport com.mongodb.MongoCredential; \npublic class ListOfCollection { \n \n public static void main( String args[] ) { \n \n // Creating a Mongo client \n MongoClient mongo = new MongoClient( \"localhost\" , 27017 ); \n // Creating Credentials \n MongoCredential credential; \n credential = MongoCredential.createCredential(\"sampleUser\", \"myDb\", \n \"password\".toCharArray()); \n System.out.println(\"Connected to the database successfully\"); \n \n // Accessing the database \n MongoDatabase database = mongo.getDatabase(\"myDb\"); \n System.out.println(\"Collection created successfully\"); \n for (String name : database.listCollectionNames()) { \n System.out.println(name); \n } \n }\n} "
},
{
"code": null,
"e": 17869,
"s": 17804,
"text": "On compiling, the above program gives you the following result −"
},
{
"code": null,
"e": 17986,
"s": 17869,
"text": "Connected to the database successfully \nCollection created successfully \nmyCollection \nmyCollection1 \nmyCollection5\n"
},
{
"code": null,
"e": 18100,
"s": 17986,
"text": "Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial."
},
{
"code": null,
"e": 18133,
"s": 18100,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 18152,
"s": 18133,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 18187,
"s": 18152,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 18215,
"s": 18187,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 18250,
"s": 18215,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18273,
"s": 18250,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 18308,
"s": 18273,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 18325,
"s": 18308,
"text": " University Code"
},
{
"code": null,
"e": 18358,
"s": 18325,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 18377,
"s": 18358,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 18412,
"s": 18377,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 18432,
"s": 18412,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 18439,
"s": 18432,
"text": " Print"
},
{
"code": null,
"e": 18450,
"s": 18439,
"text": " Add Notes"
}
] |
Load CSV Data into MySQL Server Using PHP - GeeksforGeeks
|
14 Dec, 2020
In this article, we are going to store data present in CSV file into MySQL database using PHP in XAMPP server and display the data on web browser.
Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension. A CSV file can be created with the use of any text editor such as notepad, notepad++, etc. After adding content to a text file in the notepad, store it as a csv file with the use of .csv extension.
Requirements: XAMPP Server
Steps:
Create connection to database
Load CSV
Execute Query and verify results
Syntax with Step by Step:
1. Create connection to database
<?php
$db=new mysqli(‘servername’,’username’,’password’,’databasename’);
if ($db->connect_errno) {
echo “Failed ” . $db->connect_error;
exit();
}
?>
Here, Servername is the localhost, username is your user default is root, password is empty by default. database name is name of your database.
2. Take CSV file using fopen function
It is used to open a file
fopen(filename, mode, include_path, context)
Here:
filename is used to specify the file or URL to open
mode is to Specify the type of access you require to the file/stream.
3. Get the CSV file: We can get CSV file using fgetcsv() function
4. Database Query
Now we can write database query to insert data
$db->query(‘INSERT INTO table VALUES (“‘ . $row[0] . ‘”, “‘ . $row[1] . ‘”, “‘ . $row[2] . ‘” . . . “‘ . $row[n] . ‘”)’);
Query is used to take query
row[n] represents the number of rows to be taken to load
Process to Create Database and table
1. Consider the CSV file named detail.csv
2. Open XAMPP and start MySQL, Apache service
3. Type “http://localhost/phpmyadmin/” in your browser
4. Click on new and create database named “gfg”
5. Create table with name “table2”
Execution Steps:
1. Store detail.csv and index.php code files in one folder under the path “C:\xampp\htdocs\gfg”
2. Open index.php file and type the code given below:
PHP
<?php // Create connection// Localhost is the server name, // root is the username, // password is empty// database name is gfg$db = new mysqli('localhost', 'root', '', 'gfg'); // Checking connectionif ($db->connect_errno) { echo "Failed " . $db->connect_error; exit();}?> <h1> html table code for displaying details like name, rollno, city in tabular format and store in database</h1> <table align="center" width="800" border="1" style= "border-collapse: collapse; border:1px solid #ddd;" cellpadding="5" cellspacing="0"> <thead> <tr bgcolor="#FFCC00"> <th> <center>NAME</center> </th> <th> <center>ROLL NO</center> </th> <th> <center>CITY</center> </th> </tr> </thead> <tbody> <?php // Get csv file if(($handle = fopen("detail.csv", "r")) !== FALSE) { $n = 1; while(($row = fgetcsv($handle)) !== FALSE) { // SQL query to store data in // database our table name is // table2 $db->query('INSERT INTO table2 VALUES ("'.$row[0].'","'.$row[1].'", "'.$row[2].'")'); // row[0] = name // row[1] = rollno // row[2] = city if($n>1) { ?> <tr> <td> <center> <?php echo $row[0];?> </center> </td> <td> <center> <?php echo $row[1];?> </center> </td> <td> <center> <?php echo $row[2];?> </center> </td> </tr> <?php } // Increment records $n++; } // Closing the file fclose($handle); } ?> </tbody></table>
Output:
Output in web page
Go to localhost/phpmyadmin and refresh gfg data base to view the stored data.
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
PHP-Misc
HTML
PHP
PHP Programs
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
How to execute PHP code using command line ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
|
[
{
"code": null,
"e": 25104,
"s": 25076,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 25251,
"s": 25104,
"text": "In this article, we are going to store data present in CSV file into MySQL database using PHP in XAMPP server and display the data on web browser."
},
{
"code": null,
"e": 25623,
"s": 25251,
"text": "Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension. A CSV file can be created with the use of any text editor such as notepad, notepad++, etc. After adding content to a text file in the notepad, store it as a csv file with the use of .csv extension."
},
{
"code": null,
"e": 25650,
"s": 25623,
"text": "Requirements: XAMPP Server"
},
{
"code": null,
"e": 25657,
"s": 25650,
"text": "Steps:"
},
{
"code": null,
"e": 25687,
"s": 25657,
"text": "Create connection to database"
},
{
"code": null,
"e": 25696,
"s": 25687,
"text": "Load CSV"
},
{
"code": null,
"e": 25729,
"s": 25696,
"text": "Execute Query and verify results"
},
{
"code": null,
"e": 25755,
"s": 25729,
"text": "Syntax with Step by Step:"
},
{
"code": null,
"e": 25789,
"s": 25755,
"text": "1. Create connection to database"
},
{
"code": null,
"e": 25795,
"s": 25789,
"text": "<?php"
},
{
"code": null,
"e": 25862,
"s": 25795,
"text": "$db=new mysqli(‘servername’,’username’,’password’,’databasename’);"
},
{
"code": null,
"e": 25888,
"s": 25862,
"text": "if ($db->connect_errno) {"
},
{
"code": null,
"e": 25926,
"s": 25888,
"text": " echo “Failed ” . $db->connect_error;"
},
{
"code": null,
"e": 25935,
"s": 25926,
"text": " exit();"
},
{
"code": null,
"e": 25937,
"s": 25935,
"text": "}"
},
{
"code": null,
"e": 25940,
"s": 25937,
"text": "?>"
},
{
"code": null,
"e": 26084,
"s": 25940,
"text": "Here, Servername is the localhost, username is your user default is root, password is empty by default. database name is name of your database."
},
{
"code": null,
"e": 26122,
"s": 26084,
"text": "2. Take CSV file using fopen function"
},
{
"code": null,
"e": 26148,
"s": 26122,
"text": "It is used to open a file"
},
{
"code": null,
"e": 26193,
"s": 26148,
"text": "fopen(filename, mode, include_path, context)"
},
{
"code": null,
"e": 26199,
"s": 26193,
"text": "Here:"
},
{
"code": null,
"e": 26251,
"s": 26199,
"text": "filename is used to specify the file or URL to open"
},
{
"code": null,
"e": 26322,
"s": 26251,
"text": "mode is to Specify the type of access you require to the file/stream."
},
{
"code": null,
"e": 26389,
"s": 26322,
"text": "3. Get the CSV file: We can get CSV file using fgetcsv() function"
},
{
"code": null,
"e": 26407,
"s": 26389,
"text": "4. Database Query"
},
{
"code": null,
"e": 26454,
"s": 26407,
"text": "Now we can write database query to insert data"
},
{
"code": null,
"e": 26576,
"s": 26454,
"text": "$db->query(‘INSERT INTO table VALUES (“‘ . $row[0] . ‘”, “‘ . $row[1] . ‘”, “‘ . $row[2] . ‘” . . . “‘ . $row[n] . ‘”)’);"
},
{
"code": null,
"e": 26604,
"s": 26576,
"text": "Query is used to take query"
},
{
"code": null,
"e": 26661,
"s": 26604,
"text": "row[n] represents the number of rows to be taken to load"
},
{
"code": null,
"e": 26698,
"s": 26661,
"text": "Process to Create Database and table"
},
{
"code": null,
"e": 26740,
"s": 26698,
"text": "1. Consider the CSV file named detail.csv"
},
{
"code": null,
"e": 26786,
"s": 26740,
"text": "2. Open XAMPP and start MySQL, Apache service"
},
{
"code": null,
"e": 26841,
"s": 26786,
"text": "3. Type “http://localhost/phpmyadmin/” in your browser"
},
{
"code": null,
"e": 26889,
"s": 26841,
"text": "4. Click on new and create database named “gfg”"
},
{
"code": null,
"e": 26924,
"s": 26889,
"text": "5. Create table with name “table2”"
},
{
"code": null,
"e": 26941,
"s": 26924,
"text": "Execution Steps:"
},
{
"code": null,
"e": 27037,
"s": 26941,
"text": "1. Store detail.csv and index.php code files in one folder under the path “C:\\xampp\\htdocs\\gfg”"
},
{
"code": null,
"e": 27091,
"s": 27037,
"text": "2. Open index.php file and type the code given below:"
},
{
"code": null,
"e": 27095,
"s": 27091,
"text": "PHP"
},
{
"code": "<?php // Create connection// Localhost is the server name, // root is the username, // password is empty// database name is gfg$db = new mysqli('localhost', 'root', '', 'gfg'); // Checking connectionif ($db->connect_errno) { echo \"Failed \" . $db->connect_error; exit();}?> <h1> html table code for displaying details like name, rollno, city in tabular format and store in database</h1> <table align=\"center\" width=\"800\" border=\"1\" style= \"border-collapse: collapse; border:1px solid #ddd;\" cellpadding=\"5\" cellspacing=\"0\"> <thead> <tr bgcolor=\"#FFCC00\"> <th> <center>NAME</center> </th> <th> <center>ROLL NO</center> </th> <th> <center>CITY</center> </th> </tr> </thead> <tbody> <?php // Get csv file if(($handle = fopen(\"detail.csv\", \"r\")) !== FALSE) { $n = 1; while(($row = fgetcsv($handle)) !== FALSE) { // SQL query to store data in // database our table name is // table2 $db->query('INSERT INTO table2 VALUES (\"'.$row[0].'\",\"'.$row[1].'\", \"'.$row[2].'\")'); // row[0] = name // row[1] = rollno // row[2] = city if($n>1) { ?> <tr> <td> <center> <?php echo $row[0];?> </center> </td> <td> <center> <?php echo $row[1];?> </center> </td> <td> <center> <?php echo $row[2];?> </center> </td> </tr> <?php } // Increment records $n++; } // Closing the file fclose($handle); } ?> </tbody></table>",
"e": 29326,
"s": 27095,
"text": null
},
{
"code": null,
"e": 29334,
"s": 29326,
"text": "Output:"
},
{
"code": null,
"e": 29353,
"s": 29334,
"text": "Output in web page"
},
{
"code": null,
"e": 29431,
"s": 29353,
"text": "Go to localhost/phpmyadmin and refresh gfg data base to view the stored data."
},
{
"code": null,
"e": 29568,
"s": 29431,
"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": 29578,
"s": 29568,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29587,
"s": 29578,
"text": "PHP-Misc"
},
{
"code": null,
"e": 29592,
"s": 29587,
"text": "HTML"
},
{
"code": null,
"e": 29596,
"s": 29592,
"text": "PHP"
},
{
"code": null,
"e": 29609,
"s": 29596,
"text": "PHP Programs"
},
{
"code": null,
"e": 29626,
"s": 29609,
"text": "Web Technologies"
},
{
"code": null,
"e": 29653,
"s": 29626,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29658,
"s": 29653,
"text": "HTML"
},
{
"code": null,
"e": 29662,
"s": 29658,
"text": "PHP"
},
{
"code": null,
"e": 29760,
"s": 29662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29784,
"s": 29760,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29821,
"s": 29784,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29841,
"s": 29821,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29870,
"s": 29841,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29898,
"s": 29870,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 29943,
"s": 29898,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 29967,
"s": 29943,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 30007,
"s": 29967,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 30051,
"s": 30007,
"text": "How to pop an alert message box using PHP ?"
}
] |
How to set JAVA_HOME on Linux | export JAVA_HOME
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
We can set JAVA_HOME on Linux in different ways. One of the prominent ways is to set the JAVA_HOME using an environment variable.
Environment variables can be set up in three different types:
Local Environment variables: Bind to a specific session.
User Environment variables: Bind to a specific user.
System Environment variables: Bind to system-wide.
Using export command we can set the JAVA_HOME, but as we discussed, this is volatile – as soon as we leave the terminal session, this setting will go away.
$ export JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
$ echo $JAVA_HOME
/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
export PATH=$PATH:$JAVA_HOME/bin
We can permanently set the JAVA_HOME using /etc/environment file. This will be applied to system-level.
$ sudo vi /etc/environment
Add the below lines to add the JAVA_HOME
JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
PATH=$PATH:$JAVA_HOME/bin
Apply the environment variables by using the source command.
$ source /etc/environment
$ echo $JAVA_HOME
/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64
How to set JAVA_HOME on windows
Happy Learning 🙂
Java 8 – How to set JAVA_HOME on Windows10
How to install Java on Mac OS
How to restart MsSQL server on Linux
How to find Linux RHEL version ? OS and Kernel Version ?
Python – How to read environment variables ?
How to install Maven on windows 7 command line
How to install Maven in Mac OSX
How to install Maven on Windows10
Linux vi commands list
Difference between Path vs Classpath in Java
How set AWS Access Keys in Windows or Mac Environment
How to Install Ant on Windows 10
C How to Pass Arrays to Functions
Jdk Jre Jvm and differences
C Local and Global Variables
Java 8 – How to set JAVA_HOME on Windows10
How to install Java on Mac OS
How to restart MsSQL server on Linux
How to find Linux RHEL version ? OS and Kernel Version ?
Python – How to read environment variables ?
How to install Maven on windows 7 command line
How to install Maven in Mac OSX
How to install Maven on Windows10
Linux vi commands list
Difference between Path vs Classpath in Java
How set AWS Access Keys in Windows or Mac Environment
How to Install Ant on Windows 10
C How to Pass Arrays to Functions
Jdk Jre Jvm and differences
C Local and Global Variables
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 528,
"s": 398,
"text": "We can set JAVA_HOME on Linux in different ways. One of the prominent ways is to set the JAVA_HOME using an environment variable."
},
{
"code": null,
"e": 590,
"s": 528,
"text": "Environment variables can be set up in three different types:"
},
{
"code": null,
"e": 647,
"s": 590,
"text": "Local Environment variables: Bind to a specific session."
},
{
"code": null,
"e": 700,
"s": 647,
"text": "User Environment variables: Bind to a specific user."
},
{
"code": null,
"e": 751,
"s": 700,
"text": "System Environment variables: Bind to system-wide."
},
{
"code": null,
"e": 907,
"s": 751,
"text": "Using export command we can set the JAVA_HOME, but as we discussed, this is volatile – as soon as we leave the terminal session, this setting will go away."
},
{
"code": null,
"e": 1020,
"s": 907,
"text": "$ export JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64\n$ echo $JAVA_HOME\n/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64"
},
{
"code": null,
"e": 1053,
"s": 1020,
"text": "export PATH=$PATH:$JAVA_HOME/bin"
},
{
"code": null,
"e": 1157,
"s": 1053,
"text": "We can permanently set the JAVA_HOME using /etc/environment file. This will be applied to system-level."
},
{
"code": null,
"e": 1185,
"s": 1157,
"text": "$ sudo vi /etc/environment\n"
},
{
"code": null,
"e": 1226,
"s": 1185,
"text": "Add the below lines to add the JAVA_HOME"
},
{
"code": null,
"e": 1300,
"s": 1226,
"text": "JAVA_HOME=/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64\nPATH=$PATH:$JAVA_HOME/bin"
},
{
"code": null,
"e": 1361,
"s": 1300,
"text": "Apply the environment variables by using the source command."
},
{
"code": null,
"e": 1443,
"s": 1361,
"text": "$ source /etc/environment\n$ echo $JAVA_HOME\n/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64"
},
{
"code": null,
"e": 1475,
"s": 1443,
"text": "How to set JAVA_HOME on windows"
},
{
"code": null,
"e": 1492,
"s": 1475,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2065,
"s": 1492,
"text": "\nJava 8 – How to set JAVA_HOME on Windows10\nHow to install Java on Mac OS\nHow to restart MsSQL server on Linux\nHow to find Linux RHEL version ? OS and Kernel Version ?\nPython – How to read environment variables ?\nHow to install Maven on windows 7 command line\nHow to install Maven in Mac OSX\nHow to install Maven on Windows10\nLinux vi commands list\nDifference between Path vs Classpath in Java\nHow set AWS Access Keys in Windows or Mac Environment\nHow to Install Ant on Windows 10\nC How to Pass Arrays to Functions\nJdk Jre Jvm and differences\nC Local and Global Variables\n"
},
{
"code": null,
"e": 2108,
"s": 2065,
"text": "Java 8 – How to set JAVA_HOME on Windows10"
},
{
"code": null,
"e": 2138,
"s": 2108,
"text": "How to install Java on Mac OS"
},
{
"code": null,
"e": 2175,
"s": 2138,
"text": "How to restart MsSQL server on Linux"
},
{
"code": null,
"e": 2232,
"s": 2175,
"text": "How to find Linux RHEL version ? OS and Kernel Version ?"
},
{
"code": null,
"e": 2277,
"s": 2232,
"text": "Python – How to read environment variables ?"
},
{
"code": null,
"e": 2324,
"s": 2277,
"text": "How to install Maven on windows 7 command line"
},
{
"code": null,
"e": 2356,
"s": 2324,
"text": "How to install Maven in Mac OSX"
},
{
"code": null,
"e": 2390,
"s": 2356,
"text": "How to install Maven on Windows10"
},
{
"code": null,
"e": 2413,
"s": 2390,
"text": "Linux vi commands list"
},
{
"code": null,
"e": 2458,
"s": 2413,
"text": "Difference between Path vs Classpath in Java"
},
{
"code": null,
"e": 2512,
"s": 2458,
"text": "How set AWS Access Keys in Windows or Mac Environment"
},
{
"code": null,
"e": 2545,
"s": 2512,
"text": "How to Install Ant on Windows 10"
},
{
"code": null,
"e": 2579,
"s": 2545,
"text": "C How to Pass Arrays to Functions"
},
{
"code": null,
"e": 2607,
"s": 2579,
"text": "Jdk Jre Jvm and differences"
}
] |
Bitwise AND of Numbers Range in C++
|
Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4.
To solve this, we will follow these steps −
i := 0
i := 0
while m is not n, thenm := m/2, n := n / 2, increase i by 1
while m is not n, then
m := m/2, n := n / 2, increase i by 1
m := m/2, n := n / 2, increase i by 1
return m after shifting to the left i times.
return m after shifting to the left i times.
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int i = 0;
while(m != n){
m >>= 1;
n >>= 1;
i++;
}
return m << i;
}
};
main(){
Solution ob;
cout << (ob.rangeBitwiseAnd(5,7));
}
5
7
4
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4."
},
{
"code": null,
"e": 1297,
"s": 1253,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1304,
"s": 1297,
"text": "i := 0"
},
{
"code": null,
"e": 1311,
"s": 1304,
"text": "i := 0"
},
{
"code": null,
"e": 1371,
"s": 1311,
"text": "while m is not n, thenm := m/2, n := n / 2, increase i by 1"
},
{
"code": null,
"e": 1394,
"s": 1371,
"text": "while m is not n, then"
},
{
"code": null,
"e": 1432,
"s": 1394,
"text": "m := m/2, n := n / 2, increase i by 1"
},
{
"code": null,
"e": 1470,
"s": 1432,
"text": "m := m/2, n := n / 2, increase i by 1"
},
{
"code": null,
"e": 1515,
"s": 1470,
"text": "return m after shifting to the left i times."
},
{
"code": null,
"e": 1560,
"s": 1515,
"text": "return m after shifting to the left i times."
},
{
"code": null,
"e": 1632,
"s": 1560,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": " Live Demo"
},
{
"code": null,
"e": 1945,
"s": 1643,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int rangeBitwiseAnd(int m, int n) {\n int i = 0;\n while(m != n){\n m >>= 1;\n n >>= 1;\n i++;\n }\n return m << i;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.rangeBitwiseAnd(5,7));\n}"
},
{
"code": null,
"e": 1949,
"s": 1945,
"text": "5\n7"
},
{
"code": null,
"e": 1951,
"s": 1949,
"text": "4"
}
] |
\wedge - Tex Command
|
\wedge - Used to create wedge symbol.
{ \wedge}
\wedge command draws wedge symbol.
\wedge
∧
\wedge
∧
\wedge
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8024,
"s": 7986,
"text": "\\wedge - Used to create wedge symbol."
},
{
"code": null,
"e": 8034,
"s": 8024,
"text": "{ \\wedge}"
},
{
"code": null,
"e": 8069,
"s": 8034,
"text": "\\wedge command draws wedge symbol."
},
{
"code": null,
"e": 8083,
"s": 8069,
"text": "\n\\wedge\n\n∧\n\n\n"
},
{
"code": null,
"e": 8095,
"s": 8083,
"text": "\\wedge\n\n∧\n\n"
},
{
"code": null,
"e": 8102,
"s": 8095,
"text": "\\wedge"
},
{
"code": null,
"e": 8134,
"s": 8102,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8147,
"s": 8134,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8180,
"s": 8147,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8193,
"s": 8180,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8225,
"s": 8193,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8261,
"s": 8225,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8296,
"s": 8261,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8313,
"s": 8296,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8346,
"s": 8313,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8360,
"s": 8346,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8392,
"s": 8360,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8407,
"s": 8392,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8414,
"s": 8407,
"text": " Print"
},
{
"code": null,
"e": 8425,
"s": 8414,
"text": " Add Notes"
}
] |
How to create a System Tray icon of a Tkinter application?
|
A System Tray icon is used for showing the application’s running state in the taskbar. It typically shows which application is currently running. The system tray icon is visible in the taskbar.
To create a System Tray icon of a tkinter application, we can use pystray module in Python. It has many inbuilt functions and methods that can be used to configure the system tray icon of the application.
To install pystray in your machine you can type "pip install pystray" command in your shell or command prompt.
To create a System Tray icon, you can follow these steps,
Import the required libraries − Pystray, Python PIL or Pillow.
Import the required libraries − Pystray, Python PIL or Pillow.
Define a function hide_window() to withdraw the window and provide the icon in the system tray.
Define a function hide_window() to withdraw the window and provide the icon in the system tray.
Add and define two menu items, "Show" and "Quit".
Add and define two menu items, "Show" and "Quit".
Add a command in the menu items by defining a function for Show and Quit.
Add a command in the menu items by defining a function for Show and Quit.
# Import the required libraries
from tkinter import *
from pystray import MenuItem as item
import pystray
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
win.title("System Tray Application")
# Set the size of the window
win.geometry("700x350")
# Define a function for quit the window
def quit_window(icon, item):
icon.stop()
win.destroy()
# Define a function to show the window again
def show_window(icon, item):
icon.stop()
win.after(0,win.deiconify())
# Hide the window and show on the system taskbar
def hide_window():
win.withdraw()
image=Image.open("favicon.ico")
menu=(item('Quit', quit_window), item('Show', show_window))
icon=pystray.Icon("name", image, "My System Tray Icon", menu)
icon.run()
win.protocol('WM_DELETE_WINDOW', hide_window)
win.mainloop()
If you will run the above code, it will display a window.
When we close the window it will still appear in the Taskbar as a System Tray icon.
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "A System Tray icon is used for showing the application’s running state in the taskbar. It typically shows which application is currently running. The system tray icon is visible in the taskbar."
},
{
"code": null,
"e": 1461,
"s": 1256,
"text": "To create a System Tray icon of a tkinter application, we can use pystray module in Python. It has many inbuilt functions and methods that can be used to configure the system tray icon of the application."
},
{
"code": null,
"e": 1572,
"s": 1461,
"text": "To install pystray in your machine you can type \"pip install pystray\" command in your shell or command prompt."
},
{
"code": null,
"e": 1630,
"s": 1572,
"text": "To create a System Tray icon, you can follow these steps,"
},
{
"code": null,
"e": 1693,
"s": 1630,
"text": "Import the required libraries − Pystray, Python PIL or Pillow."
},
{
"code": null,
"e": 1756,
"s": 1693,
"text": "Import the required libraries − Pystray, Python PIL or Pillow."
},
{
"code": null,
"e": 1852,
"s": 1756,
"text": "Define a function hide_window() to withdraw the window and provide the icon in the system tray."
},
{
"code": null,
"e": 1948,
"s": 1852,
"text": "Define a function hide_window() to withdraw the window and provide the icon in the system tray."
},
{
"code": null,
"e": 1998,
"s": 1948,
"text": "Add and define two menu items, \"Show\" and \"Quit\"."
},
{
"code": null,
"e": 2048,
"s": 1998,
"text": "Add and define two menu items, \"Show\" and \"Quit\"."
},
{
"code": null,
"e": 2122,
"s": 2048,
"text": "Add a command in the menu items by defining a function for Show and Quit."
},
{
"code": null,
"e": 2196,
"s": 2122,
"text": "Add a command in the menu items by defining a function for Show and Quit."
},
{
"code": null,
"e": 3033,
"s": 2196,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom pystray import MenuItem as item\nimport pystray\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\nwin.title(\"System Tray Application\")\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function for quit the window\ndef quit_window(icon, item):\n icon.stop()\n win.destroy()\n\n# Define a function to show the window again\ndef show_window(icon, item):\n icon.stop()\n win.after(0,win.deiconify())\n\n# Hide the window and show on the system taskbar\ndef hide_window():\n win.withdraw()\n image=Image.open(\"favicon.ico\")\n menu=(item('Quit', quit_window), item('Show', show_window))\n icon=pystray.Icon(\"name\", image, \"My System Tray Icon\", menu)\n icon.run()\n\nwin.protocol('WM_DELETE_WINDOW', hide_window)\n\nwin.mainloop()"
},
{
"code": null,
"e": 3091,
"s": 3033,
"text": "If you will run the above code, it will display a window."
},
{
"code": null,
"e": 3175,
"s": 3091,
"text": "When we close the window it will still appear in the Taskbar as a System Tray icon."
}
] |
Python - Tkinter Text
|
Text widgets provide advanced capabilities that allow you to edit a multiline text and format the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections of the text, and apply changes to those areas. Moreover, you can embed windows and images in the text because this widget was designed to handle both plain and formatted text.
Here is the simple syntax to create this widget −
w = Text ( master, option, ... )
master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The default background color of the text widget.
bd
The width of the border around the text widget. Default is 2 pixels.
cursor
The cursor that will appear when the mouse is over the text widget.
exportselection
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don't want that behavior.
font
The default font for text inserted into the widget.
fg
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
height
The height of the widget in lines (not pixels!), measured according to the current font size.
highlightbackground
The color of the focus highlight when the text widget does not have focus.
highlightcolor
The color of the focus highlight when the text widget has the focus.
highlightthickness
The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight.
insertbackground
The color of the insertion cursor. Default is black.
insertborderwidth
Size of the 3-D border around the insertion cursor. Default is 0.
insertofftime
The number of milliseconds the insertion cursor is off during its blink cycle. Set this option to zero to suppress blinking. Default is 300.
insertontime
The number of milliseconds the insertion cursor is on during its blink cycle. Default is 600.
insertwidth
Width of the insertion cursor (its height is determined by the tallest item in its line). Default is 2 pixels.
padx
The size of the internal padding added to the left and right of the text area. Default is one pixel.
pady
The size of the internal padding added above and below the text area. Default is one pixel.
relief
The 3-D appearance of the text widget. Default is relief=SUNKEN.
selectbackground
The background color to use displaying selected text.
selectborderwidth
The width of the border to use around selected text.
spacing1
This option specifies how much extra vertical space is put above each line of text. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0.
spacing2
This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0.
spacing3
This option specifies how much extra vertical space is added below each line of text. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0.
state
Normally, text widgets respond to keyboard and mouse events; set state=NORMAL to get this behavior. If you set state=DISABLED, the text widget will not respond, and you won't be able to modify its contents programmatically either.
tabs
This option controls how tab characters position text.
width
The width of the widget in characters (not pixels!), measured according to the current font size.
wrap
This option controls the display of lines that are too wide. Set wrap=WORD and it will break the line after the last word that will fit. With the default behavior, wrap=CHAR, any line that gets too long will be broken at any character.
xscrollcommand
To make the text widget horizontally scrollable, set this option to the set() method of the horizontal scrollbar.
yscrollcommand
To make the text widget vertically scrollable, set this option to the set() method of the vertical scrollbar.
Text objects have these methods −
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
get(startindex [,endindex])
This method returns a specific character or a range of text.
index(index)
Returns the absolute value of an index based on the given index.
insert(index [,string]...)
This method inserts strings at the specified index location.
see(index)
This method returns true if the text located at the index position is visible.
Text widgets support three distinct helper structures: Marks, Tabs, and Indexes −
Marks are used to bookmark positions between two characters within a given text. We have the following methods available when handling marks −
index(mark)
Returns the line and column location of a specific mark.
mark_gravity(mark [,gravity])
Returns the gravity of the given mark. If the second argument is provided, the gravity is set for the given mark.
mark_names()
Returns all marks from the Text widget.
mark_set(mark, index)
Informs a new position to the given mark.
mark_unset(mark)
Removes the given mark from the Text widget.
Tags are used to associate names to regions of text which makes easy the task of modifying the display settings of specific text areas. Tags are also used to bind event callbacks to specific ranges of text.
Following are the available methods for handling tabs −
tag_add(tagname, startindex[,endindex] ...)
This method tags either the position defined by startindex, or a range delimited by the positions startindex and endindex.
tag_config
You can use this method to configure the tag properties, which include, justify(center, left, or right), tabs(this property has the same functionality of the Text widget tabs's property), and underline(used to underline the tagged text).
tag_delete(tagname)
This method is used to delete and remove a given tag.
tag_remove(tagname [,startindex[.endindex]] ...)
After applying this method, the given tag is removed from the provided area without deleting the actual tag definition.
Try the following example yourself −
from Tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2407,
"s": 2244,
"text": "Text widgets provide advanced capabilities that allow you to edit a multiline text and format the way it has to be displayed, such as changing its color and font."
},
{
"code": null,
"e": 2667,
"s": 2407,
"text": "You can also use elegant structures like tabs and marks to locate specific sections of the text, and apply changes to those areas. Moreover, you can embed windows and images in the text because this widget was designed to handle both plain and formatted text."
},
{
"code": null,
"e": 2717,
"s": 2667,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2751,
"s": 2717,
"text": "w = Text ( master, option, ... )\n"
},
{
"code": null,
"e": 2795,
"s": 2751,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2839,
"s": 2795,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2979,
"s": 2839,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3119,
"s": 2979,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3122,
"s": 3119,
"text": "bg"
},
{
"code": null,
"e": 3171,
"s": 3122,
"text": "The default background color of the text widget."
},
{
"code": null,
"e": 3174,
"s": 3171,
"text": "bd"
},
{
"code": null,
"e": 3243,
"s": 3174,
"text": "The width of the border around the text widget. Default is 2 pixels."
},
{
"code": null,
"e": 3250,
"s": 3243,
"text": "cursor"
},
{
"code": null,
"e": 3318,
"s": 3250,
"text": "The cursor that will appear when the mouse is over the text widget."
},
{
"code": null,
"e": 3334,
"s": 3318,
"text": "exportselection"
},
{
"code": null,
"e": 3489,
"s": 3334,
"text": "Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don't want that behavior."
},
{
"code": null,
"e": 3494,
"s": 3489,
"text": "font"
},
{
"code": null,
"e": 3546,
"s": 3494,
"text": "The default font for text inserted into the widget."
},
{
"code": null,
"e": 3549,
"s": 3546,
"text": "fg"
},
{
"code": null,
"e": 3684,
"s": 3549,
"text": "The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default."
},
{
"code": null,
"e": 3691,
"s": 3684,
"text": "height"
},
{
"code": null,
"e": 3785,
"s": 3691,
"text": "The height of the widget in lines (not pixels!), measured according to the current font size."
},
{
"code": null,
"e": 3805,
"s": 3785,
"text": "highlightbackground"
},
{
"code": null,
"e": 3880,
"s": 3805,
"text": "The color of the focus highlight when the text widget does not have focus."
},
{
"code": null,
"e": 3895,
"s": 3880,
"text": "highlightcolor"
},
{
"code": null,
"e": 3964,
"s": 3895,
"text": "The color of the focus highlight when the text widget has the focus."
},
{
"code": null,
"e": 3983,
"s": 3964,
"text": "highlightthickness"
},
{
"code": null,
"e": 4104,
"s": 3983,
"text": "The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight."
},
{
"code": null,
"e": 4121,
"s": 4104,
"text": "insertbackground"
},
{
"code": null,
"e": 4174,
"s": 4121,
"text": "The color of the insertion cursor. Default is black."
},
{
"code": null,
"e": 4192,
"s": 4174,
"text": "insertborderwidth"
},
{
"code": null,
"e": 4258,
"s": 4192,
"text": "Size of the 3-D border around the insertion cursor. Default is 0."
},
{
"code": null,
"e": 4272,
"s": 4258,
"text": "insertofftime"
},
{
"code": null,
"e": 4413,
"s": 4272,
"text": "The number of milliseconds the insertion cursor is off during its blink cycle. Set this option to zero to suppress blinking. Default is 300."
},
{
"code": null,
"e": 4426,
"s": 4413,
"text": "insertontime"
},
{
"code": null,
"e": 4520,
"s": 4426,
"text": "The number of milliseconds the insertion cursor is on during its blink cycle. Default is 600."
},
{
"code": null,
"e": 4532,
"s": 4520,
"text": "insertwidth"
},
{
"code": null,
"e": 4643,
"s": 4532,
"text": "Width of the insertion cursor (its height is determined by the tallest item in its line). Default is 2 pixels."
},
{
"code": null,
"e": 4648,
"s": 4643,
"text": "padx"
},
{
"code": null,
"e": 4749,
"s": 4648,
"text": "The size of the internal padding added to the left and right of the text area. Default is one pixel."
},
{
"code": null,
"e": 4754,
"s": 4749,
"text": "pady"
},
{
"code": null,
"e": 4846,
"s": 4754,
"text": "The size of the internal padding added above and below the text area. Default is one pixel."
},
{
"code": null,
"e": 4853,
"s": 4846,
"text": "relief"
},
{
"code": null,
"e": 4918,
"s": 4853,
"text": "The 3-D appearance of the text widget. Default is relief=SUNKEN."
},
{
"code": null,
"e": 4935,
"s": 4918,
"text": "selectbackground"
},
{
"code": null,
"e": 4989,
"s": 4935,
"text": "The background color to use displaying selected text."
},
{
"code": null,
"e": 5007,
"s": 4989,
"text": "selectborderwidth"
},
{
"code": null,
"e": 5060,
"s": 5007,
"text": "The width of the border to use around selected text."
},
{
"code": null,
"e": 5069,
"s": 5060,
"text": "spacing1"
},
{
"code": null,
"e": 5259,
"s": 5069,
"text": "This option specifies how much extra vertical space is put above each line of text. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0."
},
{
"code": null,
"e": 5268,
"s": 5259,
"text": "spacing2"
},
{
"code": null,
"e": 5400,
"s": 5268,
"text": "This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0."
},
{
"code": null,
"e": 5409,
"s": 5400,
"text": "spacing3"
},
{
"code": null,
"e": 5599,
"s": 5409,
"text": "This option specifies how much extra vertical space is added below each line of text. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0."
},
{
"code": null,
"e": 5605,
"s": 5599,
"text": "state"
},
{
"code": null,
"e": 5836,
"s": 5605,
"text": "Normally, text widgets respond to keyboard and mouse events; set state=NORMAL to get this behavior. If you set state=DISABLED, the text widget will not respond, and you won't be able to modify its contents programmatically either."
},
{
"code": null,
"e": 5841,
"s": 5836,
"text": "tabs"
},
{
"code": null,
"e": 5896,
"s": 5841,
"text": "This option controls how tab characters position text."
},
{
"code": null,
"e": 5902,
"s": 5896,
"text": "width"
},
{
"code": null,
"e": 6000,
"s": 5902,
"text": "The width of the widget in characters (not pixels!), measured according to the current font size."
},
{
"code": null,
"e": 6005,
"s": 6000,
"text": "wrap"
},
{
"code": null,
"e": 6241,
"s": 6005,
"text": "This option controls the display of lines that are too wide. Set wrap=WORD and it will break the line after the last word that will fit. With the default behavior, wrap=CHAR, any line that gets too long will be broken at any character."
},
{
"code": null,
"e": 6256,
"s": 6241,
"text": "xscrollcommand"
},
{
"code": null,
"e": 6370,
"s": 6256,
"text": "To make the text widget horizontally scrollable, set this option to the set() method of the horizontal scrollbar."
},
{
"code": null,
"e": 6385,
"s": 6370,
"text": "yscrollcommand"
},
{
"code": null,
"e": 6495,
"s": 6385,
"text": "To make the text widget vertically scrollable, set this option to the set() method of the vertical scrollbar."
},
{
"code": null,
"e": 6529,
"s": 6495,
"text": "Text objects have these methods −"
},
{
"code": null,
"e": 6560,
"s": 6529,
"text": "delete(startindex [,endindex])"
},
{
"code": null,
"e": 6621,
"s": 6560,
"text": "This method deletes a specific character or a range of text."
},
{
"code": null,
"e": 6649,
"s": 6621,
"text": "get(startindex [,endindex])"
},
{
"code": null,
"e": 6710,
"s": 6649,
"text": "This method returns a specific character or a range of text."
},
{
"code": null,
"e": 6723,
"s": 6710,
"text": "index(index)"
},
{
"code": null,
"e": 6788,
"s": 6723,
"text": "Returns the absolute value of an index based on the given index."
},
{
"code": null,
"e": 6815,
"s": 6788,
"text": "insert(index [,string]...)"
},
{
"code": null,
"e": 6876,
"s": 6815,
"text": "This method inserts strings at the specified index location."
},
{
"code": null,
"e": 6887,
"s": 6876,
"text": "see(index)"
},
{
"code": null,
"e": 6966,
"s": 6887,
"text": "This method returns true if the text located at the index position is visible."
},
{
"code": null,
"e": 7048,
"s": 6966,
"text": "Text widgets support three distinct helper structures: Marks, Tabs, and Indexes −"
},
{
"code": null,
"e": 7191,
"s": 7048,
"text": "Marks are used to bookmark positions between two characters within a given text. We have the following methods available when handling marks −"
},
{
"code": null,
"e": 7203,
"s": 7191,
"text": "index(mark)"
},
{
"code": null,
"e": 7260,
"s": 7203,
"text": "Returns the line and column location of a specific mark."
},
{
"code": null,
"e": 7290,
"s": 7260,
"text": "mark_gravity(mark [,gravity])"
},
{
"code": null,
"e": 7404,
"s": 7290,
"text": "Returns the gravity of the given mark. If the second argument is provided, the gravity is set for the given mark."
},
{
"code": null,
"e": 7417,
"s": 7404,
"text": "mark_names()"
},
{
"code": null,
"e": 7457,
"s": 7417,
"text": "Returns all marks from the Text widget."
},
{
"code": null,
"e": 7479,
"s": 7457,
"text": "mark_set(mark, index)"
},
{
"code": null,
"e": 7521,
"s": 7479,
"text": "Informs a new position to the given mark."
},
{
"code": null,
"e": 7538,
"s": 7521,
"text": "mark_unset(mark)"
},
{
"code": null,
"e": 7583,
"s": 7538,
"text": "Removes the given mark from the Text widget."
},
{
"code": null,
"e": 7790,
"s": 7583,
"text": "Tags are used to associate names to regions of text which makes easy the task of modifying the display settings of specific text areas. Tags are also used to bind event callbacks to specific ranges of text."
},
{
"code": null,
"e": 7846,
"s": 7790,
"text": "Following are the available methods for handling tabs −"
},
{
"code": null,
"e": 7890,
"s": 7846,
"text": "tag_add(tagname, startindex[,endindex] ...)"
},
{
"code": null,
"e": 8013,
"s": 7890,
"text": "This method tags either the position defined by startindex, or a range delimited by the positions startindex and endindex."
},
{
"code": null,
"e": 8024,
"s": 8013,
"text": "tag_config"
},
{
"code": null,
"e": 8262,
"s": 8024,
"text": "You can use this method to configure the tag properties, which include, justify(center, left, or right), tabs(this property has the same functionality of the Text widget tabs's property), and underline(used to underline the tagged text)."
},
{
"code": null,
"e": 8282,
"s": 8262,
"text": "tag_delete(tagname)"
},
{
"code": null,
"e": 8336,
"s": 8282,
"text": "This method is used to delete and remove a given tag."
},
{
"code": null,
"e": 8385,
"s": 8336,
"text": "tag_remove(tagname [,startindex[.endindex]] ...)"
},
{
"code": null,
"e": 8505,
"s": 8385,
"text": "After applying this method, the given tag is removed from the provided area without deleting the actual tag definition."
},
{
"code": null,
"e": 8542,
"s": 8505,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 8916,
"s": 8542,
"text": "from Tkinter import *\n\ndef onclick():\n pass\n\nroot = Tk()\ntext = Text(root)\ntext.insert(INSERT, \"Hello.....\")\ntext.insert(END, \"Bye Bye.....\")\ntext.pack()\n\ntext.tag_add(\"here\", \"1.0\", \"1.4\")\ntext.tag_add(\"start\", \"1.8\", \"1.13\")\ntext.tag_config(\"here\", background=\"yellow\", foreground=\"blue\")\ntext.tag_config(\"start\", background=\"black\", foreground=\"green\")\nroot.mainloop()"
},
{
"code": null,
"e": 8985,
"s": 8916,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 9022,
"s": 8985,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9038,
"s": 9022,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9071,
"s": 9038,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9090,
"s": 9071,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9125,
"s": 9090,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 9147,
"s": 9125,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 9181,
"s": 9147,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 9209,
"s": 9181,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9244,
"s": 9209,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 9258,
"s": 9244,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9291,
"s": 9258,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9308,
"s": 9291,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9315,
"s": 9308,
"text": " Print"
},
{
"code": null,
"e": 9326,
"s": 9315,
"text": " Add Notes"
}
] |
String Formatting in Java using %
|
Followimg is the code to implement String formatting in Java using % −
Live Demo
public class Demo {
public static void main(String args[]){
String my_str = " sample.";
String concat_Str = String.format("This is a" + "%s", my_str);
String format_str_1 = String.format("The value is %.4f", 78.92367);
System.out.println(concat_Str);
System.out.println(format_str_1);
}
}
This is a sample.
The value is 78.9237
A class named Demo contains the main function. Here a string value is defined, which is used to format the string, by concatenating it to another variable. Similarly, a floating point number is also formatted using the ‘%’ operator. Both these values are printed on the console.
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "Followimg is the code to implement String formatting in Java using % −"
},
{
"code": null,
"e": 1144,
"s": 1133,
"text": " Live Demo"
},
{
"code": null,
"e": 1469,
"s": 1144,
"text": "public class Demo {\n public static void main(String args[]){\n String my_str = \" sample.\";\n String concat_Str = String.format(\"This is a\" + \"%s\", my_str);\n String format_str_1 = String.format(\"The value is %.4f\", 78.92367);\n System.out.println(concat_Str);\n System.out.println(format_str_1);\n }\n}"
},
{
"code": null,
"e": 1508,
"s": 1469,
"text": "This is a sample.\nThe value is 78.9237"
},
{
"code": null,
"e": 1787,
"s": 1508,
"text": "A class named Demo contains the main function. Here a string value is defined, which is used to format the string, by concatenating it to another variable. Similarly, a floating point number is also formatted using the ‘%’ operator. Both these values are printed on the console."
}
] |
Instruction set of 8051
|
The instructions of 8051 Microcontroller can be classified into five different groups. These groups are like below
Data Transfer Group
Data Transfer Group
Arithmetic Group
Arithmetic Group
Logical Group
Logical Group
Program Branch Group
Program Branch Group
Bit Processing Group
Bit Processing Group
This Bit-Processing group is also known as Boolean Variable Manipulation.
Like 8085, some instruction has two operands. The first operand is the Destination, and the second operator is Source.
In the following examples, you will get some notations. The notations are like −
Rn = Any register from R0to R7
Ri = Either R0 or R1
d8 = Any 8-bit immediate data (00H to FFH)
d16 = 16-bit immediate data
a8 = 8-bit address
bit = 8-bit address of bit which is bit addressable
rel = 8-bit signed displacement. The range is -128 to 127. It is relative to the first byte of the instruction.
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "The instructions of 8051 Microcontroller can be classified into five different groups. These groups are like below"
},
{
"code": null,
"e": 1197,
"s": 1177,
"text": "Data Transfer Group"
},
{
"code": null,
"e": 1217,
"s": 1197,
"text": "Data Transfer Group"
},
{
"code": null,
"e": 1234,
"s": 1217,
"text": "Arithmetic Group"
},
{
"code": null,
"e": 1251,
"s": 1234,
"text": "Arithmetic Group"
},
{
"code": null,
"e": 1265,
"s": 1251,
"text": "Logical Group"
},
{
"code": null,
"e": 1279,
"s": 1265,
"text": "Logical Group"
},
{
"code": null,
"e": 1300,
"s": 1279,
"text": "Program Branch Group"
},
{
"code": null,
"e": 1321,
"s": 1300,
"text": "Program Branch Group"
},
{
"code": null,
"e": 1342,
"s": 1321,
"text": "Bit Processing Group"
},
{
"code": null,
"e": 1363,
"s": 1342,
"text": "Bit Processing Group"
},
{
"code": null,
"e": 1437,
"s": 1363,
"text": "This Bit-Processing group is also known as Boolean Variable Manipulation."
},
{
"code": null,
"e": 1556,
"s": 1437,
"text": "Like 8085, some instruction has two operands. The first operand is the Destination, and the second operator is Source."
},
{
"code": null,
"e": 1637,
"s": 1556,
"text": "In the following examples, you will get some notations. The notations are like −"
},
{
"code": null,
"e": 1943,
"s": 1637,
"text": "Rn = Any register from R0to R7\nRi = Either R0 or R1\nd8 = Any 8-bit immediate data (00H to FFH)\nd16 = 16-bit immediate data\na8 = 8-bit address\nbit = 8-bit address of bit which is bit addressable\nrel = 8-bit signed displacement. The range is -128 to 127. It is relative to the first byte of the instruction."
}
] |
Selenium - Synchronization
|
To synchronize between script execution and application, we need to wait after performing appropriate actions. Let us look at the ways to achieve the same.
Thread.Sleep is a static wait and it is not a good way to use in scripts as it is sleep without condition.
Thread.Sleep(1000); //Will wait for 1 second.
An 'explicit wait,' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible.
WebDriver driver = new FirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement =
(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));
Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period.
Once the specified time limit is crossed, the webDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws exception.
It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));
A FluentWait instance defines the maximum amount of time to wait for a condition to take place, as well as the frequency with which to check the existence of the object condition.
Let us say we will 60 seconds for an element to be available on the page, but we will check its avilable once in every 10 seconds.
Wait wait =
new FluentWait(driver).withTimeout(60, SECONDS).pollingEvery(10, SECONDS).ignoring(NoSuchElementException.class);
WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("dynamicelement"));
}
});
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2031,
"s": 1875,
"text": "To synchronize between script execution and application, we need to wait after performing appropriate actions. Let us look at the ways to achieve the same."
},
{
"code": null,
"e": 2138,
"s": 2031,
"text": "Thread.Sleep is a static wait and it is not a good way to use in scripts as it is sleep without condition."
},
{
"code": null,
"e": 2184,
"s": 2138,
"text": "Thread.Sleep(1000); //Will wait for 1 second."
},
{
"code": null,
"e": 2350,
"s": 2184,
"text": "An 'explicit wait,' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible."
},
{
"code": null,
"e": 2560,
"s": 2350,
"text": "WebDriver driver = new FirefoxDriver();\ndriver.get(\"Enter an URL\"S);\nWebElement DynamicElement = \n (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id(\"DynamicElement\")));"
},
{
"code": null,
"e": 2817,
"s": 2560,
"text": "Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period."
},
{
"code": null,
"e": 3015,
"s": 2817,
"text": "Once the specified time limit is crossed, the webDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws exception."
},
{
"code": null,
"e": 3185,
"s": 3015,
"text": "It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time."
},
{
"code": null,
"e": 3391,
"s": 3185,
"text": "WebDriver driver = new FirefoxDriver();\ndriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\ndriver.get(\"Enter an URL\");\nWebElement DynamicElement = driver.findElement(By.id(\"DynamicElement\"));"
},
{
"code": null,
"e": 3571,
"s": 3391,
"text": "A FluentWait instance defines the maximum amount of time to wait for a condition to take place, as well as the frequency with which to check the existence of the object condition."
},
{
"code": null,
"e": 3703,
"s": 3571,
"text": "Let us say we will 60 seconds for an element to be available on the page, but we will check its avilable once in every 10 seconds."
},
{
"code": null,
"e": 4036,
"s": 3703,
"text": "Wait wait = \n new FluentWait(driver).withTimeout(60, SECONDS).pollingEvery(10, SECONDS).ignoring(NoSuchElementException.class);\n \n WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() {\n \n public WebElement apply(WebDriver driver) {\n return driver.findElement(By.id(\"dynamicelement\"));\n }\n});"
},
{
"code": null,
"e": 4071,
"s": 4036,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4083,
"s": 4071,
"text": " Aditya Dua"
},
{
"code": null,
"e": 4119,
"s": 4083,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 4133,
"s": 4119,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4170,
"s": 4133,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 4192,
"s": 4170,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4225,
"s": 4192,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4239,
"s": 4225,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4274,
"s": 4239,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 4288,
"s": 4274,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4325,
"s": 4288,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 4339,
"s": 4325,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4346,
"s": 4339,
"text": " Print"
},
{
"code": null,
"e": 4357,
"s": 4346,
"text": " Add Notes"
}
] |
Perl scalar Function
|
This function forces the evaluation of EXPR to be in scalar context, even if it would normally work in list context.
Following is the simple syntax for this function −
scalar EXPR
This function returns Scalar.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
@a = (1,2,3,4);
@b = (10,20,30,40);
@c = ( @a, @b );
print "1 - Final Array is @c\n";
@c = ( scalar(@a), scalar(@b) );
print "2 - Final Array is @c\n";
When above code is executed, it produces the following result −
1 - Final Array is 1 2 3 4 10 20 30 40
2 - Final Array is 4 4
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2337,
"s": 2220,
"text": "This function forces the evaluation of EXPR to be in scalar context, even if it would normally work in list context."
},
{
"code": null,
"e": 2388,
"s": 2337,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2401,
"s": 2388,
"text": "scalar EXPR\n"
},
{
"code": null,
"e": 2431,
"s": 2401,
"text": "This function returns Scalar."
},
{
"code": null,
"e": 2487,
"s": 2431,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2661,
"s": 2487,
"text": "#!/usr/bin/perl -w\n\n@a = (1,2,3,4);\n@b = (10,20,30,40);\n\n@c = ( @a, @b );\nprint \"1 - Final Array is @c\\n\";\n\n@c = ( scalar(@a), scalar(@b) );\nprint \"2 - Final Array is @c\\n\";"
},
{
"code": null,
"e": 2725,
"s": 2661,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2788,
"s": 2725,
"text": "1 - Final Array is 1 2 3 4 10 20 30 40\n2 - Final Array is 4 4\n"
},
{
"code": null,
"e": 2823,
"s": 2788,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2837,
"s": 2823,
"text": " Devi Killada"
},
{
"code": null,
"e": 2872,
"s": 2837,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2892,
"s": 2872,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2925,
"s": 2892,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2941,
"s": 2925,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2974,
"s": 2941,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2991,
"s": 2974,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3024,
"s": 2991,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3047,
"s": 3024,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3082,
"s": 3047,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3105,
"s": 3082,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3112,
"s": 3105,
"text": " Print"
},
{
"code": null,
"e": 3123,
"s": 3112,
"text": " Add Notes"
}
] |
XAML - TimePicker
|
A TimePicker is a control that allows a user to pick a time value. The hierarchical inheritance of TimePicker class is as follows −
ClockIdentifier
Gets or sets the clock system to use.
ClockIdentifierProperty
Gets the identifier for the ClockIdentifier dependency property.
Header
Gets or sets the content for the control's header.
HeaderProperty
Identifies the Header dependency property.
HeaderTemplate
Gets or sets the DataTemplate used to display the content of the control's header.
HeaderTemplateProperty
Identifies the HeaderTemplate dependency property.
MinuteIncrement
Gets or sets a value that indicates the time increments shown in the minute picker. For example, 15 specifies that the TimePicker minute control displays only the choices 00, 15, 30, 45.
MinuteIncrementProperty
Gets the identifier for the MinuteIncrement dependency property.
Time
Gets or sets the time currently set in the time picker.
TimeProperty
Gets the identifier for the Time dependency property.
ManipulationCompleted
Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)
ManipulationDelta
Occurs when the input device changes position during a manipulation. (Inherited from UIElement)
ManipulationInertiaStarting
Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)
ManipulationStarted
Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)
ManipulationStarting
Occurs when the manipulation processor is first created. (Inherited from UIElement)
TimeChanged
Occurs when the time value is changed.
OnManipulationCompleted
Called before the ManipulationCompleted event occurs. (Inherited from Control)
OnManipulationDelta
Called before the ManipulationDelta event occurs. (Inherited from Control)
OnManipulationInertiaStarting
Called before the ManipulationInertiaStarting event occurs. (Inherited from Control)
OnManipulationStarted
Called before the ManipulationStarted event occurs. (Inherited from Control)
OnManipulationStarting
Called before the ManipulationStarting event occurs. (Inherited from Control)
The following example shows the usage of TimePicker in an XAML application. Here is the XAML code to create and initialize a TimePicker with some properties.
<Page x:Class = "XAMLTimePicker.MainPage"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local = "using:XAMLTimePicker"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable = "d">
<Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Orientation = "Horizontal" Height = "60" Margin = "46,67,-46,641">
<TimePicker x:Name = "arrivalTimePicker" Header = "Arrival Time" Margin = "0,1"/>
<Button Content = "Submit" Click = "SubmitButton_Click"
Margin = "5,0,0,-2" VerticalAlignment = "Bottom"/>
<TextBlock x:Name = "Control1Output" FontSize = "24"/>
</StackPanel>
</Grid>
</Page>
Here is the click event implementation in C# −
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace XAMLTimePicker {
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
}
private void SubmitButton_Click(object sender, RoutedEventArgs e) {
if (VerifyTimeIsAvailable(arrivalTimePicker.Time) == true) {
Control1Output.Text = string.Format("Thank you. Your appointment is set for {0}.",
arrivalTimePicker.Time.ToString());
} else {
Control1Output.Text = "Sorry, we're only open from 8AM to 5PM.";
}
}
private bool VerifyTimeIsAvailable(TimeSpan time) {
// Set open (8AM) and close (5PM) times.
TimeSpan openTime = new TimeSpan(8, 0, 0);
TimeSpan closeTime = new TimeSpan(17, 0, 0);
if (time >= openTime && time < closeTime) {
return true; // Open
}
return false; // Closed
}
}
}
When you compile and execute the above code, it will display the following output. When time is selected between 8 am to 5 pm, it will display the following message −
Otherwise, the following message will be displayed −
We recommend you to execute the above example code and experiment with some other properties and events.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2055,
"s": 1923,
"text": "A TimePicker is a control that allows a user to pick a time value. The hierarchical inheritance of TimePicker class is as follows −"
},
{
"code": null,
"e": 2071,
"s": 2055,
"text": "ClockIdentifier"
},
{
"code": null,
"e": 2109,
"s": 2071,
"text": "Gets or sets the clock system to use."
},
{
"code": null,
"e": 2133,
"s": 2109,
"text": "ClockIdentifierProperty"
},
{
"code": null,
"e": 2198,
"s": 2133,
"text": "Gets the identifier for the ClockIdentifier dependency property."
},
{
"code": null,
"e": 2205,
"s": 2198,
"text": "Header"
},
{
"code": null,
"e": 2256,
"s": 2205,
"text": "Gets or sets the content for the control's header."
},
{
"code": null,
"e": 2271,
"s": 2256,
"text": "HeaderProperty"
},
{
"code": null,
"e": 2314,
"s": 2271,
"text": "Identifies the Header dependency property."
},
{
"code": null,
"e": 2329,
"s": 2314,
"text": "HeaderTemplate"
},
{
"code": null,
"e": 2412,
"s": 2329,
"text": "Gets or sets the DataTemplate used to display the content of the control's header."
},
{
"code": null,
"e": 2435,
"s": 2412,
"text": "HeaderTemplateProperty"
},
{
"code": null,
"e": 2486,
"s": 2435,
"text": "Identifies the HeaderTemplate dependency property."
},
{
"code": null,
"e": 2502,
"s": 2486,
"text": "MinuteIncrement"
},
{
"code": null,
"e": 2689,
"s": 2502,
"text": "Gets or sets a value that indicates the time increments shown in the minute picker. For example, 15 specifies that the TimePicker minute control displays only the choices 00, 15, 30, 45."
},
{
"code": null,
"e": 2713,
"s": 2689,
"text": "MinuteIncrementProperty"
},
{
"code": null,
"e": 2778,
"s": 2713,
"text": "Gets the identifier for the MinuteIncrement dependency property."
},
{
"code": null,
"e": 2783,
"s": 2778,
"text": "Time"
},
{
"code": null,
"e": 2839,
"s": 2783,
"text": "Gets or sets the time currently set in the time picker."
},
{
"code": null,
"e": 2852,
"s": 2839,
"text": "TimeProperty"
},
{
"code": null,
"e": 2906,
"s": 2852,
"text": "Gets the identifier for the Time dependency property."
},
{
"code": null,
"e": 2928,
"s": 2906,
"text": "ManipulationCompleted"
},
{
"code": null,
"e": 3012,
"s": 2928,
"text": "Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)"
},
{
"code": null,
"e": 3030,
"s": 3012,
"text": "ManipulationDelta"
},
{
"code": null,
"e": 3126,
"s": 3030,
"text": "Occurs when the input device changes position during a manipulation. (Inherited from UIElement)"
},
{
"code": null,
"e": 3154,
"s": 3126,
"text": "ManipulationInertiaStarting"
},
{
"code": null,
"e": 3292,
"s": 3154,
"text": "Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)"
},
{
"code": null,
"e": 3312,
"s": 3292,
"text": "ManipulationStarted"
},
{
"code": null,
"e": 3407,
"s": 3312,
"text": "Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)"
},
{
"code": null,
"e": 3428,
"s": 3407,
"text": "ManipulationStarting"
},
{
"code": null,
"e": 3512,
"s": 3428,
"text": "Occurs when the manipulation processor is first created. (Inherited from UIElement)"
},
{
"code": null,
"e": 3524,
"s": 3512,
"text": "TimeChanged"
},
{
"code": null,
"e": 3563,
"s": 3524,
"text": "Occurs when the time value is changed."
},
{
"code": null,
"e": 3587,
"s": 3563,
"text": "OnManipulationCompleted"
},
{
"code": null,
"e": 3666,
"s": 3587,
"text": "Called before the ManipulationCompleted event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 3686,
"s": 3666,
"text": "OnManipulationDelta"
},
{
"code": null,
"e": 3761,
"s": 3686,
"text": "Called before the ManipulationDelta event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 3791,
"s": 3761,
"text": "OnManipulationInertiaStarting"
},
{
"code": null,
"e": 3876,
"s": 3791,
"text": "Called before the ManipulationInertiaStarting event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 3898,
"s": 3876,
"text": "OnManipulationStarted"
},
{
"code": null,
"e": 3975,
"s": 3898,
"text": "Called before the ManipulationStarted event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 3998,
"s": 3975,
"text": "OnManipulationStarting"
},
{
"code": null,
"e": 4076,
"s": 3998,
"text": "Called before the ManipulationStarting event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 4234,
"s": 4076,
"text": "The following example shows the usage of TimePicker in an XAML application. Here is the XAML code to create and initialize a TimePicker with some properties."
},
{
"code": null,
"e": 5107,
"s": 4234,
"text": "<Page x:Class = \"XAMLTimePicker.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local = \"using:XAMLTimePicker\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n mc:Ignorable = \"d\">\n\n <Grid Background = \"{ThemeResource ApplicationPageBackgroundThemeBrush}\">\n <StackPanel Orientation = \"Horizontal\" Height = \"60\" Margin = \"46,67,-46,641\">\n <TimePicker x:Name = \"arrivalTimePicker\" Header = \"Arrival Time\" Margin = \"0,1\"/> \n <Button Content = \"Submit\" Click = \"SubmitButton_Click\"\n Margin = \"5,0,0,-2\" VerticalAlignment = \"Bottom\"/> \n <TextBlock x:Name = \"Control1Output\" FontSize = \"24\"/> \n </StackPanel> \n </Grid> \n\t\n</Page>"
},
{
"code": null,
"e": 5154,
"s": 5107,
"text": "Here is the click event implementation in C# −"
},
{
"code": null,
"e": 6146,
"s": 5154,
"text": "using System; \nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls;\n\nnamespace XAMLTimePicker {\n public sealed partial class MainPage : Page {\n public MainPage() { \n this.InitializeComponent(); \n }\n private void SubmitButton_Click(object sender, RoutedEventArgs e) {\n if (VerifyTimeIsAvailable(arrivalTimePicker.Time) == true) {\n Control1Output.Text = string.Format(\"Thank you. Your appointment is set for {0}.\",\n arrivalTimePicker.Time.ToString());\n } else {\n Control1Output.Text = \"Sorry, we're only open from 8AM to 5PM.\";\n }\n }\n private bool VerifyTimeIsAvailable(TimeSpan time) {\n // Set open (8AM) and close (5PM) times. \n TimeSpan openTime = new TimeSpan(8, 0, 0); \n TimeSpan closeTime = new TimeSpan(17, 0, 0);\n\t\t\n if (time >= openTime && time < closeTime) { \n return true; // Open \n }\n return false; // Closed \n }\n }\n}"
},
{
"code": null,
"e": 6313,
"s": 6146,
"text": "When you compile and execute the above code, it will display the following output. When time is selected between 8 am to 5 pm, it will display the following message −"
},
{
"code": null,
"e": 6366,
"s": 6313,
"text": "Otherwise, the following message will be displayed −"
},
{
"code": null,
"e": 6471,
"s": 6366,
"text": "We recommend you to execute the above example code and experiment with some other properties and events."
},
{
"code": null,
"e": 6478,
"s": 6471,
"text": " Print"
},
{
"code": null,
"e": 6489,
"s": 6478,
"text": " Add Notes"
}
] |
Google Guice - @Provides Annotation
|
Guice provides a way to create bindings with complex objects using @provides method.
@Provides
public SpellChecker provideSpellChecker() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
This methods is being part of Binding Module and provides the complex object to be mapped. See the complete example below.
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provides;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor( SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {}
@Provides
public SpellChecker provideSpellChecker() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
private String user;
private Integer timeout;
@Inject
public SpellCheckerImpl(String dbUrl,
String user,
Integer timeout) {
this.dbUrl = dbUrl;
this.user = user;
this.timeout = timeout;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
System.out.println(user);
System.out.println(timeout);
}
}
Now, compile and run the file. You can see the following output −
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
user
100
27 Lectures
1.5 hours
Lemuel Ogbunude
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2187,
"s": 2102,
"text": "Guice provides a way to create bindings with complex objects using @provides method."
},
{
"code": null,
"e": 2442,
"s": 2187,
"text": "@Provides\npublic SpellChecker provideSpellChecker() {\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n}"
},
{
"code": null,
"e": 2565,
"s": 2442,
"text": "This methods is being part of Binding Module and provides the complex object to be mapped. See the complete example below."
},
{
"code": null,
"e": 2604,
"s": 2565,
"text": "Create a java class named GuiceTester."
},
{
"code": null,
"e": 2621,
"s": 2604,
"text": "GuiceTester.java"
},
{
"code": null,
"e": 4324,
"s": 2621,
"text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\nclass TextEditor {\n private SpellChecker spellChecker;\n \n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n public void makeSpellCheck() {\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n @Override\n protected void configure() {} \n\n @Provides\n public SpellChecker provideSpellChecker() {\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n }\n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl;\n private String user;\n private Integer timeout;\n\n @Inject\n public SpellCheckerImpl(String dbUrl, \n String user, \n Integer timeout) {\n this.dbUrl = dbUrl;\n this.user = user;\n this.timeout = timeout;\n } \n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl);\n System.out.println(user);\n System.out.println(timeout);\n }\n}"
},
{
"code": null,
"e": 4390,
"s": 4324,
"text": "Now, compile and run the file. You can see the following output −"
},
{
"code": null,
"e": 4454,
"s": 4390,
"text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\nuser\n100\n"
},
{
"code": null,
"e": 4489,
"s": 4454,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4506,
"s": 4489,
"text": " Lemuel Ogbunude"
},
{
"code": null,
"e": 4513,
"s": 4506,
"text": " Print"
},
{
"code": null,
"e": 4524,
"s": 4513,
"text": " Add Notes"
}
] |
Predicting Tweet Sentiment With Word2Vec Embeddings | by Kurtis Pykes | Towards Data Science
|
As the year comes to a close, I’ve been revisiting previous work mainly for fun and to have things in order for the beginning of the new year. Previously, I did an introduction to sentiment analysis then started a project where I used Machine Learning to predict the sentiment of a tweet, and lastly used that same project to determine a systematic way of improving our machine learning models.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Using our systematic strategy to improve our models, we were able to get our score from 0.71008 to 0.79374 on the Kaggle leaderboard respectively. These scores are great. However, they are still quite bad from a Kaggle point of view so we would want to improve on them.
Error analysis is very beneficial for determining what sort of errors our algorithm is making, hence providing us with good insight to what we can improve to provide us with the most significant improvement to our model. On the other hand, Error analysis is incapable of distinguishing whether something like stemming or how we vectorize the text is beneficial to the final solution, and the only solution is to try it and evaluate the change on the evaluation metric. — An extract from Sysematically
At first, we used the counts of the word occurrences to vectorize the tweets then used the Naive Bayes classifier to predict which class each tweet belongs to.
towardsdatascience.com
The issue with this way of vectorizing our tweets is that it doesn’t take into account the context of the tweet and this could be detrimental to our classifier. For example, imagine this is our tweet that we want to classify as a disaster or not “I had a good day today, but the weather was not good”. A human could easily distinguish that this is a negative tweet, but remember a computer doesn’t see words, it sees numbers so we’d have to vectorize the tweet. Therefore, we vectorize the tweet and we decide to use the counts of each word which makes the assumption that each word is independent of one another which isn’t true, even though our Naive Bayes classifier did well on this task.
We can arrive at better vector representations by using word embeddings. Word embeddings (a.k.a word vectors) are a numerical representation of each word in a way that captures the semantic and syntactic underpinnings of that word. The encodings for the vectors are learned by taking the context of which the words appear into consideration, such that words that appear in a similar context would have similar word vectors. For instance, “tiger” and “lion” would be close together but they will be far away from “planet” and “castle”.
What’s great about these word vectors is that we can find relationships between the words by doing mathematical operations with word vectors. If you do king - man + woman the result would be a vector that is closest to the vector for queen.
In an attempt to improve our model, we will be implementing the Word2Vec algorithm which allows us to arrive at a distributed representation of words. There are 2 model architectures underlying the Word2Vec algorithm, the Continuous Bag of Words (CBOW) and Continous Skip-Gram.
Though similar in the sense that they both require a 2 layer neural network and they both take in a large corpus of text to produce a vector space with each word in the corpus corresponding to a vector in the space, the way the algorithm arrives at these vectors in vector space is quite different.
The CBOW model architecture predicts the current word from a window of surrounding context words which makes the assumption that the order of the context words does not influence the prediction.
Alternatively, the Continous Skip-Gram model architecture uses the current word to predict the surrounding window of context words, therefore, giving more weight to the context words that are nearby than the more distant ones.
Note: According to the author’s note, the CBOW is faster while the skip-gram is slower but does a better job for infrequent words. We will implement both and see how the model does.
The simplest way to implement a Word2Vec model is by using pre-trained word embeddings. Pre-trained models are simply word embeddings that were trained on another dataset — for example, the entire corpus of Wikipedia or Google News Dataset — and we can load these embeddings and use them for our task.
The most obvious advantage of this is that we can leverage a massive dataset that is built using billions of different words, and it removes the need for us to have to extract, clean, and process these large datasets. On the other hand, they may not capture the peculiarities of the language in the specific domain. People generally use informal language on Twitter (i.e. “Wyu2”, “OMW”, etc) and these may not be captured by the pre-trained models.
Nonetheless, we will be training our own word embeddings from our corpus. I’ve used Gensim to apply the Word2Vec algorithm which is a popular Natural Language Modelling and Topic modeling framework.
Please visit my Github Portfolio for the full script.
github.com
There’s are two ways we can evaluate our word embeddings to determine the quality of them, intrinsic and extrinsic.
Intrinsic evaluations of word embedding are when we evaluate a set of word embedding that has been generated on a specific intermediate subtask like analogy completion. Analogy completion consists of example term pairs and a query, for instance, “London is to England as Paris is to” and the task would be to correctly fill in the blank.
Extrinsic evaluations of word embeddings are when we evaluate the word vectors that have been generated by applying them to the task at hand. For example, we are doing a sentiment analysis task, therefore when we generate our embeddings, the task is now to pass them into a classifier and evaluate the outcome of the task, hence, this form of evaluation is typically slower to compute and more elaborate than intrinsic.
In saying that, we are going to evaluate our word embeddings using extrinsic evaluation using the F1 score as the evaluation metric; We can see how our Word2Vec, specifically the Continuous Skip-Gram model architecture, performed on the training data with a Logistic Regression:
Logistic RegressionFold 1Train f1: 0.7321764582897763Val f1: 0.7062706270627062Fold 2Train f1: 0.7255189767246802Val f1: 0.7187765505522514Fold 3Train f1: 0.715187210769878Val f1: 0.7360532889258952Fold 4Train f1: 0.7226537896283856Val f1: 0.7138157894736842Fold 5Train f1: 0.7307772889168238Val f1: 0.6845637583892618
Let’s also check how te model does with a Random Forest Classifier:
Random Forest ClassifierFold 1Train f1: 0.9922898997686971Val f1: 0.7015437392795884Fold 2Train f1: 0.9917132395451916Val f1: 0.7080419580419579Fold 3Train f1: 0.9922839506172839Val f1: 0.7291311754684837Fold 4Train f1: 0.9930635838150289Val f1: 0.6848381601362862Fold 5Train f1: 0.9923017705927637Val f1: 0.6888694127957932
and lastly, SVM:
SVMFold 1Train f1: 0.8672164948453608Val f1: 0.725925925925926Fold 2Train f1: 0.8634655532359081Val f1: 0.7072961373390558Fold 3Train f1: 0.8673998754928408Val f1: 0.7487603305785123Fold 4Train f1: 0.8674147963424771Val f1: 0.7133105802047782Fold 5Train f1: 0.8687202811660121Val f1: 0.7007672634271099
For more information on these models, visit the algorithms from scratch series...
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Note: I wasn't able to get around an error I was receiving when trying to use Naive Bayes — ValueError: Negative Values in Data Passed to MultinomialNB (Input X) — so I ended up scrapping the Naive Bayes classifier.
Given these results, I decided to submit the SVM output to Kaggle...
We weren’t able to improve on our leaderboard score. In the future, I will try out more powerful Machine Learning models such as LightGBM and Neural Networks, as well as extracting the word embeddings using different techniques. Once I’ve found a model I am happy with, I will then work on some feature engineering to try and squeeze the most out of the model before considering stacking and blending to push the score that little bit further.
Note: This is all about the leaderboard and I am not trying to build a real-world tool.
Thank you for reading to the end, connect with me on LinkedIn to keep in touch:
|
[
{
"code": null,
"e": 442,
"s": 47,
"text": "As the year comes to a close, I’ve been revisiting previous work mainly for fun and to have things in order for the beginning of the new year. Previously, I did an introduction to sentiment analysis then started a project where I used Machine Learning to predict the sentiment of a tweet, and lastly used that same project to determine a systematic way of improving our machine learning models."
},
{
"code": null,
"e": 465,
"s": 442,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 488,
"s": 465,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 511,
"s": 488,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 781,
"s": 511,
"text": "Using our systematic strategy to improve our models, we were able to get our score from 0.71008 to 0.79374 on the Kaggle leaderboard respectively. These scores are great. However, they are still quite bad from a Kaggle point of view so we would want to improve on them."
},
{
"code": null,
"e": 1282,
"s": 781,
"text": "Error analysis is very beneficial for determining what sort of errors our algorithm is making, hence providing us with good insight to what we can improve to provide us with the most significant improvement to our model. On the other hand, Error analysis is incapable of distinguishing whether something like stemming or how we vectorize the text is beneficial to the final solution, and the only solution is to try it and evaluate the change on the evaluation metric. — An extract from Sysematically"
},
{
"code": null,
"e": 1442,
"s": 1282,
"text": "At first, we used the counts of the word occurrences to vectorize the tweets then used the Naive Bayes classifier to predict which class each tweet belongs to."
},
{
"code": null,
"e": 1465,
"s": 1442,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2158,
"s": 1465,
"text": "The issue with this way of vectorizing our tweets is that it doesn’t take into account the context of the tweet and this could be detrimental to our classifier. For example, imagine this is our tweet that we want to classify as a disaster or not “I had a good day today, but the weather was not good”. A human could easily distinguish that this is a negative tweet, but remember a computer doesn’t see words, it sees numbers so we’d have to vectorize the tweet. Therefore, we vectorize the tweet and we decide to use the counts of each word which makes the assumption that each word is independent of one another which isn’t true, even though our Naive Bayes classifier did well on this task."
},
{
"code": null,
"e": 2693,
"s": 2158,
"text": "We can arrive at better vector representations by using word embeddings. Word embeddings (a.k.a word vectors) are a numerical representation of each word in a way that captures the semantic and syntactic underpinnings of that word. The encodings for the vectors are learned by taking the context of which the words appear into consideration, such that words that appear in a similar context would have similar word vectors. For instance, “tiger” and “lion” would be close together but they will be far away from “planet” and “castle”."
},
{
"code": null,
"e": 2934,
"s": 2693,
"text": "What’s great about these word vectors is that we can find relationships between the words by doing mathematical operations with word vectors. If you do king - man + woman the result would be a vector that is closest to the vector for queen."
},
{
"code": null,
"e": 3212,
"s": 2934,
"text": "In an attempt to improve our model, we will be implementing the Word2Vec algorithm which allows us to arrive at a distributed representation of words. There are 2 model architectures underlying the Word2Vec algorithm, the Continuous Bag of Words (CBOW) and Continous Skip-Gram."
},
{
"code": null,
"e": 3511,
"s": 3212,
"text": "Though similar in the sense that they both require a 2 layer neural network and they both take in a large corpus of text to produce a vector space with each word in the corpus corresponding to a vector in the space, the way the algorithm arrives at these vectors in vector space is quite different."
},
{
"code": null,
"e": 3706,
"s": 3511,
"text": "The CBOW model architecture predicts the current word from a window of surrounding context words which makes the assumption that the order of the context words does not influence the prediction."
},
{
"code": null,
"e": 3933,
"s": 3706,
"text": "Alternatively, the Continous Skip-Gram model architecture uses the current word to predict the surrounding window of context words, therefore, giving more weight to the context words that are nearby than the more distant ones."
},
{
"code": null,
"e": 4115,
"s": 3933,
"text": "Note: According to the author’s note, the CBOW is faster while the skip-gram is slower but does a better job for infrequent words. We will implement both and see how the model does."
},
{
"code": null,
"e": 4417,
"s": 4115,
"text": "The simplest way to implement a Word2Vec model is by using pre-trained word embeddings. Pre-trained models are simply word embeddings that were trained on another dataset — for example, the entire corpus of Wikipedia or Google News Dataset — and we can load these embeddings and use them for our task."
},
{
"code": null,
"e": 4866,
"s": 4417,
"text": "The most obvious advantage of this is that we can leverage a massive dataset that is built using billions of different words, and it removes the need for us to have to extract, clean, and process these large datasets. On the other hand, they may not capture the peculiarities of the language in the specific domain. People generally use informal language on Twitter (i.e. “Wyu2”, “OMW”, etc) and these may not be captured by the pre-trained models."
},
{
"code": null,
"e": 5065,
"s": 4866,
"text": "Nonetheless, we will be training our own word embeddings from our corpus. I’ve used Gensim to apply the Word2Vec algorithm which is a popular Natural Language Modelling and Topic modeling framework."
},
{
"code": null,
"e": 5119,
"s": 5065,
"text": "Please visit my Github Portfolio for the full script."
},
{
"code": null,
"e": 5130,
"s": 5119,
"text": "github.com"
},
{
"code": null,
"e": 5246,
"s": 5130,
"text": "There’s are two ways we can evaluate our word embeddings to determine the quality of them, intrinsic and extrinsic."
},
{
"code": null,
"e": 5584,
"s": 5246,
"text": "Intrinsic evaluations of word embedding are when we evaluate a set of word embedding that has been generated on a specific intermediate subtask like analogy completion. Analogy completion consists of example term pairs and a query, for instance, “London is to England as Paris is to” and the task would be to correctly fill in the blank."
},
{
"code": null,
"e": 6004,
"s": 5584,
"text": "Extrinsic evaluations of word embeddings are when we evaluate the word vectors that have been generated by applying them to the task at hand. For example, we are doing a sentiment analysis task, therefore when we generate our embeddings, the task is now to pass them into a classifier and evaluate the outcome of the task, hence, this form of evaluation is typically slower to compute and more elaborate than intrinsic."
},
{
"code": null,
"e": 6283,
"s": 6004,
"text": "In saying that, we are going to evaluate our word embeddings using extrinsic evaluation using the F1 score as the evaluation metric; We can see how our Word2Vec, specifically the Continuous Skip-Gram model architecture, performed on the training data with a Logistic Regression:"
},
{
"code": null,
"e": 6602,
"s": 6283,
"text": "Logistic RegressionFold 1Train f1: 0.7321764582897763Val f1: 0.7062706270627062Fold 2Train f1: 0.7255189767246802Val f1: 0.7187765505522514Fold 3Train f1: 0.715187210769878Val f1: 0.7360532889258952Fold 4Train f1: 0.7226537896283856Val f1: 0.7138157894736842Fold 5Train f1: 0.7307772889168238Val f1: 0.6845637583892618"
},
{
"code": null,
"e": 6670,
"s": 6602,
"text": "Let’s also check how te model does with a Random Forest Classifier:"
},
{
"code": null,
"e": 6995,
"s": 6670,
"text": "Random Forest ClassifierFold 1Train f1: 0.9922898997686971Val f1: 0.7015437392795884Fold 2Train f1: 0.9917132395451916Val f1: 0.7080419580419579Fold 3Train f1: 0.9922839506172839Val f1: 0.7291311754684837Fold 4Train f1: 0.9930635838150289Val f1: 0.6848381601362862Fold 5Train f1: 0.9923017705927637Val f1: 0.6888694127957932"
},
{
"code": null,
"e": 7012,
"s": 6995,
"text": "and lastly, SVM:"
},
{
"code": null,
"e": 7315,
"s": 7012,
"text": "SVMFold 1Train f1: 0.8672164948453608Val f1: 0.725925925925926Fold 2Train f1: 0.8634655532359081Val f1: 0.7072961373390558Fold 3Train f1: 0.8673998754928408Val f1: 0.7487603305785123Fold 4Train f1: 0.8674147963424771Val f1: 0.7133105802047782Fold 5Train f1: 0.8687202811660121Val f1: 0.7007672634271099"
},
{
"code": null,
"e": 7397,
"s": 7315,
"text": "For more information on these models, visit the algorithms from scratch series..."
},
{
"code": null,
"e": 7420,
"s": 7397,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7443,
"s": 7420,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7466,
"s": 7443,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7682,
"s": 7466,
"text": "Note: I wasn't able to get around an error I was receiving when trying to use Naive Bayes — ValueError: Negative Values in Data Passed to MultinomialNB (Input X) — so I ended up scrapping the Naive Bayes classifier."
},
{
"code": null,
"e": 7751,
"s": 7682,
"text": "Given these results, I decided to submit the SVM output to Kaggle..."
},
{
"code": null,
"e": 8195,
"s": 7751,
"text": "We weren’t able to improve on our leaderboard score. In the future, I will try out more powerful Machine Learning models such as LightGBM and Neural Networks, as well as extracting the word embeddings using different techniques. Once I’ve found a model I am happy with, I will then work on some feature engineering to try and squeeze the most out of the model before considering stacking and blending to push the score that little bit further."
},
{
"code": null,
"e": 8283,
"s": 8195,
"text": "Note: This is all about the leaderboard and I am not trying to build a real-world tool."
}
] |
Installing Tensorflow with CUDA, cuDNN and GPU support on Windows 10 | by Dr. Joanne Kitson | Towards Data Science
|
In Part 1 of this series, I discussed how you can upgrade your PC hardware to incorporate a CUDA Toolkit compatible graphics processing card, such as an Nvidia GPU. This Part 2 covers the installation of CUDA, cuDNN and Tensorflow on Windows 10. This article below assumes that you have a CUDA-compatible GPU already installed on your PC; but if you haven’t got this already, Part 1 of this series will help you get that hardware set up, ready for these steps.
Assuming that Windows is already installed on your PC, the additional bits of software you will install as part of these steps are:-
Microsoft Visual Studio
the NVIDIA CUDA Toolkit
NVIDIA cuDNN
Python
Tensorflow (with GPU support)
Visual studio is required for the installation of Nvidia CUDA Toolkit (this prerequisite is referred to here). If you attempt to download and install CUDA Toolkit for Windows without having first installed Visual Studio, you get the message shown in Fig. 1.
At the time of writing, the most recent version of Visual Studio (which is free) is the Visual Studio Express Community Version 2017, shown in Fig 2. You can get previous versions of Visual Studio for free by joining “Visual Studio Dev Essentials” and then searching for the version of Visual Studio you want.
Once you have downloaded Visual Studio Express, its installation is straightforward. Fig 3 shows the executable file you receive as a download.
When you press the ‘save file’ option on Fig 3, the window in Fig 4 will appear where you can set installation options (or just leave them as they are by default, as I did).
During installation, Visual Studio prompts you to as whether you ‘want to continue without workloads’. I pressed ‘continue’ here, as I had no intention of using workloads at all.
A PC reboot after installation of Visual Studio May be Required
After installing Visual Studio, I initially moved straight on to downloading and attempting to install CUDA Toolkit for Windows — that step is Step 3 which I will be describing next. I got a message that Visual Studio was still operating and was preventing the installation of CUDA Toolkit. Rebooting my PC before attempting to install CUDA Toolkit again solved this problem.
These CUDA installation steps are loosely based on the Nvidia CUDA installation guide for windows. The CUDA Toolkit (free) can be downloaded from the Nvidia website here.
At the time of writing, the default version of CUDA Toolkit offered is version 10.0, as shown in Fig 6. However, you should check which version of CUDA Toolkit you choose for download and installation to ensure compatibility with Tensorflow (looking ahead to Step 7 of this process). When you go onto the Tensorflow website, the latest version of Tensorflow available (1.12.0) requires CUDA 9.0, not CUDA 10.0. To find CUDA 9.0, you need to navigate to the “Legacy Releases” on the bottom right hand side of Fig 6.
Step 3.1: Downloading CUDA 9.0 from the CUDA Toolkit Archive
Choosing “Legacy Releases” takes you to the CUDA Toolkit Archive. Based on Tensorflow installation guidance, the CUDA version required is 9.0, as listed in Fig 7.
Step 3.2: Installing CUDA 9.0
CUDA 9.0 comes as a base installation and four patches; the base installation of CUDA 9.0 must be installed first, followed by the patches. The options for the base install which I selected are shown in Fig 8.
Running the base installer which has just been downloaded will produce the CUDA Setup Package window, as shown in Fig 9.
The CUDA installer extracts to your PC and, when complete, the NVIDIA CUDA Toolkit installation will start; you will get a message to that effect. The resulting NVIDIA Installer windows throughout the installation process are shown at Fig 10 — Fig 13. I chose the express installation option (Fig. 10).
Fig. 11 provides the opportunity to select installation location; I chose the default locations provided, which for CUDA is :
C:\Program Files\NVIDA GPU Computing Toolkit\CUDA\v9.0
Fig. 12 below shows the CUDA installations which rely on Visual studio, previously installed in Step 1.
Pressing ‘next’ at the window shown in Fig. 12 above, gives the final installation window, shown as Fig.13 below, where the NVIDIA installer is marked as finished.
At the time of writing, there are four CUDA patches to get (as well as the base installer), so let’s go and download these. They are shown in Fig.14.
When the four patches are downloaded, they can be installed in the same way as the base installer — with installation windows providing guidance through the process.
Having installed CUDA 9.0 base installer and its four patches, the next step is to find a compatible version of CuDNN. Based on the information on the Tensorflow website, Tensorflow with GPU support requires a cuDNN version of at least 7.2.
Step 5.1: Downloading cuDNN
In order to download CuDNN, you have to register to become a member of the NVIDIA Developer Program (which is free).
When you create an account, login and fill out some other required details about why you are using the account, you get the download page shown in Fig. 16.
As I have downloaded CUDA 9.0, the corresponding version of cuDNN is version 7.4.2. Choosing cuDNN version 7.4.2 enables the download as a zip file named as follows:
cudnn-9.0-windows10-x64-v7.zip
Step 5.2: Unzipping cuDNN files and copying to CUDA folders
Instructions at Nvidia provide support for windows cuDNN installation, as do instructions on the Tensorflow website ; I have reproduced these instructions in distilled form, based on my implementation of them. In my case, I downloaded the cuDNN .zip file named above into a folder which has the following path on my PC (your path will no doubt be different).
C:\Users\jo\Documents\cuDNN_downloads\
In the instructions below, I refer to the folder path “ C:\Users\jo\Documents\cuDNN_downloads\” (referred to just above) as “<downloadpath>”, such that the zip file is now in the path:
<downloadpath>\cudnn-9.0-windows10-x64-v7.5.0.56.zip
I unzipped the cuDNN “.zip” file where I downloaded it, hence the unzipped folder structure which will contain the required cuDNN files is now:-
<downloadpath>\cudnn-9.0-windows10-x64-v7.5.0.56\
There are three files in the unzipped cuDNN folder subdirectories which are to be copied into the CUDA Toolkit directories. These are cudnn64_7.dll, cudnn.h and :
1. cudnn64_7.dll
cudnn64_7.dll can be found in the following path within the downloaded cuDNN files:
<downloadpath>\cudnn-9.0-windows10-x64-v7.5.0.56\cuda\bin\cudnn64_7.dll
Assuming that you installed CUDA 9.0 to its default path (as I did at Step 2.3), namely the following default path:
C:\Program Files\NVIDA GPU Computing Toolkit\CUDA\v9.0
you can copy the cudnn64_7.dll file directly into the CUDA folder’s bin folder path (note: you don’t need to create any new subfolders):
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin\
2. cudnn.h
As with the cudnn64_7.dll file above, after downloading and unzipping the cuDNN folder, the header file cudnn64.h can be found in the path:
<downloadpath>\cudnn-9.0-windows10-x64-v7.5.0.56\cuda\ include\cudnn.h
Again, assuming that you installed CUDA 9.0 into the default path as I did at Step 2.3, copy cudnn.h directly into the CUDA folder with the following path (no new subfolders are necessary):
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\include\
3. cudnn.lib
The .lib file cudnn.lib can be found in the downloaded cuDNN path:
<downloadpath>\cudnn-9.0-windows10-x64-v7.5.0.56\cuda\lib\x64\cudnn.lib
Copy cudnn.lib directly into the CUDA folder with the following path:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib\x64\
Step 5.3: Checking CUDA environment variables are set in Windows
Finally, the instructions at Nvidia direct that you ensure that the CUDA environment variable has previously been set up, as follows:
Variable Name: CUDA_PATH Variable Value: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0
In Windows 10, the Environment Variables can be found by choosing:
Control Panel ->System and Security->System->Advanced System settings.
This opens up a window called “System Properties” (Fig 17), at which point the “Environment Variables” button should be chosen.
When the Environment Variables window then appears, within “system variables” (in the bottom half of the window), click on “Path” and choose the button “edit”. A new window will appear, called “Edit environment variable” as shown in Fig 18 below.
On checking the Environment Variables, I found the installation process which determines the CUDA installation path — Step 3.2, see Fig. 11 — had already added two paths to CUDA . These paths are shown in Fig 18 below, so I found I did not need to add a further CUDA path.
Now that CUDA and cuDNN are installed, it is time to install Python to enable Tensorflow to be installed later on. At the time of writing, the most up to date version of Python 3 available is Python 3.7, but the Python 3 versions required for Tensorflow are 3.4, 3.5 or 3.6. Python 3.6 can be downloaded for Windows 10 from here. When you run the Python installer for windows, the setup window in Fig 19 will appear.
Of the options in Fig. 19 above during Python installation, I chose to select all of them. These options are useful: Python’s ‘pip’ installer is used at Step 7.2 of this guide to install Tensorflow. Additionally, I use the IDE (integrated development environment for writing and running python code) called “IDLE” at Step 8.
In the “Advanced Options” (shown at Fig 20 below), I chose the installation of Python for all users (which was not ticked by default); this gives the more useful system wide installation.
Tensorflow provides instructions for checking that CUDA, cuDNN and (optional: CUPTI) installation directories are correctly added to the PATH environmental variables. As the three cuDNN files were copied into the subfolders of CUDA, I did not update the existing CUDA environmental variables path.
Step 7.1: Calling up the command prompt with administration rights
In this step a system-wide install of Tensorflow is carried out, not a per user install. System wide installation of Tensorflow requires administrative rights, therefore, accordingly the command prompt should be run with administrative rights.
Open up the command prompt by running ‘cmd’ in the search bar, and then right clicking on command prompt to choose ‘run as administrator’. This opens up Administrator: Command Prompt as shown in Fig 21.
Step 7.2: System wide install of Tensorflow via python pip
Having opened the Command Prompt, the system-wide installation command for Tensorflow with GPU support is as follows:
pip3 install --upgrade tensorflow-gpu
The “pip3” command (as opposed to “pip”) is required as the installation is to Python 3. Execution of this command in the command prompt is shown in Fig 22.
The resulting output from the command is shown in Fig 23, and if all goes to plan there should eventually be a message to confirm that Tensorflow has been installed successfully.
Go to the start menu in windows and search for the IDE called ‘idle’, which will be installed as part of your python installation if you selected as I did at Step 6. A Python window should appear labelled Python 3.6.x Shell. At the prompt (denoted by ‘>>>’), import the Tensorflow package. This will check that Tensorflow has been installed (as you can import it). The command for the IDLE shell to import the tensorflow package is as follows:
# importing the tensorflow packageimport tensorflow as tf
To test CUDA support for your Tensorflow installation, you can run the following command in the shell:
tf.test.is_built_with_cuda()
Finally, to confirm that the GPU is available to Tensorflow, you can test using a built-in utility function in TensorFlow as shown here:
tf.test.is_gpu_available(cuda_only=False, min_cuda_compute_capability=None)
It takes a few minutes to return a result from this; when it is finished it returns True, and then the prompt `>>>`appears again. Importing tensorflow and these tests are all shown in Fig 24 in the Python IDLE Shell.
These were the steps I took to install Visual Studio, CUDA Toolkit, CuDNN and Python 3.6, all with the ultimate aim of installing Tensorflow with GPU support on Windows 10. To date, my GPU based machine learning and deep learning work has been on Linux Ubuntu machines; by the same token, much of the machine learning community support online focuses on Ubuntu.
For Machine Learning, the major drawback to using Windows is that it is necessary to build more things from source (for example using Cmake) than on Linux, and also to install additional software for the build processes, such as Visual Studio. For example, if you were to install Caffe2 on Windows, there are no pre-built binaries and Windows build is in testing and beta mode. I installed CUDA and cuDNN on Windows 10 more out of curiosity than anything else, just to see how straightforward (or otherwise) it was.
As I intimated in Part 1, now that CUDA, cuDNN and Tensorflow are successfully installed on Windows 10 and I have checked Tensorflow’s access to GPU, I am going to sweep the whole Windows 10 operating system away in order to make a fresh installation of Ubuntu 18.04 LTS. This new installation of Ubuntu will be covered in Part 3 of this series.
This article has also been published here on my own blog.
|
[
{
"code": null,
"e": 632,
"s": 171,
"text": "In Part 1 of this series, I discussed how you can upgrade your PC hardware to incorporate a CUDA Toolkit compatible graphics processing card, such as an Nvidia GPU. This Part 2 covers the installation of CUDA, cuDNN and Tensorflow on Windows 10. This article below assumes that you have a CUDA-compatible GPU already installed on your PC; but if you haven’t got this already, Part 1 of this series will help you get that hardware set up, ready for these steps."
},
{
"code": null,
"e": 765,
"s": 632,
"text": "Assuming that Windows is already installed on your PC, the additional bits of software you will install as part of these steps are:-"
},
{
"code": null,
"e": 789,
"s": 765,
"text": "Microsoft Visual Studio"
},
{
"code": null,
"e": 813,
"s": 789,
"text": "the NVIDIA CUDA Toolkit"
},
{
"code": null,
"e": 826,
"s": 813,
"text": "NVIDIA cuDNN"
},
{
"code": null,
"e": 833,
"s": 826,
"text": "Python"
},
{
"code": null,
"e": 863,
"s": 833,
"text": "Tensorflow (with GPU support)"
},
{
"code": null,
"e": 1121,
"s": 863,
"text": "Visual studio is required for the installation of Nvidia CUDA Toolkit (this prerequisite is referred to here). If you attempt to download and install CUDA Toolkit for Windows without having first installed Visual Studio, you get the message shown in Fig. 1."
},
{
"code": null,
"e": 1431,
"s": 1121,
"text": "At the time of writing, the most recent version of Visual Studio (which is free) is the Visual Studio Express Community Version 2017, shown in Fig 2. You can get previous versions of Visual Studio for free by joining “Visual Studio Dev Essentials” and then searching for the version of Visual Studio you want."
},
{
"code": null,
"e": 1575,
"s": 1431,
"text": "Once you have downloaded Visual Studio Express, its installation is straightforward. Fig 3 shows the executable file you receive as a download."
},
{
"code": null,
"e": 1749,
"s": 1575,
"text": "When you press the ‘save file’ option on Fig 3, the window in Fig 4 will appear where you can set installation options (or just leave them as they are by default, as I did)."
},
{
"code": null,
"e": 1928,
"s": 1749,
"text": "During installation, Visual Studio prompts you to as whether you ‘want to continue without workloads’. I pressed ‘continue’ here, as I had no intention of using workloads at all."
},
{
"code": null,
"e": 1992,
"s": 1928,
"text": "A PC reboot after installation of Visual Studio May be Required"
},
{
"code": null,
"e": 2368,
"s": 1992,
"text": "After installing Visual Studio, I initially moved straight on to downloading and attempting to install CUDA Toolkit for Windows — that step is Step 3 which I will be describing next. I got a message that Visual Studio was still operating and was preventing the installation of CUDA Toolkit. Rebooting my PC before attempting to install CUDA Toolkit again solved this problem."
},
{
"code": null,
"e": 2539,
"s": 2368,
"text": "These CUDA installation steps are loosely based on the Nvidia CUDA installation guide for windows. The CUDA Toolkit (free) can be downloaded from the Nvidia website here."
},
{
"code": null,
"e": 3054,
"s": 2539,
"text": "At the time of writing, the default version of CUDA Toolkit offered is version 10.0, as shown in Fig 6. However, you should check which version of CUDA Toolkit you choose for download and installation to ensure compatibility with Tensorflow (looking ahead to Step 7 of this process). When you go onto the Tensorflow website, the latest version of Tensorflow available (1.12.0) requires CUDA 9.0, not CUDA 10.0. To find CUDA 9.0, you need to navigate to the “Legacy Releases” on the bottom right hand side of Fig 6."
},
{
"code": null,
"e": 3115,
"s": 3054,
"text": "Step 3.1: Downloading CUDA 9.0 from the CUDA Toolkit Archive"
},
{
"code": null,
"e": 3278,
"s": 3115,
"text": "Choosing “Legacy Releases” takes you to the CUDA Toolkit Archive. Based on Tensorflow installation guidance, the CUDA version required is 9.0, as listed in Fig 7."
},
{
"code": null,
"e": 3308,
"s": 3278,
"text": "Step 3.2: Installing CUDA 9.0"
},
{
"code": null,
"e": 3518,
"s": 3308,
"text": "CUDA 9.0 comes as a base installation and four patches; the base installation of CUDA 9.0 must be installed first, followed by the patches. The options for the base install which I selected are shown in Fig 8."
},
{
"code": null,
"e": 3639,
"s": 3518,
"text": "Running the base installer which has just been downloaded will produce the CUDA Setup Package window, as shown in Fig 9."
},
{
"code": null,
"e": 3942,
"s": 3639,
"text": "The CUDA installer extracts to your PC and, when complete, the NVIDIA CUDA Toolkit installation will start; you will get a message to that effect. The resulting NVIDIA Installer windows throughout the installation process are shown at Fig 10 — Fig 13. I chose the express installation option (Fig. 10)."
},
{
"code": null,
"e": 4068,
"s": 3942,
"text": "Fig. 11 provides the opportunity to select installation location; I chose the default locations provided, which for CUDA is :"
},
{
"code": null,
"e": 4123,
"s": 4068,
"text": "C:\\Program Files\\NVIDA GPU Computing Toolkit\\CUDA\\v9.0"
},
{
"code": null,
"e": 4227,
"s": 4123,
"text": "Fig. 12 below shows the CUDA installations which rely on Visual studio, previously installed in Step 1."
},
{
"code": null,
"e": 4391,
"s": 4227,
"text": "Pressing ‘next’ at the window shown in Fig. 12 above, gives the final installation window, shown as Fig.13 below, where the NVIDIA installer is marked as finished."
},
{
"code": null,
"e": 4541,
"s": 4391,
"text": "At the time of writing, there are four CUDA patches to get (as well as the base installer), so let’s go and download these. They are shown in Fig.14."
},
{
"code": null,
"e": 4707,
"s": 4541,
"text": "When the four patches are downloaded, they can be installed in the same way as the base installer — with installation windows providing guidance through the process."
},
{
"code": null,
"e": 4948,
"s": 4707,
"text": "Having installed CUDA 9.0 base installer and its four patches, the next step is to find a compatible version of CuDNN. Based on the information on the Tensorflow website, Tensorflow with GPU support requires a cuDNN version of at least 7.2."
},
{
"code": null,
"e": 4976,
"s": 4948,
"text": "Step 5.1: Downloading cuDNN"
},
{
"code": null,
"e": 5093,
"s": 4976,
"text": "In order to download CuDNN, you have to register to become a member of the NVIDIA Developer Program (which is free)."
},
{
"code": null,
"e": 5249,
"s": 5093,
"text": "When you create an account, login and fill out some other required details about why you are using the account, you get the download page shown in Fig. 16."
},
{
"code": null,
"e": 5415,
"s": 5249,
"text": "As I have downloaded CUDA 9.0, the corresponding version of cuDNN is version 7.4.2. Choosing cuDNN version 7.4.2 enables the download as a zip file named as follows:"
},
{
"code": null,
"e": 5447,
"s": 5415,
"text": "cudnn-9.0-windows10-x64-v7.zip "
},
{
"code": null,
"e": 5507,
"s": 5447,
"text": "Step 5.2: Unzipping cuDNN files and copying to CUDA folders"
},
{
"code": null,
"e": 5866,
"s": 5507,
"text": "Instructions at Nvidia provide support for windows cuDNN installation, as do instructions on the Tensorflow website ; I have reproduced these instructions in distilled form, based on my implementation of them. In my case, I downloaded the cuDNN .zip file named above into a folder which has the following path on my PC (your path will no doubt be different)."
},
{
"code": null,
"e": 5905,
"s": 5866,
"text": "C:\\Users\\jo\\Documents\\cuDNN_downloads\\"
},
{
"code": null,
"e": 6090,
"s": 5905,
"text": "In the instructions below, I refer to the folder path “ C:\\Users\\jo\\Documents\\cuDNN_downloads\\” (referred to just above) as “<downloadpath>”, such that the zip file is now in the path:"
},
{
"code": null,
"e": 6143,
"s": 6090,
"text": "<downloadpath>\\cudnn-9.0-windows10-x64-v7.5.0.56.zip"
},
{
"code": null,
"e": 6288,
"s": 6143,
"text": "I unzipped the cuDNN “.zip” file where I downloaded it, hence the unzipped folder structure which will contain the required cuDNN files is now:-"
},
{
"code": null,
"e": 6338,
"s": 6288,
"text": "<downloadpath>\\cudnn-9.0-windows10-x64-v7.5.0.56\\"
},
{
"code": null,
"e": 6501,
"s": 6338,
"text": "There are three files in the unzipped cuDNN folder subdirectories which are to be copied into the CUDA Toolkit directories. These are cudnn64_7.dll, cudnn.h and :"
},
{
"code": null,
"e": 6518,
"s": 6501,
"text": "1. cudnn64_7.dll"
},
{
"code": null,
"e": 6602,
"s": 6518,
"text": "cudnn64_7.dll can be found in the following path within the downloaded cuDNN files:"
},
{
"code": null,
"e": 6674,
"s": 6602,
"text": "<downloadpath>\\cudnn-9.0-windows10-x64-v7.5.0.56\\cuda\\bin\\cudnn64_7.dll"
},
{
"code": null,
"e": 6790,
"s": 6674,
"text": "Assuming that you installed CUDA 9.0 to its default path (as I did at Step 2.3), namely the following default path:"
},
{
"code": null,
"e": 6845,
"s": 6790,
"text": "C:\\Program Files\\NVIDA GPU Computing Toolkit\\CUDA\\v9.0"
},
{
"code": null,
"e": 6982,
"s": 6845,
"text": "you can copy the cudnn64_7.dll file directly into the CUDA folder’s bin folder path (note: you don’t need to create any new subfolders):"
},
{
"code": null,
"e": 7043,
"s": 6982,
"text": "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v9.0\\bin\\"
},
{
"code": null,
"e": 7054,
"s": 7043,
"text": "2. cudnn.h"
},
{
"code": null,
"e": 7194,
"s": 7054,
"text": "As with the cudnn64_7.dll file above, after downloading and unzipping the cuDNN folder, the header file cudnn64.h can be found in the path:"
},
{
"code": null,
"e": 7265,
"s": 7194,
"text": "<downloadpath>\\cudnn-9.0-windows10-x64-v7.5.0.56\\cuda\\ include\\cudnn.h"
},
{
"code": null,
"e": 7455,
"s": 7265,
"text": "Again, assuming that you installed CUDA 9.0 into the default path as I did at Step 2.3, copy cudnn.h directly into the CUDA folder with the following path (no new subfolders are necessary):"
},
{
"code": null,
"e": 7520,
"s": 7455,
"text": "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v9.0\\include\\"
},
{
"code": null,
"e": 7533,
"s": 7520,
"text": "3. cudnn.lib"
},
{
"code": null,
"e": 7600,
"s": 7533,
"text": "The .lib file cudnn.lib can be found in the downloaded cuDNN path:"
},
{
"code": null,
"e": 7672,
"s": 7600,
"text": "<downloadpath>\\cudnn-9.0-windows10-x64-v7.5.0.56\\cuda\\lib\\x64\\cudnn.lib"
},
{
"code": null,
"e": 7742,
"s": 7672,
"text": "Copy cudnn.lib directly into the CUDA folder with the following path:"
},
{
"code": null,
"e": 7807,
"s": 7742,
"text": "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v9.0\\lib\\x64\\"
},
{
"code": null,
"e": 7872,
"s": 7807,
"text": "Step 5.3: Checking CUDA environment variables are set in Windows"
},
{
"code": null,
"e": 8006,
"s": 7872,
"text": "Finally, the instructions at Nvidia direct that you ensure that the CUDA environment variable has previously been set up, as follows:"
},
{
"code": null,
"e": 8103,
"s": 8006,
"text": "Variable Name: CUDA_PATH Variable Value: C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v9.0"
},
{
"code": null,
"e": 8170,
"s": 8103,
"text": "In Windows 10, the Environment Variables can be found by choosing:"
},
{
"code": null,
"e": 8241,
"s": 8170,
"text": "Control Panel ->System and Security->System->Advanced System settings."
},
{
"code": null,
"e": 8369,
"s": 8241,
"text": "This opens up a window called “System Properties” (Fig 17), at which point the “Environment Variables” button should be chosen."
},
{
"code": null,
"e": 8616,
"s": 8369,
"text": "When the Environment Variables window then appears, within “system variables” (in the bottom half of the window), click on “Path” and choose the button “edit”. A new window will appear, called “Edit environment variable” as shown in Fig 18 below."
},
{
"code": null,
"e": 8889,
"s": 8616,
"text": "On checking the Environment Variables, I found the installation process which determines the CUDA installation path — Step 3.2, see Fig. 11 — had already added two paths to CUDA . These paths are shown in Fig 18 below, so I found I did not need to add a further CUDA path."
},
{
"code": null,
"e": 9306,
"s": 8889,
"text": "Now that CUDA and cuDNN are installed, it is time to install Python to enable Tensorflow to be installed later on. At the time of writing, the most up to date version of Python 3 available is Python 3.7, but the Python 3 versions required for Tensorflow are 3.4, 3.5 or 3.6. Python 3.6 can be downloaded for Windows 10 from here. When you run the Python installer for windows, the setup window in Fig 19 will appear."
},
{
"code": null,
"e": 9631,
"s": 9306,
"text": "Of the options in Fig. 19 above during Python installation, I chose to select all of them. These options are useful: Python’s ‘pip’ installer is used at Step 7.2 of this guide to install Tensorflow. Additionally, I use the IDE (integrated development environment for writing and running python code) called “IDLE” at Step 8."
},
{
"code": null,
"e": 9819,
"s": 9631,
"text": "In the “Advanced Options” (shown at Fig 20 below), I chose the installation of Python for all users (which was not ticked by default); this gives the more useful system wide installation."
},
{
"code": null,
"e": 10117,
"s": 9819,
"text": "Tensorflow provides instructions for checking that CUDA, cuDNN and (optional: CUPTI) installation directories are correctly added to the PATH environmental variables. As the three cuDNN files were copied into the subfolders of CUDA, I did not update the existing CUDA environmental variables path."
},
{
"code": null,
"e": 10184,
"s": 10117,
"text": "Step 7.1: Calling up the command prompt with administration rights"
},
{
"code": null,
"e": 10428,
"s": 10184,
"text": "In this step a system-wide install of Tensorflow is carried out, not a per user install. System wide installation of Tensorflow requires administrative rights, therefore, accordingly the command prompt should be run with administrative rights."
},
{
"code": null,
"e": 10631,
"s": 10428,
"text": "Open up the command prompt by running ‘cmd’ in the search bar, and then right clicking on command prompt to choose ‘run as administrator’. This opens up Administrator: Command Prompt as shown in Fig 21."
},
{
"code": null,
"e": 10690,
"s": 10631,
"text": "Step 7.2: System wide install of Tensorflow via python pip"
},
{
"code": null,
"e": 10808,
"s": 10690,
"text": "Having opened the Command Prompt, the system-wide installation command for Tensorflow with GPU support is as follows:"
},
{
"code": null,
"e": 10846,
"s": 10808,
"text": "pip3 install --upgrade tensorflow-gpu"
},
{
"code": null,
"e": 11003,
"s": 10846,
"text": "The “pip3” command (as opposed to “pip”) is required as the installation is to Python 3. Execution of this command in the command prompt is shown in Fig 22."
},
{
"code": null,
"e": 11182,
"s": 11003,
"text": "The resulting output from the command is shown in Fig 23, and if all goes to plan there should eventually be a message to confirm that Tensorflow has been installed successfully."
},
{
"code": null,
"e": 11626,
"s": 11182,
"text": "Go to the start menu in windows and search for the IDE called ‘idle’, which will be installed as part of your python installation if you selected as I did at Step 6. A Python window should appear labelled Python 3.6.x Shell. At the prompt (denoted by ‘>>>’), import the Tensorflow package. This will check that Tensorflow has been installed (as you can import it). The command for the IDLE shell to import the tensorflow package is as follows:"
},
{
"code": null,
"e": 11685,
"s": 11626,
"text": "# importing the tensorflow packageimport tensorflow as tf "
},
{
"code": null,
"e": 11788,
"s": 11685,
"text": "To test CUDA support for your Tensorflow installation, you can run the following command in the shell:"
},
{
"code": null,
"e": 11817,
"s": 11788,
"text": "tf.test.is_built_with_cuda()"
},
{
"code": null,
"e": 11954,
"s": 11817,
"text": "Finally, to confirm that the GPU is available to Tensorflow, you can test using a built-in utility function in TensorFlow as shown here:"
},
{
"code": null,
"e": 12030,
"s": 11954,
"text": "tf.test.is_gpu_available(cuda_only=False, min_cuda_compute_capability=None)"
},
{
"code": null,
"e": 12247,
"s": 12030,
"text": "It takes a few minutes to return a result from this; when it is finished it returns True, and then the prompt `>>>`appears again. Importing tensorflow and these tests are all shown in Fig 24 in the Python IDLE Shell."
},
{
"code": null,
"e": 12609,
"s": 12247,
"text": "These were the steps I took to install Visual Studio, CUDA Toolkit, CuDNN and Python 3.6, all with the ultimate aim of installing Tensorflow with GPU support on Windows 10. To date, my GPU based machine learning and deep learning work has been on Linux Ubuntu machines; by the same token, much of the machine learning community support online focuses on Ubuntu."
},
{
"code": null,
"e": 13125,
"s": 12609,
"text": "For Machine Learning, the major drawback to using Windows is that it is necessary to build more things from source (for example using Cmake) than on Linux, and also to install additional software for the build processes, such as Visual Studio. For example, if you were to install Caffe2 on Windows, there are no pre-built binaries and Windows build is in testing and beta mode. I installed CUDA and cuDNN on Windows 10 more out of curiosity than anything else, just to see how straightforward (or otherwise) it was."
},
{
"code": null,
"e": 13471,
"s": 13125,
"text": "As I intimated in Part 1, now that CUDA, cuDNN and Tensorflow are successfully installed on Windows 10 and I have checked Tensorflow’s access to GPU, I am going to sweep the whole Windows 10 operating system away in order to make a fresh installation of Ubuntu 18.04 LTS. This new installation of Ubuntu will be covered in Part 3 of this series."
}
] |
Explain asynchronous functions in JavaScript with an example
|
The asynchronous functions are defined with async keyword and were introduced in ES 2015. These functions were introduced to define a better way to write consice promises than callback. The await keyword is used inside an async function to pause the flow of control
and it waits for promise.
Following is the code for asynchronous functions in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
color: blueviolet;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Asynchronous functions in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the function asyncFunc</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
function displayText() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Hello World");
}, 1500);
});
}
async function asyncFunc() {
resEle.innerHTML = await displayText();
}
BtnEle.addEventListener("click", () => {
asyncFunc();
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button and waiting for 2 seconds −
|
[
{
"code": null,
"e": 1354,
"s": 1062,
"text": "The asynchronous functions are defined with async keyword and were introduced in ES 2015. These functions were introduced to define a better way to write consice promises than callback. The await keyword is used inside an async function to pause the flow of control\nand it waits for promise."
},
{
"code": null,
"e": 1419,
"s": 1354,
"text": "Following is the code for asynchronous functions in JavaScript −"
},
{
"code": null,
"e": 1430,
"s": 1419,
"text": " Live Demo"
},
{
"code": null,
"e": 2429,
"s": 1430,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n color: blueviolet;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Asynchronous functions in JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to call the function asyncFunc</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n function displayText() {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(\"Hello World\");\n }, 1500);\n });\n }\n async function asyncFunc() {\n resEle.innerHTML = await displayText();\n }\n BtnEle.addEventListener(\"click\", () => {\n asyncFunc();\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2493,
"s": 2429,
"text": "On clicking the ‘CLICK HERE’ button and waiting for 2 seconds −"
}
] |
Highcharts - Configuration Syntax
|
In this chapter, we will showcase the configuration required to draw a chart using the Highcharts API.
Create an HTML page with the jQuery and Highcharts javascript libraries.
HighchartsTestHarness.htm
<html>
<head>
<title>Highcharts Tutorial</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
<script language = "JavaScript">
$(document).ready(function() {
});
</script>
</body>
</html>
Here the container div is used to contain the chart drawn using Highcharts library.
Highcharts library uses very simple configurations using json syntax.
$('#container').highcharts(json);
Here json represents the json data and configuration which the Highcharts library uses to draw a chart within the container div using the highcharts() method. Now, we will configure the various parameters to create the required json string.
Configure the title of the chart.
var title = {
text: 'Monthly Average Temperature'
};
Configure the subtitle of the chart.
var subtitle = {
text: 'Source: WorldClimate.com'
};
Configure the ticker to be displayed on the X-Axis.
var xAxis = {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'
,'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};
Configure the title, plot lines to be displayed on the Y-Axis.
var yAxis = {
title: {
text: 'Temperature (\xB0C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
};
Configure the tooltip. Put suffix to be added after value (y-axis).
var tooltip = {
valueSuffix: '\xB0C'
}
Configure the legend to be displayed on the right side of the chart along with other properties.
var legend = {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
};
Configure the data to be displayed on the chart. Series is an array where each element of this array represents a single line on the chart.
var series = [
{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
},
{
name: 'New York',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
},
{
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
},
{
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}
];
Combine all the configurations.
var json = {};
json.title = title;
json.subtitle = subtitle;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.tooltip = tooltip;
json.legend = legend;
json.series = series;
$('#container').highcharts(json);
Consider the following example to further understand the Configuration Syntax −
highcharts_configuration.htm
<html>
<head>
<title>Highcharts Tutorial</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
<script language = "JavaScript">
$(document).ready(function() {
var title = {
text: 'Monthly Average Temperature'
};
var subtitle = {
text: 'Source: WorldClimate.com'
};
var xAxis = {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};
var yAxis = {
title: {
text: 'Temperature (\xB0C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
};
var tooltip = {
valueSuffix: '\xB0C'
}
var legend = {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
};
var series = [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,
26.5, 23.3, 18.3, 13.9, 9.6]
},
{
name: 'New York',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8,
24.1, 20.1, 14.1, 8.6, 2.5]
},
{
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6,
17.9, 14.3, 9.0, 3.9, 1.0]
},
{
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0,
16.6, 14.2, 10.3, 6.6, 4.8]
}
];
var json = {};
json.title = title;
json.subtitle = subtitle;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.tooltip = tooltip;
json.legend = legend;
json.series = series;
$('#container').highcharts(json);
});
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2120,
"s": 2017,
"text": "In this chapter, we will showcase the configuration required to draw a chart using the Highcharts API."
},
{
"code": null,
"e": 2193,
"s": 2120,
"text": "Create an HTML page with the jQuery and Highcharts javascript libraries."
},
{
"code": null,
"e": 2219,
"s": 2193,
"text": "HighchartsTestHarness.htm"
},
{
"code": null,
"e": 2710,
"s": 2219,
"text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n \n <script language = \"JavaScript\">\n $(document).ready(function() {\n });\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 2794,
"s": 2710,
"text": "Here the container div is used to contain the chart drawn using Highcharts library."
},
{
"code": null,
"e": 2864,
"s": 2794,
"text": "Highcharts library uses very simple configurations using json syntax."
},
{
"code": null,
"e": 2899,
"s": 2864,
"text": "$('#container').highcharts(json);\n"
},
{
"code": null,
"e": 3140,
"s": 2899,
"text": "Here json represents the json data and configuration which the Highcharts library uses to draw a chart within the container div using the highcharts() method. Now, we will configure the various parameters to create the required json string."
},
{
"code": null,
"e": 3174,
"s": 3140,
"text": "Configure the title of the chart."
},
{
"code": null,
"e": 3233,
"s": 3174,
"text": "var title = {\n text: 'Monthly Average Temperature' \n};"
},
{
"code": null,
"e": 3270,
"s": 3233,
"text": "Configure the subtitle of the chart."
},
{
"code": null,
"e": 3326,
"s": 3270,
"text": "var subtitle = {\n text: 'Source: WorldClimate.com'\n};"
},
{
"code": null,
"e": 3378,
"s": 3326,
"text": "Configure the ticker to be displayed on the X-Axis."
},
{
"code": null,
"e": 3501,
"s": 3378,
"text": "var xAxis = {\n categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'\n ,'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n};"
},
{
"code": null,
"e": 3564,
"s": 3501,
"text": "Configure the title, plot lines to be displayed on the Y-Axis."
},
{
"code": null,
"e": 3713,
"s": 3564,
"text": "var yAxis = {\n title: {\n text: 'Temperature (\\xB0C)'\n },\n plotLines: [{\n value: 0,\n width: 1,\n color: '#808080'\n }]\n}; "
},
{
"code": null,
"e": 3781,
"s": 3713,
"text": "Configure the tooltip. Put suffix to be added after value (y-axis)."
},
{
"code": null,
"e": 3823,
"s": 3781,
"text": "var tooltip = {\n valueSuffix: '\\xB0C'\n}"
},
{
"code": null,
"e": 3920,
"s": 3823,
"text": "Configure the legend to be displayed on the right side of the chart along with other properties."
},
{
"code": null,
"e": 4026,
"s": 3920,
"text": "var legend = {\n layout: 'vertical',\n align: 'right',\n verticalAlign: 'middle',\n borderWidth: 0\n};"
},
{
"code": null,
"e": 4166,
"s": 4026,
"text": "Configure the data to be displayed on the chart. Series is an array where each element of this array represents a single line on the chart."
},
{
"code": null,
"e": 4639,
"s": 4166,
"text": "var series = [\n {\n name: 'Tokyo',\n data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]\n }, \n {\n name: 'New York',\n data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]\n }, \n {\n name: 'Berlin',\n data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]\n }, \n {\n name: 'London',\n data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]\n }\n];"
},
{
"code": null,
"e": 4671,
"s": 4639,
"text": "Combine all the configurations."
},
{
"code": null,
"e": 4841,
"s": 4671,
"text": "var json = {};\n\njson.title = title;\njson.subtitle = subtitle;\njson.xAxis = xAxis;\njson.yAxis = yAxis;\njson.tooltip = tooltip;\njson.legend = legend;\njson.series = series;"
},
{
"code": null,
"e": 4875,
"s": 4841,
"text": "$('#container').highcharts(json);"
},
{
"code": null,
"e": 4955,
"s": 4875,
"text": "Consider the following example to further understand the Configuration Syntax −"
},
{
"code": null,
"e": 4984,
"s": 4955,
"text": "highcharts_configuration.htm"
},
{
"code": null,
"e": 7424,
"s": 4984,
"text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() {\n var title = {\n text: 'Monthly Average Temperature' \n };\n var subtitle = {\n text: 'Source: WorldClimate.com'\n };\n var xAxis = {\n categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n };\n var yAxis = {\n title: {\n text: 'Temperature (\\xB0C)'\n },\n plotLines: [{\n value: 0,\n width: 1,\n color: '#808080'\n }]\n }; \n\n var tooltip = {\n valueSuffix: '\\xB0C'\n }\n var legend = {\n layout: 'vertical',\n align: 'right',\n verticalAlign: 'middle',\n borderWidth: 0\n };\n var series = [{\n name: 'Tokyo',\n data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,\n 26.5, 23.3, 18.3, 13.9, 9.6]\n }, \n {\n name: 'New York',\n data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, \n 24.1, 20.1, 14.1, 8.6, 2.5]\n }, \n {\n name: 'Berlin',\n data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6,\n 17.9, 14.3, 9.0, 3.9, 1.0]\n }, \n {\n name: 'London',\n data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, \n 16.6, 14.2, 10.3, 6.6, 4.8]\n }\n ];\n\n var json = {};\n json.title = title;\n json.subtitle = subtitle;\n json.xAxis = xAxis;\n json.yAxis = yAxis;\n json.tooltip = tooltip;\n json.legend = legend;\n json.series = series;\n\n $('#container').highcharts(json);\n });\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 7443,
"s": 7424,
"text": "Verify the result."
},
{
"code": null,
"e": 7450,
"s": 7443,
"text": " Print"
},
{
"code": null,
"e": 7461,
"s": 7450,
"text": " Add Notes"
}
] |
SymPy - Solvers
|
Since the symbols = and == are defined as assignment and equality operators in Python, they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set up an equation.
>>> from sympy import *
>>> x,y=symbols('x y')
>>> Eq(x,y)
The above code snippet gives an output equivalent to the below expression −
x = y
Since x=y is possible if and only if x-y=0, above equation can be written as −
>>> Eq(x-y,0)
The above code snippet gives an output equivalent to the below expression −
x − y = 0
The solver module in SymPy provides soveset() function whose prototype is as follows −
solveset(equation, variable, domain)
The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic equation as follows −
>>> solveset(Eq(x**2-9,0), x)
The following output is obtained −
{−3, 3}
>>> solveset(Eq(x**2-3*x, -2),x)
The following output is obtained after executing the above code snippet −
{1,2}
The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet is returned
>>> solveset(exp(x),x)
The following output is obtained after executing the above code snippet −
∅
We have to use linsolve() function to solve linear equations.
For example, the equations are as follows −
x-y=4
x+y=1
>>> from sympy import *
>>> x,y=symbols('x y')
>>> linsolve([Eq(x-y,4),Eq( x + y ,1) ], (x, y))
The following output is obtained after executing the above code snippet −
{(52,−32)}
The linsolve() function can also solve linear equations expressed in matrix form.
>>> a,b=symbols('a b')
>>> a=Matrix([[1,-1],[1,1]])
>>> b=Matrix([4,1])
>>> linsolve([a,b], (x,y))
We get the following output if we execute the above code snippet −
{(52,−32)}
For this purpose, we use nonlinsolve() function. Equations for this example −
a2+a=0 a-b=0
>>> a,b=symbols('a b')
>>> nonlinsolve([a**2 + a, a - b], [a, b])
We get the following output if we execute the above code snippet −
{(−1,−1),(0,0)}
First, create an undefined function by passing cls=Function to the symbols function. To solve differential equations, use dsolve.
>>> x=Symbol('x')
>>> f=symbols('f', cls=Function)
>>> f(x)
The following output is obtained after executing the above code snippet −
f(x)
Here f(x) is an unevaluated function. Its derivative is as follows −
>>> f(x).diff(x)
The above code snippet gives an output equivalent to the below expression −
ddxf(x)
We first create Eq object corresponding to following differential equation
>>> eqn=Eq(f(x).diff(x)-f(x), sin(x))
>>> eqn
The above code snippet gives an output equivalent to the below expression −
−f(x)+ddxf(x)=sin(x)
>>> dsolve(eqn, f(x))
The above code snippet gives an output equivalent to the below expression −
f(x)=(c1−e−xsin(x)2−e−xcos(x)2)ex
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2211,
"s": 2019,
"text": "Since the symbols = and == are defined as assignment and equality operators in Python, they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set up an equation."
},
{
"code": null,
"e": 2273,
"s": 2211,
"text": ">>> from sympy import * \n>>> x,y=symbols('x y') \n>>> Eq(x,y)\n"
},
{
"code": null,
"e": 2349,
"s": 2273,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 2355,
"s": 2349,
"text": "x = y"
},
{
"code": null,
"e": 2434,
"s": 2355,
"text": "Since x=y is possible if and only if x-y=0, above equation can be written as −"
},
{
"code": null,
"e": 2449,
"s": 2434,
"text": ">>> Eq(x-y,0)\n"
},
{
"code": null,
"e": 2525,
"s": 2449,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 2535,
"s": 2525,
"text": "x − y = 0"
},
{
"code": null,
"e": 2622,
"s": 2535,
"text": "The solver module in SymPy provides soveset() function whose prototype is as follows −"
},
{
"code": null,
"e": 2660,
"s": 2622,
"text": "solveset(equation, variable, domain)\n"
},
{
"code": null,
"e": 2773,
"s": 2660,
"text": "The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic equation as follows −"
},
{
"code": null,
"e": 2804,
"s": 2773,
"text": ">>> solveset(Eq(x**2-9,0), x)\n"
},
{
"code": null,
"e": 2839,
"s": 2804,
"text": "The following output is obtained −"
},
{
"code": null,
"e": 2847,
"s": 2839,
"text": "{−3, 3}"
},
{
"code": null,
"e": 2881,
"s": 2847,
"text": ">>> solveset(Eq(x**2-3*x, -2),x)\n"
},
{
"code": null,
"e": 2955,
"s": 2881,
"text": "The following output is obtained after executing the above code snippet −"
},
{
"code": null,
"e": 2961,
"s": 2955,
"text": "{1,2}"
},
{
"code": null,
"e": 3068,
"s": 2961,
"text": "The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet is returned"
},
{
"code": null,
"e": 3092,
"s": 3068,
"text": ">>> solveset(exp(x),x)\n"
},
{
"code": null,
"e": 3166,
"s": 3092,
"text": "The following output is obtained after executing the above code snippet −"
},
{
"code": null,
"e": 3168,
"s": 3166,
"text": "∅"
},
{
"code": null,
"e": 3230,
"s": 3168,
"text": "We have to use linsolve() function to solve linear equations."
},
{
"code": null,
"e": 3274,
"s": 3230,
"text": "For example, the equations are as follows −"
},
{
"code": null,
"e": 3280,
"s": 3274,
"text": "x-y=4"
},
{
"code": null,
"e": 3286,
"s": 3280,
"text": "x+y=1"
},
{
"code": null,
"e": 3385,
"s": 3286,
"text": ">>> from sympy import * \n>>> x,y=symbols('x y') \n>>> linsolve([Eq(x-y,4),Eq( x + y ,1) ], (x, y))\n"
},
{
"code": null,
"e": 3459,
"s": 3385,
"text": "The following output is obtained after executing the above code snippet −"
},
{
"code": null,
"e": 3470,
"s": 3459,
"text": "{(52,−32)}"
},
{
"code": null,
"e": 3552,
"s": 3470,
"text": "The linsolve() function can also solve linear equations expressed in matrix form."
},
{
"code": null,
"e": 3655,
"s": 3552,
"text": ">>> a,b=symbols('a b') \n>>> a=Matrix([[1,-1],[1,1]]) \n>>> b=Matrix([4,1]) \n>>> linsolve([a,b], (x,y))\n"
},
{
"code": null,
"e": 3722,
"s": 3655,
"text": "We get the following output if we execute the above code snippet −"
},
{
"code": null,
"e": 3733,
"s": 3722,
"text": "{(52,−32)}"
},
{
"code": null,
"e": 3811,
"s": 3733,
"text": "For this purpose, we use nonlinsolve() function. Equations for this example −"
},
{
"code": null,
"e": 3824,
"s": 3811,
"text": "a2+a=0 a-b=0"
},
{
"code": null,
"e": 3892,
"s": 3824,
"text": ">>> a,b=symbols('a b') \n>>> nonlinsolve([a**2 + a, a - b], [a, b])\n"
},
{
"code": null,
"e": 3959,
"s": 3892,
"text": "We get the following output if we execute the above code snippet −"
},
{
"code": null,
"e": 3975,
"s": 3959,
"text": "{(−1,−1),(0,0)}"
},
{
"code": null,
"e": 4105,
"s": 3975,
"text": "First, create an undefined function by passing cls=Function to the symbols function. To solve differential equations, use dsolve."
},
{
"code": null,
"e": 4168,
"s": 4105,
"text": ">>> x=Symbol('x') \n>>> f=symbols('f', cls=Function) \n>>> f(x)\n"
},
{
"code": null,
"e": 4242,
"s": 4168,
"text": "The following output is obtained after executing the above code snippet −"
},
{
"code": null,
"e": 4247,
"s": 4242,
"text": "f(x)"
},
{
"code": null,
"e": 4316,
"s": 4247,
"text": "Here f(x) is an unevaluated function. Its derivative is as follows −"
},
{
"code": null,
"e": 4334,
"s": 4316,
"text": ">>> f(x).diff(x)\n"
},
{
"code": null,
"e": 4410,
"s": 4334,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 4418,
"s": 4410,
"text": "ddxf(x)"
},
{
"code": null,
"e": 4493,
"s": 4418,
"text": "We first create Eq object corresponding to following differential equation"
},
{
"code": null,
"e": 4541,
"s": 4493,
"text": ">>> eqn=Eq(f(x).diff(x)-f(x), sin(x)) \n>>> eqn\n"
},
{
"code": null,
"e": 4617,
"s": 4541,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 4639,
"s": 4617,
"text": "−f(x)+ddxf(x)=sin(x)"
},
{
"code": null,
"e": 4662,
"s": 4639,
"text": ">>> dsolve(eqn, f(x))\n"
},
{
"code": null,
"e": 4738,
"s": 4662,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 4772,
"s": 4738,
"text": "f(x)=(c1−e−xsin(x)2−e−xcos(x)2)ex"
},
{
"code": null,
"e": 4779,
"s": 4772,
"text": " Print"
},
{
"code": null,
"e": 4790,
"s": 4779,
"text": " Add Notes"
}
] |
Concurrency and Parallelism in Python | by Anna Astori | Towards Data Science
|
If you’re about to start a big data project you will be either retrieving a lot of information or crunching big numbers on your machine, or both. However, if the code is sequential or synchronous your application may start struggling.
Let’s see which concepts and Python libraries can improve your application’s performance in each case.
There are two dimensions along which you can speed your program — I/O and CPU consumption. If your code does, for instance, a lot of file accessing or communication over the network, it’s I/O-bound. CPU-bound code involves heavy computation. For example, training a statistical model is definitely a compute-intensive job.
How do both types of work differ regarding the resources they require?
When the I/O-bound code sends multiple requests, it doesn’t really utilize the machine’s CPU cores that much since essentially, it’s idly waiting for the responses. Hence, such applications can’t improve their performance by having more compute power added. It’s more about the wait time between the request and response.
It’s the opposite for the CPU-bound pieces of code.
The two mechanisms to alleviate either type of bottlenecks are concurrency and parallelism respectively.
Generally, concurrency is considered to be a larger concept than parallelism. Simply put, it’s doing multiple things at the same time. In practice, there is a particular angle to the distinction between the two ideas, especially in Python. Concurrency is then often understood as “managing” multiple jobs simultaneously. In actuality, those jobs don’t really execute all at the same time. They cleverly alternate.
The parallel execution, however, does mean executing multiple jobs simultaneously, or in parallel. The parallelism allows to leverage multiple cores on a single machine.
In Python, concurrency is represented by threading and asyncio, whereas parallelism is achieved with multiprocessing.
With threading, you create multiple threads across which you distribute some I/O-bound workload. For example, if you have a simple function to download some files download_file(f), you can use the ThreadPoolExecutor to spin up the threads and map the function calls to each argument file from a list of files:
with ThreadPoolExecutor() as executor: executor.map(download_file, files)
Something that is worth mentioning here is that threading in Python doesn’t work quite the same way as it does in other languages like Java— CPython’s Global Interpreter Lock (GIL) actually ensures that memory usage is thread-safe and so only one thread can be processed at a time (see more in threading documentation). So it’s really a concurrent mechanism as defined above.
With asyncio, you create tasks for similar purposes:
tasks = [asyncio.create_task(download_file(f)) for f in files]
But the idea behind the asyncio’s tasks is different from the threads. In fact, tasks run on a single thread. However, each task allows the OS to run another task if the first one is waiting for its response instead of blocking it. That’s the essence of the asynchronous IO. (A more thorough walk-through for an asynchronous program in a later article).
Most often, you’ll also want to create a special event loop object to manage the tasks in your main function.
The asyncio module can improve performance even more considerably for I/O-bound programs because there is less overhead with creating and managing tasks than with threads.
The threading approach can be deemed more dangerous because the switching between the threads can happen at any time, even in the middle of a statement execution due to the pre-emptive multitasking, whereas asyncio tasks signal themselves when they are ready to switch over —a mechanism that is known as cooperative multitasking. If an issues occurs at that time, it can be more difficult to trace it with the threading approach.
However, using the asyncio module involves writing a fair amount of code to just accommodate it.
Both approaches above work well for speeding up I/O-bound programs. As for the CPU-bound programs, it’s multiprocessing that will really help.
The multiprocessing module creates a Python interpreter for each process. It actually leverages the number of CPU cores on your machine. A typical example of a CPU-bound piece of code is compressing files. So if you have a function compress_file(f), the syntax for spinning up new processes and distributing the workload across them will look similar to the threading example:
with ProcessPoolExecutor() as executor: executor.map(compress_file, files)
If multiprocessing is so amazing, why not use it all the time?
There are a couple of tricky things about writing code with multiprocessing. First, you need to be able to establish if some data might actually need to be accessed by all processes — because the memory between the processes is not shared. Also, it can sometimes be difficult to figure out which parts of the program can be cleanly split up into separate processes.
Finally, you should carefully evaluate the trade-offs between the performance gain thanks to multiprocessing and its cost in your case. If the computation in fact is not all that intensive, multiprocessing might not speed things up that much because of the significant overhead associated with spinning up interpreters for each process.
What are the results of your experiments with these modules? Any interesting observation about their behavior in different setups?
If you are interested in articles on Python, feel free to check out my post on new features in Python 3.9 and Python code optimization!
|
[
{
"code": null,
"e": 407,
"s": 172,
"text": "If you’re about to start a big data project you will be either retrieving a lot of information or crunching big numbers on your machine, or both. However, if the code is sequential or synchronous your application may start struggling."
},
{
"code": null,
"e": 510,
"s": 407,
"text": "Let’s see which concepts and Python libraries can improve your application’s performance in each case."
},
{
"code": null,
"e": 833,
"s": 510,
"text": "There are two dimensions along which you can speed your program — I/O and CPU consumption. If your code does, for instance, a lot of file accessing or communication over the network, it’s I/O-bound. CPU-bound code involves heavy computation. For example, training a statistical model is definitely a compute-intensive job."
},
{
"code": null,
"e": 904,
"s": 833,
"text": "How do both types of work differ regarding the resources they require?"
},
{
"code": null,
"e": 1226,
"s": 904,
"text": "When the I/O-bound code sends multiple requests, it doesn’t really utilize the machine’s CPU cores that much since essentially, it’s idly waiting for the responses. Hence, such applications can’t improve their performance by having more compute power added. It’s more about the wait time between the request and response."
},
{
"code": null,
"e": 1278,
"s": 1226,
"text": "It’s the opposite for the CPU-bound pieces of code."
},
{
"code": null,
"e": 1383,
"s": 1278,
"text": "The two mechanisms to alleviate either type of bottlenecks are concurrency and parallelism respectively."
},
{
"code": null,
"e": 1797,
"s": 1383,
"text": "Generally, concurrency is considered to be a larger concept than parallelism. Simply put, it’s doing multiple things at the same time. In practice, there is a particular angle to the distinction between the two ideas, especially in Python. Concurrency is then often understood as “managing” multiple jobs simultaneously. In actuality, those jobs don’t really execute all at the same time. They cleverly alternate."
},
{
"code": null,
"e": 1967,
"s": 1797,
"text": "The parallel execution, however, does mean executing multiple jobs simultaneously, or in parallel. The parallelism allows to leverage multiple cores on a single machine."
},
{
"code": null,
"e": 2085,
"s": 1967,
"text": "In Python, concurrency is represented by threading and asyncio, whereas parallelism is achieved with multiprocessing."
},
{
"code": null,
"e": 2395,
"s": 2085,
"text": "With threading, you create multiple threads across which you distribute some I/O-bound workload. For example, if you have a simple function to download some files download_file(f), you can use the ThreadPoolExecutor to spin up the threads and map the function calls to each argument file from a list of files:"
},
{
"code": null,
"e": 2472,
"s": 2395,
"text": "with ThreadPoolExecutor() as executor: executor.map(download_file, files)"
},
{
"code": null,
"e": 2848,
"s": 2472,
"text": "Something that is worth mentioning here is that threading in Python doesn’t work quite the same way as it does in other languages like Java— CPython’s Global Interpreter Lock (GIL) actually ensures that memory usage is thread-safe and so only one thread can be processed at a time (see more in threading documentation). So it’s really a concurrent mechanism as defined above."
},
{
"code": null,
"e": 2901,
"s": 2848,
"text": "With asyncio, you create tasks for similar purposes:"
},
{
"code": null,
"e": 2964,
"s": 2901,
"text": "tasks = [asyncio.create_task(download_file(f)) for f in files]"
},
{
"code": null,
"e": 3318,
"s": 2964,
"text": "But the idea behind the asyncio’s tasks is different from the threads. In fact, tasks run on a single thread. However, each task allows the OS to run another task if the first one is waiting for its response instead of blocking it. That’s the essence of the asynchronous IO. (A more thorough walk-through for an asynchronous program in a later article)."
},
{
"code": null,
"e": 3428,
"s": 3318,
"text": "Most often, you’ll also want to create a special event loop object to manage the tasks in your main function."
},
{
"code": null,
"e": 3600,
"s": 3428,
"text": "The asyncio module can improve performance even more considerably for I/O-bound programs because there is less overhead with creating and managing tasks than with threads."
},
{
"code": null,
"e": 4030,
"s": 3600,
"text": "The threading approach can be deemed more dangerous because the switching between the threads can happen at any time, even in the middle of a statement execution due to the pre-emptive multitasking, whereas asyncio tasks signal themselves when they are ready to switch over —a mechanism that is known as cooperative multitasking. If an issues occurs at that time, it can be more difficult to trace it with the threading approach."
},
{
"code": null,
"e": 4127,
"s": 4030,
"text": "However, using the asyncio module involves writing a fair amount of code to just accommodate it."
},
{
"code": null,
"e": 4270,
"s": 4127,
"text": "Both approaches above work well for speeding up I/O-bound programs. As for the CPU-bound programs, it’s multiprocessing that will really help."
},
{
"code": null,
"e": 4647,
"s": 4270,
"text": "The multiprocessing module creates a Python interpreter for each process. It actually leverages the number of CPU cores on your machine. A typical example of a CPU-bound piece of code is compressing files. So if you have a function compress_file(f), the syntax for spinning up new processes and distributing the workload across them will look similar to the threading example:"
},
{
"code": null,
"e": 4725,
"s": 4647,
"text": "with ProcessPoolExecutor() as executor: executor.map(compress_file, files)"
},
{
"code": null,
"e": 4788,
"s": 4725,
"text": "If multiprocessing is so amazing, why not use it all the time?"
},
{
"code": null,
"e": 5154,
"s": 4788,
"text": "There are a couple of tricky things about writing code with multiprocessing. First, you need to be able to establish if some data might actually need to be accessed by all processes — because the memory between the processes is not shared. Also, it can sometimes be difficult to figure out which parts of the program can be cleanly split up into separate processes."
},
{
"code": null,
"e": 5491,
"s": 5154,
"text": "Finally, you should carefully evaluate the trade-offs between the performance gain thanks to multiprocessing and its cost in your case. If the computation in fact is not all that intensive, multiprocessing might not speed things up that much because of the significant overhead associated with spinning up interpreters for each process."
},
{
"code": null,
"e": 5622,
"s": 5491,
"text": "What are the results of your experiments with these modules? Any interesting observation about their behavior in different setups?"
}
] |
Python SQLite - Delete Data
|
To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it.
Following is the syntax of the DELETE query in SQLite −
DELETE FROM table_name [WHERE Clause]
Assume we have created a table with name CRICKETERS using the following query −
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
And if we have inserted 5 records in to it using INSERT statements as −
sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>
Following statement deletes the record of the cricketer whose last name is 'Sangakkara'.
sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';
sqlite>
If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one.
sqlite> SELECT * FROM CRICKETERS;
First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- --------
Shikhar Dhawan 46 Delhi India
Jonathan Trott 39 CapeTown SouthAfrica
Virat Kohli 31 Delhi India
Rohit Sharma 33 Nagpur India
sqlite>
If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted.
sqlite> DELETE FROM CRICKETERS;
sqlite>
Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −
sqlite> SELECT * FROM CRICKETERS;
sqlite>
To add records to an existing table in SQLite database −
Import sqlite3 package.
Import sqlite3 package.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object.
The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object.
Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it.
Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it.
Following python example deletes the records from EMPLOYEE table with age value greater than 25.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving contents of the table
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())
#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')
#Retrieving data after delete
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
Contents of the table:
[
('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
Contents of the table after delete operation
[
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2136,
"s": 1982,
"text": "To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it."
},
{
"code": null,
"e": 2192,
"s": 2136,
"text": "Following is the syntax of the DELETE query in SQLite −"
},
{
"code": null,
"e": 2231,
"s": 2192,
"text": "DELETE FROM table_name [WHERE Clause]\n"
},
{
"code": null,
"e": 2311,
"s": 2231,
"text": "Assume we have created a table with name CRICKETERS using the following query −"
},
{
"code": null,
"e": 2479,
"s": 2311,
"text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>"
},
{
"code": null,
"e": 2551,
"s": 2479,
"text": "And if we have inserted 5 records in to it using INSERT statements as −"
},
{
"code": null,
"e": 2981,
"s": 2551,
"text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>"
},
{
"code": null,
"e": 3070,
"s": 2981,
"text": "Following statement deletes the record of the cricketer whose last name is 'Sangakkara'."
},
{
"code": null,
"e": 3142,
"s": 3070,
"text": "sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';\nsqlite>\n"
},
{
"code": null,
"e": 3266,
"s": 3142,
"text": "If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one."
},
{
"code": null,
"e": 3632,
"s": 3266,
"text": "sqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- --------\nShikhar Dhawan 46 Delhi India\nJonathan Trott 39 CapeTown SouthAfrica\nVirat Kohli 31 Delhi India\nRohit Sharma 33 Nagpur India\nsqlite>\n"
},
{
"code": null,
"e": 3757,
"s": 3632,
"text": "If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted."
},
{
"code": null,
"e": 3798,
"s": 3757,
"text": "sqlite> DELETE FROM CRICKETERS;\nsqlite>\n"
},
{
"code": null,
"e": 3972,
"s": 3798,
"text": "Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −"
},
{
"code": null,
"e": 4015,
"s": 3972,
"text": "sqlite> SELECT * FROM CRICKETERS;\nsqlite>\n"
},
{
"code": null,
"e": 4072,
"s": 4015,
"text": "To add records to an existing table in SQLite database −"
},
{
"code": null,
"e": 4096,
"s": 4072,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 4120,
"s": 4096,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 4232,
"s": 4120,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 4344,
"s": 4232,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 4531,
"s": 4344,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 4718,
"s": 4531,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 4827,
"s": 4718,
"text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it."
},
{
"code": null,
"e": 4936,
"s": 4827,
"text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it."
},
{
"code": null,
"e": 5033,
"s": 4936,
"text": "Following python example deletes the records from EMPLOYEE table with age value greater than 25."
},
{
"code": null,
"e": 5640,
"s": 5033,
"text": "import sqlite3\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving contents of the table\nprint(\"Contents of the table: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Deleting records\ncursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')\n\n#Retrieving data after delete\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 6030,
"s": 5640,
"text": "Contents of the table:\n[\n ('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)\n]\nContents of the table after delete operation\n[\n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)\n]\n"
},
{
"code": null,
"e": 6067,
"s": 6030,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6083,
"s": 6067,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6116,
"s": 6083,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6135,
"s": 6116,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6170,
"s": 6135,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6192,
"s": 6170,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6226,
"s": 6192,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6254,
"s": 6226,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6289,
"s": 6254,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6303,
"s": 6289,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6336,
"s": 6303,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6353,
"s": 6336,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6360,
"s": 6353,
"text": " Print"
},
{
"code": null,
"e": 6371,
"s": 6360,
"text": " Add Notes"
}
] |
Lexicographically next permutation in C++
|
Here we will see how to generate lexicographically next permutation of a string in C++. The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc.
In C++ we can do it by using a library function called next_permutation(). This is present in the algorithm header file.
#include <iostream>
#include <algorithm>
using namespace std;
main() {
string s = "DBAC";
for(int i = 0; i<5; i++) {
bool val = next_permutation(s.begin(), s.end());
if (val == false) {
cout << "No next permutation" << endl;
break;
} else
cout << "Next: " << s << endl;
}
}
Next: DBCA
Next: DCAB
Next: DCBA
No next permutation
|
[
{
"code": null,
"e": 1369,
"s": 1062,
"text": "Here we will see how to generate lexicographically next permutation of a string in C++. The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc."
},
{
"code": null,
"e": 1490,
"s": 1369,
"text": "In C++ we can do it by using a library function called next_permutation(). This is present in the algorithm header file."
},
{
"code": null,
"e": 1815,
"s": 1490,
"text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nmain() {\n string s = \"DBAC\";\n for(int i = 0; i<5; i++) {\n bool val = next_permutation(s.begin(), s.end());\n if (val == false) {\n cout << \"No next permutation\" << endl;\n break;\n } else\n cout << \"Next: \" << s << endl;\n }\n}"
},
{
"code": null,
"e": 1868,
"s": 1815,
"text": "Next: DBCA\nNext: DCAB\nNext: DCBA\nNo next permutation"
}
] |
Recycler view item animate when scrolling in Android
|
Before getting into Item animation for recycler view example, we should know what is Recycler view in android. Recycler view is a more advanced version of the list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items.
card view is extended by frame layout and it is used to show items in card manner. It supports radius and shadow as predefined tags.
This example demonstrates how to integrate Animation in Recycler View with card view by creating a beautiful student records app that displays student name with age.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Open build.gradle and add Recycler view and card view library dependencies.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.tutorialspoint"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − 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"
xmlns:app =" http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:showIn = "@layout/activity_main"
tools:context = ".MainActivity">
<android.support.v7.widget.RecyclerView
android:id = "@+id/recycler_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:scrollbars = "vertical" />
</RelativeLayout>
In the above code we have added recycler view to window manger as relative parent layout.
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.tutorialspoint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StudentAdapter studentAdapter;
private List<studentData> studentDataList = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(studentAdapter);
StudentDataPrepare();
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void StudentDataPrepare() {
studentData data = new studentData("sai", 25);
studentDataList.add(data);
data = new studentData("sai", 25);
studentDataList.add(data);
data = new studentData("raghu", 20);
studentDataList.add(data);
data = new studentData("raj", 28);
studentDataList.add(data);
data = new studentData("amar", 15);
studentDataList.add(data);
data = new studentData("bapu", 19);
studentDataList.add(data);
data = new studentData("chandra", 52);
studentDataList.add(data);
data = new studentData("deraj", 30);
studentDataList.add(data);
data = new studentData("eshanth", 28);
studentDataList.add(data);
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
}
}
In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age.
To compare recycler view items we have used collections framework and sort method as shown below -
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
In the above code we are comparing elements by using name.
Step 5 − Following is the content of the modified file src/ StudentAdapter.java.
package com.example.andy.tutorialspoint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
class StudentAdapter extends RecyclerView.Adapter {
List studentDataList;
Context context;
private int lastPosition = -1;
public StudentAdapter(List studentDataList, Context context) {
this.studentDataList=studentDataList;
this.context=context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.student_list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
studentData data=studentDataList.get(i);
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
viewHolder.name.setText(data.name);
viewHolder.age.setText(String.valueOf(data.age));
setAnimation(viewHolder.parent, i);
}
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@Override
public int getItemCount() {
return studentDataList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,age;
LinearLayout parent;
public MyViewHolder(View itemView) {
super(itemView);
parent = itemView.findViewById(R.id.parent);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
}
}
}
In the adapter class, we have four methods as shown below -
onCreateViewHolder():- It is used to create a view holder and it returns a view.
onCreateViewHolder():- It is used to create a view holder and it returns a view.
onBindViewHolder() - it going to bind with created view holder.
onBindViewHolder() - it going to bind with created view holder.
getItemCount() - it contains size of list.
getItemCount() - it contains size of list.
MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder
MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder
To set the random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to the parent of view item as shown below -
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
In the adapter we have used setAnimation(), in that method we have passed, parent of child item and its position as shown below -
setAnimation(viewHolder.parent, i);
In the above method viewHolder.parent is linear layout in the child item layout and "i" is position of the view.
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
In the above method we are comparing current position with last position using greater than(>), than we are applying animation from AnimationUtils Class.
Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:card_view = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
card_view:cardCornerRadius = "4dp"
android:id = "@+id/card_view"
android:layout_margin = "10dp"
android:layout_height = "200dp">
<LinearLayout
android:id = "@+id/parent"
android:layout_gravity = "center"
android:layout_width = "match_parent"
android:orientation = "vertical"
android:gravity = "center"
android:layout_height = "match_parent">
<TextView
android:id = "@+id/name"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
<TextView
android:id = "@+id/age"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
In the above list item view we have created two text views for name and age inside the card view. Card view contains pre defined corner radius and shadow property. So we have used corner radius with cardview.
Step 7 − Following is the content of the modified file src/ studentData.java.
package com.example.andy.tutorialspoint;
class studentData {
String name;
int age;
public studentData(String name, int age) {
this.name = name;
this.age = age;
}
}
In the above code informs about student data object. 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 −
Now scroll down to the recyclerview, it will show the result as shown below -
Now see the last element, it is loading with animations. There are more reference samples available as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "Before getting into Item animation for recycler view example, we should know what is Recycler view in android. Recycler view is a more advanced version of the list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items."
},
{
"code": null,
"e": 1471,
"s": 1338,
"text": "card view is extended by frame layout and it is used to show items in card manner. It supports radius and shadow as predefined tags."
},
{
"code": null,
"e": 1637,
"s": 1471,
"text": "This example demonstrates how to integrate Animation in Recycler View with card view by creating a beautiful student records app that displays student name with age."
},
{
"code": null,
"e": 1766,
"s": 1637,
"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": 1851,
"s": 1766,
"text": "Step 2 − Open build.gradle and add Recycler view and card view library dependencies."
},
{
"code": null,
"e": 2950,
"s": 1851,
"text": "apply plugin: 'com.android.application'\n\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.tutorialspoint\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.android.support:cardview-v7:28.0.0'\n implementation 'com.android.support:recyclerview-v7:28.0.0'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 3015,
"s": 2950,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3704,
"s": 3015,
"text": "<?xml version = \"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n xmlns:app =\" http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"\n tools:showIn = \"@layout/activity_main\"\n tools:context = \".MainActivity\">\n\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:scrollbars = \"vertical\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3794,
"s": 3704,
"text": "In the above code we have added recycler view to window manger as relative parent layout."
},
{
"code": null,
"e": 3851,
"s": 3794,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6153,
"s": 3851,
"text": "package com.example.andy.tutorialspoint;\n\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.widget.LinearLayout;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\n\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private StudentAdapter studentAdapter;\n private List<studentData> studentDataList = new ArrayList<>();\n\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n recyclerView = findViewById(R.id.recycler_view);\n studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);\n RecyclerView.LayoutManager manager = new LinearLayoutManager(this);\n recyclerView.setLayoutManager(manager);\n recyclerView.setAdapter(studentAdapter);\n StudentDataPrepare();\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n private void StudentDataPrepare() {\n studentData data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"raghu\", 20);\n studentDataList.add(data);\n data = new studentData(\"raj\", 28);\n studentDataList.add(data);\n data = new studentData(\"amar\", 15);\n studentDataList.add(data);\n data = new studentData(\"bapu\", 19);\n studentDataList.add(data);\n data = new studentData(\"chandra\", 52);\n studentDataList.add(data);\n data = new studentData(\"deraj\", 30);\n studentDataList.add(data);\n data = new studentData(\"eshanth\", 28);\n studentDataList.add(data);\n Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n });\n }\n}"
},
{
"code": null,
"e": 6347,
"s": 6153,
"text": "In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age."
},
{
"code": null,
"e": 6446,
"s": 6347,
"text": "To compare recycler view items we have used collections framework and sort method as shown below -"
},
{
"code": null,
"e": 6618,
"s": 6446,
"text": "Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n});"
},
{
"code": null,
"e": 6677,
"s": 6618,
"text": "In the above code we are comparing elements by using name."
},
{
"code": null,
"e": 6758,
"s": 6677,
"text": "Step 5 − Following is the content of the modified file src/ StudentAdapter.java."
},
{
"code": null,
"e": 9117,
"s": 6758,
"text": "package com.example.andy.tutorialspoint;\n\nimport android.content.Context;\nimport android.graphics.Color;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.animation.AlphaAnimation;\nimport android.view.animation.Animation;\nimport android.view.animation.AnimationUtils;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport java.util.List;\nimport java.util.Random;\n\nclass StudentAdapter extends RecyclerView.Adapter {\n List studentDataList;\n Context context;\n private int lastPosition = -1;\n public StudentAdapter(List studentDataList, Context context) {\n this.studentDataList=studentDataList;\n this.context=context;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.student_list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder viewHolder, int i) {\n studentData data=studentDataList.get(i);\n Random rnd = new Random();\n int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\n viewHolder.parent.setBackgroundColor(currentColor);\n viewHolder.name.setText(data.name);\n viewHolder.age.setText(String.valueOf(data.age));\n setAnimation(viewHolder.parent, i);\n }\n private void setAnimation(View viewToAnimate, int position) {\n // If the bound view wasn't previously displayed on screen, it's animated\n if (position > lastPosition) {\n Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);\n viewToAnimate.startAnimation(animation);\n lastPosition = position;\n }\n }\n @Override\n public int getItemCount() {\n return studentDataList.size();\n }\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView name,age;\n LinearLayout parent;\n public MyViewHolder(View itemView) {\n super(itemView);\n parent = itemView.findViewById(R.id.parent);\n name = itemView.findViewById(R.id.name);\n age = itemView.findViewById(R.id.age);\n }\n }\n}"
},
{
"code": null,
"e": 9177,
"s": 9117,
"text": "In the adapter class, we have four methods as shown below -"
},
{
"code": null,
"e": 9258,
"s": 9177,
"text": "onCreateViewHolder():- It is used to create a view holder and it returns a view."
},
{
"code": null,
"e": 9339,
"s": 9258,
"text": "onCreateViewHolder():- It is used to create a view holder and it returns a view."
},
{
"code": null,
"e": 9403,
"s": 9339,
"text": "onBindViewHolder() - it going to bind with created view holder."
},
{
"code": null,
"e": 9467,
"s": 9403,
"text": "onBindViewHolder() - it going to bind with created view holder."
},
{
"code": null,
"e": 9510,
"s": 9467,
"text": "getItemCount() - it contains size of list."
},
{
"code": null,
"e": 9553,
"s": 9510,
"text": "getItemCount() - it contains size of list."
},
{
"code": null,
"e": 9648,
"s": 9553,
"text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder"
},
{
"code": null,
"e": 9743,
"s": 9648,
"text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder"
},
{
"code": null,
"e": 9946,
"s": 9743,
"text": "To set the random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to the parent of view item as shown below -"
},
{
"code": null,
"e": 10115,
"s": 9946,
"text": "Random rnd = new Random();\nint currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\nviewHolder.parent.setBackgroundColor(currentColor);"
},
{
"code": null,
"e": 10245,
"s": 10115,
"text": "In the adapter we have used setAnimation(), in that method we have passed, parent of child item and its position as shown below -"
},
{
"code": null,
"e": 10281,
"s": 10245,
"text": "setAnimation(viewHolder.parent, i);"
},
{
"code": null,
"e": 10394,
"s": 10281,
"text": "In the above method viewHolder.parent is linear layout in the child item layout and \"i\" is position of the view."
},
{
"code": null,
"e": 10752,
"s": 10394,
"text": "private void setAnimation(View viewToAnimate, int position)\n{\n // If the bound view wasn't previously displayed on screen, it's animated\n if (position > lastPosition)\n {\n Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);\n viewToAnimate.startAnimation(animation);\n lastPosition = position;\n }\n}"
},
{
"code": null,
"e": 10906,
"s": 10752,
"text": "In the above method we are comparing current position with last position using greater than(>), than we are applying animation from AnimationUtils Class."
},
{
"code": null,
"e": 10993,
"s": 10906,
"text": "Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml."
},
{
"code": null,
"e": 12154,
"s": 10993,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:card_view = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n card_view:cardCornerRadius = \"4dp\"\n android:id = \"@+id/card_view\"\n android:layout_margin = \"10dp\"\n android:layout_height = \"200dp\">\n <LinearLayout\n android:id = \"@+id/parent\"\n android:layout_gravity = \"center\"\n android:layout_width = \"match_parent\"\n android:orientation = \"vertical\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/name\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/age\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>"
},
{
"code": null,
"e": 12363,
"s": 12154,
"text": "In the above list item view we have created two text views for name and age inside the card view. Card view contains pre defined corner radius and shadow property. So we have used corner radius with cardview."
},
{
"code": null,
"e": 12441,
"s": 12363,
"text": "Step 7 − Following is the content of the modified file src/ studentData.java."
},
{
"code": null,
"e": 12630,
"s": 12441,
"text": "package com.example.andy.tutorialspoint;\n\nclass studentData {\n String name;\n int age;\n public studentData(String name, int age) {\n this.name = name;\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 13031,
"s": 12630,
"text": "In the above code informs about student data object. 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": 13109,
"s": 13031,
"text": "Now scroll down to the recyclerview, it will show the result as shown below -"
},
{
"code": null,
"e": 13226,
"s": 13109,
"text": "Now see the last element, it is loading with animations. There are more reference samples available as shown below -"
},
{
"code": null,
"e": 13266,
"s": 13226,
"text": "Click here to download the project code"
}
] |
A Hands-on Tutorial For Creating Matplotlib Animations | by Shuai Guo | Towards Data Science
|
Animations are great data visualization tools to convey complicated insights engagingly. In this article, we will walk through the steps of creating an animation with Matplotlib and Celluloid.
This is what we will make: it simulates various projectile motion trajectories and updates the associated histogram of the projectile shooting range.
This tutorial goes as follows. After introducing the animation packages and the employed data, we dive straight into creating the animation. We go from simple to complex: to start, we animate a single trajectory, followed by animating multiple trajectories. Finally, we will add a histogram component and take a close look at how to synchronize the histogram updates with the trajectory data.
If your time is short, the simple example of animating a single trajectory should be sufficient to give you a good grasp of the general workflow. Otherwise, I would encourage you to go through all the steps.
This Jupyter Notebook contains the code for this tutorial. Alternatively, you could run the code on Google Colaboratory.
colab.research.google.com
Without further ado, let’s get to it!
· 1. Packages· 2. Data· 3. Animate A Single Trajectory· 4. Animate Multiple Trajectories· 5. Animate Histogram· 6. Side Notes· About the Author
In this tutorial, we will use theCelluloid module. If you have ever made a plot with Matplotlib, creating animations with Celluloid is no more difficult. The basic idea is to use a “Camera” to take snapshots of individual frames, which are later rolled up into an animation.
To install Celluloid, use
pip install celluloid
Also, to display the created animation within the Jupyter notebook, we need to import HTML from IPython.display.
For this tutorial, we will load the pre-calculated projectile trajectory data: two NumPy 2D arrays that record the x and y coordinates of the projectile trajectories, respectively.
Both NumPy arrays have 1000 rows, corresponding to 1000 different trajectories. Each trajectory is discretized with 20 points, hence the NumPy arrays have 20 columns. One sample trajectory is plotted below.
Now we are ready to create some animations! We start by simulating a single trajectory. Let’s first see the code and the output, and then we elaborate on the steps to get there.
We set up the graph using Matplotlib (line 12–16).We initiate a Camera instance using the created graph (line 19).We create 20 frames, where each frame depicts the current location of the projectile and its trajectory. camera.snap() is used to take a snapshot of the individual frames (line 22–35).We call camera.animate() to roll the captured snapshots up into an animation (line 38).We display the animation with HTML (line 41).
We set up the graph using Matplotlib (line 12–16).
We initiate a Camera instance using the created graph (line 19).
We create 20 frames, where each frame depicts the current location of the projectile and its trajectory. camera.snap() is used to take a snapshot of the individual frames (line 22–35).
We call camera.animate() to roll the captured snapshots up into an animation (line 38).
We display the animation with HTML (line 41).
Under the hood, camera.animate() uses animation.ArtistAnimation() from Matplotlib. We feed three parameters to camera.animate(): the interval, which controls the delay between frames in milliseconds; the repeat, which controls whether the animation should repeat when the sequence of frames is completed; the repeat_delay, which controls the delay in milliseconds before repeating the animation when the animation is set to repeat.
Once we get the hang of simulating a single trajectory, simulating multiple trajectories becomes easy. We simply need to add an extra loop to cycle through all the trajectories.
For demonstration purposes, we will simulate the first 30 trajectories. The steps are the same as the last example. However, in this example, we will create a total of 20×30 frames to capture all 30 trajectories.
Here is the animation we’ve just made.
In this final step, we will add an updating histogram on top of multiple trajectory simulations. This histogram describes the distribution of the shooting range, and it updates when receiving new data, i.e., when a sample trajectory reaches its end.
First, let’s extract the range data and obtain the bins' edges for plotting the histogram.
Then, let’s specify how we want our histogram to behave:
the histogram has its own y-axis;
the histogram only gets updated in the frames when a sample trajectory reaches its end;
in other frames when the projectile is still “flying,” the histogram should stay the same.
To address those requirements, we will
use ax.twin() to create a twin Axes that shares the x-axis while having an independent y-axis. This new twin axis will host our histogram;
maintain a list R, which contains the range values for all sample trajectories. R starts as an empty list and gets appended when a new trajectory reaches its end. The final x coordinate value of this new trajectory (i.e., its shooting range) is appended to R;
plot the histogram using the up-to-date R.
Here are the results.
There you have it! Thanks for going through the entire tutorial😊 Hopefully, the stuff covered in this tutorial could help create your own animations!
The animation we’ve just made is intended to show the audience the uncertainty of the projectile shooting range under various combinations of initial projectile velocity and shooting angle. This type of visualization is also known as the Hypothetical Outcome Plots, a powerful technique that is especially good at delivering intuitive and effective uncertainty visualization. To learn more about hypothetical outcome plots, take a look at this article:
towardsdatascience.com
I’m a Ph.D. researcher working on uncertainty quantification and reliability analysis for aerospace applications. Statistics and data science form the core of my daily work. I love sharing what I’ve learned in the fascinating world of statistics. Check my previous posts to find out more and connect with me on Medium and Linkedin.
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "Animations are great data visualization tools to convey complicated insights engagingly. In this article, we will walk through the steps of creating an animation with Matplotlib and Celluloid."
},
{
"code": null,
"e": 515,
"s": 365,
"text": "This is what we will make: it simulates various projectile motion trajectories and updates the associated histogram of the projectile shooting range."
},
{
"code": null,
"e": 908,
"s": 515,
"text": "This tutorial goes as follows. After introducing the animation packages and the employed data, we dive straight into creating the animation. We go from simple to complex: to start, we animate a single trajectory, followed by animating multiple trajectories. Finally, we will add a histogram component and take a close look at how to synchronize the histogram updates with the trajectory data."
},
{
"code": null,
"e": 1116,
"s": 908,
"text": "If your time is short, the simple example of animating a single trajectory should be sufficient to give you a good grasp of the general workflow. Otherwise, I would encourage you to go through all the steps."
},
{
"code": null,
"e": 1237,
"s": 1116,
"text": "This Jupyter Notebook contains the code for this tutorial. Alternatively, you could run the code on Google Colaboratory."
},
{
"code": null,
"e": 1263,
"s": 1237,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 1301,
"s": 1263,
"text": "Without further ado, let’s get to it!"
},
{
"code": null,
"e": 1445,
"s": 1301,
"text": "· 1. Packages· 2. Data· 3. Animate A Single Trajectory· 4. Animate Multiple Trajectories· 5. Animate Histogram· 6. Side Notes· About the Author"
},
{
"code": null,
"e": 1720,
"s": 1445,
"text": "In this tutorial, we will use theCelluloid module. If you have ever made a plot with Matplotlib, creating animations with Celluloid is no more difficult. The basic idea is to use a “Camera” to take snapshots of individual frames, which are later rolled up into an animation."
},
{
"code": null,
"e": 1746,
"s": 1720,
"text": "To install Celluloid, use"
},
{
"code": null,
"e": 1768,
"s": 1746,
"text": "pip install celluloid"
},
{
"code": null,
"e": 1881,
"s": 1768,
"text": "Also, to display the created animation within the Jupyter notebook, we need to import HTML from IPython.display."
},
{
"code": null,
"e": 2062,
"s": 1881,
"text": "For this tutorial, we will load the pre-calculated projectile trajectory data: two NumPy 2D arrays that record the x and y coordinates of the projectile trajectories, respectively."
},
{
"code": null,
"e": 2269,
"s": 2062,
"text": "Both NumPy arrays have 1000 rows, corresponding to 1000 different trajectories. Each trajectory is discretized with 20 points, hence the NumPy arrays have 20 columns. One sample trajectory is plotted below."
},
{
"code": null,
"e": 2447,
"s": 2269,
"text": "Now we are ready to create some animations! We start by simulating a single trajectory. Let’s first see the code and the output, and then we elaborate on the steps to get there."
},
{
"code": null,
"e": 2878,
"s": 2447,
"text": "We set up the graph using Matplotlib (line 12–16).We initiate a Camera instance using the created graph (line 19).We create 20 frames, where each frame depicts the current location of the projectile and its trajectory. camera.snap() is used to take a snapshot of the individual frames (line 22–35).We call camera.animate() to roll the captured snapshots up into an animation (line 38).We display the animation with HTML (line 41)."
},
{
"code": null,
"e": 2929,
"s": 2878,
"text": "We set up the graph using Matplotlib (line 12–16)."
},
{
"code": null,
"e": 2994,
"s": 2929,
"text": "We initiate a Camera instance using the created graph (line 19)."
},
{
"code": null,
"e": 3179,
"s": 2994,
"text": "We create 20 frames, where each frame depicts the current location of the projectile and its trajectory. camera.snap() is used to take a snapshot of the individual frames (line 22–35)."
},
{
"code": null,
"e": 3267,
"s": 3179,
"text": "We call camera.animate() to roll the captured snapshots up into an animation (line 38)."
},
{
"code": null,
"e": 3313,
"s": 3267,
"text": "We display the animation with HTML (line 41)."
},
{
"code": null,
"e": 3745,
"s": 3313,
"text": "Under the hood, camera.animate() uses animation.ArtistAnimation() from Matplotlib. We feed three parameters to camera.animate(): the interval, which controls the delay between frames in milliseconds; the repeat, which controls whether the animation should repeat when the sequence of frames is completed; the repeat_delay, which controls the delay in milliseconds before repeating the animation when the animation is set to repeat."
},
{
"code": null,
"e": 3923,
"s": 3745,
"text": "Once we get the hang of simulating a single trajectory, simulating multiple trajectories becomes easy. We simply need to add an extra loop to cycle through all the trajectories."
},
{
"code": null,
"e": 4136,
"s": 3923,
"text": "For demonstration purposes, we will simulate the first 30 trajectories. The steps are the same as the last example. However, in this example, we will create a total of 20×30 frames to capture all 30 trajectories."
},
{
"code": null,
"e": 4175,
"s": 4136,
"text": "Here is the animation we’ve just made."
},
{
"code": null,
"e": 4425,
"s": 4175,
"text": "In this final step, we will add an updating histogram on top of multiple trajectory simulations. This histogram describes the distribution of the shooting range, and it updates when receiving new data, i.e., when a sample trajectory reaches its end."
},
{
"code": null,
"e": 4516,
"s": 4425,
"text": "First, let’s extract the range data and obtain the bins' edges for plotting the histogram."
},
{
"code": null,
"e": 4573,
"s": 4516,
"text": "Then, let’s specify how we want our histogram to behave:"
},
{
"code": null,
"e": 4607,
"s": 4573,
"text": "the histogram has its own y-axis;"
},
{
"code": null,
"e": 4695,
"s": 4607,
"text": "the histogram only gets updated in the frames when a sample trajectory reaches its end;"
},
{
"code": null,
"e": 4786,
"s": 4695,
"text": "in other frames when the projectile is still “flying,” the histogram should stay the same."
},
{
"code": null,
"e": 4825,
"s": 4786,
"text": "To address those requirements, we will"
},
{
"code": null,
"e": 4964,
"s": 4825,
"text": "use ax.twin() to create a twin Axes that shares the x-axis while having an independent y-axis. This new twin axis will host our histogram;"
},
{
"code": null,
"e": 5224,
"s": 4964,
"text": "maintain a list R, which contains the range values for all sample trajectories. R starts as an empty list and gets appended when a new trajectory reaches its end. The final x coordinate value of this new trajectory (i.e., its shooting range) is appended to R;"
},
{
"code": null,
"e": 5267,
"s": 5224,
"text": "plot the histogram using the up-to-date R."
},
{
"code": null,
"e": 5289,
"s": 5267,
"text": "Here are the results."
},
{
"code": null,
"e": 5439,
"s": 5289,
"text": "There you have it! Thanks for going through the entire tutorial😊 Hopefully, the stuff covered in this tutorial could help create your own animations!"
},
{
"code": null,
"e": 5892,
"s": 5439,
"text": "The animation we’ve just made is intended to show the audience the uncertainty of the projectile shooting range under various combinations of initial projectile velocity and shooting angle. This type of visualization is also known as the Hypothetical Outcome Plots, a powerful technique that is especially good at delivering intuitive and effective uncertainty visualization. To learn more about hypothetical outcome plots, take a look at this article:"
},
{
"code": null,
"e": 5915,
"s": 5892,
"text": "towardsdatascience.com"
}
] |
fread() function in C++
|
The C/C++ library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr. Following is the declaration for fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
The Following table contains the fread() parameters and description:
The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.
#include <stdio.h>
#include <string.h>
int main () {
FILE *fp;
char c[] = "this is tutorialspoint";
char buffer[100];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −
this is tutorialspoint
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "The C/C++ library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr. Following is the declaration for fread() function."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)"
},
{
"code": null,
"e": 1407,
"s": 1338,
"text": "The Following table contains the fread() parameters and description:"
},
{
"code": null,
"e": 1634,
"s": 1407,
"text": "The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached."
},
{
"code": null,
"e": 2107,
"s": 1634,
"text": "#include <stdio.h>\n#include <string.h>\nint main () {\n FILE *fp;\n char c[] = \"this is tutorialspoint\";\n char buffer[100];\n /* Open file for both reading and writing */\n fp = fopen(\"file.txt\", \"w+\");\n /* Write data to the file */\n fwrite(c, strlen(c) + 1, 1, fp);\n /* Seek to the beginning of the file */\n fseek(fp, 0, SEEK_SET);\n /* Read and display data */\n fread(buffer, strlen(c)+1, 1, fp);\n printf(\"%s\\n\", buffer);\n fclose(fp);\n return(0);\n}"
},
{
"code": null,
"e": 2366,
"s": 2107,
"text": "Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −"
},
{
"code": null,
"e": 2389,
"s": 2366,
"text": "this is tutorialspoint"
}
] |
Variations in different Sorting techniques in Python - GeeksforGeeks
|
17 Nov, 2020
These are all different types for sorting techniques that behave very differently. Let’s study which technique works how and which one to use.
Let ‘a’ be a numpy array
a.sort()(i) Sorts the array in-place & returns None(ii) Return type is None(iii) Occupies less space. No copy created as it directly sorts the original array(iv) Faster than sorted(a)# Python code to sort an array in-place# using a.sortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a) # Return type is Noneprint('Return type:', a.sort()) # Sorted array outputprint('Original array sorted->', a)OUTPUT: For a.sort()
Original array:
[9 3 1 7 4 3 6]
Return type: None
Original array sorted-> [1 3 3 4 6 7 9]
# Python code to sort an array in-place# using a.sortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a) # Return type is Noneprint('Return type:', a.sort()) # Sorted array outputprint('Original array sorted->', a)
OUTPUT: For a.sort()
Original array:
[9 3 1 7 4 3 6]
Return type: None
Original array sorted-> [1 3 3 4 6 7 9]
sorted(a)(i) Creates a new list from the old & returns the new one, sorted(ii) Return type is a list(iii) Occupies more space as copy of original array is created and then sorting is done(iv) Slower than a.sort()# Python code to create a sorted copy using# sorted()import numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a)b = sorted(a) # sorted list returned to b, b type is# <class 'list'> print('New array sorted->', b) # original array no changeprint('Original array->', a)OUTPUT:a.sorted()
Original array:
[9 3 1 7 4 3 6]
New array sorted-> [1, 3, 3, 4, 6, 7, 9]
Original array-> [9 3 1 7 4 3 6]
# Python code to create a sorted copy using# sorted()import numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a)b = sorted(a) # sorted list returned to b, b type is# <class 'list'> print('New array sorted->', b) # original array no changeprint('Original array->', a)
OUTPUT:a.sorted()
Original array:
[9 3 1 7 4 3 6]
New array sorted-> [1, 3, 3, 4, 6, 7, 9]
Original array-> [9 3 1 7 4 3 6]
np.argsort(a)(i) Returns the indices that would sort an array(ii) Return type is numpy array(iii) Occupies space as a new array of sorted indices is returned# Python code to demonstrate working of np.argsortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a) # Sort array indicesb = np.argsort(a)print('Sorted indices of original array->', b) # To get sorted array using sorted indices# c is temp array created of same len as of bc = np.zeros(len(b), dtype = int)for i in range(0, len(b)): c[i]= a[b[i]]print('Sorted array->', c)OUTPUT:np.argsort(a)
Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]
# Python code to demonstrate working of np.argsortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\n', a) # Sort array indicesb = np.argsort(a)print('Sorted indices of original array->', b) # To get sorted array using sorted indices# c is temp array created of same len as of bc = np.zeros(len(b), dtype = int)for i in range(0, len(b)): c[i]= a[b[i]]print('Sorted array->', c)
OUTPUT:np.argsort(a)
Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]
np.lexsort((b, a))(i) Perform an indirect sort using a sequence of keys(ii) Sort by a, then by b(iii) Return type ndarray of ints Array of indices that sort the keys along the specified axis(iv) Occupies space as a new array of sorted indices pair wise is returned.# Python code to demonstrate working of # np.lexsort()import numpy as np # Numpy array createda = np.array([9, 3, 1, 3, 4, 3, 6]) # First columnb = np.array([4, 6, 9, 2, 1, 8, 7]) # Second columnprint('column a, column b')for (i, j) in zip(a, b): print(i, ' ', j) ind = np.lexsort((b, a)) # Sort by a then by bprint('Sorted indices->', ind)OUTPUT:np.lexsort((b, a))
column a, column b
9 4
3 6
1 9
3 2
4 1
3 8
6 7
Sorted indices-> [2 3 1 5 4 6 0]
# Python code to demonstrate working of # np.lexsort()import numpy as np # Numpy array createda = np.array([9, 3, 1, 3, 4, 3, 6]) # First columnb = np.array([4, 6, 9, 2, 1, 8, 7]) # Second columnprint('column a, column b')for (i, j) in zip(a, b): print(i, ' ', j) ind = np.lexsort((b, a)) # Sort by a then by bprint('Sorted indices->', ind)
OUTPUT:np.lexsort((b, a))
column a, column b
9 4
3 6
1 9
3 2
4 1
3 8
6 7
Sorted indices-> [2 3 1 5 4 6 0]
This article is contributed by SHAURYA UPPAL. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 23845,
"s": 23817,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 23988,
"s": 23845,
"text": "These are all different types for sorting techniques that behave very differently. Let’s study which technique works how and which one to use."
},
{
"code": null,
"e": 24013,
"s": 23988,
"text": "Let ‘a’ be a numpy array"
},
{
"code": null,
"e": 24603,
"s": 24013,
"text": "a.sort()(i) Sorts the array in-place & returns None(ii) Return type is None(iii) Occupies less space. No copy created as it directly sorts the original array(iv) Faster than sorted(a)# Python code to sort an array in-place# using a.sortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a) # Return type is Noneprint('Return type:', a.sort()) # Sorted array outputprint('Original array sorted->', a)OUTPUT: For a.sort()\nOriginal array:\n [9 3 1 7 4 3 6]\nReturn type: None\nOriginal array sorted-> [1 3 3 4 6 7 9]\n"
},
{
"code": "# Python code to sort an array in-place# using a.sortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a) # Return type is Noneprint('Return type:', a.sort()) # Sorted array outputprint('Original array sorted->', a)",
"e": 24898,
"s": 24603,
"text": null
},
{
"code": null,
"e": 25011,
"s": 24898,
"text": "OUTPUT: For a.sort()\nOriginal array:\n [9 3 1 7 4 3 6]\nReturn type: None\nOriginal array sorted-> [1 3 3 4 6 7 9]\n"
},
{
"code": null,
"e": 25687,
"s": 25011,
"text": "sorted(a)(i) Creates a new list from the old & returns the new one, sorted(ii) Return type is a list(iii) Occupies more space as copy of original array is created and then sorting is done(iv) Slower than a.sort()# Python code to create a sorted copy using# sorted()import numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a)b = sorted(a) # sorted list returned to b, b type is# <class 'list'> print('New array sorted->', b) # original array no changeprint('Original array->', a)OUTPUT:a.sorted()\nOriginal array:\n [9 3 1 7 4 3 6]\nNew array sorted-> [1, 3, 3, 4, 6, 7, 9]\nOriginal array-> [9 3 1 7 4 3 6]\n"
},
{
"code": "# Python code to create a sorted copy using# sorted()import numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a)b = sorted(a) # sorted list returned to b, b type is# <class 'list'> print('New array sorted->', b) # original array no changeprint('Original array->', a)",
"e": 26026,
"s": 25687,
"text": null
},
{
"code": null,
"e": 26152,
"s": 26026,
"text": "OUTPUT:a.sorted()\nOriginal array:\n [9 3 1 7 4 3 6]\nNew array sorted-> [1, 3, 3, 4, 6, 7, 9]\nOriginal array-> [9 3 1 7 4 3 6]\n"
},
{
"code": null,
"e": 26901,
"s": 26152,
"text": "np.argsort(a)(i) Returns the indices that would sort an array(ii) Return type is numpy array(iii) Occupies space as a new array of sorted indices is returned# Python code to demonstrate working of np.argsortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a) # Sort array indicesb = np.argsort(a)print('Sorted indices of original array->', b) # To get sorted array using sorted indices# c is temp array created of same len as of bc = np.zeros(len(b), dtype = int)for i in range(0, len(b)): c[i]= a[b[i]]print('Sorted array->', c)OUTPUT:np.argsort(a)\nOriginal array:\n [9 3 1 7 4 3 6]\nSorted indices of original array-> [2 1 5 4 6 3 0]\nSorted array-> [1 3 3 4 6 7 9]\n"
},
{
"code": "# Python code to demonstrate working of np.argsortimport numpy as np # Numpy array createda = np.array([9, 3, 1, 7, 4, 3, 6]) # unsorted array printprint('Original array:\\n', a) # Sort array indicesb = np.argsort(a)print('Sorted indices of original array->', b) # To get sorted array using sorted indices# c is temp array created of same len as of bc = np.zeros(len(b), dtype = int)for i in range(0, len(b)): c[i]= a[b[i]]print('Sorted array->', c)",
"e": 27357,
"s": 26901,
"text": null
},
{
"code": null,
"e": 27494,
"s": 27357,
"text": "OUTPUT:np.argsort(a)\nOriginal array:\n [9 3 1 7 4 3 6]\nSorted indices of original array-> [2 1 5 4 6 3 0]\nSorted array-> [1 3 3 4 6 7 9]\n"
},
{
"code": null,
"e": 28225,
"s": 27494,
"text": "np.lexsort((b, a))(i) Perform an indirect sort using a sequence of keys(ii) Sort by a, then by b(iii) Return type ndarray of ints Array of indices that sort the keys along the specified axis(iv) Occupies space as a new array of sorted indices pair wise is returned.# Python code to demonstrate working of # np.lexsort()import numpy as np # Numpy array createda = np.array([9, 3, 1, 3, 4, 3, 6]) # First columnb = np.array([4, 6, 9, 2, 1, 8, 7]) # Second columnprint('column a, column b')for (i, j) in zip(a, b): print(i, ' ', j) ind = np.lexsort((b, a)) # Sort by a then by bprint('Sorted indices->', ind)OUTPUT:np.lexsort((b, a))\ncolumn a, column b\n9 4\n3 6\n1 9\n3 2\n4 1\n3 8\n6 7\nSorted indices-> [2 3 1 5 4 6 0]\n"
},
{
"code": "# Python code to demonstrate working of # np.lexsort()import numpy as np # Numpy array createda = np.array([9, 3, 1, 3, 4, 3, 6]) # First columnb = np.array([4, 6, 9, 2, 1, 8, 7]) # Second columnprint('column a, column b')for (i, j) in zip(a, b): print(i, ' ', j) ind = np.lexsort((b, a)) # Sort by a then by bprint('Sorted indices->', ind)",
"e": 28571,
"s": 28225,
"text": null
},
{
"code": null,
"e": 28692,
"s": 28571,
"text": "OUTPUT:np.lexsort((b, a))\ncolumn a, column b\n9 4\n3 6\n1 9\n3 2\n4 1\n3 8\n6 7\nSorted indices-> [2 3 1 5 4 6 0]\n"
},
{
"code": null,
"e": 28993,
"s": 28692,
"text": "This article is contributed by SHAURYA UPPAL. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29118,
"s": 28993,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29149,
"s": 29118,
"text": "Python numpy-Sorting Searching"
},
{
"code": null,
"e": 29162,
"s": 29149,
"text": "Python-numpy"
},
{
"code": null,
"e": 29169,
"s": 29162,
"text": "Python"
},
{
"code": null,
"e": 29267,
"s": 29169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29276,
"s": 29267,
"text": "Comments"
},
{
"code": null,
"e": 29289,
"s": 29276,
"text": "Old Comments"
},
{
"code": null,
"e": 29324,
"s": 29289,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29346,
"s": 29324,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29378,
"s": 29346,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29408,
"s": 29378,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29450,
"s": 29408,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29476,
"s": 29450,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29520,
"s": 29476,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29545,
"s": 29520,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29582,
"s": 29545,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Understand your data with principal component analysis (PCA) and discover underlying patterns | by Philipp Schmalen | Towards Data Science
|
Save time, resources and stay healthy with data exploration that goes beyond means, distributions and correlations: Leverage PCA to see through the surface of variables. It saves time and resources, because it uncovers data issues before an hour-long model training and is good for a programmer’s health, since she trades off data worries with something more enjoyable. For example, a well-proven machine learning model might fail, because of one-dimensional data with insufficient variance or other related issues. PCA offers valuable insights that make you confident about data properties and its hidden dimensions.
This article shows how to leverage PCA to understand key properties of a dataset, saving time and resources down the road which ultimately leads to a happier, more fulfilled coding life. I hope this post helps to apply PCA in a consistent way and understand its results.
PCA provides valuable insights that reach beyond descriptive statistics and help to discover underlying patterns. Two PCA metrics indicate 1. how many components capture the largest share of variance (explained variance), and 2., which features correlate with the most important components (factor loading). These metrics crosscheck previous steps in the project work flow, such as data collection which then can be adjusted. As a shortcut and ready-to-use tool, I provide the function do_pca() which conducts a PCA for a prepared dataset to inspect its results within seconds in this notebook or this script.
When a project structure resembles the one below, the prepared dataset is under scrutiny in the 4. step by looking at descriptive statistics. Among the most common ones are means, distributions and correlations taken across all observations or subgroups.
Common project structure
Collection: gather, retrieve or load dataProcessing: Format raw data, handle missing entriesEngineering: Construct and select featuresExploration: Inspect descriptives, propertiesModelling: Train, validate and test modelsEvaluation: Inspect results, compare models
Collection: gather, retrieve or load data
Processing: Format raw data, handle missing entries
Engineering: Construct and select features
Exploration: Inspect descriptives, properties
Modelling: Train, validate and test models
Evaluation: Inspect results, compare models
When the moment arrives of having a clean dataset after hours of work, makes many glances already towards the exciting step of applying models to the data. At this stage, around 80–90% of the project’s workload is done, if the data did not fell out of the sky, cleaned and processed. Of course, the urge is strong for modeling, but here are two reasons why a thorough data exploration saves time down the road:
catch coding errors → revise feature engineering (step 3)identify underlying properties → rethink data collection (step 1), preprocessing (step 2) or feature engineering (step 3)
catch coding errors → revise feature engineering (step 3)
identify underlying properties → rethink data collection (step 1), preprocessing (step 2) or feature engineering (step 3)
Wondering about underperforming models due to underlying data issues after a few hours into training, validating and testing is like a photographer on the set, not knowing how their models might look like. Therefore, the key message is to see data exploration as an opportunity to get to know your data, understanding its strength and weaknesses.
Descriptive statistics often reveal coding errors. However, detecting underlying issues likely requires more than that. Decomposition methods such as PCA help to identify these and enable to revise previous steps. This ensures a smooth transition to model building.
Large datasets often require PCA to reduce dimensionality anyway. The method as such captures the maximum possible variance across features and projects observations onto mutually uncorrelated vectors, called components. Still, PCA serves other purposes than dimensionality reduction. It also helps to discover underlying patterns across features.
To focus on the implementation in Python instead of methodology, I will skip describing PCA in its workings. There exist many great resources about it that I refer to those instead:
Animations showing PCA in action: https://setosa.io/ev/principal-component-analysis/
PCA explained in a family conversation: https://stats.stackexchange.com/a/140579
Smith [2]. A tutorial on principal components analysis: Accessible here.
Two metrics are crucial to make sense of PCA for data exploration:
1. Explained variance measures how much a model can reflect the variance of the whole data. Principle components try to capture as much of the variance as possible and this measure shows to what extent they can do that. It helps to see Components are sorted by explained variance, with the first one scoring highest and with a total sum of up to 1 across all components.
2. Factor loading indicates how much a variable correlates with a component. Each component is made of a linear combination of variables, where some might have more weight than others. Factor loadings indicate this as correlation coefficients, ranging from -1 to 1, and make components interpretable.
The upcoming sections apply PCA to exciting data from a behavioral field experiment and guide through using these metrics to enhance data exploration.
The iris dataset served well as a canonical example of several PCA. In an effort to be diverse and using novel data from a field study, I rely on replication data from Alan et al. [1]. I hope this is appreciated. It comprises data from behavioral experiments at Turkish schools, where 10 year olds took part in a curriculum to improve a non-cognitive skill called grit which defines as perseverance to pursue a task. The authors sampled individual characteristics and conducted behavioral experiments to measure a potential treatment effect between those receiving the program ( grit == 1) and those taking part in a control treatment ( grit == 0).
The following loads the data from an URL and stores it as a pandas dataframe.
# To load data from Harvard Dataverseimport io import requests# load exciting data from URL (at least something else than Iris)url = ‘https://dataverse.harvard.edu/api/access/datafile/3352340?gbrecs=false's = requests.get(url).content# store as dataframedf_raw = pd.read_csv(io.StringIO(s.decode(‘utf-8’)), sep=’\t’)
For PCA to work, the data needs to be numeric, without missings, and standardized. I put all steps into one function ( clean_data) which returns a dataframe with standardized features. and conduct steps 1 to 3 of the project work flow (collecting, processing and engineering). To begin with, import necessary modules and packages.
import pandas as pdimport numpy as np# sklearn modulefrom sklearn.decomposition import PCA# plotsimport matplotlib.pyplot as pltimport seaborn as sns# seaborn settingssns.set_style("whitegrid")sns.set_context("talk")# imports for functionfrom sklearn.preprocessing import StandardScalerfrom sklearn.impute import SimpleImputer
Next, the clean_data() function is defined. It gives a shortcut to transform the raw data into a prepared dataset with (i.) selected features, (ii.) missings replaced by column means, and (iii.) standardized variables.
Note about selected features: I selected features in (iv.) according to their replication scripts, accessible on Harvard Dataverse and solely used sample 2 (“sample B” in the publicly accessible working paper). To be concise, refer to the paper for relevant descriptives (p. 30, Table 2).
Preparing the data takes one line of code (v).
def clean_data(data, select_X=None, impute=False, std=False): """Returns dataframe with selected, imputed and standardized features Input data: dataframe select_X: list of feature names to be selected (string) impute: If True impute np.nan with mean std: If True standardize data Return dataframe: data with selected, imputed and standardized features """ # (i.) select features if select_X is not None: data = data.filter(select_X, axis='columns') print("\t>>> Selected features: {}".format(select_X)) else: # store column names select_X = list(data.columns) # (ii.) impute with mean if impute: imp = SimpleImputer() data = imp.fit_transform(data) print("\t>>> Imputed missings") # (iii.) standardize if std: std_scaler = StandardScaler() data = std_scaler.fit_transform(data) print("\t>>> Standardized data") return pd.DataFrame(data, columns=select_X)# (iv.) select relevant features in line with Alan et al. (2019)selected_features = ['grit', 'male', 'task_ability', 'raven', 'grit_survey1', 'belief_survey1', 'mathscore1', 'verbalscore1', 'risk', 'inconsistent']# (v.) select features, impute missings and standardizeX_std = clean_data(df_raw, selected_features, impute=True, std=True)
Now, the data is ready for exploration.
A PCA yields two metrics that are relevant for data exploration: Firstly, how much variance each component explains (scree plot), and secondly how much a variable correlates with a component (factor loading). The following sections provide a practical example and guide through the PCA output with a scree plot for explained variance and a heatmap on factor loadings.
Nowadays, data is abundant and the size of datasets continues to grow. Data scientists routinely deal with hundreds of variables. However, are these variables worth their memory? Put differently: Does a variable capture unique patterns or does it measure similar properties already reflected by other variables?
PCA might answer this through the metric of explained variance per component. It details the number of underlying dimensions on which most of the variance is observed.
The code below initializes a PCA object from sklearn and transforms the original data along the calculated components (i.). Thereafter, information on explained variance is retrieved (ii.) and printed (iii.).
# (i.) initialize and compute pcapca = PCA()X_pca = pca.fit_transform(X_std)# (ii.) get basic infon_components = len(pca.explained_variance_ratio_)explained_variance = pca.explained_variance_ratio_cum_explained_variance = np.cumsum(explained_variance)idx = np.arange(n_components)+1df_explained_variance = pd.DataFrame([explained_variance, cum_explained_variance], index=['explained variance', 'cumulative'], columns=idx).Tmean_explained_variance = df_explained_variance.iloc[:,0].mean() # calculate mean explained variance# (iii.) Print explained variance as plain textprint('PCA Overview')print('='*40)print("Total: {} components".format(n_components))print('-'*40)print('Mean explained variance:', round(mean_explained_variance,3))print('-'*40)print(df_explained_variance.head(20))print('-'*40)PCA Overview ======================================== Total: 10 components ---------------------------------------- Mean explained variance: 0.1 ---------------------------------------- explained variance cumulative 1 0.265261 0.265261 2 0.122700 0.387962 3 0.113990 0.501951 4 0.099139 0.601090 5 0.094357 0.695447 6 0.083412 0.778859 7 0.063117 0.841976 8 0.056386 0.898362 9 0.052588 0.950950 10 0.049050 1.000000 ----------------------------------------
Interpretation: The first component makes up for around 27% of the explained variance. This is relatively low as compared to other datasets, but no matter of concern. It simply indicates that a major share (100%–27%=73%) of observations distributes across more than one dimension. Another way to approach the output is to ask: How much components are required to cover more than X% of the variance? For example, I want to reduce the data’s dimensionality and retain at least 90% variance of the original data. Then I would have to include 9 components to reach at least 90% and even have 95% of explained variance covered in this case. With an overall of 10 variables in the original dataset, the scope to reduce dimensionality is limited. Additionally, this shows that each of the 10 original variables adds somewhat unique patterns and limitedly repeats information from other variables.
To give another example, I list explained variance of “the” wine dataset:
PCA Overview: Wine dataset ======================================== Total: 13 components ---------------------------------------- Mean explained variance: 0.077 ---------------------------------------- explained variance cumulative 1 0.361988 0.361988 2 0.192075 0.554063 3 0.111236 0.665300 4 0.070690 0.735990 5 0.065633 0.801623 6 0.049358 0.850981 7 0.042387 0.893368 8 0.026807 0.920175 9 0.022222 0.942397 10 0.019300 0.961697 11 0.017368 0.979066 12 0.012982 0.992048 13 0.007952 1.000000 ----------------------------------------
Here, 8 out of 13 components suffice to capture at least 90% of the original variance. Thus, there is more scope to reduce dimensionality. Furthermore, it indicates that some variables do not contribute much to variance in the data.
Instead of plain text, a scree plot visualizes explained variance across components and informs about individual and cumulative explained variance for each component. The next code chunk creates such a scree plot and includes an option to focus on the first X components to be manageable when dealing with hundreds of components for larger datasets (limit).
#limit plot to x PClimit = int(input("Limit scree plot to nth component (0 for all) > "))if limit > 0: limit_df = limitelse: limit_df = n_componentsdf_explained_variance_limited = df_explained_variance.iloc[:limit_df,:]#make scree plotfig, ax1 = plt.subplots(figsize=(15,6))ax1.set_title('Explained variance across principal components', fontsize=14)ax1.set_xlabel('Principal component', fontsize=12)ax1.set_ylabel('Explained variance', fontsize=12)ax2 = sns.barplot(x=idx[:limit_df], y='explained variance', data=df_explained_variance_limited, palette='summer')ax2 = ax1.twinx()ax2.grid(False)ax2.set_ylabel('Cumulative', fontsize=14)ax2 = sns.lineplot(x=idx[:limit_df]-1, y='cumulative', data=df_explained_variance_limited, color='#fc8d59')ax1.axhline(mean_explained_variance, ls='--', color='#fc8d59') #plot meanax1.text(-.8, mean_explained_variance+(mean_explained_variance*.05), "average", color='#fc8d59', fontsize=14) #label y axismax_y1 = max(df_explained_variance_limited.iloc[:,0])max_y2 = max(df_explained_variance_limited.iloc[:,1])ax1.set(ylim=(0, max_y1+max_y1*.1))ax2.set(ylim=(0, max_y2+max_y2*.1))plt.show()
A scree plot might show distinct jumps from one component to another. For example, when the first component captures disproportionately more variance than others, it could be a sign that variables inform about the same underlying factor or do not add additional dimensions, but say the same thing from a marginally different angle.
To give a direct example and to get a feeling for how distinct jumps might look like, I provide the scree plot of the Boston house prices dataset:
Assume you have hundreds of variables, apply PCA and discover that over much of the explained variance is captured by the first few components. This might hint at a much lower number of underlying dimensions than the number of variables. Most likely, dropping some hundred variables leads to performance gains for training, validation and testing. There will be more time left to select a suitable model and refine it than to wait for the model itself to discover lack of variance behind several variables.
In addition to this, imagine that the data was constructed by oneself, e.g. through web scraping, and the scraper extracted pre-specified information from a web page. In that case, the retrieved information could be one-dimensional, when the developer of the scraper had only few relevant items in mind, but forgot to include items that shed light on further aspects of the problem setting. At this stage, it might be worthwhile to go back to the first step of the work flow and adjust data collection.
PCA offers another valuable statistic besides explained variance: The correlation between each principle component and a variable, also called factor loading. This statistic facilitates to grasp the dimension that lies behind a component. For example, a dataset includes information about individuals such as math score, reaction time and retention span. The overarching dimension would be cognitive skills and a component that strongly correlates with these variables can be interpreted as the cognitive skill dimension. Similarly, another dimension could be non-cognitive skills and personality, when the data has features such as self-confidence, patience or conscientiousness. A component that captures this area highly correlates with those features.
The following code creates a heatmap to inspect these correlations, also called factor loading matrix.
# adjust y-axis size dynamicallysize_yaxis = round(X_std.shape[1] * 0.5)fig, ax = plt.subplots(figsize=(8,size_yaxis))# plot the first top_pc componentstop_pc = 3sns.heatmap(df_c.iloc[:,:top_pc], annot=True, cmap="YlGnBu", ax=ax)plt.show()
The first component strongly negatively associates with task ability, reasoning score (raven), math score, verbal score and positively links to beliefs about being gritty (grit_survey1). Summarizing this into a common underlying factor is subjective and requires domain knowledge. In my opinion, the first component mainly captures cognitive skills.
The second component correlates negatively with receiving the treatment (grit), gender (male) and positively relates to being inconsistent. Interpreting this dimension is less clear-cut and much more challenging. Nevertheless, it accounts for 12% of explained variance instead of 27% like the first component, which results in less interpretable dimensions as it spans slightly across several topical areas. All components that follow might be analogously difficult to interpret.
Evidence that variables capture similar dimensions could be uniformly distributed factor loadings. One example which inspired this article is on of my projects where I relied on Google Trends data and self-constructed keywords about a firm’s sustainability. A list of the 15th highest factor loadings for the first principle component revealed loadings ranging from 0.12 as the highest value to 0.11 as the lowest loading of all 15. Such a uniform distribution of factor loadings could be an issue. This especially applies when data is self-collected and someone preselected what is being considered for collection. Adjusting this selection might add dimensionality to your data which possibly improves model performance at the end.
If the data was self-constructed, the factor loadings show how each feature contributes to an underlying dimension, which helps to come up with additional perspectives on data collection and what features or dimensions could add valuable variance. Rather than blind guessing which features to add, factor loadings lead to informed decisions for data collection. They may even be an inspiration in the search for more advanced features.
All in all, PCA is a flexible instrument in the toolbox for data exploration. Its main purpose is to reduce complexity of large datasets. But it also serves well to look beneath the surface of variables, discover latent dimensions and relate variables to these dimensions, making them interpretable. Key metrics to consider are explained variance and factor loading.
This article shows how to leverage these metrics for data exploration that goes beyond averages, distributions and correlations and build an understanding of underlying properties of the data. Identifying patterns across variables is valuable to rethink previous steps in the project workflow, such as data collection, processing or feature engineering.
Thanks for reading! I hope you find it as useful as I had fun to write this guide. I am curious of your thoughts on this matter. If you have any feedback I highly appreciate your feedback and look forward receiving your message.
I applied PCA to even more exemplary datasets like Boston housing market, wine and iris using do_pca(). It illustrates how PCA output looks like for small datasets. Feel free to download my notebook or script.
A rule of thumb formulated here states: Use PCA if you want to reduce your correlated observed variables to a smaller set of uncorrelated variables and use factor analysis to test a model of latent factors on observed variables.
Even though this distinction is scientifically correct, it becomes less relevant in an applied context. PCA relates closely to factor analysis which often leads to similar conclusions about data properties which is what we care about. Therefore, the distinction can be relaxed for data exploration. This post gives an example in an applied context and another example with hands-on code for factor analysis is attached in the notebook.
Finally, for those interested in the differences between factor analysis and PCA refer to this post. Note, that throughout this article I never used the term latent factor to be precise.
[1] Alan, S., Boneva, T., & Ertac, S. (2019). Ever failed, try again, succeed better: Results from a randomized educational intervention on grit. The Quarterly Journal of Economics, 134(3), 1121–1162.
[2] Smith, L. I. (2002). A tutorial on principal components analysis.
|
[
{
"code": null,
"e": 790,
"s": 172,
"text": "Save time, resources and stay healthy with data exploration that goes beyond means, distributions and correlations: Leverage PCA to see through the surface of variables. It saves time and resources, because it uncovers data issues before an hour-long model training and is good for a programmer’s health, since she trades off data worries with something more enjoyable. For example, a well-proven machine learning model might fail, because of one-dimensional data with insufficient variance or other related issues. PCA offers valuable insights that make you confident about data properties and its hidden dimensions."
},
{
"code": null,
"e": 1061,
"s": 790,
"text": "This article shows how to leverage PCA to understand key properties of a dataset, saving time and resources down the road which ultimately leads to a happier, more fulfilled coding life. I hope this post helps to apply PCA in a consistent way and understand its results."
},
{
"code": null,
"e": 1671,
"s": 1061,
"text": "PCA provides valuable insights that reach beyond descriptive statistics and help to discover underlying patterns. Two PCA metrics indicate 1. how many components capture the largest share of variance (explained variance), and 2., which features correlate with the most important components (factor loading). These metrics crosscheck previous steps in the project work flow, such as data collection which then can be adjusted. As a shortcut and ready-to-use tool, I provide the function do_pca() which conducts a PCA for a prepared dataset to inspect its results within seconds in this notebook or this script."
},
{
"code": null,
"e": 1926,
"s": 1671,
"text": "When a project structure resembles the one below, the prepared dataset is under scrutiny in the 4. step by looking at descriptive statistics. Among the most common ones are means, distributions and correlations taken across all observations or subgroups."
},
{
"code": null,
"e": 1951,
"s": 1926,
"text": "Common project structure"
},
{
"code": null,
"e": 2216,
"s": 1951,
"text": "Collection: gather, retrieve or load dataProcessing: Format raw data, handle missing entriesEngineering: Construct and select featuresExploration: Inspect descriptives, propertiesModelling: Train, validate and test modelsEvaluation: Inspect results, compare models"
},
{
"code": null,
"e": 2258,
"s": 2216,
"text": "Collection: gather, retrieve or load data"
},
{
"code": null,
"e": 2310,
"s": 2258,
"text": "Processing: Format raw data, handle missing entries"
},
{
"code": null,
"e": 2353,
"s": 2310,
"text": "Engineering: Construct and select features"
},
{
"code": null,
"e": 2399,
"s": 2353,
"text": "Exploration: Inspect descriptives, properties"
},
{
"code": null,
"e": 2442,
"s": 2399,
"text": "Modelling: Train, validate and test models"
},
{
"code": null,
"e": 2486,
"s": 2442,
"text": "Evaluation: Inspect results, compare models"
},
{
"code": null,
"e": 2897,
"s": 2486,
"text": "When the moment arrives of having a clean dataset after hours of work, makes many glances already towards the exciting step of applying models to the data. At this stage, around 80–90% of the project’s workload is done, if the data did not fell out of the sky, cleaned and processed. Of course, the urge is strong for modeling, but here are two reasons why a thorough data exploration saves time down the road:"
},
{
"code": null,
"e": 3076,
"s": 2897,
"text": "catch coding errors → revise feature engineering (step 3)identify underlying properties → rethink data collection (step 1), preprocessing (step 2) or feature engineering (step 3)"
},
{
"code": null,
"e": 3134,
"s": 3076,
"text": "catch coding errors → revise feature engineering (step 3)"
},
{
"code": null,
"e": 3256,
"s": 3134,
"text": "identify underlying properties → rethink data collection (step 1), preprocessing (step 2) or feature engineering (step 3)"
},
{
"code": null,
"e": 3603,
"s": 3256,
"text": "Wondering about underperforming models due to underlying data issues after a few hours into training, validating and testing is like a photographer on the set, not knowing how their models might look like. Therefore, the key message is to see data exploration as an opportunity to get to know your data, understanding its strength and weaknesses."
},
{
"code": null,
"e": 3869,
"s": 3603,
"text": "Descriptive statistics often reveal coding errors. However, detecting underlying issues likely requires more than that. Decomposition methods such as PCA help to identify these and enable to revise previous steps. This ensures a smooth transition to model building."
},
{
"code": null,
"e": 4217,
"s": 3869,
"text": "Large datasets often require PCA to reduce dimensionality anyway. The method as such captures the maximum possible variance across features and projects observations onto mutually uncorrelated vectors, called components. Still, PCA serves other purposes than dimensionality reduction. It also helps to discover underlying patterns across features."
},
{
"code": null,
"e": 4399,
"s": 4217,
"text": "To focus on the implementation in Python instead of methodology, I will skip describing PCA in its workings. There exist many great resources about it that I refer to those instead:"
},
{
"code": null,
"e": 4484,
"s": 4399,
"text": "Animations showing PCA in action: https://setosa.io/ev/principal-component-analysis/"
},
{
"code": null,
"e": 4565,
"s": 4484,
"text": "PCA explained in a family conversation: https://stats.stackexchange.com/a/140579"
},
{
"code": null,
"e": 4638,
"s": 4565,
"text": "Smith [2]. A tutorial on principal components analysis: Accessible here."
},
{
"code": null,
"e": 4705,
"s": 4638,
"text": "Two metrics are crucial to make sense of PCA for data exploration:"
},
{
"code": null,
"e": 5076,
"s": 4705,
"text": "1. Explained variance measures how much a model can reflect the variance of the whole data. Principle components try to capture as much of the variance as possible and this measure shows to what extent they can do that. It helps to see Components are sorted by explained variance, with the first one scoring highest and with a total sum of up to 1 across all components."
},
{
"code": null,
"e": 5377,
"s": 5076,
"text": "2. Factor loading indicates how much a variable correlates with a component. Each component is made of a linear combination of variables, where some might have more weight than others. Factor loadings indicate this as correlation coefficients, ranging from -1 to 1, and make components interpretable."
},
{
"code": null,
"e": 5528,
"s": 5377,
"text": "The upcoming sections apply PCA to exciting data from a behavioral field experiment and guide through using these metrics to enhance data exploration."
},
{
"code": null,
"e": 6177,
"s": 5528,
"text": "The iris dataset served well as a canonical example of several PCA. In an effort to be diverse and using novel data from a field study, I rely on replication data from Alan et al. [1]. I hope this is appreciated. It comprises data from behavioral experiments at Turkish schools, where 10 year olds took part in a curriculum to improve a non-cognitive skill called grit which defines as perseverance to pursue a task. The authors sampled individual characteristics and conducted behavioral experiments to measure a potential treatment effect between those receiving the program ( grit == 1) and those taking part in a control treatment ( grit == 0)."
},
{
"code": null,
"e": 6255,
"s": 6177,
"text": "The following loads the data from an URL and stores it as a pandas dataframe."
},
{
"code": null,
"e": 6572,
"s": 6255,
"text": "# To load data from Harvard Dataverseimport io import requests# load exciting data from URL (at least something else than Iris)url = ‘https://dataverse.harvard.edu/api/access/datafile/3352340?gbrecs=false's = requests.get(url).content# store as dataframedf_raw = pd.read_csv(io.StringIO(s.decode(‘utf-8’)), sep=’\\t’)"
},
{
"code": null,
"e": 6903,
"s": 6572,
"text": "For PCA to work, the data needs to be numeric, without missings, and standardized. I put all steps into one function ( clean_data) which returns a dataframe with standardized features. and conduct steps 1 to 3 of the project work flow (collecting, processing and engineering). To begin with, import necessary modules and packages."
},
{
"code": null,
"e": 7230,
"s": 6903,
"text": "import pandas as pdimport numpy as np# sklearn modulefrom sklearn.decomposition import PCA# plotsimport matplotlib.pyplot as pltimport seaborn as sns# seaborn settingssns.set_style(\"whitegrid\")sns.set_context(\"talk\")# imports for functionfrom sklearn.preprocessing import StandardScalerfrom sklearn.impute import SimpleImputer"
},
{
"code": null,
"e": 7449,
"s": 7230,
"text": "Next, the clean_data() function is defined. It gives a shortcut to transform the raw data into a prepared dataset with (i.) selected features, (ii.) missings replaced by column means, and (iii.) standardized variables."
},
{
"code": null,
"e": 7738,
"s": 7449,
"text": "Note about selected features: I selected features in (iv.) according to their replication scripts, accessible on Harvard Dataverse and solely used sample 2 (“sample B” in the publicly accessible working paper). To be concise, refer to the paper for relevant descriptives (p. 30, Table 2)."
},
{
"code": null,
"e": 7785,
"s": 7738,
"text": "Preparing the data takes one line of code (v)."
},
{
"code": null,
"e": 9189,
"s": 7785,
"text": "def clean_data(data, select_X=None, impute=False, std=False): \"\"\"Returns dataframe with selected, imputed and standardized features Input data: dataframe select_X: list of feature names to be selected (string) impute: If True impute np.nan with mean std: If True standardize data Return dataframe: data with selected, imputed and standardized features \"\"\" # (i.) select features if select_X is not None: data = data.filter(select_X, axis='columns') print(\"\\t>>> Selected features: {}\".format(select_X)) else: # store column names select_X = list(data.columns) # (ii.) impute with mean if impute: imp = SimpleImputer() data = imp.fit_transform(data) print(\"\\t>>> Imputed missings\") # (iii.) standardize if std: std_scaler = StandardScaler() data = std_scaler.fit_transform(data) print(\"\\t>>> Standardized data\") return pd.DataFrame(data, columns=select_X)# (iv.) select relevant features in line with Alan et al. (2019)selected_features = ['grit', 'male', 'task_ability', 'raven', 'grit_survey1', 'belief_survey1', 'mathscore1', 'verbalscore1', 'risk', 'inconsistent']# (v.) select features, impute missings and standardizeX_std = clean_data(df_raw, selected_features, impute=True, std=True)"
},
{
"code": null,
"e": 9229,
"s": 9189,
"text": "Now, the data is ready for exploration."
},
{
"code": null,
"e": 9597,
"s": 9229,
"text": "A PCA yields two metrics that are relevant for data exploration: Firstly, how much variance each component explains (scree plot), and secondly how much a variable correlates with a component (factor loading). The following sections provide a practical example and guide through the PCA output with a scree plot for explained variance and a heatmap on factor loadings."
},
{
"code": null,
"e": 9909,
"s": 9597,
"text": "Nowadays, data is abundant and the size of datasets continues to grow. Data scientists routinely deal with hundreds of variables. However, are these variables worth their memory? Put differently: Does a variable capture unique patterns or does it measure similar properties already reflected by other variables?"
},
{
"code": null,
"e": 10077,
"s": 9909,
"text": "PCA might answer this through the metric of explained variance per component. It details the number of underlying dimensions on which most of the variance is observed."
},
{
"code": null,
"e": 10286,
"s": 10077,
"text": "The code below initializes a PCA object from sklearn and transforms the original data along the calculated components (i.). Thereafter, information on explained variance is retrieved (ii.) and printed (iii.)."
},
{
"code": null,
"e": 11615,
"s": 10286,
"text": "# (i.) initialize and compute pcapca = PCA()X_pca = pca.fit_transform(X_std)# (ii.) get basic infon_components = len(pca.explained_variance_ratio_)explained_variance = pca.explained_variance_ratio_cum_explained_variance = np.cumsum(explained_variance)idx = np.arange(n_components)+1df_explained_variance = pd.DataFrame([explained_variance, cum_explained_variance], index=['explained variance', 'cumulative'], columns=idx).Tmean_explained_variance = df_explained_variance.iloc[:,0].mean() # calculate mean explained variance# (iii.) Print explained variance as plain textprint('PCA Overview')print('='*40)print(\"Total: {} components\".format(n_components))print('-'*40)print('Mean explained variance:', round(mean_explained_variance,3))print('-'*40)print(df_explained_variance.head(20))print('-'*40)PCA Overview ======================================== Total: 10 components ---------------------------------------- Mean explained variance: 0.1 ---------------------------------------- explained variance cumulative 1 0.265261 0.265261 2 0.122700 0.387962 3 0.113990 0.501951 4 0.099139 0.601090 5 0.094357 0.695447 6 0.083412 0.778859 7 0.063117 0.841976 8 0.056386 0.898362 9 0.052588 0.950950 10 0.049050 1.000000 ----------------------------------------"
},
{
"code": null,
"e": 12505,
"s": 11615,
"text": "Interpretation: The first component makes up for around 27% of the explained variance. This is relatively low as compared to other datasets, but no matter of concern. It simply indicates that a major share (100%–27%=73%) of observations distributes across more than one dimension. Another way to approach the output is to ask: How much components are required to cover more than X% of the variance? For example, I want to reduce the data’s dimensionality and retain at least 90% variance of the original data. Then I would have to include 9 components to reach at least 90% and even have 95% of explained variance covered in this case. With an overall of 10 variables in the original dataset, the scope to reduce dimensionality is limited. Additionally, this shows that each of the 10 original variables adds somewhat unique patterns and limitedly repeats information from other variables."
},
{
"code": null,
"e": 12579,
"s": 12505,
"text": "To give another example, I list explained variance of “the” wine dataset:"
},
{
"code": null,
"e": 13116,
"s": 12579,
"text": "PCA Overview: Wine dataset ======================================== Total: 13 components ---------------------------------------- Mean explained variance: 0.077 ---------------------------------------- explained variance cumulative 1 0.361988 0.361988 2 0.192075 0.554063 3 0.111236 0.665300 4 0.070690 0.735990 5 0.065633 0.801623 6 0.049358 0.850981 7 0.042387 0.893368 8 0.026807 0.920175 9 0.022222 0.942397 10 0.019300 0.961697 11 0.017368 0.979066 12 0.012982 0.992048 13 0.007952 1.000000 ----------------------------------------"
},
{
"code": null,
"e": 13349,
"s": 13116,
"text": "Here, 8 out of 13 components suffice to capture at least 90% of the original variance. Thus, there is more scope to reduce dimensionality. Furthermore, it indicates that some variables do not contribute much to variance in the data."
},
{
"code": null,
"e": 13707,
"s": 13349,
"text": "Instead of plain text, a scree plot visualizes explained variance across components and informs about individual and cumulative explained variance for each component. The next code chunk creates such a scree plot and includes an option to focus on the first X components to be manageable when dealing with hundreds of components for larger datasets (limit)."
},
{
"code": null,
"e": 14838,
"s": 13707,
"text": "#limit plot to x PClimit = int(input(\"Limit scree plot to nth component (0 for all) > \"))if limit > 0: limit_df = limitelse: limit_df = n_componentsdf_explained_variance_limited = df_explained_variance.iloc[:limit_df,:]#make scree plotfig, ax1 = plt.subplots(figsize=(15,6))ax1.set_title('Explained variance across principal components', fontsize=14)ax1.set_xlabel('Principal component', fontsize=12)ax1.set_ylabel('Explained variance', fontsize=12)ax2 = sns.barplot(x=idx[:limit_df], y='explained variance', data=df_explained_variance_limited, palette='summer')ax2 = ax1.twinx()ax2.grid(False)ax2.set_ylabel('Cumulative', fontsize=14)ax2 = sns.lineplot(x=idx[:limit_df]-1, y='cumulative', data=df_explained_variance_limited, color='#fc8d59')ax1.axhline(mean_explained_variance, ls='--', color='#fc8d59') #plot meanax1.text(-.8, mean_explained_variance+(mean_explained_variance*.05), \"average\", color='#fc8d59', fontsize=14) #label y axismax_y1 = max(df_explained_variance_limited.iloc[:,0])max_y2 = max(df_explained_variance_limited.iloc[:,1])ax1.set(ylim=(0, max_y1+max_y1*.1))ax2.set(ylim=(0, max_y2+max_y2*.1))plt.show()"
},
{
"code": null,
"e": 15170,
"s": 14838,
"text": "A scree plot might show distinct jumps from one component to another. For example, when the first component captures disproportionately more variance than others, it could be a sign that variables inform about the same underlying factor or do not add additional dimensions, but say the same thing from a marginally different angle."
},
{
"code": null,
"e": 15317,
"s": 15170,
"text": "To give a direct example and to get a feeling for how distinct jumps might look like, I provide the scree plot of the Boston house prices dataset:"
},
{
"code": null,
"e": 15824,
"s": 15317,
"text": "Assume you have hundreds of variables, apply PCA and discover that over much of the explained variance is captured by the first few components. This might hint at a much lower number of underlying dimensions than the number of variables. Most likely, dropping some hundred variables leads to performance gains for training, validation and testing. There will be more time left to select a suitable model and refine it than to wait for the model itself to discover lack of variance behind several variables."
},
{
"code": null,
"e": 16327,
"s": 15824,
"text": "In addition to this, imagine that the data was constructed by oneself, e.g. through web scraping, and the scraper extracted pre-specified information from a web page. In that case, the retrieved information could be one-dimensional, when the developer of the scraper had only few relevant items in mind, but forgot to include items that shed light on further aspects of the problem setting. At this stage, it might be worthwhile to go back to the first step of the work flow and adjust data collection."
},
{
"code": null,
"e": 17083,
"s": 16327,
"text": "PCA offers another valuable statistic besides explained variance: The correlation between each principle component and a variable, also called factor loading. This statistic facilitates to grasp the dimension that lies behind a component. For example, a dataset includes information about individuals such as math score, reaction time and retention span. The overarching dimension would be cognitive skills and a component that strongly correlates with these variables can be interpreted as the cognitive skill dimension. Similarly, another dimension could be non-cognitive skills and personality, when the data has features such as self-confidence, patience or conscientiousness. A component that captures this area highly correlates with those features."
},
{
"code": null,
"e": 17186,
"s": 17083,
"text": "The following code creates a heatmap to inspect these correlations, also called factor loading matrix."
},
{
"code": null,
"e": 17426,
"s": 17186,
"text": "# adjust y-axis size dynamicallysize_yaxis = round(X_std.shape[1] * 0.5)fig, ax = plt.subplots(figsize=(8,size_yaxis))# plot the first top_pc componentstop_pc = 3sns.heatmap(df_c.iloc[:,:top_pc], annot=True, cmap=\"YlGnBu\", ax=ax)plt.show()"
},
{
"code": null,
"e": 17776,
"s": 17426,
"text": "The first component strongly negatively associates with task ability, reasoning score (raven), math score, verbal score and positively links to beliefs about being gritty (grit_survey1). Summarizing this into a common underlying factor is subjective and requires domain knowledge. In my opinion, the first component mainly captures cognitive skills."
},
{
"code": null,
"e": 18256,
"s": 17776,
"text": "The second component correlates negatively with receiving the treatment (grit), gender (male) and positively relates to being inconsistent. Interpreting this dimension is less clear-cut and much more challenging. Nevertheless, it accounts for 12% of explained variance instead of 27% like the first component, which results in less interpretable dimensions as it spans slightly across several topical areas. All components that follow might be analogously difficult to interpret."
},
{
"code": null,
"e": 18989,
"s": 18256,
"text": "Evidence that variables capture similar dimensions could be uniformly distributed factor loadings. One example which inspired this article is on of my projects where I relied on Google Trends data and self-constructed keywords about a firm’s sustainability. A list of the 15th highest factor loadings for the first principle component revealed loadings ranging from 0.12 as the highest value to 0.11 as the lowest loading of all 15. Such a uniform distribution of factor loadings could be an issue. This especially applies when data is self-collected and someone preselected what is being considered for collection. Adjusting this selection might add dimensionality to your data which possibly improves model performance at the end."
},
{
"code": null,
"e": 19425,
"s": 18989,
"text": "If the data was self-constructed, the factor loadings show how each feature contributes to an underlying dimension, which helps to come up with additional perspectives on data collection and what features or dimensions could add valuable variance. Rather than blind guessing which features to add, factor loadings lead to informed decisions for data collection. They may even be an inspiration in the search for more advanced features."
},
{
"code": null,
"e": 19792,
"s": 19425,
"text": "All in all, PCA is a flexible instrument in the toolbox for data exploration. Its main purpose is to reduce complexity of large datasets. But it also serves well to look beneath the surface of variables, discover latent dimensions and relate variables to these dimensions, making them interpretable. Key metrics to consider are explained variance and factor loading."
},
{
"code": null,
"e": 20146,
"s": 19792,
"text": "This article shows how to leverage these metrics for data exploration that goes beyond averages, distributions and correlations and build an understanding of underlying properties of the data. Identifying patterns across variables is valuable to rethink previous steps in the project workflow, such as data collection, processing or feature engineering."
},
{
"code": null,
"e": 20375,
"s": 20146,
"text": "Thanks for reading! I hope you find it as useful as I had fun to write this guide. I am curious of your thoughts on this matter. If you have any feedback I highly appreciate your feedback and look forward receiving your message."
},
{
"code": null,
"e": 20585,
"s": 20375,
"text": "I applied PCA to even more exemplary datasets like Boston housing market, wine and iris using do_pca(). It illustrates how PCA output looks like for small datasets. Feel free to download my notebook or script."
},
{
"code": null,
"e": 20814,
"s": 20585,
"text": "A rule of thumb formulated here states: Use PCA if you want to reduce your correlated observed variables to a smaller set of uncorrelated variables and use factor analysis to test a model of latent factors on observed variables."
},
{
"code": null,
"e": 21250,
"s": 20814,
"text": "Even though this distinction is scientifically correct, it becomes less relevant in an applied context. PCA relates closely to factor analysis which often leads to similar conclusions about data properties which is what we care about. Therefore, the distinction can be relaxed for data exploration. This post gives an example in an applied context and another example with hands-on code for factor analysis is attached in the notebook."
},
{
"code": null,
"e": 21437,
"s": 21250,
"text": "Finally, for those interested in the differences between factor analysis and PCA refer to this post. Note, that throughout this article I never used the term latent factor to be precise."
},
{
"code": null,
"e": 21638,
"s": 21437,
"text": "[1] Alan, S., Boneva, T., & Ertac, S. (2019). Ever failed, try again, succeed better: Results from a randomized educational intervention on grit. The Quarterly Journal of Economics, 134(3), 1121–1162."
}
] |
Compiler Design - Symbol Table
|
Symbol table is an important data structure created and maintained by compilers in order to store information about the occurrence of various entities such as variable names, function names, objects, classes, interfaces, etc. Symbol table is used by both the analysis and the synthesis parts of a compiler.
A symbol table may serve the following purposes depending upon the language in hand:
To store the names of all entities in a structured form at one place.
To store the names of all entities in a structured form at one place.
To verify if a variable has been declared.
To verify if a variable has been declared.
To implement type checking, by verifying assignments and expressions in the source code are semantically correct.
To implement type checking, by verifying assignments and expressions in the source code are semantically correct.
To determine the scope of a name (scope resolution).
To determine the scope of a name (scope resolution).
A symbol table is simply a table which can be either linear or a hash table. It maintains an entry for each name in the following format:
<symbol name, type, attribute>
For example, if a symbol table has to store information about the following variable declaration:
static int interest;
then it should store the entry such as:
<interest, int, static>
The attribute clause contains the entries related to the name.
If a compiler is to handle a small amount of data, then the symbol table can be implemented as an unordered list, which is easy to code, but it is only suitable for small tables only. A symbol table can be implemented in one of the following ways:
Linear (sorted or unsorted) list
Binary Search Tree
Hash table
Among all, symbol tables are mostly implemented as hash tables, where the source code symbol itself is treated as a key for the hash function and the return value is the information about the symbol.
A symbol table, either linear or hash, should provide the following operations.
This operation is more frequently used by analysis phase, i.e., the first half of the compiler where tokens are identified and names are stored in the table. This operation is used to add information in the symbol table about unique names occurring in the source code. The format or structure in which the names are stored depends upon the compiler in hand.
An attribute for a symbol in the source code is the information associated with that symbol. This information contains the value, state, scope, and type about the symbol. The insert() function takes the symbol and its attributes as arguments and stores the information in the symbol table.
For example:
int a;
should be processed by the compiler as:
insert(a, int);
lookup() operation is used to search a name in the symbol table to determine:
if the symbol exists in the table.
if it is declared before it is being used.
if the name is used in the scope.
if the symbol is initialized.
if the symbol declared multiple times.
The format of lookup() function varies according to the programming language. The basic format should match the following:
lookup(symbol)
This method returns 0 (zero) if the symbol does not exist in the symbol table. If the symbol exists in the symbol table, it returns its attributes stored in the table.
A compiler maintains two types of symbol tables: a global symbol table which can be accessed by all the procedures and scope symbol tables that are created for each scope in the program.
To determine the scope of a name, symbol tables are arranged in hierarchical structure as shown in the example below:
. . .
int value=10;
void pro_one()
{
int one_1;
int one_2;
{ \
int one_3; |_ inner scope 1
int one_4; |
} /
int one_5;
{ \
int one_6; |_ inner scope 2
int one_7; |
} /
}
void pro_two()
{
int two_1;
int two_2;
{ \
int two_3; |_ inner scope 3
int two_4; |
} /
int two_5;
}
. . .
The above program can be represented in a hierarchical structure of symbol tables:
The global symbol table contains names for one global variable (int value) and two procedure names, which should be available to all the child nodes shown above. The names mentioned in the pro_one symbol table (and all its child tables) are not available for pro_two symbols and its child tables.
This symbol table data structure hierarchy is stored in the semantic analyzer and whenever a name needs to be searched in a symbol table, it is searched using the following algorithm:
first a symbol will be searched in the current scope, i.e. current symbol table.
first a symbol will be searched in the current scope, i.e. current symbol table.
if a name is found, then search is completed, else it will be searched in the parent symbol table until,
if a name is found, then search is completed, else it will be searched in the parent symbol table until,
either the name is found or global symbol table has been searched for the name.
either the name is found or global symbol table has been searched for the name.
102 Lectures
10 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2500,
"s": 2193,
"text": "Symbol table is an important data structure created and maintained by compilers in order to store information about the occurrence of various entities such as variable names, function names, objects, classes, interfaces, etc. Symbol table is used by both the analysis and the synthesis parts of a compiler."
},
{
"code": null,
"e": 2585,
"s": 2500,
"text": "A symbol table may serve the following purposes depending upon the language in hand:"
},
{
"code": null,
"e": 2655,
"s": 2585,
"text": "To store the names of all entities in a structured form at one place."
},
{
"code": null,
"e": 2725,
"s": 2655,
"text": "To store the names of all entities in a structured form at one place."
},
{
"code": null,
"e": 2768,
"s": 2725,
"text": "To verify if a variable has been declared."
},
{
"code": null,
"e": 2811,
"s": 2768,
"text": "To verify if a variable has been declared."
},
{
"code": null,
"e": 2925,
"s": 2811,
"text": "To implement type checking, by verifying assignments and expressions in the source code are semantically correct."
},
{
"code": null,
"e": 3039,
"s": 2925,
"text": "To implement type checking, by verifying assignments and expressions in the source code are semantically correct."
},
{
"code": null,
"e": 3092,
"s": 3039,
"text": "To determine the scope of a name (scope resolution)."
},
{
"code": null,
"e": 3145,
"s": 3092,
"text": "To determine the scope of a name (scope resolution)."
},
{
"code": null,
"e": 3283,
"s": 3145,
"text": "A symbol table is simply a table which can be either linear or a hash table. It maintains an entry for each name in the following format:"
},
{
"code": null,
"e": 3316,
"s": 3283,
"text": "<symbol name, type, attribute>"
},
{
"code": null,
"e": 3414,
"s": 3316,
"text": "For example, if a symbol table has to store information about the following variable declaration:"
},
{
"code": null,
"e": 3435,
"s": 3414,
"text": "static int interest;"
},
{
"code": null,
"e": 3475,
"s": 3435,
"text": "then it should store the entry such as:"
},
{
"code": null,
"e": 3499,
"s": 3475,
"text": "<interest, int, static>"
},
{
"code": null,
"e": 3562,
"s": 3499,
"text": "The attribute clause contains the entries related to the name."
},
{
"code": null,
"e": 3810,
"s": 3562,
"text": "If a compiler is to handle a small amount of data, then the symbol table can be implemented as an unordered list, which is easy to code, but it is only suitable for small tables only. A symbol table can be implemented in one of the following ways:"
},
{
"code": null,
"e": 3843,
"s": 3810,
"text": "Linear (sorted or unsorted) list"
},
{
"code": null,
"e": 3862,
"s": 3843,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 3873,
"s": 3862,
"text": "Hash table"
},
{
"code": null,
"e": 4073,
"s": 3873,
"text": "Among all, symbol tables are mostly implemented as hash tables, where the source code symbol itself is treated as a key for the hash function and the return value is the information about the symbol."
},
{
"code": null,
"e": 4153,
"s": 4073,
"text": "A symbol table, either linear or hash, should provide the following operations."
},
{
"code": null,
"e": 4511,
"s": 4153,
"text": "This operation is more frequently used by analysis phase, i.e., the first half of the compiler where tokens are identified and names are stored in the table. This operation is used to add information in the symbol table about unique names occurring in the source code. The format or structure in which the names are stored depends upon the compiler in hand."
},
{
"code": null,
"e": 4801,
"s": 4511,
"text": "An attribute for a symbol in the source code is the information associated with that symbol. This information contains the value, state, scope, and type about the symbol. The insert() function takes the symbol and its attributes as arguments and stores the information in the symbol table."
},
{
"code": null,
"e": 4814,
"s": 4801,
"text": "For example:"
},
{
"code": null,
"e": 4821,
"s": 4814,
"text": "int a;"
},
{
"code": null,
"e": 4861,
"s": 4821,
"text": "should be processed by the compiler as:"
},
{
"code": null,
"e": 4877,
"s": 4861,
"text": "insert(a, int);"
},
{
"code": null,
"e": 4955,
"s": 4877,
"text": "lookup() operation is used to search a name in the symbol table to determine:"
},
{
"code": null,
"e": 4990,
"s": 4955,
"text": "if the symbol exists in the table."
},
{
"code": null,
"e": 5033,
"s": 4990,
"text": "if it is declared before it is being used."
},
{
"code": null,
"e": 5067,
"s": 5033,
"text": "if the name is used in the scope."
},
{
"code": null,
"e": 5097,
"s": 5067,
"text": "if the symbol is initialized."
},
{
"code": null,
"e": 5136,
"s": 5097,
"text": "if the symbol declared multiple times."
},
{
"code": null,
"e": 5259,
"s": 5136,
"text": "The format of lookup() function varies according to the programming language. The basic format should match the following:"
},
{
"code": null,
"e": 5274,
"s": 5259,
"text": "lookup(symbol)"
},
{
"code": null,
"e": 5442,
"s": 5274,
"text": "This method returns 0 (zero) if the symbol does not exist in the symbol table. If the symbol exists in the symbol table, it returns its attributes stored in the table."
},
{
"code": null,
"e": 5629,
"s": 5442,
"text": "A compiler maintains two types of symbol tables: a global symbol table which can be accessed by all the procedures and scope symbol tables that are created for each scope in the program."
},
{
"code": null,
"e": 5747,
"s": 5629,
"text": "To determine the scope of a name, symbol tables are arranged in hierarchical structure as shown in the example below:"
},
{
"code": null,
"e": 6276,
"s": 5747,
"text": ". . . \nint value=10;\n\nvoid pro_one()\n {\n int one_1;\n int one_2;\n \n { \\\n int one_3; |_ inner scope 1 \n int one_4; | \n } /\n \n int one_5; \n \n { \\ \n int one_6; |_ inner scope 2\n int one_7; |\n } /\n }\n \nvoid pro_two()\n {\n int two_1;\n int two_2;\n \n { \\\n int two_3; |_ inner scope 3\n int two_4; |\n } /\n \n int two_5;\n }\n. . . "
},
{
"code": null,
"e": 6359,
"s": 6276,
"text": "The above program can be represented in a hierarchical structure of symbol tables:"
},
{
"code": null,
"e": 6656,
"s": 6359,
"text": "The global symbol table contains names for one global variable (int value) and two procedure names, which should be available to all the child nodes shown above. The names mentioned in the pro_one symbol table (and all its child tables) are not available for pro_two symbols and its child tables."
},
{
"code": null,
"e": 6840,
"s": 6656,
"text": "This symbol table data structure hierarchy is stored in the semantic analyzer and whenever a name needs to be searched in a symbol table, it is searched using the following algorithm:"
},
{
"code": null,
"e": 6921,
"s": 6840,
"text": "first a symbol will be searched in the current scope, i.e. current symbol table."
},
{
"code": null,
"e": 7002,
"s": 6921,
"text": "first a symbol will be searched in the current scope, i.e. current symbol table."
},
{
"code": null,
"e": 7107,
"s": 7002,
"text": "if a name is found, then search is completed, else it will be searched in the parent symbol table until,"
},
{
"code": null,
"e": 7212,
"s": 7107,
"text": "if a name is found, then search is completed, else it will be searched in the parent symbol table until,"
},
{
"code": null,
"e": 7292,
"s": 7212,
"text": "either the name is found or global symbol table has been searched for the name."
},
{
"code": null,
"e": 7372,
"s": 7292,
"text": "either the name is found or global symbol table has been searched for the name."
},
{
"code": null,
"e": 7407,
"s": 7372,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7426,
"s": 7407,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7433,
"s": 7426,
"text": " Print"
},
{
"code": null,
"e": 7444,
"s": 7433,
"text": " Add Notes"
}
] |
C/C++ program for Armstrong Numbers - GeeksforGeeks
|
11 Jul, 2020
Given a number N, the task is to check whether the given number is Armstrong number or not. If the given number is Armstrong Number then print “Yes” else print “No”.
A positive integer of D digits is called an armstrong-numbers of order D (order is the number of digits) ifWhere D is number of digit in number Nand N(1), N(2), N(3)... are digit of number N.
Examples:
Input: N = 153Output: YesExplanation:153 is an Armstrong number.1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120Output: NoExplanation:120 is not an Armstrong number.1*1*1 + 2*2*2 + 0*0*0 = 9
Approach: The idea is to count the number of digits(say d) in the given number N. For every digit(say r) in the given number N find the value of rd and if the summation of all the values is N then print “Yes” else print “No”.
Below is the implementation of the above approach:
C
C++
// C program to find Armstrong number#include <stdio.h> // Function to calculate N raised// to the power Dint power(int N, unsigned int D){ if (D == 0) return 1; if (D % 2 == 0) return power(N, D / 2) * power(N, D / 2); return N * power(N, D / 2) * power(N, D / 2);} // Function to calculate the order of// the numberint order(int N){ int r = 0; // For each digit while (N) { r++; N = N / 10; } return r;} // Function to check whether the given// number is Armstrong number or notint isArmstrong(int N){ // Calling order function int D = order(N); int temp = N, sum = 0; // For each digit while (temp) { int Ni = temp % 10; sum += power(Ni, D); temp = temp / 10; } // If satisfies Armstrong condition if (sum == N) return 1; else return 0;} // Driver Codeint main(){ // Given Number N int N = 153; // Function Call if (isArmstrong(N) == 1) printf("True\n"); else printf("False\n"); return 0;}
// C++ program to find Armstrong number#include <bits/stdc++.h>using namespace std; // Function to calculate N raised// to the power Dint power(int N, unsigned int D){ if (D == 0) return 1; if (D % 2 == 0) return power(N, D / 2) * power(N, D / 2); return N * power(N, D / 2) * power(N, D / 2);} // Function to calculate the order of// the numberint order(int N){ int r = 0; // For each digit while (N) { r++; N = N / 10; } return r;} // Function to check whether the given// number is Armstrong number or notint isArmstrong(int N){ // To find order of N int D = order(N); int temp = N, sum = 0; // Traverse each digit while (temp) { int Ni = temp % 10; sum += power(Ni, D); temp = temp / 10; } // If satisfies Armstrong condition if (sum == N) return 1; else return 0;} // Driver Codeint main(){ // Given Number N int N = 153; // Function Call if (isArmstrong(N) == 1) cout << "True"; else cout << "False"; return 0;}
True
Time Complexity: O(log10N)Auxiliary Space: O(1)
number-digits
number-theory
Numbers
C Programs
C++ Programs
Mathematical
number-theory
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
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
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25122,
"s": 25094,
"text": "\n11 Jul, 2020"
},
{
"code": null,
"e": 25288,
"s": 25122,
"text": "Given a number N, the task is to check whether the given number is Armstrong number or not. If the given number is Armstrong Number then print “Yes” else print “No”."
},
{
"code": null,
"e": 25480,
"s": 25288,
"text": "A positive integer of D digits is called an armstrong-numbers of order D (order is the number of digits) ifWhere D is number of digit in number Nand N(1), N(2), N(3)... are digit of number N."
},
{
"code": null,
"e": 25490,
"s": 25480,
"text": "Examples:"
},
{
"code": null,
"e": 25582,
"s": 25490,
"text": "Input: N = 153Output: YesExplanation:153 is an Armstrong number.1*1*1 + 5*5*5 + 3*3*3 = 153"
},
{
"code": null,
"e": 25671,
"s": 25582,
"text": "Input: 120Output: NoExplanation:120 is not an Armstrong number.1*1*1 + 2*2*2 + 0*0*0 = 9"
},
{
"code": null,
"e": 25897,
"s": 25671,
"text": "Approach: The idea is to count the number of digits(say d) in the given number N. For every digit(say r) in the given number N find the value of rd and if the summation of all the values is N then print “Yes” else print “No”."
},
{
"code": null,
"e": 25948,
"s": 25897,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25950,
"s": 25948,
"text": "C"
},
{
"code": null,
"e": 25954,
"s": 25950,
"text": "C++"
},
{
"code": "// C program to find Armstrong number#include <stdio.h> // Function to calculate N raised// to the power Dint power(int N, unsigned int D){ if (D == 0) return 1; if (D % 2 == 0) return power(N, D / 2) * power(N, D / 2); return N * power(N, D / 2) * power(N, D / 2);} // Function to calculate the order of// the numberint order(int N){ int r = 0; // For each digit while (N) { r++; N = N / 10; } return r;} // Function to check whether the given// number is Armstrong number or notint isArmstrong(int N){ // Calling order function int D = order(N); int temp = N, sum = 0; // For each digit while (temp) { int Ni = temp % 10; sum += power(Ni, D); temp = temp / 10; } // If satisfies Armstrong condition if (sum == N) return 1; else return 0;} // Driver Codeint main(){ // Given Number N int N = 153; // Function Call if (isArmstrong(N) == 1) printf(\"True\\n\"); else printf(\"False\\n\"); return 0;}",
"e": 27035,
"s": 25954,
"text": null
},
{
"code": "// C++ program to find Armstrong number#include <bits/stdc++.h>using namespace std; // Function to calculate N raised// to the power Dint power(int N, unsigned int D){ if (D == 0) return 1; if (D % 2 == 0) return power(N, D / 2) * power(N, D / 2); return N * power(N, D / 2) * power(N, D / 2);} // Function to calculate the order of// the numberint order(int N){ int r = 0; // For each digit while (N) { r++; N = N / 10; } return r;} // Function to check whether the given// number is Armstrong number or notint isArmstrong(int N){ // To find order of N int D = order(N); int temp = N, sum = 0; // Traverse each digit while (temp) { int Ni = temp % 10; sum += power(Ni, D); temp = temp / 10; } // If satisfies Armstrong condition if (sum == N) return 1; else return 0;} // Driver Codeint main(){ // Given Number N int N = 153; // Function Call if (isArmstrong(N) == 1) cout << \"True\"; else cout << \"False\"; return 0;}",
"e": 28141,
"s": 27035,
"text": null
},
{
"code": null,
"e": 28147,
"s": 28141,
"text": "True\n"
},
{
"code": null,
"e": 28195,
"s": 28147,
"text": "Time Complexity: O(log10N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28209,
"s": 28195,
"text": "number-digits"
},
{
"code": null,
"e": 28223,
"s": 28209,
"text": "number-theory"
},
{
"code": null,
"e": 28231,
"s": 28223,
"text": "Numbers"
},
{
"code": null,
"e": 28242,
"s": 28231,
"text": "C Programs"
},
{
"code": null,
"e": 28255,
"s": 28242,
"text": "C++ Programs"
},
{
"code": null,
"e": 28268,
"s": 28255,
"text": "Mathematical"
},
{
"code": null,
"e": 28282,
"s": 28268,
"text": "number-theory"
},
{
"code": null,
"e": 28295,
"s": 28282,
"text": "Mathematical"
},
{
"code": null,
"e": 28303,
"s": 28295,
"text": "Numbers"
},
{
"code": null,
"e": 28401,
"s": 28303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28442,
"s": 28401,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28477,
"s": 28442,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 28536,
"s": 28477,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 28579,
"s": 28536,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 28623,
"s": 28579,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 28658,
"s": 28623,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 28717,
"s": 28658,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 28743,
"s": 28717,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 28787,
"s": 28743,
"text": "Program to print ASCII Value of a character"
}
] |
Matplotlib Styles for Scientific Plotting | by Rizky Maulana N | Towards Data Science
|
There are at least two inspirations in writing this story. The first inspiration is coming from my participation in Summer School on Galaxies and Cosmology (SSGC 2020). It has three parts: Public Lecture, Lectures, and Workshops. One of the Workshops analyzed the weak gravitational lensing using Oguri et al. (2012) as the primary reference. Oguri-san gave the participants his code to analyze the lensing, including the Maptlotlib parameter settings. I won’t talk about the gravitational lensing, but how to generate a professional plot using Matplotlib, as shown in Oguri-san paper.
The other one comes from when I was reading the General Instructions to submit an article in Monthly Notices of the Royal Astronomical Society (MNRAS), one of the world’s leading primary research journals in astronomy and astrophysics. One of the parts in the instructions is how to embed figures in MNRAS. The authors are advised to ensure the color used in their figures are color-blind friendly. Here, I quote the instruction.
Where possible, please ensure that your figures are color-blind friendly. The use of red and green in the same figure is particularly problematic for some readers (General Instructions from MNRAS)
I was surprised by the instruction. I did not realize that we need to provide color-blind friendly in my figures/plots because I have no problem with color. After understanding it, I suggest you (all of the readers) perform color-blind friendly in your figures/plots. I will explain more about color blindness in the next part.
This story will guide you on how to:
Customize Matplotlib parameters, using plotting style and rcParamsChoose color-blind friendly
Customize Matplotlib parameters, using plotting style and rcParams
Choose color-blind friendly
This story is significant for you who boost your data visualization skills because I will share how to generate professional plots based on the main goals mentioned before. So, let’s start it.
Matplotlib provides users the style package to customize plotting style. If you did not change the style, you would get a default style, as shown in Figure 1.
By default, the background color is white, and the first color for the plot is blue. You can change it using style syntax, as shown in the following code.
import matplotlib as pltplt.style.use('fivethirtyeight') # fivethirtyeight is name of style
After applying it, you will get the result, as shown in Figure 2.
It’s pretty cool, I think. How about the other styles? How many styles Matplotlib provides? You can check it using this code.
print(plt.style.available)
You will get all available styles provided by Matplotlib, as shown in Figure 3.
Can you count it? :D. There are 26 different styles you can use in Matplotlib. I have generated plots using all of the plotting styles, but I will show you just four of them, as shown in Figure 4.
I suggest you check all the plotting styles in Matplotlib, choose your favorite styles, and make it your default style. If you want to reset the plotting style, you can use this code.
plt.style.use('default')
Back to this story’s inspiration, I will show the figure example used by Oguri-san in his paper, as shown in Figure 5.
Customize Matplotlib parameters using rcParamsThere are seven settings that I will share with you using rcParams in Matplotlib. They are using LaTeX font, customizing font size, adjusting legend text length, customizing axes line width, changing x-axis and y-axis tick direction, and the last is adjusting the major and minor size for the x-axis and y-axis tick. Let’s discuss it one by one.
Use LaTeX font
As you can see in Figure 5, Oguri-san uses LaTeX for his plots. For many people, they need some special symbol which is hidden by Matplotlib. In Matplotlib, the LaTeX font is deactivated by default. To activate it, you can use this code.
plt.rcParams['text.usetex'] = True
You can visit my other story that explains more detail about using LaTeX font in Matplotlib by clicking this link.
towardsdatascience.com
If I apply the LaTeX font in Figure 4, I will get a different result, as shown in Figure 6. You can compare the font used in the title, axis, tick, and the text in Figure 4 and Figure 6.
Adjust font size
You can adjust the font size using this code.
plt.rcParams[‘font.size’] = 15
Matplotlib gives you 10, given in pts, as the default font size. In the code above, I change it from 10 to 18 pts. Parameter font.size control all text size, including title, x-axis and y-axis label, the x-axis and y-axis tick, legend, text, and annotation. You can change the font size for each element (for example, title) using another code. For example, you want to adjust all of the text sizes to 18, but the legend will be 20. You can adjust it with this code.
plt.rcParams[‘font.size’] = 15plt.rcParams['legend.fontsize'] = 18
You will get different representations of the font size if you declare a different figure size, even if you have the same font size. This condition is shown in Figure 7.
The difference between the two plots in Figure 7 is from the calibration of font size in pts.
Change x-axis and y-axis tick direction
If you see the Oguri-san plot (Figure 5) in more detail, you will see that the tick direction in the x-axis and y-axis is in the axes, not outside of the axis. You can compare Figure 5 and Figure 7, especially in the tick direction.
By default, the direction of the tick (x-axis and y-axis) is in the axes. You can change it by typing the following code.
plt.rcParams['xtick.direction'] = 'out'plt.rcParams['ytick.direction'] = 'out'
There are three options you can use: in, out, and inout. You can see the different results of them in Figure 8.
Adjust major and minor tick size
In Figure 8, I think you can not see the difference between the three plots because the tick’s size is too small. How to make it bigger? You can change it using this code for the x-axis and y-axis.
plt.rcParams['xtick.major.size'] = 5.0plt.rcParams['xtick.minor.size'] = 3.0plt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0
Matplotlib gives you xtick and ytick major size of 3.5 and for minor tick is 2.0. To show the minor tick, you can use this code.
from matplotlib.ticker import MultipleLocatorax.xaxis.set_minor_locator(MultipleLocator(.5))ax.yaxis.set_minor_locator(MultipleLocator(.005))
Of course, you need to define ax using
fig, ax = plt.subplots(figsize=(xsize, ysize))
or
ax = plt.gca()
Here is the code to figure with configuring the minor tick
If you run the code, you will get a figure, as shown in Figure 9.
Adjust line width
In this part, I will share with you how to adjust the line width of the axes. You can use this code to adjust it.
plt.rcParams['axes.linewidth'] = 3.0
By default, the line width is set to 0.8, given in pts. I set it in 3.0 to feel the difference between the default setting and the updated version. If you add the code above in Figure 9, it will give the result shown in Figure 10.
As you see in Figure 10, the now minor tick is not visible because the minor tick size is smaller than the line width.
Adjust handle length
In the last part, I will demonstrate how to adjust the handle length and the distance between the text legend and its symbol. I think you will know more if you run the following code and analyze the result, as shown in Figure 11.
plt.rcParams['legend.handlelength'] = 5.0
You can see the difference in the legend box. I set it to 5.0 so that you can see the difference clearly.
Here is the full style to create scientific plots for your data visualization
fsize = 15tsize = 18tdir = 'in'major = 5.0minor = 3.0lwidth = 0.8lhandle = 2.0plt.style.use('default')plt.rcParams['text.usetex'] = Trueplt.rcParams['font.size'] = fsizeplt.rcParams['legend.fontsize'] = tsizeplt.rcParams['xtick.direction'] = tdirplt.rcParams['ytick.direction'] = tdirplt.rcParams['xtick.major.size'] = majorplt.rcParams['xtick.minor.size'] = minorplt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0plt.rcParams['axes.linewidth'] = lwidthplt.rcParams['legend.handlelength'] = lhandle
Color blindness (or color blindness — or more specific color vision deficiency (CVD)) is well known but hard to imagine if you are not suffering. Before I know the data from https://www.color-blindness.com/, I did not realize that people who have color blindness is not small, approximately every 1 in 12 men (8%) and 1 in 200 women (0.5%). So, if you want to generate figures/plots, please ensure it is color-blind friendly.
There are four types of color blindness, they are Protan Color Blindness, Deutan Color Blindness, Tritan Color Blindness / Tritanomaly, and Monochromacy and Achromatopsia. Detail information for each type can be accessed here.
One of the safest solutions you can use to deal with color blind is to avoid using red and green together. For simply, you can use the service from Gregor Aisch in https://gka.github.io/palettes. You can generate many palettes, which is color-blind friendly. To use it, first, you need to choose what palettes type you want to create. There are two options, sequential and diverging, as shown in Figure 12.
After that, in the same section (section number 1), you need to declare how many colors you want to generate. In this story, I will choose diverging colors, with the number of colors is 5.
In section 2, you can fill it with several colors you want in the Hex color code. If you just know the colors you want in RGB, you can transform it using this link. I choose these colors for the left panel.
#0051a2, #10542c, #ffd44f
and these colors for the right panel.
lightyellow, #ff005e, #93003a
In section 3, check correct lightness and bezier interpolation. If your choice colors are color-blind friendly, you will get the information “The palette is color-blind safe” in the right panel of section 3, as shown in Figure 13.
Then, scroll down in section 4, “Export the color codes in various formats.” You can pick the color code to generate from the colors in section 3. Here is the color code I got.
['#0051a2', '#97964a', '#ffd44f', '#f4777f', '#93003a']
How to apply it? Just declare it as your color in your plots. Here is the example of my plot, shown in Figure 14.
It’s still pretty and, of course, color-blind friendly. You can vary the colors you want to generate. Please ensure that you get the notification that says The palette is color-blind safe in section 2.
You can see the example of my chosen colors that is not color-blind friendly.
If you got a notification like that, please change the colors to help the people who have color blindness.
If you want to apply the colorblind-safe palettes to your colormaps, you need to build your own colormaps. You can learn how to create your own colormaps using my other story in the following link.
towardsdatascience.com
To boost your skills in data visualization using Matplotlib, you need to make a plotting template. It can be built by choosing your right plotting style, adjusting some basic parameters using rcParams, and choosing the color-blind friendly palettes. I hope this story can help you create scientific and professional plots considering some information I mentioned before.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
That’s all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story.
[1] Oguri, M et al., (2012) MNRAS Volume 420, Issue 4, March 2012, Pages 3213–3239, https://doi.org/10.1111/j.1365-2966.2011.20248.x
[2] MNRAS, General Instruction for Submission in MNRAS https://academic.oup.com/mnras/pages/General_Instructions
[3] Color Blindness https://www.color-blindness.com/
[4] Color-blind friendly palettes https://gka.github.io/palettes
[5] Color code transformation https://html-color-codes.info/convert-color-format/
|
[
{
"code": null,
"e": 633,
"s": 47,
"text": "There are at least two inspirations in writing this story. The first inspiration is coming from my participation in Summer School on Galaxies and Cosmology (SSGC 2020). It has three parts: Public Lecture, Lectures, and Workshops. One of the Workshops analyzed the weak gravitational lensing using Oguri et al. (2012) as the primary reference. Oguri-san gave the participants his code to analyze the lensing, including the Maptlotlib parameter settings. I won’t talk about the gravitational lensing, but how to generate a professional plot using Matplotlib, as shown in Oguri-san paper."
},
{
"code": null,
"e": 1063,
"s": 633,
"text": "The other one comes from when I was reading the General Instructions to submit an article in Monthly Notices of the Royal Astronomical Society (MNRAS), one of the world’s leading primary research journals in astronomy and astrophysics. One of the parts in the instructions is how to embed figures in MNRAS. The authors are advised to ensure the color used in their figures are color-blind friendly. Here, I quote the instruction."
},
{
"code": null,
"e": 1260,
"s": 1063,
"text": "Where possible, please ensure that your figures are color-blind friendly. The use of red and green in the same figure is particularly problematic for some readers (General Instructions from MNRAS)"
},
{
"code": null,
"e": 1588,
"s": 1260,
"text": "I was surprised by the instruction. I did not realize that we need to provide color-blind friendly in my figures/plots because I have no problem with color. After understanding it, I suggest you (all of the readers) perform color-blind friendly in your figures/plots. I will explain more about color blindness in the next part."
},
{
"code": null,
"e": 1625,
"s": 1588,
"text": "This story will guide you on how to:"
},
{
"code": null,
"e": 1719,
"s": 1625,
"text": "Customize Matplotlib parameters, using plotting style and rcParamsChoose color-blind friendly"
},
{
"code": null,
"e": 1786,
"s": 1719,
"text": "Customize Matplotlib parameters, using plotting style and rcParams"
},
{
"code": null,
"e": 1814,
"s": 1786,
"text": "Choose color-blind friendly"
},
{
"code": null,
"e": 2007,
"s": 1814,
"text": "This story is significant for you who boost your data visualization skills because I will share how to generate professional plots based on the main goals mentioned before. So, let’s start it."
},
{
"code": null,
"e": 2166,
"s": 2007,
"text": "Matplotlib provides users the style package to customize plotting style. If you did not change the style, you would get a default style, as shown in Figure 1."
},
{
"code": null,
"e": 2321,
"s": 2166,
"text": "By default, the background color is white, and the first color for the plot is blue. You can change it using style syntax, as shown in the following code."
},
{
"code": null,
"e": 2413,
"s": 2321,
"text": "import matplotlib as pltplt.style.use('fivethirtyeight') # fivethirtyeight is name of style"
},
{
"code": null,
"e": 2479,
"s": 2413,
"text": "After applying it, you will get the result, as shown in Figure 2."
},
{
"code": null,
"e": 2605,
"s": 2479,
"text": "It’s pretty cool, I think. How about the other styles? How many styles Matplotlib provides? You can check it using this code."
},
{
"code": null,
"e": 2632,
"s": 2605,
"text": "print(plt.style.available)"
},
{
"code": null,
"e": 2712,
"s": 2632,
"text": "You will get all available styles provided by Matplotlib, as shown in Figure 3."
},
{
"code": null,
"e": 2909,
"s": 2712,
"text": "Can you count it? :D. There are 26 different styles you can use in Matplotlib. I have generated plots using all of the plotting styles, but I will show you just four of them, as shown in Figure 4."
},
{
"code": null,
"e": 3093,
"s": 2909,
"text": "I suggest you check all the plotting styles in Matplotlib, choose your favorite styles, and make it your default style. If you want to reset the plotting style, you can use this code."
},
{
"code": null,
"e": 3118,
"s": 3093,
"text": "plt.style.use('default')"
},
{
"code": null,
"e": 3237,
"s": 3118,
"text": "Back to this story’s inspiration, I will show the figure example used by Oguri-san in his paper, as shown in Figure 5."
},
{
"code": null,
"e": 3629,
"s": 3237,
"text": "Customize Matplotlib parameters using rcParamsThere are seven settings that I will share with you using rcParams in Matplotlib. They are using LaTeX font, customizing font size, adjusting legend text length, customizing axes line width, changing x-axis and y-axis tick direction, and the last is adjusting the major and minor size for the x-axis and y-axis tick. Let’s discuss it one by one."
},
{
"code": null,
"e": 3644,
"s": 3629,
"text": "Use LaTeX font"
},
{
"code": null,
"e": 3882,
"s": 3644,
"text": "As you can see in Figure 5, Oguri-san uses LaTeX for his plots. For many people, they need some special symbol which is hidden by Matplotlib. In Matplotlib, the LaTeX font is deactivated by default. To activate it, you can use this code."
},
{
"code": null,
"e": 3917,
"s": 3882,
"text": "plt.rcParams['text.usetex'] = True"
},
{
"code": null,
"e": 4032,
"s": 3917,
"text": "You can visit my other story that explains more detail about using LaTeX font in Matplotlib by clicking this link."
},
{
"code": null,
"e": 4055,
"s": 4032,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4242,
"s": 4055,
"text": "If I apply the LaTeX font in Figure 4, I will get a different result, as shown in Figure 6. You can compare the font used in the title, axis, tick, and the text in Figure 4 and Figure 6."
},
{
"code": null,
"e": 4259,
"s": 4242,
"text": "Adjust font size"
},
{
"code": null,
"e": 4305,
"s": 4259,
"text": "You can adjust the font size using this code."
},
{
"code": null,
"e": 4336,
"s": 4305,
"text": "plt.rcParams[‘font.size’] = 15"
},
{
"code": null,
"e": 4803,
"s": 4336,
"text": "Matplotlib gives you 10, given in pts, as the default font size. In the code above, I change it from 10 to 18 pts. Parameter font.size control all text size, including title, x-axis and y-axis label, the x-axis and y-axis tick, legend, text, and annotation. You can change the font size for each element (for example, title) using another code. For example, you want to adjust all of the text sizes to 18, but the legend will be 20. You can adjust it with this code."
},
{
"code": null,
"e": 4870,
"s": 4803,
"text": "plt.rcParams[‘font.size’] = 15plt.rcParams['legend.fontsize'] = 18"
},
{
"code": null,
"e": 5040,
"s": 4870,
"text": "You will get different representations of the font size if you declare a different figure size, even if you have the same font size. This condition is shown in Figure 7."
},
{
"code": null,
"e": 5134,
"s": 5040,
"text": "The difference between the two plots in Figure 7 is from the calibration of font size in pts."
},
{
"code": null,
"e": 5174,
"s": 5134,
"text": "Change x-axis and y-axis tick direction"
},
{
"code": null,
"e": 5407,
"s": 5174,
"text": "If you see the Oguri-san plot (Figure 5) in more detail, you will see that the tick direction in the x-axis and y-axis is in the axes, not outside of the axis. You can compare Figure 5 and Figure 7, especially in the tick direction."
},
{
"code": null,
"e": 5529,
"s": 5407,
"text": "By default, the direction of the tick (x-axis and y-axis) is in the axes. You can change it by typing the following code."
},
{
"code": null,
"e": 5608,
"s": 5529,
"text": "plt.rcParams['xtick.direction'] = 'out'plt.rcParams['ytick.direction'] = 'out'"
},
{
"code": null,
"e": 5720,
"s": 5608,
"text": "There are three options you can use: in, out, and inout. You can see the different results of them in Figure 8."
},
{
"code": null,
"e": 5753,
"s": 5720,
"text": "Adjust major and minor tick size"
},
{
"code": null,
"e": 5951,
"s": 5753,
"text": "In Figure 8, I think you can not see the difference between the three plots because the tick’s size is too small. How to make it bigger? You can change it using this code for the x-axis and y-axis."
},
{
"code": null,
"e": 6104,
"s": 5951,
"text": "plt.rcParams['xtick.major.size'] = 5.0plt.rcParams['xtick.minor.size'] = 3.0plt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0"
},
{
"code": null,
"e": 6233,
"s": 6104,
"text": "Matplotlib gives you xtick and ytick major size of 3.5 and for minor tick is 2.0. To show the minor tick, you can use this code."
},
{
"code": null,
"e": 6375,
"s": 6233,
"text": "from matplotlib.ticker import MultipleLocatorax.xaxis.set_minor_locator(MultipleLocator(.5))ax.yaxis.set_minor_locator(MultipleLocator(.005))"
},
{
"code": null,
"e": 6414,
"s": 6375,
"text": "Of course, you need to define ax using"
},
{
"code": null,
"e": 6461,
"s": 6414,
"text": "fig, ax = plt.subplots(figsize=(xsize, ysize))"
},
{
"code": null,
"e": 6464,
"s": 6461,
"text": "or"
},
{
"code": null,
"e": 6479,
"s": 6464,
"text": "ax = plt.gca()"
},
{
"code": null,
"e": 6538,
"s": 6479,
"text": "Here is the code to figure with configuring the minor tick"
},
{
"code": null,
"e": 6604,
"s": 6538,
"text": "If you run the code, you will get a figure, as shown in Figure 9."
},
{
"code": null,
"e": 6622,
"s": 6604,
"text": "Adjust line width"
},
{
"code": null,
"e": 6736,
"s": 6622,
"text": "In this part, I will share with you how to adjust the line width of the axes. You can use this code to adjust it."
},
{
"code": null,
"e": 6773,
"s": 6736,
"text": "plt.rcParams['axes.linewidth'] = 3.0"
},
{
"code": null,
"e": 7004,
"s": 6773,
"text": "By default, the line width is set to 0.8, given in pts. I set it in 3.0 to feel the difference between the default setting and the updated version. If you add the code above in Figure 9, it will give the result shown in Figure 10."
},
{
"code": null,
"e": 7123,
"s": 7004,
"text": "As you see in Figure 10, the now minor tick is not visible because the minor tick size is smaller than the line width."
},
{
"code": null,
"e": 7144,
"s": 7123,
"text": "Adjust handle length"
},
{
"code": null,
"e": 7374,
"s": 7144,
"text": "In the last part, I will demonstrate how to adjust the handle length and the distance between the text legend and its symbol. I think you will know more if you run the following code and analyze the result, as shown in Figure 11."
},
{
"code": null,
"e": 7416,
"s": 7374,
"text": "plt.rcParams['legend.handlelength'] = 5.0"
},
{
"code": null,
"e": 7522,
"s": 7416,
"text": "You can see the difference in the legend box. I set it to 5.0 so that you can see the difference clearly."
},
{
"code": null,
"e": 7600,
"s": 7522,
"text": "Here is the full style to create scientific plots for your data visualization"
},
{
"code": null,
"e": 8125,
"s": 7600,
"text": "fsize = 15tsize = 18tdir = 'in'major = 5.0minor = 3.0lwidth = 0.8lhandle = 2.0plt.style.use('default')plt.rcParams['text.usetex'] = Trueplt.rcParams['font.size'] = fsizeplt.rcParams['legend.fontsize'] = tsizeplt.rcParams['xtick.direction'] = tdirplt.rcParams['ytick.direction'] = tdirplt.rcParams['xtick.major.size'] = majorplt.rcParams['xtick.minor.size'] = minorplt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0plt.rcParams['axes.linewidth'] = lwidthplt.rcParams['legend.handlelength'] = lhandle"
},
{
"code": null,
"e": 8551,
"s": 8125,
"text": "Color blindness (or color blindness — or more specific color vision deficiency (CVD)) is well known but hard to imagine if you are not suffering. Before I know the data from https://www.color-blindness.com/, I did not realize that people who have color blindness is not small, approximately every 1 in 12 men (8%) and 1 in 200 women (0.5%). So, if you want to generate figures/plots, please ensure it is color-blind friendly."
},
{
"code": null,
"e": 8778,
"s": 8551,
"text": "There are four types of color blindness, they are Protan Color Blindness, Deutan Color Blindness, Tritan Color Blindness / Tritanomaly, and Monochromacy and Achromatopsia. Detail information for each type can be accessed here."
},
{
"code": null,
"e": 9185,
"s": 8778,
"text": "One of the safest solutions you can use to deal with color blind is to avoid using red and green together. For simply, you can use the service from Gregor Aisch in https://gka.github.io/palettes. You can generate many palettes, which is color-blind friendly. To use it, first, you need to choose what palettes type you want to create. There are two options, sequential and diverging, as shown in Figure 12."
},
{
"code": null,
"e": 9374,
"s": 9185,
"text": "After that, in the same section (section number 1), you need to declare how many colors you want to generate. In this story, I will choose diverging colors, with the number of colors is 5."
},
{
"code": null,
"e": 9581,
"s": 9374,
"text": "In section 2, you can fill it with several colors you want in the Hex color code. If you just know the colors you want in RGB, you can transform it using this link. I choose these colors for the left panel."
},
{
"code": null,
"e": 9607,
"s": 9581,
"text": "#0051a2, #10542c, #ffd44f"
},
{
"code": null,
"e": 9645,
"s": 9607,
"text": "and these colors for the right panel."
},
{
"code": null,
"e": 9675,
"s": 9645,
"text": "lightyellow, #ff005e, #93003a"
},
{
"code": null,
"e": 9906,
"s": 9675,
"text": "In section 3, check correct lightness and bezier interpolation. If your choice colors are color-blind friendly, you will get the information “The palette is color-blind safe” in the right panel of section 3, as shown in Figure 13."
},
{
"code": null,
"e": 10083,
"s": 9906,
"text": "Then, scroll down in section 4, “Export the color codes in various formats.” You can pick the color code to generate from the colors in section 3. Here is the color code I got."
},
{
"code": null,
"e": 10139,
"s": 10083,
"text": "['#0051a2', '#97964a', '#ffd44f', '#f4777f', '#93003a']"
},
{
"code": null,
"e": 10253,
"s": 10139,
"text": "How to apply it? Just declare it as your color in your plots. Here is the example of my plot, shown in Figure 14."
},
{
"code": null,
"e": 10455,
"s": 10253,
"text": "It’s still pretty and, of course, color-blind friendly. You can vary the colors you want to generate. Please ensure that you get the notification that says The palette is color-blind safe in section 2."
},
{
"code": null,
"e": 10533,
"s": 10455,
"text": "You can see the example of my chosen colors that is not color-blind friendly."
},
{
"code": null,
"e": 10640,
"s": 10533,
"text": "If you got a notification like that, please change the colors to help the people who have color blindness."
},
{
"code": null,
"e": 10838,
"s": 10640,
"text": "If you want to apply the colorblind-safe palettes to your colormaps, you need to build your own colormaps. You can learn how to create your own colormaps using my other story in the following link."
},
{
"code": null,
"e": 10861,
"s": 10838,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11232,
"s": 10861,
"text": "To boost your skills in data visualization using Matplotlib, you need to make a plotting template. It can be built by choosing your right plotting style, adjusting some basic parameters using rcParams, and choosing the color-blind friendly palettes. I hope this story can help you create scientific and professional plots considering some information I mentioned before."
},
{
"code": null,
"e": 11255,
"s": 11232,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11278,
"s": 11255,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11301,
"s": 11278,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11324,
"s": 11301,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11335,
"s": 11324,
"text": "medium.com"
},
{
"code": null,
"e": 11499,
"s": 11335,
"text": "That’s all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story."
},
{
"code": null,
"e": 11632,
"s": 11499,
"text": "[1] Oguri, M et al., (2012) MNRAS Volume 420, Issue 4, March 2012, Pages 3213–3239, https://doi.org/10.1111/j.1365-2966.2011.20248.x"
},
{
"code": null,
"e": 11745,
"s": 11632,
"text": "[2] MNRAS, General Instruction for Submission in MNRAS https://academic.oup.com/mnras/pages/General_Instructions"
},
{
"code": null,
"e": 11798,
"s": 11745,
"text": "[3] Color Blindness https://www.color-blindness.com/"
},
{
"code": null,
"e": 11863,
"s": 11798,
"text": "[4] Color-blind friendly palettes https://gka.github.io/palettes"
}
] |
Working with Page Break – Python .docx Module
|
03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module.
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also add page breaks using this module. To add a page break in a word document you can use add_page_break() method.
This method adds a hard page break in the document and creates a new paragraph object. This is an essential paragraph styling tool. Whenever the requirement is to start a new page, mostly cases where you want a new page for a new topic, a single method is sufficient. It helps increase clarity and improves presentation to reap the most of word.
Syntax: doc.add_page_break()
Import module
Create docx object
Add add_page_break() function whenever the control need to be shift to a new page
Save document.
Example:
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Adding a paragraphdoc.add_heading('Page 1:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Adding a page breakdoc.add_page_break() # Adding a paragraphdoc.add_heading('Page 2:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a locationdoc.save('gfg.docx')
Output:
Page – 1
Page – 2
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 48,
"s": 28,
"text": "Prerequisites: docx"
},
{
"code": null,
"e": 369,
"s": 48,
"text": "Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. "
},
{
"code": null,
"e": 727,
"s": 369,
"text": "Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also add page breaks using this module. To add a page break in a word document you can use add_page_break() method. "
},
{
"code": null,
"e": 1073,
"s": 727,
"text": "This method adds a hard page break in the document and creates a new paragraph object. This is an essential paragraph styling tool. Whenever the requirement is to start a new page, mostly cases where you want a new page for a new topic, a single method is sufficient. It helps increase clarity and improves presentation to reap the most of word."
},
{
"code": null,
"e": 1102,
"s": 1073,
"text": "Syntax: doc.add_page_break()"
},
{
"code": null,
"e": 1116,
"s": 1102,
"text": "Import module"
},
{
"code": null,
"e": 1135,
"s": 1116,
"text": "Create docx object"
},
{
"code": null,
"e": 1217,
"s": 1135,
"text": "Add add_page_break() function whenever the control need to be shift to a new page"
},
{
"code": null,
"e": 1232,
"s": 1217,
"text": "Save document."
},
{
"code": null,
"e": 1241,
"s": 1232,
"text": "Example:"
},
{
"code": null,
"e": 1249,
"s": 1241,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Adding a paragraphdoc.add_heading('Page 1:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Adding a page breakdoc.add_page_break() # Adding a paragraphdoc.add_heading('Page 2:', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a locationdoc.save('gfg.docx')",
"e": 1770,
"s": 1249,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Output:"
},
{
"code": null,
"e": 1787,
"s": 1778,
"text": "Page – 1"
},
{
"code": null,
"e": 1796,
"s": 1787,
"text": "Page – 2"
},
{
"code": null,
"e": 1820,
"s": 1796,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1827,
"s": 1820,
"text": "Python"
},
{
"code": null,
"e": 1846,
"s": 1827,
"text": "Technical Scripter"
}
] |
Top Hat and Black Hat Transform using Python-OpenCV
|
08 Jun, 2020
In morphology and digital image processing, top-hat and black-hat transform are operations that are used to extract small elements and details from given images. These two types of transforms in which, the top-hat transform is defined as the difference between the input image and its opening by some structuring element, while the black-hat transform is defined as the difference between the closing and the input image. These transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others.
Here we will use Opening and Closing morphological operations.
The top-hat filter is used to enhance bright objects of interest in a dark background. The black-hat operation is used to do the opposite, enhance dark objects of interest in a bright background.Example 1: Top-Hat Transform
Image used:
# Importing OpenCV import cv2 # Getting the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, filterSize) # Reading the image named 'input.jpg'input_image = cv2.imread("testing.jpg")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) # Applying the Top-Hat operationtophat_img = cv2.morphologyEx(input_image, cv2.MORPH_TOPHAT, kernel) cv2.imshow("original", input_image)cv2.imshow("tophat", tophat_img)cv2.waitKey(5000)
Output:
As you can observe in the above image, the very small details are enhanced and taken out using the Top-Hat operation. Hence, it is useful in observing the minor details of the inputs when are present as light pixels on a dark background.
Example 2: Black Hat transform
Input Image:
# Importing OpenCV and numpyimport cv2 # Defining the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, filterSize) # Reading the image named 'input.jpg'input_image = cv2.imread("testing.jpg")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) # Applying the Black-Hat operationtophat_img = cv2.morphologyEx(input_image, cv2.MORPH_BLACKHAT, kernel) cv2.imshow("original", input_image)cv2.imshow("tophat", tophat_img)cv2.waitKey(5000)
Output:
Here in this image, all the objects which are white on a dark background are highlighted due to the Black Hat transformation applied to the input image.
Image-Processing
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 596,
"s": 28,
"text": "In morphology and digital image processing, top-hat and black-hat transform are operations that are used to extract small elements and details from given images. These two types of transforms in which, the top-hat transform is defined as the difference between the input image and its opening by some structuring element, while the black-hat transform is defined as the difference between the closing and the input image. These transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others."
},
{
"code": null,
"e": 659,
"s": 596,
"text": "Here we will use Opening and Closing morphological operations."
},
{
"code": null,
"e": 883,
"s": 659,
"text": "The top-hat filter is used to enhance bright objects of interest in a dark background. The black-hat operation is used to do the opposite, enhance dark objects of interest in a bright background.Example 1: Top-Hat Transform"
},
{
"code": null,
"e": 895,
"s": 883,
"text": "Image used:"
},
{
"code": "# Importing OpenCV import cv2 # Getting the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, filterSize) # Reading the image named 'input.jpg'input_image = cv2.imread(\"testing.jpg\")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) # Applying the Top-Hat operationtophat_img = cv2.morphologyEx(input_image, cv2.MORPH_TOPHAT, kernel) cv2.imshow(\"original\", input_image)cv2.imshow(\"tophat\", tophat_img)cv2.waitKey(5000)",
"e": 1470,
"s": 895,
"text": null
},
{
"code": null,
"e": 1478,
"s": 1470,
"text": "Output:"
},
{
"code": null,
"e": 1716,
"s": 1478,
"text": "As you can observe in the above image, the very small details are enhanced and taken out using the Top-Hat operation. Hence, it is useful in observing the minor details of the inputs when are present as light pixels on a dark background."
},
{
"code": null,
"e": 1747,
"s": 1716,
"text": "Example 2: Black Hat transform"
},
{
"code": null,
"e": 1760,
"s": 1747,
"text": "Input Image:"
},
{
"code": "# Importing OpenCV and numpyimport cv2 # Defining the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, filterSize) # Reading the image named 'input.jpg'input_image = cv2.imread(\"testing.jpg\")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) # Applying the Black-Hat operationtophat_img = cv2.morphologyEx(input_image, cv2.MORPH_BLACKHAT, kernel) cv2.imshow(\"original\", input_image)cv2.imshow(\"tophat\", tophat_img)cv2.waitKey(5000)",
"e": 2346,
"s": 1760,
"text": null
},
{
"code": null,
"e": 2354,
"s": 2346,
"text": "Output:"
},
{
"code": null,
"e": 2507,
"s": 2354,
"text": "Here in this image, all the objects which are white on a dark background are highlighted due to the Black Hat transformation applied to the input image."
},
{
"code": null,
"e": 2524,
"s": 2507,
"text": "Image-Processing"
},
{
"code": null,
"e": 2538,
"s": 2524,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 2545,
"s": 2538,
"text": "Python"
},
{
"code": null,
"e": 2643,
"s": 2545,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2661,
"s": 2643,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2703,
"s": 2661,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2725,
"s": 2703,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2751,
"s": 2725,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2783,
"s": 2751,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2812,
"s": 2783,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2839,
"s": 2812,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2875,
"s": 2839,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2906,
"s": 2875,
"text": "Python | os.path.join() method"
}
] |
RTTI (Run-Time Type Information) in C++
|
18 May, 2022
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.
Runtime Casts
The runtime cast, which checks that the cast is valid, is the simplest approach to ascertain the runtime type of an object using a pointer or reference. This is especially beneficial when we need to cast a pointer from a base class to a derived type. When dealing with the inheritance hierarchy of classes, the casting of an object is usually required. There are two types of casting:
Upcasting: When a pointer or a reference of a derived class object is treated as a base class pointer.
Downcasting: When a base class pointer or reference is converted to a derived class pointer.
Using ‘dynamic_cast‘: In an inheritance hierarchy, it is used for downcasting a base class pointer to a child class. On successful casting, it returns a pointer of the converted type and, however, it fails if we try to cast an invalid type such as an object pointer that is not of the type of the desired subclass.
For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.
CPP
// C++ program to demonstrate// Run Time Type Identification(RTTI)// but without virtual function #include <iostream>using namespace std; // initialization of base classclass B {}; // initialization of derived classclass D : public B {}; // Driver Codeint main(){ B* b = new D; // Base class pointer D* d = dynamic_cast<D*>(b); // Derived class pointer if (d != NULL) cout << "works"; else cout << "cannot cast B* to D*"; getchar(); // to get the next character return 0;}
Adding a virtual function to the base class B makes it work.
CPP
// C++ program to demonstrate// Run Time Type Identification successfully// With virtual function #include <iostream>using namespace std; // Initialization of base classclass B { virtual void fun() {}}; // Initialization of Derived classclass D : public B {}; // Driver Codeint main(){ B* b = new D; // Base class pointer D* d = dynamic_cast<D*>(b); // Derived class pointer if (d != NULL) cout << "works"; else cout << "cannot cast B* to D*"; getchar(); return 0;}
works
anshikajain26
harsh_shokeen
rkbhola5
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 329,
"s": 54,
"text": "In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution."
},
{
"code": null,
"e": 343,
"s": 329,
"text": "Runtime Casts"
},
{
"code": null,
"e": 729,
"s": 343,
"text": "The runtime cast, which checks that the cast is valid, is the simplest approach to ascertain the runtime type of an object using a pointer or reference. This is especially beneficial when we need to cast a pointer from a base class to a derived type. When dealing with the inheritance hierarchy of classes, the casting of an object is usually required. There are two types of casting: "
},
{
"code": null,
"e": 832,
"s": 729,
"text": "Upcasting: When a pointer or a reference of a derived class object is treated as a base class pointer."
},
{
"code": null,
"e": 925,
"s": 832,
"text": "Downcasting: When a base class pointer or reference is converted to a derived class pointer."
},
{
"code": null,
"e": 1240,
"s": 925,
"text": "Using ‘dynamic_cast‘: In an inheritance hierarchy, it is used for downcasting a base class pointer to a child class. On successful casting, it returns a pointer of the converted type and, however, it fails if we try to cast an invalid type such as an object pointer that is not of the type of the desired subclass."
},
{
"code": null,
"e": 1481,
"s": 1240,
"text": "For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B."
},
{
"code": null,
"e": 1485,
"s": 1481,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// Run Time Type Identification(RTTI)// but without virtual function #include <iostream>using namespace std; // initialization of base classclass B {}; // initialization of derived classclass D : public B {}; // Driver Codeint main(){ B* b = new D; // Base class pointer D* d = dynamic_cast<D*>(b); // Derived class pointer if (d != NULL) cout << \"works\"; else cout << \"cannot cast B* to D*\"; getchar(); // to get the next character return 0;}",
"e": 1990,
"s": 1485,
"text": null
},
{
"code": null,
"e": 2052,
"s": 1990,
"text": " Adding a virtual function to the base class B makes it work."
},
{
"code": null,
"e": 2056,
"s": 2052,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// Run Time Type Identification successfully// With virtual function #include <iostream>using namespace std; // Initialization of base classclass B { virtual void fun() {}}; // Initialization of Derived classclass D : public B {}; // Driver Codeint main(){ B* b = new D; // Base class pointer D* d = dynamic_cast<D*>(b); // Derived class pointer if (d != NULL) cout << \"works\"; else cout << \"cannot cast B* to D*\"; getchar(); return 0;}",
"e": 2557,
"s": 2056,
"text": null
},
{
"code": null,
"e": 2563,
"s": 2557,
"text": "works"
},
{
"code": null,
"e": 2577,
"s": 2563,
"text": "anshikajain26"
},
{
"code": null,
"e": 2591,
"s": 2577,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 2600,
"s": 2591,
"text": "rkbhola5"
},
{
"code": null,
"e": 2604,
"s": 2600,
"text": "C++"
},
{
"code": null,
"e": 2608,
"s": 2604,
"text": "CPP"
}
] |
What is the Python Global Interpreter Lock (GIL)
|
06 Jan, 2019
Python Global Interpreter Lock (GIL) is a type of process lock which is used by python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. This means that in python only one thread will be executed at a time. The performance of the single-threaded process and the multi-threaded process will be the same in python and this is because of GIL in python. We can not achieve multithreading in python because we have global interpreter lock which restricts the threads and works as a single thread.
What problem did the GIL solve for Python :
Python has something that no other language has that is a reference counter. With the help of the reference counter, we can count the total number of references that are made internally in python to assign a value to a data object. Due to this counter, we can count the references and when this count reaches to zero the variable or data object will be released automatically. For Example
# Python program showing# use of reference counterimport sys geek_var = "Geek"print(sys.getrefcount(geek_var)) string_gfg = geek_varprint(sys.getrefcount(string_gfg))
Output:
4
5
This reference counter variable needed to be protected, because sometimes two threads increase or decrease its value simultaneously by doing that it may lead to memory leaked so in order to protect thread we add locks to all data structures that are shared across threads but sometimes by adding locks there exists a multiple locks which lead to another problem that is deadlock. In order to avoid memory leaked and deadlocks problem, we used single lock on the interpreter that is Global Interpreter Lock(GIL). Why was the GIL chosen as the solution :Python supports C language in the backend and all the related libraries that python have are mostly written in C and C++. Due to GIL, Python provides a better way to deal with thread-safe memory management. Global Interpreter Lock is easy to implement in python as it only needs to provide a single lock to a thread for processing in python. The GIL is simple to implement and was easily added to Python. It provides a performance increase to single-threaded programs as only one lock needs to be managed. Impact on multi-threaded Python programs :When a user writes Python programs or any computer programs then there’s a difference between those that are CPU-bound in their performance and those that are I/O-bound. CPU push the program to its limits by performing many operations simultaneously whereas I/O program had to spend time waiting for Input/Output. For ExampleCode 1: CPU bound program that perform simple countdown
# Python program showing# CPU bound program import timefrom threading import Thread COUNT = 50000000 def countdown(n): while n>0: n -= 1 start = time.time()countdown(COUNT)end = time.time() print('Time taken in seconds -', end - start)
Output:
Time taken in seconds - 2.5236213207244873
Code 2: Two threads running parallel
# Python program showing# two threads running parallel import timefrom threading import Thread COUNT = 50000000 def countdown(n): while n>0: n -= 1 t1 = Thread(target = countdown, args =(COUNT//2, ))t2 = Thread(target = countdown, args =(COUNT//2, )) start = time.time()t1.start()t2.start()t1.join()t2.join()end = time.time() print('Time taken in seconds -', end - start)
Output:
Time taken in seconds - 2.183610439300537
As you can see, In the above code two code where CPU bound process and multi-threaded process have the same performance because in CPU bound program because GIL restricts CPU to only work with a single thread. The impact of CPU bound thread and multi-threading will be the same in python.
Why hasn’t the GIL been removed yet :
GIL is not improved as of now because python 2 having GIL implementation and if we change this in python 3 then it will create a problem for us. So instead of removing GIL, we improve the concept of GIL. It’s one of the reasons to not remove the GIL at yet is python heavily depends on C in the backend and C extension heavily depends on the implementation methods of GIL. Although there are many more methods to solve the problems that GIL solve most of them are difficult to implement and can slow down the system.
How to deal with Python’s GIL :
Most of the time we use the multiprocessing to prevent the program from GIL. In this implementation, python provide a different interpreter to each process to run so in this case the single thread is provided to each process in multi-processing.
# Python program showing # multiprocessing import multiprocessing import time COUNT = 50000000 def countdown(n): while n>0: n -= 1 if __name__ == "__main__": # creating processes start = time.time() p1 = multiprocessing.Process(target = countdown, args =(COUNT//2, )) p2 = multiprocessing.Process(target = countdown, args =(COUNT//2, )) # starting process 1 p1.start() # starting process 2 p2.start() # wait until process 1 is finished p1.join() # wait until process 2 is finished p2.join() end = time.time() print('Time taken in seconds -', end - start)
Output:
Time taken in seconds - 2.5148496627807617
As you can see that there is no difference between the time taken by the multi-threaded system and the multi-processing system. This is because a multi-processing system has their own problems to solve. So this will not solve the problem but yes it provides the solution that GIL allows to be performed by python.
Picked
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jan, 2019"
},
{
"code": null,
"e": 614,
"s": 52,
"text": "Python Global Interpreter Lock (GIL) is a type of process lock which is used by python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. This means that in python only one thread will be executed at a time. The performance of the single-threaded process and the multi-threaded process will be the same in python and this is because of GIL in python. We can not achieve multithreading in python because we have global interpreter lock which restricts the threads and works as a single thread."
},
{
"code": null,
"e": 658,
"s": 614,
"text": "What problem did the GIL solve for Python :"
},
{
"code": null,
"e": 1047,
"s": 658,
"text": "Python has something that no other language has that is a reference counter. With the help of the reference counter, we can count the total number of references that are made internally in python to assign a value to a data object. Due to this counter, we can count the references and when this count reaches to zero the variable or data object will be released automatically. For Example"
},
{
"code": "# Python program showing# use of reference counterimport sys geek_var = \"Geek\"print(sys.getrefcount(geek_var)) string_gfg = geek_varprint(sys.getrefcount(string_gfg))",
"e": 1216,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1224,
"s": 1216,
"text": "Output:"
},
{
"code": null,
"e": 1229,
"s": 1224,
"text": "4\n5\n"
},
{
"code": null,
"e": 2710,
"s": 1229,
"text": "This reference counter variable needed to be protected, because sometimes two threads increase or decrease its value simultaneously by doing that it may lead to memory leaked so in order to protect thread we add locks to all data structures that are shared across threads but sometimes by adding locks there exists a multiple locks which lead to another problem that is deadlock. In order to avoid memory leaked and deadlocks problem, we used single lock on the interpreter that is Global Interpreter Lock(GIL). Why was the GIL chosen as the solution :Python supports C language in the backend and all the related libraries that python have are mostly written in C and C++. Due to GIL, Python provides a better way to deal with thread-safe memory management. Global Interpreter Lock is easy to implement in python as it only needs to provide a single lock to a thread for processing in python. The GIL is simple to implement and was easily added to Python. It provides a performance increase to single-threaded programs as only one lock needs to be managed. Impact on multi-threaded Python programs :When a user writes Python programs or any computer programs then there’s a difference between those that are CPU-bound in their performance and those that are I/O-bound. CPU push the program to its limits by performing many operations simultaneously whereas I/O program had to spend time waiting for Input/Output. For ExampleCode 1: CPU bound program that perform simple countdown"
},
{
"code": "# Python program showing# CPU bound program import timefrom threading import Thread COUNT = 50000000 def countdown(n): while n>0: n -= 1 start = time.time()countdown(COUNT)end = time.time() print('Time taken in seconds -', end - start)",
"e": 2961,
"s": 2710,
"text": null
},
{
"code": null,
"e": 2969,
"s": 2961,
"text": "Output:"
},
{
"code": null,
"e": 3013,
"s": 2969,
"text": "Time taken in seconds - 2.5236213207244873\n"
},
{
"code": null,
"e": 3050,
"s": 3013,
"text": "Code 2: Two threads running parallel"
},
{
"code": "# Python program showing# two threads running parallel import timefrom threading import Thread COUNT = 50000000 def countdown(n): while n>0: n -= 1 t1 = Thread(target = countdown, args =(COUNT//2, ))t2 = Thread(target = countdown, args =(COUNT//2, )) start = time.time()t1.start()t2.start()t1.join()t2.join()end = time.time() print('Time taken in seconds -', end - start)",
"e": 3438,
"s": 3050,
"text": null
},
{
"code": null,
"e": 3446,
"s": 3438,
"text": "Output:"
},
{
"code": null,
"e": 3489,
"s": 3446,
"text": "Time taken in seconds - 2.183610439300537\n"
},
{
"code": null,
"e": 3778,
"s": 3489,
"text": "As you can see, In the above code two code where CPU bound process and multi-threaded process have the same performance because in CPU bound program because GIL restricts CPU to only work with a single thread. The impact of CPU bound thread and multi-threading will be the same in python."
},
{
"code": null,
"e": 3816,
"s": 3778,
"text": "Why hasn’t the GIL been removed yet :"
},
{
"code": null,
"e": 4333,
"s": 3816,
"text": "GIL is not improved as of now because python 2 having GIL implementation and if we change this in python 3 then it will create a problem for us. So instead of removing GIL, we improve the concept of GIL. It’s one of the reasons to not remove the GIL at yet is python heavily depends on C in the backend and C extension heavily depends on the implementation methods of GIL. Although there are many more methods to solve the problems that GIL solve most of them are difficult to implement and can slow down the system."
},
{
"code": null,
"e": 4365,
"s": 4333,
"text": "How to deal with Python’s GIL :"
},
{
"code": null,
"e": 4611,
"s": 4365,
"text": "Most of the time we use the multiprocessing to prevent the program from GIL. In this implementation, python provide a different interpreter to each process to run so in this case the single thread is provided to each process in multi-processing."
},
{
"code": "# Python program showing # multiprocessing import multiprocessing import time COUNT = 50000000 def countdown(n): while n>0: n -= 1 if __name__ == \"__main__\": # creating processes start = time.time() p1 = multiprocessing.Process(target = countdown, args =(COUNT//2, )) p2 = multiprocessing.Process(target = countdown, args =(COUNT//2, )) # starting process 1 p1.start() # starting process 2 p2.start() # wait until process 1 is finished p1.join() # wait until process 2 is finished p2.join() end = time.time() print('Time taken in seconds -', end - start)",
"e": 5233,
"s": 4611,
"text": null
},
{
"code": null,
"e": 5241,
"s": 5233,
"text": "Output:"
},
{
"code": null,
"e": 5285,
"s": 5241,
"text": "Time taken in seconds - 2.5148496627807617\n"
},
{
"code": null,
"e": 5599,
"s": 5285,
"text": "As you can see that there is no difference between the time taken by the multi-threaded system and the multi-processing system. This is because a multi-processing system has their own problems to solve. So this will not solve the problem but yes it provides the solution that GIL allows to be performed by python."
},
{
"code": null,
"e": 5606,
"s": 5599,
"text": "Picked"
},
{
"code": null,
"e": 5630,
"s": 5606,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 5637,
"s": 5630,
"text": "Python"
},
{
"code": null,
"e": 5656,
"s": 5637,
"text": "Technical Scripter"
}
] |
Output of C++ programs | Set 43 (Decision and Control Statements)
|
05 Sep, 2017
Decision and Loops & Control StatementsQUE.1 What is the output of this program ?
#include <iostream>using namespace std;int main (){ int n; for (n = 5; n > 0; n--) { cout << n; if (n == 3) break; } return 0;}
OPTIONa) 543b) 54c) 5432d) 53
Answer: a
Explanation : In this program, we are printing the numbers in reverse order and by using break statement we stopped printing on 3.
QUE.2 What is the output of this program?
#include <iostream>using namespace std;int main(){ int a = 10; if (a < 15) { time: cout << a; goto time; } break; return 0;}
OPTIONa) 1010b) 10c) infinitely print 10d) compile time error
Answer: d
Explanation: Because the break statement needs to be presented inside a loop or a switch statement.
QUE. 3 What is the output of this program ?
#include <iostream>using namespace std;int main(){ int n = 15; for ( ; ; ) cout << n; return 0;}
OPTIONa) errorb) 15c) infinite times of printing nd) none of the mentioned
Answer: c
Explanation: There is no condition in the for loop, So it will loop continuously.
QUE.4 What is the output?
#include <iostream>using namespace std;int main(){ int i; for (i = 0; i < 10; i++); { cout << i; } return 0;}
OPTIONa) 0123456789b) 10c) 012345678910d) compile time error
Answer: b
Explanation: for loop with a semicolon is called as body less for loop. It is used only for incrementing the variable values. So, in this program the value is incremented and printed as 10.
QUE.5 what is output of this program?
#include <iostream>int i = 30;using namespace std;int main(){ int i = 10; for (i = 0; i < 5; i++) { int i = 20; cout << i <<" "; } return 0;}
OPTIONa) 0 1 2 3 4b) 10 10 10 10 10c) 20 20 20 20 20d) Compile Errors
Answer: c
Explanation: int i = 20 is initialized in the body of loop so it considers the value i = 20 inside loop only. For loop control, the i declared outside is used and loop runs 5 times and print 20 five times.
This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Sep, 2017"
},
{
"code": null,
"e": 136,
"s": 54,
"text": "Decision and Loops & Control StatementsQUE.1 What is the output of this program ?"
},
{
"code": "#include <iostream>using namespace std;int main (){ int n; for (n = 5; n > 0; n--) { cout << n; if (n == 3) break; } return 0;}",
"e": 304,
"s": 136,
"text": null
},
{
"code": null,
"e": 334,
"s": 304,
"text": "OPTIONa) 543b) 54c) 5432d) 53"
},
{
"code": null,
"e": 344,
"s": 334,
"text": "Answer: a"
},
{
"code": null,
"e": 475,
"s": 344,
"text": "Explanation : In this program, we are printing the numbers in reverse order and by using break statement we stopped printing on 3."
},
{
"code": null,
"e": 517,
"s": 475,
"text": "QUE.2 What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int a = 10; if (a < 15) { time: cout << a; goto time; } break; return 0;}",
"e": 681,
"s": 517,
"text": null
},
{
"code": null,
"e": 743,
"s": 681,
"text": "OPTIONa) 1010b) 10c) infinitely print 10d) compile time error"
},
{
"code": null,
"e": 754,
"s": 743,
"text": "Answer: d"
},
{
"code": null,
"e": 854,
"s": 754,
"text": "Explanation: Because the break statement needs to be presented inside a loop or a switch statement."
},
{
"code": null,
"e": 898,
"s": 854,
"text": "QUE. 3 What is the output of this program ?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int n = 15; for ( ; ; ) cout << n; return 0;}",
"e": 1007,
"s": 898,
"text": null
},
{
"code": null,
"e": 1082,
"s": 1007,
"text": "OPTIONa) errorb) 15c) infinite times of printing nd) none of the mentioned"
},
{
"code": null,
"e": 1092,
"s": 1082,
"text": "Answer: c"
},
{
"code": null,
"e": 1174,
"s": 1092,
"text": "Explanation: There is no condition in the for loop, So it will loop continuously."
},
{
"code": null,
"e": 1200,
"s": 1174,
"text": "QUE.4 What is the output?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i; for (i = 0; i < 10; i++); { cout << i; } return 0;}",
"e": 1332,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1393,
"s": 1332,
"text": "OPTIONa) 0123456789b) 10c) 012345678910d) compile time error"
},
{
"code": null,
"e": 1403,
"s": 1393,
"text": "Answer: b"
},
{
"code": null,
"e": 1593,
"s": 1403,
"text": "Explanation: for loop with a semicolon is called as body less for loop. It is used only for incrementing the variable values. So, in this program the value is incremented and printed as 10."
},
{
"code": null,
"e": 1631,
"s": 1593,
"text": "QUE.5 what is output of this program?"
},
{
"code": "#include <iostream>int i = 30;using namespace std;int main(){ int i = 10; for (i = 0; i < 5; i++) { int i = 20; cout << i <<\" \"; } return 0;}",
"e": 1802,
"s": 1631,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1802,
"text": "OPTIONa) 0 1 2 3 4b) 10 10 10 10 10c) 20 20 20 20 20d) Compile Errors"
},
{
"code": null,
"e": 1882,
"s": 1872,
"text": "Answer: c"
},
{
"code": null,
"e": 2088,
"s": 1882,
"text": "Explanation: int i = 20 is initialized in the body of loop so it considers the value i = 20 inside loop only. For loop control, the i declared outside is used and loop runs 5 times and print 20 five times."
},
{
"code": null,
"e": 2385,
"s": 2088,
"text": "This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2510,
"s": 2385,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2521,
"s": 2510,
"text": "CPP-Output"
},
{
"code": null,
"e": 2536,
"s": 2521,
"text": "Program Output"
}
] |
Python program to convert unix timestamp string to readable date
|
31 Oct, 2021
In this article, we are going to see the conversion of the Unix timestamp string to a readable date. This can be done with the help of fromtimestamp() and strftime() functions.
fromtimestamp(): The fromtimestamp() function is used to return the date and time corresponding to a specified timestamp.
Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method.
Syntax: @classmethod fromtimestamp(timestamp)
Parameters: This function accepts a parameter which is illustrated below:
timestamp: This is the specified timestamp for which the date is going to be returned.
Return values: This function returns the date and time corresponding to a specified timestamp.
strftime(): The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation.
Syntax: strftime(format)
Parameter: This function accepts a single parameter which is illustrated below:
format: This is the specified date and time object.
Return Values: It returns the string representation of the date or time object.
Example 1: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamp # Calling the strftime() function to convert# the extracted datetime into its string formatprint(datetime.datetime.fromtimestamp(int("1294113662")) .strftime('%Y-%m-%d %H:%M:%S'))
Output:
2011-01-04 04:01:02
Example 2: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamptimestamp = datetime.datetime.fromtimestamp(1200001234) # Calling the strftime() function to convert# the extracted datetime into its string formatprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2008-01-10 21:40:34
rajeev0719singh
clintra
anikakapoor
Picked
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "In this article, we are going to see the conversion of the Unix timestamp string to a readable date. This can be done with the help of fromtimestamp() and strftime() functions."
},
{
"code": null,
"e": 327,
"s": 205,
"text": "fromtimestamp(): The fromtimestamp() function is used to return the date and time corresponding to a specified timestamp."
},
{
"code": null,
"e": 515,
"s": 327,
"text": "Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method."
},
{
"code": null,
"e": 562,
"s": 515,
"text": "Syntax: @classmethod fromtimestamp(timestamp)"
},
{
"code": null,
"e": 636,
"s": 562,
"text": "Parameters: This function accepts a parameter which is illustrated below:"
},
{
"code": null,
"e": 723,
"s": 636,
"text": "timestamp: This is the specified timestamp for which the date is going to be returned."
},
{
"code": null,
"e": 818,
"s": 723,
"text": "Return values: This function returns the date and time corresponding to a specified timestamp."
},
{
"code": null,
"e": 1012,
"s": 818,
"text": "strftime(): The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation."
},
{
"code": null,
"e": 1037,
"s": 1012,
"text": "Syntax: strftime(format)"
},
{
"code": null,
"e": 1117,
"s": 1037,
"text": "Parameter: This function accepts a single parameter which is illustrated below:"
},
{
"code": null,
"e": 1169,
"s": 1117,
"text": "format: This is the specified date and time object."
},
{
"code": null,
"e": 1249,
"s": 1169,
"text": "Return Values: It returns the string representation of the date or time object."
},
{
"code": null,
"e": 1305,
"s": 1249,
"text": "Example 1: Convert the specified Unix timestamp string."
},
{
"code": null,
"e": 1312,
"s": 1305,
"text": "Python"
},
{
"code": "# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamp # Calling the strftime() function to convert# the extracted datetime into its string formatprint(datetime.datetime.fromtimestamp(int(\"1294113662\")) .strftime('%Y-%m-%d %H:%M:%S'))",
"e": 1719,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1727,
"s": 1719,
"text": "Output:"
},
{
"code": null,
"e": 1747,
"s": 1727,
"text": "2011-01-04 04:01:02"
},
{
"code": null,
"e": 1803,
"s": 1747,
"text": "Example 2: Convert the specified Unix timestamp string."
},
{
"code": null,
"e": 1810,
"s": 1803,
"text": "Python"
},
{
"code": "# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamptimestamp = datetime.datetime.fromtimestamp(1200001234) # Calling the strftime() function to convert# the extracted datetime into its string formatprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))",
"e": 2225,
"s": 1810,
"text": null
},
{
"code": null,
"e": 2233,
"s": 2225,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 2233,
"text": "2008-01-10 21:40:34"
},
{
"code": null,
"e": 2269,
"s": 2253,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2277,
"s": 2269,
"text": "clintra"
},
{
"code": null,
"e": 2289,
"s": 2277,
"text": "anikakapoor"
},
{
"code": null,
"e": 2296,
"s": 2289,
"text": "Picked"
},
{
"code": null,
"e": 2320,
"s": 2296,
"text": "Python datetime-program"
},
{
"code": null,
"e": 2327,
"s": 2320,
"text": "Python"
},
{
"code": null,
"e": 2343,
"s": 2327,
"text": "Python Programs"
}
] |
Second Normal Form (2NF)
|
25 Nov, 2019
First Normal Form (1NF) does not eliminate redundancy, but rather, it’s that it eliminates repeating groups.
Instead of having multiple columns of the same kind of data in a record, (0NF or Unnormalized form) you remove the repeated information into a separate relation and represent them as rows. This is what constitutes 1NF.
Second Normal Form (2NF):Second Normal Form (2NF) is based on the concept of full functional dependency. Second Normal Form applies to relations with composite keys, that is, relations with a primary key composed of two or more attributes. A relation with a single-attribute primary key is automatically in at least 2NF. A relation that is not in 2NF may suffer from the update anomalies.
To be in second normal form, a relation must be in first normal form and relation must not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency, i.e., no non-prime attribute (attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key of the table.
In other words,
A relation that is in First Normal Form and every non-primary-key attribute is fully functionally dependent on the primary key, then the relation is in Second Normal Form (2NF).
Note – If the proper subset of candidate key determines non-prime attribute, it is called partial dependency.
The normalization of 1NF relations to 2NF involves the removal of partial dependencies. If a partial dependency exists, we remove the partially dependent attribute(s) from the relation by placing them in a new relation along with a copy of their determinant.
Consider the examples given below.
Example-1:Consider table as following below.
STUD_NO COURSE_NO COURSE_FEE
1 C1 1000
2 C2 1500
1 C4 2000
4 C3 1000
4 C1 1000
2 C5 2000
{Note that, there are many courses having the same course fee. }
Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF.
To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE
Table 1 Table 2
STUD_NO COURSE_NO COURSE_NO COURSE_FEE
1 C1 C1 1000
2 C2 C2 1500
1 C4 C3 1000
4 C3 C4 2000
4 C1 C5 2000
2 C5
Note – 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we dont need to store its Fee as 1000 for all the 100 records, instead once we can store it in the second table as the course fee for C1 is 1000.
Example-2:Consider following functional dependencies in relation R (A, B, C, D )
AB -> C [A and B together determine C]
BC -> D [B and C together determine D]
In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute.
Groudon
DBMS-Normalization
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Trigger | Student Database
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 163,
"s": 54,
"text": "First Normal Form (1NF) does not eliminate redundancy, but rather, it’s that it eliminates repeating groups."
},
{
"code": null,
"e": 382,
"s": 163,
"text": "Instead of having multiple columns of the same kind of data in a record, (0NF or Unnormalized form) you remove the repeated information into a separate relation and represent them as rows. This is what constitutes 1NF."
},
{
"code": null,
"e": 771,
"s": 382,
"text": "Second Normal Form (2NF):Second Normal Form (2NF) is based on the concept of full functional dependency. Second Normal Form applies to relations with composite keys, that is, relations with a primary key composed of two or more attributes. A relation with a single-attribute primary key is automatically in at least 2NF. A relation that is not in 2NF may suffer from the update anomalies."
},
{
"code": null,
"e": 1099,
"s": 771,
"text": "To be in second normal form, a relation must be in first normal form and relation must not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency, i.e., no non-prime attribute (attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key of the table."
},
{
"code": null,
"e": 1115,
"s": 1099,
"text": "In other words,"
},
{
"code": null,
"e": 1293,
"s": 1115,
"text": "A relation that is in First Normal Form and every non-primary-key attribute is fully functionally dependent on the primary key, then the relation is in Second Normal Form (2NF)."
},
{
"code": null,
"e": 1403,
"s": 1293,
"text": "Note – If the proper subset of candidate key determines non-prime attribute, it is called partial dependency."
},
{
"code": null,
"e": 1662,
"s": 1403,
"text": "The normalization of 1NF relations to 2NF involves the removal of partial dependencies. If a partial dependency exists, we remove the partially dependent attribute(s) from the relation by placing them in a new relation along with a copy of their determinant."
},
{
"code": null,
"e": 1697,
"s": 1662,
"text": "Consider the examples given below."
},
{
"code": null,
"e": 1742,
"s": 1697,
"text": "Example-1:Consider table as following below."
},
{
"code": null,
"e": 2072,
"s": 1742,
"text": "STUD_NO COURSE_NO COURSE_FEE\n1 C1 1000\n2 C2 1500\n1 C4 2000\n4 C3 1000\n4 C1 1000\n2 C5 2000\n"
},
{
"code": null,
"e": 2137,
"s": 2072,
"text": "{Note that, there are many courses having the same course fee. }"
},
{
"code": null,
"e": 2742,
"s": 2137,
"text": "Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF."
},
{
"code": null,
"e": 2889,
"s": 2742,
"text": "To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE"
},
{
"code": null,
"e": 3426,
"s": 2889,
"text": " Table 1 Table 2\nSTUD_NO COURSE_NO COURSE_NO COURSE_FEE \n1 C1 C1 1000\n2 C2 C2 1500\n1 C4 C3 1000\n4 C3 C4 2000\n4 C1 C5 2000 \n2 C5 \n"
},
{
"code": null,
"e": 3702,
"s": 3426,
"text": "Note – 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we dont need to store its Fee as 1000 for all the 100 records, instead once we can store it in the second table as the course fee for C1 is 1000."
},
{
"code": null,
"e": 3788,
"s": 3702,
"text": "Example-2:Consider following functional dependencies in relation R (A, B, C, D )"
},
{
"code": null,
"e": 3868,
"s": 3788,
"text": "AB -> C [A and B together determine C]\nBC -> D [B and C together determine D]"
},
{
"code": null,
"e": 4029,
"s": 3868,
"text": "In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute."
},
{
"code": null,
"e": 4037,
"s": 4029,
"text": "Groudon"
},
{
"code": null,
"e": 4056,
"s": 4037,
"text": "DBMS-Normalization"
},
{
"code": null,
"e": 4061,
"s": 4056,
"text": "DBMS"
},
{
"code": null,
"e": 4069,
"s": 4061,
"text": "GATE CS"
},
{
"code": null,
"e": 4074,
"s": 4069,
"text": "DBMS"
},
{
"code": null,
"e": 4172,
"s": 4074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4183,
"s": 4172,
"text": "CTE in SQL"
},
{
"code": null,
"e": 4236,
"s": 4183,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 4294,
"s": 4236,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 4317,
"s": 4294,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 4348,
"s": 4317,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 4368,
"s": 4348,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 4395,
"s": 4368,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 4408,
"s": 4395,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 4457,
"s": 4408,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Find cells in Matrix that are not visited by Robot for given movements
|
27 Oct, 2021
Given an integer N, which denotes the size of the matrix that is N*N. There is a robot placed over the top-left corner (0, 0) of the matrix, the direction of movement of the robot are given as (N, S, W, E, NE, NW, SE, SW which denotes North, South, West, East, North-East, North-west, South-east, South-west respectively) and the duration of the movement in a particular direction is also given. The task is to find the unvisited cells of the matrix after the movement of the robot is completed at the end of all winds.
Note: Robot can visit a cell only once. If at any point robot cannot move then it will stay at its current position. Also, robot can make one move per second.
Examples:
Input: N = 3, move[] = {(0, SE), (2, N)}Output: 4Explanation:
Input: N = 5, move[] = {(0, SE), (1, NE), (2, E), (6, SW), (15, N), (20, W)}Output: 13Explanation: After the movements of the robot, there are 13 Cells unvisited.
Approach: The idea is to use recursion to solve this problem. Initially, set the current position of the robot as the (0, 0). Start the movement of the robot as per the given direction and mark the cells as visited of the matrix. Finally, After the complete movement of the robot mark count the cells of the matrix which are not marked as visited
Below code implements the approach discussed above:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// unvisited cells of the matrix #include <bits/stdc++.h> using namespace std; // Dimension// of the boardint n; // Current location// of the robotint curr_i = 0, curr_j = 0; // Function to move the robotvoid moveRobot( int n, int i, int j, int dx, int dy, int& duration, vector<vector<bool> >& visited){ // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy, duration, visited);} // Function to find the unvisited// cells of the matrix after movementvoid findUnvisited( int p, vector<pair<int, string> > periods){ // nXn matrix to store the // visited state of positions vector<vector<bool> > visited; // map to store the wind directions unordered_map<string, vector<int> > mp = { { "N", { -1, 0 } }, { "S", { 1, 0 } }, { "E", { 0, 1 } }, { "W", { 0, -1 } }, { "NE", { -1, 1 } }, { "NW", { -1, -1 } }, { "SE", { 1, 1 } }, { "SW", { 1, -1 } } }; // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.push_back(vector<bool>{}); for (int j = 0; j < n; j++) { visited[i].push_back(false); } } for (int i = 0; i < p; i++) { string dir = periods[i].second; int dx = mp[dir][0]; int dy = mp[dir][1]; // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1].first - periods[i].first; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy, duration, visited); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } cout << not_visited << "\n";} // Driver Codeint main(){ // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs vector<pair<int, string> > periods(p); periods[0] = { 0, "SE" }; periods[1] = { 1, "NE" }; periods[2] = { 2, "E" }; periods[3] = { 6, "SW" }; periods[4] = { 15, "N" }; periods[5] = { 20, "W" }; // Function Call findUnvisited(p, periods); return 0;}
// Java implementation to find the// unvisited cells of the matriximport java.util.*;import java.awt.Point; class pair{ int x; String y;} public class Main{ // Dimension // of the board static int n; // Current location // of the robot static int curr_i = 0, curr_j = 0; static int duration; // nXn matrix to store the // visited state of positions static Vector<Vector<Boolean>> visited = new Vector<Vector<Boolean>>(); // Function to move the robot static void moveRobot(int n, int i, int j, int dx, int dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited.get(i).get(j) == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited.get(i).set(j, true); // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement static void findUnvisited(int p, Vector<pair> periods) { // map to store the wind directions int[] array = new int[]{-1, 0}; Vector<Integer> l = new Vector<Integer>(); l.add(-1); l.add(0); HashMap<String, Vector<Integer>> mp = new HashMap<String, Vector<Integer>>(); mp.put("N", l); l.clear(); l.add(1); l.add(0); mp.put("S", l); l.clear(); l.add(0); l.add(1); mp.put("E", l); l.clear(); l.add(0); l.add(-1); mp.put("W", l); l.clear(); l.add(-1); l.add(1); mp.put("NE", l); l.clear(); l.add(-1); l.add(-1); mp.put("NW", l); l.clear(); l.add(1); l.add(1); mp.put("SE", l); l.clear(); l.add(1); l.add(-1); mp.put("SW", l); // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.add(new Vector<Boolean>()); for (int j = 0; j < n; j++) { visited.get(i).add(false); } } for (int i = 0; i < p; i++) { String dir = periods.get(i).y; int dx = mp.get(dir).get(0); int dy = mp.get(dir).get(1); // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods.get(i + 1).x - periods.get(i).x; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = (int)Math.sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited.get(next_i).get(next_j) == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited.get(i).get(j) == false) { not_visited++; } } } System.out.print(not_visited/2+1); } public static void main(String[] args) { // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs Vector<pair> periods = new Vector<pair>(); pair p1 = new pair(); p1.x = 0; p1.y = "SE"; periods.add(p1); p1 = new pair(); p1.x = 1; p1.y = "NE"; periods.add(p1); p1 = new pair(); p1.x = 2; p1.y = "E"; periods.add(p1); p1 = new pair(); p1.x = 6; p1.y = "SW"; periods.add(p1); p1 = new pair(); p1.x = 15; p1.y = "N"; periods.add(p1); p1 = new pair(); p1.x = 1; p1.y = "NE"; periods.add(p1); p1 = new pair(); p1.x = 20; p1.y = "W"; periods.add(p1); // Function Call findUnvisited(p, periods); }} // This code is contributed by rameshtravel07.
# Python3 implementation to find the# unvisited cells of the matriximport math # Dimension# of the boardn = 5 # Current location# of the robotcurr_i, curr_j = 0, 0duration = 0 # nXn matrix to store the# visited state of positionsvisited = [] # Function to move the robotdef moveRobot(n, i, j, dx, dy): global curr_i, curr_j, duration, visited # if the robot tends to move # out of the board # or tends to visit an # already visited position # or the wind direction is changed if i < 0 or i >= n or j < 0 or j >= n or visited[i][j] == True or duration == 0: # the robot can't move further # under the influence of # current wind direction return # Change the current location # and mark the current # position as visited curr_i = i curr_j = j visited[i][j] = True # One second passed # visiting this position duration-=1 moveRobot(n, i + dx, j + dy, dx, dy) # Function to find the unvisited# cells of the matrix after movementdef findUnvisited(p, periods): global n, curr_i, curr_j, duration, visited # map to store the wind directions mp = {} mp["N"] = [-1, 0] mp["S"] = [1, 0] mp["E"] = [0, 1] mp["W"] = [0, -1] mp["NE"] = [ -1, 1 ] mp["NW"] = [-1, -1] mp["SE"] = [1, 1] mp["SW"] = [1, -1] # Initially all of the # positions are unvisited for i in range(n): visited.append([]) for j in range(n): visited[i].append(False) for i in range(p): Dir = periods[i][1] dx = mp[Dir][0] dy = mp[Dir][1] if i < p - 1: # difference of the start time # of current wind direction # and start time of the # upcoming wind direction duration = periods[i + 1][0] - periods[i][0] else: # the maximum time for which # a robot can move is # equal to the diagonal # length of the square board duration = math.sqrt(2) * n # If its possible to move # the robot once in the # direction of wind, then # move it once and call the # recursive function for # further movements next_i = curr_i + dx next_j = curr_j + dy if next_i >= 0 and next_i < n and next_j >= 0 and next_j < n and visited[next_i][next_j] == False and duration > 0: moveRobot(n, next_i, next_j, dx, dy) # Variable to store the # number of unvisited positions not_visited = 0 # traverse over the matrix and # keep counting the unvisited positions for i in range(n): for j in range(n): if visited[i][j] == False: not_visited += 1 print(not_visited) # Dimension of the boardn = 5; # number of periodsp = 6 # vector of pairsperiods = []for i in range(p): periods.append([])periods[0] = [ 0, "SE" ]periods[1] = [ 1, "NE" ]periods[2] = [ 2, "E" ]periods[3] = [ 6, "SW"]periods[4] = [ 15, "N"]periods[5] = [ 20, "W"] # Function CallfindUnvisited(p, periods) # This code is contributed by divyeshrabadiya07.
// C# implementation to find the// unvisited cells of the matrixusing System;using System.Collections.Generic;class GFG { // Dimension // of the board static int n; // Current location // of the robot static int curr_i = 0, curr_j = 0; static int duration; // nXn matrix to store the // visited state of positions static List<List<bool>> visited = new List<List<bool>>(); // Function to move the robot static void moveRobot(int n, int i, int j, int dx, int dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement static void findUnvisited(int p, List<Tuple<int,string>> periods) { // map to store the wind directions Dictionary<string, List<int>> mp = new Dictionary<string, List<int>>(); mp["N"] = new List<int>(new int[]{-1, 0}); mp["S"] = new List<int>(new int[]{1, 0}); mp["E"] = new List<int>(new int[]{0, 1}); mp["W"] = new List<int>(new int[]{0, -1}); mp["NE"] = new List<int>(new int[]{-1, 1}); mp["NW"] = new List<int>(new int[]{-1, -1}); mp["SE"] = new List<int>(new int[]{1, 1}); mp["SW"] = new List<int>(new int[]{1, -1}); // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.Add(new List<bool>()); for (int j = 0; j < n; j++) { visited[i].Add(false); } } for (int i = 0; i < p; i++) { string dir = periods[i].Item2; int dx = mp[dir][0]; int dy = mp[dir][1]; // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1].Item1 - periods[i].Item1; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = (int)Math.Sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } Console.Write(not_visited/2+1); } static void Main() { // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs List<Tuple<int, string>> periods = new List<Tuple<int, string>>(); periods.Add(new Tuple<int,string>(0, "SE")); periods.Add(new Tuple<int,string>(1, "NE")); periods.Add(new Tuple<int,string>(2, "E")); periods.Add(new Tuple<int,string>(6, "SW")); periods.Add(new Tuple<int,string>(15, "N")); periods.Add(new Tuple<int,string>(20, "W")); // Function Call findUnvisited(p, periods); }} // This code is contributed by mukesh07.
<script> // Javascript implementation to find the // unvisited cells of the matrix // Dimension // of the board let n; // Current location // of the robot let curr_i = 0, curr_j = 0; let duration; // nXn matrix to store the // visited state of positions let visited = []; // Function to move the robot function moveRobot(n, i, j, dx, dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement function findUnvisited(p, periods) { // map to store the wind directions let mp = new Map(); mp["N"] = [-1, 0]; mp["S"] = [1, 0]; mp["E"] = [0, 1]; mp["W"] = [0, -1]; mp["NE"] = [ -1, 1 ]; mp["NW"] = [-1, -1]; mp["SE"] = [1, 1]; mp["SW"] = [1, -1]; // Initially all of the // positions are unvisited for (let i = 0; i < n; i++) { visited.push([]); for (let j = 0; j < n; j++) { visited[i].push(false); } } for (let i = 0; i < p; i++) { let dir = periods[i][1]; let dx = mp[dir][0]; let dy = mp[dir][1]; // duration for the which the // current direction of wind exists let duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1][0] - periods[i][0]; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = Math.sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements let next_i = curr_i + dx; let next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions let not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } document.write(not_visited); } // Dimension of the board n = 5; // number of periods let p = 6; // vector of pairs let periods = []; for(let i = 0; i < p; i++) { periods.push([]); } periods[0] = [ 0, "SE" ]; periods[1] = [ 1, "NE" ]; periods[2] = [ 2, "E" ]; periods[3] = [ 6, "SW"]; periods[4] = [ 15, "N"]; periods[5] = [ 20, "W"]; // Function Call findUnvisited(p, periods); // This code is contributed by suresh07.</script>
13
amarjeet_singh
suresh07
divyeshrabadiya07
mukesh07
rameshtravel07
Picked
Arrays
Graph
Matrix
Recursion
Stack
Arrays
Recursion
Stack
Matrix
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 548,
"s": 28,
"text": "Given an integer N, which denotes the size of the matrix that is N*N. There is a robot placed over the top-left corner (0, 0) of the matrix, the direction of movement of the robot are given as (N, S, W, E, NE, NW, SE, SW which denotes North, South, West, East, North-East, North-west, South-east, South-west respectively) and the duration of the movement in a particular direction is also given. The task is to find the unvisited cells of the matrix after the movement of the robot is completed at the end of all winds."
},
{
"code": null,
"e": 707,
"s": 548,
"text": "Note: Robot can visit a cell only once. If at any point robot cannot move then it will stay at its current position. Also, robot can make one move per second."
},
{
"code": null,
"e": 718,
"s": 707,
"text": "Examples: "
},
{
"code": null,
"e": 781,
"s": 718,
"text": "Input: N = 3, move[] = {(0, SE), (2, N)}Output: 4Explanation: "
},
{
"code": null,
"e": 945,
"s": 781,
"text": "Input: N = 5, move[] = {(0, SE), (1, NE), (2, E), (6, SW), (15, N), (20, W)}Output: 13Explanation: After the movements of the robot, there are 13 Cells unvisited."
},
{
"code": null,
"e": 1293,
"s": 945,
"text": "Approach: The idea is to use recursion to solve this problem. Initially, set the current position of the robot as the (0, 0). Start the movement of the robot as per the given direction and mark the cells as visited of the matrix. Finally, After the complete movement of the robot mark count the cells of the matrix which are not marked as visited "
},
{
"code": null,
"e": 1345,
"s": 1293,
"text": "Below code implements the approach discussed above:"
},
{
"code": null,
"e": 1349,
"s": 1345,
"text": "C++"
},
{
"code": null,
"e": 1354,
"s": 1349,
"text": "Java"
},
{
"code": null,
"e": 1362,
"s": 1354,
"text": "Python3"
},
{
"code": null,
"e": 1365,
"s": 1362,
"text": "C#"
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// unvisited cells of the matrix #include <bits/stdc++.h> using namespace std; // Dimension// of the boardint n; // Current location// of the robotint curr_i = 0, curr_j = 0; // Function to move the robotvoid moveRobot( int n, int i, int j, int dx, int dy, int& duration, vector<vector<bool> >& visited){ // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy, duration, visited);} // Function to find the unvisited// cells of the matrix after movementvoid findUnvisited( int p, vector<pair<int, string> > periods){ // nXn matrix to store the // visited state of positions vector<vector<bool> > visited; // map to store the wind directions unordered_map<string, vector<int> > mp = { { \"N\", { -1, 0 } }, { \"S\", { 1, 0 } }, { \"E\", { 0, 1 } }, { \"W\", { 0, -1 } }, { \"NE\", { -1, 1 } }, { \"NW\", { -1, -1 } }, { \"SE\", { 1, 1 } }, { \"SW\", { 1, -1 } } }; // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.push_back(vector<bool>{}); for (int j = 0; j < n; j++) { visited[i].push_back(false); } } for (int i = 0; i < p; i++) { string dir = periods[i].second; int dx = mp[dir][0]; int dy = mp[dir][1]; // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1].first - periods[i].first; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy, duration, visited); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } cout << not_visited << \"\\n\";} // Driver Codeint main(){ // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs vector<pair<int, string> > periods(p); periods[0] = { 0, \"SE\" }; periods[1] = { 1, \"NE\" }; periods[2] = { 2, \"E\" }; periods[3] = { 6, \"SW\" }; periods[4] = { 15, \"N\" }; periods[5] = { 20, \"W\" }; // Function Call findUnvisited(p, periods); return 0;}",
"e": 5260,
"s": 1376,
"text": null
},
{
"code": "// Java implementation to find the// unvisited cells of the matriximport java.util.*;import java.awt.Point; class pair{ int x; String y;} public class Main{ // Dimension // of the board static int n; // Current location // of the robot static int curr_i = 0, curr_j = 0; static int duration; // nXn matrix to store the // visited state of positions static Vector<Vector<Boolean>> visited = new Vector<Vector<Boolean>>(); // Function to move the robot static void moveRobot(int n, int i, int j, int dx, int dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited.get(i).get(j) == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited.get(i).set(j, true); // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement static void findUnvisited(int p, Vector<pair> periods) { // map to store the wind directions int[] array = new int[]{-1, 0}; Vector<Integer> l = new Vector<Integer>(); l.add(-1); l.add(0); HashMap<String, Vector<Integer>> mp = new HashMap<String, Vector<Integer>>(); mp.put(\"N\", l); l.clear(); l.add(1); l.add(0); mp.put(\"S\", l); l.clear(); l.add(0); l.add(1); mp.put(\"E\", l); l.clear(); l.add(0); l.add(-1); mp.put(\"W\", l); l.clear(); l.add(-1); l.add(1); mp.put(\"NE\", l); l.clear(); l.add(-1); l.add(-1); mp.put(\"NW\", l); l.clear(); l.add(1); l.add(1); mp.put(\"SE\", l); l.clear(); l.add(1); l.add(-1); mp.put(\"SW\", l); // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.add(new Vector<Boolean>()); for (int j = 0; j < n; j++) { visited.get(i).add(false); } } for (int i = 0; i < p; i++) { String dir = periods.get(i).y; int dx = mp.get(dir).get(0); int dy = mp.get(dir).get(1); // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods.get(i + 1).x - periods.get(i).x; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = (int)Math.sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited.get(next_i).get(next_j) == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited.get(i).get(j) == false) { not_visited++; } } } System.out.print(not_visited/2+1); } public static void main(String[] args) { // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs Vector<pair> periods = new Vector<pair>(); pair p1 = new pair(); p1.x = 0; p1.y = \"SE\"; periods.add(p1); p1 = new pair(); p1.x = 1; p1.y = \"NE\"; periods.add(p1); p1 = new pair(); p1.x = 2; p1.y = \"E\"; periods.add(p1); p1 = new pair(); p1.x = 6; p1.y = \"SW\"; periods.add(p1); p1 = new pair(); p1.x = 15; p1.y = \"N\"; periods.add(p1); p1 = new pair(); p1.x = 1; p1.y = \"NE\"; periods.add(p1); p1 = new pair(); p1.x = 20; p1.y = \"W\"; periods.add(p1); // Function Call findUnvisited(p, periods); }} // This code is contributed by rameshtravel07.",
"e": 10648,
"s": 5260,
"text": null
},
{
"code": "# Python3 implementation to find the# unvisited cells of the matriximport math # Dimension# of the boardn = 5 # Current location# of the robotcurr_i, curr_j = 0, 0duration = 0 # nXn matrix to store the# visited state of positionsvisited = [] # Function to move the robotdef moveRobot(n, i, j, dx, dy): global curr_i, curr_j, duration, visited # if the robot tends to move # out of the board # or tends to visit an # already visited position # or the wind direction is changed if i < 0 or i >= n or j < 0 or j >= n or visited[i][j] == True or duration == 0: # the robot can't move further # under the influence of # current wind direction return # Change the current location # and mark the current # position as visited curr_i = i curr_j = j visited[i][j] = True # One second passed # visiting this position duration-=1 moveRobot(n, i + dx, j + dy, dx, dy) # Function to find the unvisited# cells of the matrix after movementdef findUnvisited(p, periods): global n, curr_i, curr_j, duration, visited # map to store the wind directions mp = {} mp[\"N\"] = [-1, 0] mp[\"S\"] = [1, 0] mp[\"E\"] = [0, 1] mp[\"W\"] = [0, -1] mp[\"NE\"] = [ -1, 1 ] mp[\"NW\"] = [-1, -1] mp[\"SE\"] = [1, 1] mp[\"SW\"] = [1, -1] # Initially all of the # positions are unvisited for i in range(n): visited.append([]) for j in range(n): visited[i].append(False) for i in range(p): Dir = periods[i][1] dx = mp[Dir][0] dy = mp[Dir][1] if i < p - 1: # difference of the start time # of current wind direction # and start time of the # upcoming wind direction duration = periods[i + 1][0] - periods[i][0] else: # the maximum time for which # a robot can move is # equal to the diagonal # length of the square board duration = math.sqrt(2) * n # If its possible to move # the robot once in the # direction of wind, then # move it once and call the # recursive function for # further movements next_i = curr_i + dx next_j = curr_j + dy if next_i >= 0 and next_i < n and next_j >= 0 and next_j < n and visited[next_i][next_j] == False and duration > 0: moveRobot(n, next_i, next_j, dx, dy) # Variable to store the # number of unvisited positions not_visited = 0 # traverse over the matrix and # keep counting the unvisited positions for i in range(n): for j in range(n): if visited[i][j] == False: not_visited += 1 print(not_visited) # Dimension of the boardn = 5; # number of periodsp = 6 # vector of pairsperiods = []for i in range(p): periods.append([])periods[0] = [ 0, \"SE\" ]periods[1] = [ 1, \"NE\" ]periods[2] = [ 2, \"E\" ]periods[3] = [ 6, \"SW\"]periods[4] = [ 15, \"N\"]periods[5] = [ 20, \"W\"] # Function CallfindUnvisited(p, periods) # This code is contributed by divyeshrabadiya07.",
"e": 13734,
"s": 10648,
"text": null
},
{
"code": "// C# implementation to find the// unvisited cells of the matrixusing System;using System.Collections.Generic;class GFG { // Dimension // of the board static int n; // Current location // of the robot static int curr_i = 0, curr_j = 0; static int duration; // nXn matrix to store the // visited state of positions static List<List<bool>> visited = new List<List<bool>>(); // Function to move the robot static void moveRobot(int n, int i, int j, int dx, int dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement static void findUnvisited(int p, List<Tuple<int,string>> periods) { // map to store the wind directions Dictionary<string, List<int>> mp = new Dictionary<string, List<int>>(); mp[\"N\"] = new List<int>(new int[]{-1, 0}); mp[\"S\"] = new List<int>(new int[]{1, 0}); mp[\"E\"] = new List<int>(new int[]{0, 1}); mp[\"W\"] = new List<int>(new int[]{0, -1}); mp[\"NE\"] = new List<int>(new int[]{-1, 1}); mp[\"NW\"] = new List<int>(new int[]{-1, -1}); mp[\"SE\"] = new List<int>(new int[]{1, 1}); mp[\"SW\"] = new List<int>(new int[]{1, -1}); // Initially all of the // positions are unvisited for (int i = 0; i < n; i++) { visited.Add(new List<bool>()); for (int j = 0; j < n; j++) { visited[i].Add(false); } } for (int i = 0; i < p; i++) { string dir = periods[i].Item2; int dx = mp[dir][0]; int dy = mp[dir][1]; // duration for the which the // current direction of wind exists int duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1].Item1 - periods[i].Item1; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = (int)Math.Sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements int next_i = curr_i + dx; int next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions int not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } Console.Write(not_visited/2+1); } static void Main() { // Dimension of the board n = 5; // number of periods int p = 6; // vector of pairs List<Tuple<int, string>> periods = new List<Tuple<int, string>>(); periods.Add(new Tuple<int,string>(0, \"SE\")); periods.Add(new Tuple<int,string>(1, \"NE\")); periods.Add(new Tuple<int,string>(2, \"E\")); periods.Add(new Tuple<int,string>(6, \"SW\")); periods.Add(new Tuple<int,string>(15, \"N\")); periods.Add(new Tuple<int,string>(20, \"W\")); // Function Call findUnvisited(p, periods); }} // This code is contributed by mukesh07.",
"e": 18335,
"s": 13734,
"text": null
},
{
"code": "<script> // Javascript implementation to find the // unvisited cells of the matrix // Dimension // of the board let n; // Current location // of the robot let curr_i = 0, curr_j = 0; let duration; // nXn matrix to store the // visited state of positions let visited = []; // Function to move the robot function moveRobot(n, i, j, dx, dy) { // if the robot tends to move // out of the board // or tends to visit an // already visited position // or the wind direction is changed if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] == true || duration == 0) { // the robot can't move further // under the influence of // current wind direction return; } // Change the current location // and mark the current // position as visited curr_i = i; curr_j = j; visited[i][j] = true; // One second passed // visiting this position duration--; moveRobot(n, i + dx, j + dy, dx, dy); } // Function to find the unvisited // cells of the matrix after movement function findUnvisited(p, periods) { // map to store the wind directions let mp = new Map(); mp[\"N\"] = [-1, 0]; mp[\"S\"] = [1, 0]; mp[\"E\"] = [0, 1]; mp[\"W\"] = [0, -1]; mp[\"NE\"] = [ -1, 1 ]; mp[\"NW\"] = [-1, -1]; mp[\"SE\"] = [1, 1]; mp[\"SW\"] = [1, -1]; // Initially all of the // positions are unvisited for (let i = 0; i < n; i++) { visited.push([]); for (let j = 0; j < n; j++) { visited[i].push(false); } } for (let i = 0; i < p; i++) { let dir = periods[i][1]; let dx = mp[dir][0]; let dy = mp[dir][1]; // duration for the which the // current direction of wind exists let duration; if (i < p - 1) { // difference of the start time // of current wind direction // and start time of the // upcoming wind direction duration = periods[i + 1][0] - periods[i][0]; } else { // the maximum time for which // a robot can move is // equal to the diagonal // length of the square board duration = Math.sqrt(2) * n; } // If its possible to move // the robot once in the // direction of wind, then // move it once and call the // recursive function for // further movements let next_i = curr_i + dx; let next_j = curr_j + dy; if (next_i >= 0 && next_i < n && next_j >= 0 && next_j < n && visited[next_i][next_j] == false && duration > 0) { moveRobot(n, next_i, next_j, dx, dy); } } // Variable to store the // number of unvisited positions let not_visited = 0; // traverse over the matrix and // keep counting the unvisited positions for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (visited[i][j] == false) { not_visited++; } } } document.write(not_visited); } // Dimension of the board n = 5; // number of periods let p = 6; // vector of pairs let periods = []; for(let i = 0; i < p; i++) { periods.push([]); } periods[0] = [ 0, \"SE\" ]; periods[1] = [ 1, \"NE\" ]; periods[2] = [ 2, \"E\" ]; periods[3] = [ 6, \"SW\"]; periods[4] = [ 15, \"N\"]; periods[5] = [ 20, \"W\"]; // Function Call findUnvisited(p, periods); // This code is contributed by suresh07.</script>",
"e": 22380,
"s": 18335,
"text": null
},
{
"code": null,
"e": 22383,
"s": 22380,
"text": "13"
},
{
"code": null,
"e": 22400,
"s": 22385,
"text": "amarjeet_singh"
},
{
"code": null,
"e": 22409,
"s": 22400,
"text": "suresh07"
},
{
"code": null,
"e": 22427,
"s": 22409,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 22436,
"s": 22427,
"text": "mukesh07"
},
{
"code": null,
"e": 22451,
"s": 22436,
"text": "rameshtravel07"
},
{
"code": null,
"e": 22458,
"s": 22451,
"text": "Picked"
},
{
"code": null,
"e": 22465,
"s": 22458,
"text": "Arrays"
},
{
"code": null,
"e": 22471,
"s": 22465,
"text": "Graph"
},
{
"code": null,
"e": 22478,
"s": 22471,
"text": "Matrix"
},
{
"code": null,
"e": 22488,
"s": 22478,
"text": "Recursion"
},
{
"code": null,
"e": 22494,
"s": 22488,
"text": "Stack"
},
{
"code": null,
"e": 22501,
"s": 22494,
"text": "Arrays"
},
{
"code": null,
"e": 22511,
"s": 22501,
"text": "Recursion"
},
{
"code": null,
"e": 22517,
"s": 22511,
"text": "Stack"
},
{
"code": null,
"e": 22524,
"s": 22517,
"text": "Matrix"
},
{
"code": null,
"e": 22530,
"s": 22524,
"text": "Graph"
},
{
"code": null,
"e": 22628,
"s": 22530,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22660,
"s": 22628,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 22685,
"s": 22660,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 22732,
"s": 22685,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 22763,
"s": 22732,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 22821,
"s": 22763,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 22861,
"s": 22821,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 22899,
"s": 22861,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 22950,
"s": 22899,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 23001,
"s": 22950,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
How to Switch Themes in Android Using RadioButtons?
|
22 Mar, 2021
We have seen android app comes with two different types of mode or theme which are dark mode or light mode or we also called them as night and morning mode. In this article, we will implement the light and dark mode in android using RadioButton.
We will be building a simple application in which we will be displaying simple text and RadioButton in which we will be switching our theme from light to dark using simple RadioButtons. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
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"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--text view for displaying simple heading--> <TextView android:id="@+id/idTVHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:gravity="center_horizontal" android:text="Welcome to Geeks for Geeks" android:textAlignment="center" android:textSize="20sp" /> <!--text view for displaying the selected theme--> <TextView android:id="@+id/idtvTheme" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeading" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:text="System Default Theme" android:textAlignment="center" android:textSize="20sp" /> <!--radio group for switching theme--> <RadioGroup android:id="@+id/idRGgroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idtvTheme" android:layout_marginTop="30dp" android:orientation="vertical" android:padding="4dp"> <!--radio button for light theme--> <RadioButton android:id="@+id/idRBLight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:padding="5dp" android:text="Light" /> <!--radio button for dark theme--> <RadioButton android:id="@+id/idRBDark" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:layout_weight="1" android:padding="5dp" android:text="Dark" /> </RadioGroup> </RelativeLayout>
Step 3: Working with the colors.xml file
Navigate to the app > res > values > colors.xml and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#0F9D58</color> <color name="purple_500">#0F9D58</color> <color name="purple_700">#0F9D58</color> <color name="teal_200">#0F9D58</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color></resources>
Step 4: Working with themes.xml for light mode
Navigate to the app > res > values > themes > themes.xml for light mode and add the below code to it.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.Your Package Name" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!--below is the text color--> <item name="android:textColor">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>
Step 5: Working with themes.xml(night) for dark mode.
Navigate to the app > res > values > themes > themes.xml(night) for dark mode and add the below code to it.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.Your Package Name" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_200</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_200</item> <item name="colorOnSecondary">@color/white</item> <!--text color--> <item name="android:textColor">@color/white</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.RadioGroup;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.app.AppCompatDelegate; public class MainActivity extends AppCompatActivity { // initializing variables for // our radio group and text view. private RadioGroup radioGroup; private TextView themeTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. radioGroup = findViewById(R.id.idRGgroup); themeTV = findViewById(R.id.idtvTheme); // on below line we are setting on check change method for our radio group. radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // on radio button check change switch (checkedId) { case R.id.idRBLight: // on below line we are checking the radio button with id. // on below line we are setting the text to text view as light mode. themeTV.setText("Light Theme"); // on below line we are changing the theme to light mode. AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; case R.id.idRBDark: // this method is called when dark radio button is selected // on below line we are setting dark theme text to our text view. themeTV.setText("Dark Theme"); // on below line we are changing the theme to dark mode. AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); break; } } }); }}
Now run your app and see the output of the app.
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "We have seen android app comes with two different types of mode or theme which are dark mode or light mode or we also called them as night and morning mode. In this article, we will implement the light and dark mode in android using RadioButton. "
},
{
"code": null,
"e": 628,
"s": 275,
"text": "We will be building a simple application in which we will be displaying simple text and RadioButton in which we will be switching our theme from light to dark using simple RadioButtons. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 657,
"s": 628,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 819,
"s": 657,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 867,
"s": 819,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1010,
"s": 867,
"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": 1014,
"s": 1010,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--text view for displaying simple heading--> <TextView android:id=\"@+id/idTVHeading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"40dp\" android:gravity=\"center_horizontal\" android:text=\"Welcome to Geeks for Geeks\" android:textAlignment=\"center\" android:textSize=\"20sp\" /> <!--text view for displaying the selected theme--> <TextView android:id=\"@+id/idtvTheme\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeading\" android:layout_marginTop=\"30dp\" android:gravity=\"center_horizontal\" android:text=\"System Default Theme\" android:textAlignment=\"center\" android:textSize=\"20sp\" /> <!--radio group for switching theme--> <RadioGroup android:id=\"@+id/idRGgroup\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idtvTheme\" android:layout_marginTop=\"30dp\" android:orientation=\"vertical\" android:padding=\"4dp\"> <!--radio button for light theme--> <RadioButton android:id=\"@+id/idRBLight\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_margin=\"5dp\" android:padding=\"5dp\" android:text=\"Light\" /> <!--radio button for dark theme--> <RadioButton android:id=\"@+id/idRBDark\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_margin=\"5dp\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Dark\" /> </RadioGroup> </RelativeLayout>",
"e": 3282,
"s": 1014,
"text": null
},
{
"code": null,
"e": 3324,
"s": 3282,
"text": "Step 3: Working with the colors.xml file "
},
{
"code": null,
"e": 3402,
"s": 3324,
"text": "Navigate to the app > res > values > colors.xml and add the below code to it."
},
{
"code": null,
"e": 3406,
"s": 3402,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"purple_200\">#0F9D58</color> <color name=\"purple_500\">#0F9D58</color> <color name=\"purple_700\">#0F9D58</color> <color name=\"teal_200\">#0F9D58</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color></resources>",
"e": 3768,
"s": 3406,
"text": null
},
{
"code": null,
"e": 3815,
"s": 3768,
"text": "Step 4: Working with themes.xml for light mode"
},
{
"code": null,
"e": 3918,
"s": 3815,
"text": "Navigate to the app > res > values > themes > themes.xml for light mode and add the below code to it. "
},
{
"code": null,
"e": 3922,
"s": 3918,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.Your Package Name\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_500</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!--below is the text color--> <item name=\"android:textColor\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>",
"e": 4843,
"s": 3922,
"text": null
},
{
"code": null,
"e": 4897,
"s": 4843,
"text": "Step 5: Working with themes.xml(night) for dark mode."
},
{
"code": null,
"e": 5006,
"s": 4897,
"text": "Navigate to the app > res > values > themes > themes.xml(night) for dark mode and add the below code to it. "
},
{
"code": null,
"e": 5010,
"s": 5006,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.Your Package Name\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_200</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_200</item> <item name=\"colorOnSecondary\">@color/white</item> <!--text color--> <item name=\"android:textColor\">@color/white</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>",
"e": 5918,
"s": 5010,
"text": null
},
{
"code": null,
"e": 5966,
"s": 5918,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 6156,
"s": 5966,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 6161,
"s": 6156,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.RadioGroup;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.app.AppCompatDelegate; public class MainActivity extends AppCompatActivity { // initializing variables for // our radio group and text view. private RadioGroup radioGroup; private TextView themeTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. radioGroup = findViewById(R.id.idRGgroup); themeTV = findViewById(R.id.idtvTheme); // on below line we are setting on check change method for our radio group. radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // on radio button check change switch (checkedId) { case R.id.idRBLight: // on below line we are checking the radio button with id. // on below line we are setting the text to text view as light mode. themeTV.setText(\"Light Theme\"); // on below line we are changing the theme to light mode. AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; case R.id.idRBDark: // this method is called when dark radio button is selected // on below line we are setting dark theme text to our text view. themeTV.setText(\"Dark Theme\"); // on below line we are changing the theme to dark mode. AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); break; } } }); }}",
"e": 8200,
"s": 6161,
"text": null
},
{
"code": null,
"e": 8249,
"s": 8200,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 8257,
"s": 8249,
"text": "Output:"
},
{
"code": null,
"e": 8265,
"s": 8257,
"text": "Android"
},
{
"code": null,
"e": 8270,
"s": 8265,
"text": "Java"
},
{
"code": null,
"e": 8275,
"s": 8270,
"text": "Java"
},
{
"code": null,
"e": 8283,
"s": 8275,
"text": "Android"
}
] |
How to detect the browser language preference using JavaScript ?
|
23 Sep, 2020
Detecting the language preference of users can be very important for Websites or Web Apps for increasing user interaction. By using JavaScript, this task can be easily done by using:
Languages property is available for the navigator interface, which returns the most preferred / user preferred language set in the web browser. This property is read-only.
Syntax:
navigator.languages
// Or
navigator.language
Return Value:
The navigator.languages property will return an array which stores the languages in an order in which language most preferred by the user will be the first element.
The navigator.language property will return the first element of the array which is returned by the navigator.languages property i.e. the most preferred user language.
Note: Language property is a read-only property, thus it is only possible for us to get the value, we cannot make changes to the user preferred language.
Example 1: Getting the most preferred language.
HTML
<!DOCTYPE html><html> <body> <h1 align="left">GeekforGeeks</h1> <script> var usrlang = navigator.language || navigator.userLanguage; document.write( "User's preferred language is: " + usrlang); </script> </body> </html>
Output:
Example 2: Getting the preferred language array.
HTML
<!DOCTYPE html><html> <body> <h1 align="left">GeekforGeeks</h1> <script> var usrlang = navigator.languages; console.log(usrlang); </script> </body> </html>
Output:
Supported Browsers:
Google Chrome
Mozilla Firefox
Edge
Opera
Internet Explorer
JavaScript-Misc
Picked
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "Detecting the language preference of users can be very important for Websites or Web Apps for increasing user interaction. By using JavaScript, this task can be easily done by using:"
},
{
"code": null,
"e": 383,
"s": 211,
"text": "Languages property is available for the navigator interface, which returns the most preferred / user preferred language set in the web browser. This property is read-only."
},
{
"code": null,
"e": 391,
"s": 383,
"text": "Syntax:"
},
{
"code": null,
"e": 440,
"s": 391,
"text": "navigator.languages \n\n// Or\n\nnavigator.language\n"
},
{
"code": null,
"e": 455,
"s": 440,
"text": "Return Value: "
},
{
"code": null,
"e": 620,
"s": 455,
"text": "The navigator.languages property will return an array which stores the languages in an order in which language most preferred by the user will be the first element."
},
{
"code": null,
"e": 788,
"s": 620,
"text": "The navigator.language property will return the first element of the array which is returned by the navigator.languages property i.e. the most preferred user language."
},
{
"code": null,
"e": 942,
"s": 788,
"text": "Note: Language property is a read-only property, thus it is only possible for us to get the value, we cannot make changes to the user preferred language."
},
{
"code": null,
"e": 990,
"s": 942,
"text": "Example 1: Getting the most preferred language."
},
{
"code": null,
"e": 995,
"s": 990,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 align=\"left\">GeekforGeeks</h1> <script> var usrlang = navigator.language || navigator.userLanguage; document.write( \"User's preferred language is: \" + usrlang); </script> </body> </html>",
"e": 1281,
"s": 995,
"text": null
},
{
"code": null,
"e": 1289,
"s": 1281,
"text": "Output:"
},
{
"code": null,
"e": 1338,
"s": 1289,
"text": "Example 2: Getting the preferred language array."
},
{
"code": null,
"e": 1343,
"s": 1338,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 align=\"left\">GeekforGeeks</h1> <script> var usrlang = navigator.languages; console.log(usrlang); </script> </body> </html>",
"e": 1534,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1542,
"s": 1534,
"text": "Output:"
},
{
"code": null,
"e": 1562,
"s": 1542,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1576,
"s": 1562,
"text": "Google Chrome"
},
{
"code": null,
"e": 1592,
"s": 1576,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 1597,
"s": 1592,
"text": "Edge"
},
{
"code": null,
"e": 1603,
"s": 1597,
"text": "Opera"
},
{
"code": null,
"e": 1621,
"s": 1603,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1637,
"s": 1621,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1644,
"s": 1637,
"text": "Picked"
},
{
"code": null,
"e": 1655,
"s": 1644,
"text": "JavaScript"
},
{
"code": null,
"e": 1672,
"s": 1655,
"text": "Web Technologies"
},
{
"code": null,
"e": 1770,
"s": 1672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1831,
"s": 1770,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1871,
"s": 1831,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1912,
"s": 1871,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1954,
"s": 1912,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1976,
"s": 1954,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2038,
"s": 1976,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2071,
"s": 2038,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2132,
"s": 2071,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2182,
"s": 2132,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Maximum cost of splitting given Binary Tree into two halves
|
21 Jun, 2021
Given a Binary Tree with N nodes valued 0 to N – 1 and N-1 edges and an array arr[] consisting of values of edges, the task is to find the maximum cost of splitting the tree into two halves.
The cost of splitting a tree is equal to the product of sum of node values of the splitted subtrees.
Examples:
Input: N = 6, arr[] = {13, 8, 7, 4, 5, 9}, Edges[][] = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}Output: 504Explanation:Below is the given tree and resultant tree after removing the edge:
Remove the edge between 1st and 4th, thent1 = valueat[0] + valueat[1] + valueat[2] = 13 + 8 + 7t1 = valueat[3] + valueat[4] + valueat[5] = 4 + 5 + 9t1*t2 = (13 + 8 + 7) * (4 + 5 + 9) = 504
Input: N = 7, arr[]= {13, 8, 7, 4, 5, 9, 100}, Edges[][] = { {0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}, {2, 6}}Output: 4600Explanation:Below is the given tree and resultant tree after removing the edge:
Remove the edge between 2nd and 6th, thent1 = valueat[0] + valueat[1] + valueat[2] + valueat[3] + valueat[4] + valueat[5]= 13 + 8 + 7 + 4 + 5 + 9t2 = valueat[6] = 100t1*t2 = (13 + 8 + 7 + 5 + 4 + 9) * (100) = 4600
Approach: The idea is to traverse the given tree and try to break the tree at every possible edge and then find the maximum cost of splitting at that edges. After all the above steps print the maximum cost among all the splitting. Below are the steps:
All the edges are stored using the adjacency list edges and values at each node is stored in the given array arr[].For the current-node, find the sum of values in its descendants including itself.Suppose if the edge between the current node and its parent is removed then two trees can be formed.Now, calculate values of t1, t2, and check the product of t1 and t2 is maximum or not.Repeat this process recursively to all the child-nodes of current-node.
All the edges are stored using the adjacency list edges and values at each node is stored in the given array arr[].
For the current-node, find the sum of values in its descendants including itself.
Suppose if the edge between the current node and its parent is removed then two trees can be formed.
Now, calculate values of t1, t2, and check the product of t1 and t2 is maximum or not.
Repeat this process recursively to all the child-nodes of current-node.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To store the results and sum of// all nodes in the arrayint ans = 0, allsum = 0; // To create adjacency listvector<int> edges[100001]; // Function to add edges into the// adjacency listvoid addedge(int a, int b){ edges[a].push_back(b); edges[b].push_back(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelyvoid findCost(int r, int p, int arr[]){ int i, cur; for (i = 0; i < edges[r].size(); i++) { // Fetch the child of node-r cur = edges[r].at(i); // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesvoid maximumCost(int r, int p, int N, int M, int arr[], int Edges[][2]){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr);} // Driver Codeint main(){ int a, b, N = 6; // Values in each node int arr[] = { 13, 8, 7, 4, 5, 9 }; int M = 5; // Given Edges int Edges[][2] = { { 0, 1 }, { 1, 2 }, { 1, 4 }, { 3, 4 }, { 4, 5 } }; maximumCost(1, -1, N, M, arr, Edges); cout << ans; return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // To store the results and sum of// all nodes in the arraystatic int ans = 0, allsum = 0; // To create adjacency liststatic Vector<Integer> []edges = new Vector[100001]; // Function to add edges into the// adjacency liststatic void addedge(int a, int b){ edges[a].add(b); edges[b].add(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelystatic void findCost(int r, int p, int arr[]){ int i, cur; for (i = 0; i < edges[r].size(); i++) { // Fetch the child of node-r cur = edges[r].get(i); // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesstatic void maximumCost(int r, int p, int N, int M, int arr[], int Edges[][]){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr);} // Driver Codepublic static void main(String[] args){ int a, b, N = 6; // Values in each node int arr[] = {13, 8, 7, 4, 5, 9}; int M = 5; // Given Edges int Edges[][] = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}; for (int i = 0; i < edges.length; i++) edges[i] = new Vector<Integer>(); maximumCost(1, -1, N, M, arr, Edges); System.out.print(ans);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # To store the results and sum of# all nodes in the arrayans = 0allsum = 0 # To create adjacency listedges = [[] for i in range(100001)] # Function to add edges into the# adjacency listdef addedge(a, b): global edges edges[a].append(b) edges[b].append(a) # Recursive function that calculate# the value of the cost of splitting# the tree recursivelydef findCost(r, p, arr): global edges global ans global allsum i = 0 for i in range(len(edges[r])): # Fetch the child of node-r cur = edges[r][i] # Neglect if cur node is parent if (cur == p): continue findCost(cur, r, arr) # Add all values of nodes # which are decendents of r arr[r] += arr[cur] # The two trees formed are rooted # at 'r' with its decendents t1 = arr[r] t2 = allsum - t1 # Check and replace if current # product t1*t2 is large if (t1 * t2 > ans): ans = t1 * t2 # Function to find the maximum cost# after splitting the tree in 2 halvesdef maximumCost(r, p, N, M, arr, Edges): global allsum # Find sum of values in all nodes for i in range(N): allsum += arr[i] # Traverse edges to create # adjacency list for i in range(M): addedge(Edges[i][0], Edges[i][1]) # Function Call findCost(r, p, arr) # Driver Codeif __name__ == '__main__': N = 6 # Values in each node arr = [ 13, 8, 7, 4, 5, 9 ] M = 5 # Given Edges Edges = [ [ 0, 1 ], [ 1, 2 ], [ 1, 4 ], [ 3, 4 ], [ 4, 5 ] ] maximumCost(1, -1, N, M, arr, Edges) print(ans) # This code is contributed by ipg2016107
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // To store the results and sum of// all nodes in the arraystatic int ans = 0, allsum = 0; // To create adjacency liststatic List<int> []edges = new List<int>[100001]; // Function to add edges into the// adjacency liststatic void addedge(int a, int b){ edges[a].Add(b); edges[b].Add(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelystatic void findCost(int r, int p, int []arr){ int i, cur; for (i = 0; i < edges[r].Count; i++) { // Fetch the child of node-r cur = edges[r][i]; // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesstatic void maximumCost(int r, int p, int N, int M, int []arr, int [, ]Edges){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i, 0], Edges[i, 1]); } // Function Call findCost(r, p, arr);} // Driver Codepublic static void Main(String[] args){ int N = 6; // Values in each node int []arr = {13, 8, 7, 4, 5, 9}; int M = 5; // Given Edges int [,]Edges = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}; for (int i = 0; i < edges.Length; i++) edges[i] = new List<int>(); maximumCost(1, -1, N, M, arr, Edges); Console.Write(ans);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program for the above approach // To store the results and sum of // all nodes in the array let ans = 0, allsum = 0; // To create adjacency list let edges = new Array(100001); // Function to add edges into the // adjacency list function addedge(a, b) { edges[a].push(b); edges[b].push(a); } // Recursive function that calculate // the value of the cost of splitting // the tree recursively function findCost(r, p, arr) { let i, cur; for (i = 0; i < edges[r].length; i++) { // Fetch the child of node-r cur = edges[r][i]; // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents let t1 = arr[r]; let t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; } } // Function to find the maximum cost // after splitting the tree in 2 halves function maximumCost(r, p, N, M, arr, Edges) { // Find sum of values in all nodes for (let i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (let i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr); } let N = 6; // Values in each node let arr = [13, 8, 7, 4, 5, 9]; let M = 5; // Given Edges let Edges = [[0, 1], [1, 2], [1, 4], [3, 4], [4, 5]]; for (let i = 0; i < edges.length; i++) edges[i] = []; maximumCost(1, -1, N, M, arr, Edges); document.write(ans); </script>
504
Time Complexity: O(N)Auxiliary Space: O(N)
amit143katiyar
Rajput-Ji
ipg2016107
rameshtravel07
Binary Tree
Tree Traversals
Recursion
Searching
Tree
Searching
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Print all subsequences of a string
Recursive Practice Problems with Solutions
Print all possible combinations of r elements in a given array of size n
Reverse a stack using recursion
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 247,
"s": 54,
"text": "Given a Binary Tree with N nodes valued 0 to N – 1 and N-1 edges and an array arr[] consisting of values of edges, the task is to find the maximum cost of splitting the tree into two halves. "
},
{
"code": null,
"e": 348,
"s": 247,
"text": "The cost of splitting a tree is equal to the product of sum of node values of the splitted subtrees."
},
{
"code": null,
"e": 358,
"s": 348,
"text": "Examples:"
},
{
"code": null,
"e": 544,
"s": 358,
"text": "Input: N = 6, arr[] = {13, 8, 7, 4, 5, 9}, Edges[][] = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}Output: 504Explanation:Below is the given tree and resultant tree after removing the edge:"
},
{
"code": null,
"e": 733,
"s": 544,
"text": "Remove the edge between 1st and 4th, thent1 = valueat[0] + valueat[1] + valueat[2] = 13 + 8 + 7t1 = valueat[3] + valueat[4] + valueat[5] = 4 + 5 + 9t1*t2 = (13 + 8 + 7) * (4 + 5 + 9) = 504"
},
{
"code": null,
"e": 933,
"s": 733,
"text": "Input: N = 7, arr[]= {13, 8, 7, 4, 5, 9, 100}, Edges[][] = { {0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}, {2, 6}}Output: 4600Explanation:Below is the given tree and resultant tree after removing the edge:"
},
{
"code": null,
"e": 1147,
"s": 933,
"text": "Remove the edge between 2nd and 6th, thent1 = valueat[0] + valueat[1] + valueat[2] + valueat[3] + valueat[4] + valueat[5]= 13 + 8 + 7 + 4 + 5 + 9t2 = valueat[6] = 100t1*t2 = (13 + 8 + 7 + 5 + 4 + 9) * (100) = 4600"
},
{
"code": null,
"e": 1399,
"s": 1147,
"text": "Approach: The idea is to traverse the given tree and try to break the tree at every possible edge and then find the maximum cost of splitting at that edges. After all the above steps print the maximum cost among all the splitting. Below are the steps:"
},
{
"code": null,
"e": 1853,
"s": 1399,
"text": "All the edges are stored using the adjacency list edges and values at each node is stored in the given array arr[].For the current-node, find the sum of values in its descendants including itself.Suppose if the edge between the current node and its parent is removed then two trees can be formed.Now, calculate values of t1, t2, and check the product of t1 and t2 is maximum or not.Repeat this process recursively to all the child-nodes of current-node."
},
{
"code": null,
"e": 1969,
"s": 1853,
"text": "All the edges are stored using the adjacency list edges and values at each node is stored in the given array arr[]."
},
{
"code": null,
"e": 2051,
"s": 1969,
"text": "For the current-node, find the sum of values in its descendants including itself."
},
{
"code": null,
"e": 2152,
"s": 2051,
"text": "Suppose if the edge between the current node and its parent is removed then two trees can be formed."
},
{
"code": null,
"e": 2239,
"s": 2152,
"text": "Now, calculate values of t1, t2, and check the product of t1 and t2 is maximum or not."
},
{
"code": null,
"e": 2311,
"s": 2239,
"text": "Repeat this process recursively to all the child-nodes of current-node."
},
{
"code": null,
"e": 2362,
"s": 2311,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2366,
"s": 2362,
"text": "C++"
},
{
"code": null,
"e": 2371,
"s": 2366,
"text": "Java"
},
{
"code": null,
"e": 2379,
"s": 2371,
"text": "Python3"
},
{
"code": null,
"e": 2382,
"s": 2379,
"text": "C#"
},
{
"code": null,
"e": 2393,
"s": 2382,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To store the results and sum of// all nodes in the arrayint ans = 0, allsum = 0; // To create adjacency listvector<int> edges[100001]; // Function to add edges into the// adjacency listvoid addedge(int a, int b){ edges[a].push_back(b); edges[b].push_back(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelyvoid findCost(int r, int p, int arr[]){ int i, cur; for (i = 0; i < edges[r].size(); i++) { // Fetch the child of node-r cur = edges[r].at(i); // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesvoid maximumCost(int r, int p, int N, int M, int arr[], int Edges[][2]){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr);} // Driver Codeint main(){ int a, b, N = 6; // Values in each node int arr[] = { 13, 8, 7, 4, 5, 9 }; int M = 5; // Given Edges int Edges[][2] = { { 0, 1 }, { 1, 2 }, { 1, 4 }, { 3, 4 }, { 4, 5 } }; maximumCost(1, -1, N, M, arr, Edges); cout << ans; return 0;}",
"e": 4291,
"s": 2393,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // To store the results and sum of// all nodes in the arraystatic int ans = 0, allsum = 0; // To create adjacency liststatic Vector<Integer> []edges = new Vector[100001]; // Function to add edges into the// adjacency liststatic void addedge(int a, int b){ edges[a].add(b); edges[b].add(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelystatic void findCost(int r, int p, int arr[]){ int i, cur; for (i = 0; i < edges[r].size(); i++) { // Fetch the child of node-r cur = edges[r].get(i); // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesstatic void maximumCost(int r, int p, int N, int M, int arr[], int Edges[][]){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr);} // Driver Codepublic static void main(String[] args){ int a, b, N = 6; // Values in each node int arr[] = {13, 8, 7, 4, 5, 9}; int M = 5; // Given Edges int Edges[][] = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}; for (int i = 0; i < edges.length; i++) edges[i] = new Vector<Integer>(); maximumCost(1, -1, N, M, arr, Edges); System.out.print(ans);}} // This code is contributed by Amit Katiyar",
"e": 6389,
"s": 4291,
"text": null
},
{
"code": "# Python3 program for the above approach # To store the results and sum of# all nodes in the arrayans = 0allsum = 0 # To create adjacency listedges = [[] for i in range(100001)] # Function to add edges into the# adjacency listdef addedge(a, b): global edges edges[a].append(b) edges[b].append(a) # Recursive function that calculate# the value of the cost of splitting# the tree recursivelydef findCost(r, p, arr): global edges global ans global allsum i = 0 for i in range(len(edges[r])): # Fetch the child of node-r cur = edges[r][i] # Neglect if cur node is parent if (cur == p): continue findCost(cur, r, arr) # Add all values of nodes # which are decendents of r arr[r] += arr[cur] # The two trees formed are rooted # at 'r' with its decendents t1 = arr[r] t2 = allsum - t1 # Check and replace if current # product t1*t2 is large if (t1 * t2 > ans): ans = t1 * t2 # Function to find the maximum cost# after splitting the tree in 2 halvesdef maximumCost(r, p, N, M, arr, Edges): global allsum # Find sum of values in all nodes for i in range(N): allsum += arr[i] # Traverse edges to create # adjacency list for i in range(M): addedge(Edges[i][0], Edges[i][1]) # Function Call findCost(r, p, arr) # Driver Codeif __name__ == '__main__': N = 6 # Values in each node arr = [ 13, 8, 7, 4, 5, 9 ] M = 5 # Given Edges Edges = [ [ 0, 1 ], [ 1, 2 ], [ 1, 4 ], [ 3, 4 ], [ 4, 5 ] ] maximumCost(1, -1, N, M, arr, Edges) print(ans) # This code is contributed by ipg2016107",
"e": 8112,
"s": 6389,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // To store the results and sum of// all nodes in the arraystatic int ans = 0, allsum = 0; // To create adjacency liststatic List<int> []edges = new List<int>[100001]; // Function to add edges into the// adjacency liststatic void addedge(int a, int b){ edges[a].Add(b); edges[b].Add(a);} // Recursive function that calculate// the value of the cost of splitting// the tree recursivelystatic void findCost(int r, int p, int []arr){ int i, cur; for (i = 0; i < edges[r].Count; i++) { // Fetch the child of node-r cur = edges[r][i]; // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents int t1 = arr[r]; int t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; }} // Function to find the maximum cost// after splitting the tree in 2 halvesstatic void maximumCost(int r, int p, int N, int M, int []arr, int [, ]Edges){ // Find sum of values in all nodes for (int i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (int i = 0; i < M; i++) { addedge(Edges[i, 0], Edges[i, 1]); } // Function Call findCost(r, p, arr);} // Driver Codepublic static void Main(String[] args){ int N = 6; // Values in each node int []arr = {13, 8, 7, 4, 5, 9}; int M = 5; // Given Edges int [,]Edges = {{0, 1}, {1, 2}, {1, 4}, {3, 4}, {4, 5}}; for (int i = 0; i < edges.Length; i++) edges[i] = new List<int>(); maximumCost(1, -1, N, M, arr, Edges); Console.Write(ans);}} // This code is contributed by Rajput-Ji",
"e": 10184,
"s": 8112,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // To store the results and sum of // all nodes in the array let ans = 0, allsum = 0; // To create adjacency list let edges = new Array(100001); // Function to add edges into the // adjacency list function addedge(a, b) { edges[a].push(b); edges[b].push(a); } // Recursive function that calculate // the value of the cost of splitting // the tree recursively function findCost(r, p, arr) { let i, cur; for (i = 0; i < edges[r].length; i++) { // Fetch the child of node-r cur = edges[r][i]; // Neglect if cur node is parent if (cur == p) continue; findCost(cur, r, arr); // Add all values of nodes // which are decendents of r arr[r] += arr[cur]; } // The two trees formed are rooted // at 'r' with its decendents let t1 = arr[r]; let t2 = allsum - t1; // Check and replace if current // product t1*t2 is large if (t1 * t2 > ans) { ans = t1 * t2; } } // Function to find the maximum cost // after splitting the tree in 2 halves function maximumCost(r, p, N, M, arr, Edges) { // Find sum of values in all nodes for (let i = 0; i < N; i++) { allsum += arr[i]; } // Traverse edges to create // adjacency list for (let i = 0; i < M; i++) { addedge(Edges[i][0], Edges[i][1]); } // Function Call findCost(r, p, arr); } let N = 6; // Values in each node let arr = [13, 8, 7, 4, 5, 9]; let M = 5; // Given Edges let Edges = [[0, 1], [1, 2], [1, 4], [3, 4], [4, 5]]; for (let i = 0; i < edges.length; i++) edges[i] = []; maximumCost(1, -1, N, M, arr, Edges); document.write(ans); </script>",
"e": 12172,
"s": 10184,
"text": null
},
{
"code": null,
"e": 12176,
"s": 12172,
"text": "504"
},
{
"code": null,
"e": 12221,
"s": 12178,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 12236,
"s": 12221,
"text": "amit143katiyar"
},
{
"code": null,
"e": 12246,
"s": 12236,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 12257,
"s": 12246,
"text": "ipg2016107"
},
{
"code": null,
"e": 12272,
"s": 12257,
"text": "rameshtravel07"
},
{
"code": null,
"e": 12284,
"s": 12272,
"text": "Binary Tree"
},
{
"code": null,
"e": 12300,
"s": 12284,
"text": "Tree Traversals"
},
{
"code": null,
"e": 12310,
"s": 12300,
"text": "Recursion"
},
{
"code": null,
"e": 12320,
"s": 12310,
"text": "Searching"
},
{
"code": null,
"e": 12325,
"s": 12320,
"text": "Tree"
},
{
"code": null,
"e": 12335,
"s": 12325,
"text": "Searching"
},
{
"code": null,
"e": 12345,
"s": 12335,
"text": "Recursion"
},
{
"code": null,
"e": 12350,
"s": 12345,
"text": "Tree"
},
{
"code": null,
"e": 12448,
"s": 12350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12476,
"s": 12448,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 12511,
"s": 12476,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 12554,
"s": 12511,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 12627,
"s": 12554,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 12659,
"s": 12627,
"text": "Reverse a stack using recursion"
},
{
"code": null,
"e": 12673,
"s": 12659,
"text": "Binary Search"
},
{
"code": null,
"e": 12741,
"s": 12673,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 12755,
"s": 12741,
"text": "Linear Search"
},
{
"code": null,
"e": 12811,
"s": 12755,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
How to read a JSON response from a link in Python?
|
24 Feb, 2021
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which helps to open the URL from the web and read the data.
To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json.loads() method returns JSON object. Below is the process by which we can read the JSON response from a link or URL in python.
Import required modules.
Assign URL.
Get the response of the URL using urlopen().
Convert it to a JSON response using json.loads().
Display the generated JSON response.
Implementation:
Python3
# import urllib libraryfrom urllib.request import urlopen # import jsonimport json# store the URL in url as # parameter for urlopenurl = "https://api.github.com" # store the response of URLresponse = urlopen(url) # storing the JSON response # from url in datadata_json = json.loads(response.read()) # print the json responseprint(data_json)
Output:
In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json.loads() to convert the response into a JSON object.
Picked
Python-json
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 454,
"s": 52,
"text": "There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which helps to open the URL from the web and read the data."
},
{
"code": null,
"e": 850,
"s": 454,
"text": "To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json.loads() method returns JSON object. Below is the process by which we can read the JSON response from a link or URL in python."
},
{
"code": null,
"e": 875,
"s": 850,
"text": "Import required modules."
},
{
"code": null,
"e": 887,
"s": 875,
"text": "Assign URL."
},
{
"code": null,
"e": 932,
"s": 887,
"text": "Get the response of the URL using urlopen()."
},
{
"code": null,
"e": 982,
"s": 932,
"text": "Convert it to a JSON response using json.loads()."
},
{
"code": null,
"e": 1019,
"s": 982,
"text": "Display the generated JSON response."
},
{
"code": null,
"e": 1035,
"s": 1019,
"text": "Implementation:"
},
{
"code": null,
"e": 1043,
"s": 1035,
"text": "Python3"
},
{
"code": "# import urllib libraryfrom urllib.request import urlopen # import jsonimport json# store the URL in url as # parameter for urlopenurl = \"https://api.github.com\" # store the response of URLresponse = urlopen(url) # storing the JSON response # from url in datadata_json = json.loads(response.read()) # print the json responseprint(data_json)",
"e": 1388,
"s": 1043,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1578,
"s": 1396,
"text": "In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json.loads() to convert the response into a JSON object."
},
{
"code": null,
"e": 1585,
"s": 1578,
"text": "Picked"
},
{
"code": null,
"e": 1597,
"s": 1585,
"text": "Python-json"
},
{
"code": null,
"e": 1621,
"s": 1597,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1628,
"s": 1621,
"text": "Python"
},
{
"code": null,
"e": 1647,
"s": 1628,
"text": "Technical Scripter"
}
] |
Java 8 | Collectors averagingInt() with Examples
|
06 Dec, 2018
Collectors averagingInt(ToIntFunction<? super T> mapper) method is used to find the mean of the integers passed in the parameters. This method returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements. If no elements are passed as the input elements, then this method returns 0.
The formula used by this method to calculate arithmetic mean is:
Syntax:
public static
<T> Collector<T, ?, Double>
averagingInt(ToIntFunction<? super T> mapper)
where,
Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation.
T: The type of input elements to the reduction operation.
A: The mutable accumulation type of the reduction operation.
R: The result type of the reduction operation.
Double: The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
ToIntFunction: Represents a function that produces an int-valued result.
Parameters: This method takes a mandatory parameter mapper which is of type ToIntFunction. It is a Function which extracts an int type of value from a stream.
Below are examples to illustrate averagingInt() method:
Program 1:
// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream with numbers Stream<String> s = Stream.of("3", "4", "5"); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}
4.0
Program 2: When no input element is passed as the parameter to averagingInt() method.
// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a empty string stream Stream<String> s = Stream.of(); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}
0.0
Program 3:
// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of("7", "8", "9", "10"); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}
8.5
Java - util package
Java-Collectors
Java-Functions
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 363,
"s": 28,
"text": "Collectors averagingInt(ToIntFunction<? super T> mapper) method is used to find the mean of the integers passed in the parameters. This method returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements. If no elements are passed as the input elements, then this method returns 0."
},
{
"code": null,
"e": 428,
"s": 363,
"text": "The formula used by this method to calculate arithmetic mean is:"
},
{
"code": null,
"e": 436,
"s": 428,
"text": "Syntax:"
},
{
"code": null,
"e": 535,
"s": 436,
"text": "public static \n <T> Collector<T, ?, Double> \n averagingInt(ToIntFunction<? super T> mapper)\n"
},
{
"code": null,
"e": 542,
"s": 535,
"text": "where,"
},
{
"code": null,
"e": 1025,
"s": 542,
"text": "Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation."
},
{
"code": null,
"e": 1083,
"s": 1025,
"text": "T: The type of input elements to the reduction operation."
},
{
"code": null,
"e": 1144,
"s": 1083,
"text": "A: The mutable accumulation type of the reduction operation."
},
{
"code": null,
"e": 1191,
"s": 1144,
"text": "R: The result type of the reduction operation."
},
{
"code": null,
"e": 1344,
"s": 1191,
"text": "Double: The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double."
},
{
"code": null,
"e": 1417,
"s": 1344,
"text": "ToIntFunction: Represents a function that produces an int-valued result."
},
{
"code": null,
"e": 1576,
"s": 1417,
"text": "Parameters: This method takes a mandatory parameter mapper which is of type ToIntFunction. It is a Function which extracts an int type of value from a stream."
},
{
"code": null,
"e": 1632,
"s": 1576,
"text": "Below are examples to illustrate averagingInt() method:"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream with numbers Stream<String> s = Stream.of(\"3\", \"4\", \"5\"); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}",
"e": 2377,
"s": 1643,
"text": null
},
{
"code": null,
"e": 2382,
"s": 2377,
"text": "4.0\n"
},
{
"code": null,
"e": 2468,
"s": 2382,
"text": "Program 2: When no input element is passed as the parameter to averagingInt() method."
},
{
"code": "// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a empty string stream Stream<String> s = Stream.of(); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}",
"e": 3180,
"s": 2468,
"text": null
},
{
"code": null,
"e": 3185,
"s": 3180,
"text": "0.0\n"
},
{
"code": null,
"e": 3196,
"s": 3185,
"text": "Program 3:"
},
{
"code": "// Java code to show the implementation of// Collectors averagingInt(ToIntFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of(\"7\", \"8\", \"9\", \"10\"); // using Collectors averagingInt(ToIntFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingInt( num -> Integer.parseInt(num))); // displaying the result System.out.println(ans); }}",
"e": 3921,
"s": 3196,
"text": null
},
{
"code": null,
"e": 3926,
"s": 3921,
"text": "8.5\n"
},
{
"code": null,
"e": 3946,
"s": 3926,
"text": "Java - util package"
},
{
"code": null,
"e": 3962,
"s": 3946,
"text": "Java-Collectors"
},
{
"code": null,
"e": 3977,
"s": 3962,
"text": "Java-Functions"
},
{
"code": null,
"e": 3989,
"s": 3977,
"text": "java-stream"
},
{
"code": null,
"e": 4012,
"s": 3989,
"text": "Java-Stream-Collectors"
},
{
"code": null,
"e": 4017,
"s": 4012,
"text": "Java"
},
{
"code": null,
"e": 4022,
"s": 4017,
"text": "Java"
},
{
"code": null,
"e": 4120,
"s": 4022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4135,
"s": 4120,
"text": "Stream In Java"
},
{
"code": null,
"e": 4156,
"s": 4135,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4177,
"s": 4156,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4196,
"s": 4177,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4213,
"s": 4196,
"text": "Generics in Java"
},
{
"code": null,
"e": 4243,
"s": 4213,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4269,
"s": 4243,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4285,
"s": 4269,
"text": "Strings in Java"
},
{
"code": null,
"e": 4322,
"s": 4285,
"text": "Differences between JDK, JRE and JVM"
}
] |
Tarjan’s off-line lowest common ancestors algorithm
|
02 Mar, 2022
Prerequisite : LCA basics, Disjoint Set Union by Rank and Path CompressionWe are given a tree(can be extended to a DAG) and we have many queries of form LCA(u, v), i.e., find LCA of nodes ‘u’ and ‘v’.We can perform those queries in O(N + QlogN) time using RMQ, where O(N) time for pre-processing and O(log N) for answering the queries, where N = number of nodes and Q = number of queries to be answered.Can we do better than this? Can we do in linear(almost) time? Yes. The article presents an offline algorithm which performs those queries in approximately O(N + Q) time. Although, this is not exactly linear, as there is an Inverse Ackermann function involved in the time complexity analysis. For more details on Inverse Ackermann function see this. Just as a summary, we can say that the Inverse Ackermann Function remains less than 4, for any value of input size that can be written in physical inverse. Thus, we consider this as almost linear. We consider the input tree as shown below. We will Pre-Process the tree and fill two arrays- child[] and sibling[] according to the below explanation-
Let we want to process these queries- LCA(5,4), LCA(1,3), LCA(2,3)Now, after pre-processing, we perform a LCA walk starting from the root of the tree(here- node ‘1’). But prior to the LCA walk, we colour all the nodes with WHITE. During the whole LCA walk, we use three disjoint set union functions- makeSet(), findSet(), unionSet(). These functions use the technique of union by rank and path compression to improve the running time. During the LCA walk, our queries gets processed and outputted (in a random order). After the LCA walk of the whole tree, all the nodes gets coloured BLACK.Tarjan Offline LCA Algorithm steps from CLRS, Section-21-3, Pg 584, 2nd /3rd edition.
Note- The queries may not be processed in the original order. We can easily modify the process and sort them according to the input order.The below pictures clearly depict all the steps happening. The red arrow shows the direction of travel of our recursive function LCA().
As, we can clearly see from the above pictures, the queries are processed in the following order, LCA(5,4), LCA(2,3), LCA(1,3) which is not in the same order as the input(LCA(5,4), LCA(1,3), LCA(2,3)).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// A C++ Program to implement Tarjan Offline LCA Algorithm#include <bits/stdc++.h> #define V 5 // number of nodes in input tree#define WHITE 1 // COLOUR 'WHITE' is assigned value 1#define BLACK 2 // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node* left, *right;}; /* subset[i].parent-->Holds the parent of node-'i' subset[i].rank-->Holds the rank of node-'i' subset[i].ancestor-->Holds the LCA queries answers subset[i].child-->Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-->Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-->Holds the colour of node-'i'*/struct subset{ int parent, rank, ancestor, child, sibling, color;}; // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmstruct Query{ int L, R;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} //A utility function to make setvoid makeSet(struct subset subsets[], int i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)int findSet(struct subset subsets[], int i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)void unionSet(struct subset subsets[], int x, int y){ int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]void lcaWalk(int u, struct Query q[], int m, struct subset subsets[]){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { printf("LCA(%d %d) -> %d\n", q[i].L, q[i].R, subsets[findSet(subsets,q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { printf("LCA(%d %d) -> %d\n", q[i].L, q[i].R, subsets[findSet(subsets,q[i].L)].ancestor); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays-> child[]// and sibling[] in "struct subset" with// the tree structure using this function.void preprocess(Node * node, struct subset subsets[]){ if (node == NULL) return; // Recur on left child preprocess(node->left, subsets); if (node->left != NULL&&node->right != NULL) { /* Note that the below two lines can also be this- subsets[node->data].child = node->right->data; subsets[node->right->data].sibling = node->left->data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node->data].child = node->left->data; subsets[node->left->data].sibling = node->right->data; } else if ((node->left != NULL && node->right == NULL) || (node->left == NULL && node->right != NULL)) { if(node->left != NULL && node->right == NULL) subsets[node->data].child = node->left->data; else subsets[node->data].child = node->right->data; } //Recur on right child preprocess (node->right, subsets);} // A function to initialise prior to pre-processing and// LCA walkvoid initialise(struct subset subsets[]){ // Initialising the structure with 0's memset(subsets, 0, (V+1) * sizeof(struct subset)); // We colour all nodes WHITE before LCA Walk. for (int i=1; i<=V; i++) subsets[i].color=WHITE; return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootvoid printLCAs(Node *root, Query q[], int m){ // Allocate memory for V subsets and nodes struct subset * subsets = new subset[V+1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root->data , q, m, subsets);} // Driver program to test above functionsint main(){ /* We construct a binary tree :- 1 / \ 2 3 / \ 4 5 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // LCA Queries to answer Query q[] = {{5, 4}, {1, 3}, {2, 3}}; int m = sizeof(q)/sizeof(q[0]); printLCAs(root, q, m); return 0;}
// A Java Program to implement Tarjan Offline LCA Algorithmimport java.util.Arrays;class GFG{static final int V = 5; // number of nodes in input treestatic final int WHITE = 1; // COLOUR 'WHITE' is assigned value 1static final int BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */static class Node{ int data; Node left, right;}; /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/static class subset{ int parent; int rank; int ancestor; int child; int sibling; int color;}; // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmstatic class Query{ int L, R; Query(int L, int R) { this.L = L; this.R = R; }}; /* Helper function that allocates a new node with the given data and null left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // A utility function to make setstatic void makeSet(subset subsets[], int i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)static int findSet(subset subsets[], int i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)static void unionSet(subset subsets[], int x, int y){ int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]static void lcaWalk(int u, Query q[], int m, subset subsets[]){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { System.out.printf("LCA(%d %d)->%d\n", q[i].L, q[i].R, subsets[findSet(subsets,q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { System.out.printf("LCA(%d %d)->%d\n", q[i].L, q[i].R, subsets[findSet(subsets,q[i].L)].ancestor); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays. child[]// and sibling[] in "subset" with// the tree structure using this function.static void preprocess(Node node, subset subsets[]){ if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets);} // A function to initialise prior to pre-processing and// LCA walkstatic void initialise(subset subsets[]){ // We colour all nodes WHITE before LCA Walk. for (int i = 1; i < subsets.length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootstatic void printLCAs(Node root, Query q[], int m){ // Allocate memory for V subsets and nodes subset []subsets = new subset[V + 1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data , q, m, subsets);} // Driver codepublic static void main(String[] args){ /* We construct a binary tree :- 1 / \ 2 3 / \ 4 5 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // LCA Queries to answer Query q[] = new Query[3]; q[0] = new Query(5, 4); q[1] = new Query(1, 3); q[2] = new Query(2, 3); int m = q.length; printLCAs(root, q, m);}} // This code is contributed by gauravrajput1
# A Python3 program to implement Tarjan# Offline LCA Algorithm # Number of nodes in input treeV = 5 # COLOUR 'WHITE' is assigned value 1WHITE = 1 # COLOUR 'BLACK' is assigned value 2BLACK = 2 # A binary tree node has data, pointer# to left child and a pointer to right childclass Node: def __init__(self): self.data = 0 self.left = None self.right = None ''' subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i''''class subset: def __init__(self): self.parent = 0 self.rank = 0 self.ancestor = 0 self.child = 0 self.sibling = 0 self.color = 0 # Structure to represent a query# A query consists of (L,R) and we# will process the queries offline# a/c to Tarjan's offline LCA algorithmclass Query: def __init__(self, L, R): self.L = L self.R = R # Helper function that allocates a new node# with the given data and None left and# right pointers.def newNode(data): node = Node() node.data = data node.left = node.right = None return (node) # A utility function to make setdef makeSet(subsets, i): if (i < 1 or i > V): return subsets[i].color = WHITE subsets[i].parent = i subsets[i].rank = 0 return # A utility function to find set of an element i# (uses path compression technique)def findSet(subsets, i): # Find root and make root as parent # of i (path compression) if (subsets[i].parent != i): subsets[i].parent = findSet(subsets, subsets[i].parent) return subsets[i].parent # A function that does union of two sets# of x and y (uses union by rank)def unionSet(subsets, x, y): xroot = findSet(subsets, x) yroot = findSet(subsets, y) # Attach smaller rank tree under root of # high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank): subsets[xroot].parent = yroot else if (subsets[xroot].rank > subsets[yroot].rank): subsets[yroot].parent = xroot # If ranks are same, then make one as root # and increment its rank by one else: subsets[yroot].parent = xroot (subsets[xroot].rank) += 1 # The main function that prints LCAs. u is# root's data. m is size of q[]def lcaWalk(u, q, m, subsets): # Make Sets makeSet(subsets, u) # Initially, each node's ancestor is the node # itself. subsets[findSet(subsets, u)].ancestor = u child = subsets[u].child # This while loop doesn't run for more than 2 times # as there can be at max. two children of a node while (child != 0): lcaWalk(child, q, m, subsets) unionSet(subsets, u, child) subsets[findSet(subsets, u)].ancestor = u child = subsets[child].sibling subsets[u].color = BLACK for i in range(m): if (q[i].L == u): if (subsets[q[i].R].color == BLACK): print("LCA(%d %d) -> %d" % (q[i].L, q[i].R, subsets[findSet(subsets, q[i].R)].ancestor)) else if (q[i].R == u): if (subsets[q[i].L].color == BLACK): print("LCA(%d %d) -> %d" % (q[i].L, q[i].R, subsets[findSet(subsets, q[i].L)].ancestor)) return # This is basically an inorder traversal and# we preprocess the arrays. child[]# and sibling[] in "struct subset" with# the tree structure using this function.def preprocess(node, subsets): if (node == None): return # Recur on left child preprocess(node.left, subsets) if (node.left != None and node.right != None): ''' Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling''' subsets[node.data].child = node.left.data subsets[node.left.data].sibling = node.right.data else if ((node.left != None and node.right == None) or (node.left == None and node.right != None)): if (node.left != None and node.right == None): subsets[node.data].child = node.left.data else: subsets[node.data].child = node.right.data # Recur on right child preprocess(node.right, subsets) # A function to initialise prior to pre-processing and# LCA walkdef initialise(subsets): # Initialising the structure with 0's # memset(subsets, 0, (V+1) * sizeof(struct subset)); # We colour all nodes WHITE before LCA Walk. for i in range(1, V + 1): subsets[i].color = WHITE return # Prints LCAs for given queries q[0..m-1] in a tree# with given rootdef printLCAs(root, q, m): # Allocate memory for V subsets and nodes subsets = [subset() for _ in range(V + 1)] # Creates subsets and colors them WHITE initialise(subsets) # Preprocess the tree preprocess(root, subsets) # Perform a tree walk to process the LCA queries # offline lcaWalk(root.data, q, m, subsets) # Driver codeif __name__ == "__main__": ''' We construct a binary tree :- 1 / \ 2 3 / \ 4 5 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # LCA Queries to answer q = [Query(5, 4), Query(1, 3), Query(2, 3)] m = len(q) printLCAs(root, q, m) # This code is contributed by sanjeev2552
// A C# Program to implement Tarjan Offline LCA Algorithmusing System; public class GFG{ static readonly int V = 5; // number of nodes in input tree static readonly int WHITE = 1; // COLOUR 'WHITE' is assigned value 1 static readonly int BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; }; /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/ public class subset { public int parent; public int rank; public int ancestor; public int child; public int sibling; public int color; }; // Structure to represent a query // A query consists of (L,R) and we will process the // queries offline a/c to Tarjan's offline LCA algorithm public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node); } // A utility function to make set static void makeSet(subset []subsets, int i) { if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return; } // A utility function to find set of an element i // (uses path compression technique) static int findSet(subset []subsets, int i) { // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) static void unionSet(subset []subsets, int x, int y) { int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; } } // The main function that prints LCAs. u is root's data. // m is size of q[] static void lcaWalk(int u, Query []q, int m, subset []subsets) { // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { Console.WriteLine("LCA(" + q[i].L + " " + q[i].R+") -> " + subsets[findSet(subsets, q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { Console.WriteLine("LCA(" + q[i].L + " " + q[i].R + ") -> " + subsets[findSet(subsets, q[i].L)].ancestor); } } } return; } // This is basically an inorder traversal and // we preprocess the arrays. child[] // and sibling[] in "subset" with // the tree structure using this function. static void preprocess(Node node, subset []subsets) { if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets); } // A function to initialise prior to pre-processing and // LCA walk static void initialise(subset []subsets) { // We colour all nodes WHITE before LCA Walk. for (int i = 1; i < subsets.Length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return; } // Prints LCAs for given queries q[0..m-1] in a tree // with given root static void printLCAs(Node root, Query []q, int m) { // Allocate memory for V subsets and nodes subset []subsets = new subset[V + 1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data, q, m, subsets); } // Driver code public static void Main(String[] args) { /* We construct a binary tree :- 1 / \ 2 3 / \ 4 5 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // LCA Queries to answer Query []q = new Query[3]; q[0] = new Query(5, 4); q[1] = new Query(1, 3); q[2] = new Query(2, 3); int m = q.Length; printLCAs(root, q, m); }} // This code is contributed by Rajput-Ji
<script>// A Javascript Program to implement Tarjan Offline LCA Algorithm let V = 5; // number of nodes in input treelet WHITE = 1; // COLOUR 'WHITE' is assigned value 1let BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor(data) { this.data = data; this.left = this.right = null; }} /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/class subset{ constructor() { this.parent = 0; this.rank = 0; this.ancestor = 0; this.child = 0; this.sibling = 0; this.color = 0; }} // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmclass Query{ constructor(L, R) { this.L = L; this.R = R; }} /* Helper function that allocates a new node with the given data and null left and right pointers. */function newNode(data){ let node = new Node(); node.data = data; node.left = node.right = null; return(node);} // A utility function to make setfunction makeSet(subsets,i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)function findSet(subsets, i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)function unionSet(subsets, x, y){ let xroot = findSet (subsets, x); let yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]function lcaWalk(u,q,m,subsets){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; let child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (let i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { document.write("LCA("+ q[i].L+" " +q[i].R+") -> ",subsets[findSet(subsets,q[i].R)].ancestor+"<br>"); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { document.write("LCA("+ q[i].L+" " +q[i].R+") -> ",subsets[findSet(subsets,q[i].L)].ancestor+"<br>"); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays. child[]// and sibling[] in "subset" with// the tree structure using this function.function preprocess(node,subsets){ if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets);} // A function to initialise prior to pre-processing and// LCA walkfunction initialise(subsets){ // We colour all nodes WHITE before LCA Walk. for (let i = 1; i < subsets.length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootfunction printLCAs(root, q, m){ // Allocate memory for V subsets and nodes let subsets = new Array(V + 1); // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data , q, m, subsets);} // Driver code/* We construct a binary tree :- 1 / \ 2 3 / \ 4 5 */ let root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5); // LCA Queries to answerlet q = new Array(3);q[0] = new Query(5, 4);q[1] = new Query(1, 3);q[2] = new Query(2, 3);let m = q.length;printLCAs(root, q, m); // This code is contributed by patel2127</script>
Output :
LCA(5 4) -> 2
LCA(2 3) -> 1
LCA(1 3) -> 1
Time Complexity : Super-linear, i.e- barely slower than linear. O(N + Q) time, where O(N) time for pre-processing and almost O(1) time for answering the queries.
Auxiliary Space : We use a many arrays- parent[], rank[], ancestor[] which are used in Disjoint Set Union Operations each with the size equal to the number of nodes. We also use the arrays- child[], sibling[], color[] which are useful in this offline algorithm. Hence, we use O(N). For convenience, all these arrays are put up in a structure- struct subset to hold these arrays.
References https://en.wikipedia.org/wiki/Tarjan%27s_off-line_lowest_common_ancestors_algorithm CLRS, Section-21-3, Pg 584, 2nd /3rd edition http://wcipeg.com/wiki/Lowest_common_ancestor#OfflineThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
GauravRajput1
Rajput-Ji
sanjeev2552
patel2127
surindertarika1234
simmytarika5
surinderdawra388
LCA
union-find
Advanced Data Structure
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 1156,
"s": 54,
"text": "Prerequisite : LCA basics, Disjoint Set Union by Rank and Path CompressionWe are given a tree(can be extended to a DAG) and we have many queries of form LCA(u, v), i.e., find LCA of nodes ‘u’ and ‘v’.We can perform those queries in O(N + QlogN) time using RMQ, where O(N) time for pre-processing and O(log N) for answering the queries, where N = number of nodes and Q = number of queries to be answered.Can we do better than this? Can we do in linear(almost) time? Yes. The article presents an offline algorithm which performs those queries in approximately O(N + Q) time. Although, this is not exactly linear, as there is an Inverse Ackermann function involved in the time complexity analysis. For more details on Inverse Ackermann function see this. Just as a summary, we can say that the Inverse Ackermann Function remains less than 4, for any value of input size that can be written in physical inverse. Thus, we consider this as almost linear. We consider the input tree as shown below. We will Pre-Process the tree and fill two arrays- child[] and sibling[] according to the below explanation- "
},
{
"code": null,
"e": 1834,
"s": 1156,
"text": "Let we want to process these queries- LCA(5,4), LCA(1,3), LCA(2,3)Now, after pre-processing, we perform a LCA walk starting from the root of the tree(here- node ‘1’). But prior to the LCA walk, we colour all the nodes with WHITE. During the whole LCA walk, we use three disjoint set union functions- makeSet(), findSet(), unionSet(). These functions use the technique of union by rank and path compression to improve the running time. During the LCA walk, our queries gets processed and outputted (in a random order). After the LCA walk of the whole tree, all the nodes gets coloured BLACK.Tarjan Offline LCA Algorithm steps from CLRS, Section-21-3, Pg 584, 2nd /3rd edition. "
},
{
"code": null,
"e": 2110,
"s": 1834,
"text": "Note- The queries may not be processed in the original order. We can easily modify the process and sort them according to the input order.The below pictures clearly depict all the steps happening. The red arrow shows the direction of travel of our recursive function LCA(). "
},
{
"code": null,
"e": 2318,
"s": 2116,
"text": "As, we can clearly see from the above pictures, the queries are processed in the following order, LCA(5,4), LCA(2,3), LCA(1,3) which is not in the same order as the input(LCA(5,4), LCA(1,3), LCA(2,3))."
},
{
"code": null,
"e": 2369,
"s": 2318,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2373,
"s": 2369,
"text": "C++"
},
{
"code": null,
"e": 2378,
"s": 2373,
"text": "Java"
},
{
"code": null,
"e": 2386,
"s": 2378,
"text": "Python3"
},
{
"code": null,
"e": 2389,
"s": 2386,
"text": "C#"
},
{
"code": null,
"e": 2400,
"s": 2389,
"text": "Javascript"
},
{
"code": "// A C++ Program to implement Tarjan Offline LCA Algorithm#include <bits/stdc++.h> #define V 5 // number of nodes in input tree#define WHITE 1 // COLOUR 'WHITE' is assigned value 1#define BLACK 2 // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node* left, *right;}; /* subset[i].parent-->Holds the parent of node-'i' subset[i].rank-->Holds the rank of node-'i' subset[i].ancestor-->Holds the LCA queries answers subset[i].child-->Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-->Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-->Holds the colour of node-'i'*/struct subset{ int parent, rank, ancestor, child, sibling, color;}; // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmstruct Query{ int L, R;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} //A utility function to make setvoid makeSet(struct subset subsets[], int i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)int findSet(struct subset subsets[], int i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)void unionSet(struct subset subsets[], int x, int y){ int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]void lcaWalk(int u, struct Query q[], int m, struct subset subsets[]){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { printf(\"LCA(%d %d) -> %d\\n\", q[i].L, q[i].R, subsets[findSet(subsets,q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { printf(\"LCA(%d %d) -> %d\\n\", q[i].L, q[i].R, subsets[findSet(subsets,q[i].L)].ancestor); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays-> child[]// and sibling[] in \"struct subset\" with// the tree structure using this function.void preprocess(Node * node, struct subset subsets[]){ if (node == NULL) return; // Recur on left child preprocess(node->left, subsets); if (node->left != NULL&&node->right != NULL) { /* Note that the below two lines can also be this- subsets[node->data].child = node->right->data; subsets[node->right->data].sibling = node->left->data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node->data].child = node->left->data; subsets[node->left->data].sibling = node->right->data; } else if ((node->left != NULL && node->right == NULL) || (node->left == NULL && node->right != NULL)) { if(node->left != NULL && node->right == NULL) subsets[node->data].child = node->left->data; else subsets[node->data].child = node->right->data; } //Recur on right child preprocess (node->right, subsets);} // A function to initialise prior to pre-processing and// LCA walkvoid initialise(struct subset subsets[]){ // Initialising the structure with 0's memset(subsets, 0, (V+1) * sizeof(struct subset)); // We colour all nodes WHITE before LCA Walk. for (int i=1; i<=V; i++) subsets[i].color=WHITE; return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootvoid printLCAs(Node *root, Query q[], int m){ // Allocate memory for V subsets and nodes struct subset * subsets = new subset[V+1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root->data , q, m, subsets);} // Driver program to test above functionsint main(){ /* We construct a binary tree :- 1 / \\ 2 3 / \\ 4 5 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // LCA Queries to answer Query q[] = {{5, 4}, {1, 3}, {2, 3}}; int m = sizeof(q)/sizeof(q[0]); printLCAs(root, q, m); return 0;}",
"e": 8616,
"s": 2400,
"text": null
},
{
"code": "// A Java Program to implement Tarjan Offline LCA Algorithmimport java.util.Arrays;class GFG{static final int V = 5; // number of nodes in input treestatic final int WHITE = 1; // COLOUR 'WHITE' is assigned value 1static final int BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */static class Node{ int data; Node left, right;}; /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/static class subset{ int parent; int rank; int ancestor; int child; int sibling; int color;}; // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmstatic class Query{ int L, R; Query(int L, int R) { this.L = L; this.R = R; }}; /* Helper function that allocates a new node with the given data and null left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} // A utility function to make setstatic void makeSet(subset subsets[], int i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)static int findSet(subset subsets[], int i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)static void unionSet(subset subsets[], int x, int y){ int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]static void lcaWalk(int u, Query q[], int m, subset subsets[]){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { System.out.printf(\"LCA(%d %d)->%d\\n\", q[i].L, q[i].R, subsets[findSet(subsets,q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { System.out.printf(\"LCA(%d %d)->%d\\n\", q[i].L, q[i].R, subsets[findSet(subsets,q[i].L)].ancestor); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays. child[]// and sibling[] in \"subset\" with// the tree structure using this function.static void preprocess(Node node, subset subsets[]){ if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets);} // A function to initialise prior to pre-processing and// LCA walkstatic void initialise(subset subsets[]){ // We colour all nodes WHITE before LCA Walk. for (int i = 1; i < subsets.length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootstatic void printLCAs(Node root, Query q[], int m){ // Allocate memory for V subsets and nodes subset []subsets = new subset[V + 1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data , q, m, subsets);} // Driver codepublic static void main(String[] args){ /* We construct a binary tree :- 1 / \\ 2 3 / \\ 4 5 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // LCA Queries to answer Query q[] = new Query[3]; q[0] = new Query(5, 4); q[1] = new Query(1, 3); q[2] = new Query(2, 3); int m = q.length; printLCAs(root, q, m);}} // This code is contributed by gauravrajput1",
"e": 15017,
"s": 8616,
"text": null
},
{
"code": "# A Python3 program to implement Tarjan# Offline LCA Algorithm # Number of nodes in input treeV = 5 # COLOUR 'WHITE' is assigned value 1WHITE = 1 # COLOUR 'BLACK' is assigned value 2BLACK = 2 # A binary tree node has data, pointer# to left child and a pointer to right childclass Node: def __init__(self): self.data = 0 self.left = None self.right = None ''' subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i''''class subset: def __init__(self): self.parent = 0 self.rank = 0 self.ancestor = 0 self.child = 0 self.sibling = 0 self.color = 0 # Structure to represent a query# A query consists of (L,R) and we# will process the queries offline# a/c to Tarjan's offline LCA algorithmclass Query: def __init__(self, L, R): self.L = L self.R = R # Helper function that allocates a new node# with the given data and None left and# right pointers.def newNode(data): node = Node() node.data = data node.left = node.right = None return (node) # A utility function to make setdef makeSet(subsets, i): if (i < 1 or i > V): return subsets[i].color = WHITE subsets[i].parent = i subsets[i].rank = 0 return # A utility function to find set of an element i# (uses path compression technique)def findSet(subsets, i): # Find root and make root as parent # of i (path compression) if (subsets[i].parent != i): subsets[i].parent = findSet(subsets, subsets[i].parent) return subsets[i].parent # A function that does union of two sets# of x and y (uses union by rank)def unionSet(subsets, x, y): xroot = findSet(subsets, x) yroot = findSet(subsets, y) # Attach smaller rank tree under root of # high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank): subsets[xroot].parent = yroot else if (subsets[xroot].rank > subsets[yroot].rank): subsets[yroot].parent = xroot # If ranks are same, then make one as root # and increment its rank by one else: subsets[yroot].parent = xroot (subsets[xroot].rank) += 1 # The main function that prints LCAs. u is# root's data. m is size of q[]def lcaWalk(u, q, m, subsets): # Make Sets makeSet(subsets, u) # Initially, each node's ancestor is the node # itself. subsets[findSet(subsets, u)].ancestor = u child = subsets[u].child # This while loop doesn't run for more than 2 times # as there can be at max. two children of a node while (child != 0): lcaWalk(child, q, m, subsets) unionSet(subsets, u, child) subsets[findSet(subsets, u)].ancestor = u child = subsets[child].sibling subsets[u].color = BLACK for i in range(m): if (q[i].L == u): if (subsets[q[i].R].color == BLACK): print(\"LCA(%d %d) -> %d\" % (q[i].L, q[i].R, subsets[findSet(subsets, q[i].R)].ancestor)) else if (q[i].R == u): if (subsets[q[i].L].color == BLACK): print(\"LCA(%d %d) -> %d\" % (q[i].L, q[i].R, subsets[findSet(subsets, q[i].L)].ancestor)) return # This is basically an inorder traversal and# we preprocess the arrays. child[]# and sibling[] in \"struct subset\" with# the tree structure using this function.def preprocess(node, subsets): if (node == None): return # Recur on left child preprocess(node.left, subsets) if (node.left != None and node.right != None): ''' Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling''' subsets[node.data].child = node.left.data subsets[node.left.data].sibling = node.right.data else if ((node.left != None and node.right == None) or (node.left == None and node.right != None)): if (node.left != None and node.right == None): subsets[node.data].child = node.left.data else: subsets[node.data].child = node.right.data # Recur on right child preprocess(node.right, subsets) # A function to initialise prior to pre-processing and# LCA walkdef initialise(subsets): # Initialising the structure with 0's # memset(subsets, 0, (V+1) * sizeof(struct subset)); # We colour all nodes WHITE before LCA Walk. for i in range(1, V + 1): subsets[i].color = WHITE return # Prints LCAs for given queries q[0..m-1] in a tree# with given rootdef printLCAs(root, q, m): # Allocate memory for V subsets and nodes subsets = [subset() for _ in range(V + 1)] # Creates subsets and colors them WHITE initialise(subsets) # Preprocess the tree preprocess(root, subsets) # Perform a tree walk to process the LCA queries # offline lcaWalk(root.data, q, m, subsets) # Driver codeif __name__ == \"__main__\": ''' We construct a binary tree :- 1 / \\ 2 3 / \\ 4 5 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # LCA Queries to answer q = [Query(5, 4), Query(1, 3), Query(2, 3)] m = len(q) printLCAs(root, q, m) # This code is contributed by sanjeev2552",
"e": 20905,
"s": 15017,
"text": null
},
{
"code": "// A C# Program to implement Tarjan Offline LCA Algorithmusing System; public class GFG{ static readonly int V = 5; // number of nodes in input tree static readonly int WHITE = 1; // COLOUR 'WHITE' is assigned value 1 static readonly int BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; }; /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/ public class subset { public int parent; public int rank; public int ancestor; public int child; public int sibling; public int color; }; // Structure to represent a query // A query consists of (L,R) and we will process the // queries offline a/c to Tarjan's offline LCA algorithm public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node); } // A utility function to make set static void makeSet(subset []subsets, int i) { if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return; } // A utility function to find set of an element i // (uses path compression technique) static int findSet(subset []subsets, int i) { // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) static void unionSet(subset []subsets, int x, int y) { int xroot = findSet (subsets, x); int yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; } } // The main function that prints LCAs. u is root's data. // m is size of q[] static void lcaWalk(int u, Query []q, int m, subset []subsets) { // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; int child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (int i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { Console.WriteLine(\"LCA(\" + q[i].L + \" \" + q[i].R+\") -> \" + subsets[findSet(subsets, q[i].R)].ancestor); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { Console.WriteLine(\"LCA(\" + q[i].L + \" \" + q[i].R + \") -> \" + subsets[findSet(subsets, q[i].L)].ancestor); } } } return; } // This is basically an inorder traversal and // we preprocess the arrays. child[] // and sibling[] in \"subset\" with // the tree structure using this function. static void preprocess(Node node, subset []subsets) { if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets); } // A function to initialise prior to pre-processing and // LCA walk static void initialise(subset []subsets) { // We colour all nodes WHITE before LCA Walk. for (int i = 1; i < subsets.Length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return; } // Prints LCAs for given queries q[0..m-1] in a tree // with given root static void printLCAs(Node root, Query []q, int m) { // Allocate memory for V subsets and nodes subset []subsets = new subset[V + 1]; // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data, q, m, subsets); } // Driver code public static void Main(String[] args) { /* We construct a binary tree :- 1 / \\ 2 3 / \\ 4 5 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); // LCA Queries to answer Query []q = new Query[3]; q[0] = new Query(5, 4); q[1] = new Query(1, 3); q[2] = new Query(2, 3); int m = q.Length; printLCAs(root, q, m); }} // This code is contributed by Rajput-Ji",
"e": 27511,
"s": 20905,
"text": null
},
{
"code": "<script>// A Javascript Program to implement Tarjan Offline LCA Algorithm let V = 5; // number of nodes in input treelet WHITE = 1; // COLOUR 'WHITE' is assigned value 1let BLACK = 2; // COLOUR 'BLACK' is assigned value 2 /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor(data) { this.data = data; this.left = this.right = null; }} /* subset[i].parent-.Holds the parent of node-'i' subset[i].rank-.Holds the rank of node-'i' subset[i].ancestor-.Holds the LCA queries answers subset[i].child-.Holds one of the child of node-'i' if present, else -'0' subset[i].sibling-.Holds the right-sibling of node-'i' if present, else -'0' subset[i].color-.Holds the colour of node-'i'*/class subset{ constructor() { this.parent = 0; this.rank = 0; this.ancestor = 0; this.child = 0; this.sibling = 0; this.color = 0; }} // Structure to represent a query// A query consists of (L,R) and we will process the// queries offline a/c to Tarjan's offline LCA algorithmclass Query{ constructor(L, R) { this.L = L; this.R = R; }} /* Helper function that allocates a new node with the given data and null left and right pointers. */function newNode(data){ let node = new Node(); node.data = data; node.left = node.right = null; return(node);} // A utility function to make setfunction makeSet(subsets,i){ if (i < 1 || i > V) return; subsets[i].color = WHITE; subsets[i].parent = i; subsets[i].rank = 0; return;} // A utility function to find set of an element i// (uses path compression technique)function findSet(subsets, i){ // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = findSet (subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)function unionSet(subsets, x, y){ let xroot = findSet (subsets, x); let yroot = findSet (subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; (subsets[xroot].rank)++; }} // The main function that prints LCAs. u is root's data.// m is size of q[]function lcaWalk(u,q,m,subsets){ // Make Sets makeSet(subsets, u); // Initially, each node's ancestor is the node // itself. subsets[findSet(subsets, u)].ancestor = u; let child = subsets[u].child; // This while loop doesn't run for more than 2 times // as there can be at max. two children of a node while (child != 0) { lcaWalk(child, q, m, subsets); unionSet (subsets, u, child); subsets[findSet(subsets, u)].ancestor = u; child = subsets[child].sibling; } subsets[u].color = BLACK; for (let i = 0; i < m; i++) { if (q[i].L == u) { if (subsets[q[i].R].color == BLACK) { document.write(\"LCA(\"+ q[i].L+\" \" +q[i].R+\") -> \",subsets[findSet(subsets,q[i].R)].ancestor+\"<br>\"); } } else if (q[i].R == u) { if (subsets[q[i].L].color == BLACK) { document.write(\"LCA(\"+ q[i].L+\" \" +q[i].R+\") -> \",subsets[findSet(subsets,q[i].L)].ancestor+\"<br>\"); } } } return;} // This is basically an inorder traversal and// we preprocess the arrays. child[]// and sibling[] in \"subset\" with// the tree structure using this function.function preprocess(node,subsets){ if (node == null) return; // Recur on left child preprocess(node.left, subsets); if (node.left != null && node.right != null) { /* Note that the below two lines can also be this- subsets[node.data].child = node.right.data; subsets[node.right.data].sibling = node.left.data; This is because if both left and right children of node-'i' are present then we can store any of them in subsets[i].child and correspondingly its sibling*/ subsets[node.data].child = node.left.data; subsets[node.left.data].sibling = node.right.data; } else if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { if(node.left != null && node.right == null) subsets[node.data].child = node.left.data; else subsets[node.data].child = node.right.data; } // Recur on right child preprocess (node.right, subsets);} // A function to initialise prior to pre-processing and// LCA walkfunction initialise(subsets){ // We colour all nodes WHITE before LCA Walk. for (let i = 1; i < subsets.length; i++) { subsets[i] = new subset(); subsets[i].color = WHITE; } return;} // Prints LCAs for given queries q[0..m-1] in a tree// with given rootfunction printLCAs(root, q, m){ // Allocate memory for V subsets and nodes let subsets = new Array(V + 1); // Creates subsets and colors them WHITE initialise(subsets); // Preprocess the tree preprocess(root, subsets); // Perform a tree walk to process the LCA queries // offline lcaWalk(root.data , q, m, subsets);} // Driver code/* We construct a binary tree :- 1 / \\ 2 3 / \\ 4 5 */ let root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5); // LCA Queries to answerlet q = new Array(3);q[0] = new Query(5, 4);q[1] = new Query(1, 3);q[2] = new Query(2, 3);let m = q.length;printLCAs(root, q, m); // This code is contributed by patel2127</script>",
"e": 33631,
"s": 27511,
"text": null
},
{
"code": null,
"e": 33641,
"s": 33631,
"text": "Output : "
},
{
"code": null,
"e": 33683,
"s": 33641,
"text": "LCA(5 4) -> 2\nLCA(2 3) -> 1\nLCA(1 3) -> 1"
},
{
"code": null,
"e": 33845,
"s": 33683,
"text": "Time Complexity : Super-linear, i.e- barely slower than linear. O(N + Q) time, where O(N) time for pre-processing and almost O(1) time for answering the queries."
},
{
"code": null,
"e": 34224,
"s": 33845,
"text": "Auxiliary Space : We use a many arrays- parent[], rank[], ancestor[] which are used in Disjoint Set Union Operations each with the size equal to the number of nodes. We also use the arrays- child[], sibling[], color[] which are useful in this offline algorithm. Hence, we use O(N). For convenience, all these arrays are put up in a structure- struct subset to hold these arrays."
},
{
"code": null,
"e": 34812,
"s": 34224,
"text": "References https://en.wikipedia.org/wiki/Tarjan%27s_off-line_lowest_common_ancestors_algorithm CLRS, Section-21-3, Pg 584, 2nd /3rd edition http://wcipeg.com/wiki/Lowest_common_ancestor#OfflineThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 34826,
"s": 34812,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34836,
"s": 34826,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34848,
"s": 34836,
"text": "sanjeev2552"
},
{
"code": null,
"e": 34858,
"s": 34848,
"text": "patel2127"
},
{
"code": null,
"e": 34877,
"s": 34858,
"text": "surindertarika1234"
},
{
"code": null,
"e": 34890,
"s": 34877,
"text": "simmytarika5"
},
{
"code": null,
"e": 34907,
"s": 34890,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34911,
"s": 34907,
"text": "LCA"
},
{
"code": null,
"e": 34922,
"s": 34911,
"text": "union-find"
},
{
"code": null,
"e": 34946,
"s": 34922,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 34957,
"s": 34946,
"text": "union-find"
}
] |
Strings in Julia
|
20 Apr, 2020
Strings in Julia are a set of characters or a single character that is enclosed within double quotes(” “). It is a finite sequence of characters. Julia allows extracting elements of a string to form multiple substrings with the use of square brackets([ ]).
Strings in Julia can be created using double quotes and triple quotes.
# Julia Program for # Creation of String # Creating a String # with double Quotes String1 = "Welcome to the Geeks World"println("String with the use of Double Quotes: ") println(String1) # Creating a String # with triple Quotes String1 = """I'm a Geek and I live in a world of Geeks"""println("\nString with the use of Triple Quotes: ") println(String1) # Creating String with triple # Quotes allows multiple lines String1 ="""Geeks For Life"""println("\nCreating a multiline String: ") println(String1)
Output:
Julia allows extracting characters by accessing a String with the use of Indexing. To extract a character, just pass the index value or a range of values in square brackets([]). While accessing an index out of the range will cause a BoundsError. Only Integers are allowed to be passed as an index, float or other types will also cause a BoundsError.
# Julia Program to Access # characters of String String1 = "GeeksForGeeks"println("Initial String: ") println(String1) # Printing First character println("\nFirst character of String is: ") println(String1[1]) # Printing Last character println("\nLast character of String is: ") println(String1[end])
Output:
Slicing of a String is done to access a range of characters in a String. It is done by passing a range of Index values with the use of a Slicing Operator(colon) within the square brackets([]).
# Julia Program to Access # characters of String String1 = "GeeksForGeeks"println("Initial String: ") println(String1) # Printing 1st to 5th character println("\nSlicing characters from 1-5: ") println(String1[1:5]) # Printing characters between # 4th and 3rd last character println("\nSlicing characters between ", "4th and 3rd last character: ") println(String1[4:end-2])
The concatenation of strings is the process of adding two or more strings together to form one single string. Concatenation of Strings in Julia can be done in a very simple way by using string(str1, str2, ...) function.
# Julia Program to concatenate# two or more strings # Declaring String 1String1 = "Geeks"println("String1: ") println(String1) # Declaring String 2String2 = "for"println("\nString2: ") println(String2) # Declaring String 3String3 = "Geeks"println("\nString3: ") println(String3) # String concatenation functionString4 = string(String1, String2, String3) # Final String after concatenationprintln("\nFinal String:")println(String4)
Output:
Interpolation of Strings is the process of substituting variable values or expressions in a String. It is a process of combining strings but without using the method of concatenation. Interpolation is basically the process of executing whatever that is executable in a string. In Julia, a dollar sign($) is used to insert the value of a variable in the string.
# Julia Program to for# Interpolation of Strings # Declaring a string str1 = "Geek" # Declaring a Numberscore = 47 # Interpolation of StringString = "Hello $str1, your score is $score" # Printing Final Stringprintln(String)
Output:
Julia-dataTypes
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2020"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Strings in Julia are a set of characters or a single character that is enclosed within double quotes(” “). It is a finite sequence of characters. Julia allows extracting elements of a string to form multiple substrings with the use of square brackets([ ])."
},
{
"code": null,
"e": 356,
"s": 285,
"text": "Strings in Julia can be created using double quotes and triple quotes."
},
{
"code": "# Julia Program for # Creation of String # Creating a String # with double Quotes String1 = \"Welcome to the Geeks World\"println(\"String with the use of Double Quotes: \") println(String1) # Creating a String # with triple Quotes String1 = \"\"\"I'm a Geek and I live in a world of Geeks\"\"\"println(\"\\nString with the use of Triple Quotes: \") println(String1) # Creating String with triple # Quotes allows multiple lines String1 =\"\"\"Geeks For Life\"\"\"println(\"\\nCreating a multiline String: \") println(String1) ",
"e": 891,
"s": 356,
"text": null
},
{
"code": null,
"e": 899,
"s": 891,
"text": "Output:"
},
{
"code": null,
"e": 1249,
"s": 899,
"text": "Julia allows extracting characters by accessing a String with the use of Indexing. To extract a character, just pass the index value or a range of values in square brackets([]). While accessing an index out of the range will cause a BoundsError. Only Integers are allowed to be passed as an index, float or other types will also cause a BoundsError."
},
{
"code": "# Julia Program to Access # characters of String String1 = \"GeeksForGeeks\"println(\"Initial String: \") println(String1) # Printing First character println(\"\\nFirst character of String is: \") println(String1[1]) # Printing Last character println(\"\\nLast character of String is: \") println(String1[end]) ",
"e": 1563,
"s": 1249,
"text": null
},
{
"code": null,
"e": 1571,
"s": 1563,
"text": "Output:"
},
{
"code": null,
"e": 1764,
"s": 1571,
"text": "Slicing of a String is done to access a range of characters in a String. It is done by passing a range of Index values with the use of a Slicing Operator(colon) within the square brackets([])."
},
{
"code": "# Julia Program to Access # characters of String String1 = \"GeeksForGeeks\"println(\"Initial String: \") println(String1) # Printing 1st to 5th character println(\"\\nSlicing characters from 1-5: \") println(String1[1:5]) # Printing characters between # 4th and 3rd last character println(\"\\nSlicing characters between \", \"4th and 3rd last character: \") println(String1[4:end-2]) ",
"e": 2159,
"s": 1764,
"text": null
},
{
"code": null,
"e": 2379,
"s": 2159,
"text": "The concatenation of strings is the process of adding two or more strings together to form one single string. Concatenation of Strings in Julia can be done in a very simple way by using string(str1, str2, ...) function."
},
{
"code": "# Julia Program to concatenate# two or more strings # Declaring String 1String1 = \"Geeks\"println(\"String1: \") println(String1) # Declaring String 2String2 = \"for\"println(\"\\nString2: \") println(String2) # Declaring String 3String3 = \"Geeks\"println(\"\\nString3: \") println(String3) # String concatenation functionString4 = string(String1, String2, String3) # Final String after concatenationprintln(\"\\nFinal String:\")println(String4)",
"e": 2818,
"s": 2379,
"text": null
},
{
"code": null,
"e": 2826,
"s": 2818,
"text": "Output:"
},
{
"code": null,
"e": 3187,
"s": 2826,
"text": "Interpolation of Strings is the process of substituting variable values or expressions in a String. It is a process of combining strings but without using the method of concatenation. Interpolation is basically the process of executing whatever that is executable in a string. In Julia, a dollar sign($) is used to insert the value of a variable in the string."
},
{
"code": "# Julia Program to for# Interpolation of Strings # Declaring a string str1 = \"Geek\" # Declaring a Numberscore = 47 # Interpolation of StringString = \"Hello $str1, your score is $score\" # Printing Final Stringprintln(String)",
"e": 3415,
"s": 3187,
"text": null
},
{
"code": null,
"e": 3423,
"s": 3415,
"text": "Output:"
},
{
"code": null,
"e": 3439,
"s": 3423,
"text": "Julia-dataTypes"
},
{
"code": null,
"e": 3445,
"s": 3439,
"text": "Julia"
}
] |
Breadth First Search or BFS for a Graph
|
27 Jun, 2022
Breadth-First Traversal (or Search) for a graph is similar to Breadth-First Traversal of a tree (See method 2 of this post). The only catch here is, that, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex. BFS uses a queue data structure for traversal.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process.
There can be multiple BFS traversals for a graph. Different BFS traversals for the above graph :2, 3, 0, 1 2, 0, 3, 1
Following are the implementations of simple Breadth-First Traversal from a given source. The implementation uses an adjacency list representation of graphs. STL‘s list container stores lists of adjacent nodes and the queue of nodes needed for BFS traversal.
C++
Java
Python3
C#
// Program to print BFS traversal from a given// source vertex. BFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency // lists vector<list<int>> adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V){ this->V = V; adj.resize(V);} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::BFS(int s){ // Mark all the vertices as not visited vector<bool> visited; visited.resize(V,false); // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (auto adjecent: adj[s]) { if (!visited[adjecent]) { visited[adjecent] = true; queue.push_back(adjecent); } } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); return 0;}
// Java program to print BFS traversal from a given source vertex.// BFS(int s) traverses vertices reachable from s.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+" "); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.BFS(2); }}// This code is contributed by Aakash Hasija
# Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = " ") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print ("Following is Breadth First Traversal" " (starting from vertex 2)")g.BFS(2) # This code is contributed by Neelam Yadav
// C# program to print BFS traversal// from a given source vertex.// BFS(int s) traverses vertices// reachable from s.using System;using System.Collections.Generic;using System.Linq;using System.Text; // This class represents a directed// graph using adjacency list// representationclass Graph{ // No. of vertices private int _V; //Adjacency ListsLinkedList<int>[] _adj; public Graph(int V){ _adj = new LinkedList<int>[V]; for(int i = 0; i < _adj.Length; i++) { _adj[i] = new LinkedList<int>(); } _V = V;} // Function to add an edge into the graphpublic void AddEdge(int v, int w){ _adj[v].AddLast(w); } // Prints BFS traversal from a given source spublic void BFS(int s){ // Mark all the vertices as not // visited(By default set as false) bool[] visited = new bool[_V]; for(int i = 0; i < _V; i++) visited[i] = false; // Create a queue for BFS LinkedList<int> queue = new LinkedList<int>(); // Mark the current node as // visited and enqueue it visited[s] = true; queue.AddLast(s); while(queue.Any()) { // Dequeue a vertex from queue // and print it s = queue.First(); Console.Write(s + " " ); queue.RemoveFirst(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent // has not been visited, then mark it // visited and enqueue it LinkedList<int> list = _adj[s]; foreach (var val in list) { if (!visited[val]) { visited[val] = true; queue.AddLast(val); } } }} // Driver codestatic void Main(string[] args){ Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.Write("Following is Breadth First " + "Traversal(starting from " + "vertex 2)\n"); g.BFS(2);}} // This code is contributed by anv89
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
Time Complexity: O(V+E), where V is the number of nodes and E is the number of edges.Auxiliary Space: O(V)
Illustration :
Note that the above code traverses only the vertices reachable from a given source vertex. The vertices may not be reachable from a given vertex (for example Disconnected graph).
To print all the vertices, we can modify the BFS function to do traversal starting from all nodes one by one (Like the DFS modified version).
The C++ code for BFS traversal for the entire graph (valid for directed as well as undirected graphs) with possible multiple disconnected components is as follows:
C++
/******************************************************* * Generic Function for BFS traversal of a Graph * (valid for directed as well as undirected graphs * which can have multiple disconnected commponents) * ********** Inputs ************************************* * V - represents number of vertices in the Graph * adj[] - represents adjacency list for the Graph * ********** Output ************************************* * bfs_traversal - a vector containing bfs traversal * for entire graph *******************************************************/ vector<int> bfsOfGraph(int V, vector<int> adj[]){ vector<int> bfs_traversal; vector<bool> vis(V, false); for (int i = 0; i < V; ++i) { if (!vis[i]) { queue<int> q; vis[i] = true; q.push(i); while (!q.empty()) { int g_node = q.front(); q.pop(); bfs_traversal.push_back(g_node); for (auto it : adj[g_node]) { if (!vis[it]) { vis[it] = true; q.push(it); } } } } } return bfs_traversal;}
Breadth First Traversal for a Graph | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersBreadth First Traversal for a Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0u78hx-66Xk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
You may like to see below also :
Recent Articles on BFS
Depth First Traversal
Applications of Breadth First Traversal
Applications of Depth First Search
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anvudemy1
atharvacp20
surinderdawra388
punamsingh628700
vladozaric
akjlucky4all
devendrasalunke
aayushi2402
BFS
graph-basics
Graph
Queue
Graph
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Detect Cycle in a Directed Graph
Introduction to Data Structures
Level Order Binary Tree Traversal
Queue in Python
Queue Interface In Java
Introduction to Data Structures
Queue using Stacks
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 497,
"s": 52,
"text": "Breadth-First Traversal (or Search) for a graph is similar to Breadth-First Traversal of a tree (See method 2 of this post). The only catch here is, that, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex. BFS uses a queue data structure for traversal."
},
{
"code": null,
"e": 783,
"s": 497,
"text": "For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. "
},
{
"code": null,
"e": 901,
"s": 783,
"text": "There can be multiple BFS traversals for a graph. Different BFS traversals for the above graph :2, 3, 0, 1 2, 0, 3, 1"
},
{
"code": null,
"e": 1159,
"s": 901,
"text": "Following are the implementations of simple Breadth-First Traversal from a given source. The implementation uses an adjacency list representation of graphs. STL‘s list container stores lists of adjacent nodes and the queue of nodes needed for BFS traversal."
},
{
"code": null,
"e": 1163,
"s": 1159,
"text": "C++"
},
{
"code": null,
"e": 1168,
"s": 1163,
"text": "Java"
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Python3"
},
{
"code": null,
"e": 1179,
"s": 1176,
"text": "C#"
},
{
"code": "// Program to print BFS traversal from a given// source vertex. BFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency // lists vector<list<int>> adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V){ this->V = V; adj.resize(V);} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::BFS(int s){ // Mark all the vertices as not visited vector<bool> visited; visited.resize(V,false); // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << \" \"; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (auto adjecent: adj[s]) { if (!visited[adjecent]) { visited[adjecent] = true; queue.push_back(adjecent); } } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << \"Following is Breadth First Traversal \" << \"(starting from vertex 2) \\n\"; g.BFS(2); return 0;}",
"e": 3022,
"s": 1179,
"text": null
},
{
"code": "// Java program to print BFS traversal from a given source vertex.// BFS(int s) traverses vertices reachable from s.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+\" \"); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println(\"Following is Breadth First Traversal \"+ \"(starting from vertex 2)\"); g.BFS(2); }}// This code is contributed by Aakash Hasija",
"e": 5092,
"s": 3022,
"text": null
},
{
"code": "# Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = \" \") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print (\"Following is Breadth First Traversal\" \" (starting from vertex 2)\")g.BFS(2) # This code is contributed by Neelam Yadav",
"e": 6651,
"s": 5092,
"text": null
},
{
"code": "// C# program to print BFS traversal// from a given source vertex.// BFS(int s) traverses vertices// reachable from s.using System;using System.Collections.Generic;using System.Linq;using System.Text; // This class represents a directed// graph using adjacency list// representationclass Graph{ // No. of vertices private int _V; //Adjacency ListsLinkedList<int>[] _adj; public Graph(int V){ _adj = new LinkedList<int>[V]; for(int i = 0; i < _adj.Length; i++) { _adj[i] = new LinkedList<int>(); } _V = V;} // Function to add an edge into the graphpublic void AddEdge(int v, int w){ _adj[v].AddLast(w); } // Prints BFS traversal from a given source spublic void BFS(int s){ // Mark all the vertices as not // visited(By default set as false) bool[] visited = new bool[_V]; for(int i = 0; i < _V; i++) visited[i] = false; // Create a queue for BFS LinkedList<int> queue = new LinkedList<int>(); // Mark the current node as // visited and enqueue it visited[s] = true; queue.AddLast(s); while(queue.Any()) { // Dequeue a vertex from queue // and print it s = queue.First(); Console.Write(s + \" \" ); queue.RemoveFirst(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent // has not been visited, then mark it // visited and enqueue it LinkedList<int> list = _adj[s]; foreach (var val in list) { if (!visited[val]) { visited[val] = true; queue.AddLast(val); } } }} // Driver codestatic void Main(string[] args){ Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.Write(\"Following is Breadth First \" + \"Traversal(starting from \" + \"vertex 2)\\n\"); g.BFS(2);}} // This code is contributed by anv89",
"e": 8712,
"s": 6651,
"text": null
},
{
"code": null,
"e": 8784,
"s": 8712,
"text": "Following is Breadth First Traversal (starting from vertex 2) \n2 0 3 1 "
},
{
"code": null,
"e": 8891,
"s": 8784,
"text": "Time Complexity: O(V+E), where V is the number of nodes and E is the number of edges.Auxiliary Space: O(V)"
},
{
"code": null,
"e": 8907,
"s": 8891,
"text": "Illustration : "
},
{
"code": null,
"e": 9095,
"s": 8915,
"text": "Note that the above code traverses only the vertices reachable from a given source vertex. The vertices may not be reachable from a given vertex (for example Disconnected graph). "
},
{
"code": null,
"e": 9238,
"s": 9095,
"text": "To print all the vertices, we can modify the BFS function to do traversal starting from all nodes one by one (Like the DFS modified version). "
},
{
"code": null,
"e": 9402,
"s": 9238,
"text": "The C++ code for BFS traversal for the entire graph (valid for directed as well as undirected graphs) with possible multiple disconnected components is as follows:"
},
{
"code": null,
"e": 9406,
"s": 9402,
"text": "C++"
},
{
"code": "/******************************************************* * Generic Function for BFS traversal of a Graph * (valid for directed as well as undirected graphs * which can have multiple disconnected commponents) * ********** Inputs ************************************* * V - represents number of vertices in the Graph * adj[] - represents adjacency list for the Graph * ********** Output ************************************* * bfs_traversal - a vector containing bfs traversal * for entire graph *******************************************************/ vector<int> bfsOfGraph(int V, vector<int> adj[]){ vector<int> bfs_traversal; vector<bool> vis(V, false); for (int i = 0; i < V; ++i) { if (!vis[i]) { queue<int> q; vis[i] = true; q.push(i); while (!q.empty()) { int g_node = q.front(); q.pop(); bfs_traversal.push_back(g_node); for (auto it : adj[g_node]) { if (!vis[it]) { vis[it] = true; q.push(it); } } } } } return bfs_traversal;}",
"e": 10601,
"s": 9406,
"text": null
},
{
"code": null,
"e": 11491,
"s": 10603,
"text": "Breadth First Traversal for a Graph | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersBreadth First Traversal for a Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0u78hx-66Xk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 11525,
"s": 11491,
"text": "You may like to see below also : "
},
{
"code": null,
"e": 11548,
"s": 11525,
"text": "Recent Articles on BFS"
},
{
"code": null,
"e": 11570,
"s": 11548,
"text": "Depth First Traversal"
},
{
"code": null,
"e": 11610,
"s": 11570,
"text": "Applications of Breadth First Traversal"
},
{
"code": null,
"e": 11645,
"s": 11610,
"text": "Applications of Depth First Search"
},
{
"code": null,
"e": 11771,
"s": 11645,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11781,
"s": 11771,
"text": "anvudemy1"
},
{
"code": null,
"e": 11793,
"s": 11781,
"text": "atharvacp20"
},
{
"code": null,
"e": 11810,
"s": 11793,
"text": "surinderdawra388"
},
{
"code": null,
"e": 11827,
"s": 11810,
"text": "punamsingh628700"
},
{
"code": null,
"e": 11838,
"s": 11827,
"text": "vladozaric"
},
{
"code": null,
"e": 11851,
"s": 11838,
"text": "akjlucky4all"
},
{
"code": null,
"e": 11867,
"s": 11851,
"text": "devendrasalunke"
},
{
"code": null,
"e": 11879,
"s": 11867,
"text": "aayushi2402"
},
{
"code": null,
"e": 11883,
"s": 11879,
"text": "BFS"
},
{
"code": null,
"e": 11896,
"s": 11883,
"text": "graph-basics"
},
{
"code": null,
"e": 11902,
"s": 11896,
"text": "Graph"
},
{
"code": null,
"e": 11908,
"s": 11902,
"text": "Queue"
},
{
"code": null,
"e": 11914,
"s": 11908,
"text": "Graph"
},
{
"code": null,
"e": 11920,
"s": 11914,
"text": "Queue"
},
{
"code": null,
"e": 11924,
"s": 11920,
"text": "BFS"
},
{
"code": null,
"e": 12022,
"s": 11924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12073,
"s": 12022,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 12131,
"s": 12073,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 12196,
"s": 12131,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 12229,
"s": 12196,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 12261,
"s": 12229,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12295,
"s": 12261,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 12311,
"s": 12295,
"text": "Queue in Python"
},
{
"code": null,
"e": 12335,
"s": 12311,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 12367,
"s": 12335,
"text": "Introduction to Data Structures"
}
] |
R – Keywords
|
22 Jun, 2020
R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool.
Keywords are specific reserved words in R, each of which has a specific feature associated with it. Almost all of the words which help one to use the functionality of the R language are included in the list of keywords. So one can imagine that the list of keywords is not going to be a small one! In R, one can view these keywords by using either help(reserved) or ?reserved. Here is the list of keywords in R:
Following are some most important keywords along with their examples:
if: If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Example:# R program to illustrate if statement # assigning value to variable a a <- 5 # condition if( a > 0 ) { print("Positive Number") # Statement } Output:Positive Number
# R program to illustrate if statement # assigning value to variable a a <- 5 # condition if( a > 0 ) { print("Positive Number") # Statement }
Output:
Positive Number
else: It is similar to if statement but when the test expression in if condition fails, then statements in else condition are executed.Example:x <- 5 # Check value is less than or greater than 10 if(x > 10){ print(paste(x, "is greater than 10")) }else{ print(paste(x, "is less than 10")) }Output:[1] "5 is less than 10"
x <- 5 # Check value is less than or greater than 10 if(x > 10){ print(paste(x, "is greater than 10")) }else{ print(paste(x, "is less than 10")) }
Output:
[1] "5 is less than 10"
while: It is a type of control statement which will run a statement or a set of statements repeatedly unless the given condition becomes false. It is also an entry controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.Example:# R program to demonstrate the use of while loop val = 1 # using while loop while (val <= 5 ) { # statements print(val) val = val + 1} Output:[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# R program to demonstrate the use of while loop val = 1 # using while loop while (val <= 5 ) { # statements print(val) val = val + 1}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
repeat: It is a simple loop that will run the same statement or a group of statements repeatedly until the stop condition has been encountered. Repeat loop does not have any condition to terminate the loop, a programmer must specifically place a condition within the loop’s body and use the declaration of a break statement to terminate this loop. If no condition is present in the body of the repeat loop then it will iterate infinitely.Example:# R program to demonstrate the use of repeat loop val = 1 # using repeat loop repeat { # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break } } Output:[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# R program to demonstrate the use of repeat loop val = 1 # using repeat loop repeat { # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break } }
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
for: It is a type of control statement that enables one to easily construct a loop that has to run statements or a set of statements multiple times. For loop is commonly used to iterate over items of a sequence. It is an entry controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.Example:# R program to demonstrate the use of for loop # using for loop for (val in 1:5) { # statement print(val) } Output:[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# R program to demonstrate the use of for loop # using for loop for (val in 1:5) { # statement print(val) }
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
function: Functions are useful when you want to perform a certain task multiple number of times. In R functions are created using function keyword.Example:# A simple R function to check # whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return("even") else return("odd") } print(evenOdd(4)) print(evenOdd(3)) Output:[1] "even"
[1] "odd"
# A simple R function to check # whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return("even") else return("odd") } print(evenOdd(4)) print(evenOdd(3))
Output:
[1] "even"
[1] "odd"
next:Next statement in R is used to skip any remaining statements in the loop and continue the execution of the program. In other words, it is a statement that skips the current iteration without loop termination.Example:# R program to illustrate next in for loop val <- 6:11 # Loop for (i in val) { if (i == 8) { # test expression next } print(i) } Output:[1] 6
[1] 7
[1] 9
[1] 10
[1] 11
# R program to illustrate next in for loop val <- 6:11 # Loop for (i in val) { if (i == 8) { # test expression next } print(i) }
Output:
[1] 6
[1] 7
[1] 9
[1] 10
[1] 11
break: The break keyword is a jump statement that is used to terminate the loop at a particular iteration.Example:# R Break Statement Example a<-1 while (a < 10) { print(a) if(a == 5) break a = a + 1 } Output:[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# R Break Statement Example a<-1 while (a < 10) { print(a) if(a == 5) break a = a + 1 }
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
TRUE/FALSE: The TRUE and FALSE keywords are used to represent a Boolean true and Boolean false. If the given statement is true, then the interpreter returns true else the interpreter returns false.Example:# A simple R program # to illustrate TRUE / FALSE # Sample values x = 4y = 3 # Comparing two values z = x > y p = x < y # print the logical value print(z) print(p)Output:[1] TRUE
[1] FALSE
# A simple R program # to illustrate TRUE / FALSE # Sample values x = 4y = 3 # Comparing two values z = x > y p = x < y # print the logical value print(z) print(p)
Output:
[1] TRUE
[1] FALSE
NULL: In R, NULL represents the null object. NULL is used to represent missing and undefined values. NULL is the logical representation of a statement which is neither TRUE nor FALSE.Example:# A simple R program # to illustrate NULL v = as.null(c(1, 2, 3, 4))print(v)Output:NULL
# A simple R program # to illustrate NULL v = as.null(c(1, 2, 3, 4))print(v)
Output:
NULL
Inf and NaN: In R is.finite and is.infinite return a vector of the same length as x, where x is an R object to be tested. This indicating which elements are finite (not infinite and not missing) or infinite. Inf and -Inf keyword mean positive and negative infinity whereas NaN keyword means ‘Not a Number’.# A simple R program # to illustrate Inf and NaN # To check Infx = c(Inf, 2, 3)print(is.finite(x)) # To check NaNy = c(1, NaN, 3)print(is.nan(y))Output:[1] FALSE TRUE TRUE
[1] FALSE TRUE FALSE
# A simple R program # to illustrate Inf and NaN # To check Infx = c(Inf, 2, 3)print(is.finite(x)) # To check NaNy = c(1, NaN, 3)print(is.nan(y))
Output:
[1] FALSE TRUE TRUE
[1] FALSE TRUE FALSE
NA: NA stands for “Not Available” and is used to represent missing values. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values and all of these are reserved words in the R language.# A simple R program # to illustrate NA # To check NAx = c(1, NA, 2, 3)print(is.na(x))Output:[1] FALSE TRUE FALSE FALSE
# A simple R program # to illustrate NA # To check NAx = c(1, NA, 2, 3)print(is.na(x))
Output:
[1] FALSE TRUE FALSE FALSE
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool."
},
{
"code": null,
"e": 769,
"s": 358,
"text": "Keywords are specific reserved words in R, each of which has a specific feature associated with it. Almost all of the words which help one to use the functionality of the R language are included in the list of keywords. So one can imagine that the list of keywords is not going to be a small one! In R, one can view these keywords by using either help(reserved) or ?reserved. Here is the list of keywords in R:"
},
{
"code": null,
"e": 839,
"s": 769,
"text": "Following are some most important keywords along with their examples:"
},
{
"code": null,
"e": 1346,
"s": 839,
"text": "if: If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Example:# R program to illustrate if statement # assigning value to variable a a <- 5 # condition if( a > 0 ) { print(\"Positive Number\") # Statement } Output:Positive Number\n"
},
{
"code": "# R program to illustrate if statement # assigning value to variable a a <- 5 # condition if( a > 0 ) { print(\"Positive Number\") # Statement } ",
"e": 1497,
"s": 1346,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Output:"
},
{
"code": null,
"e": 1522,
"s": 1505,
"text": "Positive Number\n"
},
{
"code": null,
"e": 1852,
"s": 1522,
"text": "else: It is similar to if statement but when the test expression in if condition fails, then statements in else condition are executed.Example:x <- 5 # Check value is less than or greater than 10 if(x > 10){ print(paste(x, \"is greater than 10\")) }else{ print(paste(x, \"is less than 10\")) }Output:[1] \"5 is less than 10\"\n"
},
{
"code": "x <- 5 # Check value is less than or greater than 10 if(x > 10){ print(paste(x, \"is greater than 10\")) }else{ print(paste(x, \"is less than 10\")) }",
"e": 2008,
"s": 1852,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Output:"
},
{
"code": null,
"e": 2041,
"s": 2016,
"text": "[1] \"5 is less than 10\"\n"
},
{
"code": null,
"e": 2573,
"s": 2041,
"text": "while: It is a type of control statement which will run a statement or a set of statements repeatedly unless the given condition becomes false. It is also an entry controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.Example:# R program to demonstrate the use of while loop val = 1 # using while loop while (val <= 5 ) { # statements print(val) val = val + 1} Output:[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": "# R program to demonstrate the use of while loop val = 1 # using while loop while (val <= 5 ) { # statements print(val) val = val + 1} ",
"e": 2724,
"s": 2573,
"text": null
},
{
"code": null,
"e": 2732,
"s": 2724,
"text": "Output:"
},
{
"code": null,
"e": 2763,
"s": 2732,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 3529,
"s": 2763,
"text": "repeat: It is a simple loop that will run the same statement or a group of statements repeatedly until the stop condition has been encountered. Repeat loop does not have any condition to terminate the loop, a programmer must specifically place a condition within the loop’s body and use the declaration of a break statement to terminate this loop. If no condition is present in the body of the repeat loop then it will iterate infinitely.Example:# R program to demonstrate the use of repeat loop val = 1 # using repeat loop repeat { # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break } } Output:[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": "# R program to demonstrate the use of repeat loop val = 1 # using repeat loop repeat { # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break } } ",
"e": 3812,
"s": 3529,
"text": null
},
{
"code": null,
"e": 3820,
"s": 3812,
"text": "Output:"
},
{
"code": null,
"e": 3851,
"s": 3820,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 4414,
"s": 3851,
"text": "for: It is a type of control statement that enables one to easily construct a loop that has to run statements or a set of statements multiple times. For loop is commonly used to iterate over items of a sequence. It is an entry controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.Example:# R program to demonstrate the use of for loop # using for loop for (val in 1:5) { # statement print(val) } Output:[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": "# R program to demonstrate the use of for loop # using for loop for (val in 1:5) { # statement print(val) } ",
"e": 4533,
"s": 4414,
"text": null
},
{
"code": null,
"e": 4541,
"s": 4533,
"text": "Output:"
},
{
"code": null,
"e": 4572,
"s": 4541,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 4936,
"s": 4572,
"text": "function: Functions are useful when you want to perform a certain task multiple number of times. In R functions are created using function keyword.Example:# A simple R function to check # whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return(\"even\") else return(\"odd\") } print(evenOdd(4)) print(evenOdd(3)) Output:[1] \"even\"\n[1] \"odd\"\n"
},
{
"code": "# A simple R function to check # whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return(\"even\") else return(\"odd\") } print(evenOdd(4)) print(evenOdd(3)) ",
"e": 5117,
"s": 4936,
"text": null
},
{
"code": null,
"e": 5125,
"s": 5117,
"text": "Output:"
},
{
"code": null,
"e": 5147,
"s": 5125,
"text": "[1] \"even\"\n[1] \"odd\"\n"
},
{
"code": null,
"e": 5571,
"s": 5147,
"text": "next:Next statement in R is used to skip any remaining statements in the loop and continue the execution of the program. In other words, it is a statement that skips the current iteration without loop termination.Example:# R program to illustrate next in for loop val <- 6:11 # Loop for (i in val) { if (i == 8) { # test expression next } print(i) } Output:[1] 6\n[1] 7\n[1] 9\n[1] 10\n[1] 11\n"
},
{
"code": "# R program to illustrate next in for loop val <- 6:11 # Loop for (i in val) { if (i == 8) { # test expression next } print(i) } ",
"e": 5735,
"s": 5571,
"text": null
},
{
"code": null,
"e": 5743,
"s": 5735,
"text": "Output:"
},
{
"code": null,
"e": 5776,
"s": 5743,
"text": "[1] 6\n[1] 7\n[1] 9\n[1] 10\n[1] 11\n"
},
{
"code": null,
"e": 6061,
"s": 5776,
"text": "break: The break keyword is a jump statement that is used to terminate the loop at a particular iteration.Example:# R Break Statement Example a<-1 while (a < 10) { print(a) if(a == 5) break a = a + 1 } Output:[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": "# R Break Statement Example a<-1 while (a < 10) { print(a) if(a == 5) break a = a + 1 } ",
"e": 6195,
"s": 6061,
"text": null
},
{
"code": null,
"e": 6203,
"s": 6195,
"text": "Output:"
},
{
"code": null,
"e": 6234,
"s": 6203,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 6634,
"s": 6234,
"text": "TRUE/FALSE: The TRUE and FALSE keywords are used to represent a Boolean true and Boolean false. If the given statement is true, then the interpreter returns true else the interpreter returns false.Example:# A simple R program # to illustrate TRUE / FALSE # Sample values x = 4y = 3 # Comparing two values z = x > y p = x < y # print the logical value print(z) print(p)Output:[1] TRUE\n[1] FALSE\n"
},
{
"code": "# A simple R program # to illustrate TRUE / FALSE # Sample values x = 4y = 3 # Comparing two values z = x > y p = x < y # print the logical value print(z) print(p)",
"e": 6803,
"s": 6634,
"text": null
},
{
"code": null,
"e": 6811,
"s": 6803,
"text": "Output:"
},
{
"code": null,
"e": 6831,
"s": 6811,
"text": "[1] TRUE\n[1] FALSE\n"
},
{
"code": null,
"e": 7112,
"s": 6831,
"text": "NULL: In R, NULL represents the null object. NULL is used to represent missing and undefined values. NULL is the logical representation of a statement which is neither TRUE nor FALSE.Example:# A simple R program # to illustrate NULL v = as.null(c(1, 2, 3, 4))print(v)Output:NULL\n"
},
{
"code": "# A simple R program # to illustrate NULL v = as.null(c(1, 2, 3, 4))print(v)",
"e": 7190,
"s": 7112,
"text": null
},
{
"code": null,
"e": 7198,
"s": 7190,
"text": "Output:"
},
{
"code": null,
"e": 7204,
"s": 7198,
"text": "NULL\n"
},
{
"code": null,
"e": 7709,
"s": 7204,
"text": "Inf and NaN: In R is.finite and is.infinite return a vector of the same length as x, where x is an R object to be tested. This indicating which elements are finite (not infinite and not missing) or infinite. Inf and -Inf keyword mean positive and negative infinity whereas NaN keyword means ‘Not a Number’.# A simple R program # to illustrate Inf and NaN # To check Infx = c(Inf, 2, 3)print(is.finite(x)) # To check NaNy = c(1, NaN, 3)print(is.nan(y))Output:[1] FALSE TRUE TRUE\n[1] FALSE TRUE FALSE\n"
},
{
"code": "# A simple R program # to illustrate Inf and NaN # To check Infx = c(Inf, 2, 3)print(is.finite(x)) # To check NaNy = c(1, NaN, 3)print(is.nan(y))",
"e": 7857,
"s": 7709,
"text": null
},
{
"code": null,
"e": 7865,
"s": 7857,
"text": "Output:"
},
{
"code": null,
"e": 7910,
"s": 7865,
"text": "[1] FALSE TRUE TRUE\n[1] FALSE TRUE FALSE\n"
},
{
"code": null,
"e": 8303,
"s": 7910,
"text": "NA: NA stands for “Not Available” and is used to represent missing values. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values and all of these are reserved words in the R language.# A simple R program # to illustrate NA # To check NAx = c(1, NA, 2, 3)print(is.na(x))Output:[1] FALSE TRUE FALSE FALSE\n"
},
{
"code": "# A simple R program # to illustrate NA # To check NAx = c(1, NA, 2, 3)print(is.na(x))",
"e": 8392,
"s": 8303,
"text": null
},
{
"code": null,
"e": 8400,
"s": 8392,
"text": "Output:"
},
{
"code": null,
"e": 8429,
"s": 8400,
"text": "[1] FALSE TRUE FALSE FALSE\n"
},
{
"code": null,
"e": 8436,
"s": 8429,
"text": "Picked"
},
{
"code": null,
"e": 8447,
"s": 8436,
"text": "R Language"
}
] |
Python Program for n-th Fibonacci number
|
12 Jan, 2022
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
With seed values
F0 = 0 and F1 = 1.
Method 1 ( Use recursion ) :
Python3
# Function for nth Fibonacci number def Fibonacci(n): if n<= 0: print("Incorrect input") # First Fibonacci number is 0 elif n == 1: return 0 # Second Fibonacci number is 1 elif n == 2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(10)) # This code is contributed by Saket Modi
34
Method 2 ( Use Dynamic Programming ) :
Python3
# Function for nth fibonacci number - Dynamic Programming# Taking 1st two fibonacci numbers as 0 and 1 FibArray = [0, 1] def fibonacci(n): if n<0: print("Incorrect input") elif n<= len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib # Driver Program print(fibonacci(9)) # This code is contributed by Saket Modi
21
Output:
21
Method 3 ( Use Dynamic Programming with Space Optimization) :
Python3
# Function for nth fibonacci number - Space Optimisation# Taking 1st two fibonacci numbers as 0 and 1 def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2, n): c = a + b a = b b = c return b # Driver Program print(fibonacci(9)) # This code is contributed by Saket Modi
21
Output:
21
Method 4 ( Using Arrays ) :
Python3
# creating an array in the function to find the nth number in fibonacci series. [0, 1, 1, ...] def fibonacci (n): if n<= 0: return "Incorrect Output" data = [0, 1] if n > 2: for i in range (2, n): data.append(data[i-1] + data[i-2]) return data[n-1] # Driver Program print(fibonacci(9)) # This Code is contributed by Prasun Parate (prasun_parate)
Output :
144
Explanation:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]As we know that the Fibonacci series is the sum of the previous two terms, so if we enter 12 as the input in the program, so we should get 144 as the output. And that is what is the result.
Method 5 ( Using Direct Formula ) :
The formula for finding the n-th Fibonacci number is as follows:
Python3
# To find the n-th Fibonacci Number using formulafrom math import sqrt# import square-root method from math librarydef nthFib(n): res = (((1+sqrt(5))**n)-((1-sqrt(5)))**n)/(2**n*sqrt(5)) # compute the n-th fibonacci number print(int(res),'is',str(n)+'th fibonacci number') # format and print the number # driver codenthFib(12) # This code is contributed by Kush Mehta
144 is 12th fibonacci number
Find nth fibonacci no. using recursive technique. | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersFind nth fibonacci no. using recursive technique. | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4GMh0MfCiqE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please refer complete article on Program for Fibonacci numbers for more details!
prasun_parate
varshagumber28
akshaysingh98088
arorakashish0911
kushmehta170
amartyaghoshgfg
Fibonacci
Python Programs
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Python Program for Bubble Sort
Add a key:value pair to dictionary in Python
Python | Check if a variable is string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 151,
"s": 52,
"text": "In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation "
},
{
"code": null,
"e": 168,
"s": 151,
"text": "Fn = Fn-1 + Fn-2"
},
{
"code": null,
"e": 186,
"s": 168,
"text": "With seed values "
},
{
"code": null,
"e": 205,
"s": 186,
"text": "F0 = 0 and F1 = 1."
},
{
"code": null,
"e": 234,
"s": 205,
"text": "Method 1 ( Use recursion ) :"
},
{
"code": null,
"e": 242,
"s": 234,
"text": "Python3"
},
{
"code": "# Function for nth Fibonacci number def Fibonacci(n): if n<= 0: print(\"Incorrect input\") # First Fibonacci number is 0 elif n == 1: return 0 # Second Fibonacci number is 1 elif n == 2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(10)) # This code is contributed by Saket Modi",
"e": 604,
"s": 242,
"text": null
},
{
"code": null,
"e": 607,
"s": 604,
"text": "34"
},
{
"code": null,
"e": 647,
"s": 607,
"text": "Method 2 ( Use Dynamic Programming ) : "
},
{
"code": null,
"e": 655,
"s": 647,
"text": "Python3"
},
{
"code": "# Function for nth fibonacci number - Dynamic Programming# Taking 1st two fibonacci numbers as 0 and 1 FibArray = [0, 1] def fibonacci(n): if n<0: print(\"Incorrect input\") elif n<= len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib # Driver Program print(fibonacci(9)) # This code is contributed by Saket Modi",
"e": 1083,
"s": 655,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1083,
"text": "21"
},
{
"code": null,
"e": 1095,
"s": 1086,
"text": "Output: "
},
{
"code": null,
"e": 1098,
"s": 1095,
"text": "21"
},
{
"code": null,
"e": 1161,
"s": 1098,
"text": "Method 3 ( Use Dynamic Programming with Space Optimization) : "
},
{
"code": null,
"e": 1169,
"s": 1161,
"text": "Python3"
},
{
"code": "# Function for nth fibonacci number - Space Optimisation# Taking 1st two fibonacci numbers as 0 and 1 def fibonacci(n): a = 0 b = 1 if n < 0: print(\"Incorrect input\") elif n == 0: return a elif n == 1: return b else: for i in range(2, n): c = a + b a = b b = c return b # Driver Program print(fibonacci(9)) # This code is contributed by Saket Modi",
"e": 1603,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1603,
"text": "21"
},
{
"code": null,
"e": 1615,
"s": 1606,
"text": "Output: "
},
{
"code": null,
"e": 1618,
"s": 1615,
"text": "21"
},
{
"code": null,
"e": 1647,
"s": 1618,
"text": "Method 4 ( Using Arrays ) : "
},
{
"code": null,
"e": 1655,
"s": 1647,
"text": "Python3"
},
{
"code": "# creating an array in the function to find the nth number in fibonacci series. [0, 1, 1, ...] def fibonacci (n): if n<= 0: return \"Incorrect Output\" data = [0, 1] if n > 2: for i in range (2, n): data.append(data[i-1] + data[i-2]) return data[n-1] # Driver Program print(fibonacci(9)) # This Code is contributed by Prasun Parate (prasun_parate)",
"e": 2032,
"s": 1655,
"text": null
},
{
"code": null,
"e": 2041,
"s": 2032,
"text": "Output :"
},
{
"code": null,
"e": 2045,
"s": 2041,
"text": "144"
},
{
"code": null,
"e": 2058,
"s": 2045,
"text": "Explanation:"
},
{
"code": null,
"e": 2295,
"s": 2058,
"text": "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]As we know that the Fibonacci series is the sum of the previous two terms, so if we enter 12 as the input in the program, so we should get 144 as the output. And that is what is the result. "
},
{
"code": null,
"e": 2332,
"s": 2295,
"text": "Method 5 ( Using Direct Formula ) : "
},
{
"code": null,
"e": 2397,
"s": 2332,
"text": "The formula for finding the n-th Fibonacci number is as follows:"
},
{
"code": null,
"e": 2405,
"s": 2397,
"text": "Python3"
},
{
"code": "# To find the n-th Fibonacci Number using formulafrom math import sqrt# import square-root method from math librarydef nthFib(n): res = (((1+sqrt(5))**n)-((1-sqrt(5)))**n)/(2**n*sqrt(5)) # compute the n-th fibonacci number print(int(res),'is',str(n)+'th fibonacci number') # format and print the number # driver codenthFib(12) # This code is contributed by Kush Mehta",
"e": 2789,
"s": 2405,
"text": null
},
{
"code": null,
"e": 2818,
"s": 2789,
"text": "144 is 12th fibonacci number"
},
{
"code": null,
"e": 3734,
"s": 2818,
"text": "Find nth fibonacci no. using recursive technique. | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersFind nth fibonacci no. using recursive technique. | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4GMh0MfCiqE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 3816,
"s": 3734,
"text": "Please refer complete article on Program for Fibonacci numbers for more details! "
},
{
"code": null,
"e": 3830,
"s": 3816,
"text": "prasun_parate"
},
{
"code": null,
"e": 3845,
"s": 3830,
"text": "varshagumber28"
},
{
"code": null,
"e": 3862,
"s": 3845,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 3879,
"s": 3862,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3892,
"s": 3879,
"text": "kushmehta170"
},
{
"code": null,
"e": 3908,
"s": 3892,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 3918,
"s": 3908,
"text": "Fibonacci"
},
{
"code": null,
"e": 3934,
"s": 3918,
"text": "Python Programs"
},
{
"code": null,
"e": 3944,
"s": 3934,
"text": "Fibonacci"
},
{
"code": null,
"e": 4042,
"s": 3944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4076,
"s": 4042,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 4117,
"s": 4076,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 4172,
"s": 4117,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 4218,
"s": 4172,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 4251,
"s": 4218,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 4290,
"s": 4251,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 4327,
"s": 4290,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 4358,
"s": 4327,
"text": "Python Program for Bubble Sort"
},
{
"code": null,
"e": 4403,
"s": 4358,
"text": "Add a key:value pair to dictionary in Python"
}
] |
Creating Pandas dataframe using list of lists
|
22 Jun, 2021
Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object.Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe using list of lists.
Code #1:
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['Geeks', 10], ['for', 15], ['geeks', 20]] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe.print(df )
Name Age
0 Geeks 10
1 for 15
2 geeks 20
Code #2:
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7], ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks']) # print dataframe.print(df )
Category Name Marks
0 DS Linked_list 10
1 DS Stack 9
2 DS Queue 7
3 Algo Greedy 8
4 Algo DP 6
5 Algo BackTrack 5
Code #3: Doing some operation of dataframe.
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [[1, 5, 10], [2, 6, 9], [3, 7, 8]] # Create the pandas DataFramedf = pd.DataFrame(data) # specifying column namesdf.columns = ['Col_1', 'Col_2', 'Col_3'] # print dataframe.print(df, "\n") # transpose of dataframedf = df.transpose()print("Transpose of above dataframe is-\n", df)
Col_1 Col_2 Col_3
0 1 5 10
1 2 6 9
2 3 7 8
Transpose of above dataframe is-
0 1 2
Col_1 1 2 3
Col_2 5 6 7
Col_3 10 9 8
surinderdawra388
pandas-dataframe-program
Python pandas-dataFrame
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 Jun, 2021"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object.Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe using list of lists."
},
{
"code": null,
"e": 311,
"s": 301,
"text": "Code #1: "
},
{
"code": null,
"e": 319,
"s": 311,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['Geeks', 10], ['for', 15], ['geeks', 20]] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe.print(df )",
"e": 548,
"s": 319,
"text": null
},
{
"code": null,
"e": 600,
"s": 548,
"text": "Name Age\n0 Geeks 10\n1 for 15\n2 geeks 20"
},
{
"code": null,
"e": 613,
"s": 602,
"text": " Code #2:"
},
{
"code": null,
"e": 621,
"s": 613,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7], ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks']) # print dataframe.print(df )",
"e": 965,
"s": 621,
"text": null
},
{
"code": null,
"e": 1180,
"s": 965,
"text": "Category Name Marks\n0 DS Linked_list 10\n1 DS Stack 9\n2 DS Queue 7\n3 Algo Greedy 8\n4 Algo DP 6\n5 Algo BackTrack 5"
},
{
"code": null,
"e": 1229,
"s": 1182,
"text": " Code #3: Doing some operation of dataframe. "
},
{
"code": null,
"e": 1237,
"s": 1229,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # initialize list of listsdata = [[1, 5, 10], [2, 6, 9], [3, 7, 8]] # Create the pandas DataFramedf = pd.DataFrame(data) # specifying column namesdf.columns = ['Col_1', 'Col_2', 'Col_3'] # print dataframe.print(df, \"\\n\") # transpose of dataframedf = df.transpose()print(\"Transpose of above dataframe is-\\n\", df)",
"e": 1592,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1592,
"text": "Col_1 Col_2 Col_3\n0 1 5 10\n1 2 6 9\n2 3 7 8 \n\nTranspose of above dataframe is-\n 0 1 2\nCol_1 1 2 3\nCol_2 5 6 7\nCol_3 10 9 8"
},
{
"code": null,
"e": 1800,
"s": 1783,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1825,
"s": 1800,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 1849,
"s": 1825,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1863,
"s": 1849,
"text": "Python-pandas"
},
{
"code": null,
"e": 1870,
"s": 1863,
"text": "Python"
}
] |
primary_key – Django Built-in Field Validation
|
19 Feb, 2021
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. primary_key=True will make the field PRIMARY KEY for that table (model).If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.
Note: primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.
Syntax
field_name = models.Field(primary_key = True)
Illustration of primary_key=True using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using IntegerField for experimenting for primary_key.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField(primary_key = True)
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,
Python manage.py shell
Now let us try to create instance of GeeksModel using None.
# importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = 12) # saving current model instances.save()
Let us check in admin interface if the instance of model is created.Therefore, primary_key=True modifies the field to as PRIMARY KEY for that table. To know more about Primary key, visit here.
The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.
NaveenArora
AmitYadav27
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 708,
"s": 28,
"text": "Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. primary_key=True will make the field PRIMARY KEY for that table (model).If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields."
},
{
"code": null,
"e": 813,
"s": 708,
"text": "Note: primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object."
},
{
"code": null,
"e": 820,
"s": 813,
"text": "Syntax"
},
{
"code": null,
"e": 866,
"s": 820,
"text": "field_name = models.Field(primary_key = True)"
},
{
"code": null,
"e": 983,
"s": 866,
"text": "Illustration of primary_key=True using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 1070,
"s": 983,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 1121,
"s": 1070,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1154,
"s": 1121,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1278,
"s": 1154,
"text": "Enter the following code into models.py file of geeks app. We will be using IntegerField for experimenting for primary_key."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField(primary_key = True)",
"e": 1450,
"s": 1278,
"text": null
},
{
"code": null,
"e": 1637,
"s": 1450,
"text": "After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,"
},
{
"code": null,
"e": 1660,
"s": 1637,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 1720,
"s": 1660,
"text": "Now let us try to create instance of GeeksModel using None."
},
{
"code": "# importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = 12) # saving current model instances.save()",
"e": 1905,
"s": 1720,
"text": null
},
{
"code": null,
"e": 2098,
"s": 1905,
"text": "Let us check in admin interface if the instance of model is created.Therefore, primary_key=True modifies the field to as PRIMARY KEY for that table. To know more about Primary key, visit here."
},
{
"code": null,
"e": 2269,
"s": 2098,
"text": "The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one."
},
{
"code": null,
"e": 2281,
"s": 2269,
"text": "NaveenArora"
},
{
"code": null,
"e": 2293,
"s": 2281,
"text": "AmitYadav27"
},
{
"code": null,
"e": 2307,
"s": 2293,
"text": "Django-models"
},
{
"code": null,
"e": 2321,
"s": 2307,
"text": "Python Django"
},
{
"code": null,
"e": 2328,
"s": 2321,
"text": "Python"
}
] |
turtle.mode() function in Python
|
06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set turtle-mode (‘standard’, ‘logo’ or ‘world’) and perform reset.
Syntax : turtle.mode(mode=None)
Parameter:
mode: one of the strings ‘standard’, ‘logo’ or ‘world’
Mode ‘standard’ is compatible with turtle.py.
Mode ‘logo’ is compatible with most Logo-Turtle-Graphics.
Mode ‘world’ uses userdefined ‘worldcoordinates’.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle # check by default valueprint(turtle.mode())
Output :
standard
Example 2 :
Python3
# importing packageimport turtle # motion with default mode (standard)# default direction of turtle head # is north in standard modeturtle.forward(180) # set mode to 'logo' modeturtle.mode(mode='logo') # do some motion# default direction of turtle head # is east in logo modeturtle.forward(120) # set mode to 'world' modeturtle.mode(mode='world') # do some motionturtle.forward(100) # set coordinates of the turtle # mode (world) by choice of userturtle.setworldcoordinates(-500,-500,500,500)
Output :
Python-turtle
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 338,
"s": 245,
"text": "This function is used to set turtle-mode (‘standard’, ‘logo’ or ‘world’) and perform reset. "
},
{
"code": null,
"e": 370,
"s": 338,
"text": "Syntax : turtle.mode(mode=None)"
},
{
"code": null,
"e": 382,
"s": 370,
"text": "Parameter: "
},
{
"code": null,
"e": 437,
"s": 382,
"text": "mode: one of the strings ‘standard’, ‘logo’ or ‘world’"
},
{
"code": null,
"e": 483,
"s": 437,
"text": "Mode ‘standard’ is compatible with turtle.py."
},
{
"code": null,
"e": 541,
"s": 483,
"text": "Mode ‘logo’ is compatible with most Logo-Turtle-Graphics."
},
{
"code": null,
"e": 591,
"s": 541,
"text": "Mode ‘world’ uses userdefined ‘worldcoordinates’."
},
{
"code": null,
"e": 660,
"s": 591,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 672,
"s": 660,
"text": "Example 1 :"
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # check by default valueprint(turtle.mode())",
"e": 759,
"s": 680,
"text": null
},
{
"code": null,
"e": 768,
"s": 759,
"text": "Output :"
},
{
"code": null,
"e": 778,
"s": 768,
"text": "standard\n"
},
{
"code": null,
"e": 790,
"s": 778,
"text": "Example 2 :"
},
{
"code": null,
"e": 798,
"s": 790,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # motion with default mode (standard)# default direction of turtle head # is north in standard modeturtle.forward(180) # set mode to 'logo' modeturtle.mode(mode='logo') # do some motion# default direction of turtle head # is east in logo modeturtle.forward(120) # set mode to 'world' modeturtle.mode(mode='world') # do some motionturtle.forward(100) # set coordinates of the turtle # mode (world) by choice of userturtle.setworldcoordinates(-500,-500,500,500)",
"e": 1297,
"s": 798,
"text": null
},
{
"code": null,
"e": 1306,
"s": 1297,
"text": "Output :"
},
{
"code": null,
"e": 1320,
"s": 1306,
"text": "Python-turtle"
},
{
"code": null,
"e": 1327,
"s": 1320,
"text": "Python"
},
{
"code": null,
"e": 1425,
"s": 1327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1457,
"s": 1425,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1484,
"s": 1457,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1505,
"s": 1484,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1528,
"s": 1505,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1559,
"s": 1528,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1615,
"s": 1559,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1657,
"s": 1615,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1699,
"s": 1657,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1738,
"s": 1699,
"text": "Python | Get unique values from a list"
}
] |
Pizza Problem
|
13 Jul, 2021
Given an integer N and a pizza which can be cut into pieces, each cut should be a straight line going from the center of the pizza to its border. Also, the angle between any two cuts must be a positive integer. Two pieces are equal if their appropriate angles are equal. The given pizza can be cut in following three ways:
Cut the pizza into N equal pieces.Cut the pizza into N pieces of any size.Cut the pizza into N pieces such that no two of them are equal.
Cut the pizza into N equal pieces.
Cut the pizza into N pieces of any size.
Cut the pizza into N pieces such that no two of them are equal.
The task is to find if it is possible to cut the pizza in the above ways for a given value of N. Print 1 if possible else 0 for all the cases i.e. print 111 if all the cases are possible.Examples:
Input: N = 4 Output: 1 1 1 Case 1: All four pieces can have angle = 90 Case 2: Same cut as Case 1 Case 3: 1, 2, 3 and 354 are the respective angles of the four pieces cut.Input: N = 7 Output: 0 1 1
Approach:
Case 1 will only be possible if 360 is divisible by N.
For case 2 to be possible, N must be ≤ 360.
An ideal solution for case 3 would be to choose pieces in such a way that the angles they form are 1, 2, 3, ... respectively. So, in order for this case to be possible, (N * (N + 1)) / 2 must be ≤ 360.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to check if it is possible// to cut the pizza in the given wayvoid cutPizza(int n){ // Case 1 cout << (360 % n == 0) ? "1" : "0"; // Case 2 cout << (n <= 360) ? "1" : "0"; // Case 3 cout << (((n * (n + 1)) / 2) <= 360) ? "1" : "0";} // Driver codeint main(){ int n = 7; cutPizza(n); return 0;}
// Java implementation of the approachclass GFG{ // Function to check if it is possible// to cut the pizza in the given waystatic void cutPizza(int n){ // Case 1 System.out.print( (360 % n == 0) ? "1" : "0"); // Case 2 System.out.print( (n <= 360) ? "1" : "0"); // Case 3 System.out.print( (((n * (n + 1)) / 2) <= 360) ? "1" : "0");} // Driver codepublic static void main(String args[]){ int n = 7; cutPizza(n);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # Function to check if it is possible# to cut the pizza in the given waydef cutPizza(n): # Case 1 if(360 % n == 0): print("1", end = "") else: print("0", end = ""); # Case 2 if(n <= 360): print("1", end = "") else: print("0", end = ""); # Case 3 if(((n * (n + 1)) / 2) <= 360): print("1", end = "") else: print("0", end = ""); # Driver coden = 7;cutPizza(n); # This code is contributed# by Akanksha Rai
// C# implementation of the approachusing System; class GFG{ // Function to check if it is possible// to cut the pizza in the given waystatic void cutPizza(int n){ // Case 1 Console.Write((360 % n == 0) ? "1" : "0"); // Case 2 Console.Write((n <= 360) ? "1" : "0"); // Case 3 Console.Write((((n * (n + 1)) / 2) <= 360) ? "1" : "0");} // Driver codepublic static void Main(String []args){ int n = 7; cutPizza(n);}} // This code is contributed by Arnab Kundu
<?php// PHP implementation of the approach // Function to check if it is possible// to cut the pizza in the given wayfunction cutPizza($n){ // Case 1 echo (360 % $n == 0) ? "1" : "0"; // Case 2 echo ($n <= 360) ? "1" : "0"; // Case 3 echo ((($n * ($n + 1)) / 2) <= 360) ? "1" : "0";} // Driver code$n = 7;cutPizza($n); // This code is contributed// by Akanksha Rai?>
<script>// Javascript implementation of the approach // Function to check if it is possible// to cut the pizza in the given wayfunction cutPizza(n){ // Case 1 document.write( (360 % n == 0) ? "1" : "0"); // Case 2 document.write( (n <= 360) ? "1" : "0"); // Case 3 document.write( (((n * (n + 1)) / 2) <= 360) ? "1" : "0");} // Driver codelet n = 7;cutPizza(n); // This code is contributed by avanitrachhadiya2155</script>
011
andrew1234
Akanksha_Rai
avanitrachhadiya2155
programming-puzzle
C++ Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
C++ Program for QuickSort
delete keyword in C++
C Program to Swap two Numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 353,
"s": 28,
"text": "Given an integer N and a pizza which can be cut into pieces, each cut should be a straight line going from the center of the pizza to its border. Also, the angle between any two cuts must be a positive integer. Two pieces are equal if their appropriate angles are equal. The given pizza can be cut in following three ways: "
},
{
"code": null,
"e": 491,
"s": 353,
"text": "Cut the pizza into N equal pieces.Cut the pizza into N pieces of any size.Cut the pizza into N pieces such that no two of them are equal."
},
{
"code": null,
"e": 526,
"s": 491,
"text": "Cut the pizza into N equal pieces."
},
{
"code": null,
"e": 567,
"s": 526,
"text": "Cut the pizza into N pieces of any size."
},
{
"code": null,
"e": 631,
"s": 567,
"text": "Cut the pizza into N pieces such that no two of them are equal."
},
{
"code": null,
"e": 830,
"s": 631,
"text": "The task is to find if it is possible to cut the pizza in the above ways for a given value of N. Print 1 if possible else 0 for all the cases i.e. print 111 if all the cases are possible.Examples: "
},
{
"code": null,
"e": 1030,
"s": 830,
"text": "Input: N = 4 Output: 1 1 1 Case 1: All four pieces can have angle = 90 Case 2: Same cut as Case 1 Case 3: 1, 2, 3 and 354 are the respective angles of the four pieces cut.Input: N = 7 Output: 0 1 1 "
},
{
"code": null,
"e": 1044,
"s": 1032,
"text": "Approach: "
},
{
"code": null,
"e": 1099,
"s": 1044,
"text": "Case 1 will only be possible if 360 is divisible by N."
},
{
"code": null,
"e": 1143,
"s": 1099,
"text": "For case 2 to be possible, N must be ≤ 360."
},
{
"code": null,
"e": 1345,
"s": 1143,
"text": "An ideal solution for case 3 would be to choose pieces in such a way that the angles they form are 1, 2, 3, ... respectively. So, in order for this case to be possible, (N * (N + 1)) / 2 must be ≤ 360."
},
{
"code": null,
"e": 1398,
"s": 1345,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1402,
"s": 1398,
"text": "C++"
},
{
"code": null,
"e": 1407,
"s": 1402,
"text": "Java"
},
{
"code": null,
"e": 1415,
"s": 1407,
"text": "Python3"
},
{
"code": null,
"e": 1418,
"s": 1415,
"text": "C#"
},
{
"code": null,
"e": 1422,
"s": 1418,
"text": "PHP"
},
{
"code": null,
"e": 1433,
"s": 1422,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to check if it is possible// to cut the pizza in the given wayvoid cutPizza(int n){ // Case 1 cout << (360 % n == 0) ? \"1\" : \"0\"; // Case 2 cout << (n <= 360) ? \"1\" : \"0\"; // Case 3 cout << (((n * (n + 1)) / 2) <= 360) ? \"1\" : \"0\";} // Driver codeint main(){ int n = 7; cutPizza(n); return 0;}",
"e": 1846,
"s": 1433,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to check if it is possible// to cut the pizza in the given waystatic void cutPizza(int n){ // Case 1 System.out.print( (360 % n == 0) ? \"1\" : \"0\"); // Case 2 System.out.print( (n <= 360) ? \"1\" : \"0\"); // Case 3 System.out.print( (((n * (n + 1)) / 2) <= 360) ? \"1\" : \"0\");} // Driver codepublic static void main(String args[]){ int n = 7; cutPizza(n);}} // This code is contributed by Arnab Kundu",
"e": 2329,
"s": 1846,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to check if it is possible# to cut the pizza in the given waydef cutPizza(n): # Case 1 if(360 % n == 0): print(\"1\", end = \"\") else: print(\"0\", end = \"\"); # Case 2 if(n <= 360): print(\"1\", end = \"\") else: print(\"0\", end = \"\"); # Case 3 if(((n * (n + 1)) / 2) <= 360): print(\"1\", end = \"\") else: print(\"0\", end = \"\"); # Driver coden = 7;cutPizza(n); # This code is contributed# by Akanksha Rai",
"e": 2846,
"s": 2329,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to check if it is possible// to cut the pizza in the given waystatic void cutPizza(int n){ // Case 1 Console.Write((360 % n == 0) ? \"1\" : \"0\"); // Case 2 Console.Write((n <= 360) ? \"1\" : \"0\"); // Case 3 Console.Write((((n * (n + 1)) / 2) <= 360) ? \"1\" : \"0\");} // Driver codepublic static void Main(String []args){ int n = 7; cutPizza(n);}} // This code is contributed by Arnab Kundu",
"e": 3329,
"s": 2846,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to check if it is possible// to cut the pizza in the given wayfunction cutPizza($n){ // Case 1 echo (360 % $n == 0) ? \"1\" : \"0\"; // Case 2 echo ($n <= 360) ? \"1\" : \"0\"; // Case 3 echo ((($n * ($n + 1)) / 2) <= 360) ? \"1\" : \"0\";} // Driver code$n = 7;cutPizza($n); // This code is contributed// by Akanksha Rai?>",
"e": 3716,
"s": 3329,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to check if it is possible// to cut the pizza in the given wayfunction cutPizza(n){ // Case 1 document.write( (360 % n == 0) ? \"1\" : \"0\"); // Case 2 document.write( (n <= 360) ? \"1\" : \"0\"); // Case 3 document.write( (((n * (n + 1)) / 2) <= 360) ? \"1\" : \"0\");} // Driver codelet n = 7;cutPizza(n); // This code is contributed by avanitrachhadiya2155</script>",
"e": 4163,
"s": 3716,
"text": null
},
{
"code": null,
"e": 4167,
"s": 4163,
"text": "011"
},
{
"code": null,
"e": 4180,
"s": 4169,
"text": "andrew1234"
},
{
"code": null,
"e": 4193,
"s": 4180,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4214,
"s": 4193,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 4233,
"s": 4214,
"text": "programming-puzzle"
},
{
"code": null,
"e": 4246,
"s": 4233,
"text": "C++ Programs"
},
{
"code": null,
"e": 4265,
"s": 4246,
"text": "School Programming"
},
{
"code": null,
"e": 4363,
"s": 4265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4397,
"s": 4363,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 4457,
"s": 4397,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 4483,
"s": 4457,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 4505,
"s": 4483,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 4535,
"s": 4505,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 4553,
"s": 4535,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4578,
"s": 4553,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4594,
"s": 4578,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4617,
"s": 4594,
"text": "Introduction To PYTHON"
}
] |
Word Break Problem
|
In the input of this problem, one sentence is given without spaces, another dictionary is also provided of some valid English words. We have to find the possible ways to break the sentence in individual dictionary words.
We will try to search from the left of the string to find a valid word when a valid word is found, we will search for words in the next part of that string.
Input:
A set of valid words as dictionary, and a string where different words are placed without spaces.
Dictionary: {mobile, sam, sung, man, mango, icecream, and, go, i, love, ice, cream}
Given String: “ilovemangoicecream”
Output:
All possible ways to break the string into given words.
i love man go ice cream
i love man go icecream
i love mango ice cream
i love mango icecream
wordBreak(string, n, result)
Input − Given string, length of the string, the separated strings.
Output − Separate string using a dictionary.
Begin
for i := 0 to n, do
subStr := substring of given string from (0..i)
if subStr is in dictionary, then
if i = n, then
result := result + subStr
display the result
return
wordBreak(substring from (i..n-i), n-i, result, subStr, ‘space’)
done
End
#include <iostream>
#define N 13
using namespace std;
string dictionary[N] = {"mobile","samsung","sam","sung","man","mango", "icecream","and",
"go","i","love","ice","cream"};
int isInDict(string word){ //check whether the word is in dictionary or not
for (int i = 0; i < N; i++)
if (dictionary[i].compare(word) == 0)
return true;
return false;
}
void wordBreak(string str, int n, string result) {
for (int i=1; i<=n; i++) {
string subStr = str.substr(0, i); //get string from 0 to ith location of the string
if (isInDict(subStr)) { //if subStr is found in the dictionary
if (i == n) {
result += subStr; //add substring in the result.
cout << result << endl;
return;
}
wordBreak(str.substr(i, n-i), n-i, result + subStr + " "); //otherwise break rest part
}
}
}
int main() {
string str="iloveicecreamandmango";
wordBreak(str, str.size(),"");
}
i love man go ice cream
i love man go icecream
i love mango ice cream
i love mango icecream
|
[
{
"code": null,
"e": 1408,
"s": 1187,
"text": "In the input of this problem, one sentence is given without spaces, another dictionary is also provided of some valid English words. We have to find the possible ways to break the sentence in individual dictionary words."
},
{
"code": null,
"e": 1565,
"s": 1408,
"text": "We will try to search from the left of the string to find a valid word when a valid word is found, we will search for words in the next part of that string."
},
{
"code": null,
"e": 1945,
"s": 1565,
"text": "Input:\nA set of valid words as dictionary, and a string where different words are placed without spaces.\nDictionary: {mobile, sam, sung, man, mango, icecream, and, go, i, love, ice, cream}\nGiven String: “ilovemangoicecream”\nOutput:\nAll possible ways to break the string into given words.\ni love man go ice cream\ni love man go icecream\ni love mango ice cream\ni love mango icecream"
},
{
"code": null,
"e": 1974,
"s": 1945,
"text": "wordBreak(string, n, result)"
},
{
"code": null,
"e": 2041,
"s": 1974,
"text": "Input − Given string, length of the string, the separated strings."
},
{
"code": null,
"e": 2086,
"s": 2041,
"text": "Output − Separate string using a dictionary."
},
{
"code": null,
"e": 2406,
"s": 2086,
"text": "Begin\n for i := 0 to n, do\n subStr := substring of given string from (0..i)\n if subStr is in dictionary, then\n if i = n, then\n result := result + subStr\n display the result\n return\n wordBreak(substring from (i..n-i), n-i, result, subStr, ‘space’)\n done\nEnd"
},
{
"code": null,
"e": 3409,
"s": 2406,
"text": "#include <iostream>\n#define N 13\nusing namespace std;\n\nstring dictionary[N] = {\"mobile\",\"samsung\",\"sam\",\"sung\",\"man\",\"mango\", \"icecream\",\"and\",\n \"go\",\"i\",\"love\",\"ice\",\"cream\"};\n\nint isInDict(string word){ //check whether the word is in dictionary or not\n for (int i = 0; i < N; i++)\n if (dictionary[i].compare(word) == 0)\n return true;\n return false;\n}\n\nvoid wordBreak(string str, int n, string result) {\n for (int i=1; i<=n; i++) {\n string subStr = str.substr(0, i); //get string from 0 to ith location of the string\n if (isInDict(subStr)) { //if subStr is found in the dictionary\n if (i == n) {\n result += subStr; //add substring in the result.\n cout << result << endl;\n return;\n }\n wordBreak(str.substr(i, n-i), n-i, result + subStr + \" \"); //otherwise break rest part\n }\n }\n}\n\nint main() {\n string str=\"iloveicecreamandmango\";\n wordBreak(str, str.size(),\"\");\n}"
},
{
"code": null,
"e": 3501,
"s": 3409,
"text": "i love man go ice cream\ni love man go icecream\ni love mango ice cream\ni love mango icecream"
}
] |
Python – Sum elements matching condition
|
17 Dec, 2021
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals sum that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved.
Method #1 : Using loop This is brute force method to perform this particular task. In this, we iterate list, find elements that match a particular condition and take sum.
Python3
# Python 3 code to demonstrate # Sum elements matching condition# using loop # initializing listtest_list = [3, 5, 1, 6, 7, 9] # printing original listprint ("The original list is : " + str(test_list)) # using loop# Sum elements matching condition# checks for oddres = 0for ele in test_list: if ele % 2 != 0: res = res + ele # printing resultprint ("The sum of odd elements: " + str(res))
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
Method #2 : Using sum() + generator expression This method uses the trick of adding element to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of numbers matching a condition is returned.
Python3
# Python 3 code to demonstrate # Sum elements matching condition# using sum() + generator expression # initializing listtest_list = [3, 5, 1, 6, 7, 9] # printing original listprint ("The original list is : " + str(test_list)) # using sum() + generator expression# Sum elements matching condition# checks for oddres = sum(i for i in test_list if i % 2 != 0) # printing resultprint ("The sum of odd elements: " + str(res))
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
arorakashish0911
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals sum that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved."
},
{
"code": null,
"e": 519,
"s": 348,
"text": "Method #1 : Using loop This is brute force method to perform this particular task. In this, we iterate list, find elements that match a particular condition and take sum."
},
{
"code": null,
"e": 527,
"s": 519,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate # Sum elements matching condition# using loop # initializing listtest_list = [3, 5, 1, 6, 7, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # using loop# Sum elements matching condition# checks for oddres = 0for ele in test_list: if ele % 2 != 0: res = res + ele # printing resultprint (\"The sum of odd elements: \" + str(res))",
"e": 943,
"s": 527,
"text": null
},
{
"code": null,
"e": 1013,
"s": 943,
"text": "The original list is : [3, 5, 1, 6, 7, 9]\nThe sum of odd elements: 25"
},
{
"code": null,
"e": 1255,
"s": 1015,
"text": " Method #2 : Using sum() + generator expression This method uses the trick of adding element to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of numbers matching a condition is returned."
},
{
"code": null,
"e": 1263,
"s": 1255,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate # Sum elements matching condition# using sum() + generator expression # initializing listtest_list = [3, 5, 1, 6, 7, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # using sum() + generator expression# Sum elements matching condition# checks for oddres = sum(i for i in test_list if i % 2 != 0) # printing resultprint (\"The sum of odd elements: \" + str(res))",
"e": 1692,
"s": 1263,
"text": null
},
{
"code": null,
"e": 1762,
"s": 1692,
"text": "The original list is : [3, 5, 1, 6, 7, 9]\nThe sum of odd elements: 25"
},
{
"code": null,
"e": 1781,
"s": 1764,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1802,
"s": 1781,
"text": "Python list-programs"
},
{
"code": null,
"e": 1809,
"s": 1802,
"text": "Python"
},
{
"code": null,
"e": 1825,
"s": 1809,
"text": "Python Programs"
}
] |
Modulo or Remainder Operator in Java
|
23 Feb, 2022
Modulo or Remainder Operator returns the remainder of the two numbers after division. If you are provided with two numbers, say A and B, A is the dividend and B is the divisor, A mod B is there a remainder of the division of A and B. Modulo operator is an arithmetical operator which is denoted by %.
NOTE: If numerator is less than denominator then % will give output as the numerator only.
Syntax:
A % B
Where A is the dividend and B is divisor
Example:
Input : a = 15, b = 6 // 15%6 means when we divide 15(numerator) by 6(denominator) we get remainder 3// Output: 3Input : a = 16, b = 4 Output: 0
Approach:
Take Dividend and Divisor from the user.Create an integer variable and assign it with A % B expression.Print that variable.
Take Dividend and Divisor from the user.
Create an integer variable and assign it with A % B expression.
Print that variable.
Below is the implementation of the above approach:
Java
// Implementation of Modulo or Remainder Operator in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Dividend int a = 15; // Divisor int b = 8; // Mod int k = a % b; System.out.println(k); }}
7
Time Complexity :
Modular function usually takes Constant time / O(1) time like other arithmetic operations.
jyoti369
singhaditya2608
Java-Operators
Picked
Java
Java Programs
Java-Operators
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 353,
"s": 52,
"text": "Modulo or Remainder Operator returns the remainder of the two numbers after division. If you are provided with two numbers, say A and B, A is the dividend and B is the divisor, A mod B is there a remainder of the division of A and B. Modulo operator is an arithmetical operator which is denoted by %."
},
{
"code": null,
"e": 447,
"s": 353,
"text": "NOTE: If numerator is less than denominator then % will give output as the numerator only."
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Syntax:"
},
{
"code": null,
"e": 502,
"s": 455,
"text": "A % B\nWhere A is the dividend and B is divisor"
},
{
"code": null,
"e": 511,
"s": 502,
"text": "Example:"
},
{
"code": null,
"e": 656,
"s": 511,
"text": "Input : a = 15, b = 6 // 15%6 means when we divide 15(numerator) by 6(denominator) we get remainder 3// Output: 3Input : a = 16, b = 4 Output: 0"
},
{
"code": null,
"e": 666,
"s": 656,
"text": "Approach:"
},
{
"code": null,
"e": 790,
"s": 666,
"text": "Take Dividend and Divisor from the user.Create an integer variable and assign it with A % B expression.Print that variable."
},
{
"code": null,
"e": 831,
"s": 790,
"text": "Take Dividend and Divisor from the user."
},
{
"code": null,
"e": 895,
"s": 831,
"text": "Create an integer variable and assign it with A % B expression."
},
{
"code": null,
"e": 916,
"s": 895,
"text": "Print that variable."
},
{
"code": null,
"e": 967,
"s": 916,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 972,
"s": 967,
"text": "Java"
},
{
"code": "// Implementation of Modulo or Remainder Operator in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Dividend int a = 15; // Divisor int b = 8; // Mod int k = a % b; System.out.println(k); }}",
"e": 1273,
"s": 972,
"text": null
},
{
"code": null,
"e": 1275,
"s": 1273,
"text": "7"
},
{
"code": null,
"e": 1294,
"s": 1275,
"text": "Time Complexity : "
},
{
"code": null,
"e": 1386,
"s": 1294,
"text": "Modular function usually takes Constant time / O(1) time like other arithmetic operations. "
},
{
"code": null,
"e": 1395,
"s": 1386,
"text": "jyoti369"
},
{
"code": null,
"e": 1411,
"s": 1395,
"text": "singhaditya2608"
},
{
"code": null,
"e": 1426,
"s": 1411,
"text": "Java-Operators"
},
{
"code": null,
"e": 1433,
"s": 1426,
"text": "Picked"
},
{
"code": null,
"e": 1438,
"s": 1433,
"text": "Java"
},
{
"code": null,
"e": 1452,
"s": 1438,
"text": "Java Programs"
},
{
"code": null,
"e": 1467,
"s": 1452,
"text": "Java-Operators"
},
{
"code": null,
"e": 1472,
"s": 1467,
"text": "Java"
},
{
"code": null,
"e": 1570,
"s": 1472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1585,
"s": 1570,
"text": "Stream In Java"
},
{
"code": null,
"e": 1606,
"s": 1585,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1627,
"s": 1606,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1646,
"s": 1627,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1663,
"s": 1646,
"text": "Generics in Java"
},
{
"code": null,
"e": 1689,
"s": 1663,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1723,
"s": 1689,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 1770,
"s": 1723,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 1808,
"s": 1770,
"text": "Factory method design pattern in Java"
}
] |
What is the use of let & const in JavaScript ?
|
25 May, 2022
In this article, we are going to discuss the usage of let and const in JavaScript.
let: It is a keyword to declare variables in JavaScript that are block-scoped i.e. it allows to declare a variable within a block or within an expression rather than in the whole document.
Syntax:
let variable_name = value;
Following is an example (non-runnable) of the above illustrated syntax:
let name = "GeeksforGeeks";
Characteristic:
Variables declared with let cannot be redeclared in JavaScript. This means if a variable is declared with let, then we cannot redeclare the same variable again in the same context.
Example 1: We get a syntax error since x cannot be redeclared in the same scope.
HTML
<script> let x = "GeeksforGeeks"; // Redeclaring same variable let x = 12; console.log(x);</script>
Output:
SyntaxError: Identifier 'x' has already been declared
Note: let allows declaring the same variable within a block scope { } but it cannot be used outside the block scope.
Example 2:
HTML
<script> { let x = 12; } console.log(x);</script>
Output:
ReferenceError: x is not defined
Example 3:
HTML
<script> let x = "GeeksforGeeks"; { let x = 12; // local variable } // x takes value of the Global Variable x console.log(x);</script>
Output:
GeeksforGeeks
Example 4: We can declare a let variable within a block scope, which will be treated as a local variable inside the block scope and will be given more preference than a previously defined global variable.
HTML
<script> let x = "GeeksforGeeks"; let y = "Computer science portal"; { let x = 12; console.log(x); console.log(y); } console.log(x);</script>
Output:
12
Computer science portal
GeeksforGeeks
Example 5: A key point is when a variable is declared with let, it gets hosted on top of the block but is not initialized. So, if we use a let variable before declaring the variable, we will get a Reference error.
HTML
<script> x = "A variable" let x = "GeeksforGeeks"; console.log(x);</script>
Output:
ReferenceError: Cannot access 'x' before initialization
Example-6: In this example we will be visualizing how to write let variable inside as well as outside of the function scope.
Javascript
let name = "GeeksforGeeks";function displayName(){ let prefix = "Hi!" console.log(prefix + " " + name);}displayName(); // This code is contributed by Aman Singla....
Output:
Hi! GeeksforGeeks
const: It is also a keyword to declare variables that are block-scoped, but the variables declared by the const keyword cannot be updated within the same scope. Similar to let variables, the const variables can neither be redeclared nor can be accessed before they are declared.
Syntax:
const x = 12;
Characteristic:
The variables declared by the const keyword remain the same within the same scope or within a block.
Example 1:
HTML
<script> const x = 12; x = "GeeksforGeeks"; console.log(x);</script>
Output:
TypeError: Assignment to constant variable.
Example 2: Const variables can be declared as a local variable inside a block scope, and preference for a local variable is higher than a global variable inside a block scope.
HTML
<script> const x = 12; // Global variable const y = "Welcome"; // Global variable { const x = "GeeksforGeeks"; // local variable // Expected output: GeeksforGeeks console.log(x); // Expected output: Welcome console.log(y); } // Expected output: 12 console.log(x);</script>
Output:
GeeksforGeeks
Welcome
12
Example 3: If we try to declare an object using the const keyword, then the object cannot be updated, but the properties of the object can still be updated.
HTML
<script> const obj = { name: "GeeksforGeeks", message: "A computer science portal" } // Updating properties of obj obj.message = "Welcome to GeeksforGeeks"; console.log(obj.name); console.log(obj.message);</script>
Output:
GeeksforGeeks
Welcome to GeeksforGeeks
Example 4: Similar to let, a const object must be initialized before the declaration. If it is uninitialized, we will get a Reference error.
HTML
<script> x = "Welcome to GeeksforGeeks" const x = 12; console.log(x);</script>
Output:
ReferenceError: Cannot access 'x' before initialization
Example-5: In this example, we will be visualizing how to use variables declared using const keyword inside as well as outside of the function scope.
Javascript
const name = "GeeksforGeeks";function displayName(){ const prefix = "Hi!" console.log(prefix + " " + name);}displayName();
Output:
Hi! GeeksforGeeks
Key difference: So we see that a variable declared by let keyword can be reassigned whereas a variable declared with const keyword can never be reassigned within the same scope.
amansingla
javascript-basics
JavaScript-Questions
Picked
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 136,
"s": 53,
"text": "In this article, we are going to discuss the usage of let and const in JavaScript."
},
{
"code": null,
"e": 325,
"s": 136,
"text": "let: It is a keyword to declare variables in JavaScript that are block-scoped i.e. it allows to declare a variable within a block or within an expression rather than in the whole document."
},
{
"code": null,
"e": 333,
"s": 325,
"text": "Syntax:"
},
{
"code": null,
"e": 360,
"s": 333,
"text": "let variable_name = value;"
},
{
"code": null,
"e": 432,
"s": 360,
"text": "Following is an example (non-runnable) of the above illustrated syntax:"
},
{
"code": null,
"e": 460,
"s": 432,
"text": "let name = \"GeeksforGeeks\";"
},
{
"code": null,
"e": 476,
"s": 460,
"text": "Characteristic:"
},
{
"code": null,
"e": 657,
"s": 476,
"text": "Variables declared with let cannot be redeclared in JavaScript. This means if a variable is declared with let, then we cannot redeclare the same variable again in the same context."
},
{
"code": null,
"e": 738,
"s": 657,
"text": "Example 1: We get a syntax error since x cannot be redeclared in the same scope."
},
{
"code": null,
"e": 743,
"s": 738,
"text": "HTML"
},
{
"code": "<script> let x = \"GeeksforGeeks\"; // Redeclaring same variable let x = 12; console.log(x);</script>",
"e": 853,
"s": 743,
"text": null
},
{
"code": null,
"e": 861,
"s": 853,
"text": "Output:"
},
{
"code": null,
"e": 915,
"s": 861,
"text": "SyntaxError: Identifier 'x' has already been declared"
},
{
"code": null,
"e": 1032,
"s": 915,
"text": "Note: let allows declaring the same variable within a block scope { } but it cannot be used outside the block scope."
},
{
"code": null,
"e": 1043,
"s": 1032,
"text": "Example 2:"
},
{
"code": null,
"e": 1048,
"s": 1043,
"text": "HTML"
},
{
"code": "<script> { let x = 12; } console.log(x);</script>",
"e": 1105,
"s": 1048,
"text": null
},
{
"code": null,
"e": 1113,
"s": 1105,
"text": "Output:"
},
{
"code": null,
"e": 1146,
"s": 1113,
"text": "ReferenceError: x is not defined"
},
{
"code": null,
"e": 1157,
"s": 1146,
"text": "Example 3:"
},
{
"code": null,
"e": 1162,
"s": 1157,
"text": "HTML"
},
{
"code": "<script> let x = \"GeeksforGeeks\"; { let x = 12; // local variable } // x takes value of the Global Variable x console.log(x);</script>",
"e": 1308,
"s": 1162,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Output:"
},
{
"code": null,
"e": 1330,
"s": 1316,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1535,
"s": 1330,
"text": "Example 4: We can declare a let variable within a block scope, which will be treated as a local variable inside the block scope and will be given more preference than a previously defined global variable."
},
{
"code": null,
"e": 1540,
"s": 1535,
"text": "HTML"
},
{
"code": "<script> let x = \"GeeksforGeeks\"; let y = \"Computer science portal\"; { let x = 12; console.log(x); console.log(y); } console.log(x);</script>",
"e": 1700,
"s": 1540,
"text": null
},
{
"code": null,
"e": 1708,
"s": 1700,
"text": "Output:"
},
{
"code": null,
"e": 1749,
"s": 1708,
"text": "12\nComputer science portal\nGeeksforGeeks"
},
{
"code": null,
"e": 1963,
"s": 1749,
"text": "Example 5: A key point is when a variable is declared with let, it gets hosted on top of the block but is not initialized. So, if we use a let variable before declaring the variable, we will get a Reference error."
},
{
"code": null,
"e": 1968,
"s": 1963,
"text": "HTML"
},
{
"code": "<script> x = \"A variable\" let x = \"GeeksforGeeks\"; console.log(x);</script>",
"e": 2049,
"s": 1968,
"text": null
},
{
"code": null,
"e": 2057,
"s": 2049,
"text": "Output:"
},
{
"code": null,
"e": 2113,
"s": 2057,
"text": "ReferenceError: Cannot access 'x' before initialization"
},
{
"code": null,
"e": 2238,
"s": 2113,
"text": "Example-6: In this example we will be visualizing how to write let variable inside as well as outside of the function scope."
},
{
"code": null,
"e": 2249,
"s": 2238,
"text": "Javascript"
},
{
"code": "let name = \"GeeksforGeeks\";function displayName(){ let prefix = \"Hi!\" console.log(prefix + \" \" + name);}displayName(); // This code is contributed by Aman Singla....",
"e": 2421,
"s": 2249,
"text": null
},
{
"code": null,
"e": 2429,
"s": 2421,
"text": "Output:"
},
{
"code": null,
"e": 2447,
"s": 2429,
"text": "Hi! GeeksforGeeks"
},
{
"code": null,
"e": 2726,
"s": 2447,
"text": "const: It is also a keyword to declare variables that are block-scoped, but the variables declared by the const keyword cannot be updated within the same scope. Similar to let variables, the const variables can neither be redeclared nor can be accessed before they are declared."
},
{
"code": null,
"e": 2734,
"s": 2726,
"text": "Syntax:"
},
{
"code": null,
"e": 2748,
"s": 2734,
"text": "const x = 12;"
},
{
"code": null,
"e": 2764,
"s": 2748,
"text": "Characteristic:"
},
{
"code": null,
"e": 2866,
"s": 2764,
"text": " The variables declared by the const keyword remain the same within the same scope or within a block."
},
{
"code": null,
"e": 2877,
"s": 2866,
"text": "Example 1:"
},
{
"code": null,
"e": 2882,
"s": 2877,
"text": "HTML"
},
{
"code": "<script> const x = 12; x = \"GeeksforGeeks\"; console.log(x);</script>",
"e": 2956,
"s": 2882,
"text": null
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "Output:"
},
{
"code": null,
"e": 3008,
"s": 2964,
"text": "TypeError: Assignment to constant variable."
},
{
"code": null,
"e": 3184,
"s": 3008,
"text": "Example 2: Const variables can be declared as a local variable inside a block scope, and preference for a local variable is higher than a global variable inside a block scope."
},
{
"code": null,
"e": 3189,
"s": 3184,
"text": "HTML"
},
{
"code": "<script> const x = 12; // Global variable const y = \"Welcome\"; // Global variable { const x = \"GeeksforGeeks\"; // local variable // Expected output: GeeksforGeeks console.log(x); // Expected output: Welcome console.log(y); } // Expected output: 12 console.log(x);</script>",
"e": 3531,
"s": 3189,
"text": null
},
{
"code": null,
"e": 3539,
"s": 3531,
"text": "Output:"
},
{
"code": null,
"e": 3564,
"s": 3539,
"text": "GeeksforGeeks\nWelcome\n12"
},
{
"code": null,
"e": 3721,
"s": 3564,
"text": "Example 3: If we try to declare an object using the const keyword, then the object cannot be updated, but the properties of the object can still be updated."
},
{
"code": null,
"e": 3726,
"s": 3721,
"text": "HTML"
},
{
"code": "<script> const obj = { name: \"GeeksforGeeks\", message: \"A computer science portal\" } // Updating properties of obj obj.message = \"Welcome to GeeksforGeeks\"; console.log(obj.name); console.log(obj.message);</script>",
"e": 3959,
"s": 3726,
"text": null
},
{
"code": null,
"e": 3967,
"s": 3959,
"text": "Output:"
},
{
"code": null,
"e": 4006,
"s": 3967,
"text": "GeeksforGeeks\nWelcome to GeeksforGeeks"
},
{
"code": null,
"e": 4147,
"s": 4006,
"text": "Example 4: Similar to let, a const object must be initialized before the declaration. If it is uninitialized, we will get a Reference error."
},
{
"code": null,
"e": 4152,
"s": 4147,
"text": "HTML"
},
{
"code": "<script> x = \"Welcome to GeeksforGeeks\" const x = 12; console.log(x);</script>",
"e": 4236,
"s": 4152,
"text": null
},
{
"code": null,
"e": 4244,
"s": 4236,
"text": "Output:"
},
{
"code": null,
"e": 4300,
"s": 4244,
"text": "ReferenceError: Cannot access 'x' before initialization"
},
{
"code": null,
"e": 4450,
"s": 4300,
"text": "Example-5: In this example, we will be visualizing how to use variables declared using const keyword inside as well as outside of the function scope."
},
{
"code": null,
"e": 4461,
"s": 4450,
"text": "Javascript"
},
{
"code": "const name = \"GeeksforGeeks\";function displayName(){ const prefix = \"Hi!\" console.log(prefix + \" \" + name);}displayName();",
"e": 4590,
"s": 4461,
"text": null
},
{
"code": null,
"e": 4598,
"s": 4590,
"text": "Output:"
},
{
"code": null,
"e": 4616,
"s": 4598,
"text": "Hi! GeeksforGeeks"
},
{
"code": null,
"e": 4794,
"s": 4616,
"text": "Key difference: So we see that a variable declared by let keyword can be reassigned whereas a variable declared with const keyword can never be reassigned within the same scope."
},
{
"code": null,
"e": 4805,
"s": 4794,
"text": "amansingla"
},
{
"code": null,
"e": 4823,
"s": 4805,
"text": "javascript-basics"
},
{
"code": null,
"e": 4844,
"s": 4823,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 4851,
"s": 4844,
"text": "Picked"
},
{
"code": null,
"e": 4862,
"s": 4851,
"text": "JavaScript"
},
{
"code": null,
"e": 4879,
"s": 4862,
"text": "Web Technologies"
},
{
"code": null,
"e": 4977,
"s": 4879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5038,
"s": 4977,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5078,
"s": 5038,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5119,
"s": 5078,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5161,
"s": 5119,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5183,
"s": 5161,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 5245,
"s": 5183,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5278,
"s": 5245,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5339,
"s": 5278,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5389,
"s": 5339,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Node.js fs.renameSync() Method
|
12 Oct, 2021
The fs.renameSync() method is used to synchronously rename a file at the given old path to the given new path. It will overwrite the destination file if it already exists.
Syntax:
fs.renameSync( oldPath, newPath )
Property Values:
oldPath: It holds the path of the file that has to be renamed. It can be a string, buffer or URL.
newPath: It holds the new path that the file has to be renamed to. It can be a string, buffer or URL.
Below examples illustrate the fs.renameSync() method in Node.js:
Example 1: This example uses fs.renameSync() method to rename a file.
// Node.js program to demonstrate the// fs.renameSync() method // Import the filesystem moduleconst fs = require('fs'); // List all the filenames before renaminggetCurrentFilenames(); // Rename the filefs.renameSync('hello.txt', 'world.txt'); // List all the filenames after renaminggetCurrentFilenames(); // function to get current filenames in directoryfunction getCurrentFilenames() { console.log("Current filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}
Output:
Current filenames:
hello.txt
index.js
package.json
Current filenames:
index.js
package.json
world.txt
Example 2: This example uses fs.renameSync() method to demonstrate an error during file renaming.
// Node.js program to demonstrate the// fs.renameSync() method // Import the filesystem moduleconst fs = require('fs'); // List all the filenames before renaminggetCurrentFilenames(); // Rename a non-existent filefs.renameSync('nonexist.txt', 'world.txt'); // List all the filenames after renaminggetCurrentFilenames(); // Function to get current filenames in directoryfunction getCurrentFilenames() { console.log("Current filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}
Output:
Current filenames:
index.js
package.json
world.txt
internal/fs/utils.js:220
throw err;
^
Error: ENOENT: no such file or directory, rename 'nonexist.txt' -> 'world.txt'
at Object.renameSync (fs.js:643:3)
at Object. (G:\tutorials\nodejs-fs-renameSync\index.js:29:4)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11 {
errno: -4058,
syscall: 'rename',
code: 'ENOENT',
path: 'nonexist.txt',
dest: 'world.txt'
}
Reference: https://nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpath
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
Node.js Date.format() API
Difference between spawn() and fork() methods in Node.js
Convert xml data into json using Node.js
How to download a file using Node.js?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "The fs.renameSync() method is used to synchronously rename a file at the given old path to the given new path. It will overwrite the destination file if it already exists."
},
{
"code": null,
"e": 208,
"s": 200,
"text": "Syntax:"
},
{
"code": null,
"e": 242,
"s": 208,
"text": "fs.renameSync( oldPath, newPath )"
},
{
"code": null,
"e": 259,
"s": 242,
"text": "Property Values:"
},
{
"code": null,
"e": 357,
"s": 259,
"text": "oldPath: It holds the path of the file that has to be renamed. It can be a string, buffer or URL."
},
{
"code": null,
"e": 459,
"s": 357,
"text": "newPath: It holds the new path that the file has to be renamed to. It can be a string, buffer or URL."
},
{
"code": null,
"e": 524,
"s": 459,
"text": "Below examples illustrate the fs.renameSync() method in Node.js:"
},
{
"code": null,
"e": 594,
"s": 524,
"text": "Example 1: This example uses fs.renameSync() method to rename a file."
},
{
"code": "// Node.js program to demonstrate the// fs.renameSync() method // Import the filesystem moduleconst fs = require('fs'); // List all the filenames before renaminggetCurrentFilenames(); // Rename the filefs.renameSync('hello.txt', 'world.txt'); // List all the filenames after renaminggetCurrentFilenames(); // function to get current filenames in directoryfunction getCurrentFilenames() { console.log(\"Current filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}",
"e": 1096,
"s": 594,
"text": null
},
{
"code": null,
"e": 1104,
"s": 1096,
"text": "Output:"
},
{
"code": null,
"e": 1206,
"s": 1104,
"text": "Current filenames:\nhello.txt\nindex.js\npackage.json\nCurrent filenames:\nindex.js\npackage.json\nworld.txt"
},
{
"code": null,
"e": 1304,
"s": 1206,
"text": "Example 2: This example uses fs.renameSync() method to demonstrate an error during file renaming."
},
{
"code": "// Node.js program to demonstrate the// fs.renameSync() method // Import the filesystem moduleconst fs = require('fs'); // List all the filenames before renaminggetCurrentFilenames(); // Rename a non-existent filefs.renameSync('nonexist.txt', 'world.txt'); // List all the filenames after renaminggetCurrentFilenames(); // Function to get current filenames in directoryfunction getCurrentFilenames() { console.log(\"Current filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}",
"e": 1820,
"s": 1304,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1820,
"text": "Output:"
},
{
"code": null,
"e": 2598,
"s": 1828,
"text": "Current filenames:\nindex.js\npackage.json\nworld.txt\ninternal/fs/utils.js:220\n throw err;\n ^\n\nError: ENOENT: no such file or directory, rename 'nonexist.txt' -> 'world.txt'\n at Object.renameSync (fs.js:643:3)\n at Object. (G:\\tutorials\\nodejs-fs-renameSync\\index.js:29:4)\n at Module._compile (internal/modules/cjs/loader.js:956:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)\n at Module.load (internal/modules/cjs/loader.js:812:32)\n at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)\n at internal/main/run_main_module.js:17:11 {\n errno: -4058,\n syscall: 'rename',\n code: 'ENOENT',\n path: 'nonexist.txt',\n dest: 'world.txt'\n}"
},
{
"code": null,
"e": 2673,
"s": 2598,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpath"
},
{
"code": null,
"e": 2691,
"s": 2673,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 2698,
"s": 2691,
"text": "Picked"
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Node.js"
},
{
"code": null,
"e": 2723,
"s": 2706,
"text": "Web Technologies"
},
{
"code": null,
"e": 2821,
"s": 2723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2854,
"s": 2821,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2880,
"s": 2854,
"text": "Node.js Date.format() API"
},
{
"code": null,
"e": 2937,
"s": 2880,
"text": "Difference between spawn() and fork() methods in Node.js"
},
{
"code": null,
"e": 2978,
"s": 2937,
"text": "Convert xml data into json using Node.js"
},
{
"code": null,
"e": 3016,
"s": 2978,
"text": "How to download a file using Node.js?"
},
{
"code": null,
"e": 3078,
"s": 3016,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3139,
"s": 3078,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3189,
"s": 3139,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3232,
"s": 3189,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to make a Tkinter widget invisible?
|
To make a tkinter widget invisible, we can use the pack_forget() method. It is generally used to unmap the widgets from the window.
In the following example, we will create a label text and a button that can be used to trigger the invisible event on the label text widget.
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("600x250")
#Set the resizable property False
win.resizable(False, False)
#Make the widgets Invisible
def make_invisible(widget):
widget.pack_forget()
#Create a label for the window or frame
label=Label(win, text="Hello World!", font=('Helvetica bold',20),
anchor="center")
label.pack(pady=20)
#Create a button to make the widgets invisible
btn=Button(win, text="Click", font= ('Helvetica bold', 10), command=lambda:
make_invisible(label))
btn.pack(pady=20)
win.mainloop()
Running the above code will produce the following window −
Now click the “Click” Button to make the text label invisible.
|
[
{
"code": null,
"e": 1319,
"s": 1187,
"text": "To make a tkinter widget invisible, we can use the pack_forget() method. It is generally used to unmap the widgets from the window."
},
{
"code": null,
"e": 1460,
"s": 1319,
"text": "In the following example, we will create a label text and a button that can be used to trigger the invisible event on the label text widget."
},
{
"code": null,
"e": 2082,
"s": 1460,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"600x250\")\n\n#Set the resizable property False\nwin.resizable(False, False)\n\n#Make the widgets Invisible\ndef make_invisible(widget):\n widget.pack_forget()\n\n#Create a label for the window or frame\nlabel=Label(win, text=\"Hello World!\", font=('Helvetica bold',20),\nanchor=\"center\")\nlabel.pack(pady=20)\n\n#Create a button to make the widgets invisible\nbtn=Button(win, text=\"Click\", font= ('Helvetica bold', 10), command=lambda:\nmake_invisible(label))\nbtn.pack(pady=20)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2141,
"s": 2082,
"text": "Running the above code will produce the following window −"
},
{
"code": null,
"e": 2204,
"s": 2141,
"text": "Now click the “Click” Button to make the text label invisible."
}
] |
Output of Java Program | Set 1
|
22 Apr, 2022
Difficulty Level: Rookie
Predict the output of the following Java Programs.
Program 1:
Java
// filename Main.javaclass Test { protected int x, y;} class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.x + " " + t.y); }}
Output:
0 0
In Java, a protected member is accessible in all classes of the same package and in inherited classes of other packages. Since Test and Main are in the same package, no access-related problems in the above program. Also, the default constructors initialize integral variables as 0 in Java (Refer to this article for more details). That is why we get output as 0 0.
Program 2:
Java
// filename Test.javaclass Test { public static void main(String[] args) { for(int i = 0; 1; i++) { System.out.println("Hello"); break; } }}
Output: Compiler Error
There is an error in the condition check expression of for loop. Java differs from C++(or C) here. C++ considers all non-zero values as true and 0 as false. Unlike C++, an integer value expression cannot be placed where a boolean is expected in Java. Following is the corrected program.
Java
// filename Test.javaclass Test { public static void main(String[] args) { for(int i = 0; true; i++) { System.out.println("Hello"); break; } }}// Output: Hello
Program 3:
Java
// filename Main.javaclass Main { public static void main(String args[]) { System.out.println(fun()); } int fun() { return 20; }}
Output: Compiler Error Like C++, in Java, non-static methods cannot be called in a static method without creating an object. If we make fun() static OR If we create an object of the Main class and then call the method on that object then the program compiles fine without any compiler error. Following is the corrected program.
1. By defining the method as “static”
Java
// filename Main.javaclass Main { public static void main(String args[]) { System.out.println(fun()); } static int fun() { return 20; }}// Output: 20
2. By creating an object
Java
// filename Main.javaclass Main { public static void main(String args[]) { Main obj = new Main(); System.out.println(obj.fun()); } int fun() { return 20; }}// Output: 20
Program 4:
Java
// filename Test.javaclass Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 0; return ++x; }}
Output: Compiler Error
Unlike C++, static local variables are not allowed in Java. Refer to this article for more details. We can have class static members to count number of function calls and other purposes that C++ local static variables serve. Following is the corrected program.
Java
class Test { private static int x; public static void main(String args[]) { System.out.println(fun()); } static int fun() { return ++x; }}// Output: 1
Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.
himanshukawale0
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Arrow operator -> in C/C++ with Examples
Output of C Programs | Set 1
delete keyword in C++
Output of C++ programs | Set 50
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 78,
"s": 52,
"text": "Difficulty Level: Rookie "
},
{
"code": null,
"e": 129,
"s": 78,
"text": "Predict the output of the following Java Programs."
},
{
"code": null,
"e": 140,
"s": 129,
"text": "Program 1:"
},
{
"code": null,
"e": 145,
"s": 140,
"text": "Java"
},
{
"code": "// filename Main.javaclass Test { protected int x, y;} class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.x + \" \" + t.y); }}",
"e": 338,
"s": 145,
"text": null
},
{
"code": null,
"e": 346,
"s": 338,
"text": "Output:"
},
{
"code": null,
"e": 350,
"s": 346,
"text": "0 0"
},
{
"code": null,
"e": 715,
"s": 350,
"text": "In Java, a protected member is accessible in all classes of the same package and in inherited classes of other packages. Since Test and Main are in the same package, no access-related problems in the above program. Also, the default constructors initialize integral variables as 0 in Java (Refer to this article for more details). That is why we get output as 0 0."
},
{
"code": null,
"e": 726,
"s": 715,
"text": "Program 2:"
},
{
"code": null,
"e": 731,
"s": 726,
"text": "Java"
},
{
"code": "// filename Test.javaclass Test { public static void main(String[] args) { for(int i = 0; 1; i++) { System.out.println(\"Hello\"); break; } }}",
"e": 914,
"s": 731,
"text": null
},
{
"code": null,
"e": 938,
"s": 914,
"text": "Output: Compiler Error "
},
{
"code": null,
"e": 1225,
"s": 938,
"text": "There is an error in the condition check expression of for loop. Java differs from C++(or C) here. C++ considers all non-zero values as true and 0 as false. Unlike C++, an integer value expression cannot be placed where a boolean is expected in Java. Following is the corrected program."
},
{
"code": null,
"e": 1230,
"s": 1225,
"text": "Java"
},
{
"code": "// filename Test.javaclass Test { public static void main(String[] args) { for(int i = 0; true; i++) { System.out.println(\"Hello\"); break; } }}// Output: Hello",
"e": 1432,
"s": 1230,
"text": null
},
{
"code": null,
"e": 1444,
"s": 1432,
"text": "Program 3: "
},
{
"code": null,
"e": 1449,
"s": 1444,
"text": "Java"
},
{
"code": "// filename Main.javaclass Main { public static void main(String args[]) { System.out.println(fun()); } int fun() { return 20; }}",
"e": 1607,
"s": 1449,
"text": null
},
{
"code": null,
"e": 1935,
"s": 1607,
"text": "Output: Compiler Error Like C++, in Java, non-static methods cannot be called in a static method without creating an object. If we make fun() static OR If we create an object of the Main class and then call the method on that object then the program compiles fine without any compiler error. Following is the corrected program."
},
{
"code": null,
"e": 1973,
"s": 1935,
"text": "1. By defining the method as “static”"
},
{
"code": null,
"e": 1978,
"s": 1973,
"text": "Java"
},
{
"code": "// filename Main.javaclass Main { public static void main(String args[]) { System.out.println(fun()); } static int fun() { return 20; }}// Output: 20",
"e": 2154,
"s": 1978,
"text": null
},
{
"code": null,
"e": 2179,
"s": 2154,
"text": "2. By creating an object"
},
{
"code": null,
"e": 2184,
"s": 2179,
"text": "Java"
},
{
"code": "// filename Main.javaclass Main { public static void main(String args[]) { Main obj = new Main(); System.out.println(obj.fun()); } int fun() { return 20; }}// Output: 20",
"e": 2389,
"s": 2184,
"text": null
},
{
"code": null,
"e": 2401,
"s": 2389,
"text": "Program 4: "
},
{
"code": null,
"e": 2406,
"s": 2401,
"text": "Java"
},
{
"code": "// filename Test.javaclass Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 0; return ++x; }}",
"e": 2587,
"s": 2406,
"text": null
},
{
"code": null,
"e": 2611,
"s": 2587,
"text": "Output: Compiler Error "
},
{
"code": null,
"e": 2874,
"s": 2611,
"text": "Unlike C++, static local variables are not allowed in Java. Refer to this article for more details. We can have class static members to count number of function calls and other purposes that C++ local static variables serve. Following is the corrected program. "
},
{
"code": null,
"e": 2879,
"s": 2874,
"text": "Java"
},
{
"code": "class Test { private static int x; public static void main(String args[]) { System.out.println(fun()); } static int fun() { return ++x; }}// Output: 1",
"e": 3052,
"s": 2879,
"text": null
},
{
"code": null,
"e": 3197,
"s": 3052,
"text": "Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above."
},
{
"code": null,
"e": 3213,
"s": 3197,
"text": "himanshukawale0"
},
{
"code": null,
"e": 3225,
"s": 3213,
"text": "Java-Output"
},
{
"code": null,
"e": 3230,
"s": 3225,
"text": "Java"
},
{
"code": null,
"e": 3245,
"s": 3230,
"text": "Program Output"
},
{
"code": null,
"e": 3250,
"s": 3245,
"text": "Java"
},
{
"code": null,
"e": 3348,
"s": 3250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3367,
"s": 3348,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3385,
"s": 3367,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3405,
"s": 3385,
"text": "Collections in Java"
},
{
"code": null,
"e": 3437,
"s": 3405,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3452,
"s": 3437,
"text": "Stream In Java"
},
{
"code": null,
"e": 3493,
"s": 3452,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3522,
"s": 3493,
"text": "Output of C Programs | Set 1"
},
{
"code": null,
"e": 3544,
"s": 3522,
"text": "delete keyword in C++"
}
] |
Minimum operations to make two numbers equal
|
22 Feb, 2022
Given two numbers n and m, the task is to find the minimum number of operations required to make them equal if the following operations can be performed on them.
During the first operation, any of the two numbers can be increased by one.
During the second operation, any of the two numbers can be increased by two.
During the third operation, any of the two numbers can be increased by three and so on.
Examples:
Input : n = 1, m = 3
Output : 3
Explanation:
Add 1 to n; n = 2
Add 2 to m; m = 5
Add 3 to n; n = 5
Both n and m are equal now
N of operations = 3
Input : n = 30, m = 20
Output : 4
Approach: The approach used to solve the problem is the sum of N terms in an AP. It is given by the formula
S(n) = (n*(n+1))/2
So, the task is to find the difference between those two numbers and see if the difference can be achieved by adding first n elements. Therefore,
S(n) = max(m,n) - min(m,n)
On substituting this value of sum in the first equation; we get the number of elements n given by
n=(-1+sqrt(1+8*S(n)))/2
If this n is a perfect integer, then it is our final answer. Else, we increment our target value to reach by 1 and continue.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum no of operationsint minOperations(int n, int m){ int a = 0, k = 1; // find the maximum of two and store it in p int p = max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (-1 + sqrt(8 * s + 1)) / 2; if (q - floor(q) == 0) { a = q; n = m; } p = p + 1; } return a;} // Driver codeint main(){ int n = 1, m = 3; // Function calling cout << minOperations(n, m); return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the minimum no of operationsstatic int minOperations(int n, int m){ int a = 0, k = 1; // find the maximum of two and store it in p int p = Math.max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (float) ((-1 + Math.sqrt(8 * s + 1)) / 2); if (q - Math.floor(q) == 0) { a = (int) q; n = m; } p = p + 1; } return a;} // Driver codepublic static void main(String[] args){ int n = 1, m = 3; // Function calling System.out.print(minOperations(n, m));}} // This code is contributed by 29AjayKumar
# Python3 implementation of# the above approachfrom math import sqrt, floor # Function to find the minimum# no. of operationsdef minOperations( n, m) : a = 0; k = 1; # find the maximum of two and # store it in p p = max(n, m); # increase it until it is achievable # from given n and m while (n != m) : # Here value added to n and m will be # S(n)=p-n+p-m; # check whether integer value of n # exist by the formula # n=(-1+sqrt(1+8*S(n)))/2 s = float(p - n + p - m); q = (-1 + sqrt(8 * s + 1)) / 2; if (q - floor(q) == 0) : a = q; n = m; p = p + 1; return a; # Driver codeif __name__ == "__main__" : n = 1; m = 3; # Function calling print(minOperations(n, m)); # This code is contributed by AnkitRai01
// C# implementation of the above approachusing System; class GFG{ // Function to find the minimum no of operations static int minOperations(int n, int m) { int a = 0, k = 1; // find the maximum of two and store it in p int p = Math.Max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (float) ((-1 + Math.Sqrt(8 * s + 1)) / 2); if (q - Math.Floor(q) == 0) { a = (int) q; n = m; } p = p + 1; } return a; } // Driver code public static void Main() { int n = 1, m = 3; // Function calling Console.Write(minOperations(n, m)); }} // This code is contributed by AnkitRai01
<script>// javascript implementation of the above approach // Function to find the minimum no of operations function minOperations(n , m) { var a = 0, k = 1; // find the maximum of two and store it in p var p = Math.max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 var s = (p - n + p - m); var q = ((-1 + Math.sqrt(8 * s + 1)) / 2); if (q - Math.floor(q) == 0) { a = parseInt( q); n = m; } p = p + 1; } return a; } // Driver code var n = 1, m = 3; // Function calling document.write(minOperations(n, m)); // This code is contributed by Rajput-Ji</script>
3
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
ankthon
29AjayKumar
Rajput-Ji
subham348
arithmetic progression
Numbers
Greedy
Mathematical
Greedy
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 218,
"s": 54,
"text": "Given two numbers n and m, the task is to find the minimum number of operations required to make them equal if the following operations can be performed on them. "
},
{
"code": null,
"e": 294,
"s": 218,
"text": "During the first operation, any of the two numbers can be increased by one."
},
{
"code": null,
"e": 371,
"s": 294,
"text": "During the second operation, any of the two numbers can be increased by two."
},
{
"code": null,
"e": 459,
"s": 371,
"text": "During the third operation, any of the two numbers can be increased by three and so on."
},
{
"code": null,
"e": 471,
"s": 459,
"text": "Examples: "
},
{
"code": null,
"e": 653,
"s": 471,
"text": "Input : n = 1, m = 3\nOutput : 3\nExplanation: \nAdd 1 to n; n = 2\nAdd 2 to m; m = 5\nAdd 3 to n; n = 5\nBoth n and m are equal now\nN of operations = 3\n\nInput : n = 30, m = 20\nOutput : 4"
},
{
"code": null,
"e": 765,
"s": 655,
"text": "Approach: The approach used to solve the problem is the sum of N terms in an AP. It is given by the formula "
},
{
"code": null,
"e": 784,
"s": 765,
"text": "S(n) = (n*(n+1))/2"
},
{
"code": null,
"e": 932,
"s": 784,
"text": "So, the task is to find the difference between those two numbers and see if the difference can be achieved by adding first n elements. Therefore, "
},
{
"code": null,
"e": 959,
"s": 932,
"text": "S(n) = max(m,n) - min(m,n)"
},
{
"code": null,
"e": 1059,
"s": 959,
"text": "On substituting this value of sum in the first equation; we get the number of elements n given by "
},
{
"code": null,
"e": 1083,
"s": 1059,
"text": "n=(-1+sqrt(1+8*S(n)))/2"
},
{
"code": null,
"e": 1210,
"s": 1083,
"text": "If this n is a perfect integer, then it is our final answer. Else, we increment our target value to reach by 1 and continue. "
},
{
"code": null,
"e": 1263,
"s": 1210,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1267,
"s": 1263,
"text": "C++"
},
{
"code": null,
"e": 1272,
"s": 1267,
"text": "Java"
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "Python3"
},
{
"code": null,
"e": 1283,
"s": 1280,
"text": "C#"
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum no of operationsint minOperations(int n, int m){ int a = 0, k = 1; // find the maximum of two and store it in p int p = max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (-1 + sqrt(8 * s + 1)) / 2; if (q - floor(q) == 0) { a = q; n = m; } p = p + 1; } return a;} // Driver codeint main(){ int n = 1, m = 3; // Function calling cout << minOperations(n, m); return 0;}",
"e": 2139,
"s": 1294,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the minimum no of operationsstatic int minOperations(int n, int m){ int a = 0, k = 1; // find the maximum of two and store it in p int p = Math.max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (float) ((-1 + Math.sqrt(8 * s + 1)) / 2); if (q - Math.floor(q) == 0) { a = (int) q; n = m; } p = p + 1; } return a;} // Driver codepublic static void main(String[] args){ int n = 1, m = 3; // Function calling System.out.print(minOperations(n, m));}} // This code is contributed by 29AjayKumar",
"e": 3093,
"s": 2139,
"text": null
},
{
"code": "# Python3 implementation of# the above approachfrom math import sqrt, floor # Function to find the minimum# no. of operationsdef minOperations( n, m) : a = 0; k = 1; # find the maximum of two and # store it in p p = max(n, m); # increase it until it is achievable # from given n and m while (n != m) : # Here value added to n and m will be # S(n)=p-n+p-m; # check whether integer value of n # exist by the formula # n=(-1+sqrt(1+8*S(n)))/2 s = float(p - n + p - m); q = (-1 + sqrt(8 * s + 1)) / 2; if (q - floor(q) == 0) : a = q; n = m; p = p + 1; return a; # Driver codeif __name__ == \"__main__\" : n = 1; m = 3; # Function calling print(minOperations(n, m)); # This code is contributed by AnkitRai01",
"e": 3921,
"s": 3093,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to find the minimum no of operations static int minOperations(int n, int m) { int a = 0, k = 1; // find the maximum of two and store it in p int p = Math.Max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 float s = (float)(p - n + p - m); float q = (float) ((-1 + Math.Sqrt(8 * s + 1)) / 2); if (q - Math.Floor(q) == 0) { a = (int) q; n = m; } p = p + 1; } return a; } // Driver code public static void Main() { int n = 1, m = 3; // Function calling Console.Write(minOperations(n, m)); }} // This code is contributed by AnkitRai01",
"e": 5010,
"s": 3921,
"text": null
},
{
"code": "<script>// javascript implementation of the above approach // Function to find the minimum no of operations function minOperations(n , m) { var a = 0, k = 1; // find the maximum of two and store it in p var p = Math.max(n, m); // increase it until it is achievable from // given n and m while (n != m) { // Here value added to n and m will be // S(n)=p-n+p-m; // check whether integer value of n exist // by the formula // n=(-1+Math.sqrt(1+8*S(n)))/2 var s = (p - n + p - m); var q = ((-1 + Math.sqrt(8 * s + 1)) / 2); if (q - Math.floor(q) == 0) { a = parseInt( q); n = m; } p = p + 1; } return a; } // Driver code var n = 1, m = 3; // Function calling document.write(minOperations(n, m)); // This code is contributed by Rajput-Ji</script>",
"e": 6008,
"s": 5010,
"text": null
},
{
"code": null,
"e": 6010,
"s": 6008,
"text": "3"
},
{
"code": null,
"e": 6040,
"s": 6012,
"text": "Time Complexity: O(sqrt(n))"
},
{
"code": null,
"e": 6062,
"s": 6040,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6070,
"s": 6062,
"text": "ankthon"
},
{
"code": null,
"e": 6082,
"s": 6070,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6092,
"s": 6082,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6102,
"s": 6092,
"text": "subham348"
},
{
"code": null,
"e": 6125,
"s": 6102,
"text": "arithmetic progression"
},
{
"code": null,
"e": 6133,
"s": 6125,
"text": "Numbers"
},
{
"code": null,
"e": 6140,
"s": 6133,
"text": "Greedy"
},
{
"code": null,
"e": 6153,
"s": 6140,
"text": "Mathematical"
},
{
"code": null,
"e": 6160,
"s": 6153,
"text": "Greedy"
},
{
"code": null,
"e": 6173,
"s": 6160,
"text": "Mathematical"
},
{
"code": null,
"e": 6181,
"s": 6173,
"text": "Numbers"
}
] |
Linear Search
|
23 Jun, 2022
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].
A simple approach is to do a linear search, i.e
Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of the elements, return -1.
Example:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <iostream>using namespace std; int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(void){ int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call int result = search(arr, n, x); (result == -1) ? cout << "Element is not present in array" : cout << "Element is present at index " << result; return 0;}
// C code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <stdio.h> int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(void){ int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call int result = search(arr, n, x); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0;}
// Java code for linearly searching x in arr[]. If x// is present then return its location, otherwise// return -1 class GFG{ public static int search(int arr[], int x) { int n = arr.length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver code public static void main(String args[]) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; // Function call int result = search(arr, x); if (result == -1) System.out.print( "Element is not present in array"); else System.out.print("Element is present at index " + result); }}
# Python3 code to linearly search x in arr[].# If x is present then return its location,# otherwise return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Codearr = [2, 3, 4, 10, 40]x = 10n = len(arr) # Function callresult = search(arr, n, x)if(result == -1): print("Element is not present in array")else: print("Element is present at index", result)
// C# code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1using System; class GFG { public static int search(int[] arr, int x) { int n = arr.Length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 3, 4, 10, 40 }; int x = 10; // Function call int result = search(arr, x); if (result == -1) Console.WriteLine( "Element is not present in array"); else Console.WriteLine("Element is present at index " + result); }} // This code is contributed by DrRoot_
<?php// PHP code for linearly search x in arr[].// If x is present then return its location,// otherwise return -1 function search($arr, $x){ $n = sizeof($arr); for($i = 0; $i < $n; $i++) { if($arr[$i] == $x) return $i; } return -1;} // Driver Code$arr = array(2, 3, 4, 10, 40);$x = 10; // Function call$result = search($arr, $x);if($result == -1) echo "Element is not present in array";else echo "Element is present at index " , $result; // This code is contributed// by jit_t?>
<script> // Javascript code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 function search(arr, n, x){ let i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver code let arr = [ 2, 3, 4, 10, 40 ]; let x = 10; let n = arr.length; // Function call let result = search(arr, n, x); (result == -1) ? document.write("Element is not present in array") : document.write("Element is present at index " + result); // This code is contributed by Manoj </script>
Element is present at index 3
The time complexity of the above algorithm is O(n).
Linear search is rarely used practically because other search algorithms such as the binary search algorithm and hash tables allow significantly faster searching compared to Linear search.
Improve Linear Search Worst-Case Complexity
if element Found at last O(n) to O(1)It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same.
if element Found at last O(n) to O(1)
It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same.
Below is the implementation:
C++14
Java
Python3
C#
Javascript
// C++ program for linear search#include<bits/stdc++.h>using namespace std; void search(vector<int> arr, int search_Element){ int left = 0; int length = arr.size(); int position = -1; int right = length - 1; // Run loop from 0 to right for(left = 0; left <= right;) { // If search_element is found with // left variable if (arr[left] == search_Element) { position = left; cout << "Element found in Array at " << position + 1 << " Position with " << left + 1 << " Attempt"; break; } // If search_element is found with // right variable if (arr[right] == search_Element) { position = right; cout << "Element found in Array at " << position + 1 << " Position with " << length - right << " Attempt"; break; } left++; right--; } // If element not found if (position == -1) cout << "Not found in Array with " << left << " Attempt";} // Driver codeint main(){ vector<int> arr{ 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr, search_element);} // This code is contributed by mayanktyagi1709
// Java program for linear search import java.io.*; class GFG{ public static void search(int arr[], int search_Element) { int left = 0; int length = arr.length; int right = length - 1; int position = -1; // run loop from 0 to right for (left = 0; left <= right;) { // if search_element is found with left variable if (arr[left] == search_Element) { position = left; System.out.println( "Element found in Array at " + (position + 1) + " Position with " + (left + 1) + " Attempt"); break; } // if search_element is found with right variable if (arr[right] == search_Element) { position = right; System.out.println( "Element found in Array at " + (position + 1) + " Position with " + (length - right) + " Attempt"); break; } left++; right--; } // if element not found if (position == -1) System.out.println("Not found in Array with " + left + " Attempt"); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr,search_element); }}
# Python3 program for linear searchdef search(arr, search_Element): left = 0 length = len(arr) position = -1 right = length - 1 # Run loop from 0 to right for left in range(0, right, 1): # If search_element is found with # left variable if (arr[left] == search_Element): position = left print("Element found in Array at ", position + 1, " Position with ", left + 1, " Attempt") break # If search_element is found with # right variable if (arr[right] == search_Element): position = right print("Element found in Array at ", position + 1, " Position with ", length - right, " Attempt") break left += 1 right -= 1 # If element not found if (position == -1): print("Not found in Array with ", left, " Attempt") # Driver codearr = [1, 2, 3, 4, 5]search_element = 5 # Function callsearch(arr, search_element) # This code is contributed by Dharanendra L V.
// C# program for linear searchusing System;class GFG{ public static void search(int []arr, int search_Element) { int left = 0; int length = arr.Length; int right = length - 1; int position = -1; // run loop from 0 to right for (left = 0; left <= right;) { // if search_element is found with left variable if (arr[left] == search_Element) { position = left; Console.WriteLine( "Element found in Array at " + (position + 1) + " Position with " + (left + 1) + " Attempt"); break; } // if search_element is found with right variable if (arr[right] == search_Element) { position = right; Console.WriteLine( "Element found in Array at " + (position + 1) + " Position with " + (length - right) + " Attempt"); break; } left++; right--; } // if element not found if (position == -1) Console.WriteLine("Not found in Array with " + left + " Attempt"); } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr,search_element); }} // This code is contributed by 29AjayKumar
<script> // Javascript program for linear search function search(arr, search_Element){ let left = 0; let length = arr.length; let right = length - 1; let position = -1; // Run loop from 0 to right for(left = 0; left <= right;) { // If search_element is found // with left variable if (arr[left] == search_Element) { position = left; document.write( "Element found in Array at " + (position + 1) + " Position with " + (left + 1) + " Attempt"); break; } // If search_element is found // with right variable if (arr[right] == search_Element) { position = right; document.write( "Element found in Array at " + (position + 1) + " Position with " + (length - right) + " Attempt"); break; } left++; right--; } // If element not found if (position == -1) document.write("Not found in Array with " + left + " Attempt");} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let search_element = 5; // Function callsearch(arr, search_element); // This code is contributed by code_hunt </script>
Element found in Array at 5 Position with 1 Attempt
Time Complexity: O(n)
Auxiliary Space: O(1)
ALTERNATE APPROACH:
Recursive Approach For Linear Search:
The approach for the problem will be:
The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree. Now, if the size of the given array is greater than zero then we will have two conditions:
The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree.
Now, if the size of the given array is greater than zero then we will have two conditions:
If the element present at the current size index matches the given element, then return the index.
Else make a recursive call to the function by decreasing the array size by a factor of 1.
Below is the implementation for linear search using recursion:
C++
// Recursive Code For Linear Search#include <iostream>using namespace std;int linearsearch(int arr[], int size, int key){ if (size == 0) { return -1; } if (arr[size] == key) { return size; } else { int ans = linearsearch(arr, size - 1, key); return ans; }}int main() { int arr[5]={1,5,6,9,4}; int key = 5; int ans = linearsearch(arr, 5, key); if(ans == -1 ){ cout << "The element "<<key <<" is not found."<< endl; }else{ cout << "The element "<<key <<" is found at "<<ans <<" index of the given array."<< endl; } return 0;}// Code contributed by pragatikohli
The element 5 is found at 1 index of the given array.
Linear Search | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLinear Search | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4GPdGsB3OSc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Also See – Binary Search
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
RishabhPrabhu
DrRoot_
ApekshikPanigrahi
GaneshJ
abhishek07456cse
29AjayKumar
mayanktyagi1709
dharanendralv23
mank1083
code_hunt
arorakashish0911
rohanthakurarmy
susobhanakhuli
pragatikohli12
CBSE - Class 11
school-programming
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]."
},
{
"code": null,
"e": 166,
"s": 153,
"text": "Examples : "
},
{
"code": null,
"e": 462,
"s": 166,
"text": "Input : arr[] = {10, 20, 80, 30, 60, 50, \n 110, 100, 130, 170}\n x = 110;\nOutput : 6\nElement x is present at index 6\n\nInput : arr[] = {10, 20, 80, 30, 60, 50, \n 110, 100, 130, 170}\n x = 175;\nOutput : -1\nElement x is not present in arr[]."
},
{
"code": null,
"e": 512,
"s": 462,
"text": "A simple approach is to do a linear search, i.e "
},
{
"code": null,
"e": 605,
"s": 512,
"text": "Start from the leftmost element of arr[] and one by one compare x with each element of arr[]"
},
{
"code": null,
"e": 653,
"s": 605,
"text": "If x matches with an element, return the index."
},
{
"code": null,
"e": 709,
"s": 653,
"text": "If x doesn’t match with any of the elements, return -1."
},
{
"code": null,
"e": 719,
"s": 709,
"text": "Example: "
},
{
"code": null,
"e": 723,
"s": 719,
"text": "C++"
},
{
"code": null,
"e": 725,
"s": 723,
"text": "C"
},
{
"code": null,
"e": 730,
"s": 725,
"text": "Java"
},
{
"code": null,
"e": 738,
"s": 730,
"text": "Python3"
},
{
"code": null,
"e": 741,
"s": 738,
"text": "C#"
},
{
"code": null,
"e": 745,
"s": 741,
"text": "PHP"
},
{
"code": null,
"e": 756,
"s": 745,
"text": "Javascript"
},
{
"code": "// C++ code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <iostream>using namespace std; int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(void){ int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call int result = search(arr, n, x); (result == -1) ? cout << \"Element is not present in array\" : cout << \"Element is present at index \" << result; return 0;}",
"e": 1361,
"s": 756,
"text": null
},
{
"code": "// C code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <stdio.h> int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(void){ int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call int result = search(arr, n, x); (result == -1) ? printf(\"Element is not present in array\") : printf(\"Element is present at index %d\", result); return 0;}",
"e": 1943,
"s": 1361,
"text": null
},
{
"code": "// Java code for linearly searching x in arr[]. If x// is present then return its location, otherwise// return -1 class GFG{ public static int search(int arr[], int x) { int n = arr.length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver code public static void main(String args[]) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; // Function call int result = search(arr, x); if (result == -1) System.out.print( \"Element is not present in array\"); else System.out.print(\"Element is present at index \" + result); }}",
"e": 2682,
"s": 1943,
"text": null
},
{
"code": "# Python3 code to linearly search x in arr[].# If x is present then return its location,# otherwise return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Codearr = [2, 3, 4, 10, 40]x = 10n = len(arr) # Function callresult = search(arr, n, x)if(result == -1): print(\"Element is not present in array\")else: print(\"Element is present at index\", result)",
"e": 3112,
"s": 2682,
"text": null
},
{
"code": "// C# code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1using System; class GFG { public static int search(int[] arr, int x) { int n = arr.Length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 3, 4, 10, 40 }; int x = 10; // Function call int result = search(arr, x); if (result == -1) Console.WriteLine( \"Element is not present in array\"); else Console.WriteLine(\"Element is present at index \" + result); }} // This code is contributed by DrRoot_",
"e": 3888,
"s": 3112,
"text": null
},
{
"code": "<?php// PHP code for linearly search x in arr[].// If x is present then return its location,// otherwise return -1 function search($arr, $x){ $n = sizeof($arr); for($i = 0; $i < $n; $i++) { if($arr[$i] == $x) return $i; } return -1;} // Driver Code$arr = array(2, 3, 4, 10, 40);$x = 10; // Function call$result = search($arr, $x);if($result == -1) echo \"Element is not present in array\";else echo \"Element is present at index \" , $result; // This code is contributed// by jit_t?>",
"e": 4439,
"s": 3888,
"text": null
},
{
"code": "<script> // Javascript code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 function search(arr, n, x){ let i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver code let arr = [ 2, 3, 4, 10, 40 ]; let x = 10; let n = arr.length; // Function call let result = search(arr, n, x); (result == -1) ? document.write(\"Element is not present in array\") : document.write(\"Element is present at index \" + result); // This code is contributed by Manoj </script>",
"e": 5023,
"s": 4439,
"text": null
},
{
"code": null,
"e": 5053,
"s": 5023,
"text": "Element is present at index 3"
},
{
"code": null,
"e": 5106,
"s": 5053,
"text": "The time complexity of the above algorithm is O(n). "
},
{
"code": null,
"e": 5295,
"s": 5106,
"text": "Linear search is rarely used practically because other search algorithms such as the binary search algorithm and hash tables allow significantly faster searching compared to Linear search."
},
{
"code": null,
"e": 5339,
"s": 5295,
"text": "Improve Linear Search Worst-Case Complexity"
},
{
"code": null,
"e": 5600,
"s": 5339,
"text": "if element Found at last O(n) to O(1)It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same."
},
{
"code": null,
"e": 5639,
"s": 5600,
"text": "if element Found at last O(n) to O(1)"
},
{
"code": null,
"e": 5862,
"s": 5639,
"text": "It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same."
},
{
"code": null,
"e": 5891,
"s": 5862,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 5897,
"s": 5891,
"text": "C++14"
},
{
"code": null,
"e": 5902,
"s": 5897,
"text": "Java"
},
{
"code": null,
"e": 5910,
"s": 5902,
"text": "Python3"
},
{
"code": null,
"e": 5913,
"s": 5910,
"text": "C#"
},
{
"code": null,
"e": 5924,
"s": 5913,
"text": "Javascript"
},
{
"code": "// C++ program for linear search#include<bits/stdc++.h>using namespace std; void search(vector<int> arr, int search_Element){ int left = 0; int length = arr.size(); int position = -1; int right = length - 1; // Run loop from 0 to right for(left = 0; left <= right;) { // If search_element is found with // left variable if (arr[left] == search_Element) { position = left; cout << \"Element found in Array at \" << position + 1 << \" Position with \" << left + 1 << \" Attempt\"; break; } // If search_element is found with // right variable if (arr[right] == search_Element) { position = right; cout << \"Element found in Array at \" << position + 1 << \" Position with \" << length - right << \" Attempt\"; break; } left++; right--; } // If element not found if (position == -1) cout << \"Not found in Array with \" << left << \" Attempt\";} // Driver codeint main(){ vector<int> arr{ 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr, search_element);} // This code is contributed by mayanktyagi1709",
"e": 7284,
"s": 5924,
"text": null
},
{
"code": "// Java program for linear search import java.io.*; class GFG{ public static void search(int arr[], int search_Element) { int left = 0; int length = arr.length; int right = length - 1; int position = -1; // run loop from 0 to right for (left = 0; left <= right;) { // if search_element is found with left variable if (arr[left] == search_Element) { position = left; System.out.println( \"Element found in Array at \" + (position + 1) + \" Position with \" + (left + 1) + \" Attempt\"); break; } // if search_element is found with right variable if (arr[right] == search_Element) { position = right; System.out.println( \"Element found in Array at \" + (position + 1) + \" Position with \" + (length - right) + \" Attempt\"); break; } left++; right--; } // if element not found if (position == -1) System.out.println(\"Not found in Array with \" + left + \" Attempt\"); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr,search_element); }}",
"e": 8826,
"s": 7284,
"text": null
},
{
"code": "# Python3 program for linear searchdef search(arr, search_Element): left = 0 length = len(arr) position = -1 right = length - 1 # Run loop from 0 to right for left in range(0, right, 1): # If search_element is found with # left variable if (arr[left] == search_Element): position = left print(\"Element found in Array at \", position + 1, \" Position with \", left + 1, \" Attempt\") break # If search_element is found with # right variable if (arr[right] == search_Element): position = right print(\"Element found in Array at \", position + 1, \" Position with \", length - right, \" Attempt\") break left += 1 right -= 1 # If element not found if (position == -1): print(\"Not found in Array with \", left, \" Attempt\") # Driver codearr = [1, 2, 3, 4, 5]search_element = 5 # Function callsearch(arr, search_element) # This code is contributed by Dharanendra L V.",
"e": 9867,
"s": 8826,
"text": null
},
{
"code": "// C# program for linear searchusing System;class GFG{ public static void search(int []arr, int search_Element) { int left = 0; int length = arr.Length; int right = length - 1; int position = -1; // run loop from 0 to right for (left = 0; left <= right;) { // if search_element is found with left variable if (arr[left] == search_Element) { position = left; Console.WriteLine( \"Element found in Array at \" + (position + 1) + \" Position with \" + (left + 1) + \" Attempt\"); break; } // if search_element is found with right variable if (arr[right] == search_Element) { position = right; Console.WriteLine( \"Element found in Array at \" + (position + 1) + \" Position with \" + (length - right) + \" Attempt\"); break; } left++; right--; } // if element not found if (position == -1) Console.WriteLine(\"Not found in Array with \" + left + \" Attempt\"); } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4, 5 }; int search_element = 5; // Function call search(arr,search_element); }} // This code is contributed by 29AjayKumar",
"e": 11470,
"s": 9867,
"text": null
},
{
"code": "<script> // Javascript program for linear search function search(arr, search_Element){ let left = 0; let length = arr.length; let right = length - 1; let position = -1; // Run loop from 0 to right for(left = 0; left <= right;) { // If search_element is found // with left variable if (arr[left] == search_Element) { position = left; document.write( \"Element found in Array at \" + (position + 1) + \" Position with \" + (left + 1) + \" Attempt\"); break; } // If search_element is found // with right variable if (arr[right] == search_Element) { position = right; document.write( \"Element found in Array at \" + (position + 1) + \" Position with \" + (length - right) + \" Attempt\"); break; } left++; right--; } // If element not found if (position == -1) document.write(\"Not found in Array with \" + left + \" Attempt\");} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let search_element = 5; // Function callsearch(arr, search_element); // This code is contributed by code_hunt </script>",
"e": 12775,
"s": 11470,
"text": null
},
{
"code": null,
"e": 12827,
"s": 12775,
"text": "Element found in Array at 5 Position with 1 Attempt"
},
{
"code": null,
"e": 12849,
"s": 12827,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 12871,
"s": 12849,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12891,
"s": 12871,
"text": "ALTERNATE APPROACH:"
},
{
"code": null,
"e": 12929,
"s": 12891,
"text": "Recursive Approach For Linear Search:"
},
{
"code": null,
"e": 12967,
"s": 12929,
"text": "The approach for the problem will be:"
},
{
"code": null,
"e": 13312,
"s": 12967,
"text": " The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree. Now, if the size of the given array is greater than zero then we will have two conditions: "
},
{
"code": null,
"e": 13565,
"s": 13312,
"text": " The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree. "
},
{
"code": null,
"e": 13658,
"s": 13565,
"text": "Now, if the size of the given array is greater than zero then we will have two conditions: "
},
{
"code": null,
"e": 13758,
"s": 13658,
"text": " If the element present at the current size index matches the given element, then return the index."
},
{
"code": null,
"e": 13848,
"s": 13758,
"text": "Else make a recursive call to the function by decreasing the array size by a factor of 1."
},
{
"code": null,
"e": 13911,
"s": 13848,
"text": "Below is the implementation for linear search using recursion:"
},
{
"code": null,
"e": 13915,
"s": 13911,
"text": "C++"
},
{
"code": "// Recursive Code For Linear Search#include <iostream>using namespace std;int linearsearch(int arr[], int size, int key){ if (size == 0) { return -1; } if (arr[size] == key) { return size; } else { int ans = linearsearch(arr, size - 1, key); return ans; }}int main() { int arr[5]={1,5,6,9,4}; int key = 5; int ans = linearsearch(arr, 5, key); if(ans == -1 ){ cout << \"The element \"<<key <<\" is not found.\"<< endl; }else{ cout << \"The element \"<<key <<\" is found at \"<<ans <<\" index of the given array.\"<< endl; } return 0;}// Code contributed by pragatikohli",
"e": 14565,
"s": 13915,
"text": null
},
{
"code": null,
"e": 14620,
"s": 14565,
"text": "The element 5 is found at 1 index of the given array.\n"
},
{
"code": null,
"e": 15464,
"s": 14620,
"text": "Linear Search | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLinear Search | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4GPdGsB3OSc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 15489,
"s": 15464,
"text": "Also See – Binary Search"
},
{
"code": null,
"e": 15616,
"s": 15489,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15622,
"s": 15616,
"text": "jit_t"
},
{
"code": null,
"e": 15636,
"s": 15622,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 15644,
"s": 15636,
"text": "DrRoot_"
},
{
"code": null,
"e": 15662,
"s": 15644,
"text": "ApekshikPanigrahi"
},
{
"code": null,
"e": 15670,
"s": 15662,
"text": "GaneshJ"
},
{
"code": null,
"e": 15687,
"s": 15670,
"text": "abhishek07456cse"
},
{
"code": null,
"e": 15699,
"s": 15687,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15715,
"s": 15699,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 15731,
"s": 15715,
"text": "dharanendralv23"
},
{
"code": null,
"e": 15740,
"s": 15731,
"text": "mank1083"
},
{
"code": null,
"e": 15750,
"s": 15740,
"text": "code_hunt"
},
{
"code": null,
"e": 15767,
"s": 15750,
"text": "arorakashish0911"
},
{
"code": null,
"e": 15783,
"s": 15767,
"text": "rohanthakurarmy"
},
{
"code": null,
"e": 15798,
"s": 15783,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 15813,
"s": 15798,
"text": "pragatikohli12"
},
{
"code": null,
"e": 15829,
"s": 15813,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 15848,
"s": 15829,
"text": "school-programming"
},
{
"code": null,
"e": 15855,
"s": 15848,
"text": "Arrays"
},
{
"code": null,
"e": 15865,
"s": 15855,
"text": "Searching"
},
{
"code": null,
"e": 15872,
"s": 15865,
"text": "Arrays"
},
{
"code": null,
"e": 15882,
"s": 15872,
"text": "Searching"
},
{
"code": null,
"e": 15980,
"s": 15882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15995,
"s": 15980,
"text": "Arrays in Java"
},
{
"code": null,
"e": 16041,
"s": 15995,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 16109,
"s": 16041,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 16153,
"s": 16109,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 16185,
"s": 16153,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 16253,
"s": 16185,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 16309,
"s": 16253,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 16357,
"s": 16309,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 16381,
"s": 16357,
"text": "Find the Missing Number"
}
] |
StDev() and StDevP() Function in MS Access
|
15 Sep, 2020
1. StDev() Function :StDev() Function in MS Access is used to estimate the standard deviation for a population sample.
Syntax :
StDev (expr)
Parameter : This method accept one parameter as mentioned above and described below :
expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function.
Returns : It calculates standard deviation for a population sample.Note : If the underlying query contains fewer than two records or no records then it returns a Null value which indicates that a standard deviation cannot be calculated.
Table – ProcuctDetails
Example1 :The standard deviation for the product price.
SELECT stDev(Product_Price) AS StDEV_Value FROM ProcuctDetails;
Output :
Example2 :The standard deviation for only one record.
SELECT stDev(100) AS StDEV_Value ;
Output :
So, we can see it cannot be calculated.2. StDevP () Function :StDevP() Function in MS Access is used to estimate the standard deviation for a population. The main difference between the StDevP() function and StDev() function is StDevP evaluates a population, and the StDev evaluates a population sample.
Syntax :
StDevP (expr)
Parameter : This method accept one parameter as mentioned above and described below :
expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function.
Returns : It calculates standard deviation for a population.
Note : If the underlying query contains fewer than two records then it returns a Null value which indicates that a standard deviation cannot be calculated.
Table – Products
Example-1 :
SELECT stDevP(P_Price) AS StDEVp_Value FROM Procucts;
Output :
Example-2 :
SELECT stDevP(10) AS StDEVp_Value;
Output :
DBMS-SQL
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?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "1. StDev() Function :StDev() Function in MS Access is used to estimate the standard deviation for a population sample."
},
{
"code": null,
"e": 156,
"s": 147,
"text": "Syntax :"
},
{
"code": null,
"e": 169,
"s": 156,
"text": "StDev (expr)"
},
{
"code": null,
"e": 255,
"s": 169,
"text": "Parameter : This method accept one parameter as mentioned above and described below :"
},
{
"code": null,
"e": 533,
"s": 255,
"text": "expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function."
},
{
"code": null,
"e": 770,
"s": 533,
"text": "Returns : It calculates standard deviation for a population sample.Note : If the underlying query contains fewer than two records or no records then it returns a Null value which indicates that a standard deviation cannot be calculated."
},
{
"code": null,
"e": 793,
"s": 770,
"text": "Table – ProcuctDetails"
},
{
"code": null,
"e": 849,
"s": 793,
"text": "Example1 :The standard deviation for the product price."
},
{
"code": null,
"e": 913,
"s": 849,
"text": "SELECT stDev(Product_Price) AS StDEV_Value FROM ProcuctDetails;"
},
{
"code": null,
"e": 922,
"s": 913,
"text": "Output :"
},
{
"code": null,
"e": 976,
"s": 922,
"text": "Example2 :The standard deviation for only one record."
},
{
"code": null,
"e": 1011,
"s": 976,
"text": "SELECT stDev(100) AS StDEV_Value ;"
},
{
"code": null,
"e": 1020,
"s": 1011,
"text": "Output :"
},
{
"code": null,
"e": 1324,
"s": 1020,
"text": "So, we can see it cannot be calculated.2. StDevP () Function :StDevP() Function in MS Access is used to estimate the standard deviation for a population. The main difference between the StDevP() function and StDev() function is StDevP evaluates a population, and the StDev evaluates a population sample."
},
{
"code": null,
"e": 1333,
"s": 1324,
"text": "Syntax :"
},
{
"code": null,
"e": 1347,
"s": 1333,
"text": "StDevP (expr)"
},
{
"code": null,
"e": 1433,
"s": 1347,
"text": "Parameter : This method accept one parameter as mentioned above and described below :"
},
{
"code": null,
"e": 1711,
"s": 1433,
"text": "expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function."
},
{
"code": null,
"e": 1772,
"s": 1711,
"text": "Returns : It calculates standard deviation for a population."
},
{
"code": null,
"e": 1928,
"s": 1772,
"text": "Note : If the underlying query contains fewer than two records then it returns a Null value which indicates that a standard deviation cannot be calculated."
},
{
"code": null,
"e": 1945,
"s": 1928,
"text": "Table – Products"
},
{
"code": null,
"e": 1957,
"s": 1945,
"text": "Example-1 :"
},
{
"code": null,
"e": 2011,
"s": 1957,
"text": "SELECT stDevP(P_Price) AS StDEVp_Value FROM Procucts;"
},
{
"code": null,
"e": 2020,
"s": 2011,
"text": "Output :"
},
{
"code": null,
"e": 2032,
"s": 2020,
"text": "Example-2 :"
},
{
"code": null,
"e": 2067,
"s": 2032,
"text": "SELECT stDevP(10) AS StDEVp_Value;"
},
{
"code": null,
"e": 2076,
"s": 2067,
"text": "Output :"
},
{
"code": null,
"e": 2085,
"s": 2076,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2089,
"s": 2085,
"text": "SQL"
},
{
"code": null,
"e": 2093,
"s": 2089,
"text": "SQL"
},
{
"code": null,
"e": 2191,
"s": 2093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2257,
"s": 2191,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2281,
"s": 2257,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2313,
"s": 2281,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2346,
"s": 2313,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2363,
"s": 2346,
"text": "SQL using Python"
},
{
"code": null,
"e": 2393,
"s": 2363,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2471,
"s": 2393,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2507,
"s": 2471,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2538,
"s": 2507,
"text": "SQL Query to Compare Two Dates"
}
] |
turtle.towards() function in Python
|
26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the angle, between the line from turtle-position to the position specified by x, y, and the turtle’s start orientation.
Syntax :
turtle.towards(x, y=None)
Parameters:
Below is the implementation of the above method with an example :
Python3
# import packageimport turtle # go towards eastang=turtle.towards(100,0) # print angleprint(ang) # go towards northang=turtle.towards(0,100) # print angleprint(ang) # go towards westang=turtle.towards(-100,0) # print angleprint(ang) # go towards southang=turtle.towards(0,-100) # print angleprint(ang)
Output :
0.0
90.0
180.0
270.0
Here we can see that one can easily get an angle towards any coordinate point without going to that point. In the above example turtle remain on (0,0) i.e. home and get all angles to the specified position without any movement.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 397,
"s": 245,
"text": "This function is used to return the angle, between the line from turtle-position to the position specified by x, y, and the turtle’s start orientation."
},
{
"code": null,
"e": 406,
"s": 397,
"text": "Syntax :"
},
{
"code": null,
"e": 433,
"s": 406,
"text": "turtle.towards(x, y=None)\n"
},
{
"code": null,
"e": 445,
"s": 433,
"text": "Parameters:"
},
{
"code": null,
"e": 511,
"s": 445,
"text": "Below is the implementation of the above method with an example :"
},
{
"code": null,
"e": 519,
"s": 511,
"text": "Python3"
},
{
"code": "# import packageimport turtle # go towards eastang=turtle.towards(100,0) # print angleprint(ang) # go towards northang=turtle.towards(0,100) # print angleprint(ang) # go towards westang=turtle.towards(-100,0) # print angleprint(ang) # go towards southang=turtle.towards(0,-100) # print angleprint(ang)",
"e": 829,
"s": 519,
"text": null
},
{
"code": null,
"e": 838,
"s": 829,
"text": "Output :"
},
{
"code": null,
"e": 860,
"s": 838,
"text": "0.0\n90.0\n180.0\n270.0\n"
},
{
"code": null,
"e": 1088,
"s": 860,
"text": "Here we can see that one can easily get an angle towards any coordinate point without going to that point. In the above example turtle remain on (0,0) i.e. home and get all angles to the specified position without any movement."
},
{
"code": null,
"e": 1102,
"s": 1088,
"text": "Python-turtle"
},
{
"code": null,
"e": 1109,
"s": 1102,
"text": "Python"
}
] |
Python | sys.setrecursionlimit() method
|
07 Aug, 2019
This sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It provides information about constants, functions and methods of python interpreter. It can be used for manipulating Python runtime environment.
sys.setrecursionlimit() method is used to set the maximum depth of the Python interpreter stack to the required limit. This limit prevents any program from getting into infinite recursion, Otherwise infinite recursion will lead to overflow of the C stack and crash the Python.
Note: The highest possible limit is platform-dependent. This should be done with care because too-high limit can lead to crash.
Syntax: sys.setrecursionlimit(limit)
Parameter:limit: It the value of integer type that denotes the new limit of python interpreter stack.
Return Value: This method returns nothing.
Example #1 :
# Python program to explain sys.setrecursionlimit() method # Importing sys module import sys # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit() # Print the current limit print('Before changing, limit of stack =', limit) # New limitNewlimit = 500 # Using sys.setrecursionlimit() method sys.setrecursionlimit(Newlimit) # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit() # Print the current limit print('After changing, limit of stack =', limit)
Before changing, limit of stack = 1000
After changing, limit of stack = 500
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Aug, 2019"
},
{
"code": null,
"e": 349,
"s": 53,
"text": "This sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It provides information about constants, functions and methods of python interpreter. It can be used for manipulating Python runtime environment."
},
{
"code": null,
"e": 626,
"s": 349,
"text": "sys.setrecursionlimit() method is used to set the maximum depth of the Python interpreter stack to the required limit. This limit prevents any program from getting into infinite recursion, Otherwise infinite recursion will lead to overflow of the C stack and crash the Python."
},
{
"code": null,
"e": 754,
"s": 626,
"text": "Note: The highest possible limit is platform-dependent. This should be done with care because too-high limit can lead to crash."
},
{
"code": null,
"e": 791,
"s": 754,
"text": "Syntax: sys.setrecursionlimit(limit)"
},
{
"code": null,
"e": 893,
"s": 791,
"text": "Parameter:limit: It the value of integer type that denotes the new limit of python interpreter stack."
},
{
"code": null,
"e": 936,
"s": 893,
"text": "Return Value: This method returns nothing."
},
{
"code": null,
"e": 949,
"s": 936,
"text": "Example #1 :"
},
{
"code": "# Python program to explain sys.setrecursionlimit() method # Importing sys module import sys # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit() # Print the current limit print('Before changing, limit of stack =', limit) # New limitNewlimit = 500 # Using sys.setrecursionlimit() method sys.setrecursionlimit(Newlimit) # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit() # Print the current limit print('After changing, limit of stack =', limit) ",
"e": 1524,
"s": 949,
"text": null
},
{
"code": null,
"e": 1601,
"s": 1524,
"text": "Before changing, limit of stack = 1000\nAfter changing, limit of stack = 500\n"
},
{
"code": null,
"e": 1616,
"s": 1601,
"text": "python-modules"
},
{
"code": null,
"e": 1623,
"s": 1616,
"text": "Python"
},
{
"code": null,
"e": 1721,
"s": 1623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1739,
"s": 1721,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1781,
"s": 1739,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1803,
"s": 1781,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1829,
"s": 1803,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1861,
"s": 1829,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1890,
"s": 1861,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1917,
"s": 1890,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1938,
"s": 1917,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1961,
"s": 1938,
"text": "Introduction To PYTHON"
}
] |
Program for Decimal to Octal Conversion
|
11 Jul, 2022
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent octal number. i.e convert the number with base value 10 to base value 8. The base value of a number system determines the number of digits used to represent a numeric value. For example, the binary number system uses two digits 0 and 1, the octal number system uses 8 digits from 0-7 and the decimal number system uses 10 digits 0-9 to represent any numeric value.
Examples:
Input : 16
Output: 20
Input : 10
Output: 12
Input : 33
Output: 41
Store the remainder when the number is divided by 8 in an array.Divide the number by 8 nowRepeat the above two steps until the number is not equal to 0.Print the array in reverse order now.
Store the remainder when the number is divided by 8 in an array.
Divide the number by 8 now
Repeat the above two steps until the number is not equal to 0.
Print the array in reverse order now.
For Example:
If the given decimal number is 16.
Step 1: Remainder when 16 is divided by 8 is 0. Therefore, arr[0] = 0. Step 2: Divide 16 by 8. New number is 16/8 = 2. Step 3: Remainder, when 2 is divided by 8, is 2. Therefore, arr[1] = 2. Step 4: Divide 2 by 8. New number is 2/8 = 0. Step 5: Since number becomes = 0.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Stop repeating steps and print the array in reverse order. Therefore, the equivalent octal number is 20.
The below diagram shows an example of converting the decimal number 33 to an equivalent octal number.
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to convert a decimal// number to octal number #include <iostream>using namespace std; // function to convert decimal to octalvoid decToOctal(int n){ // array to store octal number int octalNum[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // printing octal number array in reverse order for (int j = i - 1; j >= 0; j--) cout << octalNum[j];} // Driver Codeint main(){ int n = 33; // Function Call decToOctal(n); return 0;}
// Java program to convert a decimal// number to octal numberimport java.io.*; class GFG { // Function to convert decimal to octal static void decToOctal(int n) { // array to store octal number int[] octalNum = new int[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // Printing octal number array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(octalNum[j]); } // Driver Code public static void main(String[] args) { int n = 33; // Function Call decToOctal(n); }} // Contributed by Pramod Kumar
# Python3 program to convert# a decimal number to# octal number # function to convert# decimal to octal def decToOctal(n): # array to store # octal number octalNum = [0] * 100 # counter for octal # number array i = 0 while (n != 0): # storing remainder # in octal array octalNum[i] = n % 8 n = int(n / 8) i += 1 # printing octal number # array in reverse order for j in range(i - 1, -1, -1): print(octalNum[j], end="") # Driver Coden = 33 # Function CalldecToOctal(n) # This code is contributed# by mits
// C# program to convert a decimal// number to octal numberusing System; class GFG { // Function to convert decimal to octal static void decToOctal(int n) { // array to store octal number int[] octalNum = new int[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // Printing octal number array in // reverse order for (int j = i - 1; j >= 0; j--) Console.Write(octalNum[j]); } // Driver Code public static void Main() { int n = 33; // Function Call decToOctal(n); }} // This code is contributed by nitin mittal.
<?php// PHP program to convert// a decimal number to// octal number // function to convert// decimal to octalfunction decToOctal($n){ // array to store // octal number $octalNum; // counter for octal // number array $i = 0; while ($n != 0) { // storing remainder // in octal array $octalNum[$i] = $n % 8; $n = (int)($n / 8); $i++; } // printing octal number // array in reverse order for ( $j = $i - 1; $j >= 0; $j--) echo $octalNum[$j];} // Driver Code$n = 33; // Function CalldecToOctal($n); // This code is contributed// by ajit?>
<script> // JavaScript program to convert a decimal// number to octal number // function to convert decimal to octalfunction decToOctal(n){ // array to store octal number let octalNum = new Array(100); // counter for octal number array let i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = Math.floor(n / 8); i++; } // printing octal number array in reverse order for (let j = i - 1; j >= 0; j--) document.write(octalNum[j]);} // Driver Code let n = 33; // Function Call decToOctal(n); // This code is contributed by Surbhi Tyagi </script>
41
Space Complexity: O(N) since creating array to store octal numbers
This problem can also be solved without using an array using the following algorithm:
Initialize octal num to 0 and countVal to 1 and the decimal number as n
Find the remainder when decimal number divided by 8
Update octal number by octalNum + (remainder * countval)
Increase countval by countval*10
Divide decimal number by 8
Repeat from the second step until the decimal number is zero
Below is the implementation of the above idea:
C++
C
Java
Python3
C#
Javascript
// C++ program to convert decimal// number to octal number#include <iostream>using namespace std; // function to calculate the octal value of the given// decimal numbervoid decimaltoOctal(int deciNum){ // initializations int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } cout << octalNum << endl;} // Driver Codeint main(){ int n = 33; // Function Call decimaltoOctal(n); return 0;}
// C program to convert decimal// number to octal number#include <stdio.h> // function to calculate the octal value of the given// decimal numbervoid decimaltoOctal(int deciNum){ int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } printf("%d", octalNum);} // Driver Codeint main(){ int n = 33; // Function Call decimaltoOctal(n); return 0;}
// JAVA program to convert decimal// number to octal number import java.io.*; class GFG { // function to calculate the octal value of the given // decimal number static void octaltodecimal(int deciNum) { int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } System.out.println(octalNum); } // Driver Code public static void main(String[] args) { int n = 33; // Function Call octaltodecimal(n); }}
# Python3 program to convert decimal# number to octal number # function to calculate the octal value of the given# decimal number def decimaltoOctal(deciNum): # initializations octalNum = 0 countval = 1 dNo = deciNum while (deciNum != 0): # decimals remainder is calculated remainder = deciNum % 8 # storing the octalvalue octalNum += remainder * countval # storing exponential value countval = countval * 10 deciNum //= 8 print(octalNum) # Driver Codeif __name__ == '__main__': n = 33 # Function Call decimaltoOctal(n) # This code is contributed by pratham76
// C# program to convert decimal// number to octal numberusing System;class GFG { // function to calculate // the octal value of the given // decimal number static void octaltodecimal(int deciNum) { int octalNum = 0, countval = 1; while (deciNum != 0) { // decimals remainder is // calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } Console.Write(octalNum); } // Driver Code public static void Main(string[] args) { int n = 33; // Function Call octaltodecimal(n); }} // This code is contributed by rutvik_56
<script> // Javascript program to convert decimal// number to octal number // function to calculate the octal value of the given// decimal numberfunction decimaltoOctal(deciNum){ // initializations let octalNum = 0, countval = 1; let dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated let remainder = Math.floor(deciNum % 8); // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum = Math.floor(deciNum/8); } document.write(octalNum + "<br>");} // Driver Code let n = 33; // Function Call decimaltoOctal(n); //This code is contributed by Mayank Tyagi </script>
41
Time Complexity: O(log N)
Auxiliary Space: O(1)
Using a predefined function
Java
Python3
C#
Javascript
C++
// JAVA program to convert decimal// number to octal numberimport java.io.*; class GFG { public static void decToOct(int n) { System.out.println(Integer.toOctalString(n)); } public static void main(String[] args) { int n = 33; decToOct(n); }}
# Python program to convert decimal# number to octal number def decToOct(n): print(oct(n)); if __name__ == '__main__': n = 33; decToOct(n); # This code is contributed by Amit Katiyar
// C# program to convert decimal// number to octal numberusing System; public class GFG{ public static void decToOct(int n) { Console.WriteLine(Convert.ToString(n, 8)); } public static void Main(String[] args) { int n = 33; decToOct(n); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to convert decimal// number to octal numberfunction decToOct(n){ document.write(n.toString(8));} var n = 33;decToOct(n); // This code contributed by Princi Singh </script>
#include <bits/stdc++.h>using namespace std; string intToOctal(int n){ stringstream st; st << oct << n; return st.str();} int main(){ int n = 43; cout << intToOctal(n); return 0;}
41
This article is contributed by Saurabh Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
Mithun Kumar
sumitava77
rutvik_56
pratham76
surbhityagi15
le0
mayanktyagi1709
princi singh
29AjayKumar
amit143katiyar
saurabhsharma29520
polymatir3j
base-conversion
Computer Organization & Architecture
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 532,
"s": 52,
"text": "Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent octal number. i.e convert the number with base value 10 to base value 8. The base value of a number system determines the number of digits used to represent a numeric value. For example, the binary number system uses two digits 0 and 1, the octal number system uses 8 digits from 0-7 and the decimal number system uses 10 digits 0-9 to represent any numeric value."
},
{
"code": null,
"e": 543,
"s": 532,
"text": "Examples: "
},
{
"code": null,
"e": 611,
"s": 543,
"text": "Input : 16\nOutput: 20\n\nInput : 10\nOutput: 12\n\nInput : 33\nOutput: 41"
},
{
"code": null,
"e": 801,
"s": 611,
"text": "Store the remainder when the number is divided by 8 in an array.Divide the number by 8 nowRepeat the above two steps until the number is not equal to 0.Print the array in reverse order now."
},
{
"code": null,
"e": 866,
"s": 801,
"text": "Store the remainder when the number is divided by 8 in an array."
},
{
"code": null,
"e": 893,
"s": 866,
"text": "Divide the number by 8 now"
},
{
"code": null,
"e": 956,
"s": 893,
"text": "Repeat the above two steps until the number is not equal to 0."
},
{
"code": null,
"e": 994,
"s": 956,
"text": "Print the array in reverse order now."
},
{
"code": null,
"e": 1008,
"s": 994,
"text": "For Example: "
},
{
"code": null,
"e": 1044,
"s": 1008,
"text": "If the given decimal number is 16. "
},
{
"code": null,
"e": 1316,
"s": 1044,
"text": "Step 1: Remainder when 16 is divided by 8 is 0. Therefore, arr[0] = 0. Step 2: Divide 16 by 8. New number is 16/8 = 2. Step 3: Remainder, when 2 is divided by 8, is 2. Therefore, arr[1] = 2. Step 4: Divide 2 by 8. New number is 2/8 = 0. Step 5: Since number becomes = 0. "
},
{
"code": null,
"e": 1325,
"s": 1316,
"text": "Chapters"
},
{
"code": null,
"e": 1352,
"s": 1325,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1402,
"s": 1352,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1425,
"s": 1402,
"text": "captions off, selected"
},
{
"code": null,
"e": 1433,
"s": 1425,
"text": "English"
},
{
"code": null,
"e": 1451,
"s": 1433,
"text": "default, selected"
},
{
"code": null,
"e": 1475,
"s": 1451,
"text": "This is a modal window."
},
{
"code": null,
"e": 1544,
"s": 1475,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1566,
"s": 1544,
"text": "End of dialog window."
},
{
"code": null,
"e": 1671,
"s": 1566,
"text": "Stop repeating steps and print the array in reverse order. Therefore, the equivalent octal number is 20."
},
{
"code": null,
"e": 1775,
"s": 1671,
"text": "The below diagram shows an example of converting the decimal number 33 to an equivalent octal number. "
},
{
"code": null,
"e": 1824,
"s": 1775,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 1828,
"s": 1824,
"text": "C++"
},
{
"code": null,
"e": 1833,
"s": 1828,
"text": "Java"
},
{
"code": null,
"e": 1841,
"s": 1833,
"text": "Python3"
},
{
"code": null,
"e": 1844,
"s": 1841,
"text": "C#"
},
{
"code": null,
"e": 1848,
"s": 1844,
"text": "PHP"
},
{
"code": null,
"e": 1859,
"s": 1848,
"text": "Javascript"
},
{
"code": "// C++ program to convert a decimal// number to octal number #include <iostream>using namespace std; // function to convert decimal to octalvoid decToOctal(int n){ // array to store octal number int octalNum[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // printing octal number array in reverse order for (int j = i - 1; j >= 0; j--) cout << octalNum[j];} // Driver Codeint main(){ int n = 33; // Function Call decToOctal(n); return 0;}",
"e": 2471,
"s": 1859,
"text": null
},
{
"code": "// Java program to convert a decimal// number to octal numberimport java.io.*; class GFG { // Function to convert decimal to octal static void decToOctal(int n) { // array to store octal number int[] octalNum = new int[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // Printing octal number array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(octalNum[j]); } // Driver Code public static void main(String[] args) { int n = 33; // Function Call decToOctal(n); }} // Contributed by Pramod Kumar",
"e": 3241,
"s": 2471,
"text": null
},
{
"code": "# Python3 program to convert# a decimal number to# octal number # function to convert# decimal to octal def decToOctal(n): # array to store # octal number octalNum = [0] * 100 # counter for octal # number array i = 0 while (n != 0): # storing remainder # in octal array octalNum[i] = n % 8 n = int(n / 8) i += 1 # printing octal number # array in reverse order for j in range(i - 1, -1, -1): print(octalNum[j], end=\"\") # Driver Coden = 33 # Function CalldecToOctal(n) # This code is contributed# by mits",
"e": 3823,
"s": 3241,
"text": null
},
{
"code": "// C# program to convert a decimal// number to octal numberusing System; class GFG { // Function to convert decimal to octal static void decToOctal(int n) { // array to store octal number int[] octalNum = new int[100]; // counter for octal number array int i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // Printing octal number array in // reverse order for (int j = i - 1; j >= 0; j--) Console.Write(octalNum[j]); } // Driver Code public static void Main() { int n = 33; // Function Call decToOctal(n); }} // This code is contributed by nitin mittal.",
"e": 4598,
"s": 3823,
"text": null
},
{
"code": "<?php// PHP program to convert// a decimal number to// octal number // function to convert// decimal to octalfunction decToOctal($n){ // array to store // octal number $octalNum; // counter for octal // number array $i = 0; while ($n != 0) { // storing remainder // in octal array $octalNum[$i] = $n % 8; $n = (int)($n / 8); $i++; } // printing octal number // array in reverse order for ( $j = $i - 1; $j >= 0; $j--) echo $octalNum[$j];} // Driver Code$n = 33; // Function CalldecToOctal($n); // This code is contributed// by ajit?>",
"e": 5218,
"s": 4598,
"text": null
},
{
"code": "<script> // JavaScript program to convert a decimal// number to octal number // function to convert decimal to octalfunction decToOctal(n){ // array to store octal number let octalNum = new Array(100); // counter for octal number array let i = 0; while (n != 0) { // storing remainder in octal array octalNum[i] = n % 8; n = Math.floor(n / 8); i++; } // printing octal number array in reverse order for (let j = i - 1; j >= 0; j--) document.write(octalNum[j]);} // Driver Code let n = 33; // Function Call decToOctal(n); // This code is contributed by Surbhi Tyagi </script>",
"e": 5875,
"s": 5218,
"text": null
},
{
"code": null,
"e": 5878,
"s": 5875,
"text": "41"
},
{
"code": null,
"e": 5945,
"s": 5878,
"text": "Space Complexity: O(N) since creating array to store octal numbers"
},
{
"code": null,
"e": 6032,
"s": 5945,
"text": "This problem can also be solved without using an array using the following algorithm:"
},
{
"code": null,
"e": 6104,
"s": 6032,
"text": "Initialize octal num to 0 and countVal to 1 and the decimal number as n"
},
{
"code": null,
"e": 6156,
"s": 6104,
"text": "Find the remainder when decimal number divided by 8"
},
{
"code": null,
"e": 6213,
"s": 6156,
"text": "Update octal number by octalNum + (remainder * countval)"
},
{
"code": null,
"e": 6246,
"s": 6213,
"text": "Increase countval by countval*10"
},
{
"code": null,
"e": 6273,
"s": 6246,
"text": "Divide decimal number by 8"
},
{
"code": null,
"e": 6334,
"s": 6273,
"text": "Repeat from the second step until the decimal number is zero"
},
{
"code": null,
"e": 6381,
"s": 6334,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 6385,
"s": 6381,
"text": "C++"
},
{
"code": null,
"e": 6387,
"s": 6385,
"text": "C"
},
{
"code": null,
"e": 6392,
"s": 6387,
"text": "Java"
},
{
"code": null,
"e": 6400,
"s": 6392,
"text": "Python3"
},
{
"code": null,
"e": 6403,
"s": 6400,
"text": "C#"
},
{
"code": null,
"e": 6414,
"s": 6403,
"text": "Javascript"
},
{
"code": "// C++ program to convert decimal// number to octal number#include <iostream>using namespace std; // function to calculate the octal value of the given// decimal numbervoid decimaltoOctal(int deciNum){ // initializations int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } cout << octalNum << endl;} // Driver Codeint main(){ int n = 33; // Function Call decimaltoOctal(n); return 0;}",
"e": 7102,
"s": 6414,
"text": null
},
{
"code": "// C program to convert decimal// number to octal number#include <stdio.h> // function to calculate the octal value of the given// decimal numbervoid decimaltoOctal(int deciNum){ int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } printf(\"%d\", octalNum);} // Driver Codeint main(){ int n = 33; // Function Call decimaltoOctal(n); return 0;}",
"e": 7742,
"s": 7102,
"text": null
},
{
"code": "// JAVA program to convert decimal// number to octal number import java.io.*; class GFG { // function to calculate the octal value of the given // decimal number static void octaltodecimal(int deciNum) { int octalNum = 0, countval = 1; int dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } System.out.println(octalNum); } // Driver Code public static void main(String[] args) { int n = 33; // Function Call octaltodecimal(n); }}",
"e": 8520,
"s": 7742,
"text": null
},
{
"code": "# Python3 program to convert decimal# number to octal number # function to calculate the octal value of the given# decimal number def decimaltoOctal(deciNum): # initializations octalNum = 0 countval = 1 dNo = deciNum while (deciNum != 0): # decimals remainder is calculated remainder = deciNum % 8 # storing the octalvalue octalNum += remainder * countval # storing exponential value countval = countval * 10 deciNum //= 8 print(octalNum) # Driver Codeif __name__ == '__main__': n = 33 # Function Call decimaltoOctal(n) # This code is contributed by pratham76",
"e": 9166,
"s": 8520,
"text": null
},
{
"code": "// C# program to convert decimal// number to octal numberusing System;class GFG { // function to calculate // the octal value of the given // decimal number static void octaltodecimal(int deciNum) { int octalNum = 0, countval = 1; while (deciNum != 0) { // decimals remainder is // calculated int remainder = deciNum % 8; // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum /= 8; } Console.Write(octalNum); } // Driver Code public static void Main(string[] args) { int n = 33; // Function Call octaltodecimal(n); }} // This code is contributed by rutvik_56",
"e": 9967,
"s": 9166,
"text": null
},
{
"code": "<script> // Javascript program to convert decimal// number to octal number // function to calculate the octal value of the given// decimal numberfunction decimaltoOctal(deciNum){ // initializations let octalNum = 0, countval = 1; let dNo = deciNum; while (deciNum != 0) { // decimals remainder is calculated let remainder = Math.floor(deciNum % 8); // storing the octalvalue octalNum += remainder * countval; // storing exponential value countval = countval * 10; deciNum = Math.floor(deciNum/8); } document.write(octalNum + \"<br>\");} // Driver Code let n = 33; // Function Call decimaltoOctal(n); //This code is contributed by Mayank Tyagi </script>",
"e": 10700,
"s": 9967,
"text": null
},
{
"code": null,
"e": 10703,
"s": 10700,
"text": "41"
},
{
"code": null,
"e": 10729,
"s": 10703,
"text": "Time Complexity: O(log N)"
},
{
"code": null,
"e": 10751,
"s": 10729,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10779,
"s": 10751,
"text": "Using a predefined function"
},
{
"code": null,
"e": 10784,
"s": 10779,
"text": "Java"
},
{
"code": null,
"e": 10792,
"s": 10784,
"text": "Python3"
},
{
"code": null,
"e": 10795,
"s": 10792,
"text": "C#"
},
{
"code": null,
"e": 10806,
"s": 10795,
"text": "Javascript"
},
{
"code": null,
"e": 10810,
"s": 10806,
"text": "C++"
},
{
"code": "// JAVA program to convert decimal// number to octal numberimport java.io.*; class GFG { public static void decToOct(int n) { System.out.println(Integer.toOctalString(n)); } public static void main(String[] args) { int n = 33; decToOct(n); }}",
"e": 11093,
"s": 10810,
"text": null
},
{
"code": "# Python program to convert decimal# number to octal number def decToOct(n): print(oct(n)); if __name__ == '__main__': n = 33; decToOct(n); # This code is contributed by Amit Katiyar",
"e": 11290,
"s": 11093,
"text": null
},
{
"code": "// C# program to convert decimal// number to octal numberusing System; public class GFG{ public static void decToOct(int n) { Console.WriteLine(Convert.ToString(n, 8)); } public static void Main(String[] args) { int n = 33; decToOct(n); }} // This code is contributed by 29AjayKumar",
"e": 11613,
"s": 11290,
"text": null
},
{
"code": "<script> // Javascript program to convert decimal// number to octal numberfunction decToOct(n){ document.write(n.toString(8));} var n = 33;decToOct(n); // This code contributed by Princi Singh </script>",
"e": 11822,
"s": 11613,
"text": null
},
{
"code": "#include <bits/stdc++.h>using namespace std; string intToOctal(int n){ stringstream st; st << oct << n; return st.str();} int main(){ int n = 43; cout << intToOctal(n); return 0;}",
"e": 12020,
"s": 11822,
"text": null
},
{
"code": null,
"e": 12023,
"s": 12020,
"text": "41"
},
{
"code": null,
"e": 12323,
"s": 12025,
"text": "This article is contributed by Saurabh Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 12448,
"s": 12323,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 12461,
"s": 12448,
"text": "nitin mittal"
},
{
"code": null,
"e": 12467,
"s": 12461,
"text": "jit_t"
},
{
"code": null,
"e": 12480,
"s": 12467,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 12491,
"s": 12480,
"text": "sumitava77"
},
{
"code": null,
"e": 12501,
"s": 12491,
"text": "rutvik_56"
},
{
"code": null,
"e": 12511,
"s": 12501,
"text": "pratham76"
},
{
"code": null,
"e": 12525,
"s": 12511,
"text": "surbhityagi15"
},
{
"code": null,
"e": 12529,
"s": 12525,
"text": "le0"
},
{
"code": null,
"e": 12545,
"s": 12529,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 12558,
"s": 12545,
"text": "princi singh"
},
{
"code": null,
"e": 12570,
"s": 12558,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12585,
"s": 12570,
"text": "amit143katiyar"
},
{
"code": null,
"e": 12604,
"s": 12585,
"text": "saurabhsharma29520"
},
{
"code": null,
"e": 12616,
"s": 12604,
"text": "polymatir3j"
},
{
"code": null,
"e": 12632,
"s": 12616,
"text": "base-conversion"
},
{
"code": null,
"e": 12669,
"s": 12632,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 12704,
"s": 12669,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 12712,
"s": 12704,
"text": "GATE CS"
}
] |
C++ program to overload addition operator to add two complex numbers
|
Suppose we have a complex number class with real and imaginary part. We shall have to overload the addition (+) operator to add two complex number. We also have to define a function to return complex number in proper representation.
So, if the input is like c1 = 8 - 5i, c2 = 2 + 3i, then the output will be 10 - 2i.
To solve this, we will follow these steps −
Overload the + operator and take another complex number c2 as argument
Overload the + operator and take another complex number c2 as argument
define a complex number called ret whose real and imag are 0
define a complex number called ret whose real and imag are 0
real of ret := own real + real of c2
real of ret := own real + real of c2
imag of ret := own imag + imag of c2
imag of ret := own imag + imag of c2
return ret
return ret
Let us see the following implementation to get better understanding −
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(){
real = imag = 0;
}
Complex (int r, int i){
real = r;
imag = i;
}
string to_string(){
stringstream ss;
if(imag >= 0)
ss << "(" << real << " + " << imag << "i)";
else
ss << "(" << real << " - " << abs(imag) << "i)";
return ss.str();
}
Complex operator+(Complex c2){
Complex ret;
ret.real = real + c2.real;
ret.imag = imag + c2.imag;
return ret;
}
};
int main(){
Complex c1(8,-5), c2(2,3);
Complex res = c1 + c2;
cout << res.to_string();
}
c1(8,-5), c2(2,3)
(10 - 2i)
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Suppose we have a complex number class with real and imaginary part. We shall have to overload the addition (+) operator to add two complex number. We also have to define a function to return complex number in proper representation."
},
{
"code": null,
"e": 1379,
"s": 1295,
"text": "So, if the input is like c1 = 8 - 5i, c2 = 2 + 3i, then the output will be 10 - 2i."
},
{
"code": null,
"e": 1423,
"s": 1379,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1494,
"s": 1423,
"text": "Overload the + operator and take another complex number c2 as argument"
},
{
"code": null,
"e": 1565,
"s": 1494,
"text": "Overload the + operator and take another complex number c2 as argument"
},
{
"code": null,
"e": 1626,
"s": 1565,
"text": "define a complex number called ret whose real and imag are 0"
},
{
"code": null,
"e": 1687,
"s": 1626,
"text": "define a complex number called ret whose real and imag are 0"
},
{
"code": null,
"e": 1724,
"s": 1687,
"text": "real of ret := own real + real of c2"
},
{
"code": null,
"e": 1761,
"s": 1724,
"text": "real of ret := own real + real of c2"
},
{
"code": null,
"e": 1798,
"s": 1761,
"text": "imag of ret := own imag + imag of c2"
},
{
"code": null,
"e": 1835,
"s": 1798,
"text": "imag of ret := own imag + imag of c2"
},
{
"code": null,
"e": 1846,
"s": 1835,
"text": "return ret"
},
{
"code": null,
"e": 1857,
"s": 1846,
"text": "return ret"
},
{
"code": null,
"e": 1927,
"s": 1857,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2678,
"s": 1927,
"text": "#include <iostream>\n#include <sstream>\n#include <cmath>\nusing namespace std;\nclass Complex {\n private:\n int real, imag;\n public:\n Complex(){\n real = imag = 0; \n }\n Complex (int r, int i){\n real = r;\n imag = i;\n }\n string to_string(){\n stringstream ss;\n if(imag >= 0)\n ss << \"(\" << real << \" + \" << imag << \"i)\";\n else\n ss << \"(\" << real << \" - \" << abs(imag) << \"i)\";\n return ss.str();\n }\n Complex operator+(Complex c2){\n Complex ret;\n ret.real = real + c2.real;\n ret.imag = imag + c2.imag;\n return ret;\n }\n};\nint main(){\n Complex c1(8,-5), c2(2,3);\n Complex res = c1 + c2;\n cout << res.to_string();\n}\n"
},
{
"code": null,
"e": 2696,
"s": 2678,
"text": "c1(8,-5), c2(2,3)"
},
{
"code": null,
"e": 2706,
"s": 2696,
"text": "(10 - 2i)"
}
] |
How to Install Python Scrapy on Windows? - GeeksforGeeks
|
09 Sep, 2021
Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scraped the data then it decides whether to:
Keep the data.
Drop the data or items.
stop and store the processed data items.
In this article, we will look into the process of installing the Scrapy module on Windows.
The only thing that you need for installing the Scrapy module on Windows are:
Python
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, you can use the below command:
conda install scrapy
Type y for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Users who prefer to use pip can use the below command to install the Scrapy package on Windows:
pip install scrapy
You will get a similar message once the installation is complete:
To verify if Scrapy has been successfully installed in your system run the below code in a python IDE of your choice:
Python3
import scrapyscrapy.__version__
If successfully installed you will get the following output.
Blogathon-2021
how-to-install
Picked
Python-Scrapy
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Numpy on MacOS?
Dart - Null Aware Operators
Format Dates in Flutter
How to Install Tkinter in Windows?
Designing algorithm to solve Ball Sort Puzzle
How to Install PIP on Windows ?
How to Install FFmpeg on Windows?
How to Use Terminal in Sublime Text Editor ?
Different Ways to Connect One Computer to Another Computer
How to Install Numpy on MacOS?
|
[
{
"code": null,
"e": 24421,
"s": 24393,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24575,
"s": 24421,
"text": "Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scraped the data then it decides whether to:"
},
{
"code": null,
"e": 24590,
"s": 24575,
"text": "Keep the data."
},
{
"code": null,
"e": 24614,
"s": 24590,
"text": "Drop the data or items."
},
{
"code": null,
"e": 24655,
"s": 24614,
"text": "stop and store the processed data items."
},
{
"code": null,
"e": 24746,
"s": 24655,
"text": "In this article, we will look into the process of installing the Scrapy module on Windows."
},
{
"code": null,
"e": 24824,
"s": 24746,
"text": "The only thing that you need for installing the Scrapy module on Windows are:"
},
{
"code": null,
"e": 24832,
"s": 24824,
"text": "Python "
},
{
"code": null,
"e": 24878,
"s": 24832,
"text": "PIP or Conda (depending upon user preference)"
},
{
"code": null,
"e": 24964,
"s": 24878,
"text": "If you want the installation to be done through conda, you can use the below command:"
},
{
"code": null,
"e": 24985,
"s": 24964,
"text": "conda install scrapy"
},
{
"code": null,
"e": 25015,
"s": 24985,
"text": "Type y for yes when prompted."
},
{
"code": null,
"e": 25080,
"s": 25015,
"text": "You will get a similar message once the installation is complete"
},
{
"code": null,
"e": 25153,
"s": 25080,
"text": "Make sure you follow the best practices for installation using conda as:"
},
{
"code": null,
"e": 25250,
"s": 25153,
"text": "Use an environment for installation rather than in the base environment using the below command:"
},
{
"code": null,
"e": 25295,
"s": 25250,
"text": "conda create -n my-env\nconda activate my-env"
},
{
"code": null,
"e": 25381,
"s": 25295,
"text": "Note: If your preferred method of installation is conda-forge, use the below command:"
},
{
"code": null,
"e": 25427,
"s": 25381,
"text": "conda config --env --add channels conda-forge"
},
{
"code": null,
"e": 25523,
"s": 25427,
"text": "Users who prefer to use pip can use the below command to install the Scrapy package on Windows:"
},
{
"code": null,
"e": 25542,
"s": 25523,
"text": "pip install scrapy"
},
{
"code": null,
"e": 25608,
"s": 25542,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 25726,
"s": 25608,
"text": "To verify if Scrapy has been successfully installed in your system run the below code in a python IDE of your choice:"
},
{
"code": null,
"e": 25734,
"s": 25726,
"text": "Python3"
},
{
"code": "import scrapyscrapy.__version__",
"e": 25766,
"s": 25734,
"text": null
},
{
"code": null,
"e": 25827,
"s": 25766,
"text": "If successfully installed you will get the following output."
},
{
"code": null,
"e": 25842,
"s": 25827,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 25857,
"s": 25842,
"text": "how-to-install"
},
{
"code": null,
"e": 25864,
"s": 25857,
"text": "Picked"
},
{
"code": null,
"e": 25878,
"s": 25864,
"text": "Python-Scrapy"
},
{
"code": null,
"e": 25888,
"s": 25878,
"text": "Blogathon"
},
{
"code": null,
"e": 25895,
"s": 25888,
"text": "How To"
},
{
"code": null,
"e": 25914,
"s": 25895,
"text": "Installation Guide"
},
{
"code": null,
"e": 26012,
"s": 25914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26021,
"s": 26012,
"text": "Comments"
},
{
"code": null,
"e": 26034,
"s": 26021,
"text": "Old Comments"
},
{
"code": null,
"e": 26065,
"s": 26034,
"text": "How to Install Numpy on MacOS?"
},
{
"code": null,
"e": 26093,
"s": 26065,
"text": "Dart - Null Aware Operators"
},
{
"code": null,
"e": 26117,
"s": 26093,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 26152,
"s": 26117,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 26198,
"s": 26152,
"text": "Designing algorithm to solve Ball Sort Puzzle"
},
{
"code": null,
"e": 26230,
"s": 26198,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26264,
"s": 26230,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26309,
"s": 26264,
"text": "How to Use Terminal in Sublime Text Editor ?"
},
{
"code": null,
"e": 26368,
"s": 26309,
"text": "Different Ways to Connect One Computer to Another Computer"
}
] |
Difference between pointer to an array and array of pointers - GeeksforGeeks
|
13 Jun, 2019
Pointer to an array:
Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array.
int a[3] = {3, 4, 5 };
int *ptr = a;
We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the array.Syntax:
data type (*var name)[size of array];
Declaration of the pointer to an array:
// pointer to an array of five numbers
int (* ptr)[5] = NULL;
The above declaration is the pointer to an array of five integers. We use parenthesis to pronounce pointer to an array. Since subscript has higher priority than indirection, it is crucial to encase the indirection operator and pointer name inside brackets.
Example:
// C program to demonstrate// pointer to an array. #include <stdio.h> int main(){ // Pointer to an array of five numbers int(*a)[5]; int b[5] = { 1, 2, 3, 4, 5 }; int i = 0; // Points to the whole array b a = &b; for (i = 0; i < 5; i++) printf("%d\n", *(*a + i)); return 0;}
1
2
3
4
5
Array of pointers:
“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values.
Example:
// C program to demonstrate// example of array of pointers. #include <stdio.h> const int SIZE = 3; void main(){ // creating an array int arr[] = { 1, 2, 3 }; // we can make an integer pointer array to // storing the address of array elements int i, *ptr[SIZE]; for (i = 0; i < SIZE; i++) { // assigning the address of integer. ptr[i] = &arr[i]; } // printing values using pointer for (i = 0; i < SIZE; i++) { printf("Value of arr[%d] = %d\n", i, *ptr[i]); }}
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3
Example: We can likewise make an array of pointers to the character to store a list of strings.
#include <stdio.h> const int size = 4; void main(){ // array of pointers to a character // to store a list of strings char* names[] = { "amit", "amar", "ankit", "akhil" }; int i = 0; for (i = 0; i < size; i++) { printf("%s\n", names[i]); }}
amit
amar
ankit
akhil
Arrays
Pointers
C Language
Difference Between
Arrays
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java
|
[
{
"code": null,
"e": 24388,
"s": 24360,
"text": "\n13 Jun, 2019"
},
{
"code": null,
"e": 24409,
"s": 24388,
"text": "Pointer to an array:"
},
{
"code": null,
"e": 24525,
"s": 24409,
"text": "Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array."
},
{
"code": null,
"e": 24569,
"s": 24525,
"text": " int a[3] = {3, 4, 5 }; \n int *ptr = a; \n"
},
{
"code": null,
"e": 24760,
"s": 24569,
"text": "We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the array.Syntax:"
},
{
"code": null,
"e": 24798,
"s": 24760,
"text": "data type (*var name)[size of array];"
},
{
"code": null,
"e": 24838,
"s": 24798,
"text": "Declaration of the pointer to an array:"
},
{
"code": null,
"e": 24906,
"s": 24838,
"text": "// pointer to an array of five numbers\n int (* ptr)[5] = NULL; "
},
{
"code": null,
"e": 25163,
"s": 24906,
"text": "The above declaration is the pointer to an array of five integers. We use parenthesis to pronounce pointer to an array. Since subscript has higher priority than indirection, it is crucial to encase the indirection operator and pointer name inside brackets."
},
{
"code": null,
"e": 25172,
"s": 25163,
"text": "Example:"
},
{
"code": "// C program to demonstrate// pointer to an array. #include <stdio.h> int main(){ // Pointer to an array of five numbers int(*a)[5]; int b[5] = { 1, 2, 3, 4, 5 }; int i = 0; // Points to the whole array b a = &b; for (i = 0; i < 5; i++) printf(\"%d\\n\", *(*a + i)); return 0;}",
"e": 25496,
"s": 25172,
"text": null
},
{
"code": null,
"e": 25507,
"s": 25496,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 25526,
"s": 25507,
"text": "Array of pointers:"
},
{
"code": null,
"e": 25627,
"s": 25526,
"text": "“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.Syntax:"
},
{
"code": null,
"e": 25654,
"s": 25627,
"text": "int *var_name[array_size];"
},
{
"code": null,
"e": 25691,
"s": 25654,
"text": "Declaration of an array of pointers:"
},
{
"code": null,
"e": 25705,
"s": 25691,
"text": " int *ptr[3];"
},
{
"code": null,
"e": 25863,
"s": 25705,
"text": "We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values."
},
{
"code": null,
"e": 25872,
"s": 25863,
"text": "Example:"
},
{
"code": "// C program to demonstrate// example of array of pointers. #include <stdio.h> const int SIZE = 3; void main(){ // creating an array int arr[] = { 1, 2, 3 }; // we can make an integer pointer array to // storing the address of array elements int i, *ptr[SIZE]; for (i = 0; i < SIZE; i++) { // assigning the address of integer. ptr[i] = &arr[i]; } // printing values using pointer for (i = 0; i < SIZE; i++) { printf(\"Value of arr[%d] = %d\\n\", i, *ptr[i]); }}",
"e": 26397,
"s": 25872,
"text": null
},
{
"code": null,
"e": 26458,
"s": 26397,
"text": "Value of arr[0] = 1\nValue of arr[1] = 2\nValue of arr[2] = 3\n"
},
{
"code": null,
"e": 26554,
"s": 26458,
"text": "Example: We can likewise make an array of pointers to the character to store a list of strings."
},
{
"code": "#include <stdio.h> const int size = 4; void main(){ // array of pointers to a character // to store a list of strings char* names[] = { \"amit\", \"amar\", \"ankit\", \"akhil\" }; int i = 0; for (i = 0; i < size; i++) { printf(\"%s\\n\", names[i]); }}",
"e": 26859,
"s": 26554,
"text": null
},
{
"code": null,
"e": 26882,
"s": 26859,
"text": "amit\namar\nankit\nakhil\n"
},
{
"code": null,
"e": 26889,
"s": 26882,
"text": "Arrays"
},
{
"code": null,
"e": 26898,
"s": 26889,
"text": "Pointers"
},
{
"code": null,
"e": 26909,
"s": 26898,
"text": "C Language"
},
{
"code": null,
"e": 26928,
"s": 26909,
"text": "Difference Between"
},
{
"code": null,
"e": 26935,
"s": 26928,
"text": "Arrays"
},
{
"code": null,
"e": 26944,
"s": 26935,
"text": "Pointers"
},
{
"code": null,
"e": 27042,
"s": 26944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27077,
"s": 27042,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27105,
"s": 27077,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27151,
"s": 27105,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27191,
"s": 27151,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27203,
"s": 27191,
"text": "fork() in C"
},
{
"code": null,
"e": 27234,
"s": 27203,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27274,
"s": 27234,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27306,
"s": 27274,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27367,
"s": 27306,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to Send Mail Spring Boot Example - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show how to send mail with Spring Boot rest service.
Technologies used :
Spring_Boot_1.5.9.RELEASE
Spring-Boot-Starter-Mail
Java 8
To send a mail from spring boot application, we should add the below dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Here I am going to implement a Simple Spring Boot Example to send a mail and also to send attachments through the mail.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorilspoint</groupId>
<artifactId>SpringBoot_Mail_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot_Mail_Example</name>
<description>Spring Boot Mail Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configure SMTP Properties in Spring Boot application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=Your-Mail@gmail.com
spring.mail.password=password (App-Password generated from google tool)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
Create Spring Rest Controller to implement mail sending logic :
SimpleMailController :
package com.onlinetutorilspoint;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SimpleMailController {
@Autowired
private JavaMailSender sender;
@RequestMapping("/sendMail")
public String sendMail() {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setTo("demo@gmail.com");
helper.setText("Greetings :)");
helper.setSubject("Mail From Spring Boot");
} catch (MessagingException e) {
e.printStackTrace();
return "Error while sending mail ..";
}
sender.send(message);
return "Mail Sent Success!";
}
}
package com.onlinetutorilspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Run the Application :
D:\> mvnw spring-boot:run
Or (Ubuntu)
$ mvn spring-boot:run
Now you can access the below endpoint URL for send Mail :
http://localhost:8080/sendMail
If everything went well, you should have to see the Mail Sent Success! Message on your browser. Then check your mail inbox to confirm.
We can also send the email with attachments like below. Add the below method to Controller and run the application.
@RequestMapping("/sendMailAtt")
public String sendMailAttachment() throws MessagingException {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
try {
helper.setTo("demo@gmail.com");
helper.setText("Greetings :)\n Please find the attached docuemnt for your reference.");
helper.setSubject("Mail From Spring Boot");
ClassPathResource file = new ClassPathResource("document.PNG");
helper.addAttachment("document.PNG", file);
} catch (MessagingException e) {
e.printStackTrace();
return "Error while sending mail ..";
}
sender.send(message);
return "Mail Sent Success!";
}
Use the MimeMessageHelper(MimeMessage mimeMessage, boolean multipart) to enable multipart mode.
Access the below endpoint URL to send mail with attachments:
http://localhost:8080/sendMailAt
Happy Learning 🙂
Simple Spring Boot Example
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot MVC Example Tutorials
Spring Boot RabbitMQ Message Publishing Example
External Apache ActiveMQ Spring Boot Example
Spring Boot Validation Login Form Example
SSL Spring Boot HTTPs Enabling Example
Spring Boot RabbitMQ Consumer Messages Example
Spring Boot How to change the Tomcat to Jetty Server
Sending Spring Boot Kafka JSON Message to Kafka Topic
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
Simple Spring Boot Example
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot MVC Example Tutorials
Spring Boot RabbitMQ Message Publishing Example
External Apache ActiveMQ Spring Boot Example
Spring Boot Validation Login Form Example
SSL Spring Boot HTTPs Enabling Example
Spring Boot RabbitMQ Consumer Messages Example
Spring Boot How to change the Tomcat to Jetty Server
Sending Spring Boot Kafka JSON Message to Kafka Topic
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
sunith
August 23, 2018 at 11:37 am - Reply
how can we send through our form
oumayma
August 24, 2018 at 2:42 pm - Reply
I have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail
please help me 🙁
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false
220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp
DEBUG SMTP: connected to host “smtp.gmail.com”, port: 587
EHLO DESKTOP-J3P2SU8
250-smtp.gmail.com at your service, [197.17.181.43]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
DEBUG SMTP: Found extension “SIZE”, arg “35882577”
DEBUG SMTP: Found extension “8BITMIME”, arg “”
DEBUG SMTP: Found extension “STARTTLS”, arg “”
DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP: Found extension “PIPELINING”, arg “”
DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
STARTTLS
220 2.0.0 Ready to start TLS
VuThuy
November 19, 2018 at 10:02 pm - Reply
Thanks you.
ghjghj
June 20, 2020 at 5:44 pm - Reply
kkkk
sunith
August 23, 2018 at 11:37 am - Reply
how can we send through our form
how can we send through our form
oumayma
August 24, 2018 at 2:42 pm - Reply
I have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail
please help me 🙁
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false
220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp
DEBUG SMTP: connected to host “smtp.gmail.com”, port: 587
EHLO DESKTOP-J3P2SU8
250-smtp.gmail.com at your service, [197.17.181.43]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
DEBUG SMTP: Found extension “SIZE”, arg “35882577”
DEBUG SMTP: Found extension “8BITMIME”, arg “”
DEBUG SMTP: Found extension “STARTTLS”, arg “”
DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP: Found extension “PIPELINING”, arg “”
DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
STARTTLS
220 2.0.0 Ready to start TLS
I have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail
please help me 🙁
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false
220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp
DEBUG SMTP: connected to host “smtp.gmail.com”, port: 587
EHLO DESKTOP-J3P2SU8
250-smtp.gmail.com at your service, [197.17.181.43]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
DEBUG SMTP: Found extension “SIZE”, arg “35882577”
DEBUG SMTP: Found extension “8BITMIME”, arg “”
DEBUG SMTP: Found extension “STARTTLS”, arg “”
DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP: Found extension “PIPELINING”, arg “”
DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
STARTTLS
220 2.0.0 Ready to start TLS
VuThuy
November 19, 2018 at 10:02 pm - Reply
Thanks you.
Thanks you.
ghjghj
June 20, 2020 at 5:44 pm - Reply
kkkk
kkkk
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 483,
"s": 398,
"text": "In this tutorial, I am going to show how to send mail with Spring Boot rest service."
},
{
"code": null,
"e": 503,
"s": 483,
"text": "Technologies used :"
},
{
"code": null,
"e": 529,
"s": 503,
"text": "Spring_Boot_1.5.9.RELEASE"
},
{
"code": null,
"e": 554,
"s": 529,
"text": "Spring-Boot-Starter-Mail"
},
{
"code": null,
"e": 561,
"s": 554,
"text": "Java 8"
},
{
"code": null,
"e": 652,
"s": 561,
"text": "To send a mail from spring boot application, we should add the below dependency in pom.xml"
},
{
"code": null,
"e": 775,
"s": 652,
"text": "\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-mail</artifactId>\n</dependency>\n"
},
{
"code": null,
"e": 895,
"s": 775,
"text": "Here I am going to implement a Simple Spring Boot Example to send a mail and also to send attachments through the mail."
},
{
"code": null,
"e": 2224,
"s": 895,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n<modelVersion>4.0.0</modelVersion>\n\n<groupId>com.onlinetutorilspoint</groupId>\n<artifactId>SpringBoot_Mail_Example</artifactId>\n<version>0.0.1-SNAPSHOT</version>\n<packaging>jar</packaging>\n\n<name>SpringBoot_Mail_Example</name>\n<description>Spring Boot Mail Example</description>\n\n<parent>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-parent</artifactId>\n<version>1.5.9.RELEASE</version>\n<relativePath />\n</parent>\n\n<properties>\n<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n<java.version>1.8</java.version>\n</properties>\n\n<dependencies>\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-mail</artifactId>\n</dependency>\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n</dependencies>\n\n<build>\n<plugins>\n<plugin>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-maven-plugin</artifactId>\n</plugin>\n</plugins>\n</build>\n</project>\n"
},
{
"code": null,
"e": 2288,
"s": 2224,
"text": "Configure SMTP Properties in Spring Boot application.properties"
},
{
"code": null,
"e": 2761,
"s": 2288,
"text": "spring.mail.host=smtp.gmail.com\nspring.mail.port=587\nspring.mail.username=Your-Mail@gmail.com\nspring.mail.password=password (App-Password generated from google tool)\nspring.mail.properties.mail.smtp.starttls.enable=true\nspring.mail.properties.mail.smtp.starttls.required=true\nspring.mail.properties.mail.smtp.auth=true\nspring.mail.properties.mail.smtp.connectiontimeout=5000\nspring.mail.properties.mail.smtp.timeout=5000\nspring.mail.properties.mail.smtp.writetimeout=5000\n"
},
{
"code": null,
"e": 2825,
"s": 2761,
"text": "Create Spring Rest Controller to implement mail sending logic :"
},
{
"code": null,
"e": 2848,
"s": 2825,
"text": "SimpleMailController :"
},
{
"code": null,
"e": 3929,
"s": 2848,
"text": "package com.onlinetutorilspoint;\n\nimport javax.mail.MessagingException;\nimport javax.mail.internet.MimeMessage;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.mail.javamail.JavaMailSender;\nimport org.springframework.mail.javamail.MimeMessageHelper;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class SimpleMailController {\n @Autowired\n private JavaMailSender sender;\n\n @RequestMapping(\"/sendMail\")\n public String sendMail() {\n MimeMessage message = sender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message);\n\n try {\n helper.setTo(\"demo@gmail.com\");\n helper.setText(\"Greetings :)\");\n helper.setSubject(\"Mail From Spring Boot\");\n } catch (MessagingException e) {\n e.printStackTrace();\n return \"Error while sending mail ..\";\n }\n sender.send(message);\n return \"Mail Sent Success!\";\n }\n}\n"
},
{
"code": null,
"e": 4244,
"s": 3929,
"text": "package com.onlinetutorilspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n"
},
{
"code": null,
"e": 4266,
"s": 4244,
"text": "Run the Application :"
},
{
"code": null,
"e": 4328,
"s": 4266,
"text": "D:\\> mvnw spring-boot:run\n\nOr (Ubuntu)\n\n$ mvn spring-boot:run"
},
{
"code": null,
"e": 4386,
"s": 4328,
"text": "Now you can access the below endpoint URL for send Mail :"
},
{
"code": null,
"e": 4417,
"s": 4386,
"text": "http://localhost:8080/sendMail"
},
{
"code": null,
"e": 4552,
"s": 4417,
"text": "If everything went well, you should have to see the Mail Sent Success! Message on your browser. Then check your mail inbox to confirm."
},
{
"code": null,
"e": 4668,
"s": 4552,
"text": "We can also send the email with attachments like below. Add the below method to Controller and run the application."
},
{
"code": null,
"e": 5451,
"s": 4668,
"text": "@RequestMapping(\"/sendMailAtt\")\n public String sendMailAttachment() throws MessagingException {\n MimeMessage message = sender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message,true);\n try {\n helper.setTo(\"demo@gmail.com\");\n helper.setText(\"Greetings :)\\n Please find the attached docuemnt for your reference.\");\n helper.setSubject(\"Mail From Spring Boot\");\n ClassPathResource file = new ClassPathResource(\"document.PNG\");\n helper.addAttachment(\"document.PNG\", file);\n } catch (MessagingException e) {\n e.printStackTrace();\n return \"Error while sending mail ..\";\n }\n sender.send(message);\n return \"Mail Sent Success!\";\n }\n"
},
{
"code": null,
"e": 5547,
"s": 5451,
"text": "Use the MimeMessageHelper(MimeMessage mimeMessage, boolean multipart) to enable multipart mode."
},
{
"code": null,
"e": 5608,
"s": 5547,
"text": "Access the below endpoint URL to send mail with attachments:"
},
{
"code": null,
"e": 5641,
"s": 5608,
"text": "http://localhost:8080/sendMailAt"
},
{
"code": null,
"e": 5658,
"s": 5641,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 6329,
"s": 5658,
"text": "\nSimple Spring Boot Example\nSpring Boot Apache ActiveMq In Memory Example\nSpring Boot Environment Properties reading based on activeprofile\nMicroServices Spring Boot Eureka Server Example\nSpring Boot MVC Example Tutorials\nSpring Boot RabbitMQ Message Publishing Example\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot Validation Login Form Example\nSSL Spring Boot HTTPs Enabling Example\nSpring Boot RabbitMQ Consumer Messages Example\nSpring Boot How to change the Tomcat to Jetty Server\nSending Spring Boot Kafka JSON Message to Kafka Topic\nSpring Boot MongoDB + Spring Data Example\nSpring Boot JPA Integration Example\nSpring Boot Hibernate Integration Example\n"
},
{
"code": null,
"e": 6356,
"s": 6329,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 6468,
"s": 6402,
"text": "Spring Boot Environment Properties reading based on activeprofile"
},
{
"code": null,
"e": 6516,
"s": 6468,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 6550,
"s": 6516,
"text": "Spring Boot MVC Example Tutorials"
},
{
"code": null,
"e": 6598,
"s": 6550,
"text": "Spring Boot RabbitMQ Message Publishing Example"
},
{
"code": null,
"e": 6643,
"s": 6598,
"text": "External Apache ActiveMQ Spring Boot Example"
},
{
"code": null,
"e": 6685,
"s": 6643,
"text": "Spring Boot Validation Login Form Example"
},
{
"code": null,
"e": 6724,
"s": 6685,
"text": "SSL Spring Boot HTTPs Enabling Example"
},
{
"code": null,
"e": 6771,
"s": 6724,
"text": "Spring Boot RabbitMQ Consumer Messages Example"
},
{
"code": null,
"e": 6824,
"s": 6771,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 6878,
"s": 6824,
"text": "Sending Spring Boot Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 6920,
"s": 6878,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 6956,
"s": 6920,
"text": "Spring Boot JPA Integration Example"
},
{
"code": null,
"e": 6998,
"s": 6956,
"text": "Spring Boot Hibernate Integration Example"
},
{
"code": null,
"e": 8129,
"s": 6998,
"text": "\n\n\n\n\n\nsunith\nAugust 23, 2018 at 11:37 am - Reply \n\nhow can we send through our form\n\n\n\n\n\n\n\n\n\noumayma\nAugust 24, 2018 at 2:42 pm - Reply \n\nI have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail\nplease help me 🙁\nDEBUG SMTP: useEhlo true, useAuth true\nDEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false\n220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp\nDEBUG SMTP: connected to host “smtp.gmail.com”, port: 587\nEHLO DESKTOP-J3P2SU8\n250-smtp.gmail.com at your service, [197.17.181.43]\n250-SIZE 35882577\n250-8BITMIME\n250-STARTTLS\n250-ENHANCEDSTATUSCODES\n250-PIPELINING\n250 SMTPUTF8\nDEBUG SMTP: Found extension “SIZE”, arg “35882577”\nDEBUG SMTP: Found extension “8BITMIME”, arg “”\nDEBUG SMTP: Found extension “STARTTLS”, arg “”\nDEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”\nDEBUG SMTP: Found extension “PIPELINING”, arg “”\nDEBUG SMTP: Found extension “SMTPUTF8”, arg “”\nSTARTTLS\n220 2.0.0 Ready to start TLS\n\n\n\n\n\n\n\n\n\nVuThuy\nNovember 19, 2018 at 10:02 pm - Reply \n\nThanks you.\n\n\n\n\n\n\n\n\n\nghjghj\nJune 20, 2020 at 5:44 pm - Reply \n\nkkkk\n\n\n\n\n"
},
{
"code": null,
"e": 8216,
"s": 8129,
"text": "\n\n\n\n\nsunith\nAugust 23, 2018 at 11:37 am - Reply \n\nhow can we send through our form\n\n\n\n"
},
{
"code": null,
"e": 8249,
"s": 8216,
"text": "how can we send through our form"
},
{
"code": null,
"e": 9167,
"s": 8249,
"text": "\n\n\n\n\noumayma\nAugust 24, 2018 at 2:42 pm - Reply \n\nI have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail\nplease help me 🙁\nDEBUG SMTP: useEhlo true, useAuth true\nDEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false\n220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp\nDEBUG SMTP: connected to host “smtp.gmail.com”, port: 587\nEHLO DESKTOP-J3P2SU8\n250-smtp.gmail.com at your service, [197.17.181.43]\n250-SIZE 35882577\n250-8BITMIME\n250-STARTTLS\n250-ENHANCEDSTATUSCODES\n250-PIPELINING\n250 SMTPUTF8\nDEBUG SMTP: Found extension “SIZE”, arg “35882577”\nDEBUG SMTP: Found extension “8BITMIME”, arg “”\nDEBUG SMTP: Found extension “STARTTLS”, arg “”\nDEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”\nDEBUG SMTP: Found extension “PIPELINING”, arg “”\nDEBUG SMTP: Found extension “SMTPUTF8”, arg “”\nSTARTTLS\n220 2.0.0 Ready to start TLS\n\n\n\n"
},
{
"code": null,
"e": 9296,
"s": 9167,
"text": "I have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail\nplease help me 🙁"
},
{
"code": null,
"e": 9525,
"s": 9296,
"text": "DEBUG SMTP: useEhlo true, useAuth true\nDEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false\n220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp\nDEBUG SMTP: connected to host “smtp.gmail.com”, port: 587"
},
{
"code": null,
"e": 10031,
"s": 9525,
"text": "EHLO DESKTOP-J3P2SU8\n250-smtp.gmail.com at your service, [197.17.181.43]\n250-SIZE 35882577\n250-8BITMIME\n250-STARTTLS\n250-ENHANCEDSTATUSCODES\n250-PIPELINING\n250 SMTPUTF8\nDEBUG SMTP: Found extension “SIZE”, arg “35882577”\nDEBUG SMTP: Found extension “8BITMIME”, arg “”\nDEBUG SMTP: Found extension “STARTTLS”, arg “”\nDEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”\nDEBUG SMTP: Found extension “PIPELINING”, arg “”\nDEBUG SMTP: Found extension “SMTPUTF8”, arg “”\nSTARTTLS\n220 2.0.0 Ready to start TLS"
},
{
"code": null,
"e": 10099,
"s": 10031,
"text": "\n\n\n\n\nVuThuy\nNovember 19, 2018 at 10:02 pm - Reply \n\nThanks you.\n\n\n\n"
},
{
"code": null,
"e": 10111,
"s": 10099,
"text": "Thanks you."
},
{
"code": null,
"e": 10167,
"s": 10111,
"text": "\n\n\n\n\nghjghj\nJune 20, 2020 at 5:44 pm - Reply \n\nkkkk\n\n\n\n"
},
{
"code": null,
"e": 10172,
"s": 10167,
"text": "kkkk"
},
{
"code": null,
"e": 10178,
"s": 10176,
"text": "Δ"
},
{
"code": null,
"e": 10205,
"s": 10178,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 10232,
"s": 10205,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 10266,
"s": 10232,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 10307,
"s": 10266,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 10352,
"s": 10307,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 10390,
"s": 10352,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 10424,
"s": 10390,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 10455,
"s": 10424,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 10489,
"s": 10455,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 10522,
"s": 10489,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 10555,
"s": 10522,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 10595,
"s": 10555,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 10620,
"s": 10595,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 10651,
"s": 10620,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 10675,
"s": 10651,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 10721,
"s": 10675,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 10744,
"s": 10721,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 10771,
"s": 10744,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 10817,
"s": 10771,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 10857,
"s": 10817,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 10886,
"s": 10857,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 10920,
"s": 10886,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 10950,
"s": 10920,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 10986,
"s": 10950,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 11019,
"s": 10986,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 11052,
"s": 11019,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 11096,
"s": 11052,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 11130,
"s": 11096,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 11162,
"s": 11130,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 11190,
"s": 11162,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 11221,
"s": 11190,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 11262,
"s": 11221,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 11296,
"s": 11262,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 11321,
"s": 11296,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 11355,
"s": 11321,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 11391,
"s": 11355,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 11437,
"s": 11391,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 11488,
"s": 11437,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 11530,
"s": 11488,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 11561,
"s": 11530,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 11584,
"s": 11561,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 11614,
"s": 11584,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 11644,
"s": 11614,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 11693,
"s": 11644,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 11727,
"s": 11693,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 11760,
"s": 11727,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 11789,
"s": 11760,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 11821,
"s": 11789,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 11858,
"s": 11821,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 11887,
"s": 11858,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 11916,
"s": 11887,
"text": " Spring Boot – MockMvc JUnit"
}
] |
MongoDB - Insert Document
|
In this chapter, we will learn how to insert document in MongoDB collection.
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)
> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "tutorials point",
... url: "http://www.tutorialspoint.com",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>
Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it.
In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
You can also pass an array of documents into the insert() method as shown below:.
> db.createCollection("post")
> db.post.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
To insert the document you can use db.post.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.
If you need to insert only one document into a collection you can use this method.
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insertOne(document)
Following example creates a new collection named empDetails and inserts a document using the insertOne() method.
> db.createCollection("empDetails")
{ "ok" : 1 }
> db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>
You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents.
Following example inserts three different documents into the empDetails collection using the insertMany() method.
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5dd631f270fb13eec3963bed"),
ObjectId("5dd631f270fb13eec3963bee"),
ObjectId("5dd631f270fb13eec3963bef")
]
}
>
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2630,
"s": 2553,
"text": "In this chapter, we will learn how to insert document in MongoDB collection."
},
{
"code": null,
"e": 2723,
"s": 2630,
"text": "To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method."
},
{
"code": null,
"e": 2776,
"s": 2723,
"text": "The basic syntax of insert() command is as follows −"
},
{
"code": null,
"e": 2814,
"s": 2776,
"text": ">db.COLLECTION_NAME.insert(document)\n"
},
{
"code": null,
"e": 3130,
"s": 2814,
"text": "> db.users.insert({\n... _id : ObjectId(\"507f191e810c19729de860ea\"),\n... title: \"MongoDB Overview\",\n... description: \"MongoDB is no sql database\",\n... by: \"tutorials point\",\n... url: \"http://www.tutorialspoint.com\",\n... tags: ['mongodb', 'database', 'NoSQL'],\n... likes: 100\n... })\nWriteResult({ \"nInserted\" : 1 })\n>"
},
{
"code": null,
"e": 3327,
"s": 3130,
"text": "Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it."
},
{
"code": null,
"e": 3450,
"s": 3327,
"text": "In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document."
},
{
"code": null,
"e": 3562,
"s": 3450,
"text": "_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows −"
},
{
"code": null,
"e": 3657,
"s": 3562,
"text": "_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)\n"
},
{
"code": null,
"e": 3739,
"s": 3657,
"text": "You can also pass an array of documents into the insert() method as shown below:."
},
{
"code": null,
"e": 4498,
"s": 3739,
"text": "> db.createCollection(\"post\")\n> db.post.insert([\n\t{\n\t\ttitle: \"MongoDB Overview\",\n\t\tdescription: \"MongoDB is no SQL database\",\n\t\tby: \"tutorials point\",\n\t\turl: \"http://www.tutorialspoint.com\",\n\t\ttags: [\"mongodb\", \"database\", \"NoSQL\"],\n\t\tlikes: 100\n\t},\n\t{\n\ttitle: \"NoSQL Database\",\n\tdescription: \"NoSQL database doesn't have tables\",\n\tby: \"tutorials point\",\n\turl: \"http://www.tutorialspoint.com\",\n\ttags: [\"mongodb\", \"database\", \"NoSQL\"],\n\tlikes: 20,\n\tcomments: [\n\t\t{\n\t\t\tuser:\"user1\",\n\t\t\tmessage: \"My first comment\",\n\t\t\tdateCreated: new Date(2013,11,10,2,35),\n\t\t\tlike: 0\n\t\t}\n\t]\n}\n])\nBulkWriteResult({\n\t\"writeErrors\" : [ ],\n\t\"writeConcernErrors\" : [ ],\n\t\"nInserted\" : 2,\n\t\"nUpserted\" : 0,\n\t\"nMatched\" : 0,\n\t\"nModified\" : 0,\n\t\"nRemoved\" : 0,\n\t\"upserted\" : [ ]\n})\n>"
},
{
"code": null,
"e": 4766,
"s": 4498,
"text": "To insert the document you can use db.post.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method."
},
{
"code": null,
"e": 4849,
"s": 4766,
"text": "If you need to insert only one document into a collection you can use this method."
},
{
"code": null,
"e": 4902,
"s": 4849,
"text": "The basic syntax of insert() command is as follows −"
},
{
"code": null,
"e": 4942,
"s": 4902,
"text": ">db.COLLECTION_NAME.insertOne(document)"
},
{
"code": null,
"e": 5055,
"s": 4942,
"text": "Following example creates a new collection named empDetails and inserts a document using the insertOne() method."
},
{
"code": null,
"e": 5104,
"s": 5055,
"text": "> db.createCollection(\"empDetails\")\n{ \"ok\" : 1 }"
},
{
"code": null,
"e": 5364,
"s": 5104,
"text": "> db.empDetails.insertOne(\n\t{\n\t\tFirst_Name: \"Radhika\",\n\t\tLast_Name: \"Sharma\",\n\t\tDate_Of_Birth: \"1995-09-26\",\n\t\te_mail: \"radhika_sharma.123@gmail.com\",\n\t\tphone: \"9848022338\"\n\t})\n{\n\t\"acknowledged\" : true,\n\t\"insertedId\" : ObjectId(\"5dd62b4070fb13eec3963bea\")\n}\n>"
},
{
"code": null,
"e": 5484,
"s": 5364,
"text": "You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents."
},
{
"code": null,
"e": 5598,
"s": 5484,
"text": "Following example inserts three different documents into the empDetails collection using the insertMany() method."
},
{
"code": null,
"e": 6281,
"s": 5598,
"text": "> db.empDetails.insertMany(\n\t[\n\t\t{\n\t\t\tFirst_Name: \"Radhika\",\n\t\t\tLast_Name: \"Sharma\",\n\t\t\tDate_Of_Birth: \"1995-09-26\",\n\t\t\te_mail: \"radhika_sharma.123@gmail.com\",\n\t\t\tphone: \"9000012345\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Rachel\",\n\t\t\tLast_Name: \"Christopher\",\n\t\t\tDate_Of_Birth: \"1990-02-16\",\n\t\t\te_mail: \"Rachel_Christopher.123@gmail.com\",\n\t\t\tphone: \"9000054321\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Fathima\",\n\t\t\tLast_Name: \"Sheik\",\n\t\t\tDate_Of_Birth: \"1990-02-16\",\n\t\t\te_mail: \"Fathima_Sheik.123@gmail.com\",\n\t\t\tphone: \"9000054321\"\n\t\t}\n\t]\n)\n{\n\t\"acknowledged\" : true,\n\t\"insertedIds\" : [\n\t\tObjectId(\"5dd631f270fb13eec3963bed\"),\n\t\tObjectId(\"5dd631f270fb13eec3963bee\"),\n\t\tObjectId(\"5dd631f270fb13eec3963bef\")\n\t]\n}\n>"
},
{
"code": null,
"e": 6314,
"s": 6281,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6333,
"s": 6314,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6368,
"s": 6333,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6396,
"s": 6368,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6431,
"s": 6396,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6454,
"s": 6431,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6489,
"s": 6454,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6506,
"s": 6489,
"text": " University Code"
},
{
"code": null,
"e": 6539,
"s": 6506,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6558,
"s": 6539,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 6593,
"s": 6558,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6613,
"s": 6593,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6620,
"s": 6613,
"text": " Print"
},
{
"code": null,
"e": 6631,
"s": 6620,
"text": " Add Notes"
}
] |
The User-Agent — That Crazy String Underpinning a Bunch of Analytics | by Randy Au | Towards Data Science
|
Work in web analytics for any amount of time, even less than a week I’d bet, and you’re going to hear about this thing called the “User-Agent”. It’s this string that we get from users, and it’s supposed to tell us various things about them. If we’re supposed to be using this thing to count and analyze users somehow, we need to understand it some more.
Currently in 2019, the most important use for it is figuring out what device (desktop, phone, etc) a client is using for the purposes of sending the correct page design to the client. It’s not the only way someone can do device detection, but it forms a very important foundation. Even Javascript device detection libraries often just request and parse the User-Agent.
User-Agents also provides one of the data points for fingerprinting users without the use of cookies. It’s included with every HTTP request and can potentially be very long and unique to a user in certain uncommon situations.
But what IS this string all about, and why is it sorta crazy any of this works?
The User-Agent (UA) is a field in the HTTP header that the client “should” (in the technical RFC 2219 sense where they may be technical ramifications if it is not done), include the field with a request to a server. This is codified within both RFC 1945-HTTP/1.0 and the current RFC 7231-HTTP/1.1 specifications (see the images below for the specific sections). RFC 7540-HTTP/2 is concerned w/ the HTTP message itself and not the headers where UA lives, so 7231 applies there too.
Let’s take a look at how the UA was defined in the RFCs.
The TL;DR is as follows: User-agents are...
A field in the HTTP request header
That SHOULD be included in every request
Should be in US-ASCII (as with the whole header)
Consists of a series of “product tokens” — a product name string with an optional version number, separated by a “/”
Product tokens are separated from one another by a space.
Comments are allowed by enclosing them in parentheses
Product tokens should be ordered most important first
One product should not copy another product’s token to declare compatibility
No advertising, no overly fine-grained detail
Although it is not required, user agents should include this field with requests. — RFC 1945
RFC 1945 predates the RFC 2119 language of SHOULD, so it reads more casually. Still, the most important points are these:
Not required but UA should be included with requests
Used for statistical purposes, tracing protocol violations tailoring responses to user agent limitations
Field can contain multiple “product tokens” and comments
Product tokens are listed in order of significance for identifying the application
It’s interesting to note that, even in this RFC, it already warns of anomalies like some proxies will append data to the UA which makes interpretation ambiguous, and some clients don’t follow the product token syntax.
A product token is simply in the format of product/version where version is optional. Tokens are whitespace delimited, so products shouldn’t have whitespace. Historically, ISO 8859–1 (Latin-1) and RFC 2047 (Base64 and Quote-printable) encodings were allowed. Nowadays, the spec says to use US-ASCII and any octet > 127 is treated as “opaque data.”
So, in theory, you could shove emoji or a base64 essay into the UA, but all bets are off on how the server decides if and how to handle it.
Subsequent versions of the HTTP RFCs have more standardized language, but generally, things remain the same. It’s still product/version entries separated by spaces, with comments in parentheses. What’s notable is the addition of very specific prohibitions against putting non-essential, fine-grained information or advertising in the UA. Overly long UAs are specifically stated to potentially fingerprint users (we’ll get to this later).
It’s also specifically stated that it’s discouraged for products to use the product tokens of other products to declare compatibility. We’ll get into that next.
What’s interesting about all these additions is that they didn’t exist in RFC 2068 the original HTTP/1.1 spec from January 1997,or RFC 2616 dating from June 1999. In the intervening 5 years of exploding internet use, it seems they had seen some abuses that they wanted to stop.
While knowing what the RFCs say about User-Agent strings is useful to know the format that things take, it doesn’t tell you very much about how it is used in practice.
As stated quite amusingly here in a “History of the browser user-agent string”, the reality of UAs today is that practically everything pretends to be Mozilla first. This was because back in the ‘90s when browser features were rapidly changing, the Mozilla browser had certain features like frames that were initially unavailable in competing browsers, so web designers sent different versions of the page based on the User-Agent.
But as the other browsers caught to Mozilla in terms of features, web designers were slow (or didn’t bother) to update their serving rules to match. So browsers that could support advanced features were not served pages with such features. To get around this, the other browsers just declared themselves to be Mozilla to fetch the Mozilla version.
Soon, practically every mainstream browser just decided to declare they were Mozilla as the first product string, while adding the actual browser in a comment or a subsequent product string. This is most likely what prompted the latest RFCs to specifically say using another product’s string (i.e. Mozilla) is discouraged. Browsers still do it to this day, with no real signs of changing.
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36-- A Chrome User-AgentMozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0-- A Firefox User-AgentMozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362-- A Microsoft Edge User-AgentMozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko-- An Internet Explorer 11 User-Agent"Links (2.16; FreeBSD 12.0-RELEASE-p10 amd64; LLVM/Clang 6.0.1; text)"-- A Links2 User-Agent
If you’d like, you can browse the vast array of User Agents online with resources such as this one.
What you’ll also notice is that every browser is fairly idiosyncratic with the sequence and types of product tokens it has. With enough study you can fairly reliably know what device and browser a request is coming from. IE11 uses the comment Trident/7.0 to denote its render engine and “rv:11.0” to denote the IE version, Chrome (and Edge which switched to being chromium on the back end) are full product-version tokens, but will also claim Safari compatibility because they both use AppleWebKit. It’s a tangled web.
It varies: some are more well behaved than others. Some state the bot as the top level product, some also claim Mozilla compatibility, or claim to be on a mobile device. Some are libraries that provide a default User-Agent that a dev can override but forgot to.
W3C_Validator/1.3 http://validator.w3.org/services - W3c's validatorGooglebot/2.1 (+http://www.google.com/bot.html) - A GooglebotMozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) - A Googlebot, but AndroidMozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) - one of the BingbotsPython/3.6 aiohttp/3.5.4 - Python's AIOHTTP librarypython-requests/2.20.1 - Python's Request library
Robots and scripts are sooorta obvious, but you sometimes have to squint a little. They’re more likely to have URLs in the text (as part of a practice to allow people to identify and report misbehaving bots) but that’s no guarantee, you gotta parse it case by case.
For various reasons, whether for testing, compatibility, or privacy reasons, users may want to have their browser give a different User-Agent string than default. The RFCs specifically say that if a client sends a masqueraded UA, then it should be interpreted as the client intentionally wanting that version, even if it may not render correctly.
If a user agent masquerades as a different user agent, recipients can assume that the user intentionally desires to see responses tailored for that identified user agent, even if they might not work as well for the actual user agent being used. — RFC 7231, HTTP/1.1
Browsers often provide the functionality for users to spoof their UAs. That said, it’s extremely rare to encounter users who go through the trouble since the differences between browser functionality has largely become trivial from a user perspective.
One thing to remember about User-Agents is that it is a very old technology, and many of the things that it has been used for historically (such as basic analytics) have been given over to other technologies that can provide more detail and resolution.
This usage is the original intended purpose of the UA string, giving the server the ability to serve different versions of the web page based on what the client is capable of handling. Internet Explorer 6 was perhaps the most egregious example of where site designers needed to know the browser version because of how poorly it handled modern web standards.
Fun side note, IE6 was a HUGE problem in the late 2000s/early 2010s due to its horrible standards support requiring lots of custom hacks from developers but stubbornly high usage numbers. The pain spawned efforts such as these to kill it.
Back in the mid/early 2000s, UAs were an important tool in analyzing what users were using. Using Javascript to pull browser info was still in its infancy, so User-Agents were the most informative thing that you had. From this, you could see what percentage of your users were using IE6 versus Firefox (and whether you should stop using certain HTML features or not). You could also see how often the search engine crawlers visited, and whether you had actual human visitors or not. Primitive by modern standards, but better than nothing.
It’s considered good practice and manners for bots, web crawlers, and similar automated programs to identify to the server via the User-Agent string. Very often the UA will contain the string “bot” “crawler” “spider”, sometimes with a URL of the bot owner as a comment. But the specific implementation of the UA will vary wildly from bot to bot. This is because ultimately a human developer decides what “self-identification” means, there’s no standard format.
The basic robots.txt file is used to tell what web crawlers and other robots should or should not access on a given web server. Very often, it doesn’t make a distinction between different types of clients, but there’s actually a facility to specify which User-Agent string is allowed in certain places.
Obviously, this assumes that the robot 1) reads and follows the directives in the robots.txt file and 2) identifies itself properly in the User-Agent (and again follows the directives).
User-Agent strings can range from being very simple, to very long with many product tokens chained together. The most egregious ones would be browsers that had many sketchy toolbars installed, each toolbar would often append its own product token to the UA.
The longer the UA, the more likely it has strayed from the base default UA provided by the browser, and it becomes increasingly likely that the UA becomes unique to a specific installation. Working under this assumption, people could use UAs as a way to pseudo-identify a user across time and IP addresses. I’ve seen browsers with as many as 6 toolbars installed and that browser + IP combo was practically unique in the sea of requests, enough to track someone across the internet.
In practice, this method only really works on the tiny subset of people who have installed enough browser extensions or poorly spoofed their UA enough to stand out from the crowd of default strings. But even so, the UA still provides bits of entropy in a larger user fingerprinting framework that involves the use of Javascript and HTML5 methods.
I’ll have to get into device fingerprinting another day, it’s a huge topic. For now, if you’re interested you can take a look at this to get an idea of what is possible when you use the full range of tech possible, spanning request headers to Javascript, Flash, and HTML5 Canvas.
With many advanced browser features being detected directly via Javascript these days, this is probably the primary modern use of the UA string, figuring out what device/platform a client is running.
UAs found a new life in the late 2000s with the smartphone and tablet explosion. While UAs used to tell you what percent of your userbase was on IE, Firefox or Chrome on a Windows machine or Mac, we suddenly started seeing exciting new strings like iPad, iPhone, Android. Not everyone was using a desktop/laptop any more, but we could see what they were using and adapt!
These new devices had different physical screen sizes and physical capabilities. It wasn’t just “oh this browser has no Javascript/HTML5/CSS support” any more. This information is highly relevant to designers, especially on older early/mid-2010 devices that did not have full-HD 1080p or higher screen resolutions. (The iPhone 4S from 2011 had a 960×640 pixel screen.) Sites designed for mobile devices needed to have different UIs that work better for touch screens, and be smaller to work with 2G, 3G wireless networks.
But again, because the User-Agent is completely free-form, it could be potentially different for every permutation of manufacturer/device/OS/browser in very unique ways. How are developers supposed to handle this situation?
Through painstaking analysis and building a large database of strings, of course!
Luckily! There are open source projects that are tackling this sort of problem (as well as paid API services that do User-Agent string analysis). One is the UA-parser project, which at its core is a giant list of over 1100 regex definitions that search for unique patterns in the UA and associates it with manufacturers and specific devices. It’s a herculean effort maintained by many people.
github.com
Running (up to) a thousand regex searches on a single string is obviously very resource-intensive, but this is the only way to make sure to identify a UA string to the fullest extent possible short of reading it manually.
In practice, you can speed up things massively with hashing and caching by relying on the fact that most users will have the same general default setup, so you’d only have to run regex on novel strings. This works because UA strings have a really dense cluster of exactly-matching values, and then a massively long-tail of esoteric values.
RFCs aren’t strongly enforced in any way, so it’s entirely possible to encounter non-conforming User-Agent strings. I’ve personally seen strings where nonsense characters like newlines (\n) and ASCII nulls (\0) have been put into the string. Unicode is also technically allowed (in that systems treat is as opaque bytes) but is generally unexpected and uncommon. Most UA handlers still assume that UAs are US-ASCII (as specified in the latest RFCs)
Usually, this stuff is from someone writing a robot and they are unfamiliar with the RFCs. Or they’re trying to be jerks and attempting to break systems. Either way, when you process UA strings at scale, your code will break a surprising amount due to malformed strings, so be prepared to write exception handlers to catch bad strings.
User-Agents are ubiquitous, so many people know just a tiny bit about them. The problem comes from when those people try to interpret them and come to bad conclusions.
People sometimes think User-Agents somehow provide them with counts of users. Often this is thinking from a mix of outdated thinking from a decade ago when people often only had 1 internet-connected computer, or they’ve heard about browser fingerprinting but aren’t aware of how many data points it takes to fingerprint a browser.
Obviously, this isn’t true today. Most users these days use multiple devices/browsers throughout the day and fingerprint methods are super complex. Counts of unique UAs do give a rough sense of the number of unique types of browsers that have made requests. But even when combined with the IP address, many humans can be using multiple devices that all use the exact same UA and sit behind a NAT and share an IP.
I’ve personally had to use UAs to put very rough bounds on the minimum number of browsers used to view a site, with the raw hit count being the upper limit. This was because we literally had no other data available. But I had to be very very clear about what we were measuring.
When people hear that UAs can be spoofed easily, they often worry that they’re being lied to and their metrics are going to be off. They often worry so much they overthink things and reach for more technically difficult solutions. I often tell people not to worry about spoofing.
The primary reason is that the vast majority of users have no motivation to bother messing with their UA string. They just want to use the internet. The only people who want to manipulate their UA are usually a microscopic number of users writing bots/crawlers of some sort. Then it breaks down into a few major cases:
The UA is by a human and doing human-scale traffic. Out of hundreds, thousands, possibly millions of humans using your site every day, they’re ultimately insignificant because they represent such a fractional percent of traffic.The UA a small volume robot — these are the small student scraper projects, the random programmer trying stuff out. So long as they’re generally well behaved and low volume, they won’t skew your metrics much so you can ignore it like the above.It’s a significantly spammy robot — You’ll need to account for this one case somehow. Often these will hammer from small set of IPs that are often a not used by end users (like an AWS IP block or a datacenter), you can usually filter those out based on a heuristics. There are often signs of problems (like your systems overloading like it’s a DDoS attack) when you’re facing these sorts of bots.
The UA is by a human and doing human-scale traffic. Out of hundreds, thousands, possibly millions of humans using your site every day, they’re ultimately insignificant because they represent such a fractional percent of traffic.
The UA a small volume robot — these are the small student scraper projects, the random programmer trying stuff out. So long as they’re generally well behaved and low volume, they won’t skew your metrics much so you can ignore it like the above.
It’s a significantly spammy robot — You’ll need to account for this one case somehow. Often these will hammer from small set of IPs that are often a not used by end users (like an AWS IP block or a datacenter), you can usually filter those out based on a heuristics. There are often signs of problems (like your systems overloading like it’s a DDoS attack) when you’re facing these sorts of bots.
It’s pretty rare to have to worry about spoofing unless you’re running something that robot-makers have an incentive to abuse (and UA is not likely to be the solution if that’s your problem). I suppose there are some edge cases: like if you get practically no traffic, so the bots will dominate, but you also have little reason to do a lot of analytics at that point.
Sooooooorta. In some very specific instances, you can catch a UA in a lie. But don’t expect it to be a regular thing.
The easiest case is when someone makes an error in spoofing their UA string. Their UA stands out like a sore thumb because no one else uses it. It could be something as simple as having an extra space or punctuation mark.
Similarly, sometimes spoofers don’t understand the User-Agent string enough and put together impossible combinations of product strings. They’ll stand out for being hyper-unique too.
Another somewhat common case is when you have access to the browser’s data via JavaScript. If you see an iPhone have a screen size that is massively different from the physical pixel dimensions of the phone itself, it’s probably lying about being a phone.
After these limited methods, the whole idea starts wandering into the realm of bot and fraud detection tech, which is a bit out of scope for here.
|
[
{
"code": null,
"e": 400,
"s": 46,
"text": "Work in web analytics for any amount of time, even less than a week I’d bet, and you’re going to hear about this thing called the “User-Agent”. It’s this string that we get from users, and it’s supposed to tell us various things about them. If we’re supposed to be using this thing to count and analyze users somehow, we need to understand it some more."
},
{
"code": null,
"e": 769,
"s": 400,
"text": "Currently in 2019, the most important use for it is figuring out what device (desktop, phone, etc) a client is using for the purposes of sending the correct page design to the client. It’s not the only way someone can do device detection, but it forms a very important foundation. Even Javascript device detection libraries often just request and parse the User-Agent."
},
{
"code": null,
"e": 995,
"s": 769,
"text": "User-Agents also provides one of the data points for fingerprinting users without the use of cookies. It’s included with every HTTP request and can potentially be very long and unique to a user in certain uncommon situations."
},
{
"code": null,
"e": 1075,
"s": 995,
"text": "But what IS this string all about, and why is it sorta crazy any of this works?"
},
{
"code": null,
"e": 1556,
"s": 1075,
"text": "The User-Agent (UA) is a field in the HTTP header that the client “should” (in the technical RFC 2219 sense where they may be technical ramifications if it is not done), include the field with a request to a server. This is codified within both RFC 1945-HTTP/1.0 and the current RFC 7231-HTTP/1.1 specifications (see the images below for the specific sections). RFC 7540-HTTP/2 is concerned w/ the HTTP message itself and not the headers where UA lives, so 7231 applies there too."
},
{
"code": null,
"e": 1613,
"s": 1556,
"text": "Let’s take a look at how the UA was defined in the RFCs."
},
{
"code": null,
"e": 1657,
"s": 1613,
"text": "The TL;DR is as follows: User-agents are..."
},
{
"code": null,
"e": 1692,
"s": 1657,
"text": "A field in the HTTP request header"
},
{
"code": null,
"e": 1733,
"s": 1692,
"text": "That SHOULD be included in every request"
},
{
"code": null,
"e": 1782,
"s": 1733,
"text": "Should be in US-ASCII (as with the whole header)"
},
{
"code": null,
"e": 1899,
"s": 1782,
"text": "Consists of a series of “product tokens” — a product name string with an optional version number, separated by a “/”"
},
{
"code": null,
"e": 1957,
"s": 1899,
"text": "Product tokens are separated from one another by a space."
},
{
"code": null,
"e": 2011,
"s": 1957,
"text": "Comments are allowed by enclosing them in parentheses"
},
{
"code": null,
"e": 2065,
"s": 2011,
"text": "Product tokens should be ordered most important first"
},
{
"code": null,
"e": 2142,
"s": 2065,
"text": "One product should not copy another product’s token to declare compatibility"
},
{
"code": null,
"e": 2188,
"s": 2142,
"text": "No advertising, no overly fine-grained detail"
},
{
"code": null,
"e": 2281,
"s": 2188,
"text": "Although it is not required, user agents should include this field with requests. — RFC 1945"
},
{
"code": null,
"e": 2403,
"s": 2281,
"text": "RFC 1945 predates the RFC 2119 language of SHOULD, so it reads more casually. Still, the most important points are these:"
},
{
"code": null,
"e": 2456,
"s": 2403,
"text": "Not required but UA should be included with requests"
},
{
"code": null,
"e": 2561,
"s": 2456,
"text": "Used for statistical purposes, tracing protocol violations tailoring responses to user agent limitations"
},
{
"code": null,
"e": 2618,
"s": 2561,
"text": "Field can contain multiple “product tokens” and comments"
},
{
"code": null,
"e": 2701,
"s": 2618,
"text": "Product tokens are listed in order of significance for identifying the application"
},
{
"code": null,
"e": 2919,
"s": 2701,
"text": "It’s interesting to note that, even in this RFC, it already warns of anomalies like some proxies will append data to the UA which makes interpretation ambiguous, and some clients don’t follow the product token syntax."
},
{
"code": null,
"e": 3267,
"s": 2919,
"text": "A product token is simply in the format of product/version where version is optional. Tokens are whitespace delimited, so products shouldn’t have whitespace. Historically, ISO 8859–1 (Latin-1) and RFC 2047 (Base64 and Quote-printable) encodings were allowed. Nowadays, the spec says to use US-ASCII and any octet > 127 is treated as “opaque data.”"
},
{
"code": null,
"e": 3407,
"s": 3267,
"text": "So, in theory, you could shove emoji or a base64 essay into the UA, but all bets are off on how the server decides if and how to handle it."
},
{
"code": null,
"e": 3845,
"s": 3407,
"text": "Subsequent versions of the HTTP RFCs have more standardized language, but generally, things remain the same. It’s still product/version entries separated by spaces, with comments in parentheses. What’s notable is the addition of very specific prohibitions against putting non-essential, fine-grained information or advertising in the UA. Overly long UAs are specifically stated to potentially fingerprint users (we’ll get to this later)."
},
{
"code": null,
"e": 4006,
"s": 3845,
"text": "It’s also specifically stated that it’s discouraged for products to use the product tokens of other products to declare compatibility. We’ll get into that next."
},
{
"code": null,
"e": 4284,
"s": 4006,
"text": "What’s interesting about all these additions is that they didn’t exist in RFC 2068 the original HTTP/1.1 spec from January 1997,or RFC 2616 dating from June 1999. In the intervening 5 years of exploding internet use, it seems they had seen some abuses that they wanted to stop."
},
{
"code": null,
"e": 4452,
"s": 4284,
"text": "While knowing what the RFCs say about User-Agent strings is useful to know the format that things take, it doesn’t tell you very much about how it is used in practice."
},
{
"code": null,
"e": 4883,
"s": 4452,
"text": "As stated quite amusingly here in a “History of the browser user-agent string”, the reality of UAs today is that practically everything pretends to be Mozilla first. This was because back in the ‘90s when browser features were rapidly changing, the Mozilla browser had certain features like frames that were initially unavailable in competing browsers, so web designers sent different versions of the page based on the User-Agent."
},
{
"code": null,
"e": 5231,
"s": 4883,
"text": "But as the other browsers caught to Mozilla in terms of features, web designers were slow (or didn’t bother) to update their serving rules to match. So browsers that could support advanced features were not served pages with such features. To get around this, the other browsers just declared themselves to be Mozilla to fetch the Mozilla version."
},
{
"code": null,
"e": 5620,
"s": 5231,
"text": "Soon, practically every mainstream browser just decided to declare they were Mozilla as the first product string, while adding the actual browser in a comment or a subsequent product string. This is most likely what prompted the latest RFCs to specifically say using another product’s string (i.e. Mozilla) is discouraged. Browsers still do it to this day, with no real signs of changing."
},
{
"code": null,
"e": 6215,
"s": 5620,
"text": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36-- A Chrome User-AgentMozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0-- A Firefox User-AgentMozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362-- A Microsoft Edge User-AgentMozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko-- An Internet Explorer 11 User-Agent\"Links (2.16; FreeBSD 12.0-RELEASE-p10 amd64; LLVM/Clang 6.0.1; text)\"-- A Links2 User-Agent"
},
{
"code": null,
"e": 6315,
"s": 6215,
"text": "If you’d like, you can browse the vast array of User Agents online with resources such as this one."
},
{
"code": null,
"e": 6834,
"s": 6315,
"text": "What you’ll also notice is that every browser is fairly idiosyncratic with the sequence and types of product tokens it has. With enough study you can fairly reliably know what device and browser a request is coming from. IE11 uses the comment Trident/7.0 to denote its render engine and “rv:11.0” to denote the IE version, Chrome (and Edge which switched to being chromium on the back end) are full product-version tokens, but will also claim Safari compatibility because they both use AppleWebKit. It’s a tangled web."
},
{
"code": null,
"e": 7096,
"s": 6834,
"text": "It varies: some are more well behaved than others. Some state the bot as the top level product, some also claim Mozilla compatibility, or claim to be on a mobile device. Some are libraries that provide a default User-Agent that a dev can override but forgot to."
},
{
"code": null,
"e": 7644,
"s": 7096,
"text": "W3C_Validator/1.3 http://validator.w3.org/services - W3c's validatorGooglebot/2.1 (+http://www.google.com/bot.html) - A GooglebotMozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) - A Googlebot, but AndroidMozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) - one of the BingbotsPython/3.6 aiohttp/3.5.4 - Python's AIOHTTP librarypython-requests/2.20.1 - Python's Request library"
},
{
"code": null,
"e": 7910,
"s": 7644,
"text": "Robots and scripts are sooorta obvious, but you sometimes have to squint a little. They’re more likely to have URLs in the text (as part of a practice to allow people to identify and report misbehaving bots) but that’s no guarantee, you gotta parse it case by case."
},
{
"code": null,
"e": 8257,
"s": 7910,
"text": "For various reasons, whether for testing, compatibility, or privacy reasons, users may want to have their browser give a different User-Agent string than default. The RFCs specifically say that if a client sends a masqueraded UA, then it should be interpreted as the client intentionally wanting that version, even if it may not render correctly."
},
{
"code": null,
"e": 8523,
"s": 8257,
"text": "If a user agent masquerades as a different user agent, recipients can assume that the user intentionally desires to see responses tailored for that identified user agent, even if they might not work as well for the actual user agent being used. — RFC 7231, HTTP/1.1"
},
{
"code": null,
"e": 8775,
"s": 8523,
"text": "Browsers often provide the functionality for users to spoof their UAs. That said, it’s extremely rare to encounter users who go through the trouble since the differences between browser functionality has largely become trivial from a user perspective."
},
{
"code": null,
"e": 9028,
"s": 8775,
"text": "One thing to remember about User-Agents is that it is a very old technology, and many of the things that it has been used for historically (such as basic analytics) have been given over to other technologies that can provide more detail and resolution."
},
{
"code": null,
"e": 9386,
"s": 9028,
"text": "This usage is the original intended purpose of the UA string, giving the server the ability to serve different versions of the web page based on what the client is capable of handling. Internet Explorer 6 was perhaps the most egregious example of where site designers needed to know the browser version because of how poorly it handled modern web standards."
},
{
"code": null,
"e": 9625,
"s": 9386,
"text": "Fun side note, IE6 was a HUGE problem in the late 2000s/early 2010s due to its horrible standards support requiring lots of custom hacks from developers but stubbornly high usage numbers. The pain spawned efforts such as these to kill it."
},
{
"code": null,
"e": 10164,
"s": 9625,
"text": "Back in the mid/early 2000s, UAs were an important tool in analyzing what users were using. Using Javascript to pull browser info was still in its infancy, so User-Agents were the most informative thing that you had. From this, you could see what percentage of your users were using IE6 versus Firefox (and whether you should stop using certain HTML features or not). You could also see how often the search engine crawlers visited, and whether you had actual human visitors or not. Primitive by modern standards, but better than nothing."
},
{
"code": null,
"e": 10625,
"s": 10164,
"text": "It’s considered good practice and manners for bots, web crawlers, and similar automated programs to identify to the server via the User-Agent string. Very often the UA will contain the string “bot” “crawler” “spider”, sometimes with a URL of the bot owner as a comment. But the specific implementation of the UA will vary wildly from bot to bot. This is because ultimately a human developer decides what “self-identification” means, there’s no standard format."
},
{
"code": null,
"e": 10928,
"s": 10625,
"text": "The basic robots.txt file is used to tell what web crawlers and other robots should or should not access on a given web server. Very often, it doesn’t make a distinction between different types of clients, but there’s actually a facility to specify which User-Agent string is allowed in certain places."
},
{
"code": null,
"e": 11114,
"s": 10928,
"text": "Obviously, this assumes that the robot 1) reads and follows the directives in the robots.txt file and 2) identifies itself properly in the User-Agent (and again follows the directives)."
},
{
"code": null,
"e": 11372,
"s": 11114,
"text": "User-Agent strings can range from being very simple, to very long with many product tokens chained together. The most egregious ones would be browsers that had many sketchy toolbars installed, each toolbar would often append its own product token to the UA."
},
{
"code": null,
"e": 11855,
"s": 11372,
"text": "The longer the UA, the more likely it has strayed from the base default UA provided by the browser, and it becomes increasingly likely that the UA becomes unique to a specific installation. Working under this assumption, people could use UAs as a way to pseudo-identify a user across time and IP addresses. I’ve seen browsers with as many as 6 toolbars installed and that browser + IP combo was practically unique in the sea of requests, enough to track someone across the internet."
},
{
"code": null,
"e": 12202,
"s": 11855,
"text": "In practice, this method only really works on the tiny subset of people who have installed enough browser extensions or poorly spoofed their UA enough to stand out from the crowd of default strings. But even so, the UA still provides bits of entropy in a larger user fingerprinting framework that involves the use of Javascript and HTML5 methods."
},
{
"code": null,
"e": 12482,
"s": 12202,
"text": "I’ll have to get into device fingerprinting another day, it’s a huge topic. For now, if you’re interested you can take a look at this to get an idea of what is possible when you use the full range of tech possible, spanning request headers to Javascript, Flash, and HTML5 Canvas."
},
{
"code": null,
"e": 12682,
"s": 12482,
"text": "With many advanced browser features being detected directly via Javascript these days, this is probably the primary modern use of the UA string, figuring out what device/platform a client is running."
},
{
"code": null,
"e": 13053,
"s": 12682,
"text": "UAs found a new life in the late 2000s with the smartphone and tablet explosion. While UAs used to tell you what percent of your userbase was on IE, Firefox or Chrome on a Windows machine or Mac, we suddenly started seeing exciting new strings like iPad, iPhone, Android. Not everyone was using a desktop/laptop any more, but we could see what they were using and adapt!"
},
{
"code": null,
"e": 13575,
"s": 13053,
"text": "These new devices had different physical screen sizes and physical capabilities. It wasn’t just “oh this browser has no Javascript/HTML5/CSS support” any more. This information is highly relevant to designers, especially on older early/mid-2010 devices that did not have full-HD 1080p or higher screen resolutions. (The iPhone 4S from 2011 had a 960×640 pixel screen.) Sites designed for mobile devices needed to have different UIs that work better for touch screens, and be smaller to work with 2G, 3G wireless networks."
},
{
"code": null,
"e": 13799,
"s": 13575,
"text": "But again, because the User-Agent is completely free-form, it could be potentially different for every permutation of manufacturer/device/OS/browser in very unique ways. How are developers supposed to handle this situation?"
},
{
"code": null,
"e": 13881,
"s": 13799,
"text": "Through painstaking analysis and building a large database of strings, of course!"
},
{
"code": null,
"e": 14274,
"s": 13881,
"text": "Luckily! There are open source projects that are tackling this sort of problem (as well as paid API services that do User-Agent string analysis). One is the UA-parser project, which at its core is a giant list of over 1100 regex definitions that search for unique patterns in the UA and associates it with manufacturers and specific devices. It’s a herculean effort maintained by many people."
},
{
"code": null,
"e": 14285,
"s": 14274,
"text": "github.com"
},
{
"code": null,
"e": 14507,
"s": 14285,
"text": "Running (up to) a thousand regex searches on a single string is obviously very resource-intensive, but this is the only way to make sure to identify a UA string to the fullest extent possible short of reading it manually."
},
{
"code": null,
"e": 14847,
"s": 14507,
"text": "In practice, you can speed up things massively with hashing and caching by relying on the fact that most users will have the same general default setup, so you’d only have to run regex on novel strings. This works because UA strings have a really dense cluster of exactly-matching values, and then a massively long-tail of esoteric values."
},
{
"code": null,
"e": 15296,
"s": 14847,
"text": "RFCs aren’t strongly enforced in any way, so it’s entirely possible to encounter non-conforming User-Agent strings. I’ve personally seen strings where nonsense characters like newlines (\\n) and ASCII nulls (\\0) have been put into the string. Unicode is also technically allowed (in that systems treat is as opaque bytes) but is generally unexpected and uncommon. Most UA handlers still assume that UAs are US-ASCII (as specified in the latest RFCs)"
},
{
"code": null,
"e": 15632,
"s": 15296,
"text": "Usually, this stuff is from someone writing a robot and they are unfamiliar with the RFCs. Or they’re trying to be jerks and attempting to break systems. Either way, when you process UA strings at scale, your code will break a surprising amount due to malformed strings, so be prepared to write exception handlers to catch bad strings."
},
{
"code": null,
"e": 15800,
"s": 15632,
"text": "User-Agents are ubiquitous, so many people know just a tiny bit about them. The problem comes from when those people try to interpret them and come to bad conclusions."
},
{
"code": null,
"e": 16131,
"s": 15800,
"text": "People sometimes think User-Agents somehow provide them with counts of users. Often this is thinking from a mix of outdated thinking from a decade ago when people often only had 1 internet-connected computer, or they’ve heard about browser fingerprinting but aren’t aware of how many data points it takes to fingerprint a browser."
},
{
"code": null,
"e": 16544,
"s": 16131,
"text": "Obviously, this isn’t true today. Most users these days use multiple devices/browsers throughout the day and fingerprint methods are super complex. Counts of unique UAs do give a rough sense of the number of unique types of browsers that have made requests. But even when combined with the IP address, many humans can be using multiple devices that all use the exact same UA and sit behind a NAT and share an IP."
},
{
"code": null,
"e": 16822,
"s": 16544,
"text": "I’ve personally had to use UAs to put very rough bounds on the minimum number of browsers used to view a site, with the raw hit count being the upper limit. This was because we literally had no other data available. But I had to be very very clear about what we were measuring."
},
{
"code": null,
"e": 17102,
"s": 16822,
"text": "When people hear that UAs can be spoofed easily, they often worry that they’re being lied to and their metrics are going to be off. They often worry so much they overthink things and reach for more technically difficult solutions. I often tell people not to worry about spoofing."
},
{
"code": null,
"e": 17421,
"s": 17102,
"text": "The primary reason is that the vast majority of users have no motivation to bother messing with their UA string. They just want to use the internet. The only people who want to manipulate their UA are usually a microscopic number of users writing bots/crawlers of some sort. Then it breaks down into a few major cases:"
},
{
"code": null,
"e": 18290,
"s": 17421,
"text": "The UA is by a human and doing human-scale traffic. Out of hundreds, thousands, possibly millions of humans using your site every day, they’re ultimately insignificant because they represent such a fractional percent of traffic.The UA a small volume robot — these are the small student scraper projects, the random programmer trying stuff out. So long as they’re generally well behaved and low volume, they won’t skew your metrics much so you can ignore it like the above.It’s a significantly spammy robot — You’ll need to account for this one case somehow. Often these will hammer from small set of IPs that are often a not used by end users (like an AWS IP block or a datacenter), you can usually filter those out based on a heuristics. There are often signs of problems (like your systems overloading like it’s a DDoS attack) when you’re facing these sorts of bots."
},
{
"code": null,
"e": 18519,
"s": 18290,
"text": "The UA is by a human and doing human-scale traffic. Out of hundreds, thousands, possibly millions of humans using your site every day, they’re ultimately insignificant because they represent such a fractional percent of traffic."
},
{
"code": null,
"e": 18764,
"s": 18519,
"text": "The UA a small volume robot — these are the small student scraper projects, the random programmer trying stuff out. So long as they’re generally well behaved and low volume, they won’t skew your metrics much so you can ignore it like the above."
},
{
"code": null,
"e": 19161,
"s": 18764,
"text": "It’s a significantly spammy robot — You’ll need to account for this one case somehow. Often these will hammer from small set of IPs that are often a not used by end users (like an AWS IP block or a datacenter), you can usually filter those out based on a heuristics. There are often signs of problems (like your systems overloading like it’s a DDoS attack) when you’re facing these sorts of bots."
},
{
"code": null,
"e": 19529,
"s": 19161,
"text": "It’s pretty rare to have to worry about spoofing unless you’re running something that robot-makers have an incentive to abuse (and UA is not likely to be the solution if that’s your problem). I suppose there are some edge cases: like if you get practically no traffic, so the bots will dominate, but you also have little reason to do a lot of analytics at that point."
},
{
"code": null,
"e": 19647,
"s": 19529,
"text": "Sooooooorta. In some very specific instances, you can catch a UA in a lie. But don’t expect it to be a regular thing."
},
{
"code": null,
"e": 19869,
"s": 19647,
"text": "The easiest case is when someone makes an error in spoofing their UA string. Their UA stands out like a sore thumb because no one else uses it. It could be something as simple as having an extra space or punctuation mark."
},
{
"code": null,
"e": 20052,
"s": 19869,
"text": "Similarly, sometimes spoofers don’t understand the User-Agent string enough and put together impossible combinations of product strings. They’ll stand out for being hyper-unique too."
},
{
"code": null,
"e": 20308,
"s": 20052,
"text": "Another somewhat common case is when you have access to the browser’s data via JavaScript. If you see an iPhone have a screen size that is massively different from the physical pixel dimensions of the phone itself, it’s probably lying about being a phone."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.