title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
All unique combinations whose sum equals to K - GeeksforGeeks
07 Sep, 2021 Given an array arr[] of size N and an integer K. The task is to find all the unique combinations from the given array such that sum of the elements in each combination is equal to K. Examples: Input: arr[] = {1, 2, 3}, K = 3 Output: {1, 2} {3} Explanation:These are the combinations whose sum equals to 3. Input: arr[] = {2, 2, 2}, K = 4 Output: {2, 2} Approach: Some elements can be repeated in the given array. Make sure to iterate over the number of occurrences of those elements to avoid repeated combinations. Once you do that, things are fairly straightforward. Call a recursive function with the remaining sum and make the indices to move forward. When the sum reaches K, print all the elements which were selected to get this sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find all unique combination of// given elements such that their sum is Kvoid unique_combination(int l, int sum, int K, vector<int>& local, vector<int>& A){ // If a unique combination is found if (sum == K) { cout << "{"; for (int i = 0; i < local.size(); i++) { if (i != 0) cout << " "; cout << local[i]; if (i != local.size() - 1) cout << ", "; } cout << "}" << endl; return; } // For all other combinations for (int i = l; i < A.size(); i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i > l and A[i] == A[i - 1]) continue; // Take the element into the combination local.push_back(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.pop_back(); }} // Function to find all combination// of the given elementsvoid Combination(vector<int> A, int K){ // Sort the given elements sort(A.begin(), A.end()); // To store combination vector<int> local; unique_combination(0, 0, K, local, A);} // Driver codeint main(){ vector<int> A = { 10, 1, 2, 7, 6, 1, 5 }; int K = 8; // Function call Combination(A, K); return 0;} // Java implementation of the approachimport java.util.*; class GFG { // Function to find all unique combination of // given elements such that their sum is K static void unique_combination(int l, int sum, int K, Vector<Integer> local, Vector<Integer> A) { // If a unique combination is found if (sum == K) { System.out.print("{"); for (int i = 0; i < local.size(); i++) { if (i != 0) System.out.print(" "); System.out.print(local.get(i)); if (i != local.size() - 1) System.out.print(", "); } System.out.println("}"); return; } // For all other combinations for (int i = l; i < A.size(); i++) { // Check if the sum exceeds K if (sum + A.get(i) > K) continue; // Check if it is repeated or not if (i > l && A.get(i) == A.get(i - 1) ) continue; // Take the element into the combination local.add(A.get(i)); // Recursive call unique_combination(i + 1, sum + A.get(i), K, local, A); // Remove element from the combination local.remove(local.size() - 1); } } // Function to find all combination // of the given elements static void Combination(Vector<Integer> A, int K) { // Sort the given elements Collections.sort(A); // To store combination Vector<Integer> local = new Vector<Integer>(); unique_combination(0, 0, K, local, A); } // Driver code public static void main(String[] args) { Integer[] arr = { 10, 1, 2, 7, 6, 1, 5 }; Vector<Integer> A = new Vector<>(Arrays.asList(arr)); int K = 8; // Function call Combination(A, K); }} // This code is contributed by PrinciRaj1992 # Python 3 implementation of the approach # Function to find all unique combination of# given elements such that their sum is K def unique_combination(l, sum, K, local, A): # If a unique combination is found if (sum == K): print("{", end="") for i in range(len(local)): if (i != 0): print(" ", end="") print(local[i], end="") if (i != len(local) - 1): print(", ", end="") print("}") return # For all other combinations for i in range(l, len(A), 1): # Check if the sum exceeds K if (sum + A[i] > K): continue # Check if it is repeated or not if (i > l and A[i] == A[i - 1]): continue # Take the element into the combination local.append(A[i]) # Recursive call unique_combination(i + 1, sum + A[i], K, local, A) # Remove element from the combination local.remove(local[len(local) - 1]) # Function to find all combination# of the given elements def Combination(A, K): # Sort the given elements A.sort(reverse=False) local = [] unique_combination(0, 0, K, local, A) # Driver codeif __name__ == '__main__': A = [10, 1, 2, 7, 6, 1, 5] K = 8 # Function call Combination(A, K) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to find all unique combination of // given elements such that their sum is K static void unique_combination(int l, int sum, int K, List<int> local, List<int> A) { // If a unique combination is found if (sum == K) { Console.Write("{"); for (int i = 0; i < local.Count; i++) { if (i != 0) Console.Write(" "); Console.Write(local[i]); if (i != local.Count - 1) Console.Write(", "); } Console.WriteLine("}"); return; } // For all other combinations for (int i = l; i < A.Count; i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i >l && A[i] == A[i - 1]) continue; // Take the element into the combination local.Add(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.RemoveAt(local.Count - 1); } } // Function to find all combination // of the given elements static void Combination(List<int> A, int K) { // Sort the given elements A.Sort(); // To store combination List<int> local = new List<int>(); unique_combination(0, 0, K, local, A); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 1, 2, 7, 6, 1, 5 }; List<int> A = new List<int>(arr); int K = 8; // Function call Combination(A, K); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Function to find all unique combination of// given elements such that their sum is Kfunction unique_combination(l, sum, K, local, A) { // If a unique combination is found if (sum == K) { document.write("{"); for (let i = 0; i < local.length; i++) { if (i != 0) document.write(" "); document.write(local[i]); if (i != local.length - 1) document.write(", "); } document.write("}" + "<br>"); return; } // For all other combinations for (let i = l; i < A.length; i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i > l && A[i] == A[i - 1]) continue; // Take the element into the combination local.push(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.pop(); }} // Function to find all combination// of the given elementsfunction Combination(A, K) { // Sort the given elements A.sort((a, b) => a - b); // To store combination let local = []; unique_combination(0, 0, K, local, A);} // Driver code let A = [10, 1, 2, 7, 6, 1, 5]; let K = 8; // Function callCombination(A, K); // This code is contributed by _saurabh_jaiswal </script> {1, 1, 6} {1, 2, 5} {1, 7} {2, 6} princiraj1992 Rajput-Ji SURENDRA_GANGWAR richaranderia _saurabh_jaiswal shijo2895 khushboogoyal499 Arrays Recursion Sorting Arrays Recursion Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Recursion Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Program for Sum of the digits of a given number Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 24790, "s": 24762, "text": "\n07 Sep, 2021" }, { "code": null, "e": 24973, "s": 24790, "text": "Given an array arr[] of size N and an integer K. The task is to find all the unique combinations from the given array such that sum of the elements in each combination is equal to K." }, { "code": null, "e": 24984, "s": 24973, "text": "Examples: " }, { "code": null, "e": 25098, "s": 24984, "text": "Input: arr[] = {1, 2, 3}, K = 3 Output: {1, 2} {3} Explanation:These are the combinations whose sum equals to 3. " }, { "code": null, "e": 25146, "s": 25098, "text": "Input: arr[] = {2, 2, 2}, K = 4 Output: {2, 2} " }, { "code": null, "e": 25532, "s": 25146, "text": "Approach: Some elements can be repeated in the given array. Make sure to iterate over the number of occurrences of those elements to avoid repeated combinations. Once you do that, things are fairly straightforward. Call a recursive function with the remaining sum and make the indices to move forward. When the sum reaches K, print all the elements which were selected to get this sum." }, { "code": null, "e": 25584, "s": 25532, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25588, "s": 25584, "text": "C++" }, { "code": null, "e": 25593, "s": 25588, "text": "Java" }, { "code": null, "e": 25601, "s": 25593, "text": "Python3" }, { "code": null, "e": 25604, "s": 25601, "text": "C#" }, { "code": null, "e": 25615, "s": 25604, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find all unique combination of// given elements such that their sum is Kvoid unique_combination(int l, int sum, int K, vector<int>& local, vector<int>& A){ // If a unique combination is found if (sum == K) { cout << \"{\"; for (int i = 0; i < local.size(); i++) { if (i != 0) cout << \" \"; cout << local[i]; if (i != local.size() - 1) cout << \", \"; } cout << \"}\" << endl; return; } // For all other combinations for (int i = l; i < A.size(); i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i > l and A[i] == A[i - 1]) continue; // Take the element into the combination local.push_back(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.pop_back(); }} // Function to find all combination// of the given elementsvoid Combination(vector<int> A, int K){ // Sort the given elements sort(A.begin(), A.end()); // To store combination vector<int> local; unique_combination(0, 0, K, local, A);} // Driver codeint main(){ vector<int> A = { 10, 1, 2, 7, 6, 1, 5 }; int K = 8; // Function call Combination(A, K); return 0;}", "e": 27154, "s": 25615, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to find all unique combination of // given elements such that their sum is K static void unique_combination(int l, int sum, int K, Vector<Integer> local, Vector<Integer> A) { // If a unique combination is found if (sum == K) { System.out.print(\"{\"); for (int i = 0; i < local.size(); i++) { if (i != 0) System.out.print(\" \"); System.out.print(local.get(i)); if (i != local.size() - 1) System.out.print(\", \"); } System.out.println(\"}\"); return; } // For all other combinations for (int i = l; i < A.size(); i++) { // Check if the sum exceeds K if (sum + A.get(i) > K) continue; // Check if it is repeated or not if (i > l && A.get(i) == A.get(i - 1) ) continue; // Take the element into the combination local.add(A.get(i)); // Recursive call unique_combination(i + 1, sum + A.get(i), K, local, A); // Remove element from the combination local.remove(local.size() - 1); } } // Function to find all combination // of the given elements static void Combination(Vector<Integer> A, int K) { // Sort the given elements Collections.sort(A); // To store combination Vector<Integer> local = new Vector<Integer>(); unique_combination(0, 0, K, local, A); } // Driver code public static void main(String[] args) { Integer[] arr = { 10, 1, 2, 7, 6, 1, 5 }; Vector<Integer> A = new Vector<>(Arrays.asList(arr)); int K = 8; // Function call Combination(A, K); }} // This code is contributed by PrinciRaj1992", "e": 29182, "s": 27154, "text": null }, { "code": "# Python 3 implementation of the approach # Function to find all unique combination of# given elements such that their sum is K def unique_combination(l, sum, K, local, A): # If a unique combination is found if (sum == K): print(\"{\", end=\"\") for i in range(len(local)): if (i != 0): print(\" \", end=\"\") print(local[i], end=\"\") if (i != len(local) - 1): print(\", \", end=\"\") print(\"}\") return # For all other combinations for i in range(l, len(A), 1): # Check if the sum exceeds K if (sum + A[i] > K): continue # Check if it is repeated or not if (i > l and A[i] == A[i - 1]): continue # Take the element into the combination local.append(A[i]) # Recursive call unique_combination(i + 1, sum + A[i], K, local, A) # Remove element from the combination local.remove(local[len(local) - 1]) # Function to find all combination# of the given elements def Combination(A, K): # Sort the given elements A.sort(reverse=False) local = [] unique_combination(0, 0, K, local, A) # Driver codeif __name__ == '__main__': A = [10, 1, 2, 7, 6, 1, 5] K = 8 # Function call Combination(A, K) # This code is contributed by# Surendra_Gangwar", "e": 30574, "s": 29182, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to find all unique combination of // given elements such that their sum is K static void unique_combination(int l, int sum, int K, List<int> local, List<int> A) { // If a unique combination is found if (sum == K) { Console.Write(\"{\"); for (int i = 0; i < local.Count; i++) { if (i != 0) Console.Write(\" \"); Console.Write(local[i]); if (i != local.Count - 1) Console.Write(\", \"); } Console.WriteLine(\"}\"); return; } // For all other combinations for (int i = l; i < A.Count; i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i >l && A[i] == A[i - 1]) continue; // Take the element into the combination local.Add(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.RemoveAt(local.Count - 1); } } // Function to find all combination // of the given elements static void Combination(List<int> A, int K) { // Sort the given elements A.Sort(); // To store combination List<int> local = new List<int>(); unique_combination(0, 0, K, local, A); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 1, 2, 7, 6, 1, 5 }; List<int> A = new List<int>(arr); int K = 8; // Function call Combination(A, K); }} // This code is contributed by Rajput-Ji", "e": 32530, "s": 30574, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to find all unique combination of// given elements such that their sum is Kfunction unique_combination(l, sum, K, local, A) { // If a unique combination is found if (sum == K) { document.write(\"{\"); for (let i = 0; i < local.length; i++) { if (i != 0) document.write(\" \"); document.write(local[i]); if (i != local.length - 1) document.write(\", \"); } document.write(\"}\" + \"<br>\"); return; } // For all other combinations for (let i = l; i < A.length; i++) { // Check if the sum exceeds K if (sum + A[i] > K) continue; // Check if it is repeated or not if (i > l && A[i] == A[i - 1]) continue; // Take the element into the combination local.push(A[i]); // Recursive call unique_combination(i + 1, sum + A[i], K, local, A); // Remove element from the combination local.pop(); }} // Function to find all combination// of the given elementsfunction Combination(A, K) { // Sort the given elements A.sort((a, b) => a - b); // To store combination let local = []; unique_combination(0, 0, K, local, A);} // Driver code let A = [10, 1, 2, 7, 6, 1, 5]; let K = 8; // Function callCombination(A, K); // This code is contributed by _saurabh_jaiswal </script>", "e": 33974, "s": 32530, "text": null }, { "code": null, "e": 34014, "s": 33974, "text": "{1, 1, 6}\n{1, 2, 5}\n{1, 7}\n{2, 6}" }, { "code": null, "e": 34028, "s": 34014, "text": "princiraj1992" }, { "code": null, "e": 34038, "s": 34028, "text": "Rajput-Ji" }, { "code": null, "e": 34055, "s": 34038, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34069, "s": 34055, "text": "richaranderia" }, { "code": null, "e": 34086, "s": 34069, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34096, "s": 34086, "text": "shijo2895" }, { "code": null, "e": 34113, "s": 34096, "text": "khushboogoyal499" }, { "code": null, "e": 34120, "s": 34113, "text": "Arrays" }, { "code": null, "e": 34130, "s": 34120, "text": "Recursion" }, { "code": null, "e": 34138, "s": 34130, "text": "Sorting" }, { "code": null, "e": 34145, "s": 34138, "text": "Arrays" }, { "code": null, "e": 34155, "s": 34145, "text": "Recursion" }, { "code": null, "e": 34163, "s": 34155, "text": "Sorting" }, { "code": null, "e": 34261, "s": 34163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34270, "s": 34261, "text": "Comments" }, { "code": null, "e": 34283, "s": 34270, "text": "Old Comments" }, { "code": null, "e": 34331, "s": 34283, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34375, "s": 34331, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34398, "s": 34375, "text": "Introduction to Arrays" }, { "code": null, "e": 34430, "s": 34398, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34444, "s": 34430, "text": "Linear Search" }, { "code": null, "e": 34454, "s": 34444, "text": "Recursion" }, { "code": null, "e": 34539, "s": 34454, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34566, "s": 34539, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 34614, "s": 34566, "text": "Program for Sum of the digits of a given number" } ]
How to make a txt file and read txt file from internal storage in android?
This example demonstrates How to make a txt file and read txt file from internal storage in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/enterText" android:hint = "Please enter text here" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/output" android:layout_width = "wrap_content" android:textSize = "25sp" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken editext and button. When user click on button, it will take data from edittext and store in internal storage as /data/data/<your.package.name>/files/text/sample.txt. It going to append the data to textview from sample.txt Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { Button save; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView output = findViewById(R.id.output); final EditText enterText = findViewById(R.id.enterText); save = findViewById(R.id.save); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!enterText.getText().toString().isEmpty()) { File file = new File(MainActivity.this.getFilesDir(), "text"); if (!file.exists()) { file.mkdir(); } try { File gpxfile = new File(file, "sample"); FileWriter writer = new FileWriter(gpxfile); writer.append(enterText.getText().toString()); writer.flush(); writer.close(); output.setText(readFile()); Toast.makeText(MainActivity.this, "Saved your text", Toast.LENGTH_LONG).show(); } catch (Exception e) { } } } }); } private String readFile() { File fileEvents = new File(MainActivity.this.getFilesDir()+"/text/sample"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(fileEvents)); String line; while ((line = br.readLine()) ! = null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { } String result = text.toString(); return result; } } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, we have added some text and clicked on save button as shown below – To verify the above result, /data/data/<your.package.name>/files/text/sample.txt as shown below – Click here to download the project code
[ { "code": null, "e": 1163, "s": 1062, "text": "This example demonstrates How to make a txt file and read txt file from internal storage in android." }, { "code": null, "e": 1292, "s": 1163, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1357, "s": 1292, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2217, "s": 1357, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/enterText\"\n android:hint = \"Please enter text here\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/output\"\n android:layout_width = \"wrap_content\"\n android:textSize = \"25sp\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2472, "s": 2217, "text": "In the above code, we have taken editext and button. When user click on button, it will take data from edittext and store in internal storage as /data/data/<your.package.name>/files/text/sample.txt. It going to append the data to textview from sample.txt" }, { "code": null, "e": 2529, "s": 2472, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4772, "s": 2529, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class MainActivity extends AppCompatActivity {\n Button save;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView output = findViewById(R.id.output);\n final EditText enterText = findViewById(R.id.enterText);\n save = findViewById(R.id.save);\n save.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!enterText.getText().toString().isEmpty()) {\n File file = new File(MainActivity.this.getFilesDir(), \"text\");\n if (!file.exists()) {\n file.mkdir();\n }\n try {\n File gpxfile = new File(file, \"sample\");\n FileWriter writer = new FileWriter(gpxfile);\n writer.append(enterText.getText().toString());\n writer.flush();\n writer.close();\n output.setText(readFile());\n Toast.makeText(MainActivity.this, \"Saved your text\", Toast.LENGTH_LONG).show();\n } catch (Exception e) { }\n }\n }\n });\n }\n private String readFile() {\n File fileEvents = new File(MainActivity.this.getFilesDir()+\"/text/sample\");\n StringBuilder text = new StringBuilder();\n try {\n BufferedReader br = new BufferedReader(new FileReader(fileEvents));\n String line;\n while ((line = br.readLine()) ! = null) {\n text.append(line);\n text.append('\\n');\n }\n br.close();\n } catch (IOException e) { }\n String result = text.toString();\n return result;\n }\n}" }, { "code": null, "e": 4820, "s": 4772, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 5690, "s": 4820, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name = \"android.permission.READ_EXTERNAL_STORAGE\"/>\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": 6037, "s": 5690, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 6126, "s": 6037, "text": "In the above result, we have added some text and clicked on save button as shown below –" }, { "code": null, "e": 6224, "s": 6126, "text": "To verify the above result, /data/data/<your.package.name>/files/text/sample.txt as shown below –" }, { "code": null, "e": 6264, "s": 6224, "text": "Click here to download the project code" } ]
PHP Cookies - GeeksforGeeks
30 Nov, 2021 A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the client computer. They are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time. A cookie can only be read from the domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript can also set a cookie directly on a browser. Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be called prior to any output generated by the script otherwise the cookie will not be set. Syntax: setcookie(name, value, expire, path, domain, security); Parameters: The setcookie() function requires six arguments in general which are: Name: It is used to set the name of the cookie. Value: It is used to set the value of the cookie. Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed. Path: It is used to specify the path on the server for which the cookie will be available. Domain: It is used to specify the domain for which the cookie is available. Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists. Below are some operations that can be performed on Cookies in PHP: Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds). Example: This example describes the creation of the cookie in PHP. PHP <!DOCTYPE html><?php setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);?><html><body> <?php echo "cookie is created." ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html> Note: Only the name argument in the setcookie() function is mandatory. To skip an argument, the argument can be replaced by an empty string(“”). Output: Cookie creation in PHP Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie is set or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP isset() function is used. To check whether a cookie “Auction_Item” is set or not, the isset() function is executed as follows: Example: This example describes checking whether the cookie is set or not. PHP <!DOCTYPE html><?php setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);?><html><body> <?php if (isset($_COOKIE["Auction_Item"])) { echo "Auction Item is a " . $_COOKIE["Auction_Item"]; } else { echo "No items for auction."; } ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html> Output: Checking for the cookie to be set Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a record of all the cookies values sent by the browser in the current request. The records are stored as a list where the cookie name is used as the key. To access a cookie named “Auction_Item”, the following code can be executed. Example: This example describes accessing & modifying the cookie value. PHP <!DOCTYPE html><?php setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);?><html><body><?php echo "Auction Item is a " . $_COOKIE["Auction_Item"];?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html> Output: Accessing the Cookie value Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie() function is called by passing the cookie name and other arguments or empty strings but however this time, the expiration date is required to be set in the past. To delete a cookie named “Auction_Item”, the following code can be executed. Example: This example describes the deletion of the cookie value. PHP <!DOCTYPE html><?php setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);?><html><body> <?php setcookie("Auction_Item", "", time() - 60); ?> <?php echo "cookie is deleted" ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html> Output: Deleting the Cookie Important Points: If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end of the session i.e. when the browser closes. The same path, domain, and other arguments should be passed that were used to create the cookie in order to ensure that the correct cookie is deleted. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. bhaskargeeksforgeeks PHP-session PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to pop an alert message box using PHP ? How to convert array to string in PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 40894, "s": 40866, "text": "\n30 Nov, 2021" }, { "code": null, "e": 41345, "s": 40894, "text": "A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the client computer. They are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time. A cookie can only be read from the domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript can also set a cookie directly on a browser." }, { "code": null, "e": 41552, "s": 41345, "text": "Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be called prior to any output generated by the script otherwise the cookie will not be set." }, { "code": null, "e": 41560, "s": 41552, "text": "Syntax:" }, { "code": null, "e": 41616, "s": 41560, "text": "setcookie(name, value, expire, path, domain, security);" }, { "code": null, "e": 41699, "s": 41616, "text": "Parameters: The setcookie() function requires six arguments in general which are: " }, { "code": null, "e": 41747, "s": 41699, "text": "Name: It is used to set the name of the cookie." }, { "code": null, "e": 41797, "s": 41747, "text": "Value: It is used to set the value of the cookie." }, { "code": null, "e": 41900, "s": 41797, "text": "Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed." }, { "code": null, "e": 41991, "s": 41900, "text": "Path: It is used to specify the path on the server for which the cookie will be available." }, { "code": null, "e": 42067, "s": 41991, "text": "Domain: It is used to specify the domain for which the cookie is available." }, { "code": null, "e": 42173, "s": 42067, "text": "Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists." }, { "code": null, "e": 42240, "s": 42173, "text": "Below are some operations that can be performed on Cookies in PHP:" }, { "code": null, "e": 42416, "s": 42240, "text": "Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds)." }, { "code": null, "e": 42483, "s": 42416, "text": "Example: This example describes the creation of the cookie in PHP." }, { "code": null, "e": 42487, "s": 42483, "text": "PHP" }, { "code": "<!DOCTYPE html><?php setcookie(\"Auction_Item\", \"Luxury Car\", time() + 2 * 24 * 60 * 60);?><html><body> <?php echo \"cookie is created.\" ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html>", "e": 42784, "s": 42487, "text": null }, { "code": null, "e": 42929, "s": 42784, "text": "Note: Only the name argument in the setcookie() function is mandatory. To skip an argument, the argument can be replaced by an empty string(“”)." }, { "code": null, "e": 42937, "s": 42929, "text": "Output:" }, { "code": null, "e": 42960, "s": 42937, "text": "Cookie creation in PHP" }, { "code": null, "e": 43278, "s": 42960, "text": "Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie is set or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP isset() function is used. To check whether a cookie “Auction_Item” is set or not, the isset() function is executed as follows:" }, { "code": null, "e": 43353, "s": 43278, "text": "Example: This example describes checking whether the cookie is set or not." }, { "code": null, "e": 43357, "s": 43353, "text": "PHP" }, { "code": "<!DOCTYPE html><?php setcookie(\"Auction_Item\", \"Luxury Car\", time() + 2 * 24 * 60 * 60);?><html><body> <?php if (isset($_COOKIE[\"Auction_Item\"])) { echo \"Auction Item is a \" . $_COOKIE[\"Auction_Item\"]; } else { echo \"No items for auction.\"; } ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html>", "e": 43787, "s": 43357, "text": null }, { "code": null, "e": 43795, "s": 43787, "text": "Output:" }, { "code": null, "e": 43829, "s": 43795, "text": "Checking for the cookie to be set" }, { "code": null, "e": 44203, "s": 43829, "text": "Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a record of all the cookies values sent by the browser in the current request. The records are stored as a list where the cookie name is used as the key. To access a cookie named “Auction_Item”, the following code can be executed." }, { "code": null, "e": 44275, "s": 44203, "text": "Example: This example describes accessing & modifying the cookie value." }, { "code": null, "e": 44279, "s": 44275, "text": "PHP" }, { "code": "<!DOCTYPE html><?php setcookie(\"Auction_Item\", \"Luxury Car\", time() + 2 * 24 * 60 * 60);?><html><body><?php echo \"Auction Item is a \" . $_COOKIE[\"Auction_Item\"];?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html>", "e": 44592, "s": 44279, "text": null }, { "code": null, "e": 44600, "s": 44592, "text": "Output:" }, { "code": null, "e": 44627, "s": 44600, "text": "Accessing the Cookie value" }, { "code": null, "e": 44979, "s": 44627, "text": "Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie() function is called by passing the cookie name and other arguments or empty strings but however this time, the expiration date is required to be set in the past. To delete a cookie named “Auction_Item”, the following code can be executed." }, { "code": null, "e": 45045, "s": 44979, "text": "Example: This example describes the deletion of the cookie value." }, { "code": null, "e": 45049, "s": 45045, "text": "PHP" }, { "code": "<!DOCTYPE html><?php setcookie(\"Auction_Item\", \"Luxury Car\", time() + 2 * 24 * 60 * 60);?><html><body> <?php setcookie(\"Auction_Item\", \"\", time() - 60); ?> <?php echo \"cookie is deleted\" ?> <p> <strong>Note:</strong> You might have to reload the page to see the value of the cookie. </p> </body></html>", "e": 45409, "s": 45049, "text": null }, { "code": null, "e": 45417, "s": 45409, "text": "Output:" }, { "code": null, "e": 45437, "s": 45417, "text": "Deleting the Cookie" }, { "code": null, "e": 45455, "s": 45437, "text": "Important Points:" }, { "code": null, "e": 45595, "s": 45455, "text": "If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end of the session i.e. when the browser closes." }, { "code": null, "e": 45746, "s": 45595, "text": "The same path, domain, and other arguments should be passed that were used to create the cookie in order to ensure that the correct cookie is deleted." }, { "code": null, "e": 45915, "s": 45746, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 45936, "s": 45915, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 45948, "s": 45936, "text": "PHP-session" }, { "code": null, "e": 45952, "s": 45948, "text": "PHP" }, { "code": null, "e": 45969, "s": 45952, "text": "Web Technologies" }, { "code": null, "e": 45973, "s": 45969, "text": "PHP" }, { "code": null, "e": 46071, "s": 45973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46116, "s": 46071, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 46166, "s": 46116, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 46190, "s": 46166, "text": "PHP in_array() Function" }, { "code": null, "e": 46234, "s": 46190, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 46274, "s": 46234, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 46316, "s": 46274, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 46349, "s": 46316, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46392, "s": 46349, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 46454, "s": 46392, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How do you properly ignore Exceptions in Python?
This can be done by following codes try: x,y =7,0 z = x/y except: pass OR try: x,y =7,0 z = x/y except Exception: pass These codes bypass the exception in the try statement and ignore the except clause and don’t raise any exception. The difference in the above codes is that the first one will also catch KeyboardInterrupt, SystemExit etc, which are derived directly from exceptions.BaseException, not exceptions.Exception. It is known that the last thrown exception is remembered in Python, some of the objects involved in the exception-throwing statement are kept live until the next exception. We might want to do the following instead of just pass: try: x,y =7,0 z = x/y except Exception: sys.exc_clear() This clears the last thrown exception
[ { "code": null, "e": 1098, "s": 1062, "text": "This can be done by following codes" }, { "code": null, "e": 1133, "s": 1098, "text": "try:\nx,y =7,0\nz = x/y\nexcept:\npass" }, { "code": null, "e": 1136, "s": 1133, "text": "OR" }, { "code": null, "e": 1181, "s": 1136, "text": "try:\nx,y =7,0\nz = x/y\nexcept Exception:\npass" }, { "code": null, "e": 1295, "s": 1181, "text": "These codes bypass the exception in the try statement and ignore the except clause and don’t raise any exception." }, { "code": null, "e": 1486, "s": 1295, "text": "The difference in the above codes is that the first one will also catch KeyboardInterrupt, SystemExit etc, which are derived directly from exceptions.BaseException, not exceptions.Exception." }, { "code": null, "e": 1715, "s": 1486, "text": "It is known that the last thrown exception is remembered in Python, some of the objects involved in the exception-throwing statement are kept live until the next exception. We might want to do the following instead of just pass:" }, { "code": null, "e": 1771, "s": 1715, "text": "try:\nx,y =7,0\nz = x/y\nexcept Exception:\nsys.exc_clear()" }, { "code": null, "e": 1809, "s": 1771, "text": "This clears the last thrown exception" } ]
Downloading Kaggle datasets directly into Google Colab | by Anna D'Angela | Towards Data Science
There are many perks to working in Google Colaboratory, or “Colab” for short, for data science projects. For those like me, who are plugging away on an older laptop — the main highlight is the free access to accelerated hardware GPU/TPU for larger projects. For the Phase 4 Project of my data science boot camp, I set out to build an image classifier to aide in diagnosing pneumonia from chest X-rays. Excited to embark on my first computer vision assignment (cue laser eyes), I hurried over to Kaggle to download the dataset. My computer informed me it would take 4 hours to download the zip file of almost 6,000 JPEGs. Oh no. As I watched the “estimated time remaining” continue to increase, I began to fill with dread about what this bode for the upcoming model training times. In the tenet of the greyscale society trapped in infomercials: “There’s gotta be a better way!” Enter Google Colab. Set up to run Python in a similar user style as Jupyter, Colab is optimized to assist with high processing needs by providing access to hosted GPU/TPU (see more here about runtimes). All you need to get started is a Google account. Your Colab notebooks will be saved in your Google Drive, but to access your files from Colab you will need to connect to (or ‘mount’) your Drive into your notebook at the start of each session. Colab’s virtual machine operates out of the ‘content’ folder (shown left). Any data you wish to work with during your session should be stored in this folder. To keep the servers available for the maximum amount of users there are limits to usage at a free or paid tier: The kernel will time out after 30 minutes of inactively — meaning all variables will need to be reloaded. The entire contents of the virtual machine ( ‘/content’) will be cleared after 12 hours. Thus, the data will need to be reimported at the start of each 12 hour stretch. For about $10 monthly, the kernel inactivity time-out will increase to 90 minutes. The contents of the virtual machine will now be cleared after 24 hours. Alright, I’ve got my driving gloves on and seatbelt buckled. I am ready to go full throttle. But how do I get my data into Colab when I can barely get it onto my computer? One solution is to download the data directly from Kaggle into Colab — bypassing my local computer entirely. Since Colab clears all data from ‘/content’ after 12/24 hours, I will download the dataset into my Google Drive for storage (and access from anywhere). I will also need to add some code to the top of my Colab project notebook to load it in from Drive for each session. The most efficient way to do this, is to keep the file on Drive in its compressed, zipped state. Even though they are both Google external machines, they do not operate on the same servers. You will need to copy the zip file from Drive to the Colab virtual machine (‘/content’) at the start of each new session and unzip it there. Otherwise, you will need to load in each, individual file from Drive — and didn’t we arrive here for speed? Once everything has been configured properly it is quite simple and quick to use. Below is the code to get it set up. First, you must collect your Kaggle API access token. Navigate to your Kaggle profile ‘Account’ page. Under your ‘Email Preferences’ you will find the button to ‘Create’ your API token. Click the button to download your token as a JSON file containing your username and key.Create a folder for Kaggle in your Google Drive. Save a copy of the API token as a private file in this folder so you can access it easily from the virtual machine.Fire up a Colab notebook and establish a connection to your Drive. You will be prompted to login to your Google account and copy a validation token each time you connect to Drive from Colab. After establishing the connection, you will see a new folder appear in the side bar as ‘/gdrive’ (or whatever you choose to name it). First, you must collect your Kaggle API access token. Navigate to your Kaggle profile ‘Account’ page. Under your ‘Email Preferences’ you will find the button to ‘Create’ your API token. Click the button to download your token as a JSON file containing your username and key. Create a folder for Kaggle in your Google Drive. Save a copy of the API token as a private file in this folder so you can access it easily from the virtual machine. Fire up a Colab notebook and establish a connection to your Drive. You will be prompted to login to your Google account and copy a validation token each time you connect to Drive from Colab. After establishing the connection, you will see a new folder appear in the side bar as ‘/gdrive’ (or whatever you choose to name it). # Mount google drivefrom google.colab import drivedrive.mount('/gdrive') 4. Configure a ‘Kaggle Environment’ using OS. This will store the API key and value as an OS environ object/variable. When you run Kaggle terminal commands (in the next step), your machine will be linked to your account through your API token. Linking to the private directory in your Drive ensures that your token information will remain hidden to those you may choose to share notebooks with. # Import OS for navigation and environment set upimport os# Check current location, '/content' is the Colab virtual machineos.getcwd()# Enable the Kaggle environment, use the path to the directory your Kaggle API JSON is stored inos.environ['KAGGLE_CONFIG_DIR'] = '../gdrive/MyDrive/kaggle' This can be done one time in a seperate notebook. Once downloaded, you can store the data as long as needed on your Drive. Install the Kaggle library to enable Kaggle terminal commands (such as downloading data or kernels, see official documentation). Install the Kaggle library to enable Kaggle terminal commands (such as downloading data or kernels, see official documentation). !pip install kaggle 2. Go to the competition page for your data. Copy the pre-formatted API command from the dataset page you wish to download (for example, this Xray image set). 3. Navigate into the directory where you would like to store the data. Paste the API command. Keep the file zipped to save space on your Drive and to import to Colab more efficiently. # Navigate into Drive where you want to store your Kaggle dataos.chdir('../gdrive/MyDrive/kaggle')# Paste and run the copied API command, the data will download to the current directory!kaggle datasets download -d paultimothymooney/chest-xray-pneumonia# Check contents of directory, you should see the .zip file for the competition in your Driveos.listdir() When you are ready to use the data in Colab, you will need to copy it from long term storage location on your Drive (‘/gdrive/’) to the temporary virtual machine ('/content') at the start of each session. In the project notebook where you will be using the data, mount a connection to Drive as shown above.Copy the compressed file to the virtual machine and unzip it to access the data. Do not remove the original zip from your Drive after copying. You will need to copy it at the start of each session while working with Colab. In the project notebook where you will be using the data, mount a connection to Drive as shown above. Copy the compressed file to the virtual machine and unzip it to access the data. Do not remove the original zip from your Drive after copying. You will need to copy it at the start of each session while working with Colab. # Complete path to storage location of the .zip file of datazip_path = '../gdrive/MyDrive/kaggle/chest-xray-pneumonia.zip'# Check current directory (be sure you're in the directory where Colab operates: '/content')os.getcwd()# Copy the .zip file into the present directory!cp '{zip_path}' .# Unzip quietly !unzip -q 'chest-xray-pneumonia.zip'# View the unzipped contents in the virtual machineos.listdir() You will be able to use this unzipped data with the Colab accelerated GPU/TPU for up to 12 hours (if free access) or 24 hours (if PRO). You can reload it from Drive as many times as needed. I was able to train TensorFlow CNN models for image classification in minutes using Google Colab. Downloading the data directly into Google Drive allowed me to spare memory on my machine and bypass a treacherous download time. Once stored on Drive, it was easy to import the data into Colab. All the time saved could be spent trying out additional model architecture or browsing the internet for pygmy versions of your favorite animals. Goodbye tedious fit times of the past, hello accelerated machines! Thank you for reading my post! View my boot camp journey and my complete computer vision analysis on my GitHub.
[ { "code": null, "e": 430, "s": 172, "text": "There are many perks to working in Google Colaboratory, or “Colab” for short, for data science projects. For those like me, who are plugging away on an older laptop — the main highlight is the free access to accelerated hardware GPU/TPU for larger projects." }, { "code": null, "e": 1049, "s": 430, "text": "For the Phase 4 Project of my data science boot camp, I set out to build an image classifier to aide in diagnosing pneumonia from chest X-rays. Excited to embark on my first computer vision assignment (cue laser eyes), I hurried over to Kaggle to download the dataset. My computer informed me it would take 4 hours to download the zip file of almost 6,000 JPEGs. Oh no. As I watched the “estimated time remaining” continue to increase, I began to fill with dread about what this bode for the upcoming model training times. In the tenet of the greyscale society trapped in infomercials: “There’s gotta be a better way!”" }, { "code": null, "e": 1495, "s": 1049, "text": "Enter Google Colab. Set up to run Python in a similar user style as Jupyter, Colab is optimized to assist with high processing needs by providing access to hosted GPU/TPU (see more here about runtimes). All you need to get started is a Google account. Your Colab notebooks will be saved in your Google Drive, but to access your files from Colab you will need to connect to (or ‘mount’) your Drive into your notebook at the start of each session." }, { "code": null, "e": 1654, "s": 1495, "text": "Colab’s virtual machine operates out of the ‘content’ folder (shown left). Any data you wish to work with during your session should be stored in this folder." }, { "code": null, "e": 1766, "s": 1654, "text": "To keep the servers available for the maximum amount of users there are limits to usage at a free or paid tier:" }, { "code": null, "e": 1872, "s": 1766, "text": "The kernel will time out after 30 minutes of inactively — meaning all variables will need to be reloaded." }, { "code": null, "e": 2041, "s": 1872, "text": "The entire contents of the virtual machine ( ‘/content’) will be cleared after 12 hours. Thus, the data will need to be reimported at the start of each 12 hour stretch." }, { "code": null, "e": 2196, "s": 2041, "text": "For about $10 monthly, the kernel inactivity time-out will increase to 90 minutes. The contents of the virtual machine will now be cleared after 24 hours." }, { "code": null, "e": 2477, "s": 2196, "text": "Alright, I’ve got my driving gloves on and seatbelt buckled. I am ready to go full throttle. But how do I get my data into Colab when I can barely get it onto my computer? One solution is to download the data directly from Kaggle into Colab — bypassing my local computer entirely." }, { "code": null, "e": 3185, "s": 2477, "text": "Since Colab clears all data from ‘/content’ after 12/24 hours, I will download the dataset into my Google Drive for storage (and access from anywhere). I will also need to add some code to the top of my Colab project notebook to load it in from Drive for each session. The most efficient way to do this, is to keep the file on Drive in its compressed, zipped state. Even though they are both Google external machines, they do not operate on the same servers. You will need to copy the zip file from Drive to the Colab virtual machine (‘/content’) at the start of each new session and unzip it there. Otherwise, you will need to load in each, individual file from Drive — and didn’t we arrive here for speed?" }, { "code": null, "e": 3303, "s": 3185, "text": "Once everything has been configured properly it is quite simple and quick to use. Below is the code to get it set up." }, { "code": null, "e": 4066, "s": 3303, "text": "First, you must collect your Kaggle API access token. Navigate to your Kaggle profile ‘Account’ page. Under your ‘Email Preferences’ you will find the button to ‘Create’ your API token. Click the button to download your token as a JSON file containing your username and key.Create a folder for Kaggle in your Google Drive. Save a copy of the API token as a private file in this folder so you can access it easily from the virtual machine.Fire up a Colab notebook and establish a connection to your Drive. You will be prompted to login to your Google account and copy a validation token each time you connect to Drive from Colab. After establishing the connection, you will see a new folder appear in the side bar as ‘/gdrive’ (or whatever you choose to name it)." }, { "code": null, "e": 4341, "s": 4066, "text": "First, you must collect your Kaggle API access token. Navigate to your Kaggle profile ‘Account’ page. Under your ‘Email Preferences’ you will find the button to ‘Create’ your API token. Click the button to download your token as a JSON file containing your username and key." }, { "code": null, "e": 4506, "s": 4341, "text": "Create a folder for Kaggle in your Google Drive. Save a copy of the API token as a private file in this folder so you can access it easily from the virtual machine." }, { "code": null, "e": 4831, "s": 4506, "text": "Fire up a Colab notebook and establish a connection to your Drive. You will be prompted to login to your Google account and copy a validation token each time you connect to Drive from Colab. After establishing the connection, you will see a new folder appear in the side bar as ‘/gdrive’ (or whatever you choose to name it)." }, { "code": null, "e": 4904, "s": 4831, "text": "# Mount google drivefrom google.colab import drivedrive.mount('/gdrive')" }, { "code": null, "e": 5299, "s": 4904, "text": "4. Configure a ‘Kaggle Environment’ using OS. This will store the API key and value as an OS environ object/variable. When you run Kaggle terminal commands (in the next step), your machine will be linked to your account through your API token. Linking to the private directory in your Drive ensures that your token information will remain hidden to those you may choose to share notebooks with." }, { "code": null, "e": 5590, "s": 5299, "text": "# Import OS for navigation and environment set upimport os# Check current location, '/content' is the Colab virtual machineos.getcwd()# Enable the Kaggle environment, use the path to the directory your Kaggle API JSON is stored inos.environ['KAGGLE_CONFIG_DIR'] = '../gdrive/MyDrive/kaggle'" }, { "code": null, "e": 5713, "s": 5590, "text": "This can be done one time in a seperate notebook. Once downloaded, you can store the data as long as needed on your Drive." }, { "code": null, "e": 5842, "s": 5713, "text": "Install the Kaggle library to enable Kaggle terminal commands (such as downloading data or kernels, see official documentation)." }, { "code": null, "e": 5971, "s": 5842, "text": "Install the Kaggle library to enable Kaggle terminal commands (such as downloading data or kernels, see official documentation)." }, { "code": null, "e": 5991, "s": 5971, "text": "!pip install kaggle" }, { "code": null, "e": 6150, "s": 5991, "text": "2. Go to the competition page for your data. Copy the pre-formatted API command from the dataset page you wish to download (for example, this Xray image set)." }, { "code": null, "e": 6334, "s": 6150, "text": "3. Navigate into the directory where you would like to store the data. Paste the API command. Keep the file zipped to save space on your Drive and to import to Colab more efficiently." }, { "code": null, "e": 6692, "s": 6334, "text": "# Navigate into Drive where you want to store your Kaggle dataos.chdir('../gdrive/MyDrive/kaggle')# Paste and run the copied API command, the data will download to the current directory!kaggle datasets download -d paultimothymooney/chest-xray-pneumonia# Check contents of directory, you should see the .zip file for the competition in your Driveos.listdir()" }, { "code": null, "e": 6897, "s": 6692, "text": "When you are ready to use the data in Colab, you will need to copy it from long term storage location on your Drive (‘/gdrive/’) to the temporary virtual machine ('/content') at the start of each session." }, { "code": null, "e": 7221, "s": 6897, "text": "In the project notebook where you will be using the data, mount a connection to Drive as shown above.Copy the compressed file to the virtual machine and unzip it to access the data. Do not remove the original zip from your Drive after copying. You will need to copy it at the start of each session while working with Colab." }, { "code": null, "e": 7323, "s": 7221, "text": "In the project notebook where you will be using the data, mount a connection to Drive as shown above." }, { "code": null, "e": 7546, "s": 7323, "text": "Copy the compressed file to the virtual machine and unzip it to access the data. Do not remove the original zip from your Drive after copying. You will need to copy it at the start of each session while working with Colab." }, { "code": null, "e": 7952, "s": 7546, "text": "# Complete path to storage location of the .zip file of datazip_path = '../gdrive/MyDrive/kaggle/chest-xray-pneumonia.zip'# Check current directory (be sure you're in the directory where Colab operates: '/content')os.getcwd()# Copy the .zip file into the present directory!cp '{zip_path}' .# Unzip quietly !unzip -q 'chest-xray-pneumonia.zip'# View the unzipped contents in the virtual machineos.listdir()" }, { "code": null, "e": 8142, "s": 7952, "text": "You will be able to use this unzipped data with the Colab accelerated GPU/TPU for up to 12 hours (if free access) or 24 hours (if PRO). You can reload it from Drive as many times as needed." }, { "code": null, "e": 8646, "s": 8142, "text": "I was able to train TensorFlow CNN models for image classification in minutes using Google Colab. Downloading the data directly into Google Drive allowed me to spare memory on my machine and bypass a treacherous download time. Once stored on Drive, it was easy to import the data into Colab. All the time saved could be spent trying out additional model architecture or browsing the internet for pygmy versions of your favorite animals. Goodbye tedious fit times of the past, hello accelerated machines!" } ]
DB2 - Sequences
This chapter introduces you to the concept of sequence, creation of sequence, viewing the sequence, and dropping them. A sequence is a software function that generates integer numbers in either ascending or descending order, within a definite range, to generate primary key and coordinate other keys among the table. You use sequence for availing integer numbers say, for employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER, and DECIMAL data types. A sequence can be shared among multiple applications. A sequence is incremented or decremented irrespective of transactions. A sequence is created by CREATE SEQUENCE statement. There are two type of sequences available: NEXTVAL: It returns an incremented value for a sequence number. NEXTVAL: It returns an incremented value for a sequence number. PREVIOUS VALUE: It returns recently generated value. PREVIOUS VALUE: It returns recently generated value. The following parameters are used for sequences: Data type: This is the data type of the returned incremented value. (SMALLINT, BIGINT, INTEGER, NUMBER, DOUBLE) START WITH: The reference value, with which the sequence starts. MINVALUE: A minimum value for a sequence to start with. MAXVALUE: A maximum value for a sequence. INCREMENT BY: step value by which a sequence is incremented. Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly. The sequence generation is conducted by referring the returned value, which is stored into the database by previous sequence generation. You can create sequence using the following syntax: Syntax: db2 create sequence <seq_name> Example: [To create a new sequence with the name ‘sales1_seq’ and increasing values from 1] db2 create sequence sales1_seq as int start with 1 increment by 1 You can view a sequence using the syntax given below: Syntax: db2 value <previous/next> value for <seq_name> Example: [To see list of previous updated value in sequence ‘sales1_seq’] db2 values previous value for sales1_seq Output: 1 ----------- 4 1 record(s) selected. To remove the sequence, you need to use the “DROP SEQUENCE ” command. Here is how you do it: Syntax: db2 drop sequence <seq_name>> Example: [To drop sequence ‘sales1_seq’ from database] db2 drop sequence sales1_seq Output: DB20000I The SQL command completed successfully. 10 Lectures 1.5 hours Nishant Malik 41 Lectures 8.5 hours Parth Panjabi 53 Lectures 11.5 hours Parth Panjabi 33 Lectures 7 hours Parth Panjabi 44 Lectures 3 hours Arnab Chakraborty 178 Lectures 14.5 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2047, "s": 1928, "text": "This chapter introduces you to the concept of sequence, creation of sequence, viewing the sequence, and dropping them." }, { "code": null, "e": 2530, "s": 2047, "text": "A sequence is a software function that generates integer numbers in either ascending or descending order, within a definite range, to generate primary key and coordinate other keys among the table. You use sequence for availing integer numbers say, for employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER, and DECIMAL data types. A sequence can be shared among multiple applications. A sequence is incremented or decremented irrespective of transactions." }, { "code": null, "e": 2582, "s": 2530, "text": "A sequence is created by CREATE SEQUENCE statement." }, { "code": null, "e": 2625, "s": 2582, "text": "There are two type of sequences available:" }, { "code": null, "e": 2689, "s": 2625, "text": "NEXTVAL: It returns an incremented value for a sequence number." }, { "code": null, "e": 2753, "s": 2689, "text": "NEXTVAL: It returns an incremented value for a sequence number." }, { "code": null, "e": 2806, "s": 2753, "text": "PREVIOUS VALUE: It returns recently generated value." }, { "code": null, "e": 2859, "s": 2806, "text": "PREVIOUS VALUE: It returns recently generated value." }, { "code": null, "e": 2908, "s": 2859, "text": "The following parameters are used for sequences:" }, { "code": null, "e": 3020, "s": 2908, "text": "Data type: This is the data type of the returned incremented value. (SMALLINT, BIGINT, INTEGER, NUMBER, DOUBLE)" }, { "code": null, "e": 3085, "s": 3020, "text": "START WITH: The reference value, with which the sequence starts." }, { "code": null, "e": 3141, "s": 3085, "text": "MINVALUE: A minimum value for a sequence to start with." }, { "code": null, "e": 3183, "s": 3141, "text": "MAXVALUE: A maximum value for a sequence." }, { "code": null, "e": 3244, "s": 3183, "text": "INCREMENT BY: step value by which a sequence is incremented." }, { "code": null, "e": 3462, "s": 3244, "text": "Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly. The sequence generation is conducted by referring the returned value, which is stored into the database by previous sequence generation." }, { "code": null, "e": 3514, "s": 3462, "text": "You can create sequence using the following syntax:" }, { "code": null, "e": 3522, "s": 3514, "text": "Syntax:" }, { "code": null, "e": 3554, "s": 3522, "text": "db2 create sequence <seq_name> " }, { "code": null, "e": 3646, "s": 3554, "text": "Example: [To create a new sequence with the name ‘sales1_seq’ and increasing values from 1]" }, { "code": null, "e": 3715, "s": 3646, "text": "db2 create sequence sales1_seq as int start \nwith 1 increment by 1 " }, { "code": null, "e": 3769, "s": 3715, "text": "You can view a sequence using the syntax given below:" }, { "code": null, "e": 3777, "s": 3769, "text": "Syntax:" }, { "code": null, "e": 3824, "s": 3777, "text": "db2 value <previous/next> value for <seq_name>" }, { "code": null, "e": 3898, "s": 3824, "text": "Example: [To see list of previous updated value in sequence ‘sales1_seq’]" }, { "code": null, "e": 3941, "s": 3898, "text": "db2 values previous value for sales1_seq " }, { "code": null, "e": 3949, "s": 3941, "text": "Output:" }, { "code": null, "e": 3996, "s": 3949, "text": " 1 \n----------- \n 4 \n 1 record(s) selected. " }, { "code": null, "e": 4089, "s": 3996, "text": "To remove the sequence, you need to use the “DROP SEQUENCE ” command. Here is how you do it:" }, { "code": null, "e": 4097, "s": 4089, "text": "Syntax:" }, { "code": null, "e": 4127, "s": 4097, "text": "db2 drop sequence <seq_name>>" }, { "code": null, "e": 4182, "s": 4127, "text": "Example: [To drop sequence ‘sales1_seq’ from database]" }, { "code": null, "e": 4213, "s": 4182, "text": "db2 drop sequence sales1_seq " }, { "code": null, "e": 4221, "s": 4213, "text": "Output:" }, { "code": null, "e": 4272, "s": 4221, "text": " DB20000I The SQL command completed successfully. " }, { "code": null, "e": 4307, "s": 4272, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4322, "s": 4307, "text": " Nishant Malik" }, { "code": null, "e": 4357, "s": 4322, "text": "\n 41 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4372, "s": 4357, "text": " Parth Panjabi" }, { "code": null, "e": 4408, "s": 4372, "text": "\n 53 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4423, "s": 4408, "text": " Parth Panjabi" }, { "code": null, "e": 4456, "s": 4423, "text": "\n 33 Lectures \n 7 hours \n" }, { "code": null, "e": 4471, "s": 4456, "text": " Parth Panjabi" }, { "code": null, "e": 4504, "s": 4471, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 4523, "s": 4504, "text": " Arnab Chakraborty" }, { "code": null, "e": 4560, "s": 4523, "text": "\n 178 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4579, "s": 4560, "text": " Arnab Chakraborty" }, { "code": null, "e": 4586, "s": 4579, "text": " Print" }, { "code": null, "e": 4597, "s": 4586, "text": " Add Notes" } ]
Regular Expressions : Using the “re” Module to Extract Information From Strings | by Muriel Kosaka | Towards Data Science
Regular Expressions, also known as Regex, comes in handy in a multitude of text processing scenarios. You can search for patterns of numbers, letters, punctuation, and even whitespace. Regex is fast and helps avoid unnecessary loops in your program to match and extract desired information. Until recently I felt that Regex was very complicated, the syntax looks frustrating and thought that I would not be able to learn about it. As with many others, we share this same feeling. After reading many resources online, I’ve decided to use this post to show how you can use the “re” module in Python to solve certain problems through the findall() function and briefly introduce match(), and search() functions; all are similar, but have different uses. To start using Regex in Python, you first need to import Python’s “re” module import re This post is divided into three sections, reviewing three simple functions to extract useful information from strings with examples. findall() match() search() Regex’s findall() function is extremely useful as it returns a list of strings containing all matches. If the pattern is not found, re.findall() returns an empty list. Let’s see when we can use the findall() function! Extract all occurrences of specific words Extract all occurrences of specific words Using the following text paragraph, which describes how Rey, an African penguin and Rosa, the oldest sea otter at the Monterey Bay Aquarium, require eye drops. aquarium='Because of problems with her eyesight, rey the African penguin had issues with swimming. That’s unusual for a penguin, and presented a big challenge for our aviculture team to help Rey overcome her hesitancy. Slowly and steadily, we trained her to be comfortable feeding in the water like the rest of the penguin colony. The aviculturists also trained Rey to accept daily eye drops from them as part of her special health care. Rey already had good relationships with some staff, and was comfortable with them handling her. Senior Aviculturist Kim Fukuda says the team built on those bonds to get Rey used to receiving the eye drops. "She knows the routine," Kim says. "I usually give her the eye drops in one area of the exhibit after all the penguins get their vitamins. When that happens, she runs over there and waits for me." Rosa, our oldest sea otter, has very limited eyesight, among other health issues. The sea otter team had already trained Rosa so they could examine her eyes, and built on that trust to include administering the eye drops she needs.' Now, you want to extract all occurrences of Rey from the text, for which you would do something like this: rey_occurences = "Rey"re.findall(rey_occurences, aquarium)# Output['Rey', 'Rey', 'Rey', 'Rey'] The findall() function takes two parameters, the first is the pattern being searched, in our case, rey_occurrences and the second parameter is text we are searching through, in our case, aquarium. As you can see, this function returns all the non-overlapping matches of the pattern which is in the rey_occurrences variables, from the second parameter aquarium. But wait, there is one more rey that was not accounted for. This happened because by default, regular expressions are case sensitive so our findall() function did not return “rey” because it is lowercase and not uppercase as it was defined in the rey_occurrences variables. We can edit our previous code so that it includes lowercase values of the pattern being searched by including a third parameter, flags, which can be used for a variety of reasons such as allowing patterns to match specific lines instead of the whole text, match patterns spanning over multiple lines, and do case-insensitive matching. For our purposes, we will be using the re.IGNORECASE flag to ignore the case while performing the search. rey_occurences = "Rey"re.findall(rey_occurences,aquarium,flags=re.IGNORECASE)# Output['rey', 'Rey', 'Rey', 'Rey', 'Rey'] We can also search multiple patterns and extract all occurrences of those patterns. With our current text, let’s also search for occurrences of “Rosa” by simply using the | operator to create the pattern. sea_animals="Rey|Rosa"re.findall(sea_animals,aquarium,flags=re.IGNORECASE)# Output['rey', 'Rey', 'Rey', 'Rey', 'Rey', 'Rosa', 'Rosa'] the | operator is a special character that tells Regex to search for pattern one or pattern two in the text. If you wanted to search for the occurrence of “|” in your text, you would need to add it in your pattern with a backslash, “ \| ”. This backslash tells Regex to read the | operator as a character without inferencing its special meaning. 2. Extracting words that only contain alphabets Let’s say you have a text document that contains numbers and words such as: gifts = "\Basketball 2 25.63\Tshirt 4 53.92\Sneakers 1 30.58\Mask 10 80.54\GiftCard 2 50.00" And let’s say that you want to extract only the words; we can do this by using Regex’s special sequences and sets to specify the pattern we are looking for. This helpful site provides a nice Regex cheatsheet. words = '[a-z]+'re.findall(words,gifts,flags=re.IGNORECASE)# Output['Basketball', 'Tshirt', 'Sneakers', 'Mask', 'GiftCard'] By setting our pattern to [a-z], this signifies a class of characters from “a” to “z”, while the + operator matches one or more repetitions of the preceding regular expression or class, which is [a-z] in our case. Notice that the [a-z] pattern still returned the uppercase letters, this is because of our re.IGNORECASE flag. 3. Extracting all occurrences of numbers We’ve only shown extracting words from text, can we also extract numbers? Of course, using the regular expressions from another helpful cheat sheet, we are able to extract numbers from the given text: text = "Sixty-six undergraduate students from an urban college in New York City participated in this study. Students participated in this research study as part of a requirement for a class. Nineteen participants were excluded from the study for meeting one or more exclusion criteria including not completing the sentence unscrambling task, not providing ratings for each of the traits, or failing either one of the two attention checks, leaving the total number of eligible participants at forty-seven. Participants included 36 women aged 18 to 52 years old (M = 20.52, SD = 6.97), 10 men aged 18 to 28 years old (M = 23.5, SD = 12.36), and one individual who did not disclose their sex."numbers="\d+"re.findall(numbers,text)# Output['36', '18','52','20', '52','6','97','10','18','28','23','5','12','36'] By setting our pattern to \d, this signifies to one digit, while the + operator will include repetitions of digits. As you can see from our text, we also have decimals, but from our output they were separated by the “.” We can correct this by using the following regular expression: all_numbers="\d+\.*?\d+"re.findall(all_numbers,text)# Output['36', '18', '52', '20.52', '6.97', '10', '18', '28', '23.5', '12.36'] As we saw previously, having the pattern \d+ will capture one dight followed by repetitions of digits, to include decimals, we use the pattern .*? will search for a match using as few characters as possible. 4. Extracting words that are followed by a specific pattern With text data, there may be times where you need to extract words that are followed by a special character such as @ for usernames or quotes within the given text. From our aquarium text, there are two quotes within the text, let’s extract these from the text. quotes='"(.*?)"'re.findall(quotes,aquarium)# Output['She knows the routine,', 'I usually give her the eye drops in one area of the exhibit after all the penguins get their vitamins. When that happens, she runs over there and waits for me.'] We set our pattern to ‘“(.+?)”’, where the single quotes represent the text body, while the double quotes represent the quotes within the text. We have the parenthesis which creates a capture group and .*? is a non-greedy moderator and only extracts the quotes and not the text between the quotes. As you can see, the findall() function of the Python’s Regex module can be very useful when searching for a list with all the necessary matches. This function is sometimes confused with the match() and search() function of the same module. Let’s briefly discuss the difference. While re.findall() returns matches of a substring found in a text, re.match() searches only from the beginning of a string and returns match object if found. However, if a match is found somewhere in the middle of the string, it returns none. The expression “w+” and “\W” will match the words starting with letter ‘r’ and thereafter, anything which is not started with ‘r’ is not identified. To check match for each element in the list or string, we run aforloop in this Python re.match() example: list = ["red rose", "ruby red", "pink peony"]# Loop.for element in list: m = re.match("(r\w+)\W(r\w+)", element)if m: print(m.groups())# Output('red', 'rose')('ruby', 'red') The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re.match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned. patterns=['penguin','Rosa']aquarium_short="Because of problems with her eyesight, rey the African penguin had issues with swimming."for pattern in patterns: print('Looking for "%s" in "%s" = '% (pattern, aquarium_short), end=" ") if re.search(pattern, aquarium_short): print("Match was found") else: print("No match was found")# OutputLooking for "penguin" in "Because of problems with her eyesight, rey the African penguin had issues with swimming." = Match was foundLooking for "Rosa" in "Because of problems with her eyesight, rey the African penguin had issues with swimming." = No match was found In this example, we looked for two strings, “penguin” and “Rosa” in a text string “Because of problems with her eyesight, rey the African penguin had issues with swimming.” For “penguin” we found the match hence it returns the output “Match was found”, while the word “Rosa” was not found in the string and returns “No match was found.” While re.search() looks for the first occurrence of a match in a string, re.findall() searches for all occurrences of a match, and re.search() matches at the beginning of a string and not at the beginning of each line. For additional operations that can be used with Python’s Regex module, please refer to the documentation. docs.python.org I hope this was helpful! Thank you for reading! :)
[ { "code": null, "e": 652, "s": 172, "text": "Regular Expressions, also known as Regex, comes in handy in a multitude of text processing scenarios. You can search for patterns of numbers, letters, punctuation, and even whitespace. Regex is fast and helps avoid unnecessary loops in your program to match and extract desired information. Until recently I felt that Regex was very complicated, the syntax looks frustrating and thought that I would not be able to learn about it. As with many others, we share this same feeling." }, { "code": null, "e": 923, "s": 652, "text": "After reading many resources online, I’ve decided to use this post to show how you can use the “re” module in Python to solve certain problems through the findall() function and briefly introduce match(), and search() functions; all are similar, but have different uses." }, { "code": null, "e": 1001, "s": 923, "text": "To start using Regex in Python, you first need to import Python’s “re” module" }, { "code": null, "e": 1011, "s": 1001, "text": "import re" }, { "code": null, "e": 1144, "s": 1011, "text": "This post is divided into three sections, reviewing three simple functions to extract useful information from strings with examples." }, { "code": null, "e": 1154, "s": 1144, "text": "findall()" }, { "code": null, "e": 1162, "s": 1154, "text": "match()" }, { "code": null, "e": 1171, "s": 1162, "text": "search()" }, { "code": null, "e": 1389, "s": 1171, "text": "Regex’s findall() function is extremely useful as it returns a list of strings containing all matches. If the pattern is not found, re.findall() returns an empty list. Let’s see when we can use the findall() function!" }, { "code": null, "e": 1431, "s": 1389, "text": "Extract all occurrences of specific words" }, { "code": null, "e": 1473, "s": 1431, "text": "Extract all occurrences of specific words" }, { "code": null, "e": 1633, "s": 1473, "text": "Using the following text paragraph, which describes how Rey, an African penguin and Rosa, the oldest sea otter at the Monterey Bay Aquarium, require eye drops." }, { "code": null, "e": 2707, "s": 1633, "text": "aquarium='Because of problems with her eyesight, rey the African penguin had issues with swimming. That’s unusual for a penguin, and presented a big challenge for our aviculture team to help Rey overcome her hesitancy. Slowly and steadily, we trained her to be comfortable feeding in the water like the rest of the penguin colony. The aviculturists also trained Rey to accept daily eye drops from them as part of her special health care. Rey already had good relationships with some staff, and was comfortable with them handling her. Senior Aviculturist Kim Fukuda says the team built on those bonds to get Rey used to receiving the eye drops. \"She knows the routine,\" Kim says. \"I usually give her the eye drops in one area of the exhibit after all the penguins get their vitamins. When that happens, she runs over there and waits for me.\" Rosa, our oldest sea otter, has very limited eyesight, among other health issues. The sea otter team had already trained Rosa so they could examine her eyes, and built on that trust to include administering the eye drops she needs.'" }, { "code": null, "e": 2814, "s": 2707, "text": "Now, you want to extract all occurrences of Rey from the text, for which you would do something like this:" }, { "code": null, "e": 2909, "s": 2814, "text": "rey_occurences = \"Rey\"re.findall(rey_occurences, aquarium)# Output['Rey', 'Rey', 'Rey', 'Rey']" }, { "code": null, "e": 3270, "s": 2909, "text": "The findall() function takes two parameters, the first is the pattern being searched, in our case, rey_occurrences and the second parameter is text we are searching through, in our case, aquarium. As you can see, this function returns all the non-overlapping matches of the pattern which is in the rey_occurrences variables, from the second parameter aquarium." }, { "code": null, "e": 3985, "s": 3270, "text": "But wait, there is one more rey that was not accounted for. This happened because by default, regular expressions are case sensitive so our findall() function did not return “rey” because it is lowercase and not uppercase as it was defined in the rey_occurrences variables. We can edit our previous code so that it includes lowercase values of the pattern being searched by including a third parameter, flags, which can be used for a variety of reasons such as allowing patterns to match specific lines instead of the whole text, match patterns spanning over multiple lines, and do case-insensitive matching. For our purposes, we will be using the re.IGNORECASE flag to ignore the case while performing the search." }, { "code": null, "e": 4106, "s": 3985, "text": "rey_occurences = \"Rey\"re.findall(rey_occurences,aquarium,flags=re.IGNORECASE)# Output['rey', 'Rey', 'Rey', 'Rey', 'Rey']" }, { "code": null, "e": 4311, "s": 4106, "text": "We can also search multiple patterns and extract all occurrences of those patterns. With our current text, let’s also search for occurrences of “Rosa” by simply using the | operator to create the pattern." }, { "code": null, "e": 4445, "s": 4311, "text": "sea_animals=\"Rey|Rosa\"re.findall(sea_animals,aquarium,flags=re.IGNORECASE)# Output['rey', 'Rey', 'Rey', 'Rey', 'Rey', 'Rosa', 'Rosa']" }, { "code": null, "e": 4791, "s": 4445, "text": "the | operator is a special character that tells Regex to search for pattern one or pattern two in the text. If you wanted to search for the occurrence of “|” in your text, you would need to add it in your pattern with a backslash, “ \\| ”. This backslash tells Regex to read the | operator as a character without inferencing its special meaning." }, { "code": null, "e": 4839, "s": 4791, "text": "2. Extracting words that only contain alphabets" }, { "code": null, "e": 4915, "s": 4839, "text": "Let’s say you have a text document that contains numbers and words such as:" }, { "code": null, "e": 5037, "s": 4915, "text": "gifts = \"\\Basketball 2 25.63\\Tshirt 4 53.92\\Sneakers 1 30.58\\Mask 10 80.54\\GiftCard 2 50.00\"" }, { "code": null, "e": 5246, "s": 5037, "text": "And let’s say that you want to extract only the words; we can do this by using Regex’s special sequences and sets to specify the pattern we are looking for. This helpful site provides a nice Regex cheatsheet." }, { "code": null, "e": 5370, "s": 5246, "text": "words = '[a-z]+'re.findall(words,gifts,flags=re.IGNORECASE)# Output['Basketball', 'Tshirt', 'Sneakers', 'Mask', 'GiftCard']" }, { "code": null, "e": 5695, "s": 5370, "text": "By setting our pattern to [a-z], this signifies a class of characters from “a” to “z”, while the + operator matches one or more repetitions of the preceding regular expression or class, which is [a-z] in our case. Notice that the [a-z] pattern still returned the uppercase letters, this is because of our re.IGNORECASE flag." }, { "code": null, "e": 5736, "s": 5695, "text": "3. Extracting all occurrences of numbers" }, { "code": null, "e": 5937, "s": 5736, "text": "We’ve only shown extracting words from text, can we also extract numbers? Of course, using the regular expressions from another helpful cheat sheet, we are able to extract numbers from the given text:" }, { "code": null, "e": 6744, "s": 5937, "text": "text = \"Sixty-six undergraduate students from an urban college in New York City participated in this study. Students participated in this research study as part of a requirement for a class. Nineteen participants were excluded from the study for meeting one or more exclusion criteria including not completing the sentence unscrambling task, not providing ratings for each of the traits, or failing either one of the two attention checks, leaving the total number of eligible participants at forty-seven. Participants included 36 women aged 18 to 52 years old (M = 20.52, SD = 6.97), 10 men aged 18 to 28 years old (M = 23.5, SD = 12.36), and one individual who did not disclose their sex.\"numbers=\"\\d+\"re.findall(numbers,text)# Output['36', '18','52','20', '52','6','97','10','18','28','23','5','12','36']" }, { "code": null, "e": 7027, "s": 6744, "text": "By setting our pattern to \\d, this signifies to one digit, while the + operator will include repetitions of digits. As you can see from our text, we also have decimals, but from our output they were separated by the “.” We can correct this by using the following regular expression:" }, { "code": null, "e": 7158, "s": 7027, "text": "all_numbers=\"\\d+\\.*?\\d+\"re.findall(all_numbers,text)# Output['36', '18', '52', '20.52', '6.97', '10', '18', '28', '23.5', '12.36']" }, { "code": null, "e": 7366, "s": 7158, "text": "As we saw previously, having the pattern \\d+ will capture one dight followed by repetitions of digits, to include decimals, we use the pattern .*? will search for a match using as few characters as possible." }, { "code": null, "e": 7426, "s": 7366, "text": "4. Extracting words that are followed by a specific pattern" }, { "code": null, "e": 7591, "s": 7426, "text": "With text data, there may be times where you need to extract words that are followed by a special character such as @ for usernames or quotes within the given text." }, { "code": null, "e": 7688, "s": 7591, "text": "From our aquarium text, there are two quotes within the text, let’s extract these from the text." }, { "code": null, "e": 7929, "s": 7688, "text": "quotes='\"(.*?)\"'re.findall(quotes,aquarium)# Output['She knows the routine,', 'I usually give her the eye drops in one area of the exhibit after all the penguins get their vitamins. When that happens, she runs over there and waits for me.']" }, { "code": null, "e": 8227, "s": 7929, "text": "We set our pattern to ‘“(.+?)”’, where the single quotes represent the text body, while the double quotes represent the quotes within the text. We have the parenthesis which creates a capture group and .*? is a non-greedy moderator and only extracts the quotes and not the text between the quotes." }, { "code": null, "e": 8505, "s": 8227, "text": "As you can see, the findall() function of the Python’s Regex module can be very useful when searching for a list with all the necessary matches. This function is sometimes confused with the match() and search() function of the same module. Let’s briefly discuss the difference." }, { "code": null, "e": 8748, "s": 8505, "text": "While re.findall() returns matches of a substring found in a text, re.match() searches only from the beginning of a string and returns match object if found. However, if a match is found somewhere in the middle of the string, it returns none." }, { "code": null, "e": 9003, "s": 8748, "text": "The expression “w+” and “\\W” will match the words starting with letter ‘r’ and thereafter, anything which is not started with ‘r’ is not identified. To check match for each element in the list or string, we run aforloop in this Python re.match() example:" }, { "code": null, "e": 9187, "s": 9003, "text": "list = [\"red rose\", \"ruby red\", \"pink peony\"]# Loop.for element in list: m = re.match(\"(r\\w+)\\W(r\\w+)\", element)if m: print(m.groups())# Output('red', 'rose')('ruby', 'red')" }, { "code": null, "e": 9449, "s": 9187, "text": "The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re.match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned." }, { "code": null, "e": 10080, "s": 9449, "text": "patterns=['penguin','Rosa']aquarium_short=\"Because of problems with her eyesight, rey the African penguin had issues with swimming.\"for pattern in patterns: print('Looking for \"%s\" in \"%s\" = '% (pattern, aquarium_short), end=\" \") if re.search(pattern, aquarium_short): print(\"Match was found\") else: print(\"No match was found\")# OutputLooking for \"penguin\" in \"Because of problems with her eyesight, rey the African penguin had issues with swimming.\" = Match was foundLooking for \"Rosa\" in \"Because of problems with her eyesight, rey the African penguin had issues with swimming.\" = No match was found" }, { "code": null, "e": 10417, "s": 10080, "text": "In this example, we looked for two strings, “penguin” and “Rosa” in a text string “Because of problems with her eyesight, rey the African penguin had issues with swimming.” For “penguin” we found the match hence it returns the output “Match was found”, while the word “Rosa” was not found in the string and returns “No match was found.”" }, { "code": null, "e": 10742, "s": 10417, "text": "While re.search() looks for the first occurrence of a match in a string, re.findall() searches for all occurrences of a match, and re.search() matches at the beginning of a string and not at the beginning of each line. For additional operations that can be used with Python’s Regex module, please refer to the documentation." }, { "code": null, "e": 10758, "s": 10742, "text": "docs.python.org" } ]
How to create a plot using ggplot2 by including values greater than a certain value in R?
To create a plot using ggplot2 by excluding values greater than a certain value, we can use subsetting with single square brackets and which function. For example, if we have a data frame called df that contains two columns say x and y, then the point chart by including values of x that are greater than 0 can be created by using the command − ggplot(df[which(df$x>0),],aes(x,y))+geom_point() Consider the below data frame − Live Demo > x<-rnorm(20) > y<-rnorm(20) > df<-data.frame(x,y) > df x y 1 -0.62160328 0.38477515 2 0.68287365 -1.56169067 3 0.75259774 1.28849990 4 0.56688920 -0.17014225 5 1.22351113 -0.32446764 6 -1.54210099 0.29001967 7 0.08800284 1.34342269 8 1.77498480 -0.75239348 9 -0.31916824 0.24433868 10 0.09802049 -0.91107863 11 -1.63060088 0.05336120 12 0.01328284 -2.36494891 13 -1.69921881 -1.29001305 14 -0.02819300 -0.06126524 15 0.77405426 0.25468262 16 -0.36423968 0.79130216 17 0.26224330 0.10437648 18 0.31894879 -0.50317250 19 0.37739488 0.62952910 20 0.26141716 -0.97143860 Loading ggplot2 package and creating scatterplot between x and y − > library(ggplot2) > ggplot(df,aes(x,y))+geom_point() Creating scatterplot between x and y by including only x values that are greater than 0 − > ggplot(df[which(df$x>0),],aes(x,y))+geom_point()
[ { "code": null, "e": 1407, "s": 1062, "text": "To create a plot using ggplot2 by excluding values greater than a certain value, we can use subsetting with single square brackets and which function. For example, if we have a data frame called df that contains two columns say x and y, then the point chart by including values of x that are greater than 0 can be created by using the command −" }, { "code": null, "e": 1456, "s": 1407, "text": "ggplot(df[which(df$x>0),],aes(x,y))+geom_point()" }, { "code": null, "e": 1488, "s": 1456, "text": "Consider the below data frame −" }, { "code": null, "e": 1498, "s": 1488, "text": "Live Demo" }, { "code": null, "e": 1555, "s": 1498, "text": "> x<-rnorm(20)\n> y<-rnorm(20)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 2122, "s": 1555, "text": " x y\n1 -0.62160328 0.38477515\n2 0.68287365 -1.56169067\n3 0.75259774 1.28849990\n4 0.56688920 -0.17014225\n5 1.22351113 -0.32446764\n6 -1.54210099 0.29001967\n7 0.08800284 1.34342269\n8 1.77498480 -0.75239348\n9 -0.31916824 0.24433868\n10 0.09802049 -0.91107863\n11 -1.63060088 0.05336120\n12 0.01328284 -2.36494891\n13 -1.69921881 -1.29001305\n14 -0.02819300 -0.06126524\n15 0.77405426 0.25468262\n16 -0.36423968 0.79130216\n17 0.26224330 0.10437648\n18 0.31894879 -0.50317250\n19 0.37739488 0.62952910\n20 0.26141716 -0.97143860" }, { "code": null, "e": 2189, "s": 2122, "text": "Loading ggplot2 package and creating scatterplot between x and y −" }, { "code": null, "e": 2243, "s": 2189, "text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2333, "s": 2243, "text": "Creating scatterplot between x and y by including only x values that are greater than 0 −" }, { "code": null, "e": 2384, "s": 2333, "text": "> ggplot(df[which(df$x>0),],aes(x,y))+geom_point()" } ]
Java Examples - String unicode
How to determine the Unicode code point in string ? This example shows you how to use codePointBefore() method to return the character (Unicode code point) before the specified index. public class StringUniCode { public static void main(String[] args) { String test_string = "Welcome to TutorialsPoint"; System.out.println("String under test is = "+test_string); System.out.println("Unicode code point at" +" position 5 in the string is = " + test_string.codePointBefore(5)); } } The above code sample will produce the following result. String under test is = Welcome to TutorialsPoint Unicode code point at position 5 in the string is =111 Print Add Notes Bookmark this page
[ { "code": null, "e": 2120, "s": 2068, "text": "How to determine the Unicode code point in string ?" }, { "code": null, "e": 2252, "s": 2120, "text": "This example shows you how to use codePointBefore() method to return the character (Unicode code point) before the specified index." }, { "code": null, "e": 2599, "s": 2252, "text": "public class StringUniCode {\n public static void main(String[] args) {\n String test_string = \"Welcome to TutorialsPoint\";\n System.out.println(\"String under test is = \"+test_string);\n \n System.out.println(\"Unicode code point at\" \n +\" position 5 in the string is = \"\n + test_string.codePointBefore(5));\n }\n}" }, { "code": null, "e": 2656, "s": 2599, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2761, "s": 2656, "text": "String under test is = Welcome to TutorialsPoint\nUnicode code point at position 5 in the string is =111\n" }, { "code": null, "e": 2768, "s": 2761, "text": " Print" }, { "code": null, "e": 2779, "s": 2768, "text": " Add Notes" } ]
Methods for tracking database schema changes in MySQL?
Whenever a table is present in a project with a single database, we can do database schema changes using schema version or migration. It aims to keep track of database schema changes or structural changes. The table creation to keep track of schema changes. mysql> create table SchemaDatabaseMethodDemo -> ( -> `WhenTime` timestamp not null default CURRENT_TIMESTAMP, -> `TheKey` varchar(200) not null, -> `Version` varchar(200), -> primary key(`TheKey`) -> )ENGINE=InnoDB; Query OK, 0 rows affected (0.45 sec) Inserting records into the table. mysql> insert into SchemaDatabaseMethodDemo values(now(),'1001','version 5.6.12'); Query OK, 1 row affected (0.17 sec) To display records. mysql> select *from SchemaDatabaseMethodDemo; The following is the output. +---------------------+--------+----------------+ | WhenTime | TheKey | Version | +---------------------+--------+----------------+ | 2018-10-29 14:21:47 | 1001 | version 5.6.12 | +---------------------+--------+----------------+ 1 row in set (0.00 sec) Note − Suppose we are executing a SQL script or migration then we need to add a row in the above table as well with the help of the INSERT statement at the beginning or end of the scripts.
[ { "code": null, "e": 1268, "s": 1062, "text": "Whenever a table is present in a project with a single database, we can do database schema changes using schema version or migration. It aims to keep track of database schema changes or structural changes." }, { "code": null, "e": 1320, "s": 1268, "text": "The table creation to keep track of schema changes." }, { "code": null, "e": 1591, "s": 1320, "text": "mysql> create table SchemaDatabaseMethodDemo\n -> (\n -> `WhenTime` timestamp not null default CURRENT_TIMESTAMP,\n -> `TheKey` varchar(200) not null,\n -> `Version` varchar(200),\n -> primary key(`TheKey`)\n -> )ENGINE=InnoDB;\nQuery OK, 0 rows affected (0.45 sec)" }, { "code": null, "e": 1625, "s": 1591, "text": "Inserting records into the table." }, { "code": null, "e": 1744, "s": 1625, "text": "mysql> insert into SchemaDatabaseMethodDemo values(now(),'1001','version 5.6.12');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1764, "s": 1744, "text": "To display records." }, { "code": null, "e": 1810, "s": 1764, "text": "mysql> select *from SchemaDatabaseMethodDemo;" }, { "code": null, "e": 1839, "s": 1810, "text": "The following is the output." }, { "code": null, "e": 2114, "s": 1839, "text": "+---------------------+--------+----------------+\n| WhenTime | TheKey | Version |\n+---------------------+--------+----------------+\n| 2018-10-29 14:21:47 | 1001 | version 5.6.12 |\n+---------------------+--------+----------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 2304, "s": 2114, "text": "Note − Suppose we are executing a SQL script or migration then we need to add a row in the above table as well with the help of the INSERT statement at the beginning or end of the scripts.\n" } ]
Bollinger Bands for stock trading — Theory and practice in Python | by Gianluca Malato | Towards Data Science
Quantitative traders often look for trading tools that can spot trends or reversals. Such tools should self-adapt to market conditions and try to describe the current situation in the most accurate way. In this article, I’ll talk about Bollinger Bands and how to work with them in Python. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Bollinger Bands are a tool introduced by the quantitative trader John Bollinger in the 1980s. They are made by two lines that wrap the price time series in a way that is related to volatility. The higher the volatility, the wider the bands. They are usually drawn in this way: Higher band: a 20-period Simple Moving Average plus 2 times the 20-period rolling standard deviation, both calculated on the close price Lower band: a 20-period Simple Moving Average minus 2 times the 20-period rolling standard deviation, both calculated on the close price This is the result applied to the SPX ETF of the S&P 500 index: As you can see, the bands try to wrap the price, but some particular events occur when the price breaks them and we can use such events for building many trading strategies. Let’s see some trading setups that can be spotted with Bollinger Bands. The most common approach, often used by binary options traders, is to consider Bollinger Bands as dynamic supports and resistances. Once the price has broken a band, it’s generally thought that it will likely return back towards the SMA. However, while this approach could seem good, Bollinger himself usually suggests using the Bands together with another indicator, for example, an oscillator. We’re going to see that breaking the bands is not often a reverse signal. If the trend is strong, the price will likely move near a band for some candles. That’s because a strong trend means high volatility, so the bands expand and the price follows them. A very used set of patterns is the W-M pattern. The former is the opposite of the latter. W pattern occurs when the price breaks the lower band, then rises, then falls again, and finally rises without breaking the band again. It really seems to draw a W letter. The M pattern occurs when the price breaks the upper band, then makes a new maximum without breaking the band again. These patterns are usually considered as a decrease of momentum, so they are used in a reversal way. W patterns are bullish, M patterns are bearish. Don’t forget that market volatility changes over time and there are some periods of low volatility that prelude a huge directional burst of the market. Bollinger Bands can spot such situations very easily. You have to look for a market condition in which the bands are flat and their width is constant. This is called “squeeze” because the volatility is lowering. Then you have to look for a breakout made by a huge candle. That is the prelude of the directional explosion of the price and you could trade following the direction of the breakout. Bollinger Bands have 2 parameters: the period of the moving average and of the standard deviation (which is the same) and the multiplier of the standard deviation. The 20-period SMA is often used to catch medium-term movements, so the value of 20 periods has been chosen empirically. Let’s talk about the multiplier of the standard deviation. According to the normal distribution, there is a probability of nearly 95% that the value of a normal variable is more than 2 standard deviations far from the mean value. That’s where the 2 number comes from. In reality, we know that prices don’t follow a normal distribution. According to the Geometric Brownian Motion model, a good approximation of the price distribution is the Lognormal distribution. Moreover, according to Chebyshev’s inequality, the probability of having a value of any random variable with a finite variance that is more than 2 standard deviations far from the mean value is less than 25%. So, it’s quite high and very different from the 5% of the normal case. John Bollinger himself suggests using a slightly different set of parameters, changing the multiplier and the period according to some particular situations. Nevertheless, the 20–2 combination is widely considered almost like a standard in trading. Calculating Bollinger Bands in Python is very easy. We’re going to see how to do it using S&P 500 historical data. The whole code can be found in my GitHub repository: https://github.com/gianlucamalato/machinelearning/blob/master/Bollinger_Bands.ipynb First, let’s install yfinance: !pip install yfinance Then let’s import some libraries: import yfinanceimport pandas as pdimport matplotlib.pyplot as plt Let’s import some data from S&P 500 index: name = "SPY"ticker = yfinance.Ticker(name)df = ticker.history(interval="1d",start="2020-01-15",end="2020-07-15") We can define the period and the multiplier: period = 20multiplier = 2 Then, we can finally calculate the bands: df['UpperBand'] = df['Close'].rolling(period).mean() + df['Close'].rolling(period).std() * multiplierdf['LowerBand'] = df['Close'].rolling(period).mean() - df['Close'].rolling(period).std() * multiplier The final chart is: As you can see, the bands wrap the price just like expected. Bollinger Bands are very useful to use in trading and very simple to calculate. Different strategies using such a dynamic tool can lead to different results, so a good backtest of a trading strategy should always be done to fine-tune the parameters of the indicators.
[ { "code": null, "e": 375, "s": 172, "text": "Quantitative traders often look for trading tools that can spot trends or reversals. Such tools should self-adapt to market conditions and try to describe the current situation in the most accurate way." }, { "code": null, "e": 461, "s": 375, "text": "In this article, I’ll talk about Bollinger Bands and how to work with them in Python." }, { "code": null, "e": 761, "s": 461, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 1002, "s": 761, "text": "Bollinger Bands are a tool introduced by the quantitative trader John Bollinger in the 1980s. They are made by two lines that wrap the price time series in a way that is related to volatility. The higher the volatility, the wider the bands." }, { "code": null, "e": 1038, "s": 1002, "text": "They are usually drawn in this way:" }, { "code": null, "e": 1175, "s": 1038, "text": "Higher band: a 20-period Simple Moving Average plus 2 times the 20-period rolling standard deviation, both calculated on the close price" }, { "code": null, "e": 1312, "s": 1175, "text": "Lower band: a 20-period Simple Moving Average minus 2 times the 20-period rolling standard deviation, both calculated on the close price" }, { "code": null, "e": 1376, "s": 1312, "text": "This is the result applied to the SPX ETF of the S&P 500 index:" }, { "code": null, "e": 1550, "s": 1376, "text": "As you can see, the bands try to wrap the price, but some particular events occur when the price breaks them and we can use such events for building many trading strategies." }, { "code": null, "e": 1622, "s": 1550, "text": "Let’s see some trading setups that can be spotted with Bollinger Bands." }, { "code": null, "e": 1860, "s": 1622, "text": "The most common approach, often used by binary options traders, is to consider Bollinger Bands as dynamic supports and resistances. Once the price has broken a band, it’s generally thought that it will likely return back towards the SMA." }, { "code": null, "e": 2092, "s": 1860, "text": "However, while this approach could seem good, Bollinger himself usually suggests using the Bands together with another indicator, for example, an oscillator. We’re going to see that breaking the bands is not often a reverse signal." }, { "code": null, "e": 2274, "s": 2092, "text": "If the trend is strong, the price will likely move near a band for some candles. That’s because a strong trend means high volatility, so the bands expand and the price follows them." }, { "code": null, "e": 2536, "s": 2274, "text": "A very used set of patterns is the W-M pattern. The former is the opposite of the latter. W pattern occurs when the price breaks the lower band, then rises, then falls again, and finally rises without breaking the band again. It really seems to draw a W letter." }, { "code": null, "e": 2653, "s": 2536, "text": "The M pattern occurs when the price breaks the upper band, then makes a new maximum without breaking the band again." }, { "code": null, "e": 2802, "s": 2653, "text": "These patterns are usually considered as a decrease of momentum, so they are used in a reversal way. W patterns are bullish, M patterns are bearish." }, { "code": null, "e": 3349, "s": 2802, "text": "Don’t forget that market volatility changes over time and there are some periods of low volatility that prelude a huge directional burst of the market. Bollinger Bands can spot such situations very easily. You have to look for a market condition in which the bands are flat and their width is constant. This is called “squeeze” because the volatility is lowering. Then you have to look for a breakout made by a huge candle. That is the prelude of the directional explosion of the price and you could trade following the direction of the breakout." }, { "code": null, "e": 3513, "s": 3349, "text": "Bollinger Bands have 2 parameters: the period of the moving average and of the standard deviation (which is the same) and the multiplier of the standard deviation." }, { "code": null, "e": 3633, "s": 3513, "text": "The 20-period SMA is often used to catch medium-term movements, so the value of 20 periods has been chosen empirically." }, { "code": null, "e": 3901, "s": 3633, "text": "Let’s talk about the multiplier of the standard deviation. According to the normal distribution, there is a probability of nearly 95% that the value of a normal variable is more than 2 standard deviations far from the mean value. That’s where the 2 number comes from." }, { "code": null, "e": 4377, "s": 3901, "text": "In reality, we know that prices don’t follow a normal distribution. According to the Geometric Brownian Motion model, a good approximation of the price distribution is the Lognormal distribution. Moreover, according to Chebyshev’s inequality, the probability of having a value of any random variable with a finite variance that is more than 2 standard deviations far from the mean value is less than 25%. So, it’s quite high and very different from the 5% of the normal case." }, { "code": null, "e": 4535, "s": 4377, "text": "John Bollinger himself suggests using a slightly different set of parameters, changing the multiplier and the period according to some particular situations." }, { "code": null, "e": 4626, "s": 4535, "text": "Nevertheless, the 20–2 combination is widely considered almost like a standard in trading." }, { "code": null, "e": 4878, "s": 4626, "text": "Calculating Bollinger Bands in Python is very easy. We’re going to see how to do it using S&P 500 historical data. The whole code can be found in my GitHub repository: https://github.com/gianlucamalato/machinelearning/blob/master/Bollinger_Bands.ipynb" }, { "code": null, "e": 4909, "s": 4878, "text": "First, let’s install yfinance:" }, { "code": null, "e": 4931, "s": 4909, "text": "!pip install yfinance" }, { "code": null, "e": 4965, "s": 4931, "text": "Then let’s import some libraries:" }, { "code": null, "e": 5031, "s": 4965, "text": "import yfinanceimport pandas as pdimport matplotlib.pyplot as plt" }, { "code": null, "e": 5074, "s": 5031, "text": "Let’s import some data from S&P 500 index:" }, { "code": null, "e": 5187, "s": 5074, "text": "name = \"SPY\"ticker = yfinance.Ticker(name)df = ticker.history(interval=\"1d\",start=\"2020-01-15\",end=\"2020-07-15\")" }, { "code": null, "e": 5232, "s": 5187, "text": "We can define the period and the multiplier:" }, { "code": null, "e": 5258, "s": 5232, "text": "period = 20multiplier = 2" }, { "code": null, "e": 5300, "s": 5258, "text": "Then, we can finally calculate the bands:" }, { "code": null, "e": 5503, "s": 5300, "text": "df['UpperBand'] = df['Close'].rolling(period).mean() + df['Close'].rolling(period).std() * multiplierdf['LowerBand'] = df['Close'].rolling(period).mean() - df['Close'].rolling(period).std() * multiplier" }, { "code": null, "e": 5523, "s": 5503, "text": "The final chart is:" }, { "code": null, "e": 5584, "s": 5523, "text": "As you can see, the bands wrap the price just like expected." } ]
How to run java class file which is in different directory? - GeeksforGeeks
07 May, 2019 In this article, we will learn about how to use other project’s utilities, classes, and members. Before proceeding let’s learn about some keywords. classpath Classpath is the location from where JVM starts execution of a program. Similar to the classic dynamic loading behavior, when executing Java programs, the Java Virtual Machine finds and loads classes lazily (it loads the bytecode of a class only when the class is first used). The classpath tells Java where to look in the filesystem for files defining these classes. Variables and methods which are accessible and available at classpath are known as classpath variables. By default JVM always access the classpath classes while executing a program. JVM always go into the deep of classpath to search for a class or resource. The JVM searches for and loads classes in this order: bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional).extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional). extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries Using import keyword import keyword is used in Java to import classes from current project’s classpath. You can import classes from different packages but from same classpath. It is to be remembered that packaging of a class starts from classpath. Suppose you have directory structure as follows: a > b > c > d > class A and your classpath starts from c, then your class should be in package d not in a.b.c.d. Using classpath -cp option import keyword can import classes from the current classpath, outside the classpath import can’t be used. Now suppose you already have a project in which you have used some utility classes, which you need in your second project also. Then in this situation import keyword doesn’t work because your first project is at another classpath. In that case, you can use -cp command while compiling and executing your program. Let’s proceed with the following example. Create a directory structure as shown in the figure below. Here you have 2 projects proj1 and proj2. proj1 contains src and classes. In the src directory, we will keep .java files that are source files and in classes directory, we will keep .classes files that are files generated after compiling the project.Following are the steps to run java class file which is in different directory: Step 1 (Create utility class): Create A.java in src directory containing following code.//java utility classpublic class A{ public void test() { System.out.println("Test() method of class A"); }}Here, We have one utility class that is A. //java utility classpublic class A{ public void test() { System.out.println("Test() method of class A"); }} Here, We have one utility class that is A. Step 2 (Compile utility class): Open terminal at proj1 location and execute following commands.cp_tutorial/proj1>cd src cp_tutorial/proj1/src>javac -d ../classes A.java -d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further. cp_tutorial/proj1>cd src cp_tutorial/proj1/src>javac -d ../classes A.java -d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further. Step 3 (Check whether A.java is successfully compiled): Check in classes directory of proj1 whether class file is created or not. It will be certainly Yes if your program was Compiled successfully. Step 4 (Write main class and compile it): Move to your proj2 directory. Here are also 2 directories for the same reasons. Create MainClass.java in src directory having the following content and try to compile it.//java class to execute programpublic class MainClass{ public static void main(String[] args){ System.out.println("In main class"); A a1 = new A(); a1.test(); }}cp_tutorial/proj2>cd src cp_tutorial/proj2/src>javac -d ../classes MainClass.java MainClass.java:4: error: cannot find symbol A a1 = new A(); ^ symbol: class A location: class MainClass MainClass.java:4: error: cannot find symbol A a1 = new A(); ^ symbol: class A location: class MainClass 2 errors As you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step. //java class to execute programpublic class MainClass{ public static void main(String[] args){ System.out.println("In main class"); A a1 = new A(); a1.test(); }} cp_tutorial/proj2>cd src cp_tutorial/proj2/src>javac -d ../classes MainClass.java MainClass.java:4: error: cannot find symbol A a1 = new A(); ^ symbol: class A location: class MainClass MainClass.java:4: error: cannot find symbol A a1 = new A(); ^ symbol: class A location: class MainClass 2 errors As you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step. Step 5 (Compile with -cp option):cp_tutorial/proj2>cd src cp_tutorial/proj2/src>javac -d ../classes -cp ../../proj1/classes MainClass.java Now, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully. cp_tutorial/proj2>cd src cp_tutorial/proj2/src>javac -d ../classes -cp ../../proj1/classes MainClass.java Now, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully. Step 6 (Execute the program): Try executing the program.execute the following commands to run your program.cp_tutorial/proj2/src>cd ../classes cp_tutorial/proj2/classes>java MainClass Exception in thread "main" java.lang.NoClassDefFoundError: A at MainClass.main(MainClass.java:4) Caused by: java.lang.ClassNotFoundException: A at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more Oops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects. execute the following commands to run your program. cp_tutorial/proj2/src>cd ../classes cp_tutorial/proj2/classes>java MainClass Exception in thread "main" java.lang.NoClassDefFoundError: A at MainClass.main(MainClass.java:4) Caused by: java.lang.ClassNotFoundException: A at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more Oops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects. Step 7 (Execute with -cp option): We have to again provide the path of class A.cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass In main class Test() method of class A Now, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux. cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass In main class Test() method of class A Now, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux. How to run a java class with a jar in the classpath? You can also use jar file instead of class files from different classpath. The process will be same, you just have to replace classes folder with jar folder and class name with jar name.Suppose you have jar file in the lib directory, then to compile you can use cp_tutorial/proj2/src>javac -d ../classes -cp ../../proj1/lib MainClass.java and to execute cp_tutorial/proj2/classes>java -cp ../../proj1/lib; MainClass Related Article: Setting up Java Environment This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. Achint Sharma Akanksha_Rai java-file-handling Java-I/O java-puzzle Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Overriding in Java Stack Class in Java Set in Java LinkedList in Java Singleton Class in Java
[ { "code": null, "e": 24100, "s": 24072, "text": "\n07 May, 2019" }, { "code": null, "e": 24248, "s": 24100, "text": "In this article, we will learn about how to use other project’s utilities, classes, and members. Before proceeding let’s learn about some keywords." }, { "code": null, "e": 24258, "s": 24248, "text": "classpath" }, { "code": null, "e": 24884, "s": 24258, "text": "Classpath is the location from where JVM starts execution of a program. Similar to the classic dynamic loading behavior, when executing Java programs, the Java Virtual Machine finds and loads classes lazily (it loads the bytecode of a class only when the class is first used). The classpath tells Java where to look in the filesystem for files defining these classes. Variables and methods which are accessible and available at classpath are known as classpath variables. By default JVM always access the classpath classes while executing a program. JVM always go into the deep of classpath to search for a class or resource." }, { "code": null, "e": 24938, "s": 24884, "text": "The JVM searches for and loads classes in this order:" }, { "code": null, "e": 25279, "s": 24938, "text": "bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional).extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries" }, { "code": null, "e": 25489, "s": 25279, "text": "bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional)." }, { "code": null, "e": 25621, "s": 25489, "text": "extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries" }, { "code": null, "e": 25642, "s": 25621, "text": "Using import keyword" }, { "code": null, "e": 25918, "s": 25642, "text": "import keyword is used in Java to import classes from current project’s classpath. You can import classes from different packages but from same classpath. It is to be remembered that packaging of a class starts from classpath. Suppose you have directory structure as follows:" }, { "code": null, "e": 25943, "s": 25918, "text": "a > b > c > d > class A\n" }, { "code": null, "e": 26032, "s": 25943, "text": "and your classpath starts from c, then your class should be in package d not in a.b.c.d." }, { "code": null, "e": 26059, "s": 26032, "text": "Using classpath -cp option" }, { "code": null, "e": 26478, "s": 26059, "text": "import keyword can import classes from the current classpath, outside the classpath import can’t be used. Now suppose you already have a project in which you have used some utility classes, which you need in your second project also. Then in this situation import keyword doesn’t work because your first project is at another classpath. In that case, you can use -cp command while compiling and executing your program." }, { "code": null, "e": 26579, "s": 26478, "text": "Let’s proceed with the following example. Create a directory structure as shown in the figure below." }, { "code": null, "e": 26909, "s": 26579, "text": "Here you have 2 projects proj1 and proj2. proj1 contains src and classes. In the src directory, we will keep .java files that are source files and in classes directory, we will keep .classes files that are files generated after compiling the project.Following are the steps to run java class file which is in different directory:" }, { "code": null, "e": 27163, "s": 26909, "text": "Step 1 (Create utility class): Create A.java in src directory containing following code.//java utility classpublic class A{ public void test() { System.out.println(\"Test() method of class A\"); }}Here, We have one utility class that is A." }, { "code": "//java utility classpublic class A{ public void test() { System.out.println(\"Test() method of class A\"); }}", "e": 27287, "s": 27163, "text": null }, { "code": null, "e": 27330, "s": 27287, "text": "Here, We have one utility class that is A." }, { "code": null, "e": 27889, "s": 27330, "text": "Step 2 (Compile utility class): Open terminal at proj1 location and execute following commands.cp_tutorial/proj1>cd src\ncp_tutorial/proj1/src>javac -d ../classes A.java\n-d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further." }, { "code": null, "e": 27964, "s": 27889, "text": "cp_tutorial/proj1>cd src\ncp_tutorial/proj1/src>javac -d ../classes A.java\n" }, { "code": null, "e": 28354, "s": 27964, "text": "-d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further." }, { "code": null, "e": 28552, "s": 28354, "text": "Step 3 (Check whether A.java is successfully compiled): Check in classes directory of proj1 whether class file is created or not. It will be certainly Yes if your program was Compiled successfully." }, { "code": null, "e": 29527, "s": 28552, "text": "Step 4 (Write main class and compile it): Move to your proj2 directory. Here are also 2 directories for the same reasons. Create MainClass.java in src directory having the following content and try to compile it.//java class to execute programpublic class MainClass{ public static void main(String[] args){ System.out.println(\"In main class\"); A a1 = new A(); a1.test(); }}cp_tutorial/proj2>cd src\ncp_tutorial/proj2/src>javac -d ../classes MainClass.java\nMainClass.java:4: error: cannot find symbol\n A a1 = new A();\n ^\n symbol: class A\n location: class MainClass\nMainClass.java:4: error: cannot find symbol\n A a1 = new A();\n ^\n symbol: class A\n location: class MainClass\n2 errors\nAs you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step." }, { "code": "//java class to execute programpublic class MainClass{ public static void main(String[] args){ System.out.println(\"In main class\"); A a1 = new A(); a1.test(); }}", "e": 29716, "s": 29527, "text": null }, { "code": null, "e": 30103, "s": 29716, "text": "cp_tutorial/proj2>cd src\ncp_tutorial/proj2/src>javac -d ../classes MainClass.java\nMainClass.java:4: error: cannot find symbol\n A a1 = new A();\n ^\n symbol: class A\n location: class MainClass\nMainClass.java:4: error: cannot find symbol\n A a1 = new A();\n ^\n symbol: class A\n location: class MainClass\n2 errors\n" }, { "code": null, "e": 30292, "s": 30103, "text": "As you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step." }, { "code": null, "e": 30720, "s": 30292, "text": "Step 5 (Compile with -cp option):cp_tutorial/proj2>cd src\ncp_tutorial/proj2/src>javac -d ../classes -cp \n../../proj1/classes MainClass.java\nNow, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully." }, { "code": null, "e": 30828, "s": 30720, "text": "cp_tutorial/proj2>cd src\ncp_tutorial/proj2/src>javac -d ../classes -cp \n../../proj1/classes MainClass.java\n" }, { "code": null, "e": 31116, "s": 30828, "text": "Now, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully." }, { "code": null, "e": 32107, "s": 31116, "text": "Step 6 (Execute the program): Try executing the program.execute the following commands to run your program.cp_tutorial/proj2/src>cd ../classes\ncp_tutorial/proj2/classes>java MainClass\nException in thread \"main\" java.lang.NoClassDefFoundError: A\n at MainClass.main(MainClass.java:4)\nCaused by: java.lang.ClassNotFoundException: A\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.net.URLClassLoader.findClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n ... 1 more\nOops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects." }, { "code": null, "e": 32159, "s": 32107, "text": "execute the following commands to run your program." }, { "code": null, "e": 32841, "s": 32159, "text": "cp_tutorial/proj2/src>cd ../classes\ncp_tutorial/proj2/classes>java MainClass\nException in thread \"main\" java.lang.NoClassDefFoundError: A\n at MainClass.main(MainClass.java:4)\nCaused by: java.lang.ClassNotFoundException: A\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.net.URLClassLoader.findClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n ... 1 more\n" }, { "code": null, "e": 33044, "s": 32841, "text": "Oops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects." }, { "code": null, "e": 33362, "s": 33044, "text": "Step 7 (Execute with -cp option): We have to again provide the path of class A.cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass\nIn main class\nTest() method of class A\nNow, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux." }, { "code": null, "e": 33468, "s": 33362, "text": "cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass\nIn main class\nTest() method of class A\n" }, { "code": null, "e": 33602, "s": 33468, "text": "Now, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux." }, { "code": null, "e": 33655, "s": 33602, "text": "How to run a java class with a jar in the classpath?" }, { "code": null, "e": 33917, "s": 33655, "text": "You can also use jar file instead of class files from different classpath. The process will be same, you just have to replace classes folder with jar folder and class name with jar name.Suppose you have jar file in the lib directory, then to compile you can use" }, { "code": null, "e": 33995, "s": 33917, "text": "cp_tutorial/proj2/src>javac -d ../classes -cp ../../proj1/lib MainClass.java\n" }, { "code": null, "e": 34010, "s": 33995, "text": "and to execute" }, { "code": null, "e": 34072, "s": 34010, "text": "cp_tutorial/proj2/classes>java -cp ../../proj1/lib; MainClass" }, { "code": null, "e": 34117, "s": 34072, "text": "Related Article: Setting up Java Environment" }, { "code": null, "e": 34416, "s": 34117, "text": "This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34541, "s": 34416, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34555, "s": 34541, "text": "Achint Sharma" }, { "code": null, "e": 34568, "s": 34555, "text": "Akanksha_Rai" }, { "code": null, "e": 34587, "s": 34568, "text": "java-file-handling" }, { "code": null, "e": 34596, "s": 34587, "text": "Java-I/O" }, { "code": null, "e": 34608, "s": 34596, "text": "java-puzzle" }, { "code": null, "e": 34613, "s": 34608, "text": "Java" }, { "code": null, "e": 34618, "s": 34613, "text": "Java" }, { "code": null, "e": 34716, "s": 34618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34725, "s": 34716, "text": "Comments" }, { "code": null, "e": 34738, "s": 34725, "text": "Old Comments" }, { "code": null, "e": 34770, "s": 34738, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34800, "s": 34770, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34819, "s": 34800, "text": "Interfaces in Java" }, { "code": null, "e": 34837, "s": 34819, "text": "ArrayList in Java" }, { "code": null, "e": 34869, "s": 34837, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34888, "s": 34869, "text": "Overriding in Java" }, { "code": null, "e": 34908, "s": 34888, "text": "Stack Class in Java" }, { "code": null, "e": 34920, "s": 34908, "text": "Set in Java" }, { "code": null, "e": 34939, "s": 34920, "text": "LinkedList in Java" } ]
What is the match() function in Python?
In Python, match() is a method of the module re Syntax of match() re.match(pattern, string): This method finds match if it occurs at start of the string. For example, calling match() on the string ‘TP Tutorials Point TP’ and looking for a pattern ‘TP’ will match. However, if we look for only Tutorials, the pattern will not match. Let’s check the code. import re result = re.match(r'TP', 'TP Tutorials Point TP') print result <_sre.SRE_Match object at 0x0000000005478648> Above, it shows that pattern match has been found. To print the matching string we use method group. Use “r” at the start of the pattern string, it designates a python raw string. import re result = re.match(r'TP', 'TP Tutorials Point TP') print result.group(0) TP Let’s now find ‘Tutorials’ in the given string. Here we see that string is not starting with ‘TP’ so it should return no match. Let’s see what we get − import re result = re.match(r'Tutorials', 'TP Tutorials Point TP') print result None
[ { "code": null, "e": 1111, "s": 1062, "text": "In Python, match() is a method of the module re " }, { "code": null, "e": 1129, "s": 1111, "text": "Syntax of match()" }, { "code": null, "e": 1156, "s": 1129, "text": "re.match(pattern, string):" }, { "code": null, "e": 1417, "s": 1156, "text": "This method finds match if it occurs at start of the string. For example, calling match() on the string ‘TP Tutorials Point TP’ and looking for a pattern ‘TP’ will match. However, if we look for only Tutorials, the pattern will not match. Let’s check the code." }, { "code": null, "e": 1490, "s": 1417, "text": "import re\nresult = re.match(r'TP', 'TP Tutorials Point TP')\nprint result" }, { "code": null, "e": 1536, "s": 1490, "text": "<_sre.SRE_Match object at 0x0000000005478648>" }, { "code": null, "e": 1716, "s": 1536, "text": "Above, it shows that pattern match has been found. To print the matching string we use method group. Use “r” at the start of the pattern string, it designates a python raw string." }, { "code": null, "e": 1798, "s": 1716, "text": "import re\nresult = re.match(r'TP', 'TP Tutorials Point TP')\nprint result.group(0)" }, { "code": null, "e": 1801, "s": 1798, "text": "TP" }, { "code": null, "e": 1953, "s": 1801, "text": "Let’s now find ‘Tutorials’ in the given string. Here we see that string is not starting with ‘TP’ so it should return no match. Let’s see what we get −" }, { "code": null, "e": 2033, "s": 1953, "text": "import re\nresult = re.match(r'Tutorials', 'TP Tutorials Point TP')\nprint result" }, { "code": null, "e": 2038, "s": 2033, "text": "None" } ]
C++ Program to Implement Parallel Array
A parallel array is a structure that contains multiple arrays. Each of these arrays are of the same size and the array elements are related to each other. All the elements in a parallel array represent a common entity. An example of parallel arrays is as follows − employee_name = { Harry, Sally, Mark, Frank, Judy } employee_salary = {10000, 5000, 20000, 12000, 5000} In the above example, the name and salary of 5 different employees is stored in 2 arrays. A program that demonstrates parallel arrays is given as follows − #include <iostream> #include <string> using namespace std; int main() { int max = 0, index = 0; string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" }; string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"}; int empSal[ ] = {10000, 5000, 20000, 12000, 5000 }; int n = sizeof(empSal)/sizeof(empSal[0]); for(int i = 0; i < n; i++) { if (empSal[i] > max) { max = empSal[i]; index = i; } } cout << "The highest salary is "<< max <<" and is earned by "<<empName[index]<<" belonging to "<<empDept[index]<<" department"; return 0; } The output of the above program is as follows − The highest salary is 20000 and is earned by Mark belonging to IT department In the above program, three arrays are declared, containing the employee name, department and salary respectively. This is given below − string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" }; string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"}; int empSal[ ] = {10000, 5000, 20000, 12000, 5000 }; The highest salary is found using the for loop and stored in max. The index that contains the highest salary is stored in index. This is shown below − int n = sizeof(empSal)/sizeof(empSal[0]); for(int i = 0; i < n; i++) { if (empSal[i] > max) { max = empSal[i]; index = i; } } Finally, the highest salary and its corresponding employee name and department are displayed. This is given below − cout << "The highest salary is "<< max <<" and is earned by "<<empName[index]<<" belonging to "<<empDept[index]<<" department";
[ { "code": null, "e": 1281, "s": 1062, "text": "A parallel array is a structure that contains multiple arrays. Each of these arrays are of the same size and the array elements are related to each other. All the elements in a parallel array represent a common entity." }, { "code": null, "e": 1327, "s": 1281, "text": "An example of parallel arrays is as follows −" }, { "code": null, "e": 1431, "s": 1327, "text": "employee_name = { Harry, Sally, Mark, Frank, Judy }\nemployee_salary = {10000, 5000, 20000, 12000, 5000}" }, { "code": null, "e": 1521, "s": 1431, "text": "In the above example, the name and salary of 5 different employees is stored in 2 arrays." }, { "code": null, "e": 1587, "s": 1521, "text": "A program that demonstrates parallel arrays is given as follows −" }, { "code": null, "e": 2189, "s": 1587, "text": "#include <iostream>\n#include <string>\n\nusing namespace std;\nint main() {\n int max = 0, index = 0;\n string empName [ ] = {\"Harry\", \"Sally\", \"Mark\", \"Frank\", \"Judy\" };\n string empDept [ ] = {\"IT\", \"Sales\", \"IT\", \"HR\", \"Sales\"};\n int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };\n int n = sizeof(empSal)/sizeof(empSal[0]);\n\n for(int i = 0; i < n; i++) {\n if (empSal[i] > max) {\n max = empSal[i];\n index = i;\n }\n }\n cout << \"The highest salary is \"<< max <<\" and is earned by\n \"<<empName[index]<<\" belonging to \"<<empDept[index]<<\" department\";\n return 0;\n}" }, { "code": null, "e": 2237, "s": 2189, "text": "The output of the above program is as follows −" }, { "code": null, "e": 2314, "s": 2237, "text": "The highest salary is 20000 and is earned by Mark belonging to IT department" }, { "code": null, "e": 2451, "s": 2314, "text": "In the above program, three arrays are declared, containing the employee name, department and salary respectively. This is given below −" }, { "code": null, "e": 2629, "s": 2451, "text": "string empName [ ] = {\"Harry\", \"Sally\", \"Mark\", \"Frank\", \"Judy\" };\nstring empDept [ ] = {\"IT\", \"Sales\", \"IT\", \"HR\", \"Sales\"};\nint empSal[ ] = {10000, 5000, 20000, 12000, 5000 };" }, { "code": null, "e": 2780, "s": 2629, "text": "The highest salary is found using the for loop and stored in max. The index that contains the highest salary is stored in index. This is shown below −" }, { "code": null, "e": 2924, "s": 2780, "text": "int n = sizeof(empSal)/sizeof(empSal[0]);\nfor(int i = 0; i < n; i++) {\n if (empSal[i] > max) {\n max = empSal[i];\n index = i;\n }\n}" }, { "code": null, "e": 3040, "s": 2924, "text": "Finally, the highest salary and its corresponding employee name and department are displayed. This is given below −" }, { "code": null, "e": 3168, "s": 3040, "text": "cout << \"The highest salary is \"<< max <<\" and is earned by \"<<empName[index]<<\"\nbelonging to \"<<empDept[index]<<\" department\";" } ]
HTML onclick Event Attribute - GeeksforGeeks
28 Jan, 2022 The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs. Syntax: <element onclick = "script"> Attribute Value: This attribute contains a single value script that works when the mouse clicked on the element. Supported Tags: This attribute is supported by all HTML tags except <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>. Example 1: This example shows the simple onClick event where the button is clicked to display the date & time in HTML. HTML <!DOCTYPE html><html><body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <span>Click the button to see the date & time.</span> <button onclick="getElementById('time').innerHTML= Date()"> Show Date </button> <p id="time"></p> </body></html> Output: HTML onclick event attribute Example 2: In this example, when the “Click Here” will be clicked then the text “Welcome to GeeksforGeeks” will be displayed. HTML <!DOCTYPE HTML><html><head> <title> onclick event attribute </title> <script> /* If onclick event call then this script will run */ function onclick_event() { document.getElementById("geeks").innerHTML = "Welcome to GeeksforGeeks!"; } </script></head> <body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <!-- onclick event call here --> <p id="geeks" onclick="onclick_event()"> Click Here </p> </body></html> Output: onclick event call to run the script using the onclick event attribute Example 3: In this example, we have used the button tag to call the event. HTML <!DOCTYPE html><html><head> <title> onclick event attribute </title> <script> document.getElementById("geeks").addEventListener("click", functionClick); function functionClick() { document.getElementById("geeks").innerHTML = "Welcome to GeeksforGeeks!"; } </script></head> <body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <!-- onclick event call here --> <button onclick="functionClick()"> Click Here </button> <p id="geeks"></p> </body></html> Output: onclick event call with button tag using onclick event attribute Supported Browser: Google Chrome 93.0 & above Microsoft Edge 93.0 Firefox 93.0 & above Safari 14.1 Opera 79.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks thecomputerguyjeff HTML-Attributes Picked Technical Scripter 2018 HTML Technical Scripter Web Technologies 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 ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24616, "s": 24588, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24754, "s": 24616, "text": "The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs." }, { "code": null, "e": 24762, "s": 24754, "text": "Syntax:" }, { "code": null, "e": 24791, "s": 24762, "text": "<element onclick = \"script\">" }, { "code": null, "e": 24904, "s": 24791, "text": "Attribute Value: This attribute contains a single value script that works when the mouse clicked on the element." }, { "code": null, "e": 25068, "s": 24904, "text": "Supported Tags: This attribute is supported by all HTML tags except <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>." }, { "code": null, "e": 25187, "s": 25068, "text": "Example 1: This example shows the simple onClick event where the button is clicked to display the date & time in HTML." }, { "code": null, "e": 25192, "s": 25187, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <span>Click the button to see the date & time.</span> <button onclick=\"getElementById('time').innerHTML= Date()\"> Show Date </button> <p id=\"time\"></p> </body></html>", "e": 25470, "s": 25192, "text": null }, { "code": null, "e": 25478, "s": 25470, "text": "Output:" }, { "code": null, "e": 25507, "s": 25478, "text": "HTML onclick event attribute" }, { "code": null, "e": 25633, "s": 25507, "text": "Example 2: In this example, when the “Click Here” will be clicked then the text “Welcome to GeeksforGeeks” will be displayed." }, { "code": null, "e": 25638, "s": 25633, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html><head> <title> onclick event attribute </title> <script> /* If onclick event call then this script will run */ function onclick_event() { document.getElementById(\"geeks\").innerHTML = \"Welcome to GeeksforGeeks!\"; } </script></head> <body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <!-- onclick event call here --> <p id=\"geeks\" onclick=\"onclick_event()\"> Click Here </p> </body></html>", "e": 26139, "s": 25638, "text": null }, { "code": null, "e": 26147, "s": 26139, "text": "Output:" }, { "code": null, "e": 26218, "s": 26147, "text": "onclick event call to run the script using the onclick event attribute" }, { "code": null, "e": 26293, "s": 26218, "text": "Example 3: In this example, we have used the button tag to call the event." }, { "code": null, "e": 26298, "s": 26293, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> onclick event attribute </title> <script> document.getElementById(\"geeks\").addEventListener(\"click\", functionClick); function functionClick() { document.getElementById(\"geeks\").innerHTML = \"Welcome to GeeksforGeeks!\"; } </script></head> <body> <h2>GeeksforGeeks</h2> <h3>onClick Event Attribute</h3> <!-- onclick event call here --> <button onclick=\"functionClick()\"> Click Here </button> <p id=\"geeks\"></p> </body></html>", "e": 26810, "s": 26298, "text": null }, { "code": null, "e": 26818, "s": 26810, "text": "Output:" }, { "code": null, "e": 26883, "s": 26818, "text": "onclick event call with button tag using onclick event attribute" }, { "code": null, "e": 26902, "s": 26883, "text": "Supported Browser:" }, { "code": null, "e": 26929, "s": 26902, "text": "Google Chrome 93.0 & above" }, { "code": null, "e": 26949, "s": 26929, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 26970, "s": 26949, "text": "Firefox 93.0 & above" }, { "code": null, "e": 26982, "s": 26970, "text": "Safari 14.1" }, { "code": null, "e": 26993, "s": 26982, "text": "Opera 79.0" }, { "code": null, "e": 27130, "s": 26993, "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": 27151, "s": 27130, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27170, "s": 27151, "text": "thecomputerguyjeff" }, { "code": null, "e": 27186, "s": 27170, "text": "HTML-Attributes" }, { "code": null, "e": 27193, "s": 27186, "text": "Picked" }, { "code": null, "e": 27217, "s": 27193, "text": "Technical Scripter 2018" }, { "code": null, "e": 27222, "s": 27217, "text": "HTML" }, { "code": null, "e": 27241, "s": 27222, "text": "Technical Scripter" }, { "code": null, "e": 27258, "s": 27241, "text": "Web Technologies" }, { "code": null, "e": 27263, "s": 27258, "text": "HTML" }, { "code": null, "e": 27361, "s": 27263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27411, "s": 27361, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27473, "s": 27411, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27533, "s": 27473, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27581, "s": 27533, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27634, "s": 27581, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27674, "s": 27634, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27707, "s": 27674, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27752, "s": 27707, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27795, "s": 27752, "text": "How to fetch data from an API in ReactJS ?" } ]
Arcesium Interview Experience 2021 - GeeksforGeeks
12 Oct, 2021 Arcesium started an FTE pool drive for some selected IITs and NITs in June 2021. All the eligible candidates were shortlisted for the online test. Eligibility criteria for online test : CGPA – 7.5 for CSE and 8 for ECE, ICE, and IPE.They also consider 10 and 12 standards marks for shortlisting. CGPA – 7.5 for CSE and 8 for ECE, ICE, and IPE. They also consider 10 and 12 standards marks for shortlisting. There were 5 rounds in the selection process and I will rate the difficulty level of the selection process as a difficult one. Round 1(Online Aptitude and Coding Round): This round was consist of 32 questions and the time duration was 80 minutes. There were three sections: Aptitude section (consist of 15 questions and duration was 20 minutes). CS fundamental section (consist of 15 questions and duration was 15 minutes) The last one was the coding section which was consist of 2 coding questions and the duration was 45 minutes. The aptitude section was really tough(time constraint), you must have a good grasp of Mathematics and Puzzles. CS fundamental section was of moderate level and have questions from OOPS, Java, DBMS, OS, DSA, and Computer Networks. There was a negative marking of 25% for the wrong answers. And there was separate timing for all sections but if you solve a section early then the remaining time will be added to the next section. The coding questions were as follow : https://www.geeksforgeeks.org/allocate-minimum-number-pages/ Practice linkhttps://www.geeksforgeeks.org/maximum-array-elements-that-can-be-removed-along-with-its-adjacent-values-to-empty-given-array/ https://www.geeksforgeeks.org/allocate-minimum-number-pages/ Practice link https://www.geeksforgeeks.org/maximum-array-elements-that-can-be-removed-along-with-its-adjacent-values-to-empty-given-array/ I do not have an exact figure of the entire result but from our college, 36 candidates make the cut to the next round. Round 2(Technical Interview): The interview was conducted virtually on Bluejeans platform, the interviewer was a Senior Software Engineer and he asked me to introduce myself and then ask me 2 coding questions. The first one was this one. Firstly I solve the problem using O(N) extra space but he was only interested in constant space solutions, he does not allow me to even use recursion stack space. Finally, I was able to write the complete iterative solution. He checks my solution for some custom inputs and then checks for all corner cases, and he was very satisfied with my solution.The second question was an easy one that why he asked me to code the problem in just five minutes. The question was this one. I was able to write the code in the given time frame and the interviewer seems to be very satisfied. The first one was this one. Firstly I solve the problem using O(N) extra space but he was only interested in constant space solutions, he does not allow me to even use recursion stack space. Finally, I was able to write the complete iterative solution. He checks my solution for some custom inputs and then checks for all corner cases, and he was very satisfied with my solution. The second question was an easy one that why he asked me to code the problem in just five minutes. The question was this one. I was able to write the code in the given time frame and the interviewer seems to be very satisfied. Finally, he asked me to ask questions and I do ask about the work culture and tech stack over which Arcesium currently works. The result was out and 22 candidates were promoted to the next round. Round 3(Technical Interview): This round of interviews was actually a panel round interview there were two interviewers both were Senior Software Engineers. They ask me to introduce myself and then ask me about my internship and then there was a detailed discussion on my project. Then they ask me the following questions: What is LRU and how you can implement it? What is MRU and ask for real-time examples of MRU in practical life. Ask me to write code for this problem. How we can make search and insert operation efficient in Data Bases querries. Various scheduling algorithms in Operating System. She gives me some test cases and then asks me for the output (Project-based test cases). Finally, she asks me one more coding question and the question was as follow: You are given N courses and M dependencies. If there is a dependency from course A to B then you can not do both courses in the same semester you can only do course B in a semester only if you have already done A in some earlier semester. The task was to find the minimum number of semesters required to do all N courses. You can enroll for an infinite number of courses in a semester just to take care of dependencies. You are given N courses and M dependencies. If there is a dependency from course A to B then you can not do both courses in the same semester you can only do course B in a semester only if you have already done A in some earlier semester. The task was to find the minimum number of semesters required to do all N courses. You can enroll for an infinite number of courses in a semester just to take care of dependencies. Example: N=3 and M=2 A-->B A-->C Answer will be 2. Do courses A in one semester and B and C in second semester. I try to find the order of courses using topological sorting and then give various approaches to the interviewer to find the minimum number of semesters, but she does not seem to be satisfied. Finally, she asked me to ask questions from them and I ask about the work culture and team environment in Arcesium. The result was out and 4 candidates directly made a cut to the HR round, but there were 5 more candidates over which they have doubts, so they decided to take one more technical round to those candidates. I was one of them whom they have doubt. Round 4(Technical Interview): Here again, the interviewer was a Senior Software Engineer with experience of 16 years. She asks me to introduce myself and ask me a coding question which was just a little modification of the minimum platform problem you can see the minimum platform problem here. But the actual problem was a variation of this problem. She asks me one more coding question which was an easy one. You can refer to the problem from here. I write the code for both problems and then she asked me the following question: Difference between thread and process. Can two threads access the same data at the same time? Critical section problem The solution to the critical section problem. Deadlock and necessary conditions for deadlock. Then she asks me the famous fastest three horses puzzle with a modification she wants me to tell the minimum number of races to find the fastest 5 horses. Since I had solved it for 3 horses earlier so I was able to extend my solution for the top 5 horses as well. Finally, she asked me to ask questions from her and I ask about her experience in Arcesium, and about current tech stacks. So 2 more candidates were able to make the cut to the HR round so total of 6 candidates were promoted for the HR round. Round 5(HR): She asks me about the previous round interview experience. Then asks me the following questions: Educational background and family background. Current location and problem in relocation. Why Arcesium? What do you know about Arcesium? Do you have any current existing offers? Difference between existing offer and Arcesium. What is your Dream Company? Who is your inspiration? Do you like freelancing? What is your plan for the day? Finally, she asked me to ask questions from her and I do ask her about the team environment and the work culture inside the organization and then ask about the expectation from the freshers. 2 days after the HR round I got a call from the same HR person she firstly congratulates me and then says that they are giving an offer to me, truly speaking I was stunned and then I relax my nerves because It took some time for me to take a breath and realize that I am finally selected, believe me, nothing can be more pleasurable than it. So finally 5 candidates get offers from Arcesium. Tips: Try to write all codes neat and clean over the editor because the interviewer has to give feedback along with evidence to the HR team. I would like to thank GeeksForGeeks for creating such an amazing platform for learning and turning our dreams into realities. Verdict: SELECTED Arcesium Marketing Interview Experiences Arcesium Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 Infosys Interview Experience for DSE 2022 Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ Google Interview Experience SDE-1 (Off-Campus) 2022
[ { "code": null, "e": 26397, "s": 26369, "text": "\n12 Oct, 2021" }, { "code": null, "e": 26544, "s": 26397, "text": "Arcesium started an FTE pool drive for some selected IITs and NITs in June 2021. All the eligible candidates were shortlisted for the online test." }, { "code": null, "e": 26583, "s": 26544, "text": "Eligibility criteria for online test :" }, { "code": null, "e": 26693, "s": 26583, "text": "CGPA – 7.5 for CSE and 8 for ECE, ICE, and IPE.They also consider 10 and 12 standards marks for shortlisting." }, { "code": null, "e": 26741, "s": 26693, "text": "CGPA – 7.5 for CSE and 8 for ECE, ICE, and IPE." }, { "code": null, "e": 26804, "s": 26741, "text": "They also consider 10 and 12 standards marks for shortlisting." }, { "code": null, "e": 26931, "s": 26804, "text": "There were 5 rounds in the selection process and I will rate the difficulty level of the selection process as a difficult one." }, { "code": null, "e": 27052, "s": 26931, "text": "Round 1(Online Aptitude and Coding Round): This round was consist of 32 questions and the time duration was 80 minutes. " }, { "code": null, "e": 27079, "s": 27052, "text": "There were three sections:" }, { "code": null, "e": 27151, "s": 27079, "text": "Aptitude section (consist of 15 questions and duration was 20 minutes)." }, { "code": null, "e": 27228, "s": 27151, "text": "CS fundamental section (consist of 15 questions and duration was 15 minutes)" }, { "code": null, "e": 27337, "s": 27228, "text": "The last one was the coding section which was consist of 2 coding questions and the duration was 45 minutes." }, { "code": null, "e": 27567, "s": 27337, "text": "The aptitude section was really tough(time constraint), you must have a good grasp of Mathematics and Puzzles. CS fundamental section was of moderate level and have questions from OOPS, Java, DBMS, OS, DSA, and Computer Networks." }, { "code": null, "e": 27766, "s": 27567, "text": "There was a negative marking of 25% for the wrong answers. And there was separate timing for all sections but if you solve a section early then the remaining time will be added to the next section. " }, { "code": null, "e": 27804, "s": 27766, "text": "The coding questions were as follow :" }, { "code": null, "e": 28004, "s": 27804, "text": "https://www.geeksforgeeks.org/allocate-minimum-number-pages/ Practice linkhttps://www.geeksforgeeks.org/maximum-array-elements-that-can-be-removed-along-with-its-adjacent-values-to-empty-given-array/" }, { "code": null, "e": 28079, "s": 28004, "text": "https://www.geeksforgeeks.org/allocate-minimum-number-pages/ Practice link" }, { "code": null, "e": 28205, "s": 28079, "text": "https://www.geeksforgeeks.org/maximum-array-elements-that-can-be-removed-along-with-its-adjacent-values-to-empty-given-array/" }, { "code": null, "e": 28324, "s": 28205, "text": "I do not have an exact figure of the entire result but from our college, 36 candidates make the cut to the next round." }, { "code": null, "e": 28535, "s": 28324, "text": "Round 2(Technical Interview): The interview was conducted virtually on Bluejeans platform, the interviewer was a Senior Software Engineer and he asked me to introduce myself and then ask me 2 coding questions. " }, { "code": null, "e": 29141, "s": 28535, "text": "The first one was this one. Firstly I solve the problem using O(N) extra space but he was only interested in constant space solutions, he does not allow me to even use recursion stack space. Finally, I was able to write the complete iterative solution. He checks my solution for some custom inputs and then checks for all corner cases, and he was very satisfied with my solution.The second question was an easy one that why he asked me to code the problem in just five minutes. The question was this one. I was able to write the code in the given time frame and the interviewer seems to be very satisfied." }, { "code": null, "e": 29521, "s": 29141, "text": "The first one was this one. Firstly I solve the problem using O(N) extra space but he was only interested in constant space solutions, he does not allow me to even use recursion stack space. Finally, I was able to write the complete iterative solution. He checks my solution for some custom inputs and then checks for all corner cases, and he was very satisfied with my solution." }, { "code": null, "e": 29748, "s": 29521, "text": "The second question was an easy one that why he asked me to code the problem in just five minutes. The question was this one. I was able to write the code in the given time frame and the interviewer seems to be very satisfied." }, { "code": null, "e": 29874, "s": 29748, "text": "Finally, he asked me to ask questions and I do ask about the work culture and tech stack over which Arcesium currently works." }, { "code": null, "e": 29944, "s": 29874, "text": "The result was out and 22 candidates were promoted to the next round." }, { "code": null, "e": 30267, "s": 29944, "text": "Round 3(Technical Interview): This round of interviews was actually a panel round interview there were two interviewers both were Senior Software Engineers. They ask me to introduce myself and then ask me about my internship and then there was a detailed discussion on my project. Then they ask me the following questions:" }, { "code": null, "e": 30309, "s": 30267, "text": "What is LRU and how you can implement it?" }, { "code": null, "e": 30378, "s": 30309, "text": "What is MRU and ask for real-time examples of MRU in practical life." }, { "code": null, "e": 30417, "s": 30378, "text": "Ask me to write code for this problem." }, { "code": null, "e": 30495, "s": 30417, "text": "How we can make search and insert operation efficient in Data Bases querries." }, { "code": null, "e": 30546, "s": 30495, "text": "Various scheduling algorithms in Operating System." }, { "code": null, "e": 30635, "s": 30546, "text": "She gives me some test cases and then asks me for the output (Project-based test cases)." }, { "code": null, "e": 30713, "s": 30635, "text": "Finally, she asks me one more coding question and the question was as follow:" }, { "code": null, "e": 31135, "s": 30713, "text": "You are given N courses and M dependencies. If there is a dependency from course A to B then you can not do both courses in the same semester you can only do course B in a semester only if you have already done A in some earlier semester. The task was to find the minimum number of semesters required to do all N courses. You can enroll for an infinite number of courses in a semester just to take care of dependencies. " }, { "code": null, "e": 31557, "s": 31135, "text": "You are given N courses and M dependencies. If there is a dependency from course A to B then you can not do both courses in the same semester you can only do course B in a semester only if you have already done A in some earlier semester. The task was to find the minimum number of semesters required to do all N courses. You can enroll for an infinite number of courses in a semester just to take care of dependencies. " }, { "code": null, "e": 31674, "s": 31559, "text": "Example:\n\nN=3 and M=2\nA-->B\nA-->C\nAnswer will be 2. \nDo courses A in one semester \nand B and C in second semester." }, { "code": null, "e": 31867, "s": 31674, "text": "I try to find the order of courses using topological sorting and then give various approaches to the interviewer to find the minimum number of semesters, but she does not seem to be satisfied." }, { "code": null, "e": 31983, "s": 31867, "text": "Finally, she asked me to ask questions from them and I ask about the work culture and team environment in Arcesium." }, { "code": null, "e": 32228, "s": 31983, "text": "The result was out and 4 candidates directly made a cut to the HR round, but there were 5 more candidates over which they have doubts, so they decided to take one more technical round to those candidates. I was one of them whom they have doubt." }, { "code": null, "e": 32579, "s": 32228, "text": "Round 4(Technical Interview): Here again, the interviewer was a Senior Software Engineer with experience of 16 years. She asks me to introduce myself and ask me a coding question which was just a little modification of the minimum platform problem you can see the minimum platform problem here. But the actual problem was a variation of this problem." }, { "code": null, "e": 32679, "s": 32579, "text": "She asks me one more coding question which was an easy one. You can refer to the problem from here." }, { "code": null, "e": 32760, "s": 32679, "text": "I write the code for both problems and then she asked me the following question:" }, { "code": null, "e": 32799, "s": 32760, "text": "Difference between thread and process." }, { "code": null, "e": 32854, "s": 32799, "text": "Can two threads access the same data at the same time?" }, { "code": null, "e": 32879, "s": 32854, "text": "Critical section problem" }, { "code": null, "e": 32925, "s": 32879, "text": "The solution to the critical section problem." }, { "code": null, "e": 32973, "s": 32925, "text": "Deadlock and necessary conditions for deadlock." }, { "code": null, "e": 33238, "s": 32973, "text": "Then she asks me the famous fastest three horses puzzle with a modification she wants me to tell the minimum number of races to find the fastest 5 horses. Since I had solved it for 3 horses earlier so I was able to extend my solution for the top 5 horses as well. " }, { "code": null, "e": 33361, "s": 33238, "text": "Finally, she asked me to ask questions from her and I ask about her experience in Arcesium, and about current tech stacks." }, { "code": null, "e": 33481, "s": 33361, "text": "So 2 more candidates were able to make the cut to the HR round so total of 6 candidates were promoted for the HR round." }, { "code": null, "e": 33553, "s": 33481, "text": "Round 5(HR): She asks me about the previous round interview experience." }, { "code": null, "e": 33592, "s": 33553, "text": " Then asks me the following questions:" }, { "code": null, "e": 33638, "s": 33592, "text": "Educational background and family background." }, { "code": null, "e": 33682, "s": 33638, "text": "Current location and problem in relocation." }, { "code": null, "e": 33696, "s": 33682, "text": "Why Arcesium?" }, { "code": null, "e": 33729, "s": 33696, "text": "What do you know about Arcesium?" }, { "code": null, "e": 33770, "s": 33729, "text": "Do you have any current existing offers?" }, { "code": null, "e": 33818, "s": 33770, "text": "Difference between existing offer and Arcesium." }, { "code": null, "e": 33846, "s": 33818, "text": "What is your Dream Company?" }, { "code": null, "e": 33871, "s": 33846, "text": "Who is your inspiration?" }, { "code": null, "e": 33896, "s": 33871, "text": "Do you like freelancing?" }, { "code": null, "e": 33927, "s": 33896, "text": "What is your plan for the day?" }, { "code": null, "e": 34118, "s": 33927, "text": "Finally, she asked me to ask questions from her and I do ask her about the team environment and the work culture inside the organization and then ask about the expectation from the freshers." }, { "code": null, "e": 34460, "s": 34118, "text": "2 days after the HR round I got a call from the same HR person she firstly congratulates me and then says that they are giving an offer to me, truly speaking I was stunned and then I relax my nerves because It took some time for me to take a breath and realize that I am finally selected, believe me, nothing can be more pleasurable than it." }, { "code": null, "e": 34510, "s": 34460, "text": "So finally 5 candidates get offers from Arcesium." }, { "code": null, "e": 34651, "s": 34510, "text": "Tips: Try to write all codes neat and clean over the editor because the interviewer has to give feedback along with evidence to the HR team." }, { "code": null, "e": 34777, "s": 34651, "text": "I would like to thank GeeksForGeeks for creating such an amazing platform for learning and turning our dreams into realities." }, { "code": null, "e": 34795, "s": 34777, "text": "Verdict: SELECTED" }, { "code": null, "e": 34804, "s": 34795, "text": "Arcesium" }, { "code": null, "e": 34814, "s": 34804, "text": "Marketing" }, { "code": null, "e": 34836, "s": 34814, "text": "Interview Experiences" }, { "code": null, "e": 34845, "s": 34836, "text": "Arcesium" }, { "code": null, "e": 34943, "s": 34845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34994, "s": 34943, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 35036, "s": 34994, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 35064, "s": 35036, "text": "Amazon Interview Experience" }, { "code": null, "e": 35102, "s": 35064, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 35174, "s": 35102, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 35220, "s": 35174, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 35262, "s": 35220, "text": "Infosys Interview Experience for DSE 2022" }, { "code": null, "e": 35312, "s": 35262, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 35388, "s": 35312, "text": "Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ" } ]
bokeh.plotting.figure.step() function in Python - GeeksforGeeks
15 Jun, 2020 Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. The step() function in plotting module of bokeh library is used to configure and add Step glyphs to this Figure. Syntax: step(x, y, *, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, mode=’before’, name=None, tags=[], **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is the x-coordinates for the steps. y: This parameter is the y-coordinates for the steps. line_alpha: This parameter is the line alpha values for the steps with default value of 1.0 . line_cap: This parameter is the line cap values for the steps with default value of butt. line_color: This parameter is the line color values for the steps with default value of black. line_dash: This parameter is the line dash values for the steps with default value of []. line_dash_offset: This parameter is the line dash offset values for the steps with default value of 0. line_join: This parameter is the line join values for the steps with default value of bevel. line_width: This parameter is the line width values for the steps with default value of 1. mode: This parameter can be one of three values : [“before”, “after”, “center”]. name: This parameter is the user-supplied name for this model. tags: This parameter is the user-supplied values for this model. Other Parameters: These parameters are **kwargs that are described below: alpha: This parameter is used to set all alpha keyword arguments at once. color: This parameter is used to to set all color keyword arguments at once. legend_field: This parameter is the name of a column in the data source that should be used or the grouping. legend_group: This parameter is the name of a column in the data source that should be used or the grouping. legend_label: This parameter is the legend entry is labeled with exactly the text supplied here. muted: This parameter contains the bool value. name: This parameter is the optional user-supplied name to attach to the renderer. source: This parameter is the user-supplied data source. view: This parameter is the view for filtering the data source. visible: This parameter contains the bool value. x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates. y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates. level: This parameter specify the render level order for this glyph. Return: This method return the GlyphRenderer value. Below examples illustrate the bokeh.plotting.figure.step() function in bokeh.plotting:Example 1: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = np.arange(16) y = np.sin(x / 3) plot = figure(plot_width = 300, plot_height = 300) plot.step(x = x, y = y + 2, color ='green')plot.line(x, y + 2, color ='black', line_alpha = 0.3, line_dash = "dashed") show(plot) Output: Example 2: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = np.arange(16) y = np.sin(x / 3) plot = figure(plot_width=300, plot_height=300) plot.step(x=x, y=y+2, color ='blue', legend_label = 'pre')plot.line(x, y+2,color ='black', line_alpha = 0.3 , line_dash = "dashed") plot.step(x=x, y=y+1, color ='orange', legend_label = 'mid')plot.line(x, y+1, color ='black', line_alpha = 0.3 , line_dash = "dashed") plot.step(x=x, y=y, color ='green', legend_label = 'post')plot.line(x, y, color ='black', line_alpha = 0.3 , line_dash = "dashed") show(plot) Output: Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n15 Jun, 2020" }, { "code": null, "e": 25981, "s": 25647, "text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc." }, { "code": null, "e": 26094, "s": 25981, "text": "The step() function in plotting module of bokeh library is used to configure and add Step glyphs to this Figure." }, { "code": null, "e": 26281, "s": 26094, "text": "Syntax: step(x, y, *, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, mode=’before’, name=None, tags=[], **kwargs)" }, { "code": null, "e": 26363, "s": 26281, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26417, "s": 26363, "text": "x: This parameter is the x-coordinates for the steps." }, { "code": null, "e": 26471, "s": 26417, "text": "y: This parameter is the y-coordinates for the steps." }, { "code": null, "e": 26565, "s": 26471, "text": "line_alpha: This parameter is the line alpha values for the steps with default value of 1.0 ." }, { "code": null, "e": 26655, "s": 26565, "text": "line_cap: This parameter is the line cap values for the steps with default value of butt." }, { "code": null, "e": 26750, "s": 26655, "text": "line_color: This parameter is the line color values for the steps with default value of black." }, { "code": null, "e": 26840, "s": 26750, "text": "line_dash: This parameter is the line dash values for the steps with default value of []." }, { "code": null, "e": 26943, "s": 26840, "text": "line_dash_offset: This parameter is the line dash offset values for the steps with default value of 0." }, { "code": null, "e": 27036, "s": 26943, "text": "line_join: This parameter is the line join values for the steps with default value of bevel." }, { "code": null, "e": 27127, "s": 27036, "text": "line_width: This parameter is the line width values for the steps with default value of 1." }, { "code": null, "e": 27208, "s": 27127, "text": "mode: This parameter can be one of three values : [“before”, “after”, “center”]." }, { "code": null, "e": 27271, "s": 27208, "text": "name: This parameter is the user-supplied name for this model." }, { "code": null, "e": 27336, "s": 27271, "text": "tags: This parameter is the user-supplied values for this model." }, { "code": null, "e": 27410, "s": 27336, "text": "Other Parameters: These parameters are **kwargs that are described below:" }, { "code": null, "e": 27484, "s": 27410, "text": "alpha: This parameter is used to set all alpha keyword arguments at once." }, { "code": null, "e": 27561, "s": 27484, "text": "color: This parameter is used to to set all color keyword arguments at once." }, { "code": null, "e": 27670, "s": 27561, "text": "legend_field: This parameter is the name of a column in the data source that should be used or the grouping." }, { "code": null, "e": 27779, "s": 27670, "text": "legend_group: This parameter is the name of a column in the data source that should be used or the grouping." }, { "code": null, "e": 27876, "s": 27779, "text": "legend_label: This parameter is the legend entry is labeled with exactly the text supplied here." }, { "code": null, "e": 27923, "s": 27876, "text": "muted: This parameter contains the bool value." }, { "code": null, "e": 28006, "s": 27923, "text": "name: This parameter is the optional user-supplied name to attach to the renderer." }, { "code": null, "e": 28063, "s": 28006, "text": "source: This parameter is the user-supplied data source." }, { "code": null, "e": 28127, "s": 28063, "text": "view: This parameter is the view for filtering the data source." }, { "code": null, "e": 28176, "s": 28127, "text": "visible: This parameter contains the bool value." }, { "code": null, "e": 28269, "s": 28176, "text": "x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates." }, { "code": null, "e": 28362, "s": 28269, "text": "y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates." }, { "code": null, "e": 28431, "s": 28362, "text": "level: This parameter specify the render level order for this glyph." }, { "code": null, "e": 28483, "s": 28431, "text": "Return: This method return the GlyphRenderer value." }, { "code": null, "e": 28580, "s": 28483, "text": "Below examples illustrate the bokeh.plotting.figure.step() function in bokeh.plotting:Example 1:" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = np.arange(16) y = np.sin(x / 3) plot = figure(plot_width = 300, plot_height = 300) plot.step(x = x, y = y + 2, color ='green')plot.line(x, y + 2, color ='black', line_alpha = 0.3, line_dash = \"dashed\") show(plot)", "e": 28936, "s": 28580, "text": null }, { "code": null, "e": 28944, "s": 28936, "text": "Output:" }, { "code": null, "e": 28955, "s": 28944, "text": "Example 2:" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = np.arange(16) y = np.sin(x / 3) plot = figure(plot_width=300, plot_height=300) plot.step(x=x, y=y+2, color ='blue', legend_label = 'pre')plot.line(x, y+2,color ='black', line_alpha = 0.3 , line_dash = \"dashed\") plot.step(x=x, y=y+1, color ='orange', legend_label = 'mid')plot.line(x, y+1, color ='black', line_alpha = 0.3 , line_dash = \"dashed\") plot.step(x=x, y=y, color ='green', legend_label = 'post')plot.line(x, y, color ='black', line_alpha = 0.3 , line_dash = \"dashed\") show(plot)", "e": 29669, "s": 28955, "text": null }, { "code": null, "e": 29677, "s": 29669, "text": "Output:" }, { "code": null, "e": 29690, "s": 29677, "text": "Python-Bokeh" }, { "code": null, "e": 29697, "s": 29690, "text": "Python" }, { "code": null, "e": 29795, "s": 29697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29827, "s": 29795, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29869, "s": 29827, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29911, "s": 29869, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29967, "s": 29911, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29994, "s": 29967, "text": "Python Classes and Objects" }, { "code": null, "e": 30025, "s": 29994, "text": "Python | os.path.join() method" }, { "code": null, "e": 30054, "s": 30025, "text": "Create a directory in Python" }, { "code": null, "e": 30076, "s": 30054, "text": "Defaultdict in Python" }, { "code": null, "e": 30112, "s": 30076, "text": "Python | Pandas dataframe.groupby()" } ]
How to Solve Class Cast Exceptions in Java? - GeeksforGeeks
08 Jun, 2021 An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally. There are mainly two types of exception in java as follows: 1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error. Examples of checked exceptions are classNotFoundException, IOException, SQLException etc. 2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked exceptions are ArithmeticException, ArrayStoreException etc. Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time. ClassCastException: It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM whenever we try to improperly typecast a class from one type to another i.e when we’re trying to typecast parent object to child type or when we try to typecast an object to a subclass of which it is not an instance. In the below program we create an object o of type Object and typecasting that object o to a String object s. As we know that Object class is the parent class of all classes in java and as we’re trying to typecast a parent object to its child type then ultimately we get java.lang.ClassCastException Java // import required packagesimport java.io.*;import java.lang.*;import java.util.*;// driver classclass geeks { // main method public static void main(String[] args) { try { // creating an object Object o = new Object(); // type casting the object o to string which // give the classcasted exception because we // type cast an parent type to its child type. String s = (String)o; System.out.println(s); } catch (Exception e) { System.out.println(e); } }} java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap') In order to deal with ClassCastException be careful that when you’re trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type. While using Collections we can prevent ClassCastException by using generics because generics provide the compile-time checking. Below is the implementation of the problem statement: Java // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass geeks { // main method public static void main(String[] args) { try { // creating an object String s = "GFG"; Object o = (Object)s; // Object class is parent class of every class // Hence exception doesn't occur. System.out.println(o); } catch (Exception e) { System.out.println(e); } }} GFG adnanirshad158 Java-Exceptions Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n08 Jun, 2021" }, { "code": null, "e": 25863, "s": 25347, "text": "An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally." }, { "code": null, "e": 25923, "s": 25863, "text": "There are mainly two types of exception in java as follows:" }, { "code": null, "e": 26280, "s": 25923, "text": "1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error." }, { "code": null, "e": 26370, "s": 26280, "text": "Examples of checked exceptions are classNotFoundException, IOException, SQLException etc." }, { "code": null, "e": 26541, "s": 26370, "text": "2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception." }, { "code": null, "e": 26624, "s": 26541, "text": "Examples of unchecked exceptions are ArithmeticException, ArrayStoreException etc." }, { "code": null, "e": 26776, "s": 26624, "text": "Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time." }, { "code": null, "e": 27139, "s": 26776, "text": "ClassCastException: It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM whenever we try to improperly typecast a class from one type to another i.e when we’re trying to typecast parent object to child type or when we try to typecast an object to a subclass of which it is not an instance." }, { "code": null, "e": 27439, "s": 27139, "text": "In the below program we create an object o of type Object and typecasting that object o to a String object s. As we know that Object class is the parent class of all classes in java and as we’re trying to typecast a parent object to its child type then ultimately we get java.lang.ClassCastException" }, { "code": null, "e": 27444, "s": 27439, "text": "Java" }, { "code": "// import required packagesimport java.io.*;import java.lang.*;import java.util.*;// driver classclass geeks { // main method public static void main(String[] args) { try { // creating an object Object o = new Object(); // type casting the object o to string which // give the classcasted exception because we // type cast an parent type to its child type. String s = (String)o; System.out.println(s); } catch (Exception e) { System.out.println(e); } }}", "e": 28062, "s": 27444, "text": null }, { "code": null, "e": 28245, "s": 28065, "text": "java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')" }, { "code": null, "e": 28624, "s": 28245, "text": "In order to deal with ClassCastException be careful that when you’re trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type. While using Collections we can prevent ClassCastException by using generics because generics provide the compile-time checking." }, { "code": null, "e": 28680, "s": 28626, "text": "Below is the implementation of the problem statement:" }, { "code": null, "e": 28687, "s": 28682, "text": "Java" }, { "code": "// import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass geeks { // main method public static void main(String[] args) { try { // creating an object String s = \"GFG\"; Object o = (Object)s; // Object class is parent class of every class // Hence exception doesn't occur. System.out.println(o); } catch (Exception e) { System.out.println(e); } }}", "e": 29221, "s": 28687, "text": null }, { "code": null, "e": 29228, "s": 29224, "text": "GFG" }, { "code": null, "e": 29245, "s": 29230, "text": "adnanirshad158" }, { "code": null, "e": 29261, "s": 29245, "text": "Java-Exceptions" }, { "code": null, "e": 29268, "s": 29261, "text": "Picked" }, { "code": null, "e": 29292, "s": 29268, "text": "Technical Scripter 2020" }, { "code": null, "e": 29297, "s": 29292, "text": "Java" }, { "code": null, "e": 29316, "s": 29297, "text": "Technical Scripter" }, { "code": null, "e": 29321, "s": 29316, "text": "Java" }, { "code": null, "e": 29419, "s": 29321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29434, "s": 29419, "text": "Stream In Java" }, { "code": null, "e": 29455, "s": 29434, "text": "Constructors in Java" }, { "code": null, "e": 29474, "s": 29455, "text": "Exceptions in Java" }, { "code": null, "e": 29504, "s": 29474, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29550, "s": 29504, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29567, "s": 29550, "text": "Generics in Java" }, { "code": null, "e": 29588, "s": 29567, "text": "Introduction to Java" }, { "code": null, "e": 29631, "s": 29588, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29653, "s": 29631, "text": "PriorityQueue in Java" } ]
How to Calculate Weighted MAPE in Excel? - GeeksforGeeks
28 Jul, 2021 In statistics, we often use Forecasting Accuracy which denotes the closeness of a quantity to the actual value of that particular quantity. The actual value is also known as the true value. It basically denotes the degree of closeness or a verification process that is highly used by business professionals to keep track records of their sales and exchanges to maintain the demand and supply mapping every year. There are various methods to calculate Forecasting Accuracy. So, one of the most common methods used to calculate the Forecasting Accuracy is MAPE which is abbreviated as Mean Absolute Percentage Error. It is an effective and more convenient method because it becomes easier to interpret the accuracy just by seeing the MAPE value. Here, we face a problem of infinite error when the Actual value of any entity becomes zero. WMAPE or Weighted MAPE abbreviated as Weighted Mean Absolute Percentage Error is also an accuracy prediction technique. Here, the problem of infinite error (divide by zero) is removed since the summation of actual value in the denominator can never be zero. It calculates the error based on weights but in case of MAPE error was calculated based on the average values. So, WMAPE is more reliable and gives efficient accuracy than MAPE. The formula to calculate WMAPE in Excel is : In this article we are going to discuss how to calculate WMAPE in Excel using a suitable example. Example : Consider the dataset shown below : The functions needed for formulas in Excel are- SUM : To calculate the sum of multiple values ABS : To calculate the absolute value. The steps are : 1. Insert the data set in the Excel sheet. 2. Calculate the sub part of the formula inside the summation which is also known as Weighted Error. =ABS(Cell_No_Act-Cell_No_Fore) where ABS : Used to calculate the absolute value Cell_No_Act : Cell number where Actual value is present Cell_No_Fore : Cell number where Forecast value is present The above formula will calculate the weighted error for the first entry in the data set. Now, you can drag the Auto Fill Options button to get the weighted error for the remaining entries. 3. Now use the SUM function to find the summation of both weighted errors and the actual values and divide them to get the WMAPE. The entries of Weighted Error are in the Cell range : D3 to D12 The entries of Actual Value are in the Cell range : B3 to B12 The value of WMAPE is 0.09189 or 9.189% approximately. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Show Percentages in Stacked Column Chart in Excel? How to Get Length of Array in Excel VBA? How to Remove Duplicates From Array Using VBA in Excel? Introduction to Excel Spreadsheet Macros in Excel How to Extract the Last Word From a Cell in Excel? How to Sum Values Based on Criteria in Another Column in Excel? How to Easily Calculate the Dot Product in Excel?
[ { "code": null, "e": 25044, "s": 25016, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25517, "s": 25044, "text": "In statistics, we often use Forecasting Accuracy which denotes the closeness of a quantity to the actual value of that particular quantity. The actual value is also known as the true value. It basically denotes the degree of closeness or a verification process that is highly used by business professionals to keep track records of their sales and exchanges to maintain the demand and supply mapping every year. There are various methods to calculate Forecasting Accuracy." }, { "code": null, "e": 25880, "s": 25517, "text": "So, one of the most common methods used to calculate the Forecasting Accuracy is MAPE which is abbreviated as Mean Absolute Percentage Error. It is an effective and more convenient method because it becomes easier to interpret the accuracy just by seeing the MAPE value. Here, we face a problem of infinite error when the Actual value of any entity becomes zero." }, { "code": null, "e": 26316, "s": 25880, "text": "WMAPE or Weighted MAPE abbreviated as Weighted Mean Absolute Percentage Error is also an accuracy prediction technique. Here, the problem of infinite error (divide by zero) is removed since the summation of actual value in the denominator can never be zero. It calculates the error based on weights but in case of MAPE error was calculated based on the average values. So, WMAPE is more reliable and gives efficient accuracy than MAPE." }, { "code": null, "e": 26361, "s": 26316, "text": "The formula to calculate WMAPE in Excel is :" }, { "code": null, "e": 26459, "s": 26361, "text": "In this article we are going to discuss how to calculate WMAPE in Excel using a suitable example." }, { "code": null, "e": 26504, "s": 26459, "text": "Example : Consider the dataset shown below :" }, { "code": null, "e": 26552, "s": 26504, "text": "The functions needed for formulas in Excel are-" }, { "code": null, "e": 26598, "s": 26552, "text": "SUM : To calculate the sum of multiple values" }, { "code": null, "e": 26637, "s": 26598, "text": "ABS : To calculate the absolute value." }, { "code": null, "e": 26653, "s": 26637, "text": "The steps are :" }, { "code": null, "e": 26696, "s": 26653, "text": "1. Insert the data set in the Excel sheet." }, { "code": null, "e": 26797, "s": 26696, "text": "2. Calculate the sub part of the formula inside the summation which is also known as Weighted Error." }, { "code": null, "e": 26993, "s": 26797, "text": "=ABS(Cell_No_Act-Cell_No_Fore)\n\nwhere\nABS : Used to calculate the absolute value\nCell_No_Act : Cell number where Actual value is present\nCell_No_Fore : Cell number where Forecast value is present" }, { "code": null, "e": 27182, "s": 26993, "text": "The above formula will calculate the weighted error for the first entry in the data set. Now, you can drag the Auto Fill Options button to get the weighted error for the remaining entries." }, { "code": null, "e": 27312, "s": 27182, "text": "3. Now use the SUM function to find the summation of both weighted errors and the actual values and divide them to get the WMAPE." }, { "code": null, "e": 27376, "s": 27312, "text": "The entries of Weighted Error are in the Cell range : D3 to D12" }, { "code": null, "e": 27438, "s": 27376, "text": "The entries of Actual Value are in the Cell range : B3 to B12" }, { "code": null, "e": 27493, "s": 27438, "text": "The value of WMAPE is 0.09189 or 9.189% approximately." }, { "code": null, "e": 27500, "s": 27493, "text": "Picked" }, { "code": null, "e": 27506, "s": 27500, "text": "Excel" }, { "code": null, "e": 27604, "s": 27506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27632, "s": 27604, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 27687, "s": 27632, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 27745, "s": 27687, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 27786, "s": 27745, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 27842, "s": 27786, "text": "How to Remove Duplicates From Array Using VBA in Excel?" }, { "code": null, "e": 27876, "s": 27842, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 27892, "s": 27876, "text": "Macros in Excel" }, { "code": null, "e": 27943, "s": 27892, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 28007, "s": 27943, "text": "How to Sum Values Based on Criteria in Another Column in Excel?" } ]
How to replace a particular character in a MySQL column?
To replace a particular character, use REPLACE() and to update, use the UPDATE command. Let us first create a table − mysql> create table DemoTable1899 ( Code varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1899 values('John_123'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1899 values('32189_Sam_987'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1899 values('Miller_David_456_909'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1899; This will produce the following output − +----------------------+ | Code | +----------------------+ | John_123 | | 32189_Sam_987 | | Miller_David_456_909 | +----------------------+ 3 rows in set (0.00 sec) Here is the query to replace a particular character − mysql> update DemoTable1899 set Code=replace(Code,'_',''); Query OK, 3 rows affected (0.00 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the table records once again: mysql> select * from DemoTable1899; This will produce the following output − +-------------------+ | Code | +-------------------+ | John123 | | 32189Sam987 | | MillerDavid456909 | +-------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1180, "s": 1062, "text": "To replace a particular character, use REPLACE() and to update, use the UPDATE command. Let us first create a table −" }, { "code": null, "e": 1282, "s": 1180, "text": "mysql> create table DemoTable1899\n (\n Code varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1338, "s": 1282, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1622, "s": 1338, "text": "mysql> insert into DemoTable1899 values('John_123');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1899 values('32189_Sam_987');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1899 values('Miller_David_456_909');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1682, "s": 1622, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1718, "s": 1682, "text": "mysql> select * from DemoTable1899;" }, { "code": null, "e": 1759, "s": 1718, "text": "This will produce the following output −" }, { "code": null, "e": 1959, "s": 1759, "text": "+----------------------+\n| Code |\n+----------------------+\n| John_123 |\n| 32189_Sam_987 |\n| Miller_David_456_909 |\n+----------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2013, "s": 1959, "text": "Here is the query to replace a particular character −" }, { "code": null, "e": 2149, "s": 2013, "text": "mysql> update DemoTable1899 set Code=replace(Code,'_','');\nQuery OK, 3 rows affected (0.00 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2192, "s": 2149, "text": "Let us check the table records once again:" }, { "code": null, "e": 2228, "s": 2192, "text": "mysql> select * from DemoTable1899;" }, { "code": null, "e": 2269, "s": 2228, "text": "This will produce the following output −" }, { "code": null, "e": 2448, "s": 2269, "text": "+-------------------+\n| Code |\n+-------------------+\n| John123 |\n| 32189Sam987 |\n| MillerDavid456909 |\n+-------------------+\n3 rows in set (0.00 sec)" } ]
VBA - InputBox
The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks the Cancel button, the function will return an empty string (""). InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context]) Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Default − An optional parameter. A default text in the text box that the user would like to be displayed. Default − An optional parameter. A default text in the text box that the user would like to be displayed. XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered. XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered. YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered. YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered. Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box. Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box. context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Let us calculate the area of a rectangle by getting values from the user at run time with the help of two input boxes (one for length and one for width). Function findArea() Dim Length As Double Dim Width As Double Length = InputBox("Enter Length ", "Enter a Number") Width = InputBox("Enter Width", "Enter a Number") findArea = Length * Width End Function Step 1 − To execute the same, call using the function name and press Enter as shown in the following screenshot. Step 2 − Upon execution, the First input box (length) is displayed. Enter a value into the input box. Step 3 − After entering the first value, the second input box (width) is displayed. Step 4 − Upon entering the second number, click the OK button. The area is displayed as shown in the following screenshot. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2231, "s": 1935, "text": "The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks the Cancel button, the function will return an empty string (\"\")." }, { "code": null, "e": 2300, "s": 2231, "text": "InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])\n" }, { "code": null, "e": 2626, "s": 2300, "text": "Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 2952, "s": 2626, "text": "Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line." }, { "code": null, "e": 3126, "s": 2952, "text": "Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 3300, "s": 3126, "text": "Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar." }, { "code": null, "e": 3406, "s": 3300, "text": "Default − An optional parameter. A default text in the text box that the user would like to be displayed." }, { "code": null, "e": 3512, "s": 3406, "text": "Default − An optional parameter. A default text in the text box that the user would like to be displayed." }, { "code": null, "e": 3698, "s": 3512, "text": "XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered." }, { "code": null, "e": 3884, "s": 3698, "text": "XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered." }, { "code": null, "e": 4066, "s": 3884, "text": "YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered." }, { "code": null, "e": 4248, "s": 4066, "text": "YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered." }, { "code": null, "e": 4396, "s": 4248, "text": "Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box." }, { "code": null, "e": 4544, "s": 4396, "text": "Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box." }, { "code": null, "e": 4753, "s": 4544, "text": "context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 4962, "s": 4753, "text": "context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided." }, { "code": null, "e": 5116, "s": 4962, "text": "Let us calculate the area of a rectangle by getting values from the user at run time with the help of two input boxes (one for length and one for width)." }, { "code": null, "e": 5344, "s": 5116, "text": "Function findArea() \n Dim Length As Double \n Dim Width As Double \n \n Length = InputBox(\"Enter Length \", \"Enter a Number\") \n Width = InputBox(\"Enter Width\", \"Enter a Number\") \n findArea = Length * Width \nEnd Function" }, { "code": null, "e": 5457, "s": 5344, "text": "Step 1 − To execute the same, call using the function name and press Enter as shown in the following screenshot." }, { "code": null, "e": 5559, "s": 5457, "text": "Step 2 − Upon execution, the First input box (length) is displayed. Enter a value into the input box." }, { "code": null, "e": 5643, "s": 5559, "text": "Step 3 − After entering the first value, the second input box (width) is displayed." }, { "code": null, "e": 5766, "s": 5643, "text": "Step 4 − Upon entering the second number, click the OK button. The area is displayed as shown in the following screenshot." }, { "code": null, "e": 5800, "s": 5766, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 5815, "s": 5800, "text": " Pavan Lalwani" }, { "code": null, "e": 5848, "s": 5815, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 5863, "s": 5848, "text": " Arnold Higuit" }, { "code": null, "e": 5898, "s": 5863, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5916, "s": 5898, "text": " Prashant Panchal" }, { "code": null, "e": 5949, "s": 5916, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 5967, "s": 5949, "text": " Prashant Panchal" }, { "code": null, "e": 6000, "s": 5967, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6015, "s": 6000, "text": " Arnold Higuit" }, { "code": null, "e": 6051, "s": 6015, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6079, "s": 6051, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6086, "s": 6079, "text": " Print" }, { "code": null, "e": 6097, "s": 6086, "text": " Add Notes" } ]
VB.Net - Date & Time
Most of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. VB.Net also provides powerful tools for date arithmetic that makes manipulating dates easy. The Date data type contains date values, time values, or date and time values. The default value of Date is 0:00:00 (midnight) on January 1, 0001. The equivalent .NET data type is System.DateTime. The DateTime structure represents an instant in time, typically expressed as a date and time of day 'Declaration <SerializableAttribute> _ Public Structure DateTime _ Implements IComparable, IFormattable, IConvertible, ISerializable, IComparable(Of DateTime), IEquatable(Of DateTime) You can also get the current date and time from the DateAndTime class. The DateAndTime module contains the procedures and properties used in date and time operations. 'Declaration <StandardModuleAttribute> _ Public NotInheritable Class DateAndTime Note: Both the DateTime structure and the DateAndTime module contain properties like Now and Today, so often beginners find it confusing. The DateAndTime class belongs to the Microsoft.VisualBasic namespace and the DateTime structure belongs to the System namespace. Therefore, using the later would help you in porting your code to another .Net language like C#. However, the DateAndTime class/module contains all the legacy date functions available in Visual Basic. The following table lists some of the commonly used properties of the DateTime Structure − The following table lists some of the commonly used methods of the DateTime structure − Public Function Add (value As TimeSpan) As DateTime Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance. Public Function AddDays ( value As Double) As DateTime Returns a new DateTime that adds the specified number of days to the value of this instance. Public Function AddHours (value As Double) As DateTime Returns a new DateTime that adds the specified number of hours to the value of this instance. Public Function AddMinutes (value As Double) As DateTime Returns a new DateTime that adds the specified number of minutes to the value of this instance. Public Function AddMonths (months As Integer) As DateTime Returns a new DateTime that adds the specified number of months to the value of this instance. Public Function AddSeconds (value As Double) As DateTime Returns a new DateTime that adds the specified number of seconds to the value of this instance. Public Function AddYears (value As Integer ) As DateTime Returns a new DateTime that adds the specified number of years to the value of this instance. Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. Public Function CompareTo (value As DateTime) As Integer Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. Public Function Equals (value As DateTime) As Boolean Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance. Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean Returns a value indicating whether two DateTime instances have the same date and time value. Public Overrides Function ToString As String Converts the value of the current DateTime object to its equivalent string representation. The above list of methods is not exhaustive, please visit Microsoft documentation for the complete list of methods and properties of the DateTime structure. You can create a DateTime object in one of the following ways − By calling a DateTime constructor from any of the overloaded DateTime constructors. By calling a DateTime constructor from any of the overloaded DateTime constructors. By assigning the DateTime object a date and time value returned by a property or method. By assigning the DateTime object a date and time value returned by a property or method. By parsing the string representation of a date and time value. By parsing the string representation of a date and time value. By calling the DateTime structure's implicit default constructor. By calling the DateTime structure's implicit default constructor. The following example demonstrates this − Module Module1 Sub Main() 'DateTime constructor: parameters year, month, day, hour, min, sec Dim date1 As New Date(2012, 12, 16, 12, 0, 0) 'initializes a new DateTime value Dim date2 As Date = #12/16/2012 12:00:52 AM# 'using properties Dim date3 As Date = Date.Now Dim date4 As Date = Date.UtcNow Dim date5 As Date = Date.Today Console.WriteLine(date1) Console.WriteLine(date2) Console.WriteLine(date3) Console.WriteLine(date4) Console.WriteLine(date5) Console.ReadKey() End Sub End Module When the above code was compiled and executed, it produces the following result − 12/16/2012 12:00:00 PM 12/16/2012 12:00:52 PM 12/12/2012 10:22:50 PM 12/12/2012 12:00:00 PM The following programs demonstrate how to get the current date and time in VB.Net − Current Time − Module dateNtime Sub Main() Console.Write("Current Time: ") Console.WriteLine(Now.ToLongTimeString) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Current Time: 11 :05 :32 AM Current Date − Module dateNtime Sub Main() Console.WriteLine("Current Date: ") Dim dt As Date = Today Console.WriteLine("Today is: {0}", dt) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Today is: 12/11/2012 12:00:00 AM A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for example #12/16/2012#. Otherwise, your code may change depending on the locale in which your application is running. For example, you specified Date literal of #2/6/2012# for the date February 6, 2012. It is alright for the locale that uses mm/dd/yyyy format. However, in a locale that uses dd/mm/yyyy format, your literal would compile to June 2, 2012. If a locale uses another format say, yyyy/mm/dd, the literal would be invalid and cause a compiler error. To convert a Date literal to the format of your locale or to a custom format, use the Format function of String class, specifying either a predefined or user-defined date format. The following example demonstrates this. Module dateNtime Sub Main() Console.WriteLine("India Wins Freedom: ") Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0) ' Use format specifiers to control the date display. Console.WriteLine(" Format 'd:' " & independenceDay.ToString("d")) Console.WriteLine(" Format 'D:' " & independenceDay.ToString("D")) Console.WriteLine(" Format 't:' " & independenceDay.ToString("t")) Console.WriteLine(" Format 'T:' " & independenceDay.ToString("T")) Console.WriteLine(" Format 'f:' " & independenceDay.ToString("f")) Console.WriteLine(" Format 'F:' " & independenceDay.ToString("F")) Console.WriteLine(" Format 'g:' " & independenceDay.ToString("g")) Console.WriteLine(" Format 'G:' " & independenceDay.ToString("G")) Console.WriteLine(" Format 'M:' " & independenceDay.ToString("M")) Console.WriteLine(" Format 'R:' " & independenceDay.ToString("R")) Console.WriteLine(" Format 'y:' " & independenceDay.ToString("y")) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − India Wins Freedom: Format 'd:' 8/15/1947 Format 'D:' Friday, August 15, 1947 Format 't:' 12:00 AM Format 'T:' 12:00:00 AM Format 'f:' Friday, August 15, 1947 12:00 AM Format 'F:' Friday, August 15, 1947 12:00:00 AM Format 'g:' 8/15/1947 12:00 AM Format 'G:' 8/15/1947 12:00:00 AM Format 'M:' 8/15/1947 August 15 Format 'R:' Fri, 15 August 1947 00:00:00 GMT Format 'y:' August, 1947 The following table identifies the predefined date and time format names. These may be used by name as the style argument for the Format function − For other formats like user-defined formats, please consult Microsoft Documentation. The following table lists some of the commonly used properties of the DateAndTime Class − Date Returns or sets a String value representing the current date according to your system. Now Returns a Date value containing the current date and time according to your system. TimeOfDay Returns or sets a Date value containing the current time of day according to your system. Timer Returns a Double value representing the number of seconds elapsed since midnight. TimeString Returns or sets a String value representing the current time of day according to your system. Today Gets the current date. The following table lists some of the commonly used methods of the DateAndTime class − Public Shared Function DateAdd (Interval As DateInterval, Number As Double, DateValue As DateTime) As DateTime Returns a Date value containing a date and time value to which a specified time interval has been added. Public Shared Function DateAdd (Interval As String,Number As Double,DateValue As Object ) As DateTime Returns a Date value containing a date and time value to which a specified time interval has been added. Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As FirstWeekOfYear ) As Long Returns a Long value specifying the number of time intervals between two Date values. Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As FirstWeekOfYear ) As Integer Returns an Integer value containing the specified component of a given Date value. Public Shared Function Day (DateValue As DateTime) As Integer Returns an Integer value from 1 through 31 representing the day of the month. Public Shared Function Hour (TimeValue As DateTime) As Integer Returns an Integer value from 0 through 23 representing the hour of the day. Public Shared Function Minute (TimeValue As DateTime) As Integer Returns an Integer value from 0 through 59 representing the minute of the hour. Public Shared Function Month (DateValue As DateTime) As Integer Returns an Integer value from 1 through 12 representing the month of the year. Public Shared Function MonthName (Month As Integer, Abbreviate As Boolean) As String Returns a String value containing the name of the specified month. Public Shared Function Second (TimeValue As DateTime) As Integer Returns an Integer value from 0 through 59 representing the second of the minute. Public Overridable Function ToString As String Returns a string that represents the current object. Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As FirstDayOfWeek) As Integer Returns an Integer value containing a number representing the day of the week. Public Shared Function WeekdayName (Weekday As Integer, Abbreviate As Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As String Returns a String value containing the name of the specified weekday. Public Shared Function Year (DateValue As DateTime) As Integer Returns an Integer value from 1 through 9999 representing the year. The above list is not exhaustive. For complete list of properties and methods of the DateAndTime class, please consult Microsoft Documentation. The following program demonstrates some of these and methods − Module Module1 Sub Main() Dim birthday As Date Dim bday As Integer Dim month As Integer Dim monthname As String ' Assign a date using standard short format. birthday = #7/27/1998# bday = Microsoft.VisualBasic.DateAndTime.Day(birthday) month = Microsoft.VisualBasic.DateAndTime.Month(birthday) monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month) Console.WriteLine(birthday) Console.WriteLine(bday) Console.WriteLine(month) Console.WriteLine(monthname) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − 7/27/1998 12:00:00 AM 27 7 July 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2600, "s": 2300, "text": "Most of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. VB.Net also provides powerful tools for date arithmetic that makes manipulating dates easy." }, { "code": null, "e": 2797, "s": 2600, "text": "The Date data type contains date values, time values, or date and time values. The default value of Date is 0:00:00 (midnight) on January 1, 0001. The equivalent .NET data type is System.DateTime." }, { "code": null, "e": 2897, "s": 2797, "text": "The DateTime structure represents an instant in time, typically expressed as a date and time of day" }, { "code": null, "e": 3090, "s": 2897, "text": "'Declaration\n<SerializableAttribute> _\nPublic Structure DateTime _\n Implements IComparable, IFormattable, IConvertible, ISerializable, \n IComparable(Of DateTime), IEquatable(Of DateTime)\n" }, { "code": null, "e": 3161, "s": 3090, "text": "You can also get the current date and time from the DateAndTime class." }, { "code": null, "e": 3257, "s": 3161, "text": "The DateAndTime module contains the procedures and properties used in date and time operations." }, { "code": null, "e": 3339, "s": 3257, "text": "'Declaration\n<StandardModuleAttribute> _\nPublic NotInheritable Class DateAndTime\n" }, { "code": null, "e": 3345, "s": 3339, "text": "Note:" }, { "code": null, "e": 3807, "s": 3345, "text": "Both the DateTime structure and the DateAndTime module contain properties like Now and Today, so often beginners find it confusing. The DateAndTime class belongs to the Microsoft.VisualBasic namespace and the DateTime structure belongs to the System namespace. Therefore, using the later would help you in porting your code to another .Net language like C#. However, the DateAndTime class/module contains all the legacy date functions available in Visual Basic." }, { "code": null, "e": 3898, "s": 3807, "text": "The following table lists some of the commonly used properties of the DateTime Structure −" }, { "code": null, "e": 3986, "s": 3898, "text": "The following table lists some of the commonly used methods of the DateTime structure −" }, { "code": null, "e": 4038, "s": 3986, "text": "Public Function Add (value As TimeSpan) As DateTime" }, { "code": null, "e": 4138, "s": 4038, "text": "Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance." }, { "code": null, "e": 4193, "s": 4138, "text": "Public Function AddDays ( value As Double) As DateTime" }, { "code": null, "e": 4286, "s": 4193, "text": "Returns a new DateTime that adds the specified number of days to the value of this instance." }, { "code": null, "e": 4341, "s": 4286, "text": "Public Function AddHours (value As Double) As DateTime" }, { "code": null, "e": 4435, "s": 4341, "text": "Returns a new DateTime that adds the specified number of hours to the value of this instance." }, { "code": null, "e": 4492, "s": 4435, "text": "Public Function AddMinutes (value As Double) As DateTime" }, { "code": null, "e": 4588, "s": 4492, "text": "Returns a new DateTime that adds the specified number of minutes to the value of this instance." }, { "code": null, "e": 4646, "s": 4588, "text": "Public Function AddMonths (months As Integer) As DateTime" }, { "code": null, "e": 4741, "s": 4646, "text": "Returns a new DateTime that adds the specified number of months to the value of this instance." }, { "code": null, "e": 4798, "s": 4741, "text": "Public Function AddSeconds (value As Double) As DateTime" }, { "code": null, "e": 4894, "s": 4798, "text": "Returns a new DateTime that adds the specified number of seconds to the value of this instance." }, { "code": null, "e": 4951, "s": 4894, "text": "Public Function AddYears (value As Integer ) As DateTime" }, { "code": null, "e": 5045, "s": 4951, "text": "Returns a new DateTime that adds the specified number of years to the value of this instance." }, { "code": null, "e": 5119, "s": 5045, "text": "Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer" }, { "code": null, "e": 5284, "s": 5119, "text": "Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance." }, { "code": null, "e": 5341, "s": 5284, "text": "Public Function CompareTo (value As DateTime) As Integer" }, { "code": null, "e": 5541, "s": 5341, "text": "Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value." }, { "code": null, "e": 5595, "s": 5541, "text": "Public Function Equals (value As DateTime) As Boolean" }, { "code": null, "e": 5715, "s": 5595, "text": "Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance." }, { "code": null, "e": 5789, "s": 5715, "text": "Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean" }, { "code": null, "e": 5882, "s": 5789, "text": "Returns a value indicating whether two DateTime instances have the same date and time value." }, { "code": null, "e": 5927, "s": 5882, "text": "Public Overrides Function ToString As String" }, { "code": null, "e": 6018, "s": 5927, "text": "Converts the value of the current DateTime object to its equivalent string representation." }, { "code": null, "e": 6175, "s": 6018, "text": "The above list of methods is not exhaustive, please visit Microsoft documentation for the complete list of methods and properties of the DateTime structure." }, { "code": null, "e": 6239, "s": 6175, "text": "You can create a DateTime object in one of the following ways −" }, { "code": null, "e": 6323, "s": 6239, "text": "By calling a DateTime constructor from any of the overloaded DateTime constructors." }, { "code": null, "e": 6407, "s": 6323, "text": "By calling a DateTime constructor from any of the overloaded DateTime constructors." }, { "code": null, "e": 6496, "s": 6407, "text": "By assigning the DateTime object a date and time value returned by a property or method." }, { "code": null, "e": 6585, "s": 6496, "text": "By assigning the DateTime object a date and time value returned by a property or method." }, { "code": null, "e": 6648, "s": 6585, "text": "By parsing the string representation of a date and time value." }, { "code": null, "e": 6711, "s": 6648, "text": "By parsing the string representation of a date and time value." }, { "code": null, "e": 6777, "s": 6711, "text": "By calling the DateTime structure's implicit default constructor." }, { "code": null, "e": 6843, "s": 6777, "text": "By calling the DateTime structure's implicit default constructor." }, { "code": null, "e": 6885, "s": 6843, "text": "The following example demonstrates this −" }, { "code": null, "e": 7472, "s": 6885, "text": "Module Module1\n Sub Main()\n 'DateTime constructor: parameters year, month, day, hour, min, sec\n Dim date1 As New Date(2012, 12, 16, 12, 0, 0)\n 'initializes a new DateTime value\n Dim date2 As Date = #12/16/2012 12:00:52 AM#\n 'using properties\n Dim date3 As Date = Date.Now\n Dim date4 As Date = Date.UtcNow\n Dim date5 As Date = Date.Today\n \n Console.WriteLine(date1)\n Console.WriteLine(date2)\n Console.WriteLine(date3)\n Console.WriteLine(date4)\n Console.WriteLine(date5)\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 7554, "s": 7472, "text": "When the above code was compiled and executed, it produces the following result −" }, { "code": null, "e": 7647, "s": 7554, "text": "12/16/2012 12:00:00 PM\n12/16/2012 12:00:52 PM\n12/12/2012 10:22:50 PM\n12/12/2012 12:00:00 PM\n" }, { "code": null, "e": 7731, "s": 7647, "text": "The following programs demonstrate how to get the current date and time in VB.Net −" }, { "code": null, "e": 7746, "s": 7731, "text": "Current Time −" }, { "code": null, "e": 7907, "s": 7746, "text": "Module dateNtime\n Sub Main()\n Console.Write(\"Current Time: \")\n Console.WriteLine(Now.ToLongTimeString)\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 7988, "s": 7907, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8017, "s": 7988, "text": "Current Time: 11 :05 :32 AM\n" }, { "code": null, "e": 8032, "s": 8017, "text": "Current Date −" }, { "code": null, "e": 8225, "s": 8032, "text": "Module dateNtime\n Sub Main()\n Console.WriteLine(\"Current Date: \")\n Dim dt As Date = Today\n Console.WriteLine(\"Today is: {0}\", dt)\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 8306, "s": 8225, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8340, "s": 8306, "text": "Today is: 12/11/2012 12:00:00 AM\n" }, { "code": null, "e": 8557, "s": 8340, "text": "A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for example #12/16/2012#. Otherwise, your code may change depending on the locale in which your application is running." }, { "code": null, "e": 8900, "s": 8557, "text": "For example, you specified Date literal of #2/6/2012# for the date February 6, 2012. It is alright for the locale that uses mm/dd/yyyy format. However, in a locale that uses dd/mm/yyyy format, your literal would compile to June 2, 2012. If a locale uses another format say, yyyy/mm/dd, the literal would be invalid and cause a compiler error." }, { "code": null, "e": 9079, "s": 8900, "text": "To convert a Date literal to the format of your locale or to a custom format, use the Format function of String class, specifying either a predefined or user-defined date format." }, { "code": null, "e": 9120, "s": 9079, "text": "The following example demonstrates this." }, { "code": null, "e": 10167, "s": 9120, "text": "Module dateNtime\n Sub Main()\n Console.WriteLine(\"India Wins Freedom: \")\n Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0)\n ' Use format specifiers to control the date display.\n Console.WriteLine(\" Format 'd:' \" & independenceDay.ToString(\"d\"))\n Console.WriteLine(\" Format 'D:' \" & independenceDay.ToString(\"D\"))\n Console.WriteLine(\" Format 't:' \" & independenceDay.ToString(\"t\"))\n Console.WriteLine(\" Format 'T:' \" & independenceDay.ToString(\"T\"))\n Console.WriteLine(\" Format 'f:' \" & independenceDay.ToString(\"f\"))\n Console.WriteLine(\" Format 'F:' \" & independenceDay.ToString(\"F\"))\n Console.WriteLine(\" Format 'g:' \" & independenceDay.ToString(\"g\"))\n Console.WriteLine(\" Format 'G:' \" & independenceDay.ToString(\"G\"))\n Console.WriteLine(\" Format 'M:' \" & independenceDay.ToString(\"M\"))\n Console.WriteLine(\" Format 'R:' \" & independenceDay.ToString(\"R\"))\n Console.WriteLine(\" Format 'y:' \" & independenceDay.ToString(\"y\"))\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 10248, "s": 10167, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 10632, "s": 10248, "text": "India Wins Freedom:\nFormat 'd:' 8/15/1947\nFormat 'D:' Friday, August 15, 1947\nFormat 't:' 12:00 AM\nFormat 'T:' 12:00:00 AM\nFormat 'f:' Friday, August 15, 1947 12:00 AM\nFormat 'F:' Friday, August 15, 1947 12:00:00 AM\nFormat 'g:' 8/15/1947 12:00 AM\nFormat 'G:' 8/15/1947 12:00:00 AM\nFormat 'M:' 8/15/1947 August 15\nFormat 'R:' Fri, 15 August 1947 00:00:00 GMT\nFormat 'y:' August, 1947\n" }, { "code": null, "e": 10780, "s": 10632, "text": "The following table identifies the predefined date and time format names. These may be used by name as the style argument for the Format function −" }, { "code": null, "e": 10865, "s": 10780, "text": "For other formats like user-defined formats, please consult Microsoft Documentation." }, { "code": null, "e": 10955, "s": 10865, "text": "The following table lists some of the commonly used properties of the DateAndTime Class −" }, { "code": null, "e": 10960, "s": 10955, "text": "Date" }, { "code": null, "e": 11047, "s": 10960, "text": "Returns or sets a String value representing the current date according to your system." }, { "code": null, "e": 11051, "s": 11047, "text": "Now" }, { "code": null, "e": 11135, "s": 11051, "text": "Returns a Date value containing the current date and time according to your system." }, { "code": null, "e": 11145, "s": 11135, "text": "TimeOfDay" }, { "code": null, "e": 11235, "s": 11145, "text": "Returns or sets a Date value containing the current time of day according to your system." }, { "code": null, "e": 11241, "s": 11235, "text": "Timer" }, { "code": null, "e": 11323, "s": 11241, "text": "Returns a Double value representing the number of seconds elapsed since midnight." }, { "code": null, "e": 11334, "s": 11323, "text": "TimeString" }, { "code": null, "e": 11428, "s": 11334, "text": "Returns or sets a String value representing the current time of day according to your system." }, { "code": null, "e": 11434, "s": 11428, "text": "Today" }, { "code": null, "e": 11457, "s": 11434, "text": "Gets the current date." }, { "code": null, "e": 11544, "s": 11457, "text": "The following table lists some of the commonly used methods of the DateAndTime class −" }, { "code": null, "e": 11655, "s": 11544, "text": "Public Shared Function DateAdd (Interval As DateInterval, Number As Double, DateValue As DateTime) As DateTime" }, { "code": null, "e": 11760, "s": 11655, "text": "Returns a Date value containing a date and time value to which a specified time interval has been added." }, { "code": null, "e": 11862, "s": 11760, "text": "Public Shared Function DateAdd (Interval As String,Number As Double,DateValue As Object ) As DateTime" }, { "code": null, "e": 11967, "s": 11862, "text": "Returns a Date value containing a date and time value to which a specified time interval has been added." }, { "code": null, "e": 12133, "s": 11967, "text": "Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As FirstWeekOfYear ) As Long" }, { "code": null, "e": 12219, "s": 12133, "text": "Returns a Long value specifying the number of time intervals between two Date values." }, { "code": null, "e": 12393, "s": 12219, "text": "Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As FirstWeekOfYear ) As Integer" }, { "code": null, "e": 12476, "s": 12393, "text": "Returns an Integer value containing the specified component of a given Date value." }, { "code": null, "e": 12538, "s": 12476, "text": "Public Shared Function Day (DateValue As DateTime) As Integer" }, { "code": null, "e": 12616, "s": 12538, "text": "Returns an Integer value from 1 through 31 representing the day of the month." }, { "code": null, "e": 12679, "s": 12616, "text": "Public Shared Function Hour (TimeValue As DateTime) As Integer" }, { "code": null, "e": 12756, "s": 12679, "text": "Returns an Integer value from 0 through 23 representing the hour of the day." }, { "code": null, "e": 12821, "s": 12756, "text": "Public Shared Function Minute (TimeValue As DateTime) As Integer" }, { "code": null, "e": 12901, "s": 12821, "text": "Returns an Integer value from 0 through 59 representing the minute of the hour." }, { "code": null, "e": 12965, "s": 12901, "text": "Public Shared Function Month (DateValue As DateTime) As Integer" }, { "code": null, "e": 13044, "s": 12965, "text": "Returns an Integer value from 1 through 12 representing the month of the year." }, { "code": null, "e": 13129, "s": 13044, "text": "Public Shared Function MonthName (Month As Integer, Abbreviate As Boolean) As String" }, { "code": null, "e": 13196, "s": 13129, "text": "Returns a String value containing the name of the specified month." }, { "code": null, "e": 13261, "s": 13196, "text": "Public Shared Function Second (TimeValue As DateTime) As Integer" }, { "code": null, "e": 13343, "s": 13261, "text": "Returns an Integer value from 0 through 59 representing the second of the minute." }, { "code": null, "e": 13390, "s": 13343, "text": "Public Overridable Function ToString As String" }, { "code": null, "e": 13443, "s": 13390, "text": "Returns a string that represents the current object." }, { "code": null, "e": 13538, "s": 13443, "text": "Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As FirstDayOfWeek) As Integer" }, { "code": null, "e": 13617, "s": 13538, "text": "Returns an Integer value containing a number representing the day of the week." }, { "code": null, "e": 13745, "s": 13617, "text": "Public Shared Function WeekdayName (Weekday As Integer, Abbreviate As Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As String" }, { "code": null, "e": 13814, "s": 13745, "text": "Returns a String value containing the name of the specified weekday." }, { "code": null, "e": 13877, "s": 13814, "text": "Public Shared Function Year (DateValue As DateTime) As Integer" }, { "code": null, "e": 13945, "s": 13877, "text": "Returns an Integer value from 1 through 9999 representing the year." }, { "code": null, "e": 14089, "s": 13945, "text": "The above list is not exhaustive. For complete list of properties and methods of the DateAndTime class, please consult Microsoft Documentation." }, { "code": null, "e": 14152, "s": 14089, "text": "The following program demonstrates some of these and methods −" }, { "code": null, "e": 14748, "s": 14152, "text": "Module Module1\n Sub Main()\n Dim birthday As Date\n Dim bday As Integer\n Dim month As Integer\n Dim monthname As String\n ' Assign a date using standard short format.\n birthday = #7/27/1998#\n bday = Microsoft.VisualBasic.DateAndTime.Day(birthday)\n month = Microsoft.VisualBasic.DateAndTime.Month(birthday)\n monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month)\n \n Console.WriteLine(birthday)\n Console.WriteLine(bday)\n Console.WriteLine(month)\n Console.WriteLine(monthname)\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 14829, "s": 14748, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 14862, "s": 14829, "text": "7/27/1998 12:00:00 AM\n27\n7\nJuly\n" }, { "code": null, "e": 14895, "s": 14862, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 14912, "s": 14895, "text": " Frahaan Hussain" }, { "code": null, "e": 14947, "s": 14912, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 14962, "s": 14947, "text": " Arnold Higuit" }, { "code": null, "e": 14997, "s": 14962, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 15012, "s": 14997, "text": " Arnold Higuit" }, { "code": null, "e": 15045, "s": 15012, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 15060, "s": 15045, "text": " Arnold Higuit" }, { "code": null, "e": 15067, "s": 15060, "text": " Print" }, { "code": null, "e": 15078, "s": 15067, "text": " Add Notes" } ]
Using Timedelta and Period to create DateTime based indexes in Pandas - GeeksforGeeks
05 Feb, 2019 Real life data often consists of date and time-based records. From weather data to measuring some other metrics in big organizations they often rely on associating the observed data with some timestamp for evaluating the performance over time. We have already discussed how to manipulate date and time in pandas, now let’s see the concepts of Timestamp, Periods and indexes created using these. Using Timestamps :Timestamp is the pandas equivalent of Python’s Datetime and is interchangeable with it in most cases. It denotes a specific point in time. Let’s see how to create Timestamp. # importing pandas as pdimport pandas as pd # Creating the timestampts = pd.Timestamp('02-06-2018') # Print the timestampprint(ts) Output : Timestamps alone is not very useful, until we create an index out of it. The index that we create using the Timestamps are of DatetimeIndex type. # importing pandas as pdimport pandas as pd # Let's create a dataframedf = pd.DataFrame({'City':['Lisbon', 'Parague', 'Macao', 'Venice'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Let's create an index using Timestampsindex_ = [pd.Timestamp('01-06-2018'), pd.Timestamp('04-06-2018'), pd.Timestamp('07-06-2018'), pd.Timestamp('10-06-2018')] # Let's set the index of the dataframedf.index = index_ # Let's visualize the dataframeprint(df) Output : Now we will see the type of dataframe index which is made up of individual timestamps. # Check the typeprint(type(df.index)) Output :As we can clearly see in the output, the type of the index of our dataframe is ‘DatetimeIndex’. Using Periods : Unlike Timestamp which represents a point in time, Periods represents a period of time. It could be a month, day, year, hour etc.. Let’s see how to create Periods in Pandas. # importing pandas as pdimport pandas as pd # Let's create the Period# We have created a period# of a monthpr = pd.Period('06-2018') # Let's print the periodprint(pr) Output : The ‘M’ in the output represents month. Period objects alone is not very useful until it is used as an Index in a Dataframe or a Series. An index made up of Periods are called PeriodIndex. # importing pandas as pdimport pandas as pd # Let's create a dataframedf = pd.DataFrame({'City':['Lisbon', 'Parague', 'Macao', 'Venice'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Let's create an index using Periodsindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018')] # Let's set the index of the dataframedf.index = index_ # Let's visualize the dataframeprint(df) Output : Now we will see the type of our dataframe index which is made up of individual Periods. # Check the typeprint(type(df.index)) Output :As we can see in the output, the index created using periods are called PeriodIndex. pandas-dataframe-program Python pandas-dataFrame Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary 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 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": 24559, "s": 24531, "text": "\n05 Feb, 2019" }, { "code": null, "e": 24803, "s": 24559, "text": "Real life data often consists of date and time-based records. From weather data to measuring some other metrics in big organizations they often rely on associating the observed data with some timestamp for evaluating the performance over time." }, { "code": null, "e": 24954, "s": 24803, "text": "We have already discussed how to manipulate date and time in pandas, now let’s see the concepts of Timestamp, Periods and indexes created using these." }, { "code": null, "e": 25146, "s": 24954, "text": "Using Timestamps :Timestamp is the pandas equivalent of Python’s Datetime and is interchangeable with it in most cases. It denotes a specific point in time. Let’s see how to create Timestamp." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the timestampts = pd.Timestamp('02-06-2018') # Print the timestampprint(ts)", "e": 25279, "s": 25146, "text": null }, { "code": null, "e": 25288, "s": 25279, "text": "Output :" }, { "code": null, "e": 25434, "s": 25288, "text": "Timestamps alone is not very useful, until we create an index out of it. The index that we create using the Timestamps are of DatetimeIndex type." }, { "code": "# importing pandas as pdimport pandas as pd # Let's create a dataframedf = pd.DataFrame({'City':['Lisbon', 'Parague', 'Macao', 'Venice'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Let's create an index using Timestampsindex_ = [pd.Timestamp('01-06-2018'), pd.Timestamp('04-06-2018'), pd.Timestamp('07-06-2018'), pd.Timestamp('10-06-2018')] # Let's set the index of the dataframedf.index = index_ # Let's visualize the dataframeprint(df)", "e": 25970, "s": 25434, "text": null }, { "code": null, "e": 25979, "s": 25970, "text": "Output :" }, { "code": null, "e": 26066, "s": 25979, "text": "Now we will see the type of dataframe index which is made up of individual timestamps." }, { "code": "# Check the typeprint(type(df.index))", "e": 26104, "s": 26066, "text": null }, { "code": null, "e": 26398, "s": 26104, "text": "Output :As we can clearly see in the output, the type of the index of our dataframe is ‘DatetimeIndex’. Using Periods : Unlike Timestamp which represents a point in time, Periods represents a period of time. It could be a month, day, year, hour etc.. Let’s see how to create Periods in Pandas." }, { "code": "# importing pandas as pdimport pandas as pd # Let's create the Period# We have created a period# of a monthpr = pd.Period('06-2018') # Let's print the periodprint(pr)", "e": 26567, "s": 26398, "text": null }, { "code": null, "e": 26576, "s": 26567, "text": "Output :" }, { "code": null, "e": 26616, "s": 26576, "text": "The ‘M’ in the output represents month." }, { "code": null, "e": 26765, "s": 26616, "text": "Period objects alone is not very useful until it is used as an Index in a Dataframe or a Series. An index made up of Periods are called PeriodIndex." }, { "code": "# importing pandas as pdimport pandas as pd # Let's create a dataframedf = pd.DataFrame({'City':['Lisbon', 'Parague', 'Macao', 'Venice'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Let's create an index using Periodsindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018')] # Let's set the index of the dataframedf.index = index_ # Let's visualize the dataframeprint(df)", "e": 27274, "s": 26765, "text": null }, { "code": null, "e": 27283, "s": 27274, "text": "Output :" }, { "code": null, "e": 27371, "s": 27283, "text": "Now we will see the type of our dataframe index which is made up of individual Periods." }, { "code": "# Check the typeprint(type(df.index))", "e": 27409, "s": 27371, "text": null }, { "code": null, "e": 27502, "s": 27409, "text": "Output :As we can see in the output, the index created using periods are called PeriodIndex." }, { "code": null, "e": 27527, "s": 27502, "text": "pandas-dataframe-program" }, { "code": null, "e": 27551, "s": 27527, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27574, "s": 27551, "text": "Python pandas-datetime" }, { "code": null, "e": 27588, "s": 27574, "text": "Python-pandas" }, { "code": null, "e": 27595, "s": 27588, "text": "Python" }, { "code": null, "e": 27693, "s": 27595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27702, "s": 27693, "text": "Comments" }, { "code": null, "e": 27715, "s": 27702, "text": "Old Comments" }, { "code": null, "e": 27733, "s": 27715, "text": "Python Dictionary" }, { "code": null, "e": 27768, "s": 27733, "text": "Read a file line by line in Python" }, { "code": null, "e": 27790, "s": 27768, "text": "Enumerate() in Python" }, { "code": null, "e": 27822, "s": 27790, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27852, "s": 27822, "text": "Iterate over a list in Python" }, { "code": null, "e": 27894, "s": 27852, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27938, "s": 27894, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27963, "s": 27938, "text": "sum() function in Python" }, { "code": null, "e": 28000, "s": 27963, "text": "Create a Pandas DataFrame from Lists" } ]
Data Science for Startups: Data Pipelines | by Ben Weber | Towards Data Science
Part three of my ongoing series about building a data science discipline at a startup. You can find links to all of the posts in the introduction, and a book based on this series on Amazon. Building data pipelines is a core component of data science at a startup. In order to build data products, you need to be able to collect data points from millions of users and process the results in near real-time. While my previous blog post discussed what type of data to collect and how to send data to an endpoint, this post will discuss how to process data that has been collected, enabling data scientists to work with the data. The coming blog post on model production will discuss how to deploy models on this data platform. Typically, the destination for a data pipeline is a data lake, such as Hadoop or parquet files on S3, or a relational database, such as Redshift. An ideal data pipeline should have the following properties: Low Event Latency: Data scientists should be able to query recent event data in the pipeline, within minutes or seconds of the event being sent to the data collection endpoint. This is useful for testing purposes and for building data products that need to update in near real-time. Scalability: A data pipeline should be able to scale to billions of data points, and potentially trillions as a product scales. A high performing system should not only be able to store this data, but make the complete data set available for querying. Interactive Querying: A high functioning data pipeline should support both long-running batch queries and smaller interactive queries that enable data scientists to explore tables and understand the schema without having to wait minutes or hours when sampling data. Versioning: You should be able to make changes to your data pipeline and event definitions without bringing down the pipeline and suffering data loss. This post will discuss how to build a pipeline that supports different event definitions, in the case of changing an event schema. Monitoring: If an event is no longer being received, or tracking data is no longer being received for a particular region, then the data pipeline should generate alerts through tools such as PagerDuty. Testing: You should be able to test your data pipeline with test events that do not end up in your data lake or database, but that do test components in the pipeline. There’s a number of other useful properties that a data pipeline should have, but this is a good starting point for a startup. As you start to build additional components that depend on your data pipeline, you’ll want to set up tooling for fault tolerance and automating tasks. This post will show how to set up a scalable data pipeline that sends tracking data to a data lake, database, and subscription service for use in data products. I’ll discuss the different types of data in a pipeline, the evolution of data pipelines, and walk through an example pipeline implemented on GCP with PubSub, DataFlow, and BigQuery. Before deploying a data pipeline, you’ll want to answer the following questions, which resemble our questions about tracking specs: Who owns the data pipeline?Which teams will be consuming data?Who will QA the pipeline? Who owns the data pipeline? Which teams will be consuming data? Who will QA the pipeline? In a small organization, a data scientist may be responsible for the pipeline, while larger organizations usually have an infrastructure team that is responsible for keeping the pipeline operational. It’s also useful to know which teams will be consuming the data, so that you can stream data to the appropriate teams. For example, marketing may need real-time data of landing page visits to perform attribution for marketing campaigns. And finally, the data quality of events passed to the pipeline should be thoroughly inspected on a regular basis. Sometimes a product update will cause a tracking event to drop relevant data, and a process should be set up to capture these types of changes in data. Data in a pipeline is often referred to by different names based on the amount of modification that has been performed. Data is typically classified with the following labels: Raw Data: Is tracking data with no processing applied. This is data stored in the message encoding format used to send tracking events, such as JSON. Raw data does not yet have a schema applied. It’s common to send all tracking events as raw events, because all events can be sent to a single endpoint and schemas can be applied later on in the pipeline. Processed Data: Processed data is raw data that has been decoded into event specific formats, with a schema applied. For example, JSON tracking events that have been translated into a session start events with a fixed schema are considered processed data. Processed events are usually stored in different event tables/destinations in a data pipeline. Cooked Data: Processed data that has been aggregated or summarized is referred to as cooked data. For example, processed data could include session start and session end events, and be used as input to cooked data that summarizes daily activity for a user, such as number of sessions and total time on site for a web page. Data scientists will typically work with processed data, and use tools to create cooked data for other teams. This post will discuss how to build a data pipeline that outputs processed data, while the Business Intelligence post will discuss how to add cooked data to your pipeline. Over the past two decades the landscape for collecting and analyzing data has changed significantly. Rather than storing data locally via log files, modern systems can track activity and apply machine learning in near real-time. Startups might want to use one of the earlier approaches for initial testing, but should really look to more recent approaches for building data pipelines. Based on my experience, I’ve noticed four different approaches to pipelines: Flat File Era: Data is saved locally on game serversDatabase Era: Data is staged in flat files and then loaded into a databaseData Lake Era: Data is stored in Hadoop/S3 and then loaded into a DBServerless Era : Managed services are used for storage and querying Flat File Era: Data is saved locally on game servers Database Era: Data is staged in flat files and then loaded into a database Data Lake Era: Data is stored in Hadoop/S3 and then loaded into a DB Serverless Era : Managed services are used for storage and querying Each of the steps in this evolution support the collection of larger data sets, but may introduce additional operational complexity. For a startup, the goal is to be able to scale data collection without scaling operational resources, and the progression to managed services provides a nice solution for growth. The data pipeline that we’ll walk through in the next section of this post is based on the most recent era of data pipelines, but it’s useful to walk through different approaches because the requirements for different companies may fit better with different architectures. Flat File Era I got started in data science at Electronic Arts in 2010, before EA had an organization built around data. While many game companies were already collecting massive amounts of data about gameplay, most telemetry was stored in the form of log files or other flat file formats that were stored locally on the game servers. Nothing could be queried directly, and calculating basic metrics such as monthly active users (MAU) took substantial effort. At Electronic Arts, a replay feature was built into Madden NFL 11 which provided an unexpected source of game telemetry. After every game, a game summary in an XML format was sent to a game server that listed each play called, moves taken during the play, and the result of the down. This resulted in millions of files that could be analyzed to learn more about how players interacted with Madden football in the wild. Storing data locally is by far the easiest approach to take when collecting gameplay data. For example, the PHP approach presented in the last post is useful for setting up a lightweight analytics endpoint. But this approach does have significant drawbacks. This approach is simple and enables teams to save data in whatever format is needed, but has no fault tolerance, does not store data in a central location, has significant latency in data availability, and has standard tooling for building an ecosystem for analysis. Flat files can work fine if you only have a few servers, but it’s not really an analytics pipeline unless you move the files to a central location. You can write scripts to pull data from log servers to a central location, but it’s not generally a scalable approach. Database Era While I was at Sony Online Entertainment, we had game servers save event files to a central file server every couple of minutes. The file server then ran an ETL process about once an hour that fast loaded these event files into our analytics database, which was Vertica at the time. This process had a reasonable latency, about one hour from a game client sending an event to the data being queryable in our analytics database. It also scaled to a large volume of data, but required using a fixed schema for event data. When I was a Twitch, we used a similar process for one of our analytics databases. The main difference from the approach at SOE was that instead of having game servers scp files to a central location, we used Amazon Kinesis to stream events from servers to a staging area on S3. We then used an ETL process to fast load data into Redshift for analysis. Since then, Twitch has shifted to a data lake approach, in order to scale to a larger volume of data and to provide more options for querying the datasets. The databases used at SOE and Twitch were immensely valuable for both of the companies, but we did run into challenges as we scaled the amount of data stored. As we collected more detailed information about gameplay, we could no longer keep complete event history in our tables and needed to truncate data older than a few months. This is fine if you can set up summary tables that maintain the most important details about these events, but it’s not an ideal situation. One of the issues with this approach is that the staging server becomes a central point of failure. It’s also possible for bottlenecks to arise where one game sends way too many events, causing events to be dropped across all of the titles. Another issue is query performance as you scale up the number of analysts working with the database. A team of a few analysts working with a few months of gameplay data may work fine, but after collecting years of data and growing the number of analysts, query performance can be a significant problem, causing some queries to take hours to complete. The main benefits of this approach are that all event data is available in a single location queryable with SQL and great tooling is available, such as Tableau and DataGrip, for working with relational databases. The drawbacks are that it’s expensive to keep all data loaded into a database like Vertica or Redshift, events needs to have a fixed schema, and truncating tables may be necessary to keep the servers performant. Another issue with using a database as the main interface for data is that machine learning tools such as Spark’s MLlib cannot be used effectively, since the relevant data needs to be unloaded from the database before it can be operated on. One of the ways of overcoming this limitation is to store gameplay data in a format and storage layer that works well with Big Data tools, such as saving events as Parquet files on S3. This type of configuration became more population in the next era, and gets around the limitations of needing to truncate tables and the reduces the cost of keeping all data. Data Lake Era The data storage pattern that was most common while I was working as a data scientist in the games industry was a data lake. The general pattern is to store semi-structured data in a distributed database, and run ETL processes to extract the most relevant data to analytics databases. A number of different tools can be used for the distributed database: at Electronic Arts we used Hadoop, at Microsoft Studios we used Cosmos, and at Twitch we used S3. This approach enables teams to scale to massive volumes of data, and provides additional fault tolerance. The main downside is that it introduces additional complexity, and can result in analysts having access to less data than if a traditional database approach was used, due to lack of tooling or access policies. Most analysts will interact with data in the same way in this model, using an analytics database populated from data lake ETLs. One of the benefits of this approach is that it supports a variety of different event schemas, and you can change the attributes of an event without impacting the analytics database. Another advantage is that analytics teams can use tools such as Spark SQL to work with the data lake directly. However, most places I worked at restricted access to the data lake, eliminating many of the benefits of this model. This approach scales to a massive amount of data, supports flexible event schemas, and provides a good solution for long-running batch queries. The down sides are that it may involve significant operational overhead, may introduce large event latencies, and may lack mature tooling for the end users of the data lake. An additional drawback with this approach is that usually a whole team is needed just to keep the system operational. This makes sense for large organizations, but may be overkill for smaller companies. One of the ways of taking advantage of using a data lake without the cost of operational overhead is by using managed services. Serverless Era In the current era, analytics platforms incorporate a number of managed services, which enable teams to work with data in near real-time, scale up systems as necessary, and reduce the overhead of maintaining servers. I never experienced this era while I was working in the game industry, but saw signs of this transition happening. Riot Games is using Spark for ETL processes and machine learning, and needed to spin up infrastructure on demand. Some game teams are using elastic computing methods for game services, and it makes sense to utilize this approach for analytics as well. This approach has many of the same benefits as using a data lake, autoscales based on query and storage needs, and has minimal operational overhead. The main drawbacks are that managed services can be expensive, and taking this approach will likely result in using platform specific tools that are not portable to other cloud providers. In my career I had the most success working with the database era approach, since it provided the analytics team with access to all of the relevant data. However, it wasn’t a setup that would continue to scale and most teams that I worked on have since moved to data lake environments. In order for a data lake environment to be successful, analytics teams need access to the underlying data, and mature tooling to support their processes. For a startup, the serverless approach is usually the best way to start building a data pipeline, because it can scale to match demand and requires minimal staff to maintain the data pipeline. The next section will walk through building a sample pipeline with managed services. We’ll build a data pipeline that receives events using Google’s PuSub as an endpoint, and save the events to a data lake and database. The approach presented here will save the events as raw data, but I’ll also discuss ways of transforming the events into processed data. The data pipeline that performs all of this functionality is relatively simple. The pipeline reads messages from PubSub and then transforms the events for persistence: the BigQuery portion of the pipeline converts messages to TableRow objects and streams directly to BigQuery, while the AVRO portion of the pipeline batches events into discrete windows and then saves the events to Google Storage. The graph of operations is shown in the figure below. Setting up the EnvironmentThe first step in building a data pipeline is setting up the dependencies necessary to compile and deploy the project. I used the following maven dependencies to set up environments for the tracking API that sends events to the pipeline, and the data pipeline that processes events. <!-- Dependencies for the Tracking API -><dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> <version>0.32.0-beta</version> </dependency></dependencies><!-- Dependencies for the data pipeline -><dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version></dependency> I used Eclipse to author and compile the code for this tutorial, since it is open source. However, other IDEs such as IntelliJ provide additional features for deploying and monitoring DataFlow tasks. Before you can deploy jobs to Google Cloud, you’ll need to set up a service account for both PubSub and DataFlow. Setting up these credentials is outside the scope of this post, and more details are available in the Google documentation. An additional prerequisite for running this data pipeline is setting up a PubSub topic on GCP. I defined a raw-events topic that is used for publishing and consuming messages for the data pipeline. Additional details on creating a PubSub topic are available here. To deploy this data pipeline, you’ll need to set up a java environment with the maven dependencies listed above, set up a Google Cloud project and enable billing, enable billing on the storage and BigQuery services, and create a PubSub topic for sending and receiving messages. All of these managed services do cost money, but there is a free tier that can be used for prototyping a data pipeline. Publishing EventsIn order to build a usable data pipeline, it’s useful to build APIs that encapsulate the details of sending event data. The Tracking API class provides this functionality, and can be used to send generated event data to the data pipeline. The code below shows the method signature for sending events, and shows how to generate sample data. /** Event Signature for the Tracking API public void sendEvent(String eventType, String eventVersion, HashMap<String, String> attributes);*/// send a batch of events for (int i=0; i<10000; i++) {// generate event names String eventType = Math.random() < 0.5 ? "Session" : (Math.random() < 0.5 ? "Login" : "MatchStart");// create attributes to send HashMap<String, String> attributes = new HashMap<String,String>(); attributes.put("userID", "" + (int)(Math.random()*10000)); attributes.put("deviceType", Math.random() < 0.5 ? "Android" : (Math.random() < 0.5 ? "iOS" : "Web"));// send the event tracking.sendEvent(eventType, "V1", attributes); } The tracking API establishes a connection to a PubSub topic, passes events as a JSON format, and implements a callback for notification of delivery failures. The code used to send events is provided below, and is based on Google’s PubSub example provided here. // Setup a PubSub connection TopicName topicName = TopicName.of(projectID, topicID);Publisher publisher = Publisher.newBuilder(topicName).build();// Specify an event to sendString event = {\"eventType\":\"session\",\"eventVersion\":\"1\"}";// Convert the event to bytes ByteString data = ByteString.copyFromUtf8(event.toString());//schedule a message to be published PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();// publish the message, and add this class as a callback listenerApiFuture<String> future = publisher.publish(pubsubMessage); ApiFutures.addCallback(future, this); The code above enables apps to send events to a PubSub topic. The next step is to process this events in a fully-managed environment that can scale as necessary to meet demand. Storing EventsOne of the key functions of a data pipeline is to make instrumented events available to data science and analytics teams for analysis. The data sources used as endpoints should have low latency and be able to scale up to a massive volume of events. The data pipeline defined in this tutorial shows how to output events to both BigQuery and a data lake that can be used to support a large number of analytics business users. The first step in this data pipeline is reading events from a PubSub topic and passing ingested messages to the DataFlow process. DataFlow provides a PubSub connector that enables streaming of PubSub messages to other DataFlow components. The code below shows how to instantiate the data pipeline, specify streaming mode, and to consume messages from a specific PubSub topic. The output of this process is a collection of PubSub messages that can be stored for later analysis. // set up pipeline options Options options = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); options.setStreaming(true); Pipeline pipeline = Pipeline.create(options);// read game events from PubSub PCollection<PubsubMessage> events = pipeline .apply(PubsubIO.readMessages().fromTopic(topic)); The first way we want to store events is in a columnar format that can be used to build a data lake. While this post doesn’t show how to utilize these files in downstream ETLs, having a data lake is a great way to maintain a copy of your data set in case you need to make changes to your database. The data lake provides a way to backload your data if necessary due to changes in schemas or data ingestion issues. The portion of the data pipeline allocated to this process is shown below. For AVRO, we can’t use a direct streaming approach. We need to group events into batches before we can save to flat files. The way this can be accomplished in DataFlow is by applying a windowing function that groups events into fixed batches. The code below applies transformations that convert the PubSub messages into String objects, group the messages into 5 minute intervals, and output the resulting batches to AVRO files on Google Storage. // AVRO output portion of the pipeline events.apply("To String", ParDo.of(new DoFn<PubsubMessage, String>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); c.output(message); } }))// Batch events into 5 minute windows .apply("Batch Events", Window.<String>into( FixedWindows.of(Duration.standardMinutes(5))) .triggering(AfterWatermark.pastEndOfWindow()) .discardingFiredPanes() .withAllowedLateness(Duration.standardMinutes(5)))// Save the events in ARVO format .apply("To AVRO", AvroIO.write(String.class) .to("gs://your_gs_bucket/avro/raw-events.avro") .withWindowedWrites() .withNumShards(8) .withSuffix(".avro")); To summarize, the above code batches events into 5 minute windows and then exports the events to AVRO files on Google Storage. The result of this portion of the data pipeline is a collection of AVRO files on google storage that can be used to build a data lake. A new AVRO output is generated every 5 minutes, and downstream ETLs can parse the raw events into processed event-specific table schemas. The image below shows a sample output of AVRO files. In addition to creating a data lake, we want the events to be immediately accessible in a query environment. DataFlow provides a BigQuery connector which serves this functionality, and data streamed to this endpoint is available for analysis after a short duration. This portion of the data pipeline is shown in the figure below. The data pipeline converts the PubSub messages into TableRow objects, which can be directly inserted into BigQuery. The code below consists of two apply methods: a data transformation and a IO writer. The transform step reads the message payloads from PubSub, parses the message as a JSON object, extracts the eventType and eventVersion attributes, and creates a TableRow object with these attributes in addition to a timestamp and the message payload. The second apply method tells the pipeline to write the records to BigQuery and to append the events to an existing table. // parse the PubSub events and create rows to insert into BigQuery events.apply("To Table Rows", new PTransform<PCollection<PubsubMessage>, PCollection<TableRow>>() { public PCollection<TableRow> expand( PCollection<PubsubMessage> input) { return input.apply("To Predictions", ParDo.of(new DoFn<PubsubMessage, TableRow>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the json message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get("eventType").getAsString(); String eventVersion = jsonObject. get("eventVersion").getAsString(); String serverTime = dateFormat.format(new Date()); // create and output the table row TableRow record = new TableRow(); record.set("eventType", eventType); record.set("eventVersion", eventVersion); record.set("serverTime", serverTime); record.set("message", message); c.output(record); }})); }}) //stream the events to Big Query .apply("To BigQuery",BigQueryIO.writeTableRows() .to(table) .withSchema(schema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND)); To summarize the above code, each message that is consumed from PubSub is converted into a TableRow object with a timestamp and then streamed to BigQuery for storage. The result of this portion of the data pipeline is that events will be streamed to BigQuery and will be available for analysis in the output table specified by the DataFlow task. In order to effectively use these events for queries, you’ll need to build additional ETLs for creating processed event tables with schematized records, but you now have a data collection mechanism in place for storing tracking events. Deploying and Auto ScalingWith DataFlow you can test the data pipeline locally or deploy to the cloud. If you run the code samples without specifying additional attributes, then the data pipeline will execute on your local machine. In order to deploy to the cloud and take advantage of the auto scaling capabilities of this data pipeline, you need to specify a new runner class as part of your runtime arguments. In order to run the data pipeline, I used the following runtime arguments: --runner=org.apache.beam.runners.dataflow.DataflowRunner --jobName=game-analytics--project=your_project_id --tempLocation=gs://temp-bucket Once the job is deployed, you should see a message that the job has been submitted. You can then click on the DataFlow console to see the task: The runtime configuration specified above will not default to an auto scaling configuration. In order to deploy a job that scales up based on demand, you’ll need to specify additional attributes, such as: --autoscalingAlgorithm=THROUGHPUT_BASED--maxNumWorkers=30 Additional details on setting up a DataFlow task to scale to heavy workload conditions are available in this Google article and this post from Spotify. The image below shows how DataFlow can scale up to meet demand as necessary. Raw to Processed EventsThe pipeline presented so far saves tracking events as raw data. To translate these events to processed data, we’ll need to apply event specific schemas. There’s a few different approaches we can take with this pipeline: Apply the schemas in the current DataFlow pipeline and save to BigQueryApply the schemas in the current pipeline and send to a new PubSubApply additional attributes to the raw events and send to a new PubSubUse downstream ETLs to apply schemas Apply the schemas in the current DataFlow pipeline and save to BigQuery Apply the schemas in the current pipeline and send to a new PubSub Apply additional attributes to the raw events and send to a new PubSub Use downstream ETLs to apply schemas The first approach is the simplest, but it doesn’t provide a good solution for updating the event definitions if needed. This approach can be implemented as shown in the code below, which shows how to filter and parse MatchStart events for entry into BigQuery. events.apply("To MatchStart Events", ParDo.of( new DoFn<PubsubMessage, TableRow>() {@ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload());JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get("eventType").getAsString(); String version = jsonObject.get("eventVersion").getAsString(); String serverTime = dateFormat.format(new Date()); // Filter for MatchStart events if (eventType.equals("MatchStart")) { TableRow record = new TableRow(); record.set("eventType", eventType); record.set("eventVersion", version); record.set("server_time", serverTime); // event specifc attributes record.set("userID", jsonObject.get("userID").getAsString()); record.set("type", jsonObject.get("deviceType").getAsString()); c.output(record); }}})).apply("To BigQuery",BigQueryIO.writeTableRows() In order to implement this approach, you’d need to create a new DoFn implementation for each type of event. The second approach is similar to the first, but instead of passing the parsed events to BigQuery, they are passed to a new PubSub topic. It’s possible to send multiple types of events to a single topic or create a topic per event. The drawback of using the first two approaches is that the message parsing logic is part of the raw event pipeline. This means that changing event definitions involves restarting the pipeline. A third approach that can be used is sending raw events with additional attributes to another PubSub topic. A second DataFlow job can then be set up to parse events as needed. The code below shows how to parse raw events, add additional attributes to the PubSub message for filtering, and publish the events to a second topic. This approach enables event definitions to be changed without restarting the raw event pipeline. # topic for raw events with additional attributes private static String processed = "projects/your_project_id/topics/processed-events";events.apply("PubSub Processed", ParDo.of(new DoFn<PubsubMessage, PubsubMessage>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the JSON message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get("eventType").getAsString(); // Add additional attributes for filtering HashMap<String, String> atts = new HashMap(); atts.put("EventType", eventType); PubsubMessage out = new PubsubMessage(message.getBytes(), atts); c.output(out); } })) .apply(PubsubIO.writeMessages().to(processed)); A fourth approach that can be used is having downstream ETLs processes apply schemas to the raw events and break apart the raw events table into event specific tables. We’ll cover this approach in the next post. This post has provided an introduction to building a data pipeline for a startup. We covered the types of data in a pipeline, desired properties of a high functioning data pipeline, the evolution of data pipelines, and a sample pipeline built on GCP. There is now a variety of tools available that make it possible to set up an analytics pipeline for an application with minimal effort. Using managed resources enables small teams to take advantage of serverless and autoscaling infrastructure to scale up to massive event volumes with minimal infrastructure management. Rather than using a data vendor’s off-the-shelf solution for collecting data, you can record all relevant data for your app. While the approach presented here isn’t directly portable to other clouds, the Apache Beam library used to implement the core functionality of this data pipeline is portable and similar tools can be leveraged to build scalable data pipelines on other cloud providers. The full source code for this sample pipeline is available on Github:
[ { "code": null, "e": 362, "s": 172, "text": "Part three of my ongoing series about building a data science discipline at a startup. You can find links to all of the posts in the introduction, and a book based on this series on Amazon." }, { "code": null, "e": 896, "s": 362, "text": "Building data pipelines is a core component of data science at a startup. In order to build data products, you need to be able to collect data points from millions of users and process the results in near real-time. While my previous blog post discussed what type of data to collect and how to send data to an endpoint, this post will discuss how to process data that has been collected, enabling data scientists to work with the data. The coming blog post on model production will discuss how to deploy models on this data platform." }, { "code": null, "e": 1103, "s": 896, "text": "Typically, the destination for a data pipeline is a data lake, such as Hadoop or parquet files on S3, or a relational database, such as Redshift. An ideal data pipeline should have the following properties:" }, { "code": null, "e": 1386, "s": 1103, "text": "Low Event Latency: Data scientists should be able to query recent event data in the pipeline, within minutes or seconds of the event being sent to the data collection endpoint. This is useful for testing purposes and for building data products that need to update in near real-time." }, { "code": null, "e": 1638, "s": 1386, "text": "Scalability: A data pipeline should be able to scale to billions of data points, and potentially trillions as a product scales. A high performing system should not only be able to store this data, but make the complete data set available for querying." }, { "code": null, "e": 1904, "s": 1638, "text": "Interactive Querying: A high functioning data pipeline should support both long-running batch queries and smaller interactive queries that enable data scientists to explore tables and understand the schema without having to wait minutes or hours when sampling data." }, { "code": null, "e": 2186, "s": 1904, "text": "Versioning: You should be able to make changes to your data pipeline and event definitions without bringing down the pipeline and suffering data loss. This post will discuss how to build a pipeline that supports different event definitions, in the case of changing an event schema." }, { "code": null, "e": 2388, "s": 2186, "text": "Monitoring: If an event is no longer being received, or tracking data is no longer being received for a particular region, then the data pipeline should generate alerts through tools such as PagerDuty." }, { "code": null, "e": 2555, "s": 2388, "text": "Testing: You should be able to test your data pipeline with test events that do not end up in your data lake or database, but that do test components in the pipeline." }, { "code": null, "e": 2833, "s": 2555, "text": "There’s a number of other useful properties that a data pipeline should have, but this is a good starting point for a startup. As you start to build additional components that depend on your data pipeline, you’ll want to set up tooling for fault tolerance and automating tasks." }, { "code": null, "e": 3176, "s": 2833, "text": "This post will show how to set up a scalable data pipeline that sends tracking data to a data lake, database, and subscription service for use in data products. I’ll discuss the different types of data in a pipeline, the evolution of data pipelines, and walk through an example pipeline implemented on GCP with PubSub, DataFlow, and BigQuery." }, { "code": null, "e": 3308, "s": 3176, "text": "Before deploying a data pipeline, you’ll want to answer the following questions, which resemble our questions about tracking specs:" }, { "code": null, "e": 3396, "s": 3308, "text": "Who owns the data pipeline?Which teams will be consuming data?Who will QA the pipeline?" }, { "code": null, "e": 3424, "s": 3396, "text": "Who owns the data pipeline?" }, { "code": null, "e": 3460, "s": 3424, "text": "Which teams will be consuming data?" }, { "code": null, "e": 3486, "s": 3460, "text": "Who will QA the pipeline?" }, { "code": null, "e": 4189, "s": 3486, "text": "In a small organization, a data scientist may be responsible for the pipeline, while larger organizations usually have an infrastructure team that is responsible for keeping the pipeline operational. It’s also useful to know which teams will be consuming the data, so that you can stream data to the appropriate teams. For example, marketing may need real-time data of landing page visits to perform attribution for marketing campaigns. And finally, the data quality of events passed to the pipeline should be thoroughly inspected on a regular basis. Sometimes a product update will cause a tracking event to drop relevant data, and a process should be set up to capture these types of changes in data." }, { "code": null, "e": 4365, "s": 4189, "text": "Data in a pipeline is often referred to by different names based on the amount of modification that has been performed. Data is typically classified with the following labels:" }, { "code": null, "e": 4720, "s": 4365, "text": "Raw Data: Is tracking data with no processing applied. This is data stored in the message encoding format used to send tracking events, such as JSON. Raw data does not yet have a schema applied. It’s common to send all tracking events as raw events, because all events can be sent to a single endpoint and schemas can be applied later on in the pipeline." }, { "code": null, "e": 5071, "s": 4720, "text": "Processed Data: Processed data is raw data that has been decoded into event specific formats, with a schema applied. For example, JSON tracking events that have been translated into a session start events with a fixed schema are considered processed data. Processed events are usually stored in different event tables/destinations in a data pipeline." }, { "code": null, "e": 5394, "s": 5071, "text": "Cooked Data: Processed data that has been aggregated or summarized is referred to as cooked data. For example, processed data could include session start and session end events, and be used as input to cooked data that summarizes daily activity for a user, such as number of sessions and total time on site for a web page." }, { "code": null, "e": 5676, "s": 5394, "text": "Data scientists will typically work with processed data, and use tools to create cooked data for other teams. This post will discuss how to build a data pipeline that outputs processed data, while the Business Intelligence post will discuss how to add cooked data to your pipeline." }, { "code": null, "e": 6138, "s": 5676, "text": "Over the past two decades the landscape for collecting and analyzing data has changed significantly. Rather than storing data locally via log files, modern systems can track activity and apply machine learning in near real-time. Startups might want to use one of the earlier approaches for initial testing, but should really look to more recent approaches for building data pipelines. Based on my experience, I’ve noticed four different approaches to pipelines:" }, { "code": null, "e": 6400, "s": 6138, "text": "Flat File Era: Data is saved locally on game serversDatabase Era: Data is staged in flat files and then loaded into a databaseData Lake Era: Data is stored in Hadoop/S3 and then loaded into a DBServerless Era : Managed services are used for storage and querying" }, { "code": null, "e": 6453, "s": 6400, "text": "Flat File Era: Data is saved locally on game servers" }, { "code": null, "e": 6528, "s": 6453, "text": "Database Era: Data is staged in flat files and then loaded into a database" }, { "code": null, "e": 6597, "s": 6528, "text": "Data Lake Era: Data is stored in Hadoop/S3 and then loaded into a DB" }, { "code": null, "e": 6665, "s": 6597, "text": "Serverless Era : Managed services are used for storage and querying" }, { "code": null, "e": 6977, "s": 6665, "text": "Each of the steps in this evolution support the collection of larger data sets, but may introduce additional operational complexity. For a startup, the goal is to be able to scale data collection without scaling operational resources, and the progression to managed services provides a nice solution for growth." }, { "code": null, "e": 7250, "s": 6977, "text": "The data pipeline that we’ll walk through in the next section of this post is based on the most recent era of data pipelines, but it’s useful to walk through different approaches because the requirements for different companies may fit better with different architectures." }, { "code": null, "e": 7264, "s": 7250, "text": "Flat File Era" }, { "code": null, "e": 7710, "s": 7264, "text": "I got started in data science at Electronic Arts in 2010, before EA had an organization built around data. While many game companies were already collecting massive amounts of data about gameplay, most telemetry was stored in the form of log files or other flat file formats that were stored locally on the game servers. Nothing could be queried directly, and calculating basic metrics such as monthly active users (MAU) took substantial effort." }, { "code": null, "e": 8129, "s": 7710, "text": "At Electronic Arts, a replay feature was built into Madden NFL 11 which provided an unexpected source of game telemetry. After every game, a game summary in an XML format was sent to a game server that listed each play called, moves taken during the play, and the result of the down. This resulted in millions of files that could be analyzed to learn more about how players interacted with Madden football in the wild." }, { "code": null, "e": 8387, "s": 8129, "text": "Storing data locally is by far the easiest approach to take when collecting gameplay data. For example, the PHP approach presented in the last post is useful for setting up a lightweight analytics endpoint. But this approach does have significant drawbacks." }, { "code": null, "e": 8921, "s": 8387, "text": "This approach is simple and enables teams to save data in whatever format is needed, but has no fault tolerance, does not store data in a central location, has significant latency in data availability, and has standard tooling for building an ecosystem for analysis. Flat files can work fine if you only have a few servers, but it’s not really an analytics pipeline unless you move the files to a central location. You can write scripts to pull data from log servers to a central location, but it’s not generally a scalable approach." }, { "code": null, "e": 8934, "s": 8921, "text": "Database Era" }, { "code": null, "e": 9454, "s": 8934, "text": "While I was at Sony Online Entertainment, we had game servers save event files to a central file server every couple of minutes. The file server then ran an ETL process about once an hour that fast loaded these event files into our analytics database, which was Vertica at the time. This process had a reasonable latency, about one hour from a game client sending an event to the data being queryable in our analytics database. It also scaled to a large volume of data, but required using a fixed schema for event data." }, { "code": null, "e": 9963, "s": 9454, "text": "When I was a Twitch, we used a similar process for one of our analytics databases. The main difference from the approach at SOE was that instead of having game servers scp files to a central location, we used Amazon Kinesis to stream events from servers to a staging area on S3. We then used an ETL process to fast load data into Redshift for analysis. Since then, Twitch has shifted to a data lake approach, in order to scale to a larger volume of data and to provide more options for querying the datasets." }, { "code": null, "e": 10434, "s": 9963, "text": "The databases used at SOE and Twitch were immensely valuable for both of the companies, but we did run into challenges as we scaled the amount of data stored. As we collected more detailed information about gameplay, we could no longer keep complete event history in our tables and needed to truncate data older than a few months. This is fine if you can set up summary tables that maintain the most important details about these events, but it’s not an ideal situation." }, { "code": null, "e": 11026, "s": 10434, "text": "One of the issues with this approach is that the staging server becomes a central point of failure. It’s also possible for bottlenecks to arise where one game sends way too many events, causing events to be dropped across all of the titles. Another issue is query performance as you scale up the number of analysts working with the database. A team of a few analysts working with a few months of gameplay data may work fine, but after collecting years of data and growing the number of analysts, query performance can be a significant problem, causing some queries to take hours to complete." }, { "code": null, "e": 11451, "s": 11026, "text": "The main benefits of this approach are that all event data is available in a single location queryable with SQL and great tooling is available, such as Tableau and DataGrip, for working with relational databases. The drawbacks are that it’s expensive to keep all data loaded into a database like Vertica or Redshift, events needs to have a fixed schema, and truncating tables may be necessary to keep the servers performant." }, { "code": null, "e": 12052, "s": 11451, "text": "Another issue with using a database as the main interface for data is that machine learning tools such as Spark’s MLlib cannot be used effectively, since the relevant data needs to be unloaded from the database before it can be operated on. One of the ways of overcoming this limitation is to store gameplay data in a format and storage layer that works well with Big Data tools, such as saving events as Parquet files on S3. This type of configuration became more population in the next era, and gets around the limitations of needing to truncate tables and the reduces the cost of keeping all data." }, { "code": null, "e": 12066, "s": 12052, "text": "Data Lake Era" }, { "code": null, "e": 12519, "s": 12066, "text": "The data storage pattern that was most common while I was working as a data scientist in the games industry was a data lake. The general pattern is to store semi-structured data in a distributed database, and run ETL processes to extract the most relevant data to analytics databases. A number of different tools can be used for the distributed database: at Electronic Arts we used Hadoop, at Microsoft Studios we used Cosmos, and at Twitch we used S3." }, { "code": null, "e": 12963, "s": 12519, "text": "This approach enables teams to scale to massive volumes of data, and provides additional fault tolerance. The main downside is that it introduces additional complexity, and can result in analysts having access to less data than if a traditional database approach was used, due to lack of tooling or access policies. Most analysts will interact with data in the same way in this model, using an analytics database populated from data lake ETLs." }, { "code": null, "e": 13374, "s": 12963, "text": "One of the benefits of this approach is that it supports a variety of different event schemas, and you can change the attributes of an event without impacting the analytics database. Another advantage is that analytics teams can use tools such as Spark SQL to work with the data lake directly. However, most places I worked at restricted access to the data lake, eliminating many of the benefits of this model." }, { "code": null, "e": 14023, "s": 13374, "text": "This approach scales to a massive amount of data, supports flexible event schemas, and provides a good solution for long-running batch queries. The down sides are that it may involve significant operational overhead, may introduce large event latencies, and may lack mature tooling for the end users of the data lake. An additional drawback with this approach is that usually a whole team is needed just to keep the system operational. This makes sense for large organizations, but may be overkill for smaller companies. One of the ways of taking advantage of using a data lake without the cost of operational overhead is by using managed services." }, { "code": null, "e": 14038, "s": 14023, "text": "Serverless Era" }, { "code": null, "e": 14622, "s": 14038, "text": "In the current era, analytics platforms incorporate a number of managed services, which enable teams to work with data in near real-time, scale up systems as necessary, and reduce the overhead of maintaining servers. I never experienced this era while I was working in the game industry, but saw signs of this transition happening. Riot Games is using Spark for ETL processes and machine learning, and needed to spin up infrastructure on demand. Some game teams are using elastic computing methods for game services, and it makes sense to utilize this approach for analytics as well." }, { "code": null, "e": 14959, "s": 14622, "text": "This approach has many of the same benefits as using a data lake, autoscales based on query and storage needs, and has minimal operational overhead. The main drawbacks are that managed services can be expensive, and taking this approach will likely result in using platform specific tools that are not portable to other cloud providers." }, { "code": null, "e": 15677, "s": 14959, "text": "In my career I had the most success working with the database era approach, since it provided the analytics team with access to all of the relevant data. However, it wasn’t a setup that would continue to scale and most teams that I worked on have since moved to data lake environments. In order for a data lake environment to be successful, analytics teams need access to the underlying data, and mature tooling to support their processes. For a startup, the serverless approach is usually the best way to start building a data pipeline, because it can scale to match demand and requires minimal staff to maintain the data pipeline. The next section will walk through building a sample pipeline with managed services." }, { "code": null, "e": 15949, "s": 15677, "text": "We’ll build a data pipeline that receives events using Google’s PuSub as an endpoint, and save the events to a data lake and database. The approach presented here will save the events as raw data, but I’ll also discuss ways of transforming the events into processed data." }, { "code": null, "e": 16401, "s": 15949, "text": "The data pipeline that performs all of this functionality is relatively simple. The pipeline reads messages from PubSub and then transforms the events for persistence: the BigQuery portion of the pipeline converts messages to TableRow objects and streams directly to BigQuery, while the AVRO portion of the pipeline batches events into discrete windows and then saves the events to Google Storage. The graph of operations is shown in the figure below." }, { "code": null, "e": 16710, "s": 16401, "text": "Setting up the EnvironmentThe first step in building a data pipeline is setting up the dependencies necessary to compile and deploy the project. I used the following maven dependencies to set up environments for the tracking API that sends events to the pipeline, and the data pipeline that processes events." }, { "code": null, "e": 17109, "s": 16710, "text": "<!-- Dependencies for the Tracking API -><dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> <version>0.32.0-beta</version> </dependency></dependencies><!-- Dependencies for the data pipeline -><dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version></dependency>" }, { "code": null, "e": 17547, "s": 17109, "text": "I used Eclipse to author and compile the code for this tutorial, since it is open source. However, other IDEs such as IntelliJ provide additional features for deploying and monitoring DataFlow tasks. Before you can deploy jobs to Google Cloud, you’ll need to set up a service account for both PubSub and DataFlow. Setting up these credentials is outside the scope of this post, and more details are available in the Google documentation." }, { "code": null, "e": 17811, "s": 17547, "text": "An additional prerequisite for running this data pipeline is setting up a PubSub topic on GCP. I defined a raw-events topic that is used for publishing and consuming messages for the data pipeline. Additional details on creating a PubSub topic are available here." }, { "code": null, "e": 18209, "s": 17811, "text": "To deploy this data pipeline, you’ll need to set up a java environment with the maven dependencies listed above, set up a Google Cloud project and enable billing, enable billing on the storage and BigQuery services, and create a PubSub topic for sending and receiving messages. All of these managed services do cost money, but there is a free tier that can be used for prototyping a data pipeline." }, { "code": null, "e": 18566, "s": 18209, "text": "Publishing EventsIn order to build a usable data pipeline, it’s useful to build APIs that encapsulate the details of sending event data. The Tracking API class provides this functionality, and can be used to send generated event data to the data pipeline. The code below shows the method signature for sending events, and shows how to generate sample data." }, { "code": null, "e": 19254, "s": 18566, "text": "/** Event Signature for the Tracking API public void sendEvent(String eventType, String eventVersion, HashMap<String, String> attributes);*/// send a batch of events for (int i=0; i<10000; i++) {// generate event names String eventType = Math.random() < 0.5 ? \"Session\" : (Math.random() < 0.5 ? \"Login\" : \"MatchStart\");// create attributes to send HashMap<String, String> attributes = new HashMap<String,String>(); attributes.put(\"userID\", \"\" + (int)(Math.random()*10000)); attributes.put(\"deviceType\", Math.random() < 0.5 ? \"Android\" : (Math.random() < 0.5 ? \"iOS\" : \"Web\"));// send the event tracking.sendEvent(eventType, \"V1\", attributes); }" }, { "code": null, "e": 19515, "s": 19254, "text": "The tracking API establishes a connection to a PubSub topic, passes events as a JSON format, and implements a callback for notification of delivery failures. The code used to send events is provided below, and is based on Google’s PubSub example provided here." }, { "code": null, "e": 20136, "s": 19515, "text": "// Setup a PubSub connection TopicName topicName = TopicName.of(projectID, topicID);Publisher publisher = Publisher.newBuilder(topicName).build();// Specify an event to sendString event = {\\\"eventType\\\":\\\"session\\\",\\\"eventVersion\\\":\\\"1\\\"}\";// Convert the event to bytes ByteString data = ByteString.copyFromUtf8(event.toString());//schedule a message to be published PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();// publish the message, and add this class as a callback listenerApiFuture<String> future = publisher.publish(pubsubMessage); ApiFutures.addCallback(future, this);" }, { "code": null, "e": 20313, "s": 20136, "text": "The code above enables apps to send events to a PubSub topic. The next step is to process this events in a fully-managed environment that can scale as necessary to meet demand." }, { "code": null, "e": 20751, "s": 20313, "text": "Storing EventsOne of the key functions of a data pipeline is to make instrumented events available to data science and analytics teams for analysis. The data sources used as endpoints should have low latency and be able to scale up to a massive volume of events. The data pipeline defined in this tutorial shows how to output events to both BigQuery and a data lake that can be used to support a large number of analytics business users." }, { "code": null, "e": 21228, "s": 20751, "text": "The first step in this data pipeline is reading events from a PubSub topic and passing ingested messages to the DataFlow process. DataFlow provides a PubSub connector that enables streaming of PubSub messages to other DataFlow components. The code below shows how to instantiate the data pipeline, specify streaming mode, and to consume messages from a specific PubSub topic. The output of this process is a collection of PubSub messages that can be stored for later analysis." }, { "code": null, "e": 21562, "s": 21228, "text": "// set up pipeline options Options options = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); options.setStreaming(true); Pipeline pipeline = Pipeline.create(options);// read game events from PubSub PCollection<PubsubMessage> events = pipeline .apply(PubsubIO.readMessages().fromTopic(topic));" }, { "code": null, "e": 22051, "s": 21562, "text": "The first way we want to store events is in a columnar format that can be used to build a data lake. While this post doesn’t show how to utilize these files in downstream ETLs, having a data lake is a great way to maintain a copy of your data set in case you need to make changes to your database. The data lake provides a way to backload your data if necessary due to changes in schemas or data ingestion issues. The portion of the data pipeline allocated to this process is shown below." }, { "code": null, "e": 22497, "s": 22051, "text": "For AVRO, we can’t use a direct streaming approach. We need to group events into batches before we can save to flat files. The way this can be accomplished in DataFlow is by applying a windowing function that groups events into fixed batches. The code below applies transformations that convert the PubSub messages into String objects, group the messages into 5 minute intervals, and output the resulting batches to AVRO files on Google Storage." }, { "code": null, "e": 23288, "s": 22497, "text": "// AVRO output portion of the pipeline events.apply(\"To String\", ParDo.of(new DoFn<PubsubMessage, String>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); c.output(message); } }))// Batch events into 5 minute windows .apply(\"Batch Events\", Window.<String>into( FixedWindows.of(Duration.standardMinutes(5))) .triggering(AfterWatermark.pastEndOfWindow()) .discardingFiredPanes() .withAllowedLateness(Duration.standardMinutes(5)))// Save the events in ARVO format .apply(\"To AVRO\", AvroIO.write(String.class) .to(\"gs://your_gs_bucket/avro/raw-events.avro\") .withWindowedWrites() .withNumShards(8) .withSuffix(\".avro\"));" }, { "code": null, "e": 23415, "s": 23288, "text": "To summarize, the above code batches events into 5 minute windows and then exports the events to AVRO files on Google Storage." }, { "code": null, "e": 23741, "s": 23415, "text": "The result of this portion of the data pipeline is a collection of AVRO files on google storage that can be used to build a data lake. A new AVRO output is generated every 5 minutes, and downstream ETLs can parse the raw events into processed event-specific table schemas. The image below shows a sample output of AVRO files." }, { "code": null, "e": 24071, "s": 23741, "text": "In addition to creating a data lake, we want the events to be immediately accessible in a query environment. DataFlow provides a BigQuery connector which serves this functionality, and data streamed to this endpoint is available for analysis after a short duration. This portion of the data pipeline is shown in the figure below." }, { "code": null, "e": 24647, "s": 24071, "text": "The data pipeline converts the PubSub messages into TableRow objects, which can be directly inserted into BigQuery. The code below consists of two apply methods: a data transformation and a IO writer. The transform step reads the message payloads from PubSub, parses the message as a JSON object, extracts the eventType and eventVersion attributes, and creates a TableRow object with these attributes in addition to a timestamp and the message payload. The second apply method tells the pipeline to write the records to BigQuery and to append the events to an existing table." }, { "code": null, "e": 26134, "s": 24647, "text": "// parse the PubSub events and create rows to insert into BigQuery events.apply(\"To Table Rows\", new PTransform<PCollection<PubsubMessage>, PCollection<TableRow>>() { public PCollection<TableRow> expand( PCollection<PubsubMessage> input) { return input.apply(\"To Predictions\", ParDo.of(new DoFn<PubsubMessage, TableRow>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the json message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get(\"eventType\").getAsString(); String eventVersion = jsonObject. get(\"eventVersion\").getAsString(); String serverTime = dateFormat.format(new Date()); // create and output the table row TableRow record = new TableRow(); record.set(\"eventType\", eventType); record.set(\"eventVersion\", eventVersion); record.set(\"serverTime\", serverTime); record.set(\"message\", message); c.output(record); }})); }}) //stream the events to Big Query .apply(\"To BigQuery\",BigQueryIO.writeTableRows() .to(table) .withSchema(schema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND));" }, { "code": null, "e": 26301, "s": 26134, "text": "To summarize the above code, each message that is consumed from PubSub is converted into a TableRow object with a timestamp and then streamed to BigQuery for storage." }, { "code": null, "e": 26716, "s": 26301, "text": "The result of this portion of the data pipeline is that events will be streamed to BigQuery and will be available for analysis in the output table specified by the DataFlow task. In order to effectively use these events for queries, you’ll need to build additional ETLs for creating processed event tables with schematized records, but you now have a data collection mechanism in place for storing tracking events." }, { "code": null, "e": 27204, "s": 26716, "text": "Deploying and Auto ScalingWith DataFlow you can test the data pipeline locally or deploy to the cloud. If you run the code samples without specifying additional attributes, then the data pipeline will execute on your local machine. In order to deploy to the cloud and take advantage of the auto scaling capabilities of this data pipeline, you need to specify a new runner class as part of your runtime arguments. In order to run the data pipeline, I used the following runtime arguments:" }, { "code": null, "e": 27343, "s": 27204, "text": "--runner=org.apache.beam.runners.dataflow.DataflowRunner --jobName=game-analytics--project=your_project_id --tempLocation=gs://temp-bucket" }, { "code": null, "e": 27487, "s": 27343, "text": "Once the job is deployed, you should see a message that the job has been submitted. You can then click on the DataFlow console to see the task:" }, { "code": null, "e": 27692, "s": 27487, "text": "The runtime configuration specified above will not default to an auto scaling configuration. In order to deploy a job that scales up based on demand, you’ll need to specify additional attributes, such as:" }, { "code": null, "e": 27750, "s": 27692, "text": "--autoscalingAlgorithm=THROUGHPUT_BASED--maxNumWorkers=30" }, { "code": null, "e": 27979, "s": 27750, "text": "Additional details on setting up a DataFlow task to scale to heavy workload conditions are available in this Google article and this post from Spotify. The image below shows how DataFlow can scale up to meet demand as necessary." }, { "code": null, "e": 28223, "s": 27979, "text": "Raw to Processed EventsThe pipeline presented so far saves tracking events as raw data. To translate these events to processed data, we’ll need to apply event specific schemas. There’s a few different approaches we can take with this pipeline:" }, { "code": null, "e": 28467, "s": 28223, "text": "Apply the schemas in the current DataFlow pipeline and save to BigQueryApply the schemas in the current pipeline and send to a new PubSubApply additional attributes to the raw events and send to a new PubSubUse downstream ETLs to apply schemas" }, { "code": null, "e": 28539, "s": 28467, "text": "Apply the schemas in the current DataFlow pipeline and save to BigQuery" }, { "code": null, "e": 28606, "s": 28539, "text": "Apply the schemas in the current pipeline and send to a new PubSub" }, { "code": null, "e": 28677, "s": 28606, "text": "Apply additional attributes to the raw events and send to a new PubSub" }, { "code": null, "e": 28714, "s": 28677, "text": "Use downstream ETLs to apply schemas" }, { "code": null, "e": 28975, "s": 28714, "text": "The first approach is the simplest, but it doesn’t provide a good solution for updating the event definitions if needed. This approach can be implemented as shown in the code below, which shows how to filter and parse MatchStart events for entry into BigQuery." }, { "code": null, "e": 29926, "s": 28975, "text": "events.apply(\"To MatchStart Events\", ParDo.of( new DoFn<PubsubMessage, TableRow>() {@ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload());JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get(\"eventType\").getAsString(); String version = jsonObject.get(\"eventVersion\").getAsString(); String serverTime = dateFormat.format(new Date()); // Filter for MatchStart events if (eventType.equals(\"MatchStart\")) { TableRow record = new TableRow(); record.set(\"eventType\", eventType); record.set(\"eventVersion\", version); record.set(\"server_time\", serverTime); // event specifc attributes record.set(\"userID\", jsonObject.get(\"userID\").getAsString()); record.set(\"type\", jsonObject.get(\"deviceType\").getAsString()); c.output(record); }}})).apply(\"To BigQuery\",BigQueryIO.writeTableRows()" }, { "code": null, "e": 30459, "s": 29926, "text": "In order to implement this approach, you’d need to create a new DoFn implementation for each type of event. The second approach is similar to the first, but instead of passing the parsed events to BigQuery, they are passed to a new PubSub topic. It’s possible to send multiple types of events to a single topic or create a topic per event. The drawback of using the first two approaches is that the message parsing logic is part of the raw event pipeline. This means that changing event definitions involves restarting the pipeline." }, { "code": null, "e": 30883, "s": 30459, "text": "A third approach that can be used is sending raw events with additional attributes to another PubSub topic. A second DataFlow job can then be set up to parse events as needed. The code below shows how to parse raw events, add additional attributes to the PubSub message for filtering, and publish the events to a second topic. This approach enables event definitions to be changed without restarting the raw event pipeline." }, { "code": null, "e": 31835, "s": 30883, "text": "# topic for raw events with additional attributes private static String processed = \"projects/your_project_id/topics/processed-events\";events.apply(\"PubSub Processed\", ParDo.of(new DoFn<PubsubMessage, PubsubMessage>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the JSON message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get(\"eventType\").getAsString(); // Add additional attributes for filtering HashMap<String, String> atts = new HashMap(); atts.put(\"EventType\", eventType); PubsubMessage out = new PubsubMessage(message.getBytes(), atts); c.output(out); } })) .apply(PubsubIO.writeMessages().to(processed));" }, { "code": null, "e": 32047, "s": 31835, "text": "A fourth approach that can be used is having downstream ETLs processes apply schemas to the raw events and break apart the raw events table into event specific tables. We’ll cover this approach in the next post." }, { "code": null, "e": 32298, "s": 32047, "text": "This post has provided an introduction to building a data pipeline for a startup. We covered the types of data in a pipeline, desired properties of a high functioning data pipeline, the evolution of data pipelines, and a sample pipeline built on GCP." }, { "code": null, "e": 33011, "s": 32298, "text": "There is now a variety of tools available that make it possible to set up an analytics pipeline for an application with minimal effort. Using managed resources enables small teams to take advantage of serverless and autoscaling infrastructure to scale up to massive event volumes with minimal infrastructure management. Rather than using a data vendor’s off-the-shelf solution for collecting data, you can record all relevant data for your app. While the approach presented here isn’t directly portable to other clouds, the Apache Beam library used to implement the core functionality of this data pipeline is portable and similar tools can be leveraged to build scalable data pipelines on other cloud providers." } ]
Conditional ternary operator ( ?: ) in C++
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows − The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing. If the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated. The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands − If both operands are of the same type, the result is of that type. If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Standard Conversions) are performed to convert them to a common type. If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type. If both operands are of reference types, reference conversions are performed to convert them to a common type. If both operands are of type void, the common type is type void. If both operands are of the same user-defined type, the common type is that type. If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.) #include <iostream> using namespace std; int main() { int i = 1, j = 2; cout << ( i > j ? i : j ) << " is greater." << endl; } This will give the output − 2 is greater.
[ { "code": null, "e": 1186, "s": 1062, "text": "The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows −" }, { "code": null, "e": 1307, "s": 1186, "text": "The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing." }, { "code": null, "e": 1384, "s": 1307, "text": "If the first operand evaluates to true (1), the second operand is evaluated." }, { "code": null, "e": 1461, "s": 1384, "text": "If the first operand evaluates to false (0), the third operand is evaluated." }, { "code": null, "e": 1932, "s": 1461, "text": "The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands −" }, { "code": null, "e": 1999, "s": 1932, "text": "If both operands are of the same type, the result is of that type." }, { "code": null, "e": 2171, "s": 1999, "text": "If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Standard Conversions) are performed to convert them to a common type." }, { "code": null, "e": 2365, "s": 2171, "text": "If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type." }, { "code": null, "e": 2476, "s": 2365, "text": "If both operands are of reference types, reference conversions are performed to convert them to a common type." }, { "code": null, "e": 2541, "s": 2476, "text": "If both operands are of type void, the common type is type void." }, { "code": null, "e": 2623, "s": 2541, "text": "If both operands are of the same user-defined type, the common type is that type." }, { "code": null, "e": 2799, "s": 2623, "text": "If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)" }, { "code": null, "e": 2943, "s": 2799, "text": "#include <iostream> \nusing namespace std; \n\nint main() { \n int i = 1, j = 2; \n cout << ( i > j ? i : j ) << \" is greater.\" << endl; \n}" }, { "code": null, "e": 2971, "s": 2943, "text": "This will give the output −" }, { "code": null, "e": 2985, "s": 2971, "text": "2 is greater." } ]
How to find mode(s) of a vector in R?
Just like mean and median there is no in-built function in R to find the mode. We can make use of the following user created function for this purpose > Modes <- function(x) { ux <- unique(x) tab <- tabulate(match(x, ux)) ux[tab == max(tab)] } > x<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,6) > Modes(x) [1] 4 We have created a function called modes because a data can have more than one mode as shown below − > y<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,3) > Modes(y) [1] 3 4
[ { "code": null, "e": 1141, "s": 1062, "text": "Just like mean and median there is no in-built function in R to find the mode." }, { "code": null, "e": 1213, "s": 1141, "text": "We can make use of the following user created function for this purpose" }, { "code": null, "e": 1315, "s": 1213, "text": "> Modes <- function(x) {\n ux <- unique(x)\n tab <- tabulate(match(x, ux))\n ux[tab == max(tab)]\n}" }, { "code": null, "e": 1398, "s": 1315, "text": "> x<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,6)\n> Modes(x)\n[1] 4" }, { "code": null, "e": 1498, "s": 1398, "text": "We have created a function called modes because a data can have more than one mode as\nshown below −" }, { "code": null, "e": 1583, "s": 1498, "text": "> y<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,3)\n> Modes(y)\n[1] 3 4" } ]
Pointer Basics in C - GeeksQuiz
12 Nov, 2020 int *ptr; /* Note: the use of * here is not for dereferencing, it is for data type int */ int x; ptr = &x; /* ptr now points to x (or ptr is equal to address of x) */ *ptr = 0; /* set value ate ptr to 0 or set x to zero */ printf(" x = %d\n", x); /* prints x = 0 */ printf(" *ptr = %d\n", *ptr); /* prints *ptr = 0 */ *ptr += 5; /* increment the value at ptr by 5 */ printf(" x = %d\n", x); /* prints x = 5 */ printf(" *ptr = %d\n", *ptr); /* prints *ptr = 5 */ (*ptr)++; /* increment the value at ptr by 1 */ printf(" x = %d\n", x); /* prints x = 6 */ printf(" *ptr = %d\n", *ptr); /* prints *ptr = 6 */ int main() { char *ptr = "GeeksQuiz"; printf("%s\n", *&*&ptr); return 0; } void fun(int arr[]) void fun(int *arr) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies What is Transmission Control Protocol (TCP)? Difference Between Skewness and Kurtosis How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File Hash Functions and list/types of Hash functions How to Replace Values in a List in Python? Understanding Semantic Analysis - NLP How to Read Text Files with Pandas? How to Calculate Moving Averages in Python?
[ { "code": null, "e": 28855, "s": 28827, "text": "\n12 Nov, 2020" }, { "code": null, "e": 29539, "s": 28855, "text": " int *ptr; /* Note: the use of * here is not for dereferencing, \n it is for data type int */\n int x;\n\n ptr = &x; /* ptr now points to x (or ptr is equal to address of x) */\n *ptr = 0; /* set value ate ptr to 0 or set x to zero */\n\n printf(\" x = %d\\n\", x); /* prints x = 0 */\n printf(\" *ptr = %d\\n\", *ptr); /* prints *ptr = 0 */\n\n\n *ptr += 5; /* increment the value at ptr by 5 */\n printf(\" x = %d\\n\", x); /* prints x = 5 */\n printf(\" *ptr = %d\\n\", *ptr); /* prints *ptr = 5 */\n\n\n (*ptr)++; /* increment the value at ptr by 1 */\n printf(\" x = %d\\n\", x); /* prints x = 6 */\n printf(\" *ptr = %d\\n\", *ptr); /* prints *ptr = 6 */\n" }, { "code": null, "e": 29617, "s": 29539, "text": "int main()\n{\n char *ptr = \"GeeksQuiz\";\n printf(\"%s\\n\", *&*&ptr);\n return 0;\n}" }, { "code": null, "e": 29657, "s": 29617, "text": "void fun(int arr[])\nvoid fun(int *arr)\n" }, { "code": null, "e": 29755, "s": 29657, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29808, "s": 29755, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29853, "s": 29808, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 29894, "s": 29853, "text": "Difference Between Skewness and Kurtosis" }, { "code": null, "e": 29956, "s": 29894, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29997, "s": 29956, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30045, "s": 29997, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 30088, "s": 30045, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 30126, "s": 30088, "text": "Understanding Semantic Analysis - NLP" }, { "code": null, "e": 30162, "s": 30126, "text": "How to Read Text Files with Pandas?" } ]
Variations of LIS | DP-21 - GeeksforGeeks
03 Jun, 2021 We have discussed Dynamic Programming solution for Longest Increasing Subsequence problem in this post and a O(nLogn) solution in this post. Following are commonly asked variations of the standard LIS problem. 1. Building Bridges: Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city i on the northern bank to city i on the southern bank. 8 1 4 3 5 2 6 7 <---- Cities on the other bank of river----> -------------------------------------------- <--------------- River---------------> -------------------------------------------- 1 2 3 4 5 6 7 8 <------- Cities on one bank of river-------> Source: Dynamic Programming Practice Problems. The link also has well explained solution for the problem. The solution for this problem has been published here. 2. Maximum Sum Increasing Subsequence: Given an array of n positive integers. Write a program to find the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be {1, 2, 3, 100}. The solution to this problem has been published here. 3. The Longest Chain You are given pairs of numbers. In a pair, the first number is smaller with respect to the second number. Suppose you have two sets (a, b) and (c, d), the second set can follow the first set if b < c. So you can form a long chain in the similar fashion. Find the longest chain which can be formed. The solution to this problem has been published here. 4. Box Stacking You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box. Source: Dynamic Programming Practice Problems. The link also has well explained solution for the problem. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SheethalKumar sumitgumber28 LIS subsequence Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Coin Change | DP-7 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Edit Distance | DP-5 Find minimum number of coins that make a given value Sieve of Eratosthenes
[ { "code": null, "e": 26609, "s": 26581, "text": "\n03 Jun, 2021" }, { "code": null, "e": 26820, "s": 26609, "text": "We have discussed Dynamic Programming solution for Longest Increasing Subsequence problem in this post and a O(nLogn) solution in this post. Following are commonly asked variations of the standard LIS problem. " }, { "code": null, "e": 27272, "s": 26820, "text": "1. Building Bridges: Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city i on the northern bank to city i on the southern bank. " }, { "code": null, "e": 27585, "s": 27274, "text": "8 1 4 3 5 2 6 7 \n<---- Cities on the other bank of river---->\n--------------------------------------------\n <--------------- River--------------->\n--------------------------------------------\n1 2 3 4 5 6 7 8\n<------- Cities on one bank of river------->" }, { "code": null, "e": 27747, "s": 27585, "text": "Source: Dynamic Programming Practice Problems. The link also has well explained solution for the problem. The solution for this problem has been published here. " }, { "code": null, "e": 28115, "s": 27747, "text": "2. Maximum Sum Increasing Subsequence: Given an array of n positive integers. Write a program to find the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be {1, 2, 3, 100}. The solution to this problem has been published here. " }, { "code": null, "e": 28489, "s": 28115, "text": "3. The Longest Chain You are given pairs of numbers. In a pair, the first number is smaller with respect to the second number. Suppose you have two sets (a, b) and (c, d), the second set can follow the first set if b < c. So you can form a long chain in the similar fashion. Find the longest chain which can be formed. The solution to this problem has been published here. " }, { "code": null, "e": 29134, "s": 28489, "text": "4. Box Stacking You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box. Source: Dynamic Programming Practice Problems. The link also has well explained solution for the problem. " }, { "code": null, "e": 29260, "s": 29134, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29274, "s": 29260, "text": "SheethalKumar" }, { "code": null, "e": 29288, "s": 29274, "text": "sumitgumber28" }, { "code": null, "e": 29292, "s": 29288, "text": "LIS" }, { "code": null, "e": 29304, "s": 29292, "text": "subsequence" }, { "code": null, "e": 29324, "s": 29304, "text": "Dynamic Programming" }, { "code": null, "e": 29344, "s": 29324, "text": "Dynamic Programming" }, { "code": null, "e": 29442, "s": 29344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29473, "s": 29442, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 29506, "s": 29473, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 29533, "s": 29506, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 29568, "s": 29533, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 29587, "s": 29568, "text": "Coin Change | DP-7" }, { "code": null, "e": 29655, "s": 29587, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 29693, "s": 29655, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 29714, "s": 29693, "text": "Edit Distance | DP-5" }, { "code": null, "e": 29767, "s": 29714, "text": "Find minimum number of coins that make a given value" } ]
C# String.ToUpperInvariant Method
The String.ToUpperInvariant() method in C# is used to return a copy of this String object converted to uppercase using the casing rules of the invariant culture. The syntax is as follows - public string ToUpperInvariant (); Let us now see an example - Live Demo using System; using System.Text; public class Demo { public static void Main(String[] args) { string str1 = "one"; string str2 = "TWO"; string str3 = "ThrEE"; Console.WriteLine("String 1 = "+str1); Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant()); Console.WriteLine("String 2 = "+str2); Console.WriteLine("String2 ToUpperInvariant = "+str2.ToUpperInvariant()); Console.WriteLine("String 3 = "+str3); Console.WriteLine("String3 ToUpperInvariant = "+str3.ToUpperInvariant()); } } String 1 = one String1 ToUpperInvariant = ONE String 2 = TWO String2 ToUpperInvariant = TWO String 3 = ThrEE String3 ToUpperInvariant = THREE Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "abcd"; string str2 = "PQRS"; Console.WriteLine("String 1 = "+str1); Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant()); Console.WriteLine("String 2 = "+str2); Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant()); } } String 1 = abcd String1 ToUpperInvariant = ABCD String 2 = PQRS String2 ToUpperInvariant = pqrs
[ { "code": null, "e": 1224, "s": 1062, "text": "The String.ToUpperInvariant() method in C# is used to return a copy of this String object converted to uppercase using the casing rules of the invariant culture." }, { "code": null, "e": 1251, "s": 1224, "text": "The syntax is as follows -" }, { "code": null, "e": 1286, "s": 1251, "text": "public string ToUpperInvariant ();" }, { "code": null, "e": 1314, "s": 1286, "text": "Let us now see an example -" }, { "code": null, "e": 1325, "s": 1314, "text": " Live Demo" }, { "code": null, "e": 1887, "s": 1325, "text": "using System;\nusing System.Text;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"one\";\n string str2 = \"TWO\";\n string str3 = \"ThrEE\";\n Console.WriteLine(\"String 1 = \"+str1);\n Console.WriteLine(\"String1 ToUpperInvariant = \"+str1.ToUpperInvariant());\n Console.WriteLine(\"String 2 = \"+str2);\n Console.WriteLine(\"String2 ToUpperInvariant = \"+str2.ToUpperInvariant());\n Console.WriteLine(\"String 3 = \"+str3);\n Console.WriteLine(\"String3 ToUpperInvariant = \"+str3.ToUpperInvariant());\n }\n}" }, { "code": null, "e": 2029, "s": 1887, "text": "String 1 = one\nString1 ToUpperInvariant = ONE\nString 2 = TWO\nString2 ToUpperInvariant = TWO\nString 3 = ThrEE\nString3 ToUpperInvariant = THREE" }, { "code": null, "e": 2040, "s": 2029, "text": " Live Demo" }, { "code": null, "e": 2431, "s": 2040, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"abcd\";\n string str2 = \"PQRS\";\n Console.WriteLine(\"String 1 = \"+str1);\n Console.WriteLine(\"String1 ToUpperInvariant = \"+str1.ToUpperInvariant());\n Console.WriteLine(\"String 2 = \"+str2);\n Console.WriteLine(\"String2 ToUpperInvariant = \"+str2.ToLowerInvariant());\n }\n}" }, { "code": null, "e": 2527, "s": 2431, "text": "String 1 = abcd\nString1 ToUpperInvariant = ABCD\nString 2 = PQRS\nString2 ToUpperInvariant = pqrs" } ]
Ordered Set and GNU C++ PBDS
In this tutorial, we will be discussing a program to understand ordered set and GNU C++ PBDS. Ordered set is a policy based structure other than those in the STL library. The ordered set keeps all the elements in a sorted order and doesn’t allow duplicate values. Live Demo #include <iostream> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> int main(){ //declaring ordered set ordered_set o_set; o_set.insert(5); o_set.insert(1); o_set.insert(2); cout << *(o_set.find_by_order(1)) << endl; cout << o_set.order_of_key(4) << endl; cout << o_set.order_of_key(5) << endl; if (o_set.find(2) != o_set.end()) o_set.erase(o_set.find(2)); cout << *(o_set.find_by_order(1)) << endl; cout << o_set.order_of_key(4) << endl; return 0; } 2 2 2 5 1
[ { "code": null, "e": 1156, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand ordered set and GNU C++ PBDS." }, { "code": null, "e": 1326, "s": 1156, "text": "Ordered set is a policy based structure other than those in the STL library. The ordered set keeps all the elements in a sorted order and doesn’t allow duplicate values." }, { "code": null, "e": 1337, "s": 1326, "text": " Live Demo" }, { "code": null, "e": 2038, "s": 1337, "text": "#include <iostream>\nusing namespace std;\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<int, null_type,less<int>, \nrb_tree_tag,tree_order_statistics_node_update>\nint main(){\n //declaring ordered set\n ordered_set o_set;\n o_set.insert(5);\n o_set.insert(1);\n o_set.insert(2);\n cout << *(o_set.find_by_order(1))\n << endl;\n cout << o_set.order_of_key(4)\n << endl;\n cout << o_set.order_of_key(5)\n << endl;\n if (o_set.find(2) != o_set.end())\n o_set.erase(o_set.find(2));\n cout << *(o_set.find_by_order(1))\n << endl;\n cout << o_set.order_of_key(4)\n << endl;\n return 0;\n}" }, { "code": null, "e": 2048, "s": 2038, "text": "2\n2\n2\n5\n1" } ]
PyQtGraph - Setting Symbol Size of Line in Line Graph - GeeksforGeeks
23 Jan, 2022 In this article we will see how we can set symbol size of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. Line graph is created with the help of plot class in PyQtGraph. Symbols are the figure of the point which connect the data of the line. It is mainly x, o. We can create a plot window and create lines on it with the help of commands given below # creating a pyqtgraph plot window plt = pg.plot() # plotting line in green color # with dot symbol as x, not a mandatory field line = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green') In order to do this we use setSymbolSize method with the line objectSyntax : line.setSymbolSize(n)Argument : It takes integer as argumentReturn : It returns None Below is the implementation Python3 # importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel("GeeksforGeeks Line Plot") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x = True, y = True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal range plt.setXRange(0, 10) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # setting symbol pen of the line 1 line1.setSymbolPen(QColor(220, 30, 30)) # setting symbol size line1.setSymbolSize(45) # label minimum width label.setMinimumWidth(120) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : surindertarika1234 anikakapoor adnanirshad158 Python-gui Python-PyQt Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24908, "s": 24880, "text": "\n23 Jan, 2022" }, { "code": null, "e": 25646, "s": 24908, "text": "In this article we will see how we can set symbol size of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. Line graph is created with the help of plot class in PyQtGraph. Symbols are the figure of the point which connect the data of the line. It is mainly x, o." }, { "code": null, "e": 25736, "s": 25646, "text": "We can create a plot window and create lines on it with the help of commands given below " }, { "code": null, "e": 25954, "s": 25736, "text": "# creating a pyqtgraph plot window\nplt = pg.plot()\n\n# plotting line in green color\n# with dot symbol as x, not a mandatory field\nline = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green')" }, { "code": null, "e": 26118, "s": 25954, "text": "In order to do this we use setSymbolSize method with the line objectSyntax : line.setSymbolSize(n)Argument : It takes integer as argumentReturn : It returns None " }, { "code": null, "e": 26148, "s": 26118, "text": "Below is the implementation " }, { "code": null, "e": 26156, "s": 26148, "text": "Python3" }, { "code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel(\"GeeksforGeeks Line Plot\") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x = True, y = True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal range plt.setXRange(0, 10) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # setting symbol pen of the line 1 line1.setSymbolPen(QColor(220, 30, 30)) # setting symbol size line1.setSymbolSize(45) # label minimum width label.setMinimumWidth(120) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 29181, "s": 26156, "text": null }, { "code": null, "e": 29190, "s": 29181, "text": "Output :" }, { "code": null, "e": 29211, "s": 29192, "text": "surindertarika1234" }, { "code": null, "e": 29223, "s": 29211, "text": "anikakapoor" }, { "code": null, "e": 29238, "s": 29223, "text": "adnanirshad158" }, { "code": null, "e": 29249, "s": 29238, "text": "Python-gui" }, { "code": null, "e": 29261, "s": 29249, "text": "Python-PyQt" }, { "code": null, "e": 29278, "s": 29261, "text": "Python-PyQtGraph" }, { "code": null, "e": 29285, "s": 29278, "text": "Python" }, { "code": null, "e": 29383, "s": 29285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29392, "s": 29383, "text": "Comments" }, { "code": null, "e": 29405, "s": 29392, "text": "Old Comments" }, { "code": null, "e": 29423, "s": 29405, "text": "Python Dictionary" }, { "code": null, "e": 29458, "s": 29423, "text": "Read a file line by line in Python" }, { "code": null, "e": 29480, "s": 29458, "text": "Enumerate() in Python" }, { "code": null, "e": 29512, "s": 29480, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29542, "s": 29512, "text": "Iterate over a list in Python" }, { "code": null, "e": 29584, "s": 29542, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29610, "s": 29584, "text": "Python String | replace()" }, { "code": null, "e": 29653, "s": 29610, "text": "Python program to convert a list to string" }, { "code": null, "e": 29690, "s": 29653, "text": "Create a Pandas DataFrame from Lists" } ]
Awesome JupyterLab Extensions. A tour of some of the useful JupyterLab... | by Parul Pandey | Towards Data Science
Jupyter Lab is one of the most widely used IDEs in the data science community. They are the choice of tool for many data scientists when it comes to quick prototyping and exploratory analysis. A JupyterLab neatly bundles many functionalities together, enabling collaborative, extensible, and scalable data science. However, this article is not about the various advantages of the Jupyter Lab. I believe there are a plethora of resources on that topic. Instead, the focus here will be on one of the useful components of JupyterLab called Extensions. These extensions are pretty helpful and can enhance a person’s productivity when working alone or in a team. Let’s start by understanding what an extension is, and then we’ll quickly go through some of the useful JupyterLab extensions currently available on Github. The JupyterLab has been designed as an extensible and modular environment. As a result, one can easily add and integrate new components into the existing environment. Extensions work on this very core idea. JupyterLab can be easily extended via third-party extensions. These extensions, written by developers from the Jupyter community, are essentially npm packages (the standard package format in Javascript development). So what makes these extensions so useful? Well, here is an excerpt from the official documentation which answers this question: “Extensions can add items to the menu or command palette, keyboard shortcuts, or settings in the settings system. Extensions can provide an API for other extensions to use and can depend on other extensions. In fact, the whole of JupyterLab itself is simply a collection of extensions that are no more powerful or privileged than any custom extension.” In this article, we’ll look at some of the useful extensions and how they can enhance our experience while working with the jupyter lab. But before we begin, let’s quickly look at how we can install these extensions. To install JupyterLab extensions, you need to have Node.js installed, either directly installed from the Node.js website or as follows. conda install -c conda-forge nodejsor# For Mac OSX usersbrew install node Once installed, it appears as a new icon in the JupyterLab sidebar. To manage the various extensions, we can use the extension manager. By default, the manager is disabled but can be enabled by clicking on the enable button. Alternatively, you can search for the Extension Manager in the command palette and enable it there also. Let’s now take a tour of some of the useful extensions available currently in JupyterLab. Please keep in mind that these are third party extensions and are not reviewed. Some extensions may introduce security risks or contain malicious code that runs on your machine. You can search for the desired extension in the extension manager. While searching, you’ll notice that some of these extensions have a Jupyter icon next to their name. These extensions are released by the Jupyter organization and are always placed first. As the name suggests, the jupyterlab-google-drive extension provides cloud storage for the JupyterLab via the google drive. Once installed, this extension adds a Google Drive file browser to the left side panel of JupyterLab. You need to be logged into your google account to access the files stored in your google drive through JupyterLab. You can install the extension via the extension manager. Search for the name of the extension in the search bar and install it. You will then need to restart the environment. Once you do so, you will be greeted with the following prompt: Click on Build to incorporate any changes, and you’ll instantly see a google drive icon in the sidebar. Apart from installing the extension, you will also need to authenticate your JupyterLab deployment with Google. Go through the setup file or the link here for the process. Once you fill in the credentials, you’ll be able to access your drive from the jupyter lab. Alternatively, you can install the extension via the CLI, as follows: #Install the jupyterlab-google-drive extensionjupyter labextension install @jupyterlab/google-drive#Set up your credentials using this guide.# Start JupyterLabjupyter lab Now, if someone shares a notebook or a markdown file with you, it will reflect in the shared with me folder in Jupyter Lab. You can open it and edit it in the Jupyter environment seamlessly. JupyterLab Github is a JupyterLab extension for accessing GitHub repositories. With this extension, you can select GitHub organizations, browse their repositories, and open the files in those repositories. If the repositories contain a jupyter notebook, you’ll be able to access them directly in your JupyterLab environment. Again, you can install this extension either through the extension manager or through the CLI. Please be aware that this package has indicated that it needs a corresponding server extension, which you will be prompted to install before using the extension. After installation, you need to get the credentials from GitHub. Once the credentials and permissions are entered, you can access all your repositories in the JupyterLab environment without switching between different interfaces. Jupyterlab-git is another useful JupyterLab extension used for version control using git. To install the extensions, you can follow perform the following steps: Once installed, the Git extension can be accessed from the Git tab on the left panel The Jupyterlab-TOC extension populates a table of contents on the left side of a JupyterLab interface. If there is a notebook or a markdown file open, its corresponding TOC will be generated on the sidebar. The entries are scrollable and clickable. Once the extension is installed, you can modify some of its properties via JupyterLab’s advanced settings editor. For instance, you can collapse sections of notebooks from the ToC by setting the collapsibleNotebooks parameter as True. Drawio plugin is a JupyterLab extension for standalone integration of drawio/ mxgraph into Jupyterlab. draw.io is a free online diagram software for making flowcharts, process diagrams, org charts, UML, ER, and network diagrams. The Jupyterlab-topbar is an extension for modifying the top bar in the JupyterLab interface. The top bar can be used to place a few useful indicators like: Once the extension is installed and enabled, you’ll see some indicators on the top bar. There will be a log-out button, dark and light theme switch, custom message, and memory indicators. The Jupyterlab Code Formatter is a small plugin to support various code formatters in JupyterLab. This is one of my favorite extensions since it takes away a lot of pain from code formatting. The first step is to install the plugin. The next step would be to install the code formatters. The Jupyterlab Code Formatter currently supports the following formatters in Python and R. # Install your favourite code formatters from the list abovepip install black isort#orconda install black isort You can then restart the JupyterLab and configure the plugin, as mentioned here. A quick demo is shown below but for detailed usage, follow the documentation. The code for the following demo has been taken from the Github repository of the extension. The jupyterlab-chart-editor extension is used for editing the Plotly charts, based on https://github.com/plotly/react-chart-editor. The extension enables editing Plotly charts through a user-friendly point-and-click interface. The following example has been taken from the official documentation. A figure is first created using plotly and then written to a JSON file. The saved file is then opened using the newly installed plotly editor, and some changes are made to it right on the jupyterLab environment. In this article, we looked at some useful JupyterLab extensions that make the JupyterLab stand out. Having different tools in a single workplace makes it very useful since one doesn’t have to switch between different environments to get the things done. These add ons will surely make your data analysis process much smoother and more productive.
[ { "code": null, "e": 986, "s": 171, "text": "Jupyter Lab is one of the most widely used IDEs in the data science community. They are the choice of tool for many data scientists when it comes to quick prototyping and exploratory analysis. A JupyterLab neatly bundles many functionalities together, enabling collaborative, extensible, and scalable data science. However, this article is not about the various advantages of the Jupyter Lab. I believe there are a plethora of resources on that topic. Instead, the focus here will be on one of the useful components of JupyterLab called Extensions. These extensions are pretty helpful and can enhance a person’s productivity when working alone or in a team. Let’s start by understanding what an extension is, and then we’ll quickly go through some of the useful JupyterLab extensions currently available on Github." }, { "code": null, "e": 1537, "s": 986, "text": "The JupyterLab has been designed as an extensible and modular environment. As a result, one can easily add and integrate new components into the existing environment. Extensions work on this very core idea. JupyterLab can be easily extended via third-party extensions. These extensions, written by developers from the Jupyter community, are essentially npm packages (the standard package format in Javascript development). So what makes these extensions so useful? Well, here is an excerpt from the official documentation which answers this question:" }, { "code": null, "e": 1890, "s": 1537, "text": "“Extensions can add items to the menu or command palette, keyboard shortcuts, or settings in the settings system. Extensions can provide an API for other extensions to use and can depend on other extensions. In fact, the whole of JupyterLab itself is simply a collection of extensions that are no more powerful or privileged than any custom extension.”" }, { "code": null, "e": 2243, "s": 1890, "text": "In this article, we’ll look at some of the useful extensions and how they can enhance our experience while working with the jupyter lab. But before we begin, let’s quickly look at how we can install these extensions. To install JupyterLab extensions, you need to have Node.js installed, either directly installed from the Node.js website or as follows." }, { "code": null, "e": 2317, "s": 2243, "text": "conda install -c conda-forge nodejsor# For Mac OSX usersbrew install node" }, { "code": null, "e": 2385, "s": 2317, "text": "Once installed, it appears as a new icon in the JupyterLab sidebar." }, { "code": null, "e": 2542, "s": 2385, "text": "To manage the various extensions, we can use the extension manager. By default, the manager is disabled but can be enabled by clicking on the enable button." }, { "code": null, "e": 2647, "s": 2542, "text": "Alternatively, you can search for the Extension Manager in the command palette and enable it there also." }, { "code": null, "e": 2915, "s": 2647, "text": "Let’s now take a tour of some of the useful extensions available currently in JupyterLab. Please keep in mind that these are third party extensions and are not reviewed. Some extensions may introduce security risks or contain malicious code that runs on your machine." }, { "code": null, "e": 3170, "s": 2915, "text": "You can search for the desired extension in the extension manager. While searching, you’ll notice that some of these extensions have a Jupyter icon next to their name. These extensions are released by the Jupyter organization and are always placed first." }, { "code": null, "e": 3511, "s": 3170, "text": "As the name suggests, the jupyterlab-google-drive extension provides cloud storage for the JupyterLab via the google drive. Once installed, this extension adds a Google Drive file browser to the left side panel of JupyterLab. You need to be logged into your google account to access the files stored in your google drive through JupyterLab." }, { "code": null, "e": 3639, "s": 3511, "text": "You can install the extension via the extension manager. Search for the name of the extension in the search bar and install it." }, { "code": null, "e": 3749, "s": 3639, "text": "You will then need to restart the environment. Once you do so, you will be greeted with the following prompt:" }, { "code": null, "e": 4117, "s": 3749, "text": "Click on Build to incorporate any changes, and you’ll instantly see a google drive icon in the sidebar. Apart from installing the extension, you will also need to authenticate your JupyterLab deployment with Google. Go through the setup file or the link here for the process. Once you fill in the credentials, you’ll be able to access your drive from the jupyter lab." }, { "code": null, "e": 4187, "s": 4117, "text": "Alternatively, you can install the extension via the CLI, as follows:" }, { "code": null, "e": 4358, "s": 4187, "text": "#Install the jupyterlab-google-drive extensionjupyter labextension install @jupyterlab/google-drive#Set up your credentials using this guide.# Start JupyterLabjupyter lab" }, { "code": null, "e": 4549, "s": 4358, "text": "Now, if someone shares a notebook or a markdown file with you, it will reflect in the shared with me folder in Jupyter Lab. You can open it and edit it in the Jupyter environment seamlessly." }, { "code": null, "e": 4874, "s": 4549, "text": "JupyterLab Github is a JupyterLab extension for accessing GitHub repositories. With this extension, you can select GitHub organizations, browse their repositories, and open the files in those repositories. If the repositories contain a jupyter notebook, you’ll be able to access them directly in your JupyterLab environment." }, { "code": null, "e": 5131, "s": 4874, "text": "Again, you can install this extension either through the extension manager or through the CLI. Please be aware that this package has indicated that it needs a corresponding server extension, which you will be prompted to install before using the extension." }, { "code": null, "e": 5196, "s": 5131, "text": "After installation, you need to get the credentials from GitHub." }, { "code": null, "e": 5361, "s": 5196, "text": "Once the credentials and permissions are entered, you can access all your repositories in the JupyterLab environment without switching between different interfaces." }, { "code": null, "e": 5451, "s": 5361, "text": "Jupyterlab-git is another useful JupyterLab extension used for version control using git." }, { "code": null, "e": 5522, "s": 5451, "text": "To install the extensions, you can follow perform the following steps:" }, { "code": null, "e": 5607, "s": 5522, "text": "Once installed, the Git extension can be accessed from the Git tab on the left panel" }, { "code": null, "e": 5856, "s": 5607, "text": "The Jupyterlab-TOC extension populates a table of contents on the left side of a JupyterLab interface. If there is a notebook or a markdown file open, its corresponding TOC will be generated on the sidebar. The entries are scrollable and clickable." }, { "code": null, "e": 6091, "s": 5856, "text": "Once the extension is installed, you can modify some of its properties via JupyterLab’s advanced settings editor. For instance, you can collapse sections of notebooks from the ToC by setting the collapsibleNotebooks parameter as True." }, { "code": null, "e": 6320, "s": 6091, "text": "Drawio plugin is a JupyterLab extension for standalone integration of drawio/ mxgraph into Jupyterlab. draw.io is a free online diagram software for making flowcharts, process diagrams, org charts, UML, ER, and network diagrams." }, { "code": null, "e": 6476, "s": 6320, "text": "The Jupyterlab-topbar is an extension for modifying the top bar in the JupyterLab interface. The top bar can be used to place a few useful indicators like:" }, { "code": null, "e": 6664, "s": 6476, "text": "Once the extension is installed and enabled, you’ll see some indicators on the top bar. There will be a log-out button, dark and light theme switch, custom message, and memory indicators." }, { "code": null, "e": 6856, "s": 6664, "text": "The Jupyterlab Code Formatter is a small plugin to support various code formatters in JupyterLab. This is one of my favorite extensions since it takes away a lot of pain from code formatting." }, { "code": null, "e": 6897, "s": 6856, "text": "The first step is to install the plugin." }, { "code": null, "e": 7043, "s": 6897, "text": "The next step would be to install the code formatters. The Jupyterlab Code Formatter currently supports the following formatters in Python and R." }, { "code": null, "e": 7155, "s": 7043, "text": "# Install your favourite code formatters from the list abovepip install black isort#orconda install black isort" }, { "code": null, "e": 7406, "s": 7155, "text": "You can then restart the JupyterLab and configure the plugin, as mentioned here. A quick demo is shown below but for detailed usage, follow the documentation. The code for the following demo has been taken from the Github repository of the extension." }, { "code": null, "e": 7633, "s": 7406, "text": "The jupyterlab-chart-editor extension is used for editing the Plotly charts, based on https://github.com/plotly/react-chart-editor. The extension enables editing Plotly charts through a user-friendly point-and-click interface." }, { "code": null, "e": 7915, "s": 7633, "text": "The following example has been taken from the official documentation. A figure is first created using plotly and then written to a JSON file. The saved file is then opened using the newly installed plotly editor, and some changes are made to it right on the jupyterLab environment." } ]
Print all nodes that are at distance k from a leaf node - GeeksforGeeks
22 Mar, 2022 Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node. Here the meaning of distance is different from previous post. Here k distance from a leaf means k levels higher than a leaf node. For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree. The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes that are already printed as output. For that we use a boolean array visited[]. C++ Java Python3 C# Javascript /* Program to print all nodeswhich are at distance k from a leaf */#include <iostream>using namespace std;#define MAX_HEIGHT 10000 struct Node { int key; Node *left, *right;}; /* utility that allocates a new Node with the given key */Node* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */void kDistantFromLeafUtil(Node* node, int path[], bool visited[], int pathLen, int k){ // Base case if (node == NULL) return; /* append this Node to the path array */ path[pathLen] = node->key; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node->left == NULL && node->right == NULL && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { cout << path[pathLen - k - 1] << " "; visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node->left, path, visited, pathLen, k); kDistantFromLeafUtil(node->right, path, visited, pathLen, k);} /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/void printKDistantfromLeaf(Node* node, int k){ int path[MAX_HEIGHT]; bool visited[MAX_HEIGHT] = { false }; kDistantFromLeafUtil(node, path, visited, 0, k);} /* Driver code*/int main(){ // Let us create binary tree // given in the above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << "Nodes at distance 2 are: "; printKDistantfromLeaf(root, 2); return 0;} // Java program to print all nodes at a distance k from leaf// A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ void kDistantFromLeafUtil(Node node, int path[], boolean visited[], int pathLen, int k) { // Base case if (node == null) return; /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { System.out.print(path[pathLen - k - 1] + " "); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ void printKDistantfromLeaf(Node node, int k) { int path[] = new int[1000]; boolean visited[] = new boolean[1000]; kDistantFromLeafUtil(node, path, visited, 0, k); } // Driver program to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); System.out.println(" Nodes at distance 2 are :"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code has been contributed by Mayank Jaiswal # Program to print all nodes which are at# distance k from a leaf # utility that allocates a new Node with# the given keyclass newNode: def __init__(self, key): self.key = key self.left = self.right = None # This function prints all nodes that# are distance k from a leaf node# path[] -. Store ancestors of a node# visited[] -. Stores true if a node is# printed as output. A node may be k distance# away from many leaves, we want to print it oncedef kDistantFromLeafUtil(node, path, visited, pathLen, k): # Base case if (node == None): return # append this Node to the path array path[pathLen] = node.key visited[pathLen] = False pathLen += 1 # it's a leaf, so print the ancestor at # distance k only if the ancestor is # not already printed if (node.left == None and node.right == None and pathLen - k - 1 >= 0 and visited[pathLen - k - 1] == False): print(path[pathLen - k - 1], end = " ") visited[pathLen - k - 1] = True return # If not leaf node, recur for left # and right subtrees kDistantFromLeafUtil(node.left, path, visited, pathLen, k) kDistantFromLeafUtil(node.right, path, visited, pathLen, k) # Given a binary tree and a number k,# print all nodes that are k distant from a leafdef printKDistantfromLeaf(node, k): global MAX_HEIGHT path = [None] * MAX_HEIGHT visited = [False] * MAX_HEIGHT kDistantFromLeafUtil(node, path, visited, 0, k) # Driver CodeMAX_HEIGHT = 10000 # Let us create binary tree given in# the above exampleroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7)root.right.left.right = newNode(8) print("Nodes at distance 2 are:", end = " ")printKDistantfromLeaf(root, 2) # This code is contributed by pranchalK using System; // C# program to print all nodes at a distance k from leaf// A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { public Node root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ public virtual void kDistantFromLeafUtil(Node node, int[] path, bool[] visited, int pathLen, int k) { // Base case if (node == null) { return; } /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { Console.Write(path[pathLen - k - 1] + " "); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ public virtual void printKDistantfromLeaf(Node node, int k) { int[] path = new int[1000]; bool[] visited = new bool[1000]; kDistantFromLeafUtil(node, path, visited, 0, k); } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Console.WriteLine(" Nodes at distance 2 are :"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code is contributed by Shrikant13 <script> // JavaScript program to print all // nodes at a distance k from leaf // A binary tree node class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ function kDistantFromLeafUtil(node, path, visited, pathLen, k) { // Base case if (node == null) return; /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && (pathLen - k - 1) >= 0 && visited[pathLen - k - 1] == false) { document.write(path[pathLen - k - 1] + " "); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ function printKDistantfromLeaf(node, k) { let path = new Array(1000); path.fill(0); let visited = new Array(1000); visited.fill(false); kDistantFromLeafUtil(node, path, visited, 0, k); } /* Let us construct the tree shown in above diagram */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); document.write(" Nodes at distance 2 are : "); printKDistantfromLeaf(root, 2); </script> Nodes at distance 2 are: 1 3 Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree traversal. Space Optimized Solution : C++ Java Python3 C# Javascript // C++ program to print all nodes at a distance k from leaf// A binary tree node#include <bits/stdc++.h>using namespace std;struct Node{ int data; Node *left, *right;}; // Utility function to // create a new tree node Node* newNode(int key) { Node *temp = new Node; temp->data= key; temp->left = temp->right = NULL; return temp; } /* Given a binary tree and a number k,print all nodes that are kdistant from a leaf*/int printKDistantfromLeaf(struct Node *node, int k){ if (node == NULL) return -1; int lk = printKDistantfromLeaf(node->left, k); int rk = printKDistantfromLeaf(node->right, k); bool isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) cout<<(" " )<<( node->data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2;} // Driver codeint main(){ Node *root = NULL; /* Let us construct the tree shown in above diagram */ root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << (" Nodes at distance 2 are :") << endl; printKDistantfromLeaf(root, 2);} // This code contributed by aashish1995 // Java program to print all nodes at a distance k from leaf// A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ int printKDistantfromLeaf(Node node, int k) { if (node == null) return -1; int lk = printKDistantfromLeaf(node.left, k); int rk = printKDistantfromLeaf(node.right, k); boolean isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) System.out.print(" " + node.data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2; } // Driver program to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); System.out.println(" Nodes at distance 2 are :"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code has been contributed by Vijayan Annamalai # Python program to print all nodes# at a distance k from leaf # A binary tree nodeclass Node: def __init__(self,item): self.data = item self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None # Given a binary tree and a number # k, print all nodes that are k # distant from a leaf def printKDistantfromLeaf(self,node, k): if (node == None): return -1 lk = self.printKDistantfromLeaf(node.left, k) rk = self.printKDistantfromLeaf(node.right, k) isLeaf = lk == -1 and lk == rk if (lk == 0 or rk == 0 or (isLeaf and k == 0)): print(node.data,end=" ") # Leaf node if (isLeaf and k > 0): return k - 1 # Parent of left leaf if (lk > 0 and lk < k): return lk - 1 # Parent of right leaf if (rk > 0 and rk < k): return rk - 1 return -2 # Driver codetree = BinaryTree() # Let us construct the tree shown# in above diagramtree.root = Node(1)tree.root.left = Node(2)tree.root.right = Node(3)tree.root.left.left = Node(4)tree.root.left.right = Node(5)tree.root.right.left = Node(6)tree.root.right.right = Node(7)tree.root.right.left.right = Node(8) print("Nodes at distance 2 are :")tree.printKDistantfromLeaf(tree.root, 2) # self code is contributed by shinjanpatra // C# program to print all nodes at a distance k from leaf// A binary tree nodeusing System; class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ int printKDistantfromLeaf(Node node, int k) { if (node == null) return -1; int lk = printKDistantfromLeaf(node.left, k); int rk = printKDistantfromLeaf(node.right, k); bool isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) Console.Write(" " + node.data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2; } // Driver program to test the above functions public static void Main(string []args) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Console.Write("Nodes at distance 2 are :"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code is contributed by rutvik_56 <script> // JavaScript program to print all nodes// at a distance k from leaf // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class BinaryTree{ constructor() { this.root = null; } // Given a binary tree and a number // k, print all nodes that are k // distant from a leaf printKDistantfromLeaf(node, k) { if (node == null) return -1; var lk = this.printKDistantfromLeaf(node.left, k); var rk = this.printKDistantfromLeaf(node.right, k); var isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) document.write(" " + node.data); // Leaf node if (isLeaf && k > 0) return k - 1; // Parent of left leaf if (lk > 0 && lk < k) return lk - 1; // Parent of right leaf if (rk > 0 && rk < k) return rk - 1; return -2; }} // Driver codevar tree = new BinaryTree(); // Let us construct the tree shown// in above diagramtree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);tree.root.right.left = new Node(6);tree.root.right.right = new Node(7);tree.root.right.left.right = new Node(8); document.write("Nodes at distance 2 are :<br>");tree.printKDistantfromLeaf(tree.root, 2); // This code is contributed by rdtank </script> Nodes at distance 2 are : 3 1 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Another approach : C++ // Print all nodes that are at distance k from a leaf node#include <iostream>using namespace std; struct bstnode { int data; bstnode* right; bstnode* left;}; bstnode* newnode(int data){ bstnode* temp = new bstnode(); temp->data = data; temp->right = temp->left = NULL; return temp;} void del(bstnode* root){ if (root != NULL) { del(root->left); del(root->right); delete root; }} int printk(bstnode* root, int k){ if (root == NULL) return 0; int l = printk(root->left, k); int r = printk(root->right, k); if (l == k || r == k) cout << root->data << " "; return 1 + max(l, r);} int main(){ bstnode* root = NULL; root = newnode(1); root->left = newnode(2); root->right = newnode(3); root->left->left = newnode(4); root->left->right = newnode(5); root->right->left = newnode(6); root->right->right = newnode(7); root->right->left->right = newnode(8); // root->right->right->right=newnode(9); int k = 2; printk(root, k); del(root); return 0; // This approach is given by gourabn2000 } 3 1 Time Complexity: O(n) as the code does a simple tree traversal. Auxiliary Space: O(h) as the function call stack is used where h=height of the tree. shrikanth13 PranchalKatiyar loginvijayan rutvik_56 aashish1995 AshokJaiswal mukesh07 rdtank arorakashish0911 gourabn2000 as5853535 shinjanpatra Microsoft Tree Microsoft Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree
[ { "code": null, "e": 25292, "s": 25264, "text": "\n22 Mar, 2022" }, { "code": null, "e": 25694, "s": 25292, "text": "Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node. Here the meaning of distance is different from previous post. Here k distance from a leaf means k levels higher than a leaf node. For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree." }, { "code": null, "e": 25961, "s": 25694, "text": "The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes that are already printed as output. For that we use a boolean array visited[]. " }, { "code": null, "e": 25965, "s": 25961, "text": "C++" }, { "code": null, "e": 25970, "s": 25965, "text": "Java" }, { "code": null, "e": 25978, "s": 25970, "text": "Python3" }, { "code": null, "e": 25981, "s": 25978, "text": "C#" }, { "code": null, "e": 25992, "s": 25981, "text": "Javascript" }, { "code": "/* Program to print all nodeswhich are at distance k from a leaf */#include <iostream>using namespace std;#define MAX_HEIGHT 10000 struct Node { int key; Node *left, *right;}; /* utility that allocates a new Node with the given key */Node* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node);} /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */void kDistantFromLeafUtil(Node* node, int path[], bool visited[], int pathLen, int k){ // Base case if (node == NULL) return; /* append this Node to the path array */ path[pathLen] = node->key; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node->left == NULL && node->right == NULL && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { cout << path[pathLen - k - 1] << \" \"; visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node->left, path, visited, pathLen, k); kDistantFromLeafUtil(node->right, path, visited, pathLen, k);} /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/void printKDistantfromLeaf(Node* node, int k){ int path[MAX_HEIGHT]; bool visited[MAX_HEIGHT] = { false }; kDistantFromLeafUtil(node, path, visited, 0, k);} /* Driver code*/int main(){ // Let us create binary tree // given in the above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << \"Nodes at distance 2 are: \"; printKDistantfromLeaf(root, 2); return 0;}", "e": 28150, "s": 25992, "text": null }, { "code": "// Java program to print all nodes at a distance k from leaf// A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ void kDistantFromLeafUtil(Node node, int path[], boolean visited[], int pathLen, int k) { // Base case if (node == null) return; /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { System.out.print(path[pathLen - k - 1] + \" \"); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ void printKDistantfromLeaf(Node node, int k) { int path[] = new int[1000]; boolean visited[] = new boolean[1000]; kDistantFromLeafUtil(node, path, visited, 0, k); } // Driver program to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); System.out.println(\" Nodes at distance 2 are :\"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code has been contributed by Mayank Jaiswal", "e": 30536, "s": 28150, "text": null }, { "code": "# Program to print all nodes which are at# distance k from a leaf # utility that allocates a new Node with# the given keyclass newNode: def __init__(self, key): self.key = key self.left = self.right = None # This function prints all nodes that# are distance k from a leaf node# path[] -. Store ancestors of a node# visited[] -. Stores true if a node is# printed as output. A node may be k distance# away from many leaves, we want to print it oncedef kDistantFromLeafUtil(node, path, visited, pathLen, k): # Base case if (node == None): return # append this Node to the path array path[pathLen] = node.key visited[pathLen] = False pathLen += 1 # it's a leaf, so print the ancestor at # distance k only if the ancestor is # not already printed if (node.left == None and node.right == None and pathLen - k - 1 >= 0 and visited[pathLen - k - 1] == False): print(path[pathLen - k - 1], end = \" \") visited[pathLen - k - 1] = True return # If not leaf node, recur for left # and right subtrees kDistantFromLeafUtil(node.left, path, visited, pathLen, k) kDistantFromLeafUtil(node.right, path, visited, pathLen, k) # Given a binary tree and a number k,# print all nodes that are k distant from a leafdef printKDistantfromLeaf(node, k): global MAX_HEIGHT path = [None] * MAX_HEIGHT visited = [False] * MAX_HEIGHT kDistantFromLeafUtil(node, path, visited, 0, k) # Driver CodeMAX_HEIGHT = 10000 # Let us create binary tree given in# the above exampleroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7)root.right.left.right = newNode(8) print(\"Nodes at distance 2 are:\", end = \" \")printKDistantfromLeaf(root, 2) # This code is contributed by pranchalK", "e": 32539, "s": 30536, "text": null }, { "code": "using System; // C# program to print all nodes at a distance k from leaf// A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { public Node root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ public virtual void kDistantFromLeafUtil(Node node, int[] path, bool[] visited, int pathLen, int k) { // Base case if (node == null) { return; } /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { Console.Write(path[pathLen - k - 1] + \" \"); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ public virtual void printKDistantfromLeaf(Node node, int k) { int[] path = new int[1000]; bool[] visited = new bool[1000]; kDistantFromLeafUtil(node, path, visited, 0, k); } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Console.WriteLine(\" Nodes at distance 2 are :\"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code is contributed by Shrikant13", "e": 34957, "s": 32539, "text": null }, { "code": "<script> // JavaScript program to print all // nodes at a distance k from leaf // A binary tree node class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ function kDistantFromLeafUtil(node, path, visited, pathLen, k) { // Base case if (node == null) return; /* append this Node to the path array */ path[pathLen] = node.data; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node.left == null && node.right == null && (pathLen - k - 1) >= 0 && visited[pathLen - k - 1] == false) { document.write(path[pathLen - k - 1] + \" \"); visited[pathLen - k - 1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node.left, path, visited, pathLen, k); kDistantFromLeafUtil(node.right, path, visited, pathLen, k); } /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ function printKDistantfromLeaf(node, k) { let path = new Array(1000); path.fill(0); let visited = new Array(1000); visited.fill(false); kDistantFromLeafUtil(node, path, visited, 0, k); } /* Let us construct the tree shown in above diagram */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); document.write(\" Nodes at distance 2 are : \"); printKDistantfromLeaf(root, 2); </script>", "e": 37128, "s": 34957, "text": null }, { "code": null, "e": 37161, "s": 37131, "text": "Nodes at distance 2 are: 1 3 " }, { "code": null, "e": 37261, "s": 37163, "text": "Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree traversal. " }, { "code": null, "e": 37290, "s": 37263, "text": "Space Optimized Solution :" }, { "code": null, "e": 37296, "s": 37292, "text": "C++" }, { "code": null, "e": 37301, "s": 37296, "text": "Java" }, { "code": null, "e": 37309, "s": 37301, "text": "Python3" }, { "code": null, "e": 37312, "s": 37309, "text": "C#" }, { "code": null, "e": 37323, "s": 37312, "text": "Javascript" }, { "code": "// C++ program to print all nodes at a distance k from leaf// A binary tree node#include <bits/stdc++.h>using namespace std;struct Node{ int data; Node *left, *right;}; // Utility function to // create a new tree node Node* newNode(int key) { Node *temp = new Node; temp->data= key; temp->left = temp->right = NULL; return temp; } /* Given a binary tree and a number k,print all nodes that are kdistant from a leaf*/int printKDistantfromLeaf(struct Node *node, int k){ if (node == NULL) return -1; int lk = printKDistantfromLeaf(node->left, k); int rk = printKDistantfromLeaf(node->right, k); bool isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) cout<<(\" \" )<<( node->data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2;} // Driver codeint main(){ Node *root = NULL; /* Let us construct the tree shown in above diagram */ root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << (\" Nodes at distance 2 are :\") << endl; printKDistantfromLeaf(root, 2);} // This code contributed by aashish1995", "e": 38730, "s": 37323, "text": null }, { "code": "// Java program to print all nodes at a distance k from leaf// A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ int printKDistantfromLeaf(Node node, int k) { if (node == null) return -1; int lk = printKDistantfromLeaf(node.left, k); int rk = printKDistantfromLeaf(node.right, k); boolean isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) System.out.print(\" \" + node.data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2; } // Driver program to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); System.out.println(\" Nodes at distance 2 are :\"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code has been contributed by Vijayan Annamalai", "e": 40361, "s": 38730, "text": null }, { "code": "# Python program to print all nodes# at a distance k from leaf # A binary tree nodeclass Node: def __init__(self,item): self.data = item self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None # Given a binary tree and a number # k, print all nodes that are k # distant from a leaf def printKDistantfromLeaf(self,node, k): if (node == None): return -1 lk = self.printKDistantfromLeaf(node.left, k) rk = self.printKDistantfromLeaf(node.right, k) isLeaf = lk == -1 and lk == rk if (lk == 0 or rk == 0 or (isLeaf and k == 0)): print(node.data,end=\" \") # Leaf node if (isLeaf and k > 0): return k - 1 # Parent of left leaf if (lk > 0 and lk < k): return lk - 1 # Parent of right leaf if (rk > 0 and rk < k): return rk - 1 return -2 # Driver codetree = BinaryTree() # Let us construct the tree shown# in above diagramtree.root = Node(1)tree.root.left = Node(2)tree.root.right = Node(3)tree.root.left.left = Node(4)tree.root.left.right = Node(5)tree.root.right.left = Node(6)tree.root.right.right = Node(7)tree.root.right.left.right = Node(8) print(\"Nodes at distance 2 are :\")tree.printKDistantfromLeaf(tree.root, 2) # self code is contributed by shinjanpatra", "e": 41806, "s": 40361, "text": null }, { "code": "// C# program to print all nodes at a distance k from leaf// A binary tree nodeusing System; class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Given a binary tree and a number k, print all nodes that are k distant from a leaf*/ int printKDistantfromLeaf(Node node, int k) { if (node == null) return -1; int lk = printKDistantfromLeaf(node.left, k); int rk = printKDistantfromLeaf(node.right, k); bool isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) Console.Write(\" \" + node.data); if (isLeaf && k > 0) return k - 1; // leaf node if (lk > 0 && lk < k) return lk - 1; // parent of left leaf if (rk > 0 && rk < k) return rk - 1; // parent of right leaf return -2; } // Driver program to test the above functions public static void Main(string []args) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Console.Write(\"Nodes at distance 2 are :\"); tree.printKDistantfromLeaf(tree.root, 2); }} // This code is contributed by rutvik_56", "e": 43456, "s": 41806, "text": null }, { "code": "<script> // JavaScript program to print all nodes// at a distance k from leaf // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class BinaryTree{ constructor() { this.root = null; } // Given a binary tree and a number // k, print all nodes that are k // distant from a leaf printKDistantfromLeaf(node, k) { if (node == null) return -1; var lk = this.printKDistantfromLeaf(node.left, k); var rk = this.printKDistantfromLeaf(node.right, k); var isLeaf = lk == -1 && lk == rk; if (lk == 0 || rk == 0 || (isLeaf && k == 0)) document.write(\" \" + node.data); // Leaf node if (isLeaf && k > 0) return k - 1; // Parent of left leaf if (lk > 0 && lk < k) return lk - 1; // Parent of right leaf if (rk > 0 && rk < k) return rk - 1; return -2; }} // Driver codevar tree = new BinaryTree(); // Let us construct the tree shown// in above diagramtree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);tree.root.right.left = new Node(6);tree.root.right.right = new Node(7);tree.root.right.left.right = new Node(8); document.write(\"Nodes at distance 2 are :<br>\");tree.printKDistantfromLeaf(tree.root, 2); // This code is contributed by rdtank </script>", "e": 45022, "s": 43456, "text": null }, { "code": null, "e": 45057, "s": 45025, "text": " Nodes at distance 2 are :\n 3 1" }, { "code": null, "e": 45184, "s": 45059, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 45205, "s": 45184, "text": "Another approach : " }, { "code": null, "e": 45209, "s": 45205, "text": "C++" }, { "code": "// Print all nodes that are at distance k from a leaf node#include <iostream>using namespace std; struct bstnode { int data; bstnode* right; bstnode* left;}; bstnode* newnode(int data){ bstnode* temp = new bstnode(); temp->data = data; temp->right = temp->left = NULL; return temp;} void del(bstnode* root){ if (root != NULL) { del(root->left); del(root->right); delete root; }} int printk(bstnode* root, int k){ if (root == NULL) return 0; int l = printk(root->left, k); int r = printk(root->right, k); if (l == k || r == k) cout << root->data << \" \"; return 1 + max(l, r);} int main(){ bstnode* root = NULL; root = newnode(1); root->left = newnode(2); root->right = newnode(3); root->left->left = newnode(4); root->left->right = newnode(5); root->right->left = newnode(6); root->right->right = newnode(7); root->right->left->right = newnode(8); // root->right->right->right=newnode(9); int k = 2; printk(root, k); del(root); return 0; // This approach is given by gourabn2000 }", "e": 46317, "s": 45209, "text": null }, { "code": null, "e": 46322, "s": 46317, "text": "3 1 " }, { "code": null, "e": 46473, "s": 46322, "text": "Time Complexity: O(n) as the code does a simple tree traversal. Auxiliary Space: O(h) as the function call stack is used where h=height of the tree. " }, { "code": null, "e": 46485, "s": 46473, "text": "shrikanth13" }, { "code": null, "e": 46501, "s": 46485, "text": "PranchalKatiyar" }, { "code": null, "e": 46514, "s": 46501, "text": "loginvijayan" }, { "code": null, "e": 46524, "s": 46514, "text": "rutvik_56" }, { "code": null, "e": 46536, "s": 46524, "text": "aashish1995" }, { "code": null, "e": 46549, "s": 46536, "text": "AshokJaiswal" }, { "code": null, "e": 46558, "s": 46549, "text": "mukesh07" }, { "code": null, "e": 46565, "s": 46558, "text": "rdtank" }, { "code": null, "e": 46582, "s": 46565, "text": "arorakashish0911" }, { "code": null, "e": 46594, "s": 46582, "text": "gourabn2000" }, { "code": null, "e": 46604, "s": 46594, "text": "as5853535" }, { "code": null, "e": 46617, "s": 46604, "text": "shinjanpatra" }, { "code": null, "e": 46627, "s": 46617, "text": "Microsoft" }, { "code": null, "e": 46632, "s": 46627, "text": "Tree" }, { "code": null, "e": 46642, "s": 46632, "text": "Microsoft" }, { "code": null, "e": 46647, "s": 46642, "text": "Tree" }, { "code": null, "e": 46745, "s": 46647, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46786, "s": 46745, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 46829, "s": 46786, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 46862, "s": 46829, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 46876, "s": 46862, "text": "Decision Tree" }, { "code": null, "e": 46959, "s": 46876, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 47017, "s": 46959, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 47053, "s": 47017, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 47101, "s": 47053, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
EnumSet noneOf() Method in Java - GeeksforGeeks
02 Jul, 2018 The java.util.EnumSet.noneOf(Class elementType) method in Java is used to create a null set of the type elementType. Syntax: public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) Parameters: The method accepts one parameter elementType of element type and refers to the class object of the element type for this enum set. Return Value: The method does not return any value. Exceptions: The method throws NullPointerException if the elementType is Null. Below programs illustrate the working of Java.util.EnumSet.noneOf() method:Program 1: // Java program to demonstrate noneof() methodimport java.util.*; // Creating an enum of GFG typeenum GFG { Welcome, To, The, World, of, Geeks}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an empty EnumSet // Getting all elements from GFG EnumSet<GFG> e_set = EnumSet.allOf(GFG.class); // Displaying the initial EnumSet System.out.println("The first set is: " + e_set); // Creating another empty set EnumSet<GFG> other_set = EnumSet.noneOf(GFG.class); // Displaying the new set System.out.println("The other set is: " + other_set); }} The first set is: [Welcome, To, The, World, of, Geeks] The other set is: [] Program 2: // Java program to demonstrate copyOf() methodimport java.util.*; // Creating an enum of CARS typeenum CARS { RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an empty EnumSet // Getting all elements from CARS EnumSet<CARS> e_set = EnumSet.allOf(CARS.class); // Displaying the initial EnumSet System.out.println("The first set is: " + e_set); // Creating another empty set EnumSet<CARS> other_set = EnumSet.noneOf(CARS.class); // Displaying the new set System.out.println("The other set is: " + other_set); }} The first set is: [RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW] The other set is: [] java-EnumSet Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Overriding in Java LinkedList in Java Initializing a List in Java
[ { "code": null, "e": 24152, "s": 24124, "text": "\n02 Jul, 2018" }, { "code": null, "e": 24269, "s": 24152, "text": "The java.util.EnumSet.noneOf(Class elementType) method in Java is used to create a null set of the type elementType." }, { "code": null, "e": 24277, "s": 24269, "text": "Syntax:" }, { "code": null, "e": 24351, "s": 24277, "text": "public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)" }, { "code": null, "e": 24494, "s": 24351, "text": "Parameters: The method accepts one parameter elementType of element type and refers to the class object of the element type for this enum set." }, { "code": null, "e": 24546, "s": 24494, "text": "Return Value: The method does not return any value." }, { "code": null, "e": 24625, "s": 24546, "text": "Exceptions: The method throws NullPointerException if the elementType is Null." }, { "code": null, "e": 24711, "s": 24625, "text": "Below programs illustrate the working of Java.util.EnumSet.noneOf() method:Program 1:" }, { "code": "// Java program to demonstrate noneof() methodimport java.util.*; // Creating an enum of GFG typeenum GFG { Welcome, To, The, World, of, Geeks}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an empty EnumSet // Getting all elements from GFG EnumSet<GFG> e_set = EnumSet.allOf(GFG.class); // Displaying the initial EnumSet System.out.println(\"The first set is: \" + e_set); // Creating another empty set EnumSet<GFG> other_set = EnumSet.noneOf(GFG.class); // Displaying the new set System.out.println(\"The other set is: \" + other_set); }}", "e": 25386, "s": 24711, "text": null }, { "code": null, "e": 25463, "s": 25386, "text": "The first set is: [Welcome, To, The, World, of, Geeks]\nThe other set is: []\n" }, { "code": null, "e": 25474, "s": 25463, "text": "Program 2:" }, { "code": "// Java program to demonstrate copyOf() methodimport java.util.*; // Creating an enum of CARS typeenum CARS { RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an empty EnumSet // Getting all elements from CARS EnumSet<CARS> e_set = EnumSet.allOf(CARS.class); // Displaying the initial EnumSet System.out.println(\"The first set is: \" + e_set); // Creating another empty set EnumSet<CARS> other_set = EnumSet.noneOf(CARS.class); // Displaying the new set System.out.println(\"The other set is: \" + other_set); }}", "e": 26158, "s": 25474, "text": null }, { "code": null, "e": 26240, "s": 26158, "text": "The first set is: [RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW]\nThe other set is: []\n" }, { "code": null, "e": 26253, "s": 26240, "text": "java-EnumSet" }, { "code": null, "e": 26258, "s": 26253, "text": "Java" }, { "code": null, "e": 26263, "s": 26258, "text": "Java" }, { "code": null, "e": 26361, "s": 26263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26393, "s": 26361, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26412, "s": 26393, "text": "Interfaces in Java" }, { "code": null, "e": 26430, "s": 26412, "text": "ArrayList in Java" }, { "code": null, "e": 26462, "s": 26430, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26482, "s": 26462, "text": "Stack Class in Java" }, { "code": null, "e": 26497, "s": 26482, "text": "Stream In Java" }, { "code": null, "e": 26521, "s": 26497, "text": "Singleton Class in Java" }, { "code": null, "e": 26540, "s": 26521, "text": "Overriding in Java" }, { "code": null, "e": 26559, "s": 26540, "text": "LinkedList in Java" } ]
Creating conditional columns on Pandas with Numpy select() and where() methods | by B. Chen | Towards Data Science
Pandas is an amazing library that contains extensive built-in functions for manipulating data. Although the built-in functions are capable of performing efficient data analysis, incorporating methods from other library adds value to Pandas. In this article, we are going to take a look at how to create conditional columns on Pandas with Numpy select() and where() methods Please check out my Github repo for the source code Suppose we have a dataset about a fruit store. df = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Apple', 'Banana'], 'supplier': ['T & C Bro', 'T & C Bro', 'JM Wholesales', 'JM Wholesales'], 'weight (kg)': [1000,2000,3000,4000], 'customer_rating': [4.8,3.2, 4.2, 4.3]}) We can see that the store has purchased fruits from 2 suppliers “T & C Bro” and “JM Wholesales”. Their price lists are kept separately like below: # T & C Brotc_price = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Orange', 'Pineapple'], 'price (kg)': [1.1, 2, 2.9, 3.1]})# JM Wholesalesjm_price = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Orange', 'Pineapple'], 'price (kg)': [1.2, 1.8, 4, 6]}) We would like to retrieve the price from the supplier’s price list, combine them and add the result to a new column. The expected output is: The tricky part in this calculation is that we need to retrieve the price (kg) conditionally (based on supplier and fruit) and then combine it back into the fruit store dataset. For this example, a game-changer solution is to incorporate with the Numpy where() function. A single line of code can solve the retrieve and combine. df = df.set_index('fruit')tc_price = tc_price.set_index('fruit')jm_price = jm_price.set_index('fruit') By calling set_index('fruit') to set the fruit column as index across all datasets. This is important so we can use loc[df.index] later to select a column for value mapping. The Numpy where(condition, x, y) method [1] returns elements chosen from x or y depending on the condition. The most important thing is that this method can take array-like inputs and returns an array-like output. df['price (kg)'] = np.where( df['supplier'] == 'T & C Bro', tc_price.loc[df.index]['price (kg)'], jm_price.loc[df.index]['price (kg)']) By executing the above statement, you should get the output like below: A bit confusion? Here are some details: df['supplier'] == 'T & C Bro' returns a boolean array df.index returns ['Apple', 'Banana', 'Apple', 'Banana'] (Index set by Step 1). And both tc_price.loc[df.index] and jm_price.loc[df.index] return a same length DataFrame based on label df.index. We have learnt how to create a conditional column from 2 datasets. What about more than 2 datasets, for example, 3 different suppliers in the fruit store dataset. For more than 2 datasets/choices, we can use Numpy select() method instead. Let’s see how it works with the help of an example. The first step is to combine all price lists into one dataset. After that, set the fruit column as index. df_3 = df_3.set_index('fruit')df_price = df_price.set_index('fruit') Numpy select(condlist, choicelist) method returns an array drawn from elements in choicelist, depending on condition in condlist. args = df_price.loc[df_3.index]conds = [ df_3['supplier'] == 'T & C Bro', df_3['supplier'] == 'JM Wholesales', df_3['supplier'] == 'Star Ltd.',]choices = [ args['T & C Bro'], args['JM Wholesales'], args['Star Ltd.'],]df_3['price (kg)'] = np.select(conds, choices) Basically, If the condition df_3['supplier'] == 'T & C Bro' is satisfied, it takes the ouput elements from args['T & C Bro'] . If the condition df_3['supplier'] == 'JM Wholesale' is satisfied, it takes the ouput elements from args['JM Wholesale'] . If the condition df_3['supplier'] == 'Star Ltd.' is satisfied, it takes the ouput elements from args['Star Ltd.'] . By executing the above statement, you should get the output like below: Thanks for reading. Please checkout the notebook on my Github for the source code. Stay tuned if you are interested in the practical aspect of machine learning. When to use Pandas transform() function A Practical Introduction to Pandas pivot_table() function Using Pandas method chaining to improve code readability Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More can be found from my Github [1] Numpy Documentation — where() [2] Numpy Documentation — select()
[ { "code": null, "e": 413, "s": 172, "text": "Pandas is an amazing library that contains extensive built-in functions for manipulating data. Although the built-in functions are capable of performing efficient data analysis, incorporating methods from other library adds value to Pandas." }, { "code": null, "e": 545, "s": 413, "text": "In this article, we are going to take a look at how to create conditional columns on Pandas with Numpy select() and where() methods" }, { "code": null, "e": 597, "s": 545, "text": "Please check out my Github repo for the source code" }, { "code": null, "e": 644, "s": 597, "text": "Suppose we have a dataset about a fruit store." }, { "code": null, "e": 878, "s": 644, "text": "df = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Apple', 'Banana'], 'supplier': ['T & C Bro', 'T & C Bro', 'JM Wholesales', 'JM Wholesales'], 'weight (kg)': [1000,2000,3000,4000], 'customer_rating': [4.8,3.2, 4.2, 4.3]})" }, { "code": null, "e": 1025, "s": 878, "text": "We can see that the store has purchased fruits from 2 suppliers “T & C Bro” and “JM Wholesales”. Their price lists are kept separately like below:" }, { "code": null, "e": 1288, "s": 1025, "text": "# T & C Brotc_price = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Orange', 'Pineapple'], 'price (kg)': [1.1, 2, 2.9, 3.1]})# JM Wholesalesjm_price = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Orange', 'Pineapple'], 'price (kg)': [1.2, 1.8, 4, 6]})" }, { "code": null, "e": 1429, "s": 1288, "text": "We would like to retrieve the price from the supplier’s price list, combine them and add the result to a new column. The expected output is:" }, { "code": null, "e": 1607, "s": 1429, "text": "The tricky part in this calculation is that we need to retrieve the price (kg) conditionally (based on supplier and fruit) and then combine it back into the fruit store dataset." }, { "code": null, "e": 1758, "s": 1607, "text": "For this example, a game-changer solution is to incorporate with the Numpy where() function. A single line of code can solve the retrieve and combine." }, { "code": null, "e": 1861, "s": 1758, "text": "df = df.set_index('fruit')tc_price = tc_price.set_index('fruit')jm_price = jm_price.set_index('fruit')" }, { "code": null, "e": 2035, "s": 1861, "text": "By calling set_index('fruit') to set the fruit column as index across all datasets. This is important so we can use loc[df.index] later to select a column for value mapping." }, { "code": null, "e": 2249, "s": 2035, "text": "The Numpy where(condition, x, y) method [1] returns elements chosen from x or y depending on the condition. The most important thing is that this method can take array-like inputs and returns an array-like output." }, { "code": null, "e": 2396, "s": 2249, "text": "df['price (kg)'] = np.where( df['supplier'] == 'T & C Bro', tc_price.loc[df.index]['price (kg)'], jm_price.loc[df.index]['price (kg)'])" }, { "code": null, "e": 2468, "s": 2396, "text": "By executing the above statement, you should get the output like below:" }, { "code": null, "e": 2508, "s": 2468, "text": "A bit confusion? Here are some details:" }, { "code": null, "e": 2562, "s": 2508, "text": "df['supplier'] == 'T & C Bro' returns a boolean array" }, { "code": null, "e": 2756, "s": 2562, "text": "df.index returns ['Apple', 'Banana', 'Apple', 'Banana'] (Index set by Step 1). And both tc_price.loc[df.index] and jm_price.loc[df.index] return a same length DataFrame based on label df.index." }, { "code": null, "e": 2919, "s": 2756, "text": "We have learnt how to create a conditional column from 2 datasets. What about more than 2 datasets, for example, 3 different suppliers in the fruit store dataset." }, { "code": null, "e": 3047, "s": 2919, "text": "For more than 2 datasets/choices, we can use Numpy select() method instead. Let’s see how it works with the help of an example." }, { "code": null, "e": 3110, "s": 3047, "text": "The first step is to combine all price lists into one dataset." }, { "code": null, "e": 3153, "s": 3110, "text": "After that, set the fruit column as index." }, { "code": null, "e": 3222, "s": 3153, "text": "df_3 = df_3.set_index('fruit')df_price = df_price.set_index('fruit')" }, { "code": null, "e": 3352, "s": 3222, "text": "Numpy select(condlist, choicelist) method returns an array drawn from elements in choicelist, depending on condition in condlist." }, { "code": null, "e": 3638, "s": 3352, "text": "args = df_price.loc[df_3.index]conds = [ df_3['supplier'] == 'T & C Bro', df_3['supplier'] == 'JM Wholesales', df_3['supplier'] == 'Star Ltd.',]choices = [ args['T & C Bro'], args['JM Wholesales'], args['Star Ltd.'],]df_3['price (kg)'] = np.select(conds, choices)" }, { "code": null, "e": 3649, "s": 3638, "text": "Basically," }, { "code": null, "e": 3765, "s": 3649, "text": "If the condition df_3['supplier'] == 'T & C Bro' is satisfied, it takes the ouput elements from args['T & C Bro'] ." }, { "code": null, "e": 3887, "s": 3765, "text": "If the condition df_3['supplier'] == 'JM Wholesale' is satisfied, it takes the ouput elements from args['JM Wholesale'] ." }, { "code": null, "e": 4003, "s": 3887, "text": "If the condition df_3['supplier'] == 'Star Ltd.' is satisfied, it takes the ouput elements from args['Star Ltd.'] ." }, { "code": null, "e": 4075, "s": 4003, "text": "By executing the above statement, you should get the output like below:" }, { "code": null, "e": 4095, "s": 4075, "text": "Thanks for reading." }, { "code": null, "e": 4158, "s": 4095, "text": "Please checkout the notebook on my Github for the source code." }, { "code": null, "e": 4236, "s": 4158, "text": "Stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 4276, "s": 4236, "text": "When to use Pandas transform() function" }, { "code": null, "e": 4334, "s": 4276, "text": "A Practical Introduction to Pandas pivot_table() function" }, { "code": null, "e": 4391, "s": 4334, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 4433, "s": 4391, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 4474, "s": 4433, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 4544, "s": 4474, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" }, { "code": null, "e": 4577, "s": 4544, "text": "More can be found from my Github" }, { "code": null, "e": 4611, "s": 4577, "text": "[1] Numpy Documentation — where()" } ]
Servlets - Interview Questions
Dear readers, these Servlets Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Servlets Programming. As per my experience, good interviewers hardly planned to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. Servlets perform the following major tasks: Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet. The servlet is initialized by calling the init () method. The servlet is initialized by calling the init () method. The servlet calls service() method to process a client's request. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM. Finally, servlet is garbage collected by the garbage collector of the JVM. The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method. A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method. The destroy() method is called only once at the end of the life cycle of a servlet. The init() method simply creates or loads some data that will be used throughout the life of the servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. This method should be used to get data from server. This method should be used to process data on the server. The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method: public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ } The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. Servlets handles form data parsing automatically using the following methods depending on the situation: getParameter(): You call request.getParameter() method to get the value of a form parameter. getParameter(): You call request.getParameter() method to get the value of a form parameter. getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames(): Call this method if you want a complete list of all parameters in the current request. getParameterNames(): Call this method if you want a complete list of all parameters in the current request. getParameterNames() method of HttpServletRequest returns complete list of all parameters in the current request. This method returns an Enumeration that contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name. We can use getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name. When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. HTTPServletRequest represents this HTTP Request. when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. HTTPServletResponse represents this HTTP Response. Get the object of PrintWriter using request. PrintWriter out = response.getWriter(); Now print html. out.println("Hello World"); We can use setStatus(statuscode) method of HttpServletResponse to send an authentication error. // Set error code and reason. response.sendError(407, "Need authentication!!!" ); Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization. The simplest way of redirecting a request to another page is using method sendRedirect() of response object. This method generates a 302 response along with a Location header giving the URL of the new document. This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client. Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes: To intercept requests from a client before they access a resource at back end. To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client. To manipulate responses from server before they are sent back to the client. There are various types of filters suggested by the specifications: Authentication Filters. Authentication Filters. Data compression Filters. Data compression Filters. Encryption Filters. Encryption Filters. Filters that trigger resource access events. Filters that trigger resource access events. Image Conversion Filters. Image Conversion Filters. Logging and Auditing Filters. Logging and Auditing Filters. MIME-TYPE Chain Filters. MIME-TYPE Chain Filters. Tokenizing Filters . Tokenizing Filters . XSL/T Filters That Transform XML Content. XSL/T Filters That Transform XML Content. Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor. This method is called by the web container to indicate to a filter that it is being placed into service. This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. This method is called by the web container to indicate to a filter that it is being taken out of service. Yes. Yes. The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file. Use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes. If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception: <error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page> Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. Setting cookies with servlet involves three steps: (1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , " / ? @ : ; (2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours. cookie.setMaxAge(60*60*24); (3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows: response.addCookie(cookie); To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value. To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps: Read an already exsiting cookie and store it in Cookie object. Read an already exsiting cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie. Set cookie age as zero using setMaxAge() method to delete an existing cookie. Add this cookie back into response header. Add this cookie back into response header. Session provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The session persists for a specified time period, across more than one connection or page request from the user. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below: // Create a session object if it is already not created. HttpSession session = request.getSession(); When you are done with a user's session data, you have several options: Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session: You can call public void invalidate() method to discard an entire session. Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Delete the whole session: You can call public void invalidate() method to discard an entire session. Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. setAttribute(String name, Object value) of HTTPSession object binds an object to this session, using the name specified and can be used to update an attribute in session. setMaxInactiveInterval(int interval) of HTTPSession object specifies the time, in seconds, between client requests before the servlet container will invalidate this session. The simplest way of refreshing a web page is using method setIntHeader() of response object. This means enabling a web site to provide different versions of content translated into the visitor's language or nationality. This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site. This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example "en_US" represents english locale for US. Following is the method of request object which returns Locale object. java.util.Locale request.getLocale() Following method returns a name for the locale's country that is appropriate for display to the user. String getDisplayCountry() Further, you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 31 Lectures 12.5 hours Uplatz 38 Lectures 4.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2642, "s": 2185, "text": "Dear readers, these Servlets Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Servlets Programming. As per my experience, good interviewers hardly planned to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 2850, "s": 2642, "text": "Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server." }, { "code": null, "e": 2912, "s": 2850, "text": "Servlets offer several advantages in comparison with the CGI." }, { "code": null, "e": 2949, "s": 2912, "text": "Performance is significantly better." }, { "code": null, "e": 2986, "s": 2949, "text": "Performance is significantly better." }, { "code": null, "e": 3125, "s": 2986, "text": "Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request." }, { "code": null, "e": 3264, "s": 3125, "text": "Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request." }, { "code": null, "e": 3332, "s": 3264, "text": "Servlets are platform-independent because they are written in Java." }, { "code": null, "e": 3400, "s": 3332, "text": "Servlets are platform-independent because they are written in Java." }, { "code": null, "e": 3538, "s": 3400, "text": "Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted." }, { "code": null, "e": 3676, "s": 3538, "text": "Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted." }, { "code": null, "e": 3879, "s": 3676, "text": "The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already." }, { "code": null, "e": 4082, "s": 3879, "text": "The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already." }, { "code": null, "e": 4126, "s": 4082, "text": "Servlets perform the following major tasks:" }, { "code": null, "e": 4292, "s": 4126, "text": "Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program." }, { "code": null, "e": 4458, "s": 4292, "text": "Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program." }, { "code": null, "e": 4624, "s": 4458, "text": "Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth." }, { "code": null, "e": 4790, "s": 4624, "text": "Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth." }, { "code": null, "e": 4973, "s": 4790, "text": "Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly." }, { "code": null, "e": 5156, "s": 4973, "text": "Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly." }, { "code": null, "e": 5341, "s": 5156, "text": "Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc." }, { "code": null, "e": 5526, "s": 5341, "text": "Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc." }, { "code": null, "e": 5753, "s": 5526, "text": "Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks." }, { "code": null, "e": 5980, "s": 5753, "text": "Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks." }, { "code": null, "e": 6129, "s": 5980, "text": "A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet." }, { "code": null, "e": 6187, "s": 6129, "text": "The servlet is initialized by calling the init () method." }, { "code": null, "e": 6245, "s": 6187, "text": "The servlet is initialized by calling the init () method." }, { "code": null, "e": 6311, "s": 6245, "text": "The servlet calls service() method to process a client's request." }, { "code": null, "e": 6377, "s": 6311, "text": "The servlet calls service() method to process a client's request." }, { "code": null, "e": 6436, "s": 6377, "text": "The servlet is terminated by calling the destroy() method." }, { "code": null, "e": 6495, "s": 6436, "text": "The servlet is terminated by calling the destroy() method." }, { "code": null, "e": 6570, "s": 6495, "text": "Finally, servlet is garbage collected by the garbage collector of the JVM." }, { "code": null, "e": 6645, "s": 6570, "text": "Finally, servlet is garbage collected by the garbage collector of the JVM." }, { "code": null, "e": 6875, "s": 6645, "text": "The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets." }, { "code": null, "e": 7132, "s": 6875, "text": "Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate." }, { "code": null, "e": 7280, "s": 7132, "text": "A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method." }, { "code": null, "e": 7409, "s": 7280, "text": "A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method." }, { "code": null, "e": 7494, "s": 7409, "text": "The destroy() method is called only once at the end of the life cycle of a servlet. " }, { "code": null, "e": 7600, "s": 7494, "text": "The init() method simply creates or loads some data that will be used throughout the life of the servlet." }, { "code": null, "e": 7781, "s": 7600, "text": "This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities." }, { "code": null, "e": 7833, "s": 7781, "text": "This method should be used to get data from server." }, { "code": null, "e": 7892, "s": 7833, "text": "This method should be used to process data on the server. " }, { "code": null, "e": 8136, "s": 7892, "text": "The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client." }, { "code": null, "e": 8393, "s": 8136, "text": "Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate." }, { "code": null, "e": 8431, "s": 8393, "text": "Here is the signature of this method:" }, { "code": null, "e": 8566, "s": 8431, "text": "public void service(ServletRequest request, \n ServletResponse response) \n throws ServletException, IOException{\n}" }, { "code": null, "e": 8857, "s": 8566, "text": "The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client." }, { "code": null, "e": 8962, "s": 8857, "text": "Servlets handles form data parsing automatically using the following methods depending on the situation:" }, { "code": null, "e": 9055, "s": 8962, "text": "getParameter(): You call request.getParameter() method to get the value of a form parameter." }, { "code": null, "e": 9148, "s": 9055, "text": "getParameter(): You call request.getParameter() method to get the value of a form parameter." }, { "code": null, "e": 9278, "s": 9148, "text": "getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox." }, { "code": null, "e": 9408, "s": 9278, "text": "getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox." }, { "code": null, "e": 9516, "s": 9408, "text": "getParameterNames(): Call this method if you want a complete list of all parameters in the current request." }, { "code": null, "e": 9624, "s": 9516, "text": "getParameterNames(): Call this method if you want a complete list of all parameters in the current request." }, { "code": null, "e": 9832, "s": 9624, "text": "getParameterNames() method of HttpServletRequest returns complete list of all parameters in the current request. This method returns an Enumeration that contains the parameter names in an unspecified order. " }, { "code": null, "e": 10034, "s": 9832, "text": "Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name." }, { "code": null, "e": 10243, "s": 10034, "text": "We can use getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request." }, { "code": null, "e": 10446, "s": 10243, "text": "Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name. " }, { "code": null, "e": 10682, "s": 10446, "text": " When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. HTTPServletRequest represents this HTTP Request." }, { "code": null, "e": 10899, "s": 10682, "text": "when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. HTTPServletResponse represents this HTTP Response." }, { "code": null, "e": 10945, "s": 10899, "text": " Get the object of PrintWriter using request." }, { "code": null, "e": 10985, "s": 10945, "text": "PrintWriter out = response.getWriter();" }, { "code": null, "e": 11002, "s": 10985, "text": " Now print html." }, { "code": null, "e": 11030, "s": 11002, "text": "out.println(\"Hello World\");" }, { "code": null, "e": 11126, "s": 11030, "text": "We can use setStatus(statuscode) method of HttpServletResponse to send an authentication error." }, { "code": null, "e": 11208, "s": 11126, "text": "// Set error code and reason.\nresponse.sendError(407, \"Need authentication!!!\" );" }, { "code": null, "e": 11510, "s": 11208, "text": "Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.\nThe simplest way of redirecting a request to another page is using method sendRedirect() of response object." }, { "code": null, "e": 11612, "s": 11510, "text": "This method generates a 302 response along with a Location header giving the URL of the new document." }, { "code": null, "e": 11765, "s": 11612, "text": "This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client." }, { "code": null, "e": 11866, "s": 11765, "text": "Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:" }, { "code": null, "e": 11945, "s": 11866, "text": "To intercept requests from a client before they access a resource at back end." }, { "code": null, "e": 12024, "s": 11945, "text": "To intercept requests from a client before they access a resource at back end." }, { "code": null, "e": 12101, "s": 12024, "text": "To manipulate responses from server before they are sent back to the client." }, { "code": null, "e": 12178, "s": 12101, "text": "To manipulate responses from server before they are sent back to the client." }, { "code": null, "e": 12246, "s": 12178, "text": "There are various types of filters suggested by the specifications:" }, { "code": null, "e": 12270, "s": 12246, "text": "Authentication Filters." }, { "code": null, "e": 12294, "s": 12270, "text": "Authentication Filters." }, { "code": null, "e": 12320, "s": 12294, "text": "Data compression Filters." }, { "code": null, "e": 12346, "s": 12320, "text": "Data compression Filters." }, { "code": null, "e": 12366, "s": 12346, "text": "Encryption Filters." }, { "code": null, "e": 12386, "s": 12366, "text": "Encryption Filters." }, { "code": null, "e": 12431, "s": 12386, "text": "Filters that trigger resource access events." }, { "code": null, "e": 12476, "s": 12431, "text": "Filters that trigger resource access events." }, { "code": null, "e": 12502, "s": 12476, "text": "Image Conversion Filters." }, { "code": null, "e": 12528, "s": 12502, "text": "Image Conversion Filters." }, { "code": null, "e": 12558, "s": 12528, "text": "Logging and Auditing Filters." }, { "code": null, "e": 12588, "s": 12558, "text": "Logging and Auditing Filters." }, { "code": null, "e": 12613, "s": 12588, "text": "MIME-TYPE Chain Filters." }, { "code": null, "e": 12638, "s": 12613, "text": "MIME-TYPE Chain Filters." }, { "code": null, "e": 12659, "s": 12638, "text": "Tokenizing Filters ." }, { "code": null, "e": 12680, "s": 12659, "text": "Tokenizing Filters ." }, { "code": null, "e": 12722, "s": 12680, "text": "XSL/T Filters That Transform XML Content." }, { "code": null, "e": 12764, "s": 12722, "text": "XSL/T Filters That Transform XML Content." }, { "code": null, "e": 12925, "s": 12764, "text": "Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor." }, { "code": null, "e": 13030, "s": 12925, "text": "This method is called by the web container to indicate to a filter that it is being placed into service." }, { "code": null, "e": 13195, "s": 13030, "text": "This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain." }, { "code": null, "e": 13301, "s": 13195, "text": "This method is called by the web container to indicate to a filter that it is being taken out of service." }, { "code": null, "e": 13306, "s": 13301, "text": "Yes." }, { "code": null, "e": 13552, "s": 13306, "text": "Yes. The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file." }, { "code": null, "e": 13684, "s": 13552, "text": "Use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes." }, { "code": null, "e": 13865, "s": 13684, "text": "If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception:" }, { "code": null, "e": 13987, "s": 13865, "text": "<error-page>\n <exception-type>java.lang.Throwable</exception-type >\n <location>/ErrorHandler</location>\n</error-page>" }, { "code": null, "e": 14151, "s": 13987, "text": "Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies." }, { "code": null, "e": 14202, "s": 14151, "text": "Setting cookies with servlet involves three steps:" }, { "code": null, "e": 14330, "s": 14202, "text": "(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings." }, { "code": null, "e": 14373, "s": 14330, "text": "Cookie cookie = new Cookie(\"key\",\"value\");" }, { "code": null, "e": 14505, "s": 14373, "text": "Keep in mind, neither the name nor the value should contain white space or any of the following characters:\n[ ] ( ) = , \" / ? @ : ;" }, { "code": null, "e": 14659, "s": 14505, "text": "(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours." }, { "code": null, "e": 14688, "s": 14659, "text": "cookie.setMaxAge(60*60*24); " }, { "code": null, "e": 14825, "s": 14688, "text": "(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:" }, { "code": null, "e": 14853, "s": 14825, "text": "response.addCookie(cookie);" }, { "code": null, "e": 15109, "s": 14853, "text": "To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value." }, { "code": null, "e": 15231, "s": 15109, "text": "To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:" }, { "code": null, "e": 15294, "s": 15231, "text": "Read an already exsiting cookie and store it in Cookie object." }, { "code": null, "e": 15357, "s": 15294, "text": "Read an already exsiting cookie and store it in Cookie object." }, { "code": null, "e": 15435, "s": 15357, "text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie." }, { "code": null, "e": 15513, "s": 15435, "text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie." }, { "code": null, "e": 15556, "s": 15513, "text": "Add this cookie back into response header." }, { "code": null, "e": 15599, "s": 15556, "text": "Add this cookie back into response header." }, { "code": null, "e": 15853, "s": 15599, "text": "Session provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The session persists for a specified time period, across more than one connection or page request from the user." }, { "code": null, "e": 16221, "s": 15853, "text": "You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.\nFor example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client." }, { "code": null, "e": 16329, "s": 16221, "text": "You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:" }, { "code": null, "e": 16431, "s": 16329, "text": "// Create a session object if it is already not created.\nHttpSession session = request.getSession();" }, { "code": null, "e": 16503, "s": 16431, "text": "When you are done with a user's session data, you have several options:" }, { "code": null, "e": 16649, "s": 16503, "text": "Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key." }, { "code": null, "e": 16795, "s": 16649, "text": "Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key." }, { "code": null, "e": 17037, "s": 16795, "text": "Delete the whole session: You can call public void invalidate() method to discard an entire session.\nSetting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually." }, { "code": null, "e": 17279, "s": 17037, "text": "Delete the whole session: You can call public void invalidate() method to discard an entire session.\nSetting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually." }, { "code": null, "e": 17452, "s": 17279, "text": "Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users." }, { "code": null, "e": 17625, "s": 17452, "text": "Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users." }, { "code": null, "e": 17796, "s": 17625, "text": "setAttribute(String name, Object value) of HTTPSession object binds an object to this session, using the name specified and can be used to update an attribute in session." }, { "code": null, "e": 17970, "s": 17796, "text": "setMaxInactiveInterval(int interval) of HTTPSession object specifies the time, in seconds, between client requests before the servlet container will invalidate this session." }, { "code": null, "e": 18063, "s": 17970, "text": "The simplest way of refreshing a web page is using method setIntHeader() of response object." }, { "code": null, "e": 18190, "s": 18063, "text": "This means enabling a web site to provide different versions of content translated into the visitor's language or nationality." }, { "code": null, "e": 18337, "s": 18190, "text": "This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site." }, { "code": null, "e": 18558, "s": 18337, "text": "This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example \"en_US\" represents english locale for US." }, { "code": null, "e": 18629, "s": 18558, "text": "Following is the method of request object which returns Locale object." }, { "code": null, "e": 18667, "s": 18629, "text": "java.util.Locale request.getLocale() " }, { "code": null, "e": 18769, "s": 18667, "text": "Following method returns a name for the locale's country that is appropriate for display to the user." }, { "code": null, "e": 18796, "s": 18769, "text": "String getDisplayCountry()" }, { "code": null, "e": 19084, "s": 18796, "text": "Further, you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 19414, "s": 19084, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 19449, "s": 19414, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19463, "s": 19449, "text": " Karthikeya T" }, { "code": null, "e": 19498, "s": 19463, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 19514, "s": 19498, "text": " TELCOMA Global" }, { "code": null, "e": 19547, "s": 19514, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 19563, "s": 19547, "text": " TELCOMA Global" }, { "code": null, "e": 19599, "s": 19563, "text": "\n 31 Lectures \n 12.5 hours \n" }, { "code": null, "e": 19607, "s": 19599, "text": " Uplatz" }, { "code": null, "e": 19642, "s": 19607, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19660, "s": 19642, "text": " Packt Publishing" }, { "code": null, "e": 19667, "s": 19660, "text": " Print" }, { "code": null, "e": 19678, "s": 19667, "text": " Add Notes" } ]
Spring Boot - Service Components
Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here − public interface ProductService { } The class that implements the Interface with @Service annotation is as shown − @Service public class ProductServiceImpl implements ProductService { } Observe that in this tutorial, we are using Product Service API(s) to store, retrieve, update and delete the products. We wrote the business logic in @RestController class file itself. Now, we are going to move the business logic code from controller to service component. You can create an Interface which contains add, edit, get and delete methods using the code as shown below − package com.tutorialspoint.demo.service; import java.util.Collection; import com.tutorialspoint.demo.model.Product; public interface ProductService { public abstract void createProduct(Product product); public abstract void updateProduct(String id, Product product); public abstract void deleteProduct(String id); public abstract Collection<Product> getProducts(); } The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic to store, retrieve, delete and updates the product. package com.tutorialspoint.demo.service; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.tutorialspoint.demo.model.Product; @Service public class ProductServiceImpl implements ProductService { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @Override public void createProduct(Product product) { productRepo.put(product.getId(), product); } @Override public void updateProduct(String id, Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); } @Override public void deleteProduct(String id) { productRepo.remove(id); } @Override public Collection<Product> getProducts() { return productRepo.values(); } } The code here show the Rest Controller class file, here we @Autowired the ProductService interface and called the methods. package com.tutorialspoint.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; import com.tutorialspoint.demo.service.ProductService; @RestController public class ProductServiceController { @Autowired ProductService productService; @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK); } @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productService.updateProduct(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productService.deleteProduct(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productService.createProduct(product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } } The code for POJO class – Product.java is shown here − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } A main Spring Boot application is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is shown below − <?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.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is shown below − buildscript { ext { springBootVersion = '1.5.8.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown in the image given below − Now hit the below URL’s in POSTMAN application and you can see the output as shown below − GET API URL is − http://localhost:8080/products POST API URL is − http://localhost:8080/products PUT API URL is − http://localhost:8080/products/3 DELETE API URL is − http://localhost:8080/products/3 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3285, "s": 3025, "text": "Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here −" }, { "code": null, "e": 3321, "s": 3285, "text": "public interface ProductService {\n}" }, { "code": null, "e": 3400, "s": 3321, "text": "The class that implements the Interface with @Service annotation is as shown −" }, { "code": null, "e": 3471, "s": 3400, "text": "@Service\npublic class ProductServiceImpl implements ProductService {\n}" }, { "code": null, "e": 3744, "s": 3471, "text": "Observe that in this tutorial, we are using Product Service API(s) to store, retrieve, update and delete the products. We wrote the business logic in @RestController class file itself. Now, we are going to move the business logic code from controller to service component." }, { "code": null, "e": 3853, "s": 3744, "text": "You can create an Interface which contains add, edit, get and delete methods using the code as shown below −" }, { "code": null, "e": 4234, "s": 3853, "text": "package com.tutorialspoint.demo.service;\n\nimport java.util.Collection;\nimport com.tutorialspoint.demo.model.Product;\n\npublic interface ProductService {\n public abstract void createProduct(Product product);\n public abstract void updateProduct(String id, Product product);\n public abstract void deleteProduct(String id);\n public abstract Collection<Product> getProducts();\n}" }, { "code": null, "e": 4436, "s": 4234, "text": "The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic to store, retrieve, delete and updates the product." }, { "code": null, "e": 5559, "s": 4436, "text": "package com.tutorialspoint.demo.service;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.stereotype.Service;\nimport com.tutorialspoint.demo.model.Product;\n\n@Service\npublic class ProductServiceImpl implements ProductService {\n private static Map<String, Product> productRepo = new HashMap<>();\n static {\n Product honey = new Product();\n honey.setId(\"1\");\n honey.setName(\"Honey\");\n productRepo.put(honey.getId(), honey);\n\n Product almond = new Product();\n almond.setId(\"2\");\n almond.setName(\"Almond\");\n productRepo.put(almond.getId(), almond);\n }\n @Override\n public void createProduct(Product product) {\n productRepo.put(product.getId(), product);\n }\n @Override\n public void updateProduct(String id, Product product) {\n productRepo.remove(id);\n product.setId(id);\n productRepo.put(id, product);\n }\n @Override\n public void deleteProduct(String id) {\n productRepo.remove(id);\n\n }\n @Override\n public Collection<Product> getProducts() {\n return productRepo.values();\n }\n}" }, { "code": null, "e": 5682, "s": 5559, "text": "The code here show the Rest Controller class file, here we @Autowired the ProductService interface and called the methods." }, { "code": null, "e": 7479, "s": 5682, "text": "package com.tutorialspoint.demo.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.tutorialspoint.demo.model.Product;\nimport com.tutorialspoint.demo.service.ProductService;\n\n@RestController\npublic class ProductServiceController {\n @Autowired\n ProductService productService;\n\n @RequestMapping(value = \"/products\")\n public ResponseEntity<Object> getProduct() {\n return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK);\n }\n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.PUT)\n public ResponseEntity<Object> \n updateProduct(@PathVariable(\"id\") String id, @RequestBody Product product) {\n \n productService.updateProduct(id, product);\n return new ResponseEntity<>(\"Product is updated successsfully\", HttpStatus.OK);\n }\n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.DELETE)\n public ResponseEntity<Object> delete(@PathVariable(\"id\") String id) {\n productService.deleteProduct(id);\n return new ResponseEntity<>(\"Product is deleted successsfully\", HttpStatus.OK);\n }\n @RequestMapping(value = \"/products\", method = RequestMethod.POST)\n public ResponseEntity<Object> createProduct(@RequestBody Product product) {\n productService.createProduct(product);\n return new ResponseEntity<>(\"Product is created successfully\", HttpStatus.CREATED);\n }\n}" }, { "code": null, "e": 7534, "s": 7479, "text": "The code for POJO class – Product.java is shown here −" }, { "code": null, "e": 7874, "s": 7534, "text": "package com.tutorialspoint.demo.model;\n\npublic class Product {\n private String id;\n private String name;\n\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 7922, "s": 7874, "text": "A main Spring Boot application is given below −" }, { "code": null, "e": 8240, "s": 7922, "text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}" }, { "code": null, "e": 8292, "s": 8240, "text": "The code for Maven build – pom.xml is shown below −" }, { "code": null, "e": 9836, "s": 8292, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.8.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-web</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\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\n</project>" }, { "code": null, "e": 9894, "s": 9836, "text": "The code for Gradle Build – build.gradle is shown below −" }, { "code": null, "e": 10478, "s": 9894, "text": "buildscript {\n ext {\n springBootVersion = '1.5.8.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}" }, { "code": null, "e": 10606, "s": 10478, "text": "You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −" }, { "code": null, "e": 10650, "s": 10606, "text": "For Maven, use the command as shown below −" }, { "code": null, "e": 10669, "s": 10650, "text": "mvn clean install\n" }, { "code": null, "e": 10746, "s": 10669, "text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory." }, { "code": null, "e": 10799, "s": 10746, "text": "For Gradle, you can use the command as shown below −" }, { "code": null, "e": 10819, "s": 10799, "text": "gradle clean build\n" }, { "code": null, "e": 10899, "s": 10819, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory." }, { "code": null, "e": 10951, "s": 10899, "text": "Run the JAR file by using the command given below −" }, { "code": null, "e": 10973, "s": 10951, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 11066, "s": 10973, "text": "Now, the application has started on the Tomcat port 8080 as shown in the image given below −" }, { "code": null, "e": 11157, "s": 11066, "text": "Now hit the below URL’s in POSTMAN application and you can see the output as shown below −" }, { "code": null, "e": 11205, "s": 11157, "text": "GET API URL is − http://localhost:8080/products" }, { "code": null, "e": 11254, "s": 11205, "text": "POST API URL is − http://localhost:8080/products" }, { "code": null, "e": 11304, "s": 11254, "text": "PUT API URL is − http://localhost:8080/products/3" }, { "code": null, "e": 11357, "s": 11304, "text": "DELETE API URL is − http://localhost:8080/products/3" }, { "code": null, "e": 11391, "s": 11357, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 11405, "s": 11391, "text": " Karthikeya T" }, { "code": null, "e": 11438, "s": 11405, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 11453, "s": 11438, "text": " Chaand Sheikh" }, { "code": null, "e": 11488, "s": 11453, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11500, "s": 11488, "text": " Senol Atac" }, { "code": null, "e": 11535, "s": 11500, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11547, "s": 11535, "text": " Senol Atac" }, { "code": null, "e": 11582, "s": 11547, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11594, "s": 11582, "text": " Senol Atac" }, { "code": null, "e": 11627, "s": 11594, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 11639, "s": 11627, "text": " Senol Atac" }, { "code": null, "e": 11646, "s": 11639, "text": " Print" }, { "code": null, "e": 11657, "s": 11646, "text": " Add Notes" } ]
CSS | translateX() Function - GeeksforGeeks
07 Aug, 2019 The translateX() function is an inbuilt function which is used to reposition the element along the horizontal axis. Syntax: translateX( t ) Parameters: This function accepts single parameter t which holds the length of translation corresponding to x-axis. Below examples illustrate the translateX() function in CSS: Example 1: <!DOCTYPE html><html> <head> <title> CSS translateX() function </title> <style> body { text-align: center; } h1 { color: green; } .translateX_image { transform: translateX(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateX() function</h2> <h4>Original Image</h4> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> <br> <h4>Translated image</h4> <img class="translateX_image" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title> CSS translateX() function </title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; } .geeks { transform: translateX(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> CSS translateX() function </h2> <h4>Original Element</h4> <div class="GFG"> Welcome to GeeksforGeeks </div> <h4>Translated Element</h4> <div class="GFG geeks"> Welcome to GeeksforGeeks </div></body> </html> Output: Supported Browsers: The browsers supported by translateX() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera CSS-Functions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25376, "s": 25348, "text": "\n07 Aug, 2019" }, { "code": null, "e": 25492, "s": 25376, "text": "The translateX() function is an inbuilt function which is used to reposition the element along the horizontal axis." }, { "code": null, "e": 25500, "s": 25492, "text": "Syntax:" }, { "code": null, "e": 25516, "s": 25500, "text": "translateX( t )" }, { "code": null, "e": 25632, "s": 25516, "text": "Parameters: This function accepts single parameter t which holds the length of translation corresponding to x-axis." }, { "code": null, "e": 25692, "s": 25632, "text": "Below examples illustrate the translateX() function in CSS:" }, { "code": null, "e": 25703, "s": 25692, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS translateX() function </title> <style> body { text-align: center; } h1 { color: green; } .translateX_image { transform: translateX(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translateX() function</h2> <h4>Original Image</h4> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> <br> <h4>Translated image</h4> <img class=\"translateX_image\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"></body> </html>", "e": 26466, "s": 25703, "text": null }, { "code": null, "e": 26474, "s": 26466, "text": "Output:" }, { "code": null, "e": 26485, "s": 26474, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS translateX() function </title> <style> body { text-align: center; } h1 { color: green; } .GFG { font-size: 35px; font-weight: bold; color: green; } .geeks { transform: translateX(100px); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> CSS translateX() function </h2> <h4>Original Element</h4> <div class=\"GFG\"> Welcome to GeeksforGeeks </div> <h4>Translated Element</h4> <div class=\"GFG geeks\"> Welcome to GeeksforGeeks </div></body> </html>", "e": 27183, "s": 26485, "text": null }, { "code": null, "e": 27191, "s": 27183, "text": "Output:" }, { "code": null, "e": 27277, "s": 27191, "text": "Supported Browsers: The browsers supported by translateX() function are listed below:" }, { "code": null, "e": 27291, "s": 27277, "text": "Google Chrome" }, { "code": null, "e": 27309, "s": 27291, "text": "Internet Explorer" }, { "code": null, "e": 27317, "s": 27309, "text": "Firefox" }, { "code": null, "e": 27324, "s": 27317, "text": "Safari" }, { "code": null, "e": 27330, "s": 27324, "text": "Opera" }, { "code": null, "e": 27344, "s": 27330, "text": "CSS-Functions" }, { "code": null, "e": 27348, "s": 27344, "text": "CSS" }, { "code": null, "e": 27365, "s": 27348, "text": "Web Technologies" }, { "code": null, "e": 27463, "s": 27365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27500, "s": 27463, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27529, "s": 27500, "text": "Form validation using jQuery" }, { "code": null, "e": 27568, "s": 27529, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27610, "s": 27568, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27657, "s": 27610, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 27699, "s": 27657, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27732, "s": 27699, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27775, "s": 27732, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27820, "s": 27775, "text": "Convert a string to an integer in JavaScript" } ]
Image Classification with Tensorflow 2.0 | by Rich Folsom | Towards Data Science
In this article, we will address one of the most common AI problems. Here is the scenario: you’re surfing the web at a bar enjoying a beer and some chicken wings when you start to wonder “could I write an image classifier using Tensorflow 2.0 and Transfer Learning?” This article will show an end to end process for accomplishing this. Note, I will not be going into how the model works, that would be a whole other article. This article will show you how to get up and running with Tensorflow 2.0. Once we have that we can go back and play with the params that might make the code more efficient. The only prerequisites are: A computer (obviously). I ran mine on a small laptop with no GPU’s.A cell phone with a camera. We’re going to be generating our own images.(Optional) A cloud image storage. I used Amazon photos.Docker, which we will use to host our Tensorflow 2.0 environment. If you don’t have it, installation instructions can be found here A computer (obviously). I ran mine on a small laptop with no GPU’s. A cell phone with a camera. We’re going to be generating our own images. (Optional) A cloud image storage. I used Amazon photos. Docker, which we will use to host our Tensorflow 2.0 environment. If you don’t have it, installation instructions can be found here The steps we will follow are: Install Tensorflow 2.0 Docker image.Acquire a set of images to train/validate/test our model.Organize our images into a directory structure suitable for our model.Download a pre-trained deep learning model.Customize our model for our specific use case (beer or wing).Train our customized model.Visualize model predictions. Install Tensorflow 2.0 Docker image. Acquire a set of images to train/validate/test our model. Organize our images into a directory structure suitable for our model. Download a pre-trained deep learning model. Customize our model for our specific use case (beer or wing). Train our customized model. Visualize model predictions. I followed the instructions on this page. Here are the specific commands I used. Note that for this tutorial the image must contain Jupyter. docker pull tensorflow/tensorflow:2.0.0a0-py3-jupyter First off, cd to the directory where you will store your source code. From there, we will start our image I created a simple shell script (note that I’m running on Linux, if you’re on a Mac or Windows you probably don’t need the sudo command: sudo docker run -it -p 8888:8888 -v $PWD:/tf/data -w /tf/data tensorflow/tensorflow:2.0.0a0-py3-jupyter The most important things to know here are: -p is a port mapping, our Jupyter notebook runs on port 8888 in Docker so we will map the port 8888 on our machine to match. You should only change this if port 8888 is already in use on your machine. -v is how to mount a volume in docker. In this case, we’re mounting our current directory ($PWD) as /tp/data. The Jupyter notebook in this Docker image runs in the /tp directory, so when you open jupyter you should see this: Where the data directory maps to your current directory on your machine. After you run the above command, you’ll see something like this in your command prompt. The important line here is the one after “The Jupyter Notebook is running at”. you’ll want to copy that line starting with the “:8888”. Then go to your browser and type http://localhost and paste in the line you copied. In this case: http://localhost:8888/?token=cd37ab44fab55bce5e44ac6f4bb187a4b34b713c5fbeac9e At this point, you have Tensorflow 2.0 up and running in a Docker container with access to your local filesystem. This step is very easy. I used my phone and took about 30 pictures of a beer glass from different angles, and 30 pictures of a chicken wing from different angles. I am a big Amazon Prime user, so I have my phone set up to back up my images to Amazon Photos. You can use whatever cloud environment you prefer (ICloud, Google photos, etc...) Or even email yourself the photos. The point here is to copy the photos to your PC. The first step is to label our images. There are several ways to do this, but in the end, you’ll want to copy all of your “beer” pictures into a directory called “beer” and your “wing” pictures into a directory called “wings”. From there you are going to want to create a directory structure that looks like this: Here are the commands I used in Linux: mkdir trainmkdir testmkdir valmkdir train/beermkdir train/wingsmkdir test/beermkdir test/wingsmkdir val/beermkdir val/wings At this point, you’ll want to move subsets of your data to the val and test directories. After some google searches, I found this command: shuf -n 6 -e * | xargs -i mv {} target-directory I implemented this using the following commands: cd beershuf -n 6 -e * | xargs -i mv {} ../test/beershuf -n 6 -e * | xargs -i mv {} ../val/beermv * ../train/beercd ..cd wingsshuf -n 6 -e * | xargs -i mv {} ../test/wingsshuf -n 6 -e * | xargs -i mv {} ../val/wingsmv * ../train/wings This code moves 6 images each to our val and test folders and the rest to our train folders. After these steps, your directory structure should look something like this: At this point, go back to your Jupyter notebook in your browser and create a new Notebook. First, we need to import the Python libraries we will be using: import numpy as npimport tensorflow.kerasfrom tensorflow.keras.models import Sequential, Modelfrom tensorflow.keras.layers import Dropout, Inputfrom tensorflow.keras.layers import Dense, Flattenfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.metrics import categorical_crossentropyfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorimport itertoolsimport matplotlib.pyplot as plt%matplotlib inline Important troubleshooting step: You may get errors with missing libraries. Depending on the version of your Docker image, you may have to run this step: !pip install --upgrade pip!pip install pillow!pip install scipy!pip install pandas After you run it, you’ll need to click on the restart kernel button and rerun the import statements. Now that we have our Python imports complete, we need to generate ImageGenerator objects for each of our image folders. ImageGenerators take an input image and slightly modify it to provide uniformity and shape to train a Neural Network. Note our pictures will be 224x224. train_path = '/tf/data/beer_wings/train'valid_path = '/tf/data/beer_wings/val'test_path = '/tf/data/beer_wings/test'train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32)valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32)test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32) Here’s a helpful function to see what our ImageGenerator is doing I found this from a very helpful Youtube series: # plots images with labels within jupyter notebookdef plots(ims, figsize=(24,12), rows=4, interp=False, titles=None): if type(ims[0]) is np.ndarray: ims = np.array(ims).astype(np.uint8) if (ims.shape[-1] != 3): ims = ims.transpose((0,2,3,1)) f = plt.figure(figsize=figsize) cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows + 1 for i in range(len(ims)): sp = f.add_subplot(rows, cols, i+1) sp.axis('Off') if titles is not None: sp.set_title(titles[i], fontsize=32) plt.imshow(ims[i], interpolation=None if interp else 'none')imgs, labels = next(train_batches)plots(imgs, titles=labels) And the output: Note [0,1] = wings, [1,0] = beer. Finally, we are ready to download our pretrained model. In this case, we will be using the VGG16 model. Tensorflow 2.0 has numerous models built in. They are defined here. This is the code to import the pretrained VGG16 model: vgg16_model = tensorflow.keras.applications.vgg16.VGG16(weights='imagenet', include_top=False, input_tensor=Input(shape=(224,224,3))) Simple as that! Well, sorta, the important thing is that we set include_top = False, since we’re going to create our own final layers, also note that our Input shape is (224,224,3). The (224,224) matches the ImageGenerators above. The extra 3 is the color channels (red, blue, green). Now that we have downloaded a pretrained model which can generally predict image classifications, let’s customize it for our needs. Theoretically speaking, the first few layers of models like these simplify parts of the image and identify shapes within them. Those early labels are pretty generic(lines, cirles, squares, etc...), so we don’t want to retrain them. We want to only train the last few layers of our network along with the new layers we add. First, let’s disable training on all but the last 4 layers of the pretrained model. for layer in vgg16_model.layers[:-4]: layer.trainable = False Now, let’s add our own final layers to the network: # Create the modelmodel = Sequential() # Add the vgg convolutional base modelmodel.add(vgg16_model) # Add new layersmodel.add(Flatten())model.add(Dense(1024, activation='relu'))model.add(Dropout(0.5))model.add(Dense(2, activation='softmax')) # Show a summary of the model. Check the number of trainable parametersmodel.summary() There you have it, our own customized model based on VGG16! Now that we have our model defined, let’s compile it and train it. model.compile(loss='categorical_crossentropy', optimizer=tensorflow.keras.optimizers.RMSprop(lr=1e-4), metrics=['acc'])history = model.fit_generator( train_batches, steps_per_epoch=train_batches.samples/train_batches.batch_size , epochs=5, validation_data=valid_batches, validation_steps=valid_batches.samples/valid_batches.batch_size, verbose=1) Now, let’s feed our trained model a set of images that it has never seen. The most important part of the code is these 2 lines: test_imgs, test_labels = next(test_batches)predictions = model.predict(test_imgs) The first one generates a new batch of previously unseen images. Let’s see what our model predicted for these images: import pandas as pddef to_label(value): if value==0: return 'beer' else: return 'wings'test_imgs, test_labels = next(test_batches)predictions = model.predict(test_imgs)df = pd.DataFrame()df['actual'] = test_labels[:,1]df['predicted'] = np.round(predictions[:,1])df['predicted_labels']=df['predicted'].map(lambda x: to_label(x))plots(test_imgs, titles=df['predicted_labels']) Obviously, this is a nonsensical example of implementing image classification, but it did provide some valuable information, which can be applied to future projects. Namely, data acquisition, transfer learning and model evaluation. Note that the code can be easily modified to allow for multiple classifications(our example only had 2).
[ { "code": null, "e": 770, "s": 172, "text": "In this article, we will address one of the most common AI problems. Here is the scenario: you’re surfing the web at a bar enjoying a beer and some chicken wings when you start to wonder “could I write an image classifier using Tensorflow 2.0 and Transfer Learning?” This article will show an end to end process for accomplishing this. Note, I will not be going into how the model works, that would be a whole other article. This article will show you how to get up and running with Tensorflow 2.0. Once we have that we can go back and play with the params that might make the code more efficient." }, { "code": null, "e": 798, "s": 770, "text": "The only prerequisites are:" }, { "code": null, "e": 1124, "s": 798, "text": "A computer (obviously). I ran mine on a small laptop with no GPU’s.A cell phone with a camera. We’re going to be generating our own images.(Optional) A cloud image storage. I used Amazon photos.Docker, which we will use to host our Tensorflow 2.0 environment. If you don’t have it, installation instructions can be found here" }, { "code": null, "e": 1192, "s": 1124, "text": "A computer (obviously). I ran mine on a small laptop with no GPU’s." }, { "code": null, "e": 1265, "s": 1192, "text": "A cell phone with a camera. We’re going to be generating our own images." }, { "code": null, "e": 1321, "s": 1265, "text": "(Optional) A cloud image storage. I used Amazon photos." }, { "code": null, "e": 1453, "s": 1321, "text": "Docker, which we will use to host our Tensorflow 2.0 environment. If you don’t have it, installation instructions can be found here" }, { "code": null, "e": 1483, "s": 1453, "text": "The steps we will follow are:" }, { "code": null, "e": 1806, "s": 1483, "text": "Install Tensorflow 2.0 Docker image.Acquire a set of images to train/validate/test our model.Organize our images into a directory structure suitable for our model.Download a pre-trained deep learning model.Customize our model for our specific use case (beer or wing).Train our customized model.Visualize model predictions." }, { "code": null, "e": 1843, "s": 1806, "text": "Install Tensorflow 2.0 Docker image." }, { "code": null, "e": 1901, "s": 1843, "text": "Acquire a set of images to train/validate/test our model." }, { "code": null, "e": 1972, "s": 1901, "text": "Organize our images into a directory structure suitable for our model." }, { "code": null, "e": 2016, "s": 1972, "text": "Download a pre-trained deep learning model." }, { "code": null, "e": 2078, "s": 2016, "text": "Customize our model for our specific use case (beer or wing)." }, { "code": null, "e": 2106, "s": 2078, "text": "Train our customized model." }, { "code": null, "e": 2135, "s": 2106, "text": "Visualize model predictions." }, { "code": null, "e": 2276, "s": 2135, "text": "I followed the instructions on this page. Here are the specific commands I used. Note that for this tutorial the image must contain Jupyter." }, { "code": null, "e": 2330, "s": 2276, "text": "docker pull tensorflow/tensorflow:2.0.0a0-py3-jupyter" }, { "code": null, "e": 2573, "s": 2330, "text": "First off, cd to the directory where you will store your source code. From there, we will start our image I created a simple shell script (note that I’m running on Linux, if you’re on a Mac or Windows you probably don’t need the sudo command:" }, { "code": null, "e": 2677, "s": 2573, "text": "sudo docker run -it -p 8888:8888 -v $PWD:/tf/data -w /tf/data tensorflow/tensorflow:2.0.0a0-py3-jupyter" }, { "code": null, "e": 2721, "s": 2677, "text": "The most important things to know here are:" }, { "code": null, "e": 2922, "s": 2721, "text": "-p is a port mapping, our Jupyter notebook runs on port 8888 in Docker so we will map the port 8888 on our machine to match. You should only change this if port 8888 is already in use on your machine." }, { "code": null, "e": 3147, "s": 2922, "text": "-v is how to mount a volume in docker. In this case, we’re mounting our current directory ($PWD) as /tp/data. The Jupyter notebook in this Docker image runs in the /tp directory, so when you open jupyter you should see this:" }, { "code": null, "e": 3220, "s": 3147, "text": "Where the data directory maps to your current directory on your machine." }, { "code": null, "e": 3308, "s": 3220, "text": "After you run the above command, you’ll see something like this in your command prompt." }, { "code": null, "e": 3542, "s": 3308, "text": "The important line here is the one after “The Jupyter Notebook is running at”. you’ll want to copy that line starting with the “:8888”. Then go to your browser and type http://localhost and paste in the line you copied. In this case:" }, { "code": null, "e": 3620, "s": 3542, "text": "http://localhost:8888/?token=cd37ab44fab55bce5e44ac6f4bb187a4b34b713c5fbeac9e" }, { "code": null, "e": 3734, "s": 3620, "text": "At this point, you have Tensorflow 2.0 up and running in a Docker container with access to your local filesystem." }, { "code": null, "e": 4158, "s": 3734, "text": "This step is very easy. I used my phone and took about 30 pictures of a beer glass from different angles, and 30 pictures of a chicken wing from different angles. I am a big Amazon Prime user, so I have my phone set up to back up my images to Amazon Photos. You can use whatever cloud environment you prefer (ICloud, Google photos, etc...) Or even email yourself the photos. The point here is to copy the photos to your PC." }, { "code": null, "e": 4472, "s": 4158, "text": "The first step is to label our images. There are several ways to do this, but in the end, you’ll want to copy all of your “beer” pictures into a directory called “beer” and your “wing” pictures into a directory called “wings”. From there you are going to want to create a directory structure that looks like this:" }, { "code": null, "e": 4511, "s": 4472, "text": "Here are the commands I used in Linux:" }, { "code": null, "e": 4635, "s": 4511, "text": "mkdir trainmkdir testmkdir valmkdir train/beermkdir train/wingsmkdir test/beermkdir test/wingsmkdir val/beermkdir val/wings" }, { "code": null, "e": 4774, "s": 4635, "text": "At this point, you’ll want to move subsets of your data to the val and test directories. After some google searches, I found this command:" }, { "code": null, "e": 4823, "s": 4774, "text": "shuf -n 6 -e * | xargs -i mv {} target-directory" }, { "code": null, "e": 4872, "s": 4823, "text": "I implemented this using the following commands:" }, { "code": null, "e": 5106, "s": 4872, "text": "cd beershuf -n 6 -e * | xargs -i mv {} ../test/beershuf -n 6 -e * | xargs -i mv {} ../val/beermv * ../train/beercd ..cd wingsshuf -n 6 -e * | xargs -i mv {} ../test/wingsshuf -n 6 -e * | xargs -i mv {} ../val/wingsmv * ../train/wings" }, { "code": null, "e": 5276, "s": 5106, "text": "This code moves 6 images each to our val and test folders and the rest to our train folders. After these steps, your directory structure should look something like this:" }, { "code": null, "e": 5431, "s": 5276, "text": "At this point, go back to your Jupyter notebook in your browser and create a new Notebook. First, we need to import the Python libraries we will be using:" }, { "code": null, "e": 5864, "s": 5431, "text": "import numpy as npimport tensorflow.kerasfrom tensorflow.keras.models import Sequential, Modelfrom tensorflow.keras.layers import Dropout, Inputfrom tensorflow.keras.layers import Dense, Flattenfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.metrics import categorical_crossentropyfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorimport itertoolsimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 6017, "s": 5864, "text": "Important troubleshooting step: You may get errors with missing libraries. Depending on the version of your Docker image, you may have to run this step:" }, { "code": null, "e": 6100, "s": 6017, "text": "!pip install --upgrade pip!pip install pillow!pip install scipy!pip install pandas" }, { "code": null, "e": 6201, "s": 6100, "text": "After you run it, you’ll need to click on the restart kernel button and rerun the import statements." }, { "code": null, "e": 6474, "s": 6201, "text": "Now that we have our Python imports complete, we need to generate ImageGenerator objects for each of our image folders. ImageGenerators take an input image and slightly modify it to provide uniformity and shape to train a Neural Network. Note our pictures will be 224x224." }, { "code": null, "e": 6988, "s": 6474, "text": "train_path = '/tf/data/beer_wings/train'valid_path = '/tf/data/beer_wings/val'test_path = '/tf/data/beer_wings/test'train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32)valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32)test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(224,224), classes=['beer', 'wings'], batch_size=32)" }, { "code": null, "e": 7103, "s": 6988, "text": "Here’s a helpful function to see what our ImageGenerator is doing I found this from a very helpful Youtube series:" }, { "code": null, "e": 7778, "s": 7103, "text": "# plots images with labels within jupyter notebookdef plots(ims, figsize=(24,12), rows=4, interp=False, titles=None): if type(ims[0]) is np.ndarray: ims = np.array(ims).astype(np.uint8) if (ims.shape[-1] != 3): ims = ims.transpose((0,2,3,1)) f = plt.figure(figsize=figsize) cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows + 1 for i in range(len(ims)): sp = f.add_subplot(rows, cols, i+1) sp.axis('Off') if titles is not None: sp.set_title(titles[i], fontsize=32) plt.imshow(ims[i], interpolation=None if interp else 'none')imgs, labels = next(train_batches)plots(imgs, titles=labels)" }, { "code": null, "e": 7794, "s": 7778, "text": "And the output:" }, { "code": null, "e": 7828, "s": 7794, "text": "Note [0,1] = wings, [1,0] = beer." }, { "code": null, "e": 8000, "s": 7828, "text": "Finally, we are ready to download our pretrained model. In this case, we will be using the VGG16 model. Tensorflow 2.0 has numerous models built in. They are defined here." }, { "code": null, "e": 8055, "s": 8000, "text": "This is the code to import the pretrained VGG16 model:" }, { "code": null, "e": 8189, "s": 8055, "text": "vgg16_model = tensorflow.keras.applications.vgg16.VGG16(weights='imagenet', include_top=False, input_tensor=Input(shape=(224,224,3)))" }, { "code": null, "e": 8474, "s": 8189, "text": "Simple as that! Well, sorta, the important thing is that we set include_top = False, since we’re going to create our own final layers, also note that our Input shape is (224,224,3). The (224,224) matches the ImageGenerators above. The extra 3 is the color channels (red, blue, green)." }, { "code": null, "e": 8929, "s": 8474, "text": "Now that we have downloaded a pretrained model which can generally predict image classifications, let’s customize it for our needs. Theoretically speaking, the first few layers of models like these simplify parts of the image and identify shapes within them. Those early labels are pretty generic(lines, cirles, squares, etc...), so we don’t want to retrain them. We want to only train the last few layers of our network along with the new layers we add." }, { "code": null, "e": 9013, "s": 8929, "text": "First, let’s disable training on all but the last 4 layers of the pretrained model." }, { "code": null, "e": 9078, "s": 9013, "text": "for layer in vgg16_model.layers[:-4]: layer.trainable = False" }, { "code": null, "e": 9130, "s": 9078, "text": "Now, let’s add our own final layers to the network:" }, { "code": null, "e": 9459, "s": 9130, "text": "# Create the modelmodel = Sequential() # Add the vgg convolutional base modelmodel.add(vgg16_model) # Add new layersmodel.add(Flatten())model.add(Dense(1024, activation='relu'))model.add(Dropout(0.5))model.add(Dense(2, activation='softmax')) # Show a summary of the model. Check the number of trainable parametersmodel.summary()" }, { "code": null, "e": 9519, "s": 9459, "text": "There you have it, our own customized model based on VGG16!" }, { "code": null, "e": 9586, "s": 9519, "text": "Now that we have our model defined, let’s compile it and train it." }, { "code": null, "e": 9989, "s": 9586, "text": "model.compile(loss='categorical_crossentropy', optimizer=tensorflow.keras.optimizers.RMSprop(lr=1e-4), metrics=['acc'])history = model.fit_generator( train_batches, steps_per_epoch=train_batches.samples/train_batches.batch_size , epochs=5, validation_data=valid_batches, validation_steps=valid_batches.samples/valid_batches.batch_size, verbose=1)" }, { "code": null, "e": 10117, "s": 9989, "text": "Now, let’s feed our trained model a set of images that it has never seen. The most important part of the code is these 2 lines:" }, { "code": null, "e": 10199, "s": 10117, "text": "test_imgs, test_labels = next(test_batches)predictions = model.predict(test_imgs)" }, { "code": null, "e": 10317, "s": 10199, "text": "The first one generates a new batch of previously unseen images. Let’s see what our model predicted for these images:" }, { "code": null, "e": 10712, "s": 10317, "text": "import pandas as pddef to_label(value): if value==0: return 'beer' else: return 'wings'test_imgs, test_labels = next(test_batches)predictions = model.predict(test_imgs)df = pd.DataFrame()df['actual'] = test_labels[:,1]df['predicted'] = np.round(predictions[:,1])df['predicted_labels']=df['predicted'].map(lambda x: to_label(x))plots(test_imgs, titles=df['predicted_labels'])" } ]
Scrapy - Create a Project
To scrap the data from web pages, first you need to create the Scrapy project where you will be storing the code. To create a new directory, run the following command − scrapy startproject first_scrapy The above code will create a directory with name first_scrapy and it will contain the following structure − first_scrapy/ scrapy.cfg # deploy configuration file first_scrapy/ # project's Python module, you'll import your code from here __init__.py items.py # project items file pipelines.py # project pipelines file settings.py # project settings file spiders/ # a directory where you'll later put your spiders __init__.py 27 Lectures 3.5 hours Attreya Bhatt Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2237, "text": "To scrap the data from web pages, first you need to create the Scrapy project where you will be storing the code. To create a new directory, run the following command −" }, { "code": null, "e": 2440, "s": 2406, "text": "scrapy startproject first_scrapy\n" }, { "code": null, "e": 2548, "s": 2440, "text": "The above code will create a directory with name first_scrapy and it will contain the following structure −" }, { "code": null, "e": 2928, "s": 2548, "text": "first_scrapy/\nscrapy.cfg # deploy configuration file\nfirst_scrapy/ # project's Python module, you'll import your code from here\n__init__.py\nitems.py # project items file\npipelines.py # project pipelines file\nsettings.py # project settings file\nspiders/ # a directory where you'll later put your spiders\n__init__.py\n" }, { "code": null, "e": 2963, "s": 2928, "text": "\n 27 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2978, "s": 2963, "text": " Attreya Bhatt" }, { "code": null, "e": 2985, "s": 2978, "text": " Print" }, { "code": null, "e": 2996, "s": 2985, "text": " Add Notes" } ]
Java Program to find Product of unique prime factors of a number
To find product of unique prime factors of a number, the Java code is as follows − Live Demo public class Demo { public static long prime_factors(int num){ long my_prod = 1; for (int i = 2; i <= num; i++){ if (num % i == 0){ boolean is_prime = true; for (int j = 2; j <= i / 2; j++){ if (i % j == 0){ is_prime = false; break; } } if (is_prime){ my_prod = my_prod * i; } } } return my_prod; } public static void main(String[] args){ int num = 68; System.out.println("The product of unique prime factors is "); System.out.print(prime_factors(num)); } } The product of unique prime factors is 34 A class named Demo contains a static function named ‘prime_factors’ that finds the prime factors of a number, find the unique numbers, and stores the product of these prime factors in a variable. In the main function, the value for the number is defined, and the function is called by passing the number as the parameter. Relevant message is displayed on the console.
[ { "code": null, "e": 1145, "s": 1062, "text": "To find product of unique prime factors of a number, the Java code is as follows −" }, { "code": null, "e": 1156, "s": 1145, "text": " Live Demo" }, { "code": null, "e": 1827, "s": 1156, "text": "public class Demo {\n public static long prime_factors(int num){\n long my_prod = 1;\n for (int i = 2; i <= num; i++){\n if (num % i == 0){\n boolean is_prime = true;\n for (int j = 2; j <= i / 2; j++){\n if (i % j == 0){\n is_prime = false;\n break;\n }\n }\n if (is_prime){\n my_prod = my_prod * i;\n }\n }\n }\n return my_prod;\n }\n public static void main(String[] args){\n int num = 68;\n System.out.println(\"The product of unique prime factors is \");\n System.out.print(prime_factors(num));\n }\n}" }, { "code": null, "e": 1869, "s": 1827, "text": "The product of unique prime factors is\n34" }, { "code": null, "e": 2237, "s": 1869, "text": "A class named Demo contains a static function named ‘prime_factors’ that finds the prime factors of a number, find the unique numbers, and stores the product of these prime factors in a variable. In the main function, the value for the number is defined, and the function is called by passing the number as the parameter. Relevant message is displayed on the console." } ]
How can I put two buttons next to each other in Tkinter?
Tkinter generally provides three general ways to define the geometry of the widgets. They are − Place, Pack, and Grid Management. If we use the Pack geometry manager, then place the two buttons in the frame using side property. It places the buttons horizontally stacked in the window in (Left, Right, Top and Bottom) direction. The side property maintains the same width and internal padding between all the adjacent widget in the application. #Import the required Libraries from tkinter import * from tkinter import ttk import random #Create an instance of Tkinter frame win = Tk() #Set the geometry of Tkinter frame win.geometry("750x250") def clear(): entry.delete(0,END) def display_num(): for i in range(1): entry.insert(0, random.randint(5,20)) #Define an Entry widget entry= Entry(win, width= 40) entry.pack() #Create Buttons with proper position button1= ttk.Button(win, text= "Print", command=display_num) button1.pack(side= TOP) button2= ttk.Button(win, text= "Clear", command= clear) button2.pack(side=TOP) win.mainloop() Running the above code will display a window that contains two Buttons horizontally stacked adjacent to each other. Now, click each button to see the resultant output.
[ { "code": null, "e": 1507, "s": 1062, "text": "Tkinter generally provides three general ways to define the geometry of the widgets. They are − Place, Pack, and Grid Management. If we use the Pack geometry manager, then place the two buttons in the frame using side property. It places the buttons horizontally stacked in the window in (Left, Right, Top and Bottom) direction. The side property maintains the same width and internal padding between all the adjacent widget in the application." }, { "code": null, "e": 2112, "s": 1507, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\nimport random\n\n#Create an instance of Tkinter frame\nwin = Tk()\n#Set the geometry of Tkinter frame\nwin.geometry(\"750x250\")\n\ndef clear():\n entry.delete(0,END)\ndef display_num():\n for i in range(1):\n entry.insert(0, random.randint(5,20))\n\n#Define an Entry widget\nentry= Entry(win, width= 40)\nentry.pack()\n#Create Buttons with proper position\nbutton1= ttk.Button(win, text= \"Print\", command=display_num)\nbutton1.pack(side= TOP)\nbutton2= ttk.Button(win, text= \"Clear\", command= clear)\nbutton2.pack(side=TOP)\n\nwin.mainloop()" }, { "code": null, "e": 2228, "s": 2112, "text": "Running the above code will display a window that contains two Buttons horizontally stacked adjacent to each other." }, { "code": null, "e": 2280, "s": 2228, "text": "Now, click each button to see the resultant output." } ]
Improving the Performance of Machine Learning Model using Bagging | by Satyam Kumar | Towards Data Science
The performance of a machine learning model tells us how the model performs for unseen data-points. There are various strategies and hacks to improve the performance of an ML model, some of them are: Fine tuning hyperparameter of the ML model Using ensemble learning. Ensemble Learning is a technique to combine multiple ML models to form a single model. The multiple ML models also referred to as base models or weak learners can be of different algorithms or same algorithms with a change in hyperparameters. Like for classification tasks, multiple ML models can be Logistic Regression, Naive Bayes, Decision Tree, SVM, etc. For regression tasks, multiple ML models can be Linear Regression, Lasso Regression, Decision Tree Regression, etc. Ensemble Learning combines the advantages of base models to form a single robust model with improved performance. Various types of ensemble learning techniques are: Bagging (Bootstrap Aggregation)BoostingVotingCascadingStacking Bagging (Bootstrap Aggregation) Boosting Voting Cascading Stacking And many more. This article will cover the working and implementation of the Bagging Ensemble technique. Bagging ensemble technique also known as Bootstrap Aggregation uses randomization to improve performance. In bagging, we use base models that are trained on part of the dataset. In bagging, we use weak learners (or base models) models as building blocks for designing complex models by combining several of them. Most of the time, these base models do not perform well because they either overfit or underfit. Overfitting or underfitting of a model is decided by bias-variance tradeoff. What is Bias-Variance Tradeoff ? [1] The overall error of a model is dependent on the bias and variance of the model following the below equation: For a good robust model, the error of the model is as minimum as possible. To minimize the error the bias and variance need to be minimum and irreducible error remains constant. The below plot of error vs model flexibility (degree of freedom) describes the change of bias and variance along with test and training error: Analysis from the above image plot: When the model is in the initial phase of training, training, and test error are very high. When the model is enough trained, the training error is very low and the test error is high. The phase where training and test error is high is Underfitting. The phase where training error is low and the test error is high is Overfitting. The phase where there is a balance between training and testing error is Best fitting. An Underfit model has low variance and high bias. An Overfit model has high variance and low bias. Bagging Ensemble technique can be used for base models that have low bias and high variance. Bagging ensemble uses randomization of the dataset (will be discussed later in this article) to reduce the variance of base models keeping the bias low. It is now clear that bagging reduces the variance of base models keeping the bias low. The variance of base models is reduced by combining strategies of bootstrap sampling and aggregation. The entire working of Bagging is divided into 3 phases: Bootstrap SamplingBase ModelingAggregation Bootstrap Sampling Base Modeling Aggregation Below diagram describes all three steps for a sample dataset D having n rows: A bootstrap sample is a smaller sample that is a subset of the initial dataset. The bootstrap sample is created from the initial dataset by sampling with replacement. Suppose for a dataset having n rows and f features, we do a bootstrap sampling that refers to sampling with replacement into k different smaller datasets each of size m with the same f features. Each smaller dataset D_i formed sees a subset of the dataset. In the figure below initial dataset D of shape (n, f) is sampled to k dataset each of shape (m, f), where m<n. The below image describes how to bootstrap the sample. The dataset D having 10 rows is sampled with replacement into k smaller dataset each having 5 rows. Here n=10 and m=5 from the above diagram. It is observed that each of the datasets formed by bootstrapping sees only a part of the original dataset and all the datasets are independent of each other. This is the 1st step of the bagging ensemble technique in which k smaller datasets are created by bootstrapping independent of each other. Modeling is the 2nd step of bagging. After k smaller datasets are created by bootstrapping each of the k datasets is trained using ML algorithms. The algorithms used for training k dataset can be the same with or without a change in hyperparameters or different algorithms can be used. For example, Decision Tree algorithms can be used as base models with a change in hyperparameters such as ‘depth’. A combination of different algorithms such as SVM, Naive Bayes, Logistic Regression can be used. The models which are trained on each bootstrap dataset are called base models or weak learners. The below diagram describes the training of each dataset of separate models: A final powerful robust model is creating by combining the k different base models. Since the base models are trained on a bootstrap sample so each model may have different predictions. The aggregation technique is different depending on the problem statement. For a regression problem: The aggregation can be taking the mean of prediction of each base model. Notation,prediction: Final Output of bagging ensemblek: number of base modelspred_i: prediction of ith base model For a classification problem: The aggregation can be using majority voting, the class having the maximum vote can be declared as the final prediction. Notation,prediction: Final Output of bagging ensemblepred_i: prediction target class of ith base model1,2,3...,c: c different target classC: Target Class having maximum vote Random Forest is an example of bagging ensemble learning. In the Random Forest algorithm, the base learners are only Decision Trees. Random Forest uses bagging along with column sampling to form a robust model. In other terms, RF uses an implementation of bagging ensemble learning, in addition to that, it does column sampling with replacement during bootstrapping step. The variation in the first step of bootstrapping is shown below: The shape of the initial dataset D is (n rows, f features), in case of bootstrap sampling + column sampling, the k base dataset formed are both row and column sampled. The shape of the base dataset D_i is (m rows, d features) where n>m and f>d. Implementation of Decision Tree and Random Forest classifier for Pima Indians Diabetes Dataset from Kaggle. Observation of Decision Tree Classifier: The decision tree classifier is trained for X_train (lines 16–19), and the performance of the DT classifier model (lines 21–23) is tested on X_test data. The observation of the performance of the DT model is: Observation of Random Forest Classifier: The Random Forest classifier for k=50 is trained for X_train (lines 25–28), and the performance of the RF classifier model (lines 30–32) is tested on X_test data. The observation of the performance of the RF model is: Observation of Performance Improvement: The accuracy of the model increases from 71% (for DT classifier) to 75% (RF Classifier). The change in a decrease in FN and FP values and an increase in TP and FN values can be observed from the two confusion matrix. References: [1] (April 23, 2019), Ensemble methods: bagging, boosting and stacking: https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205 Thank You for Reading!
[ { "code": null, "e": 371, "s": 171, "text": "The performance of a machine learning model tells us how the model performs for unseen data-points. There are various strategies and hacks to improve the performance of an ML model, some of them are:" }, { "code": null, "e": 414, "s": 371, "text": "Fine tuning hyperparameter of the ML model" }, { "code": null, "e": 439, "s": 414, "text": "Using ensemble learning." }, { "code": null, "e": 682, "s": 439, "text": "Ensemble Learning is a technique to combine multiple ML models to form a single model. The multiple ML models also referred to as base models or weak learners can be of different algorithms or same algorithms with a change in hyperparameters." }, { "code": null, "e": 914, "s": 682, "text": "Like for classification tasks, multiple ML models can be Logistic Regression, Naive Bayes, Decision Tree, SVM, etc. For regression tasks, multiple ML models can be Linear Regression, Lasso Regression, Decision Tree Regression, etc." }, { "code": null, "e": 1079, "s": 914, "text": "Ensemble Learning combines the advantages of base models to form a single robust model with improved performance. Various types of ensemble learning techniques are:" }, { "code": null, "e": 1142, "s": 1079, "text": "Bagging (Bootstrap Aggregation)BoostingVotingCascadingStacking" }, { "code": null, "e": 1174, "s": 1142, "text": "Bagging (Bootstrap Aggregation)" }, { "code": null, "e": 1183, "s": 1174, "text": "Boosting" }, { "code": null, "e": 1190, "s": 1183, "text": "Voting" }, { "code": null, "e": 1200, "s": 1190, "text": "Cascading" }, { "code": null, "e": 1209, "s": 1200, "text": "Stacking" }, { "code": null, "e": 1314, "s": 1209, "text": "And many more. This article will cover the working and implementation of the Bagging Ensemble technique." }, { "code": null, "e": 1627, "s": 1314, "text": "Bagging ensemble technique also known as Bootstrap Aggregation uses randomization to improve performance. In bagging, we use base models that are trained on part of the dataset. In bagging, we use weak learners (or base models) models as building blocks for designing complex models by combining several of them." }, { "code": null, "e": 1801, "s": 1627, "text": "Most of the time, these base models do not perform well because they either overfit or underfit. Overfitting or underfitting of a model is decided by bias-variance tradeoff." }, { "code": null, "e": 1838, "s": 1801, "text": "What is Bias-Variance Tradeoff ? [1]" }, { "code": null, "e": 1948, "s": 1838, "text": "The overall error of a model is dependent on the bias and variance of the model following the below equation:" }, { "code": null, "e": 2269, "s": 1948, "text": "For a good robust model, the error of the model is as minimum as possible. To minimize the error the bias and variance need to be minimum and irreducible error remains constant. The below plot of error vs model flexibility (degree of freedom) describes the change of bias and variance along with test and training error:" }, { "code": null, "e": 2305, "s": 2269, "text": "Analysis from the above image plot:" }, { "code": null, "e": 2397, "s": 2305, "text": "When the model is in the initial phase of training, training, and test error are very high." }, { "code": null, "e": 2490, "s": 2397, "text": "When the model is enough trained, the training error is very low and the test error is high." }, { "code": null, "e": 2555, "s": 2490, "text": "The phase where training and test error is high is Underfitting." }, { "code": null, "e": 2636, "s": 2555, "text": "The phase where training error is low and the test error is high is Overfitting." }, { "code": null, "e": 2723, "s": 2636, "text": "The phase where there is a balance between training and testing error is Best fitting." }, { "code": null, "e": 2773, "s": 2723, "text": "An Underfit model has low variance and high bias." }, { "code": null, "e": 2822, "s": 2773, "text": "An Overfit model has high variance and low bias." }, { "code": null, "e": 3068, "s": 2822, "text": "Bagging Ensemble technique can be used for base models that have low bias and high variance. Bagging ensemble uses randomization of the dataset (will be discussed later in this article) to reduce the variance of base models keeping the bias low." }, { "code": null, "e": 3313, "s": 3068, "text": "It is now clear that bagging reduces the variance of base models keeping the bias low. The variance of base models is reduced by combining strategies of bootstrap sampling and aggregation. The entire working of Bagging is divided into 3 phases:" }, { "code": null, "e": 3356, "s": 3313, "text": "Bootstrap SamplingBase ModelingAggregation" }, { "code": null, "e": 3375, "s": 3356, "text": "Bootstrap Sampling" }, { "code": null, "e": 3389, "s": 3375, "text": "Base Modeling" }, { "code": null, "e": 3401, "s": 3389, "text": "Aggregation" }, { "code": null, "e": 3479, "s": 3401, "text": "Below diagram describes all three steps for a sample dataset D having n rows:" }, { "code": null, "e": 3646, "s": 3479, "text": "A bootstrap sample is a smaller sample that is a subset of the initial dataset. The bootstrap sample is created from the initial dataset by sampling with replacement." }, { "code": null, "e": 4014, "s": 3646, "text": "Suppose for a dataset having n rows and f features, we do a bootstrap sampling that refers to sampling with replacement into k different smaller datasets each of size m with the same f features. Each smaller dataset D_i formed sees a subset of the dataset. In the figure below initial dataset D of shape (n, f) is sampled to k dataset each of shape (m, f), where m<n." }, { "code": null, "e": 4211, "s": 4014, "text": "The below image describes how to bootstrap the sample. The dataset D having 10 rows is sampled with replacement into k smaller dataset each having 5 rows. Here n=10 and m=5 from the above diagram." }, { "code": null, "e": 4369, "s": 4211, "text": "It is observed that each of the datasets formed by bootstrapping sees only a part of the original dataset and all the datasets are independent of each other." }, { "code": null, "e": 4508, "s": 4369, "text": "This is the 1st step of the bagging ensemble technique in which k smaller datasets are created by bootstrapping independent of each other." }, { "code": null, "e": 4794, "s": 4508, "text": "Modeling is the 2nd step of bagging. After k smaller datasets are created by bootstrapping each of the k datasets is trained using ML algorithms. The algorithms used for training k dataset can be the same with or without a change in hyperparameters or different algorithms can be used." }, { "code": null, "e": 4807, "s": 4794, "text": "For example," }, { "code": null, "e": 4909, "s": 4807, "text": "Decision Tree algorithms can be used as base models with a change in hyperparameters such as ‘depth’." }, { "code": null, "e": 5006, "s": 4909, "text": "A combination of different algorithms such as SVM, Naive Bayes, Logistic Regression can be used." }, { "code": null, "e": 5179, "s": 5006, "text": "The models which are trained on each bootstrap dataset are called base models or weak learners. The below diagram describes the training of each dataset of separate models:" }, { "code": null, "e": 5440, "s": 5179, "text": "A final powerful robust model is creating by combining the k different base models. Since the base models are trained on a bootstrap sample so each model may have different predictions. The aggregation technique is different depending on the problem statement." }, { "code": null, "e": 5539, "s": 5440, "text": "For a regression problem: The aggregation can be taking the mean of prediction of each base model." }, { "code": null, "e": 5653, "s": 5539, "text": "Notation,prediction: Final Output of bagging ensemblek: number of base modelspred_i: prediction of ith base model" }, { "code": null, "e": 5804, "s": 5653, "text": "For a classification problem: The aggregation can be using majority voting, the class having the maximum vote can be declared as the final prediction." }, { "code": null, "e": 5978, "s": 5804, "text": "Notation,prediction: Final Output of bagging ensemblepred_i: prediction target class of ith base model1,2,3...,c: c different target classC: Target Class having maximum vote" }, { "code": null, "e": 6189, "s": 5978, "text": "Random Forest is an example of bagging ensemble learning. In the Random Forest algorithm, the base learners are only Decision Trees. Random Forest uses bagging along with column sampling to form a robust model." }, { "code": null, "e": 6415, "s": 6189, "text": "In other terms, RF uses an implementation of bagging ensemble learning, in addition to that, it does column sampling with replacement during bootstrapping step. The variation in the first step of bootstrapping is shown below:" }, { "code": null, "e": 6660, "s": 6415, "text": "The shape of the initial dataset D is (n rows, f features), in case of bootstrap sampling + column sampling, the k base dataset formed are both row and column sampled. The shape of the base dataset D_i is (m rows, d features) where n>m and f>d." }, { "code": null, "e": 6768, "s": 6660, "text": "Implementation of Decision Tree and Random Forest classifier for Pima Indians Diabetes Dataset from Kaggle." }, { "code": null, "e": 6809, "s": 6768, "text": "Observation of Decision Tree Classifier:" }, { "code": null, "e": 7018, "s": 6809, "text": "The decision tree classifier is trained for X_train (lines 16–19), and the performance of the DT classifier model (lines 21–23) is tested on X_test data. The observation of the performance of the DT model is:" }, { "code": null, "e": 7059, "s": 7018, "text": "Observation of Random Forest Classifier:" }, { "code": null, "e": 7277, "s": 7059, "text": "The Random Forest classifier for k=50 is trained for X_train (lines 25–28), and the performance of the RF classifier model (lines 30–32) is tested on X_test data. The observation of the performance of the RF model is:" }, { "code": null, "e": 7317, "s": 7277, "text": "Observation of Performance Improvement:" }, { "code": null, "e": 7406, "s": 7317, "text": "The accuracy of the model increases from 71% (for DT classifier) to 75% (RF Classifier)." }, { "code": null, "e": 7534, "s": 7406, "text": "The change in a decrease in FN and FP values and an increase in TP and FN values can be observed from the two confusion matrix." }, { "code": null, "e": 7546, "s": 7534, "text": "References:" }, { "code": null, "e": 7709, "s": 7546, "text": "[1] (April 23, 2019), Ensemble methods: bagging, boosting and stacking: https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205" } ]
C++ Array Library - size() Function
The C++ function std::array::size() is used to get the number of elements present in the array. Following is the declaration for std::array::size() function form std::array header. constexpr size_type size(); noexcept None Returns the number of elements present in the array. This value is always same as the second parameter of the array template used to instantiate array. Do not confuse with sizeof() operator which return the size of data type in bytes. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::array::size() function. #include <iostream> #include <array> using namespace std; int main(void) { array<int, 5> int_arr; /* Array of 5 integers */ array<float, 0> float_arr; /* Array of 0 floats */ cout << "Number of elements in int_arr = " << int_arr.size() << endl; cout << "Number of elements in float_arr = " << float_arr.size() << endl; return 0; } Let us compile and run the above program, this will produce the following result − Number of elements in int_arr = 5 Number of elements in float_arr = 0 Print Add Notes Bookmark this page
[ { "code": null, "e": 2699, "s": 2603, "text": "The C++ function std::array::size() is used to get the number of elements present in the array." }, { "code": null, "e": 2784, "s": 2699, "text": "Following is the declaration for std::array::size() function form std::array header." }, { "code": null, "e": 2821, "s": 2784, "text": "constexpr size_type size(); noexcept" }, { "code": null, "e": 2826, "s": 2821, "text": "None" }, { "code": null, "e": 2978, "s": 2826, "text": "Returns the number of elements present in the array. This value is always same as the second\nparameter of the array template used to instantiate array." }, { "code": null, "e": 3061, "s": 2978, "text": "Do not confuse with sizeof() operator which return the size of data type in bytes." }, { "code": null, "e": 3106, "s": 3061, "text": "This member function never throws exception." }, { "code": null, "e": 3125, "s": 3106, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3195, "s": 3125, "text": "The following example shows the usage of std::array::size() function." }, { "code": null, "e": 3558, "s": 3195, "text": "#include <iostream>\n#include <array>\n\nusing namespace std;\n\nint main(void) {\n\n array<int, 5> int_arr; /* Array of 5 integers */\n array<float, 0> float_arr; /* Array of 0 floats */\n\n cout << \"Number of elements in int_arr = \" << int_arr.size() << endl;\n cout << \"Number of elements in float_arr = \" << float_arr.size() << endl;\n\n return 0;\n}" }, { "code": null, "e": 3641, "s": 3558, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3714, "s": 3641, "text": "Number of elements in int_arr = 5\nNumber of elements in float_arr = 0\n" }, { "code": null, "e": 3721, "s": 3714, "text": " Print" }, { "code": null, "e": 3732, "s": 3721, "text": " Add Notes" } ]
How to use Sass Variables with CSS3 Media Queries ? - GeeksforGeeks
24 Jun, 2021 SASS Variables: SASS Variables are very simple to understand and use. SASS Variables assign a value to a name that begins with $ sign, and then just refer to that name instead of the value. Despite this, they are one of the most useful tools SASS provides. SASS Variables provide the following features: Reduce repetition Do complex mathematics Configure libraries and much more ... CSS Media queries: CSS Media Queries are the features of CSS3 which allows specifying when given CSS rules must be applied. Media queries work keeping in mind the capability of the device. They can be used to check many things, for example: Width and height of the viewport Width and height of the device Orientation (landscape or portrait) Resolution of the device Using SASS Variables with CSS3 Media queries is not much easily implemented. It is possible only if SASS grabs all the properties of queries into the style-sheet containing the SASS variable and then changes them accordingly. It can be done in two ways: Using the Post-CSS variables Using mixins Using Post-CSS variables: The following example works great with SASS (even for older browsers). css $width1: 1280px;$width2: 1720px; :root { f-size: 20px; f-family: Helvetica, sans-serif;} @media (min-width: $width1) and (max-width: $width2) { :root { f-size: 22px; f-family: Helvetica; ; }} @media (min-width: $mq-hhd) { :root { f-size: 24px; f-family: sans-serif; ; }} .my-element { font-size: var(f-size); color: red; font-family: var(f-family);} The code would result in the below written CSS output. The repeating media queries will obviously increase the size of the file, but it is found that the increase is usually negligible as soon as the webserver applies compression (which it will usually do by itself). .my-element { font-size: 20px; font-family: Helvetica, sans-serif; } @media (min-width: 1280px) and (max-width: 1719px) { .my-element { font-family: Helvetica; } } @media (min-width: 1720px) { .my-element { font-family: sans-serif; } } @media (min-width: 1280px) and (max-width: 1719px) { .my-element { font-size: 22px; } } @media (min-width: 1720px) { .my-element { font-size: 24px; } } Using mixins: It lets you have everything in a single file if you want. css @mixin change($width) { // your SCSS here #Contents { width: $width; }} @media screen and (max-width: 140px) { @include change($width: 720px);} @media screen and (min-width: 1441px) { @include change($width: 960px);} This code will display the following result. @media screen and (max-width: 140px) { #Contents { width: 720px; } } @media screen and (min-width: 1441px) { #Contents { width: 960px; } } gabaa406 CSS-Misc Picked SASS CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 25011, "s": 24983, "text": "\n24 Jun, 2021" }, { "code": null, "e": 25317, "s": 25011, "text": "SASS Variables: SASS Variables are very simple to understand and use. SASS Variables assign a value to a name that begins with $ sign, and then just refer to that name instead of the value. Despite this, they are one of the most useful tools SASS provides. SASS Variables provide the following features: " }, { "code": null, "e": 25335, "s": 25317, "text": "Reduce repetition" }, { "code": null, "e": 25358, "s": 25335, "text": "Do complex mathematics" }, { "code": null, "e": 25378, "s": 25358, "text": "Configure libraries" }, { "code": null, "e": 25396, "s": 25378, "text": "and much more ..." }, { "code": null, "e": 25639, "s": 25396, "text": "CSS Media queries: CSS Media Queries are the features of CSS3 which allows specifying when given CSS rules must be applied. Media queries work keeping in mind the capability of the device. They can be used to check many things, for example: " }, { "code": null, "e": 25672, "s": 25639, "text": "Width and height of the viewport" }, { "code": null, "e": 25703, "s": 25672, "text": "Width and height of the device" }, { "code": null, "e": 25739, "s": 25703, "text": "Orientation (landscape or portrait)" }, { "code": null, "e": 25764, "s": 25739, "text": "Resolution of the device" }, { "code": null, "e": 26020, "s": 25764, "text": "Using SASS Variables with CSS3 Media queries is not much easily implemented. It is possible only if SASS grabs all the properties of queries into the style-sheet containing the SASS variable and then changes them accordingly. It can be done in two ways: " }, { "code": null, "e": 26049, "s": 26020, "text": "Using the Post-CSS variables" }, { "code": null, "e": 26062, "s": 26049, "text": "Using mixins" }, { "code": null, "e": 26161, "s": 26062, "text": "Using Post-CSS variables: The following example works great with SASS (even for older browsers). " }, { "code": null, "e": 26165, "s": 26161, "text": "css" }, { "code": "$width1: 1280px;$width2: 1720px; :root { f-size: 20px; f-family: Helvetica, sans-serif;} @media (min-width: $width1) and (max-width: $width2) { :root { f-size: 22px; f-family: Helvetica; ; }} @media (min-width: $mq-hhd) { :root { f-size: 24px; f-family: sans-serif; ; }} .my-element { font-size: var(f-size); color: red; font-family: var(f-family);}", "e": 26584, "s": 26165, "text": null }, { "code": null, "e": 26853, "s": 26584, "text": "The code would result in the below written CSS output. The repeating media queries will obviously increase the size of the file, but it is found that the increase is usually negligible as soon as the webserver applies compression (which it will usually do by itself). " }, { "code": null, "e": 27413, "s": 26853, "text": " .my-element {\n font-size: 20px;\n font-family: Helvetica, sans-serif;\n }\n\n @media (min-width: 1280px) and (max-width: 1719px) {\n .my-element {\n font-family: Helvetica;\n }\n }\n\n @media (min-width: 1720px) {\n .my-element {\n font-family: sans-serif;\n }\n }\n\n @media (min-width: 1280px) and (max-width: 1719px) {\n .my-element {\n font-size: 22px;\n }\n }\n\n @media (min-width: 1720px) {\n .my-element {\n font-size: 24px;\n }\n }" }, { "code": null, "e": 27487, "s": 27413, "text": "Using mixins: It lets you have everything in a single file if you want. " }, { "code": null, "e": 27491, "s": 27487, "text": "css" }, { "code": "@mixin change($width) { // your SCSS here #Contents { width: $width; }} @media screen and (max-width: 140px) { @include change($width: 720px);} @media screen and (min-width: 1441px) { @include change($width: 960px);}", "e": 27731, "s": 27491, "text": null }, { "code": null, "e": 27778, "s": 27731, "text": "This code will display the following result. " }, { "code": null, "e": 27990, "s": 27778, "text": " @media screen and (max-width: 140px) {\n #Contents {\n width: 720px;\n }\n }\n\n @media screen and (min-width: 1441px) {\n #Contents {\n width: 960px;\n }\n }" }, { "code": null, "e": 28001, "s": 27992, "text": "gabaa406" }, { "code": null, "e": 28010, "s": 28001, "text": "CSS-Misc" }, { "code": null, "e": 28017, "s": 28010, "text": "Picked" }, { "code": null, "e": 28022, "s": 28017, "text": "SASS" }, { "code": null, "e": 28026, "s": 28022, "text": "CSS" }, { "code": null, "e": 28043, "s": 28026, "text": "Web Technologies" }, { "code": null, "e": 28070, "s": 28043, "text": "Web technologies Questions" }, { "code": null, "e": 28168, "s": 28070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28177, "s": 28168, "text": "Comments" }, { "code": null, "e": 28190, "s": 28177, "text": "Old Comments" }, { "code": null, "e": 28227, "s": 28190, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28256, "s": 28227, "text": "Form validation using jQuery" }, { "code": null, "e": 28295, "s": 28256, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28337, "s": 28295, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28372, "s": 28337, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28428, "s": 28372, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28461, "s": 28428, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28504, "s": 28461, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28565, "s": 28504, "text": "Difference between var, let and const keywords in JavaScript" } ]
Reverse squared sum | Practice | GeeksforGeeks
Reena had been given an array arr[] of positive integers of size N.Help her to find the value A. A = arr[n]*arr[n] - arr[n-1]*arr[n-1] + arr[n-2]*arr[n-2] - ......... upto index 1 Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. 3. The second line contains N space-separated positive integers represents array arr. Output: For each test case, print the value of A in a single line Constraints: 1. 1 <= T <= 10 2. 1 <= N <= 100000 3. 1 <= arr[i] <= 100 Example: Input: 2 3 1 2 3 4 4 8 1 2 Output: 6 51 Explanation: Test case 1 : 3*3 - 2*2 + 1*1 = 6 0 skrajenf322 months ago #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long UL; typedef unsigned long long ULL; typedef vector<int> vi; typedef vector<string> vs; typedef vector<vi> vvi; typedef vector<LL> vl; typedef vector<vl> vvl; typedef vector<vs> vvs; double PI = acos(-1); #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define FOR(a,b,c) for(int (a) = (b); (a) < (c); (a)++) #define FORD(a,b,c) for(int (a) = (b); (a) > (c); (a)--) #define FORS(i,n) FOR(i,0,n) #define FOREACH(a, b) for(auto&(a): (b)) #define COUTI(a,i) cout<<a[i]<<" " #define COUT(a) cout<<a<<" " #define pb push_back #define MAX(a, b) a = max(a,b) #define MIN(a, b) a = min(a,b) #define SZ(any) (int)any.size() #define arsz(arr) sizeof(arr)/sizeof(arr[0]) int main(){ fastio int t; cin>>t; while(t--){ int n; cin>>n; int A=0; while(n--){ int m; cin>>m; A+=pow(-1,n)*m*m; } cout<<A<<"\n"; } return 0; } 0 mohituniyal462 months ago A simple answer #include <iostream> #include<cmath> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n, A=0; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } for(int i=0;i<n;i++){ A+=pow(-1, i)*arr[n-1-i]*arr[n-1-i]; } cout<<A<<endl; } return 0; } 0 singhalyash813 months ago #include <iostream>#include <bits/stdc++.h>using namespace std; int main() {//codeios_base::sync_with_stdio(NULL);cin.tie(NULL);int t;cin>>t;while(t--){ long long n; cin>>n; long long sum=0; long long arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int p=1; int neg=1; long long res=0; for(int i=n-1;i>=0;i--) { if(p==1) { res+=(arr[i]*arr[i]); p-=1; neg=1; } else if(neg==1) { res-=(arr[i]*arr[i]); neg-=1; p=1; } } cout<<res<<endl;}return 0;} 0 durpb12013 months ago c++ code int t,n; cin>>t; while(t--) { cin>>n; int arr[n],sumEvenPos=0,sumOddPos=0; for(int i=0;i<n;i++) { cin>>arr[i]; if(i%2==0) { sumEvenPos+=(arr[i]*arr[i]); } else { sumOddPos+=(arr[i]*arr[i]); } } if(n%2!=0) { int ans=sumEvenPos-sumOddPos; cout<<ans<<"\n"; } else { int ans=sumOddPos-sumEvenPos; cout<<ans<<"\n"; } } 0 shuklaps11193 months ago /*package whatever //do not write package name here */ import java.util.*;import java.lang.*;import java.io.*; class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0){ int s = sc.nextInt(); int a[]=new int[s]; int op = 0; int tp=0; for(int i=0;i<s;i++) a[i]=sc.nextInt(); for (int i=s-1;i>=0;i--){ if(tp%2==0){ op += (a[i]*a[i]); tp++; }else{ op -= (a[i]*a[i]); tp++; } } System.out.println(op); t--; }}} 0 kewatshubham993 months ago /*package whatever //do not write package name here */ import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { //code Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for(int i=0;i<test;i++){ int result = 0; int temp = 0; int size = scan.nextInt(); int[] arr = new int[size]; for(int j=0;j<size;j++){ arr[j] = scan.nextInt(); } for(int j=size-1;j>=0;j--){ if(temp%2==0){ result = result+(arr[j]*arr[j]); temp++; }else{ result = result-(arr[j]*arr[j]); temp++; } } System.out.println(result); } } } 0 krishnavakte255 months ago #include <iostream>using namespace std;int square(int i){ return i*i;} int reversesquare(int arr[],int i){ if(i==0){ return square(arr[i]); } if(i==1){ return square(arr[i])-square(arr[i-1]); } return square(arr[i])-square(arr[i-1])+reversesquare(arr,i-2);} //Compiler version g++ 6.3.0 int main(){ int t; cin>>t; int sol[t]; for(int i=0;i<t;i++){ int n; cin>>n; int arr[n]; for(int j=0;j<n;j++){ cin>>arr[j]; } sol[i]=reversesquare(arr,n-1); } for(int i=0;i<t;i++){ cout << sol[i]<<endl; } return 0;} 0 kamalisrijothi5 months ago python code #coden1=int(input())for i in range(n1): x=int(input()) a1=list(map(int,input().split())) a=a1[::-1] o=0 e=0 for j in range(x): if(j%2==0): e=e+a[j]**2 else: o=o+a[j]**2 print(e-o) 0 e20040806 months ago runtime: 0.1/7.6 for _ in range(int(input())): n = int(input()) arr = input().split() s = 0 for i in range(n): s += int(arr[-1-i]) ** 2 * ((1-i%2)*2-1) print(s) +2 c1phani1simha6 months ago #include<iostream>#include<vector>using namespace std;int main(){int t,n;cin>>t;while(t--){ cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int a,b,o=0,e=0,sum; for(int y=0;y<n;y=y+2) { b=arr[y]*arr[y]; e=e+b; if(y+1<n) { a=arr[y+1]*arr[y+1]; o=o+a; } } if(n%2==0) { sum=o-e; } else sum=e-o; cout<<sum<<endl; }return 0;} 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": 323, "s": 226, "text": "Reena had been given an array arr[] of positive integers of size N.Help her to find the value A." }, { "code": null, "e": 406, "s": 323, "text": "A = arr[n]*arr[n] - arr[n-1]*arr[n-1] + arr[n-2]*arr[n-2] - ......... upto index 1" }, { "code": null, "e": 877, "s": 406, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N.\n3. The second line contains N space-separated positive integers represents array arr.\n\nOutput: For each test case, print the value of A in a single line\n\nConstraints:\n1. 1 <= T <= 10\n2. 1 <= N <= 100000\n3. 1 <= arr[i] <= 100\n\nExample:\nInput:\n2\n3\n1 2 3\n4\n4 8 1 2" }, { "code": null, "e": 890, "s": 877, "text": "Output:\n6\n51" }, { "code": null, "e": 937, "s": 890, "text": "Explanation:\nTest case 1 : 3*3 - 2*2 + 1*1 = 6" }, { "code": null, "e": 939, "s": 937, "text": "0" }, { "code": null, "e": 962, "s": 939, "text": "skrajenf322 months ago" }, { "code": null, "e": 1985, "s": 964, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long LL;\ntypedef unsigned long UL;\ntypedef unsigned long long ULL;\ntypedef vector<int> vi;\ntypedef vector<string> vs;\ntypedef vector<vi> vvi;\ntypedef vector<LL> vl;\ntypedef vector<vl> vvl;\ntypedef vector<vs> vvs;\n\ndouble PI = acos(-1);\n\n#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n#define FOR(a,b,c) for(int (a) = (b); (a) < (c); (a)++)\n#define FORD(a,b,c) for(int (a) = (b); (a) > (c); (a)--)\n#define FORS(i,n) FOR(i,0,n)\n#define FOREACH(a, b) for(auto&(a): (b))\n#define COUTI(a,i) cout<<a[i]<<\" \"\n#define COUT(a) cout<<a<<\" \"\n#define pb push_back\n#define MAX(a, b) a = max(a,b)\n#define MIN(a, b) a = min(a,b)\n#define SZ(any) (int)any.size()\n#define arsz(arr) sizeof(arr)/sizeof(arr[0])\nint main(){\n fastio\n int t;\n cin>>t;\n while(t--){\n int n;\n cin>>n;\n int A=0;\n while(n--){\n int m;\n cin>>m;\n A+=pow(-1,n)*m*m;\n }\n cout<<A<<\"\\n\";\n }\n return 0;\n}" }, { "code": null, "e": 1987, "s": 1985, "text": "0" }, { "code": null, "e": 2013, "s": 1987, "text": "mohituniyal462 months ago" }, { "code": null, "e": 2029, "s": 2013, "text": "A simple answer" }, { "code": null, "e": 2342, "s": 2031, "text": "#include <iostream>\n#include<cmath>\nusing namespace std;\nint main() {\n//code\nint t;\ncin>>t;\nwhile(t--){\n int n, A=0;\n cin>>n;\n int arr[n];\n for(int i=0;i<n;i++){\n cin>>arr[i];\n }\n for(int i=0;i<n;i++){\n A+=pow(-1, i)*arr[n-1-i]*arr[n-1-i];\n }\n cout<<A<<endl;\n}\nreturn 0;\n}" }, { "code": null, "e": 2344, "s": 2342, "text": "0" }, { "code": null, "e": 2370, "s": 2344, "text": "singhalyash813 months ago" }, { "code": null, "e": 2434, "s": 2370, "text": "#include <iostream>#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 2970, "s": 2434, "text": "int main() {//codeios_base::sync_with_stdio(NULL);cin.tie(NULL);int t;cin>>t;while(t--){ long long n; cin>>n; long long sum=0; long long arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int p=1; int neg=1; long long res=0; for(int i=n-1;i>=0;i--) { if(p==1) { res+=(arr[i]*arr[i]); p-=1; neg=1; } else if(neg==1) { res-=(arr[i]*arr[i]); neg-=1; p=1; } } cout<<res<<endl;}return 0;}" }, { "code": null, "e": 2972, "s": 2970, "text": "0" }, { "code": null, "e": 2994, "s": 2972, "text": "durpb12013 months ago" }, { "code": null, "e": 3554, "s": 2994, "text": "c++ code\nint t,n;\n cin>>t;\n while(t--)\n {\n cin>>n;\n int arr[n],sumEvenPos=0,sumOddPos=0;\n for(int i=0;i<n;i++)\n {\n cin>>arr[i];\n if(i%2==0)\n {\n sumEvenPos+=(arr[i]*arr[i]);\n }\n else\n {\n sumOddPos+=(arr[i]*arr[i]);\n }\n }\n if(n%2!=0)\n {\n int ans=sumEvenPos-sumOddPos;\n cout<<ans<<\"\\n\";\n }\n else\n {\n int ans=sumOddPos-sumEvenPos;\n cout<<ans<<\"\\n\";\n }\n }\n\t" }, { "code": null, "e": 3556, "s": 3554, "text": "0" }, { "code": null, "e": 3581, "s": 3556, "text": "shuklaps11193 months ago" }, { "code": null, "e": 3636, "s": 3581, "text": "/*package whatever //do not write package name here */" }, { "code": null, "e": 3692, "s": 3636, "text": "import java.util.*;import java.lang.*;import java.io.*;" }, { "code": null, "e": 4190, "s": 3692, "text": "class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0){ int s = sc.nextInt(); int a[]=new int[s]; int op = 0; int tp=0; for(int i=0;i<s;i++) a[i]=sc.nextInt(); for (int i=s-1;i>=0;i--){ if(tp%2==0){ op += (a[i]*a[i]); tp++; }else{ op -= (a[i]*a[i]); tp++; } } System.out.println(op); t--; }}}" }, { "code": null, "e": 4192, "s": 4190, "text": "0" }, { "code": null, "e": 4219, "s": 4192, "text": "kewatshubham993 months ago" }, { "code": null, "e": 4974, "s": 4219, "text": "/*package whatever //do not write package name here */\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n\tpublic static void main (String[] args) {\n\t\t//code\n\t\tScanner scan = new Scanner(System.in);\n\t\tint test = scan.nextInt();\n\t\t\n\t\t\n\t\tfor(int i=0;i<test;i++){\n\t\t int result = 0;\n\t\t int temp = 0;\n\t\t int size = scan.nextInt();\n\t\t int[] arr = new int[size];\n\t\t \n\t\t for(int j=0;j<size;j++){\n\t\t arr[j] = scan.nextInt();\n\t\t }\n\t\t \n\t\t for(int j=size-1;j>=0;j--){\n\t\t if(temp%2==0){\n\t\t result = result+(arr[j]*arr[j]);\n\t\t temp++;\n\t\t }else{\n\t\t result = result-(arr[j]*arr[j]);\n\t\t temp++;\n\t\t }\n\t\t }\n\t\t System.out.println(result);\n\t\t}\n\t}\n}" }, { "code": null, "e": 4976, "s": 4974, "text": "0" }, { "code": null, "e": 5003, "s": 4976, "text": "krishnavakte255 months ago" }, { "code": null, "e": 5074, "s": 5003, "text": "#include <iostream>using namespace std;int square(int i){ return i*i;}" }, { "code": null, "e": 5265, "s": 5074, "text": "int reversesquare(int arr[],int i){ if(i==0){ return square(arr[i]); } if(i==1){ return square(arr[i])-square(arr[i-1]); } return square(arr[i])-square(arr[i-1])+reversesquare(arr,i-2);}" }, { "code": null, "e": 5294, "s": 5265, "text": "//Compiler version g++ 6.3.0" }, { "code": null, "e": 5580, "s": 5294, "text": "int main(){ int t; cin>>t; int sol[t]; for(int i=0;i<t;i++){ int n; cin>>n; int arr[n]; for(int j=0;j<n;j++){ cin>>arr[j]; } sol[i]=reversesquare(arr,n-1); } for(int i=0;i<t;i++){ cout << sol[i]<<endl; } return 0;}" }, { "code": null, "e": 5582, "s": 5580, "text": "0" }, { "code": null, "e": 5609, "s": 5582, "text": "kamalisrijothi5 months ago" }, { "code": null, "e": 5621, "s": 5609, "text": "python code" }, { "code": null, "e": 5847, "s": 5621, "text": "#coden1=int(input())for i in range(n1): x=int(input()) a1=list(map(int,input().split())) a=a1[::-1] o=0 e=0 for j in range(x): if(j%2==0): e=e+a[j]**2 else: o=o+a[j]**2 print(e-o)" }, { "code": null, "e": 5849, "s": 5847, "text": "0" }, { "code": null, "e": 5870, "s": 5849, "text": "e20040806 months ago" }, { "code": null, "e": 5887, "s": 5870, "text": "runtime: 0.1/7.6" }, { "code": null, "e": 6059, "s": 5887, "text": "for _ in range(int(input())):\n n = int(input())\n arr = input().split()\n s = 0\n for i in range(n):\n s += int(arr[-1-i]) ** 2 * ((1-i%2)*2-1)\n print(s)" }, { "code": null, "e": 6062, "s": 6059, "text": "+2" }, { "code": null, "e": 6088, "s": 6062, "text": "c1phani1simha6 months ago" }, { "code": null, "e": 6545, "s": 6088, "text": "#include<iostream>#include<vector>using namespace std;int main(){int t,n;cin>>t;while(t--){ cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int a,b,o=0,e=0,sum; for(int y=0;y<n;y=y+2) { b=arr[y]*arr[y]; e=e+b; if(y+1<n) { a=arr[y+1]*arr[y+1]; o=o+a; } } if(n%2==0) { sum=o-e; } else sum=e-o; cout<<sum<<endl; }return 0;}" }, { "code": null, "e": 6691, "s": 6545, "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": 6727, "s": 6691, "text": " Login to access your submissions. " }, { "code": null, "e": 6737, "s": 6727, "text": "\nProblem\n" }, { "code": null, "e": 6747, "s": 6737, "text": "\nContest\n" }, { "code": null, "e": 6810, "s": 6747, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6958, "s": 6810, "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": 7166, "s": 6958, "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": 7272, "s": 7166, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Adders and Subtractors in Digital Logic - GeeksforGeeks
25 Nov, 2019 Block Diagram of Combinational Logic Circuit: Points to Remember on Combinational Logic Circuit: Output depends upon the combination of inputs.Output is pure function of present inputs only i.e., Previous State inputs won’t have any effect on the output. Also, It doesn’t use memory.In other words,OUTPUT=f(INPUT)Inputs are called Excitation from circuits and outputs are called Response of combinational logic circuits. Output depends upon the combination of inputs. Output is pure function of present inputs only i.e., Previous State inputs won’t have any effect on the output. Also, It doesn’t use memory. In other words,OUTPUT=f(INPUT) OUTPUT=f(INPUT) Inputs are called Excitation from circuits and outputs are called Response of combinational logic circuits. Classification of Combinational Logic Circuits: 1. Arithmetic: Adders Subtractors Multipliers Comparators 2. Data Handling: Multiplexers DeMultiplexers Encoders and Decoders 3. Code Converters: BCD to Excess-3 code and vice versa BCD to Gray code and vice versa Seven Segment Design of Half Adders and Full Adders: A combinational logic circuit that performs the addition of two single bits is called Half Adder. A combinational logic circuit that performs the addition of three single bits is called Full Adder. 1. Half Adder: It is a arithmetic combinational logic circuit designed to perform addition of two single bits. It contain two inputs and produces two outputs. Inputs are called Augend and Added bits and Outputs are called Sum and Carry. Let us observe the addition of single bits, 0+0=0 0+1=1 1+0=1 1+1=10 Since 1+1=10, the result must be two bit output. So, Above can be rewritten as, 0+0=00 0+1=01 1+0=01 1+1=10 The result of 1+1 is 10, where ‘1’ is carry-output (Cout) and ‘0’ is Sum-output (Normal Output). Truth Table of Half Adder: Next Step is to draw the Logic Diagram. To draw Logic Diagram, We need Boolean Expression, which can be obtained using K-map (karnaugh map). Since there are two output variables ‘S’ and ‘C’, we need to define K-map for each output variable. K-map for output variable Sum ‘S’ : K-map is of Sum of products form. The equation obtained is S = AB' + A'B which can be logically written as, S = A xor B K-map for output variable Carry ‘C’ : The equation obtained from K-map is, C = AB Using the Boolean Expression, we can draw logic diagram as follows.. Limitations:Adding of Carry is not possible in Half adder. 2. Full Adder: To overcome the above limitation faced with Half adders, Full Adders are implemented. It is a arithmetic combinational logic circuit that performs addition of three single bits. It contains three inputs (A, B, Cin) and produces two outputs (Sum and Cout). Where, Cin -> Carry In and Cout -> Carry Out Truth table of Full Adder: K-map Simplification for output variable Sum ‘S’ : The equation obtained is, S = A'B'Cin + AB'Cin' + ABC + A'BCin' The equation can be simplified as, S = B'(A'Cin+ACin') + B(AC + A'Cin') S = B'(A xor Cin) + B (A xor Cin)' S = A xor B xor Cin K-map Simplification for output variable ‘Cout‘ The equation obtained is, Cout = BCin + AB + ACin Logic Diagram of Full Adder: 3. Half Subtractor: It is a combinational logic circuit designed to perform subtraction of two single bits. It contains two inputs (A and B) and produces two outputs (Difference and Borrow-output). Truth Table of Half Subtractor: K-map Simplification for output variable ‘D’ : The equation obtained is, D = A'B + AB' which can be logically written as, D = A xor B K-map Simplification for output variable ‘Bout‘ : The equation obtained from above K-map is, Bout = A'B Logic Diagram of Half Subtractor: 4. Full Subtractor: It is a Combinational logic circuit designed to perform subtraction of three single bits. It contains three inputs(A, B, Bin) and produces two outputs (D, Bout). Where, A and B are called Minuend and Subtrahend bits. And, Bin -> Borrow-In and Bout -> Borrow-Out Truth Table of Full Subtractor: K-map Simplification for output variable ‘D’ : The equation obtained from above K-map is, D = A'B'Bin + AB'Bin' + ABBin + A'BBin' which can be simplified as, D = B'(A'Bin + ABin') + B(ABin + A'Bin') D = B'(A xor Bin) + B(A xor Bin)' D = A xor B xor Bin K-map Simplification for output variable ‘Bout‘ : The equation obtained is, Bout = BBin + A'B + A'Bin Logic Diagram of Full Subtractor: Applications: For performing arithmetic calculations in electronic calculators and other digital devices.In Timers and Program Counters.Useful in Digital Signal Processing. For performing arithmetic calculations in electronic calculators and other digital devices. In Timers and Program Counters. Useful in Digital Signal Processing. Digital Electronics & Logic Design GATE CS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Shift Registers in Digital Logic Counters in Digital Logic Flip-flop types, their Conversion and Applications Difference between Unipolar, Polar and Bipolar Line Coding Schemes Properties of Boolean Algebra Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 23579, "s": 23551, "text": "\n25 Nov, 2019" }, { "code": null, "e": 23625, "s": 23579, "text": "Block Diagram of Combinational Logic Circuit:" }, { "code": null, "e": 23676, "s": 23625, "text": "Points to Remember on Combinational Logic Circuit:" }, { "code": null, "e": 24000, "s": 23676, "text": "Output depends upon the combination of inputs.Output is pure function of present inputs only i.e., Previous State inputs won’t have any effect on the output. Also, It doesn’t use memory.In other words,OUTPUT=f(INPUT)Inputs are called Excitation from circuits and outputs are called Response of combinational logic circuits." }, { "code": null, "e": 24047, "s": 24000, "text": "Output depends upon the combination of inputs." }, { "code": null, "e": 24188, "s": 24047, "text": "Output is pure function of present inputs only i.e., Previous State inputs won’t have any effect on the output. Also, It doesn’t use memory." }, { "code": null, "e": 24219, "s": 24188, "text": "In other words,OUTPUT=f(INPUT)" }, { "code": null, "e": 24235, "s": 24219, "text": "OUTPUT=f(INPUT)" }, { "code": null, "e": 24343, "s": 24235, "text": "Inputs are called Excitation from circuits and outputs are called Response of combinational logic circuits." }, { "code": null, "e": 24391, "s": 24343, "text": "Classification of Combinational Logic Circuits:" }, { "code": null, "e": 24406, "s": 24391, "text": "1. Arithmetic:" }, { "code": null, "e": 24413, "s": 24406, "text": "Adders" }, { "code": null, "e": 24425, "s": 24413, "text": "Subtractors" }, { "code": null, "e": 24437, "s": 24425, "text": "Multipliers" }, { "code": null, "e": 24449, "s": 24437, "text": "Comparators" }, { "code": null, "e": 24467, "s": 24449, "text": "2. Data Handling:" }, { "code": null, "e": 24480, "s": 24467, "text": "Multiplexers" }, { "code": null, "e": 24495, "s": 24480, "text": "DeMultiplexers" }, { "code": null, "e": 24517, "s": 24495, "text": "Encoders and Decoders" }, { "code": null, "e": 24537, "s": 24517, "text": "3. Code Converters:" }, { "code": null, "e": 24573, "s": 24537, "text": "BCD to Excess-3 code and vice versa" }, { "code": null, "e": 24605, "s": 24573, "text": "BCD to Gray code and vice versa" }, { "code": null, "e": 24619, "s": 24605, "text": "Seven Segment" }, { "code": null, "e": 24658, "s": 24619, "text": "Design of Half Adders and Full Adders:" }, { "code": null, "e": 24756, "s": 24658, "text": "A combinational logic circuit that performs the addition of two single bits is called Half Adder." }, { "code": null, "e": 24856, "s": 24756, "text": "A combinational logic circuit that performs the addition of three single bits is called Full Adder." }, { "code": null, "e": 24871, "s": 24856, "text": "1. Half Adder:" }, { "code": null, "e": 24967, "s": 24871, "text": "It is a arithmetic combinational logic circuit designed to perform addition of two single bits." }, { "code": null, "e": 25015, "s": 24967, "text": "It contain two inputs and produces two outputs." }, { "code": null, "e": 25093, "s": 25015, "text": "Inputs are called Augend and Added bits and Outputs are called Sum and Carry." }, { "code": null, "e": 25137, "s": 25093, "text": "Let us observe the addition of single bits," }, { "code": null, "e": 25162, "s": 25137, "text": "0+0=0\n0+1=1\n1+0=1\n1+1=10" }, { "code": null, "e": 25242, "s": 25162, "text": "Since 1+1=10, the result must be two bit output. So, Above can be rewritten as," }, { "code": null, "e": 25270, "s": 25242, "text": "0+0=00\n0+1=01\n1+0=01\n1+1=10" }, { "code": null, "e": 25367, "s": 25270, "text": "The result of 1+1 is 10, where ‘1’ is carry-output (Cout) and ‘0’ is Sum-output (Normal Output)." }, { "code": null, "e": 25394, "s": 25367, "text": "Truth Table of Half Adder:" }, { "code": null, "e": 25635, "s": 25394, "text": "Next Step is to draw the Logic Diagram. To draw Logic Diagram, We need Boolean Expression, which can be obtained using K-map (karnaugh map). Since there are two output variables ‘S’ and ‘C’, we need to define K-map for each output variable." }, { "code": null, "e": 25671, "s": 25635, "text": "K-map for output variable Sum ‘S’ :" }, { "code": null, "e": 25730, "s": 25671, "text": "K-map is of Sum of products form. The equation obtained is" }, { "code": null, "e": 25746, "s": 25730, "text": " S = AB' + A'B " }, { "code": null, "e": 25781, "s": 25746, "text": "which can be logically written as," }, { "code": null, "e": 25793, "s": 25781, "text": "S = A xor B" }, { "code": null, "e": 25831, "s": 25793, "text": "K-map for output variable Carry ‘C’ :" }, { "code": null, "e": 25868, "s": 25831, "text": "The equation obtained from K-map is," }, { "code": null, "e": 25875, "s": 25868, "text": "C = AB" }, { "code": null, "e": 25944, "s": 25875, "text": "Using the Boolean Expression, we can draw logic diagram as follows.." }, { "code": null, "e": 26003, "s": 25944, "text": "Limitations:Adding of Carry is not possible in Half adder." }, { "code": null, "e": 26018, "s": 26003, "text": "2. Full Adder:" }, { "code": null, "e": 26104, "s": 26018, "text": "To overcome the above limitation faced with Half adders, Full Adders are implemented." }, { "code": null, "e": 26196, "s": 26104, "text": "It is a arithmetic combinational logic circuit that performs addition of three single bits." }, { "code": null, "e": 26274, "s": 26196, "text": "It contains three inputs (A, B, Cin) and produces two outputs (Sum and Cout)." }, { "code": null, "e": 26319, "s": 26274, "text": "Where, Cin -> Carry In and Cout -> Carry Out" }, { "code": null, "e": 26346, "s": 26319, "text": "Truth table of Full Adder:" }, { "code": null, "e": 26397, "s": 26346, "text": "K-map Simplification for output variable Sum ‘S’ :" }, { "code": null, "e": 26423, "s": 26397, "text": "The equation obtained is," }, { "code": null, "e": 26462, "s": 26423, "text": "S = A'B'Cin + AB'Cin' + ABC + A'BCin' " }, { "code": null, "e": 26497, "s": 26462, "text": "The equation can be simplified as," }, { "code": null, "e": 26590, "s": 26497, "text": "S = B'(A'Cin+ACin') + B(AC + A'Cin')\nS = B'(A xor Cin) + B (A xor Cin)'\nS = A xor B xor Cin " }, { "code": null, "e": 26638, "s": 26590, "text": "K-map Simplification for output variable ‘Cout‘" }, { "code": null, "e": 26664, "s": 26638, "text": "The equation obtained is," }, { "code": null, "e": 26689, "s": 26664, "text": "Cout = BCin + AB + ACin " }, { "code": null, "e": 26718, "s": 26689, "text": "Logic Diagram of Full Adder:" }, { "code": null, "e": 26738, "s": 26718, "text": "3. Half Subtractor:" }, { "code": null, "e": 26826, "s": 26738, "text": "It is a combinational logic circuit designed to perform subtraction of two single bits." }, { "code": null, "e": 26916, "s": 26826, "text": "It contains two inputs (A and B) and produces two outputs (Difference and Borrow-output)." }, { "code": null, "e": 26948, "s": 26916, "text": "Truth Table of Half Subtractor:" }, { "code": null, "e": 26995, "s": 26948, "text": "K-map Simplification for output variable ‘D’ :" }, { "code": null, "e": 27021, "s": 26995, "text": "The equation obtained is," }, { "code": null, "e": 27035, "s": 27021, "text": "D = A'B + AB'" }, { "code": null, "e": 27070, "s": 27035, "text": "which can be logically written as," }, { "code": null, "e": 27083, "s": 27070, "text": "D = A xor B " }, { "code": null, "e": 27133, "s": 27083, "text": "K-map Simplification for output variable ‘Bout‘ :" }, { "code": null, "e": 27176, "s": 27133, "text": "The equation obtained from above K-map is," }, { "code": null, "e": 27188, "s": 27176, "text": "Bout = A'B " }, { "code": null, "e": 27222, "s": 27188, "text": "Logic Diagram of Half Subtractor:" }, { "code": null, "e": 27242, "s": 27222, "text": "4. Full Subtractor:" }, { "code": null, "e": 27332, "s": 27242, "text": "It is a Combinational logic circuit designed to perform subtraction of three single bits." }, { "code": null, "e": 27404, "s": 27332, "text": "It contains three inputs(A, B, Bin) and produces two outputs (D, Bout)." }, { "code": null, "e": 27459, "s": 27404, "text": "Where, A and B are called Minuend and Subtrahend bits." }, { "code": null, "e": 27504, "s": 27459, "text": "And, Bin -> Borrow-In and Bout -> Borrow-Out" }, { "code": null, "e": 27536, "s": 27504, "text": "Truth Table of Full Subtractor:" }, { "code": null, "e": 27583, "s": 27536, "text": "K-map Simplification for output variable ‘D’ :" }, { "code": null, "e": 27626, "s": 27583, "text": "The equation obtained from above K-map is," }, { "code": null, "e": 27666, "s": 27626, "text": "D = A'B'Bin + AB'Bin' + ABBin + A'BBin'" }, { "code": null, "e": 27694, "s": 27666, "text": "which can be simplified as," }, { "code": null, "e": 27790, "s": 27694, "text": "D = B'(A'Bin + ABin') + B(ABin + A'Bin')\nD = B'(A xor Bin) + B(A xor Bin)'\nD = A xor B xor Bin " }, { "code": null, "e": 27840, "s": 27790, "text": "K-map Simplification for output variable ‘Bout‘ :" }, { "code": null, "e": 27866, "s": 27840, "text": "The equation obtained is," }, { "code": null, "e": 27894, "s": 27866, "text": "Bout = BBin + A'B + A'Bin " }, { "code": null, "e": 27928, "s": 27894, "text": "Logic Diagram of Full Subtractor:" }, { "code": null, "e": 27942, "s": 27928, "text": "Applications:" }, { "code": null, "e": 28101, "s": 27942, "text": "For performing arithmetic calculations in electronic calculators and other digital devices.In Timers and Program Counters.Useful in Digital Signal Processing." }, { "code": null, "e": 28193, "s": 28101, "text": "For performing arithmetic calculations in electronic calculators and other digital devices." }, { "code": null, "e": 28225, "s": 28193, "text": "In Timers and Program Counters." }, { "code": null, "e": 28262, "s": 28225, "text": "Useful in Digital Signal Processing." }, { "code": null, "e": 28297, "s": 28262, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 28305, "s": 28297, "text": "GATE CS" }, { "code": null, "e": 28324, "s": 28305, "text": "Technical Scripter" }, { "code": null, "e": 28422, "s": 28324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28431, "s": 28422, "text": "Comments" }, { "code": null, "e": 28444, "s": 28431, "text": "Old Comments" }, { "code": null, "e": 28477, "s": 28444, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 28503, "s": 28477, "text": "Counters in Digital Logic" }, { "code": null, "e": 28554, "s": 28503, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 28621, "s": 28554, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 28651, "s": 28621, "text": "Properties of Boolean Algebra" }, { "code": null, "e": 28671, "s": 28651, "text": "Layers of OSI Model" }, { "code": null, "e": 28695, "s": 28671, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28722, "s": 28695, "text": "Types of Operating Systems" }, { "code": null, "e": 28735, "s": 28722, "text": "TCP/IP Model" } ]
Bias, Variance and How they are related to Underfitting, Overfitting | by Rahul Banerjee | Towards Data Science
Assume you have a classification model, training data and testing data x_train , y_train // This is the training datax_test , y_test // This is the testing datay_predicted // the values predicted by the model given an input The error rate is the average error of value predicted by the model and the correct value. Let’s assume we have trained the model and are trying to predict values with input ‘x_train’. The predicted values are y_predicted. Bias is the error rate of y_predicted and y_train. In simple terms,think of bias as the error rate of the training data. When the error rate is high, we call it High Bias and when the error rate is low, we call it Low Bias Let’s assume we have trained the model and this time we are trying to predict values with input ‘x_test’. Again, the predicted values are y_predicted. Variance is the error rate of the y_predicted and y_test In simple terms, think of variance as the error rate of the testing data. When the error rate is high, we call it High Variance and when the error rate is low, we call it Low Variance When the model has a high error rate in the training data, we can say the model is underfitting. This usually occurs when the number of training samples is too low. Since our model performs badly on the training data, it consequently performs badly on the testing data as well. A high error rate in training data implies a High Bias, therefore In simple terms, High Bias implies underfitting When the model has a low error rate in training data but a high error rate in testing data, we can say the model is overfitting. This usually occurs when the number of training samples is too high or the hyperparameters have been tuned to produce a low error rate on the training data. Think of a student who studied a certain set of questions and then gave a mock exam which contains those exact questions they studied. They might do well on the mock exam but on the real exam, which contains unseen questions, they might not necessarily do well. If the student gets a 95% in the mock exam but a 50% in the real exam, we can call it overfitting. A low error rate in training data implies Low Bias whereas a high error rate in testing data implies a High Variance, therefore In simple terms, Low Bias and Hight Variance implies overfittting In the first image, we try to fit the data using a linear equation. The model is rigid and not at all flexible. Due to the low flexibility of a linear equation, it is not able to predict the samples (training data), therefore the error rate is high and it has a High Bias which in turn means it’s underfitting. This model won’t perform well on unseen data. In the second image, we use an equation with degree 4. The model is flexible enough to predict most of the samples correctly but rigid enough to avoid overfitting. In this case, our model will be able to do well on the testing data therefore this is an ideal model. In the third image, we use an equation with degree 15 to predict the samples. Although it’s able to predict almost all the samples, it has too much flexibility and will not be able to perform well on unseen data. As a result, it will have a high error rate in testing data. Since it has a low error rate in training data (Low Bias) and high error rate in training data (High Variance), it’s overfitting. Assume we have three models ( Model A , Model B , Model C) with the following error rates on training and testing data. +---------------+---------+---------+---------+| Error Rate | Model A | Model B | Model C |+---------------+---------+---------+---------+| Training Data | 30% | 6% | 1% |+---------------+---------+---------+---------+| Testing Data | 45% | 8% | 25% |+---------------+---------+---------+---------+ For Model A, The error rate of training data is too high as a result of which the error rate of Testing data is too high as well. It has a High Bias and a High Variance, therefore it’s underfit. This model won’t perform well on unseen data. For Model B, The error rate of training data is low and the error rate ofTesting data is low as well. It has a Low Bias and a Low Variance, therefore it’s an ideal model. This model will perform well on unseen data. For Model C, The error rate of training data is too low. However, the error rate of Testing data is too high as well. It has a Low Bias and a High Variance, therefore it’s overfit. This model won’t perform well on unseen data. When the model’s complexity is too low, i.e a simple model, the model won’t be able to perform well on the training data nor the testing data, therefore it’s underfit At the sweet spot, the model has a low error rate on the training data as well as the testing data, therefore, that’s the ideal model As the complexity of the model increases, the model performs well on the training data but it doesn’t perform well on the testing data and therefore it’s overfit Thank You for reading the article. Please let me know if I made any mistakes or have any misconceptions. Always happy to receive feedback :) I recently created a blog using WordPress, I would love it if you check it out 😃 realpythonproject.com Check out my tutorial on Accuracy, Recall, Precision, F1 Score and Confusion Matrices towardsdatascience.com Connect with me on LinkedIn
[ { "code": null, "e": 243, "s": 172, "text": "Assume you have a classification model, training data and testing data" }, { "code": null, "e": 396, "s": 243, "text": "x_train , y_train // This is the training datax_test , y_test // This is the testing datay_predicted // the values predicted by the model given an input" }, { "code": null, "e": 487, "s": 396, "text": "The error rate is the average error of value predicted by the model and the correct value." }, { "code": null, "e": 670, "s": 487, "text": "Let’s assume we have trained the model and are trying to predict values with input ‘x_train’. The predicted values are y_predicted. Bias is the error rate of y_predicted and y_train." }, { "code": null, "e": 740, "s": 670, "text": "In simple terms,think of bias as the error rate of the training data." }, { "code": null, "e": 842, "s": 740, "text": "When the error rate is high, we call it High Bias and when the error rate is low, we call it Low Bias" }, { "code": null, "e": 1050, "s": 842, "text": "Let’s assume we have trained the model and this time we are trying to predict values with input ‘x_test’. Again, the predicted values are y_predicted. Variance is the error rate of the y_predicted and y_test" }, { "code": null, "e": 1124, "s": 1050, "text": "In simple terms, think of variance as the error rate of the testing data." }, { "code": null, "e": 1234, "s": 1124, "text": "When the error rate is high, we call it High Variance and when the error rate is low, we call it Low Variance" }, { "code": null, "e": 1512, "s": 1234, "text": "When the model has a high error rate in the training data, we can say the model is underfitting. This usually occurs when the number of training samples is too low. Since our model performs badly on the training data, it consequently performs badly on the testing data as well." }, { "code": null, "e": 1578, "s": 1512, "text": "A high error rate in training data implies a High Bias, therefore" }, { "code": null, "e": 1626, "s": 1578, "text": "In simple terms, High Bias implies underfitting" }, { "code": null, "e": 1912, "s": 1626, "text": "When the model has a low error rate in training data but a high error rate in testing data, we can say the model is overfitting. This usually occurs when the number of training samples is too high or the hyperparameters have been tuned to produce a low error rate on the training data." }, { "code": null, "e": 2273, "s": 1912, "text": "Think of a student who studied a certain set of questions and then gave a mock exam which contains those exact questions they studied. They might do well on the mock exam but on the real exam, which contains unseen questions, they might not necessarily do well. If the student gets a 95% in the mock exam but a 50% in the real exam, we can call it overfitting." }, { "code": null, "e": 2401, "s": 2273, "text": "A low error rate in training data implies Low Bias whereas a high error rate in testing data implies a High Variance, therefore" }, { "code": null, "e": 2467, "s": 2401, "text": "In simple terms, Low Bias and Hight Variance implies overfittting" }, { "code": null, "e": 2824, "s": 2467, "text": "In the first image, we try to fit the data using a linear equation. The model is rigid and not at all flexible. Due to the low flexibility of a linear equation, it is not able to predict the samples (training data), therefore the error rate is high and it has a High Bias which in turn means it’s underfitting. This model won’t perform well on unseen data." }, { "code": null, "e": 3090, "s": 2824, "text": "In the second image, we use an equation with degree 4. The model is flexible enough to predict most of the samples correctly but rigid enough to avoid overfitting. In this case, our model will be able to do well on the testing data therefore this is an ideal model." }, { "code": null, "e": 3494, "s": 3090, "text": "In the third image, we use an equation with degree 15 to predict the samples. Although it’s able to predict almost all the samples, it has too much flexibility and will not be able to perform well on unseen data. As a result, it will have a high error rate in testing data. Since it has a low error rate in training data (Low Bias) and high error rate in training data (High Variance), it’s overfitting." }, { "code": null, "e": 3614, "s": 3494, "text": "Assume we have three models ( Model A , Model B , Model C) with the following error rates on training and testing data." }, { "code": null, "e": 3944, "s": 3614, "text": "+---------------+---------+---------+---------+| Error Rate | Model A | Model B | Model C |+---------------+---------+---------+---------+| Training Data | 30% | 6% | 1% |+---------------+---------+---------+---------+| Testing Data | 45% | 8% | 25% |+---------------+---------+---------+---------+" }, { "code": null, "e": 4185, "s": 3944, "text": "For Model A, The error rate of training data is too high as a result of which the error rate of Testing data is too high as well. It has a High Bias and a High Variance, therefore it’s underfit. This model won’t perform well on unseen data." }, { "code": null, "e": 4401, "s": 4185, "text": "For Model B, The error rate of training data is low and the error rate ofTesting data is low as well. It has a Low Bias and a Low Variance, therefore it’s an ideal model. This model will perform well on unseen data." }, { "code": null, "e": 4628, "s": 4401, "text": "For Model C, The error rate of training data is too low. However, the error rate of Testing data is too high as well. It has a Low Bias and a High Variance, therefore it’s overfit. This model won’t perform well on unseen data." }, { "code": null, "e": 4795, "s": 4628, "text": "When the model’s complexity is too low, i.e a simple model, the model won’t be able to perform well on the training data nor the testing data, therefore it’s underfit" }, { "code": null, "e": 4929, "s": 4795, "text": "At the sweet spot, the model has a low error rate on the training data as well as the testing data, therefore, that’s the ideal model" }, { "code": null, "e": 5091, "s": 4929, "text": "As the complexity of the model increases, the model performs well on the training data but it doesn’t perform well on the testing data and therefore it’s overfit" }, { "code": null, "e": 5232, "s": 5091, "text": "Thank You for reading the article. Please let me know if I made any mistakes or have any misconceptions. Always happy to receive feedback :)" }, { "code": null, "e": 5313, "s": 5232, "text": "I recently created a blog using WordPress, I would love it if you check it out 😃" }, { "code": null, "e": 5335, "s": 5313, "text": "realpythonproject.com" }, { "code": null, "e": 5421, "s": 5335, "text": "Check out my tutorial on Accuracy, Recall, Precision, F1 Score and Confusion Matrices" }, { "code": null, "e": 5444, "s": 5421, "text": "towardsdatascience.com" } ]
How to validate Password is strong or not in ReactJS?
07 Jun, 2022 Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. Syntax: isStrongPassword(str [, options]) Parameters: This function accepts two parameters as mentioned above and described below: str: It is the input value of the string type. options: It is an optional parameter. These are options that are checked for the input password. For example minLength, minLowercase, etc. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the validator module using the following command: npm install validator Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React, { useState } from "react";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validate = (value) => { if (validator.isStrongPassword(value, { minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1 })) { setErrorMessage('Is Strong Password') } else { setErrorMessage('Is Not Strong Password') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Checking Password Strength in ReactJS</h2> <span>Enter Password: </span><input type="text" onChange={(e) => validate(e.target.value)}></input> <br /> {errorMessage === '' ? null : <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span>} </pre> </div> );} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: The following will be the output if the user enters a weak password. The following will be the output if the user enters a strong password. mp06121 react-js JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 221, "s": 52, "text": "Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. " }, { "code": null, "e": 230, "s": 221, "text": "Syntax: " }, { "code": null, "e": 264, "s": 230, "text": "isStrongPassword(str [, options])" }, { "code": null, "e": 353, "s": 264, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 400, "s": 353, "text": "str: It is the input value of the string type." }, { "code": null, "e": 539, "s": 400, "text": "options: It is an optional parameter. These are options that are checked for the input password. For example minLength, minLowercase, etc." }, { "code": null, "e": 589, "s": 539, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 653, "s": 589, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 685, "s": 653, "text": "npx create-react-app foldername" }, { "code": null, "e": 785, "s": 685, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 799, "s": 785, "text": "cd foldername" }, { "code": null, "e": 905, "s": 799, "text": "Step 3: After creating the ReactJS application, Install the validator module using the following command:" }, { "code": null, "e": 927, "s": 905, "text": "npm install validator" }, { "code": null, "e": 979, "s": 927, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 997, "s": 979, "text": "Project Structure" }, { "code": null, "e": 1126, "s": 997, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1137, "s": 1126, "text": "Javascript" }, { "code": "import React, { useState } from \"react\";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validate = (value) => { if (validator.isStrongPassword(value, { minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1 })) { setErrorMessage('Is Strong Password') } else { setErrorMessage('Is Not Strong Password') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Checking Password Strength in ReactJS</h2> <span>Enter Password: </span><input type=\"text\" onChange={(e) => validate(e.target.value)}></input> <br /> {errorMessage === '' ? null : <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span>} </pre> </div> );} export default App", "e": 2007, "s": 1137, "text": null }, { "code": null, "e": 2120, "s": 2007, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2130, "s": 2120, "text": "npm start" }, { "code": null, "e": 2138, "s": 2130, "text": "Output:" }, { "code": null, "e": 2207, "s": 2138, "text": "The following will be the output if the user enters a weak password." }, { "code": null, "e": 2280, "s": 2209, "text": "The following will be the output if the user enters a strong password." }, { "code": null, "e": 2288, "s": 2280, "text": "mp06121" }, { "code": null, "e": 2297, "s": 2288, "text": "react-js" }, { "code": null, "e": 2308, "s": 2297, "text": "JavaScript" }, { "code": null, "e": 2327, "s": 2308, "text": "Technical Scripter" }, { "code": null, "e": 2344, "s": 2327, "text": "Web Technologies" } ]
ReactJS - CLI Commands
Let us learn the basic command available in Create React App command line application in this chapter. Create React App provides multiple ways to create React application. Using npx script. npx create-react-app <react-app-name> npx create-react-app hello-react-app Using npm package manager. npm init react-app <react-app-name> npm init react-app hello-react-app Using yarn package manager. yarn init react-app <react-app-name> yarn init react-app hello-react-app Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch. create-react-app my-app --template typescript Above command will create react app using cra-template-typescript package from npm server. React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn. Using npm package manager. npm install --save react-router-dom Using yarn package manager. yarn add react-router-dom React application can be started using npm or yarn command depending on the package manager used in the project. Using npm package manager. npm start Using yarn package manager. yarn start To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode. set HTTPS=true && npm start
[ { "code": null, "e": 2270, "s": 2167, "text": "Let us learn the basic command available in Create React App command line application in this chapter." }, { "code": null, "e": 2339, "s": 2270, "text": "Create React App provides multiple ways to create React application." }, { "code": null, "e": 2357, "s": 2339, "text": "Using npx script." }, { "code": null, "e": 2433, "s": 2357, "text": "npx create-react-app <react-app-name>\nnpx create-react-app hello-react-app\n" }, { "code": null, "e": 2460, "s": 2433, "text": "Using npm package manager." }, { "code": null, "e": 2532, "s": 2460, "text": "npm init react-app <react-app-name>\nnpm init react-app hello-react-app\n" }, { "code": null, "e": 2560, "s": 2532, "text": "Using yarn package manager." }, { "code": null, "e": 2634, "s": 2560, "text": "yarn init react-app <react-app-name>\nyarn init react-app hello-react-app\n" }, { "code": null, "e": 2963, "s": 2634, "text": "Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch." }, { "code": null, "e": 3010, "s": 2963, "text": "create-react-app my-app --template typescript\n" }, { "code": null, "e": 3101, "s": 3010, "text": "Above command will create react app using cra-template-typescript package from npm server." }, { "code": null, "e": 3249, "s": 3101, "text": "React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn." }, { "code": null, "e": 3276, "s": 3249, "text": "Using npm package manager." }, { "code": null, "e": 3313, "s": 3276, "text": "npm install --save react-router-dom\n" }, { "code": null, "e": 3341, "s": 3313, "text": "Using yarn package manager." }, { "code": null, "e": 3368, "s": 3341, "text": "yarn add react-router-dom\n" }, { "code": null, "e": 3481, "s": 3368, "text": "React application can be started using npm or yarn command depending on the package manager used in the project." }, { "code": null, "e": 3508, "s": 3481, "text": "Using npm package manager." }, { "code": null, "e": 3519, "s": 3508, "text": "npm start\n" }, { "code": null, "e": 3547, "s": 3519, "text": "Using yarn package manager." }, { "code": null, "e": 3559, "s": 3547, "text": "yarn start\n" }, { "code": null, "e": 3813, "s": 3559, "text": "To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode." } ]
Ruby | Regular Expressions
17 Sep, 2019 A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes. Syntax: # finding the word 'hi' "Hi there, i am using gfg" =~ /hi/ This will return the index of first occurrence of the word ‘hi’ if present, or else will return ‘ nil ‘. We can also check if a string has a regex or not by using the match method. Below is the example to understand.Example : # Ruby program of regular expression # Checking if the word is present in the stringif "hi there".match(/hi/) puts "match"end Output: match We can use a character class which lets us define a range of characters for the match. For example, if we want to search for vowel, we can use [aeiou] for match.Example : # Ruby program of regular expression # declaring a function which checks for vowel in a stringdef contains_vowel(str) str =~ /[aeiou]/end # Driver code # Geeks has vowel at index 1, so function returns 1puts( contains_vowel("Geeks") ) # bcd has no vowel, so return nil and nothing is printedputs( contains_vowel("bcd") ) Output: 1 There are different short expressions for specifying character ranges : \w is equivalent to [0-9a-zA-Z_] \d is the same as [0-9] \s matches white space \W anything that’s not in [0-9a-zA-Z_] \D anything that’s not a number \S anything that’s not a space The dot character . matches all but does not match new line. If you want to search . character, then you have to escape it. Example : # Ruby program of regular expression a="2m3"b="2.5"# . literal matches for all characterif(a.match(/\d.\d/)) puts("match found")else puts("not found")end# after escaping it, it matches with only '.' literalif(a.match(/\d\.\d/)) puts("match found")else puts("not found")end if(b.match(/\d.\d/)) puts("match found")else puts("not found")end Output: match found not found match found For matching multiple characters we can use modifiers: + is for 1 or more characters * is for 0 or more characters ? is for 0 or 1 character {x, y} if for number of characters between x and y i is for ignores case when matching text. x is for ignores whitespace and allows comments in regular expressions. m is for matches multiple lines, recognizing newlines as normal characters. u,e,s,n are for interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. the regular expression is assumed to use the source encoding, If none of these modifiers is specified. Picked Ruby-Basics Ruby-String Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Ruby | Array slice() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Hash delete() function Ruby | unless Statement and unless Modifier
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2019" }, { "code": null, "e": 453, "s": 28, "text": "A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes." }, { "code": null, "e": 461, "s": 453, "text": "Syntax:" }, { "code": null, "e": 521, "s": 461, "text": "# finding the word 'hi'\n\"Hi there, i am using gfg\" =~ /hi/\n" }, { "code": null, "e": 626, "s": 521, "text": "This will return the index of first occurrence of the word ‘hi’ if present, or else will return ‘ nil ‘." }, { "code": null, "e": 747, "s": 626, "text": "We can also check if a string has a regex or not by using the match method. Below is the example to understand.Example :" }, { "code": "# Ruby program of regular expression # Checking if the word is present in the stringif \"hi there\".match(/hi/) puts \"match\"end", "e": 877, "s": 747, "text": null }, { "code": null, "e": 885, "s": 877, "text": "Output:" }, { "code": null, "e": 891, "s": 885, "text": "match" }, { "code": null, "e": 1062, "s": 891, "text": "We can use a character class which lets us define a range of characters for the match. For example, if we want to search for vowel, we can use [aeiou] for match.Example :" }, { "code": "# Ruby program of regular expression # declaring a function which checks for vowel in a stringdef contains_vowel(str) str =~ /[aeiou]/end # Driver code # Geeks has vowel at index 1, so function returns 1puts( contains_vowel(\"Geeks\") ) # bcd has no vowel, so return nil and nothing is printedputs( contains_vowel(\"bcd\") )", "e": 1388, "s": 1062, "text": null }, { "code": null, "e": 1396, "s": 1388, "text": "Output:" }, { "code": null, "e": 1400, "s": 1396, "text": "1\n\n" }, { "code": null, "e": 1472, "s": 1400, "text": "There are different short expressions for specifying character ranges :" }, { "code": null, "e": 1505, "s": 1472, "text": "\\w is equivalent to [0-9a-zA-Z_]" }, { "code": null, "e": 1529, "s": 1505, "text": "\\d is the same as [0-9]" }, { "code": null, "e": 1552, "s": 1529, "text": "\\s matches white space" }, { "code": null, "e": 1591, "s": 1552, "text": "\\W anything that’s not in [0-9a-zA-Z_]" }, { "code": null, "e": 1623, "s": 1591, "text": "\\D anything that’s not a number" }, { "code": null, "e": 1654, "s": 1623, "text": "\\S anything that’s not a space" }, { "code": null, "e": 1778, "s": 1654, "text": "The dot character . matches all but does not match new line. If you want to search . character, then you have to escape it." }, { "code": null, "e": 1788, "s": 1778, "text": "Example :" }, { "code": "# Ruby program of regular expression a=\"2m3\"b=\"2.5\"# . literal matches for all characterif(a.match(/\\d.\\d/)) puts(\"match found\")else puts(\"not found\")end# after escaping it, it matches with only '.' literalif(a.match(/\\d\\.\\d/)) puts(\"match found\")else puts(\"not found\")end if(b.match(/\\d.\\d/)) puts(\"match found\")else puts(\"not found\")end ", "e": 2152, "s": 1788, "text": null }, { "code": null, "e": 2160, "s": 2152, "text": "Output:" }, { "code": null, "e": 2195, "s": 2160, "text": "match found\nnot found\nmatch found\n" }, { "code": null, "e": 2250, "s": 2195, "text": "For matching multiple characters we can use modifiers:" }, { "code": null, "e": 2280, "s": 2250, "text": "+ is for 1 or more characters" }, { "code": null, "e": 2310, "s": 2280, "text": "* is for 0 or more characters" }, { "code": null, "e": 2336, "s": 2310, "text": "? is for 0 or 1 character" }, { "code": null, "e": 2387, "s": 2336, "text": "{x, y} if for number of characters between x and y" }, { "code": null, "e": 2429, "s": 2387, "text": "i is for ignores case when matching text." }, { "code": null, "e": 2501, "s": 2429, "text": "x is for ignores whitespace and allows comments in regular expressions." }, { "code": null, "e": 2577, "s": 2501, "text": "m is for matches multiple lines, recognizing newlines as normal characters." }, { "code": null, "e": 2759, "s": 2577, "text": "u,e,s,n are for interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. the regular expression is assumed to use the source encoding, If none of these modifiers is specified." }, { "code": null, "e": 2766, "s": 2759, "text": "Picked" }, { "code": null, "e": 2778, "s": 2766, "text": "Ruby-Basics" }, { "code": null, "e": 2790, "s": 2778, "text": "Ruby-String" }, { "code": null, "e": 2795, "s": 2790, "text": "Ruby" }, { "code": null, "e": 2893, "s": 2795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2939, "s": 2893, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 2970, "s": 2939, "text": "Ruby | Array count() operation" }, { "code": null, "e": 3000, "s": 2970, "text": "Ruby | Array slice() function" }, { "code": null, "e": 3027, "s": 3000, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 3051, "s": 3027, "text": "Global Variable in Ruby" }, { "code": null, "e": 3094, "s": 3051, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 3116, "s": 3094, "text": "Ruby | Case Statement" }, { "code": null, "e": 3147, "s": 3116, "text": "Ruby | Array select() function" }, { "code": null, "e": 3177, "s": 3147, "text": "Ruby | Hash delete() function" } ]
Upcasting in Java with Examples
06 May, 2020 Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class. There are two ways in which the objects can be initialized while inheriting the properties of the parent and child classes. They are: Child c = new Child(): The use of this initialization is to access all the members present in both parent and child classes, as we are inheriting the properties.Parent p = new Child(): This type of initialization is used to access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class. Child c = new Child(): The use of this initialization is to access all the members present in both parent and child classes, as we are inheriting the properties. Parent p = new Child(): This type of initialization is used to access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class. What is upcasting?Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods. Example: Let there be an animal class. There can be many different classes of animals. One such class is Fish. So, let’s assume that the fish class extends the Animal class. Therefore, the two ways of inheritance, in this case, is implemented as: Let’s understand the following code to find out the difference: // Java program to demonstrate// the concept of upcasting // Animal Classclass Animal { String name; // A method to print the // nature of the class void nature() { System.out.println("Animal"); }} // A Fish class which extends the// animal classclass Fish extends Animal { String color; // Overriding the method to // print the nature of the class @Override void nature() { System.out.println("Aquatic Animal"); }} // Demo class to understand// the concept of upcastingpublic class GFG { // Driver code public static void main(String[] args) { // Creating an object to represent // Parent p = new Child(); Animal a = new Fish(); // The object 'a' has access to // only the parent's properties. // That is, the colour property // cannot be accessed from 'a' a.name = "GoldFish"; // This statement throws // a compile-time error // a.color = "Orange"; // Creating an object to represent // Child c = new Child(); Fish f = new Fish(); // The object 'f' has access to // all the parent's properties // along with the child's properties. // That is, the colour property can // also be accessed from 'f' f.name = "Whale"; f.color = "Blue"; // Printing the 'a' properties System.out.println("Object a"); System.out.println("Name: " + a.name); // This statement will not work // System.out.println("Fish1 Color" +a.color); // Access to child class - overriden method // using parent reference a.nature(); // Printing the 'f' properties System.out.println("Object f"); System.out.println("Name: " + f.name); System.out.println("Color: " + f.color); f.nature(); }} Object a Name: GoldFish Aquatic Animal Object f Name: Whale Color: Blue Aquatic Animal An illustrative figure of the program: From the above example, it can be clearly understood that we can not access child class members using a parent class reference even though it is of the child type. That is:// This statement throws // a compile-time error a.color = "Orange"; // This statement throws // a compile-time error a.color = "Orange"; And from the above example, we can also observe that we are able to access the parent class members and child class’s overridden methods using the same parent class reference object. That is:// Access to child class // overridden method a.nature(); // Access to child class // overridden method a.nature(); Therefore, we can conclude that the main purpose of using these two different syntaxes is to get variation in accessing the respective members in classes. java-inheritance Java-Object Oriented Java Write From Home Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n06 May, 2020" }, { "code": null, "e": 246, "s": 53, "text": "Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class." }, { "code": null, "e": 380, "s": 246, "text": "There are two ways in which the objects can be initialized while inheriting the properties of the parent and child classes. They are:" }, { "code": null, "e": 778, "s": 380, "text": "Child c = new Child(): The use of this initialization is to access all the members present in both parent and child classes, as we are inheriting the properties.Parent p = new Child(): This type of initialization is used to access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class." }, { "code": null, "e": 940, "s": 778, "text": "Child c = new Child(): The use of this initialization is to access all the members present in both parent and child classes, as we are inheriting the properties." }, { "code": null, "e": 1177, "s": 940, "text": "Parent p = new Child(): This type of initialization is used to access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class." }, { "code": null, "e": 1584, "s": 1177, "text": "What is upcasting?Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods." }, { "code": null, "e": 1831, "s": 1584, "text": "Example: Let there be an animal class. There can be many different classes of animals. One such class is Fish. So, let’s assume that the fish class extends the Animal class. Therefore, the two ways of inheritance, in this case, is implemented as:" }, { "code": null, "e": 1895, "s": 1831, "text": "Let’s understand the following code to find out the difference:" }, { "code": "// Java program to demonstrate// the concept of upcasting // Animal Classclass Animal { String name; // A method to print the // nature of the class void nature() { System.out.println(\"Animal\"); }} // A Fish class which extends the// animal classclass Fish extends Animal { String color; // Overriding the method to // print the nature of the class @Override void nature() { System.out.println(\"Aquatic Animal\"); }} // Demo class to understand// the concept of upcastingpublic class GFG { // Driver code public static void main(String[] args) { // Creating an object to represent // Parent p = new Child(); Animal a = new Fish(); // The object 'a' has access to // only the parent's properties. // That is, the colour property // cannot be accessed from 'a' a.name = \"GoldFish\"; // This statement throws // a compile-time error // a.color = \"Orange\"; // Creating an object to represent // Child c = new Child(); Fish f = new Fish(); // The object 'f' has access to // all the parent's properties // along with the child's properties. // That is, the colour property can // also be accessed from 'f' f.name = \"Whale\"; f.color = \"Blue\"; // Printing the 'a' properties System.out.println(\"Object a\"); System.out.println(\"Name: \" + a.name); // This statement will not work // System.out.println(\"Fish1 Color\" +a.color); // Access to child class - overriden method // using parent reference a.nature(); // Printing the 'f' properties System.out.println(\"Object f\"); System.out.println(\"Name: \" + f.name); System.out.println(\"Color: \" + f.color); f.nature(); }}", "e": 3783, "s": 1895, "text": null }, { "code": null, "e": 3871, "s": 3783, "text": "Object a\nName: GoldFish\nAquatic Animal\nObject f\nName: Whale\nColor: Blue\nAquatic Animal\n" }, { "code": null, "e": 3910, "s": 3871, "text": "An illustrative figure of the program:" }, { "code": null, "e": 4152, "s": 3910, "text": "From the above example, it can be clearly understood that we can not access child class members using a parent class reference even though it is of the child type. That is:// This statement throws\n// a compile-time error\na.color = \"Orange\";\n" }, { "code": null, "e": 4222, "s": 4152, "text": "// This statement throws\n// a compile-time error\na.color = \"Orange\";\n" }, { "code": null, "e": 4473, "s": 4222, "text": "And from the above example, we can also observe that we are able to access the parent class members and child class’s overridden methods using the same parent class reference object. That is:// Access to child class\n// overridden method \na.nature();\n" }, { "code": null, "e": 4533, "s": 4473, "text": "// Access to child class\n// overridden method \na.nature();\n" }, { "code": null, "e": 4688, "s": 4533, "text": "Therefore, we can conclude that the main purpose of using these two different syntaxes is to get variation in accessing the respective members in classes." }, { "code": null, "e": 4705, "s": 4688, "text": "java-inheritance" }, { "code": null, "e": 4726, "s": 4705, "text": "Java-Object Oriented" }, { "code": null, "e": 4731, "s": 4726, "text": "Java" }, { "code": null, "e": 4747, "s": 4731, "text": "Write From Home" }, { "code": null, "e": 4752, "s": 4747, "text": "Java" }, { "code": null, "e": 4850, "s": 4752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4881, "s": 4850, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4900, "s": 4881, "text": "Interfaces in Java" }, { "code": null, "e": 4930, "s": 4900, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4945, "s": 4930, "text": "Stream In Java" }, { "code": null, "e": 4963, "s": 4945, "text": "ArrayList in Java" }, { "code": null, "e": 4999, "s": 4963, "text": "Convert integer to string in Python" }, { "code": null, "e": 5035, "s": 4999, "text": "Convert string to integer in Python" }, { "code": null, "e": 5096, "s": 5035, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 5112, "s": 5096, "text": "Python infinity" } ]
numpy.random.get_state() in Python
26 Nov, 2021 With the help of numpy.random.get_state() method, we can get the internal state of a generator and return the tuple by using this method. Syntax : numpy.random.get_state() Return : Return the tuple having {tuple(str, ndarray of 624 units, int, int, float), dict} Example #1 : In this example we can see that by using numpy.random.get_state() method, we are able to get the tuple having internal state of a generator and return the tuple by using this method. Python3 # import numpy and get_stateimport numpy as np # Using get_state() methodgfg = np.random.get_state()[0] print(gfg) Output : MT19937 Example #2 : Python3 # import numpy and get_stateimport numpy as npimport matplotlib.pyplot as plt # Using get_state() methodgfg = np.random.get_state()[1] count, bins, ignored = plt.hist(gfg, 24, density = True)plt.show() Output : kalrap615 Python numpy-Random Python-numpy 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 Nov, 2021" }, { "code": null, "e": 166, "s": 28, "text": "With the help of numpy.random.get_state() method, we can get the internal state of a generator and return the tuple by using this method." }, { "code": null, "e": 200, "s": 166, "text": "Syntax : numpy.random.get_state()" }, { "code": null, "e": 291, "s": 200, "text": "Return : Return the tuple having {tuple(str, ndarray of 624 units, int, int, float), dict}" }, { "code": null, "e": 304, "s": 291, "text": "Example #1 :" }, { "code": null, "e": 487, "s": 304, "text": "In this example we can see that by using numpy.random.get_state() method, we are able to get the tuple having internal state of a generator and return the tuple by using this method." }, { "code": null, "e": 495, "s": 487, "text": "Python3" }, { "code": "# import numpy and get_stateimport numpy as np # Using get_state() methodgfg = np.random.get_state()[0] print(gfg)", "e": 610, "s": 495, "text": null }, { "code": null, "e": 619, "s": 610, "text": "Output :" }, { "code": null, "e": 627, "s": 619, "text": "MT19937" }, { "code": null, "e": 640, "s": 627, "text": "Example #2 :" }, { "code": null, "e": 648, "s": 640, "text": "Python3" }, { "code": "# import numpy and get_stateimport numpy as npimport matplotlib.pyplot as plt # Using get_state() methodgfg = np.random.get_state()[1] count, bins, ignored = plt.hist(gfg, 24, density = True)plt.show()", "e": 850, "s": 648, "text": null }, { "code": null, "e": 859, "s": 850, "text": "Output :" }, { "code": null, "e": 869, "s": 859, "text": "kalrap615" }, { "code": null, "e": 889, "s": 869, "text": "Python numpy-Random" }, { "code": null, "e": 902, "s": 889, "text": "Python-numpy" }, { "code": null, "e": 909, "s": 902, "text": "Python" } ]
Angular 10 formatDate() Method
24 May, 2021 In this article, we are going to see what is formatDate in Angular 10 and how to use it. formatDate is used to format a date according to locale rules. Syntax: formatDate(value, locale, format, timezone) Parameters: value: The number to format. locale: A locale code for the locale format. format: The date-time components to include. timezone: The time zone of the place. Return Value: string: the formatted date string. NgModule: Module used by formatDate is: CommonModule Approach: Create the Angular app to be used. In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatDate. import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import formatDate and LOCALE_ID inject LOCALE_ID as a public variable. In app.component.html show the local variable using string interpolation Serve the angular app using ng serve to see the output. Example 1: app.component.ts import { formatDate } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate("02-feburary-0202", 'dd-MM-yyyy' ,this.locale);constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Date is : {{curr}}</p> Output: Example 2: app.component.ts import { formatDate } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate("03-march-0303", 'yyyy-dd-MM' ,this.locale);constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Date is : {{curr}}</p> Output: Reference: https://angular.io/api/common/formatDate Angular10 AngularJS-Function AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2021" }, { "code": null, "e": 180, "s": 28, "text": "In this article, we are going to see what is formatDate in Angular 10 and how to use it. formatDate is used to format a date according to locale rules." }, { "code": null, "e": 188, "s": 180, "text": "Syntax:" }, { "code": null, "e": 232, "s": 188, "text": "formatDate(value, locale, format, timezone)" }, { "code": null, "e": 244, "s": 232, "text": "Parameters:" }, { "code": null, "e": 273, "s": 244, "text": "value: The number to format." }, { "code": null, "e": 318, "s": 273, "text": "locale: A locale code for the locale format." }, { "code": null, "e": 363, "s": 318, "text": "format: The date-time components to include." }, { "code": null, "e": 401, "s": 363, "text": "timezone: The time zone of the place." }, { "code": null, "e": 415, "s": 401, "text": "Return Value:" }, { "code": null, "e": 450, "s": 415, "text": "string: the formatted date string." }, { "code": null, "e": 490, "s": 450, "text": "NgModule: Module used by formatDate is:" }, { "code": null, "e": 503, "s": 490, "text": "CommonModule" }, { "code": null, "e": 514, "s": 503, "text": "Approach: " }, { "code": null, "e": 549, "s": 514, "text": "Create the Angular app to be used." }, { "code": null, "e": 647, "s": 549, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatDate." }, { "code": null, "e": 700, "s": 647, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 752, "s": 700, "text": "In app.component.ts import formatDate and LOCALE_ID" }, { "code": null, "e": 791, "s": 752, "text": "inject LOCALE_ID as a public variable." }, { "code": null, "e": 864, "s": 791, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 920, "s": 864, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 931, "s": 920, "text": "Example 1:" }, { "code": null, "e": 948, "s": 931, "text": "app.component.ts" }, { "code": "import { formatDate } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate(\"02-feburary-0202\", 'dd-MM-yyyy' ,this.locale);constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 1284, "s": 948, "text": null }, { "code": null, "e": 1303, "s": 1284, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Date is : {{curr}}</p>", "e": 1362, "s": 1303, "text": null }, { "code": null, "e": 1370, "s": 1362, "text": "Output:" }, { "code": null, "e": 1381, "s": 1370, "text": "Example 2:" }, { "code": null, "e": 1398, "s": 1381, "text": "app.component.ts" }, { "code": "import { formatDate } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate(\"03-march-0303\", 'yyyy-dd-MM' ,this.locale);constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 1731, "s": 1398, "text": null }, { "code": null, "e": 1750, "s": 1731, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Date is : {{curr}}</p>", "e": 1809, "s": 1750, "text": null }, { "code": null, "e": 1817, "s": 1809, "text": "Output:" }, { "code": null, "e": 1869, "s": 1817, "text": "Reference: https://angular.io/api/common/formatDate" }, { "code": null, "e": 1879, "s": 1869, "text": "Angular10" }, { "code": null, "e": 1898, "s": 1879, "text": "AngularJS-Function" }, { "code": null, "e": 1908, "s": 1898, "text": "AngularJS" }, { "code": null, "e": 1925, "s": 1908, "text": "Web Technologies" } ]
Nth Even Fibonacci Number
07 Jan, 2022 Given a value n, find the n’th even Fibonacci Number.Examples : Input : n = 3 Output : 34 Input : n = 4 Output : 144 Input : n = 7 Output : 10946 The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... where any number in sequence is given by: Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. The even number Fibonacci sequence is, 0, 2, 8, 34, 144, 610, 2584.... We need to find n’th number in this sequence.If we take a closer look at Fibonacci sequence, we can notice that every third number in sequence is even and the sequence of even numbers follow following recursive formula. Recurrence for Even Fibonacci sequence is: EFn = 4EFn-1 + EFn-2 with seed values EF0 = 0 and EF1 = 2. EFn represents n'th term in Even Fibonacci sequence. How does above formula work? Let us take a look original Fibonacci Formula and write it in the form of Fn-3 and Fn-6 because of the fact that every third Fibonacci number is even. Fn = Fn-1 + Fn-2 [Expanding both terms] = Fn-2 + Fn-3 + Fn-3 + Fn-4 = Fn-2 + 2Fn-3 + Fn-4 [Expanding first term] = Fn-3 + Fn-4 + 2Fn-3 + Fn-4 = 3Fn-3 + 2Fn-4 [Expanding one Fn-4] = 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Combing Fn-4 and Fn-5] = 4Fn-3 + Fn-6 Since every third Fibonacci Number is even, So if Fn is even then Fn-3 is even and Fn-6 is also even. Let Fn be xth even element and mark it as EFx. If Fn is EFx, then Fn-3 is previous even number i.e. EFx-1 and Fn-6 is previous of EFx-1 i.e. EFx-2 So Fn = 4Fn-3 + Fn-6 which means, EFx = 4EFx-1 + EFx-2 C++ Java Python3 C# PHP Javascript // C++ code to find Even Fibonacci//Series using normal Recursion#include<iostream>using namespace std; // Function which return//nth even fibonacci numberlong int evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codeint main (){ int n = 7; cout << evenFib(n); return 0;} // Java code to find Even Fibonacci// Series using normal Recursion class GFG{ // Function which return// nth even fibonacci numberstatic long evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codepublic static void main (String[] args){ int n = 7; System.out.println(evenFib(n));}} // This code is contributed by// Smitha Dinesh Semwal # Python3 code to find Even Fibonacci# Series using normal Recursion # Function which return#nth even fibonacci numberdef evenFib(n) : if (n < 1) : return n if (n == 1) : return 2 # calculation of # Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2)) # Driver Coden = 7print(evenFib(n)) # This code is contributed by Nikita Tiwari. // C# code to find Even Fibonacci// Series using normal Recursionusing System; class GFG { // Function which return// nth even fibonacci numberstatic long evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n - 1)) + evenFib(n - 2));} // Driver codepublic static void Main (){ int n = 7; Console.Write(evenFib(n));}} // This code is contributed by Nitin Mittal. <?php// PHP code to find Even Fibonacci// Series using normal Recursion // Function which return// nth even fibonacci numberfunction evenFib($n){ if ($n < 1) return $n; if ($n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib($n-1)) + evenFib($n-2));} // Driver Code$n = 7;echo(evenFib($n)); // This code is contributed by Ajit.?> <script>// Javascript code to find Even Fibonacci// Series using normal Recursion // Function which return// nth even fibonacci numberfunction evenFib(n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codelet n = 7;document.write(evenFib(n)); // This code is contributed by _saurabh_jaiswal.</script> Output : 10946 Time complexity of above implementation is exponential. We can do it in linear time using Dynamic Programming. We can also do it in O(Log n) time using the fact EFn = F3n. Note that we can find n’th Fibonacci number in O(Log n) time (Please see Methods 5 and 6 here). This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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 _saurabh_jaiswal sagar0719kumar sweetyty sumitgumber28 Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jan, 2022" }, { "code": null, "e": 118, "s": 52, "text": "Given a value n, find the n’th even Fibonacci Number.Examples : " }, { "code": null, "e": 206, "s": 118, "text": "Input : n = 3\nOutput : 34\n\nInput : n = 4\nOutput : 144\n\nInput : n = 7\nOutput : 10946" }, { "code": null, "e": 374, "s": 206, "text": "The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... where any number in sequence is given by: " }, { "code": null, "e": 441, "s": 374, "text": " Fn = Fn-1 + Fn-2 \n with seed values\n F0 = 0 and F1 = 1." }, { "code": null, "e": 736, "s": 443, "text": "The even number Fibonacci sequence is, 0, 2, 8, 34, 144, 610, 2584.... We need to find n’th number in this sequence.If we take a closer look at Fibonacci sequence, we can notice that every third number in sequence is even and the sequence of even numbers follow following recursive formula. " }, { "code": null, "e": 902, "s": 736, "text": "Recurrence for Even Fibonacci sequence is:\n EFn = 4EFn-1 + EFn-2\nwith seed values\n EF0 = 0 and EF1 = 2.\n\nEFn represents n'th term in Even Fibonacci sequence." }, { "code": null, "e": 1083, "s": 902, "text": "How does above formula work? Let us take a look original Fibonacci Formula and write it in the form of Fn-3 and Fn-6 because of the fact that every third Fibonacci number is even. " }, { "code": null, "e": 1658, "s": 1083, "text": "Fn = Fn-1 + Fn-2 [Expanding both terms]\n = Fn-2 + Fn-3 + Fn-3 + Fn-4 \n = Fn-2 + 2Fn-3 + Fn-4 [Expanding first term]\n = Fn-3 + Fn-4 + 2Fn-3 + Fn-4\n = 3Fn-3 + 2Fn-4 [Expanding one Fn-4]\n = 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Combing Fn-4 and Fn-5]\n = 4Fn-3 + Fn-6 \n\nSince every third Fibonacci Number is even, So if Fn is \neven then Fn-3 is even and Fn-6 is also even. Let Fn be\nxth even element and mark it as EFx.\nIf Fn is EFx, then Fn-3 is previous even number i.e. EFx-1\nand Fn-6 is previous of EFx-1 i.e. EFx-2\nSo\nFn = 4Fn-3 + Fn-6\nwhich means,\nEFx = 4EFx-1 + EFx-2" }, { "code": null, "e": 1664, "s": 1660, "text": "C++" }, { "code": null, "e": 1669, "s": 1664, "text": "Java" }, { "code": null, "e": 1677, "s": 1669, "text": "Python3" }, { "code": null, "e": 1680, "s": 1677, "text": "C#" }, { "code": null, "e": 1684, "s": 1680, "text": "PHP" }, { "code": null, "e": 1695, "s": 1684, "text": "Javascript" }, { "code": "// C++ code to find Even Fibonacci//Series using normal Recursion#include<iostream>using namespace std; // Function which return//nth even fibonacci numberlong int evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codeint main (){ int n = 7; cout << evenFib(n); return 0;}", "e": 2117, "s": 1695, "text": null }, { "code": "// Java code to find Even Fibonacci// Series using normal Recursion class GFG{ // Function which return// nth even fibonacci numberstatic long evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codepublic static void main (String[] args){ int n = 7; System.out.println(evenFib(n));}} // This code is contributed by// Smitha Dinesh Semwal", "e": 2606, "s": 2117, "text": null }, { "code": "# Python3 code to find Even Fibonacci# Series using normal Recursion # Function which return#nth even fibonacci numberdef evenFib(n) : if (n < 1) : return n if (n == 1) : return 2 # calculation of # Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2)) # Driver Coden = 7print(evenFib(n)) # This code is contributed by Nikita Tiwari.", "e": 2987, "s": 2606, "text": null }, { "code": "// C# code to find Even Fibonacci// Series using normal Recursionusing System; class GFG { // Function which return// nth even fibonacci numberstatic long evenFib(int n){ if (n < 1) return n; if (n == 1) return 2; // calculation of Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n - 1)) + evenFib(n - 2));} // Driver codepublic static void Main (){ int n = 7; Console.Write(evenFib(n));}} // This code is contributed by Nitin Mittal.", "e": 3458, "s": 2987, "text": null }, { "code": "<?php// PHP code to find Even Fibonacci// Series using normal Recursion // Function which return// nth even fibonacci numberfunction evenFib($n){ if ($n < 1) return $n; if ($n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib($n-1)) + evenFib($n-2));} // Driver Code$n = 7;echo(evenFib($n)); // This code is contributed by Ajit.?>", "e": 3864, "s": 3458, "text": null }, { "code": "<script>// Javascript code to find Even Fibonacci// Series using normal Recursion // Function which return// nth even fibonacci numberfunction evenFib(n){ if (n < 1) return n; if (n == 1) return 2; // calculation of // Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2));} // Driver Codelet n = 7;document.write(evenFib(n)); // This code is contributed by _saurabh_jaiswal.</script>", "e": 4305, "s": 3864, "text": null }, { "code": null, "e": 4315, "s": 4305, "text": "Output : " }, { "code": null, "e": 4321, "s": 4315, "text": "10946" }, { "code": null, "e": 5024, "s": 4321, "text": "Time complexity of above implementation is exponential. We can do it in linear time using Dynamic Programming. We can also do it in O(Log n) time using the fact EFn = F3n. Note that we can find n’th Fibonacci number in O(Log n) time (Please see Methods 5 and 6 here). This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 5037, "s": 5024, "text": "nitin mittal" }, { "code": null, "e": 5043, "s": 5037, "text": "jit_t" }, { "code": null, "e": 5060, "s": 5043, "text": "_saurabh_jaiswal" }, { "code": null, "e": 5075, "s": 5060, "text": "sagar0719kumar" }, { "code": null, "e": 5084, "s": 5075, "text": "sweetyty" }, { "code": null, "e": 5098, "s": 5084, "text": "sumitgumber28" }, { "code": null, "e": 5108, "s": 5098, "text": "Fibonacci" }, { "code": null, "e": 5121, "s": 5108, "text": "Mathematical" }, { "code": null, "e": 5134, "s": 5121, "text": "Mathematical" }, { "code": null, "e": 5144, "s": 5134, "text": "Fibonacci" }, { "code": null, "e": 5242, "s": 5144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5272, "s": 5242, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5315, "s": 5272, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5375, "s": 5315, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5390, "s": 5375, "text": "C++ Data Types" }, { "code": null, "e": 5414, "s": 5390, "text": "Merge two sorted arrays" }, { "code": null, "e": 5433, "s": 5414, "text": "Coin Change | DP-7" }, { "code": null, "e": 5454, "s": 5433, "text": "Operators in C / C++" }, { "code": null, "e": 5468, "s": 5454, "text": "Prime Numbers" }, { "code": null, "e": 5510, "s": 5468, "text": "Program to find GCD or HCF of two numbers" } ]
Python | os.mknod() method
08 Sep, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.mknod() method in Python is used to create a file system node i.e a file, device special file or named pipe with specified path name. Syntax: os.mknod(path, mode = 0o600, device = 0, *, dir_fd = None)Parameters: path: A path-like object representing the file system path. device (optional): This defines the newly created device files. The default value of this parameter is 0. dir_fd (optional): This is a file descriptor referring to a directory. Return type: This method does not return any value. Code: Use of os.mknod() method Python3 # Python3 program to explain os.mknod() method # importing os moduleimport os # importing stat moduleimport stat # Pathpath = "filex.txt" # Permission to useper = 0o600 # type of node to be creatednode_type = stat.S_IRUSRmode = per | node_type # Create a file system node# with specified permission# and type using# os.mknod() methodos.mknod(path, mode) print("Filesystem node is created successfully") File system node is created successfully avtarkumar719 python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 384, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.mknod() method in Python is used to create a file system node i.e a file, device special file or named pipe with specified path name. " }, { "code": null, "e": 753, "s": 384, "text": "Syntax: os.mknod(path, mode = 0o600, device = 0, *, dir_fd = None)Parameters: path: A path-like object representing the file system path. device (optional): This defines the newly created device files. The default value of this parameter is 0. dir_fd (optional): This is a file descriptor referring to a directory. Return type: This method does not return any value. " }, { "code": null, "e": 786, "s": 753, "text": "Code: Use of os.mknod() method " }, { "code": null, "e": 794, "s": 786, "text": "Python3" }, { "code": "# Python3 program to explain os.mknod() method # importing os moduleimport os # importing stat moduleimport stat # Pathpath = \"filex.txt\" # Permission to useper = 0o600 # type of node to be creatednode_type = stat.S_IRUSRmode = per | node_type # Create a file system node# with specified permission# and type using# os.mknod() methodos.mknod(path, mode) print(\"Filesystem node is created successfully\")", "e": 1198, "s": 794, "text": null }, { "code": null, "e": 1239, "s": 1198, "text": "File system node is created successfully" }, { "code": null, "e": 1255, "s": 1241, "text": "avtarkumar719" }, { "code": null, "e": 1272, "s": 1255, "text": "python-os-module" }, { "code": null, "e": 1279, "s": 1272, "text": "Python" } ]
What is the difference between HTTP_HOST and SERVER_NAME in PHP?
06 Sep, 2021 HTTP_HOST: It is fetched from HTTP request header obtained from the client request Example: Website: https://www.geeksforgeeks.org HTTP_HOST: www.geeksforgeeks.org HTTP_SERVER: It is fetched from the server name based on the host configuration. Example: Website: https://www.geeksforgeeks.org HTTP_SERVER: Display the server name Example of HTTP_HOST: <?php echo $_SERVER['HTTP_HOST']; ?> Output: It display the host name. Example of HTTP_SERVER: <?phpecho $_SERVER['SERVER_NAME'];?> Output: It display the server name. Note: In case of localhost, HOST and SERVER name both will same. kalrap615 Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP Split a comma delimited string into an array in PHP Download file from URL using PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? Comparing two dates in PHP Split a comma delimited string into an array in PHP How to fetch data from localserver database and display on HTML table using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2021" }, { "code": null, "e": 111, "s": 28, "text": "HTTP_HOST: It is fetched from HTTP request header obtained from the client request" }, { "code": null, "e": 120, "s": 111, "text": "Example:" }, { "code": null, "e": 193, "s": 120, "text": "Website: https://www.geeksforgeeks.org\nHTTP_HOST: www.geeksforgeeks.org\n" }, { "code": null, "e": 274, "s": 193, "text": "HTTP_SERVER: It is fetched from the server name based on the host configuration." }, { "code": null, "e": 283, "s": 274, "text": "Example:" }, { "code": null, "e": 360, "s": 283, "text": "Website: https://www.geeksforgeeks.org\nHTTP_SERVER: Display the server name\n" }, { "code": null, "e": 382, "s": 360, "text": "Example of HTTP_HOST:" }, { "code": "<?php echo $_SERVER['HTTP_HOST']; ?>", "e": 419, "s": 382, "text": null }, { "code": null, "e": 427, "s": 419, "text": "Output:" }, { "code": null, "e": 453, "s": 427, "text": "It display the host name." }, { "code": null, "e": 477, "s": 453, "text": "Example of HTTP_SERVER:" }, { "code": "<?phpecho $_SERVER['SERVER_NAME'];?>", "e": 514, "s": 477, "text": null }, { "code": null, "e": 522, "s": 514, "text": "Output:" }, { "code": null, "e": 550, "s": 522, "text": "It display the server name." }, { "code": null, "e": 615, "s": 550, "text": "Note: In case of localhost, HOST and SERVER name both will same." }, { "code": null, "e": 625, "s": 615, "text": "kalrap615" }, { "code": null, "e": 632, "s": 625, "text": "Picked" }, { "code": null, "e": 636, "s": 632, "text": "PHP" }, { "code": null, "e": 649, "s": 636, "text": "PHP Programs" }, { "code": null, "e": 666, "s": 649, "text": "Web Technologies" }, { "code": null, "e": 670, "s": 666, "text": "PHP" }, { "code": null, "e": 768, "s": 670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 808, "s": 768, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 853, "s": 808, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 880, "s": 853, "text": "Comparing two dates in PHP" }, { "code": null, "e": 932, "s": 880, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 965, "s": 932, "text": "Download file from URL using PHP" }, { "code": null, "e": 1005, "s": 965, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1057, "s": 1005, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 1084, "s": 1057, "text": "Comparing two dates in PHP" }, { "code": null, "e": 1136, "s": 1084, "text": "Split a comma delimited string into an array in PHP" } ]
Ruby | Array class join() function
31 May, 2021 join() is an Array class method which returns the string which is created by converting each element of the array to a string, separated by the given separator. Syntax: Array.join()Parameter: Array separatorReturn: join value of the array elements Example #1: Ruby # Ruby code for join() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # joinputs "join : #{a.join("4")}\n\n" # joinputs "join : #{b.join('-')}\n\n" # joinputs "join : #{c.join("*")}\n\n" Output : join : 1842243344546 join : 1-4-1-1-88-9 join : 18*22***50*6 Example #2: Ruby # Ruby code for join() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # joinputs "join : #{a.join("4")}\n\n" # joinputs "join : #{b.join('-')}\n\n" # joinputs "join : #{c.join("*")}\n\n" Output : join : abc4nil4dog join : cow--dog join : cat** anikakapoor Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2021" }, { "code": null, "e": 190, "s": 28, "text": "join() is an Array class method which returns the string which is created by converting each element of the array to a string, separated by the given separator. " }, { "code": null, "e": 277, "s": 190, "text": "Syntax: Array.join()Parameter: Array separatorReturn: join value of the array elements" }, { "code": null, "e": 290, "s": 277, "text": "Example #1: " }, { "code": null, "e": 295, "s": 290, "text": "Ruby" }, { "code": "# Ruby code for join() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # joinputs \"join : #{a.join(\"4\")}\\n\\n\" # joinputs \"join : #{b.join('-')}\\n\\n\" # joinputs \"join : #{c.join(\"*\")}\\n\\n\"", "e": 575, "s": 295, "text": null }, { "code": null, "e": 586, "s": 575, "text": "Output : " }, { "code": null, "e": 649, "s": 586, "text": "join : 1842243344546\n\njoin : 1-4-1-1-88-9\n\njoin : 18*22***50*6" }, { "code": null, "e": 663, "s": 649, "text": "Example #2: " }, { "code": null, "e": 668, "s": 663, "text": "Ruby" }, { "code": "# Ruby code for join() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayb = [\"cow\", nil, \"dog\"] # declaring arrayc = [\"cat\", nil, nil] # joinputs \"join : #{a.join(\"4\")}\\n\\n\" # joinputs \"join : #{b.join('-')}\\n\\n\" # joinputs \"join : #{c.join(\"*\")}\\n\\n\"", "e": 938, "s": 668, "text": null }, { "code": null, "e": 949, "s": 938, "text": "Output : " }, { "code": null, "e": 999, "s": 949, "text": "join : abc4nil4dog\n\njoin : cow--dog\n\njoin : cat**" }, { "code": null, "e": 1013, "s": 1001, "text": "anikakapoor" }, { "code": null, "e": 1030, "s": 1013, "text": "Ruby Array-class" }, { "code": null, "e": 1043, "s": 1030, "text": "Ruby-Methods" }, { "code": null, "e": 1048, "s": 1043, "text": "Ruby" } ]
How to Find Out File Types in Linux
23 Aug, 2021 In Linux, everything is considered as a file. In UNIX, seven standard file types are regular, directory, symbolic link, FIFO special, block special, character special, and socket. In Linux/UNIX, we have to deal with different file types to manage them efficiently. In Linux/UNIX, Files are mainly categorized into 3 parts: Regular FilesDirectory FilesSpecial Files Regular Files Directory Files Special Files The easiest way to find out file type in any operating system is by looking at its extension such as .txt, .sh, .py, etc. If the file doesn’t have an extension then in Linux we can use file utility. In this article, we will demonstrate file command examples to determine a file type in Linux. To find out file types we can use the file command. Syntax: file [OPTION...] [FILE...] You can run the following command to verify the version of the file utility: file -v We can test a file type by typing the following command: file file.txt We can pass a list of files in one file and we can specify using the -f option as shown below: cat file.txt file -f file.txt Using the -s option we can read the block or character special file. file -s /dev/sda Using -b option will not prepend filenames to output lines file -f GFG.txt Using -F option will use string as separator instead of “:”. file -F '#' GFG.txt Using -L option will follow symlinks (default if POSIXLY_CORRECT is set): file -L stdin We can use the –extension option to print a slash-separated list of valid extensions for the file type found. file --extension GFG.rar For more information and usage options, you can use the following command: man file We can also use ls command to determine a type of file. Syntax: ls [OPTION]... [FILE]... The following table shows the types of files in Linux and what will be output using ls and file command Regular files are ordinary files on a system that contains programs, texts, or data. It is used to store information such as text, or images. These files are located in a directory/folder. Regular files contain all readable files such as text files, Docx files, programming files, etc, Binary files, image files such as JPG, PNG, SVG, etc, compressed files such as ZIP, RAR, etc. Example: Or we can use the “file *” command to find out the file type The sole job of directory files is to store the other regular files, directory files, and special files and their related information. This type of file will be denoted in blue color with links greater than or equal to 2. A directory file contains an entry for every file and sub-directory that it houses. If we have 10 files in a directory, we will have 10 entries in the directory file. We can navigate between directories using the cd command We can find out directory file by using the following command: ls -l | grep ^d We can also use the file * command Block files act as a direct interface to block devices hence they are also called block devices. A block device is any device that performs data Input and Output operations in units of blocks. These files are hardware files and most of them are present in /dev. We can find out block file by using the following command: ls -l | grep ^b We can use the file command also: A character file is a hardware file that reads/writes data in character by character in a file. These files provide a serial stream of input or output and provide direct access to hardware devices. The terminal, serial ports, etc are examples of this type of file. We can find out character device files by: ls -l | grep ^c We can use the file command to find out the type of file: The other name of pipe is a “named” pipe, which is sometimes called a FIFO. FIFO stands for “First In, First Out” and refers to the property that the order of bytes going in is the same coming out. The “name” of a named pipe is actually a file name within the file system. This file sends data from one process to another so that the receiving process reads the data first-in-first-out manner. We can find out pipe file by using the following command: ls -l | grep ^p We can use the file command to find out file type: A symbol link file is a type of file in Linux which points to another file or a folder on your device. Symbol link files are also called Symlink and are similar to shortcuts in Windows. We can find out Symbol link file by using the following command: ls -l | grep ^l We can use the file command to find out file type: A socket is a special file that is used to pass information between applications and enables the communication between two processes. We can create a socket file using the socket() system call. A socket file is located in /dev of the root folder or you can use the find / -type s command to find socket files. find / -type s We can find out Symbol link file by using the following command: ls -l | grep ^s We can use the file command to find out file type: linux-command Linux-file-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2021" }, { "code": null, "e": 317, "s": 52, "text": "In Linux, everything is considered as a file. In UNIX, seven standard file types are regular, directory, symbolic link, FIFO special, block special, character special, and socket. In Linux/UNIX, we have to deal with different file types to manage them efficiently." }, { "code": null, "e": 375, "s": 317, "text": "In Linux/UNIX, Files are mainly categorized into 3 parts:" }, { "code": null, "e": 417, "s": 375, "text": "Regular FilesDirectory FilesSpecial Files" }, { "code": null, "e": 431, "s": 417, "text": "Regular Files" }, { "code": null, "e": 447, "s": 431, "text": "Directory Files" }, { "code": null, "e": 461, "s": 447, "text": "Special Files" }, { "code": null, "e": 756, "s": 461, "text": "The easiest way to find out file type in any operating system is by looking at its extension such as .txt, .sh, .py, etc. If the file doesn’t have an extension then in Linux we can use file utility. In this article, we will demonstrate file command examples to determine a file type in Linux. " }, { "code": null, "e": 808, "s": 756, "text": "To find out file types we can use the file command." }, { "code": null, "e": 843, "s": 808, "text": "Syntax: file [OPTION...] [FILE...]" }, { "code": null, "e": 920, "s": 843, "text": "You can run the following command to verify the version of the file utility:" }, { "code": null, "e": 928, "s": 920, "text": "file -v" }, { "code": null, "e": 985, "s": 928, "text": "We can test a file type by typing the following command:" }, { "code": null, "e": 999, "s": 985, "text": "file file.txt" }, { "code": null, "e": 1094, "s": 999, "text": "We can pass a list of files in one file and we can specify using the -f option as shown below:" }, { "code": null, "e": 1124, "s": 1094, "text": "cat file.txt\nfile -f file.txt" }, { "code": null, "e": 1194, "s": 1124, "text": "Using the -s option we can read the block or character special file. " }, { "code": null, "e": 1211, "s": 1194, "text": "file -s /dev/sda" }, { "code": null, "e": 1270, "s": 1211, "text": "Using -b option will not prepend filenames to output lines" }, { "code": null, "e": 1286, "s": 1270, "text": "file -f GFG.txt" }, { "code": null, "e": 1347, "s": 1286, "text": "Using -F option will use string as separator instead of “:”." }, { "code": null, "e": 1367, "s": 1347, "text": "file -F '#' GFG.txt" }, { "code": null, "e": 1441, "s": 1367, "text": "Using -L option will follow symlinks (default if POSIXLY_CORRECT is set):" }, { "code": null, "e": 1455, "s": 1441, "text": "file -L stdin" }, { "code": null, "e": 1565, "s": 1455, "text": "We can use the –extension option to print a slash-separated list of valid extensions for the file type found." }, { "code": null, "e": 1590, "s": 1565, "text": "file --extension GFG.rar" }, { "code": null, "e": 1665, "s": 1590, "text": "For more information and usage options, you can use the following command:" }, { "code": null, "e": 1674, "s": 1665, "text": "man file" }, { "code": null, "e": 1730, "s": 1674, "text": "We can also use ls command to determine a type of file." }, { "code": null, "e": 1738, "s": 1730, "text": "Syntax:" }, { "code": null, "e": 1763, "s": 1738, "text": "ls [OPTION]... [FILE]..." }, { "code": null, "e": 1867, "s": 1763, "text": "The following table shows the types of files in Linux and what will be output using ls and file command" }, { "code": null, "e": 2248, "s": 1867, "text": "Regular files are ordinary files on a system that contains programs, texts, or data. It is used to store information such as text, or images. These files are located in a directory/folder. Regular files contain all readable files such as text files, Docx files, programming files, etc, Binary files, image files such as JPG, PNG, SVG, etc, compressed files such as ZIP, RAR, etc. " }, { "code": null, "e": 2257, "s": 2248, "text": "Example:" }, { "code": null, "e": 2318, "s": 2257, "text": "Or we can use the “file *” command to find out the file type" }, { "code": null, "e": 2764, "s": 2318, "text": "The sole job of directory files is to store the other regular files, directory files, and special files and their related information. This type of file will be denoted in blue color with links greater than or equal to 2. A directory file contains an entry for every file and sub-directory that it houses. If we have 10 files in a directory, we will have 10 entries in the directory file. We can navigate between directories using the cd command" }, { "code": null, "e": 2827, "s": 2764, "text": "We can find out directory file by using the following command:" }, { "code": null, "e": 2844, "s": 2827, "text": "ls -l | grep ^d " }, { "code": null, "e": 2879, "s": 2844, "text": "We can also use the file * command" }, { "code": null, "e": 3143, "s": 2879, "text": "Block files act as a direct interface to block devices hence they are also called block devices. A block device is any device that performs data Input and Output operations in units of blocks. These files are hardware files and most of them are present in /dev. " }, { "code": null, "e": 3202, "s": 3143, "text": "We can find out block file by using the following command:" }, { "code": null, "e": 3218, "s": 3202, "text": "ls -l | grep ^b" }, { "code": null, "e": 3252, "s": 3218, "text": "We can use the file command also:" }, { "code": null, "e": 3517, "s": 3252, "text": "A character file is a hardware file that reads/writes data in character by character in a file. These files provide a serial stream of input or output and provide direct access to hardware devices. The terminal, serial ports, etc are examples of this type of file." }, { "code": null, "e": 3560, "s": 3517, "text": "We can find out character device files by:" }, { "code": null, "e": 3576, "s": 3560, "text": "ls -l | grep ^c" }, { "code": null, "e": 3634, "s": 3576, "text": "We can use the file command to find out the type of file:" }, { "code": null, "e": 4028, "s": 3634, "text": "The other name of pipe is a “named” pipe, which is sometimes called a FIFO. FIFO stands for “First In, First Out” and refers to the property that the order of bytes going in is the same coming out. The “name” of a named pipe is actually a file name within the file system. This file sends data from one process to another so that the receiving process reads the data first-in-first-out manner." }, { "code": null, "e": 4086, "s": 4028, "text": "We can find out pipe file by using the following command:" }, { "code": null, "e": 4102, "s": 4086, "text": "ls -l | grep ^p" }, { "code": null, "e": 4153, "s": 4102, "text": "We can use the file command to find out file type:" }, { "code": null, "e": 4340, "s": 4153, "text": "A symbol link file is a type of file in Linux which points to another file or a folder on your device. Symbol link files are also called Symlink and are similar to shortcuts in Windows. " }, { "code": null, "e": 4405, "s": 4340, "text": "We can find out Symbol link file by using the following command:" }, { "code": null, "e": 4421, "s": 4405, "text": "ls -l | grep ^l" }, { "code": null, "e": 4472, "s": 4421, "text": "We can use the file command to find out file type:" }, { "code": null, "e": 4782, "s": 4472, "text": "A socket is a special file that is used to pass information between applications and enables the communication between two processes. We can create a socket file using the socket() system call. A socket file is located in /dev of the root folder or you can use the find / -type s command to find socket files." }, { "code": null, "e": 4798, "s": 4782, "text": "find / -type s " }, { "code": null, "e": 4863, "s": 4798, "text": "We can find out Symbol link file by using the following command:" }, { "code": null, "e": 4879, "s": 4863, "text": "ls -l | grep ^s" }, { "code": null, "e": 4930, "s": 4879, "text": "We can use the file command to find out file type:" }, { "code": null, "e": 4944, "s": 4930, "text": "linux-command" }, { "code": null, "e": 4964, "s": 4944, "text": "Linux-file-commands" }, { "code": null, "e": 4971, "s": 4964, "text": "Picked" }, { "code": null, "e": 4982, "s": 4971, "text": "Linux-Unix" }, { "code": null, "e": 5080, "s": 4982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5106, "s": 5080, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5141, "s": 5106, "text": "scp command in Linux with Examples" }, { "code": null, "e": 5178, "s": 5141, "text": "chown command in Linux with Examples" }, { "code": null, "e": 5207, "s": 5178, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 5244, "s": 5207, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 5278, "s": 5244, "text": "mv command in Linux with examples" }, { "code": null, "e": 5315, "s": 5278, "text": "chmod command in Linux with examples" }, { "code": null, "e": 5355, "s": 5315, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 5394, "s": 5355, "text": "Introduction to Linux Operating System" } ]
Splay Tree | Set 2 (Insert)
11 Aug, 2021 It is recommended to refer following post as prerequisite of this post.Splay Tree | Set 1 (Search)As discussed in the previous post, Splay tree is a self-balancing data structure where the last accessed key is always at root. The insert operation is similar to Binary Search Tree insert with additional steps to make sure that the newly inserted key becomes the new root.Following are different cases to insert a key k in splay tree.1) Root is NULL: We simply allocate a new node and return it as root.2) Splay the given key k. If k is already present, then it becomes the new root. If not present, then last accessed leaf node becomes the new root.3) If new root’s key is same as k, don’t do anything as k is already present.4) Else allocate memory for new node and compare root’s key with k. .......4.a) If k is smaller than root’s key, make root as right child of new node, copy left child of root as left child of new node and make left child of root as NULL. .......4.b) If k is greater than root’s key, make root as left child of new node, copy right child of root as right child of new node and make right child of root as NULL.5) Return new node as new root of tree.Example: 100 [20] 25 / \ \ / \ 50 200 50 20 50 / insert(25) / \ insert(25) / \ 40 ======> 30 100 ========> 30 100 / 1. Splay(25) \ \ 2. insert 25 \ \ 30 40 200 40 200 / [20] C++ C Java C# Javascript #include <bits/stdc++.h>using namespace std; // An AVL tree nodeclass node{ public: int key; node *left, *right;}; /* Helper function that allocatesa new node with the given key and NULL left and right pointers. */node* newNode(int key){ node* Node = new node(); Node->key = key; Node->left = Node->right = NULL; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.node *rightRotate(node *x){ node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.node *leftRotate(node *x){ node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootnode *splay(node *root, int key){ // Base cases: root is NULL or // key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the // key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zig-Zag (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // Function to insert a new key k// in splay tree with given rootnode *insert(node *root, int k){ // Simple Case: If tree is empty if (root == NULL) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root->key == k) return root; // Otherwise allocate memory for new node node *newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root->key > k) { newnode->right = root; newnode->left = root->left; root->left = NULL; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode->left = root; newnode->right = root->right; root->right = NULL; } return newnode; // newnode becomes new root} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(node *root){ if (root != NULL) { cout<<root->key<<" "; preOrder(root->left); preOrder(root->right); }} /* Driver code*/int main(){ node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = insert(root, 25); cout<<"Preorder traversal of the modified Splay tree is \n"; preOrder(root); return 0;} // This code is contributed by rathbhupendra // This code is adopted from http://algs4.cs.princeton.edu/33balanced/SplayBST.java.html#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct node{ int key; struct node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = node->right = NULL; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node *rightRotate(struct node *x){ struct node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node *leftRotate(struct node *x){ struct node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at root if key is present in tree.// If key is not present, then it brings the last accessed item at// root. This function modifies the tree and returns the new rootstruct node *splay(struct node *root, int key){ // Base cases: root is NULL or key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zig-Zag (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // Function to insert a new key k in splay tree with given rootstruct node *insert(struct node *root, int k){ // Simple Case: If tree is empty if (root == NULL) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root->key == k) return root; // Otherwise allocate memory for new node struct node *newnode = newNode(k); // If root's key is greater, make root as right child // of newnode and copy the left child of root to newnode if (root->key > k) { newnode->right = root; newnode->left = root->left; root->left = NULL; } // If root's key is smaller, make root as left child // of newnode and copy the right child of root to newnode else { newnode->left = root; newnode->right = root->right; root->right = NULL; } return newnode; // newnode becomes new root} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node *root){ if (root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = insert(root, 25); printf("Preorder traversal of the modified Splay tree is \n"); preOrder(root); return 0;} import java.util.*; class GFG{ // An AVL tree nodestatic class node{ int key; node left, right;}; /* Helper function that allocatesa new node with the given key and null left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null)? root: leftRotate(root); }} // Function to insert a new key k// in splay tree with given rootstatic node insert(node root, int k){ // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node node newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { System.out.print(root.key+" "); preOrder(root.left); preOrder(root.right); }} /* Driver code*/public static void main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); System.out.print("Preorder traversal of the modified Splay tree is \n"); preOrder(root);}} // This code is contributed by Rajput-Ji using System; public class node{ public int key; public node left, right; } public class GFG{ /* Helper function that allocatesa new node with the given key and null left and right pointers. */ static node newNode(int key) { node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. static node rightRotate(node x) { node y = x.left; x.left = y.right; y.right = x; return y; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; x.right = y.left; y.left = x; return y; } // This function brings the key at // root if key is present in tree. // If key is not present, then it // brings the last accessed item at // root. This function modifies the // tree and returns the new root static node splay(node root, int key) { // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null)? root: leftRotate(root); } } // Function to insert a new key k // in splay tree with given root static node insert(node root, int k) { // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node node newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root } // A utility function to print // preorder traversal of the tree. // The function also prints height of every node static void preOrder(node root) { if (root != null) { Console.Write(root.key+" "); preOrder(root.left); preOrder(root.right); } } /* Driver code*/ static public void Main () { node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); Console.Write("Preorder traversal of the modified Splay tree is \n"); preOrder(root); }} // This code is contributed by patel2127. <script> // An AVL tree node class Node { constructor(val) { this.key = val; this.left = null; this.right = null; } } /* Helper function that allocates a new node with the given key and null left and right pointers. */ function newNode(key) { var node = new Node(); node.key = key; node.left = node.right = null; return (node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. function rightRotate( x) { var y = x.left; x.left = y.right; y.right = x; return y; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. function leftRotate( x) { var y = x.right; x.right = y.left; y.left = x; return y; } // This function brings the key at // root if key is present in tree. // If key is not present, then it // brings the last accessed item at // root. This function modifies the // tree and returns the new root function splay( root , key) { // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); } } // Function to insert a new key k // in splay tree with given root function insert( root , k) { // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node var newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root } // A utility function to print // preorder traversal of the tree. // The function also prints height of every node function preOrder( root) { if (root != null) { document.write(root.key + " "); preOrder(root.left); preOrder(root.right); } } /* Driver code */ var root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); document.write( "Preorder traversal of the modified Splay tree is <br/>" ); preOrder(root); // This code contributed by umadevi9616 </script> Output: Preorder traversal of the modified Splay tree is 25 20 50 30 40 100 200 This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rathbhupendra Akanksha_Rai Rajput-Ji umadevi9616 patel2127 Self-Balancing-BST splay-tree Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Red-Black Tree | Set 1 (Introduction) Agents in Artificial Intelligence Decision Tree Introduction with example Count of strings whose prefix match with the given string to a given length k Binary Indexed Tree or Fenwick Tree Ordered Set and GNU C++ PBDS
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Aug, 2021" }, { "code": null, "e": 1239, "s": 54, "text": "It is recommended to refer following post as prerequisite of this post.Splay Tree | Set 1 (Search)As discussed in the previous post, Splay tree is a self-balancing data structure where the last accessed key is always at root. The insert operation is similar to Binary Search Tree insert with additional steps to make sure that the newly inserted key becomes the new root.Following are different cases to insert a key k in splay tree.1) Root is NULL: We simply allocate a new node and return it as root.2) Splay the given key k. If k is already present, then it becomes the new root. If not present, then last accessed leaf node becomes the new root.3) If new root’s key is same as k, don’t do anything as k is already present.4) Else allocate memory for new node and compare root’s key with k. .......4.a) If k is smaller than root’s key, make root as right child of new node, copy left child of root as left child of new node and make left child of root as NULL. .......4.b) If k is greater than root’s key, make root as left child of new node, copy right child of root as right child of new node and make right child of root as NULL.5) Return new node as new root of tree.Example: " }, { "code": null, "e": 1823, "s": 1239, "text": " \n 100 [20] 25 \n / \\ \\ / \\\n 50 200 50 20 50 \n / insert(25) / \\ insert(25) / \\ \n 40 ======> 30 100 ========> 30 100 \n / 1. Splay(25) \\ \\ 2. insert 25 \\ \\\n 30 40 200 40 200 \n / \n [20] " }, { "code": null, "e": 1829, "s": 1825, "text": "C++" }, { "code": null, "e": 1831, "s": 1829, "text": "C" }, { "code": null, "e": 1836, "s": 1831, "text": "Java" }, { "code": null, "e": 1839, "s": 1836, "text": "C#" }, { "code": null, "e": 1850, "s": 1839, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // An AVL tree nodeclass node{ public: int key; node *left, *right;}; /* Helper function that allocatesa new node with the given key and NULL left and right pointers. */node* newNode(int key){ node* Node = new node(); Node->key = key; Node->left = Node->right = NULL; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.node *rightRotate(node *x){ node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.node *leftRotate(node *x){ node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootnode *splay(node *root, int key){ // Base cases: root is NULL or // key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the // key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zig-Zag (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // Function to insert a new key k// in splay tree with given rootnode *insert(node *root, int k){ // Simple Case: If tree is empty if (root == NULL) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root->key == k) return root; // Otherwise allocate memory for new node node *newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root->key > k) { newnode->right = root; newnode->left = root->left; root->left = NULL; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode->left = root; newnode->right = root->right; root->right = NULL; } return newnode; // newnode becomes new root} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(node *root){ if (root != NULL) { cout<<root->key<<\" \"; preOrder(root->left); preOrder(root->right); }} /* Driver code*/int main(){ node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = insert(root, 25); cout<<\"Preorder traversal of the modified Splay tree is \\n\"; preOrder(root); return 0;} // This code is contributed by rathbhupendra", "e": 6376, "s": 1850, "text": null }, { "code": "// This code is adopted from http://algs4.cs.princeton.edu/33balanced/SplayBST.java.html#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct node{ int key; struct node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = node->right = NULL; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node *rightRotate(struct node *x){ struct node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node *leftRotate(struct node *x){ struct node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at root if key is present in tree.// If key is not present, then it brings the last accessed item at// root. This function modifies the tree and returns the new rootstruct node *splay(struct node *root, int key){ // Base cases: root is NULL or key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zig-Zag (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // Function to insert a new key k in splay tree with given rootstruct node *insert(struct node *root, int k){ // Simple Case: If tree is empty if (root == NULL) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root->key == k) return root; // Otherwise allocate memory for new node struct node *newnode = newNode(k); // If root's key is greater, make root as right child // of newnode and copy the left child of root to newnode if (root->key > k) { newnode->right = root; newnode->left = root->left; root->left = NULL; } // If root's key is smaller, make root as left child // of newnode and copy the right child of root to newnode else { newnode->left = root; newnode->right = root->right; root->right = NULL; } return newnode; // newnode becomes new root} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node *root){ if (root != NULL) { printf(\"%d \", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = insert(root, 25); printf(\"Preorder traversal of the modified Splay tree is \\n\"); preOrder(root); return 0;}", "e": 11020, "s": 6376, "text": null }, { "code": "import java.util.*; class GFG{ // An AVL tree nodestatic class node{ int key; node left, right;}; /* Helper function that allocatesa new node with the given key and null left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null)? root: leftRotate(root); }} // Function to insert a new key k// in splay tree with given rootstatic node insert(node root, int k){ // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node node newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { System.out.print(root.key+\" \"); preOrder(root.left); preOrder(root.right); }} /* Driver code*/public static void main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); System.out.print(\"Preorder traversal of the modified Splay tree is \\n\"); preOrder(root);}} // This code is contributed by Rajput-Ji", "e": 15519, "s": 11020, "text": null }, { "code": "using System; public class node{ public int key; public node left, right; } public class GFG{ /* Helper function that allocatesa new node with the given key and null left and right pointers. */ static node newNode(int key) { node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. static node rightRotate(node x) { node y = x.left; x.left = y.right; y.right = x; return y; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; x.right = y.left; y.left = x; return y; } // This function brings the key at // root if key is present in tree. // If key is not present, then it // brings the last accessed item at // root. This function modifies the // tree and returns the new root static node splay(node root, int key) { // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null)? root: leftRotate(root); } } // Function to insert a new key k // in splay tree with given root static node insert(node root, int k) { // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node node newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root } // A utility function to print // preorder traversal of the tree. // The function also prints height of every node static void preOrder(node root) { if (root != null) { Console.Write(root.key+\" \"); preOrder(root.left); preOrder(root.right); } } /* Driver code*/ static public void Main () { node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); Console.Write(\"Preorder traversal of the modified Splay tree is \\n\"); preOrder(root); }} // This code is contributed by patel2127.", "e": 19922, "s": 15519, "text": null }, { "code": "<script> // An AVL tree node class Node { constructor(val) { this.key = val; this.left = null; this.right = null; } } /* Helper function that allocates a new node with the given key and null left and right pointers. */ function newNode(key) { var node = new Node(); node.key = key; node.left = node.right = null; return (node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. function rightRotate( x) { var y = x.left; x.left = y.right; y.right = x; return y; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. function leftRotate( x) { var y = x.right; x.right = y.left; y.left = x; return y; } // This function brings the key at // root if key is present in tree. // If key is not present, then it // brings the last accessed item at // root. This function modifies the // tree and returns the new root function splay( root , key) { // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zig-Zag (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); } } // Function to insert a new key k // in splay tree with given root function insert( root , k) { // Simple Case: If tree is empty if (root == null) return newNode(k); // Bring the closest leaf node to root root = splay(root, k); // If key is already present, then return if (root.key == k) return root; // Otherwise allocate memory for new node var newnode = newNode(k); // If root's key is greater, make // root as right child of newnode // and copy the left child of root to newnode if (root.key > k) { newnode.right = root; newnode.left = root.left; root.left = null; } // If root's key is smaller, make // root as left child of newnode // and copy the right child of root to newnode else { newnode.left = root; newnode.right = root.right; root.right = null; } return newnode; // newnode becomes new root } // A utility function to print // preorder traversal of the tree. // The function also prints height of every node function preOrder( root) { if (root != null) { document.write(root.key + \" \"); preOrder(root.left); preOrder(root.right); } } /* Driver code */ var root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = insert(root, 25); document.write( \"Preorder traversal of the modified Splay tree is <br/>\" ); preOrder(root); // This code contributed by umadevi9616 </script>", "e": 24991, "s": 19922, "text": null }, { "code": null, "e": 25000, "s": 24991, "text": "Output: " }, { "code": null, "e": 25072, "s": 25000, "text": "Preorder traversal of the modified Splay tree is\n25 20 50 30 40 100 200" }, { "code": null, "e": 25238, "s": 25072, "text": "This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 25252, "s": 25238, "text": "rathbhupendra" }, { "code": null, "e": 25265, "s": 25252, "text": "Akanksha_Rai" }, { "code": null, "e": 25275, "s": 25265, "text": "Rajput-Ji" }, { "code": null, "e": 25287, "s": 25275, "text": "umadevi9616" }, { "code": null, "e": 25297, "s": 25287, "text": "patel2127" }, { "code": null, "e": 25316, "s": 25297, "text": "Self-Balancing-BST" }, { "code": null, "e": 25327, "s": 25316, "text": "splay-tree" }, { "code": null, "e": 25351, "s": 25327, "text": "Advanced Data Structure" }, { "code": null, "e": 25449, "s": 25351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25478, "s": 25449, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 25505, "s": 25478, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 25530, "s": 25505, "text": "LRU Cache Implementation" }, { "code": null, "e": 25553, "s": 25530, "text": "Introduction of B-Tree" }, { "code": null, "e": 25591, "s": 25553, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 25625, "s": 25591, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 25665, "s": 25625, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 25743, "s": 25665, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 25779, "s": 25743, "text": "Binary Indexed Tree or Fenwick Tree" } ]
React-Bootstrap Container, Row and Col Component
18 May, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. We can use the following approach in ReactJS to use the react-bootstrap Container, Row, Col Component. Container Component provides a way to center and horizontally pad the contents of our application. It is used when the user wants the responsive pixel width. Row Component provides a way to represent a row in the grid system. It is used when we want to display data in the form of rows. Col Component provides a way to represent a column in the grid system. It is used when we want to display data in the form of columns Container Props: as: It can be used as a custom element type for this component. fluid: It is used to allow the container to fill all of its horizontal space which is available. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Row Props: as: It can be used as a custom element type for this component. lg: It is used to denote the number of columns which will fit next to each other on large devices having resolution ≥ 992 pixels. md: It is used to denote the number of columns which will fit next to each other on medium devices having resolution ≥ 768 pixels. sm: It is used to denote the number of columns which will fit next to each other on small devices having resolution ≥ 576 pixels. xl: It is used to denote the number of columns which will fit next to each other on extra-large devices having resolution ≥ 1200 pixels. xs: It is used to denote the number of columns which will fit next to each other on extra-small devices having resolution < 576 pixels. noGutters: It is used to remove the gutter spacing between added negative margins and columns. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Col Props: as: It can be used as a custom element type for this component. lg: It is used to denote the number of columns to span on large devices having resolution ≥ 992 pixels. md: It is used to denote the number of columns to span on medium devices having resolution ≥ 768 pixels. sm: It is used to denote the number of columns to span on small devices having resolution ≥ 576 pixels. xl: It is used to denote the number of columns to span on extra-large devices having resolution ≥ 1200 pixels. xs: It is used to denote the number of columns to span on extra-small devices having resolution < 576 pixels. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Container Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Container from 'react-bootstrap/Container'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Container Component</h4> <Container style={{ backgroundColor: 'green' }} > <h3>Sample Text, Greetings from GeeksforGeeks</h3> </Container> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Row Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Row from 'react-bootstrap/Row'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Row Component</h4> <Row style={{ backgroundColor: 'red', }}> Sample First Row </Row> <Row style={{ backgroundColor: 'yellow', }}> Sample Second Row </Row> <Row style={{ backgroundColor: 'green', }}> Sample Third Row </Row> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Col from 'react-bootstrap/Col';import Row from 'react-bootstrap/Row'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Col Component</h4> <Row> <Col style={{ backgroundColor: 'red', }}> Sample First Col </Col> <Col style={{ backgroundColor: 'yellow', }}> Sample Second Col </Col> <Col style={{ backgroundColor: 'green', }}> Sample Third Col </Col> </Row> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/layout/grid/#container-props https://react-bootstrap.github.io/layout/grid/#row-props https://react-bootstrap.github.io/layout/grid/#col-props React-Bootstrap JavaScript ReactJS 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2021" }, { "code": null, "e": 213, "s": 28, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. We can use the following approach in ReactJS to use the react-bootstrap Container, Row, Col Component." }, { "code": null, "e": 372, "s": 213, "text": "Container Component provides a way to center and horizontally pad the contents of our application. It is used when the user wants the responsive pixel width. " }, { "code": null, "e": 501, "s": 372, "text": "Row Component provides a way to represent a row in the grid system. It is used when we want to display data in the form of rows." }, { "code": null, "e": 635, "s": 501, "text": "Col Component provides a way to represent a column in the grid system. It is used when we want to display data in the form of columns" }, { "code": null, "e": 652, "s": 635, "text": "Container Props:" }, { "code": null, "e": 716, "s": 652, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 813, "s": 716, "text": "fluid: It is used to allow the container to fill all of its horizontal space which is available." }, { "code": null, "e": 897, "s": 813, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 908, "s": 897, "text": "Row Props:" }, { "code": null, "e": 972, "s": 908, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1102, "s": 972, "text": "lg: It is used to denote the number of columns which will fit next to each other on large devices having resolution ≥ 992 pixels." }, { "code": null, "e": 1233, "s": 1102, "text": "md: It is used to denote the number of columns which will fit next to each other on medium devices having resolution ≥ 768 pixels." }, { "code": null, "e": 1363, "s": 1233, "text": "sm: It is used to denote the number of columns which will fit next to each other on small devices having resolution ≥ 576 pixels." }, { "code": null, "e": 1500, "s": 1363, "text": "xl: It is used to denote the number of columns which will fit next to each other on extra-large devices having resolution ≥ 1200 pixels." }, { "code": null, "e": 1636, "s": 1500, "text": "xs: It is used to denote the number of columns which will fit next to each other on extra-small devices having resolution < 576 pixels." }, { "code": null, "e": 1731, "s": 1636, "text": "noGutters: It is used to remove the gutter spacing between added negative margins and columns." }, { "code": null, "e": 1815, "s": 1731, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1826, "s": 1815, "text": "Col Props:" }, { "code": null, "e": 1890, "s": 1826, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1994, "s": 1890, "text": "lg: It is used to denote the number of columns to span on large devices having resolution ≥ 992 pixels." }, { "code": null, "e": 2099, "s": 1994, "text": "md: It is used to denote the number of columns to span on medium devices having resolution ≥ 768 pixels." }, { "code": null, "e": 2203, "s": 2099, "text": "sm: It is used to denote the number of columns to span on small devices having resolution ≥ 576 pixels." }, { "code": null, "e": 2314, "s": 2203, "text": "xl: It is used to denote the number of columns to span on extra-large devices having resolution ≥ 1200 pixels." }, { "code": null, "e": 2424, "s": 2314, "text": "xs: It is used to denote the number of columns to span on extra-small devices having resolution < 576 pixels." }, { "code": null, "e": 2508, "s": 2424, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2558, "s": 2508, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 2653, "s": 2558, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 2717, "s": 2653, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 2749, "s": 2717, "text": "npx create-react-app foldername" }, { "code": null, "e": 2863, "s": 2749, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername" }, { "code": null, "e": 2964, "s": 2863, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:" }, { "code": null, "e": 2978, "s": 2964, "text": "cd foldername" }, { "code": null, "e": 3133, "s": 2978, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 3238, "s": 3133, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 3289, "s": 3238, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 3341, "s": 3289, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 3359, "s": 3341, "text": "Project Structure" }, { "code": null, "e": 3509, "s": 3359, "text": "Container Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 3516, "s": 3509, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Container from 'react-bootstrap/Container'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Container Component</h4> <Container style={{ backgroundColor: 'green' }} > <h3>Sample Text, Greetings from GeeksforGeeks</h3> </Container> </div> );}", "e": 3982, "s": 3516, "text": null }, { "code": null, "e": 4095, "s": 3982, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4105, "s": 4095, "text": "npm start" }, { "code": null, "e": 4204, "s": 4105, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4348, "s": 4204, "text": "Row Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 4355, "s": 4348, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Row from 'react-bootstrap/Row'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Row Component</h4> <Row style={{ backgroundColor: 'red', }}> Sample First Row </Row> <Row style={{ backgroundColor: 'yellow', }}> Sample Second Row </Row> <Row style={{ backgroundColor: 'green', }}> Sample Third Row </Row> </div> );}", "e": 4936, "s": 4355, "text": null }, { "code": null, "e": 5049, "s": 4936, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 5059, "s": 5049, "text": "npm start" }, { "code": null, "e": 5158, "s": 5059, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 5288, "s": 5158, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 5295, "s": 5288, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Col from 'react-bootstrap/Col';import Row from 'react-bootstrap/Row'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Col Component</h4> <Row> <Col style={{ backgroundColor: 'red', }}> Sample First Col </Col> <Col style={{ backgroundColor: 'yellow', }}> Sample Second Col </Col> <Col style={{ backgroundColor: 'green', }}> Sample Third Col </Col> </Row> </div> );}", "e": 5943, "s": 5295, "text": null }, { "code": null, "e": 6056, "s": 5943, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 6066, "s": 6056, "text": "npm start" }, { "code": null, "e": 6165, "s": 6066, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6177, "s": 6165, "text": "Reference: " }, { "code": null, "e": 6240, "s": 6177, "text": "https://react-bootstrap.github.io/layout/grid/#container-props" }, { "code": null, "e": 6297, "s": 6240, "text": "https://react-bootstrap.github.io/layout/grid/#row-props" }, { "code": null, "e": 6354, "s": 6297, "text": "https://react-bootstrap.github.io/layout/grid/#col-props" }, { "code": null, "e": 6370, "s": 6354, "text": "React-Bootstrap" }, { "code": null, "e": 6381, "s": 6370, "text": "JavaScript" }, { "code": null, "e": 6389, "s": 6381, "text": "ReactJS" }, { "code": null, "e": 6406, "s": 6389, "text": "Web Technologies" }, { "code": null, "e": 6504, "s": 6406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6565, "s": 6504, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6605, "s": 6565, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6647, "s": 6605, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 6688, "s": 6647, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6710, "s": 6688, "text": "JavaScript | Promises" }, { "code": null, "e": 6753, "s": 6710, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 6798, "s": 6753, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 6836, "s": 6798, "text": "Axios in React: A Guide for Beginners" } ]
Student record management system using linked list
01 Dec, 2021 Prerequisites: Linked list Problem: Create a student Record Management system that can perform the following operations: Insert Student record Delete student record Show student record Search student record The student record should contain the following items Name of Student Roll Number of Student Course in which Student is Enrolled Total Marks of Student Approach: With the basic knowledge of operations on Linked Lists like insertion, deletion of elements in the Linked list, the student record management system can be created. Below are the functionalities explained that are to be implemented: Check Record: It is a utility function of creating a record it checks before insertion that the Record Already Exist or not. It uses the concept of checking for a Node with given Data in a linked list. Create Record: It is as simple as creating a new node in the Empty Linked list or inserting a new node in a non-Empty linked list. Search Record: Search a Record is similar to searching for a key in the linked list. Here in the student record key is the roll number as roll number is unique for every student. Delete Record: Delete Record is similar to deleting a key from a linked list. Here the key is the roll number. Delete record is an integer returning function it returns -1 if no such record with a given roll number is found otherwise it deletes the node with the given key and returns 0. Show Record: It shows the record is similar to printing all the elements of the Linked list. Exception Handling Although the implementation of exception handling is quite simple few things must be taken into consideration before designing such a system: Roll Number must be used as a key to distinguish between two different records so while inserting record check whether this record already exists in our database or not if it already exists then immediately report to the user that record already exists and insert that record in the database. The record should be inserted in sorted order for this to make the roll number a key and use the inserting node in the sorted linked list. Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node Classclass Node {public: int roll; string Name; string Dept; int Marks; Node* next;}; // Stores the head of the Linked ListNode* head = new Node(); // Check Function to check that if// Record Already Exist or Notbool check(int x){ // Base Case if (head == NULL) return false; Node* t = new Node; t = head; // Traverse the Linked List while (t != NULL) { if (t->roll == x) return true; t = t->next; } return false;} // Function to insert the recordvoid Insert_Record(int roll, string Name, string Dept, int Marks){ // if Record Already Exist if (check(roll)) { cout << "Student with this " << "record Already Exists\n"; return; } // Create new Node to Insert Record Node* t = new Node(); t->roll = roll; t->Name = Name; t->Dept = Dept; t->Marks = Marks; t->next = NULL; // Insert at Begin if (head == NULL || (head->roll >= t->roll)) { t->next = head; head = t; } // Insert at middle or End else { Node* c = head; while (c->next != NULL && c->next->roll < t->roll) { c = c->next; } t->next = c->next; c->next = t; } cout << "Record Inserted " << "Successfully\n";} // Function to search record for any// students Record with roll numbervoid Search_Record(int roll){ // if head is NULL if (!head) { cout << "No such Record " << "Available\n"; return; } // Otherwise else { Node* p = head; while (p) { if (p->roll == roll) { cout << "Roll Number\t" << p->roll << endl; cout << "Name\t\t" << p->Name << endl; cout << "Department\t" << p->Dept << endl; cout << "Marks\t\t" << p->Marks << endl; return; } p = p->next; } if (p == NULL) cout << "No such Record " << "Available\n"; }} // Function to delete record students// record with given roll number// if it existint Delete_Record(int roll){ Node* t = head; Node* p = NULL; // Deletion at Begin if (t != NULL && t->roll == roll) { head = t->next; delete t; cout << "Record Deleted " << "Successfully\n"; return 0; } // Deletion Other than Begin while (t != NULL && t->roll != roll) { p = t; t = t->next; } if (t == NULL) { cout << "Record does not Exist\n"; return -1; p->next = t->next; delete t; cout << "Record Deleted " << "Successfully\n"; return 0; }} // Function to display the Student's// Recordvoid Show_Record(){ Node* p = head; if (p == NULL) { cout << "No Record " << "Available\n"; } else { cout << "Index\tName\tCourse" << "\tMarks\n"; // Until p is not NULL while (p != NULL) { cout << p->roll << " \t" << p->Name << "\t" << p->Dept << "\t" << p->Marks << endl; p = p->next; } }} // Driver codeint main(){ head = NULL; string Name, Course; int Roll, Marks; // Menu-driven program while (true) { cout << "\n\t\tWelcome to Student Record " "Management System\n\n\tPress\n\t1 to " "create a new Record\n\t2 to delete a " "student record\n\t3 to Search a Student " "Record\n\t4 to view all students " "record\n\t5 to Exit\n"; cout << "\nEnter your Choice\n"; int Choice; // Enter Choice cin >> Choice; if (Choice == 1) { cout << "Enter Name of Student\n"; cin >> Name; cout << "Enter Roll Number of Student\n"; cin >> Roll; cout << "Enter Course of Student \n"; cin >> Course; cout << "Enter Total Marks of Student\n"; cin >> Marks; Insert_Record(Roll, Name, Course, Marks); } else if (Choice == 2) { cout << "Enter Roll Number of Student whose " "record is to be deleted\n"; cin >> Roll; Delete_Record(Roll); } else if (Choice == 3) { cout << "Enter Roll Number of Student whose " "record you want to Search\n"; cin >> Roll; Search_Record(Roll); } else if (Choice == 4) { Show_Record(); } else if (Choice == 5) { exit(0); } else { cout << "Invalid Choice " << "Try Again\n"; } } return 0;} Output: Below are the screenshots of the output of the various functions provided by the student record management system: Create Record: Show Record: Delete Record: Search Record: Student Record: sagar0719kumar simmytarika5 Linked Lists Technical Scripter 2020 C++ C++ Programs Project Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ program for hashing with chaining
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Dec, 2021" }, { "code": null, "e": 79, "s": 52, "text": "Prerequisites: Linked list" }, { "code": null, "e": 173, "s": 79, "text": "Problem: Create a student Record Management system that can perform the following operations:" }, { "code": null, "e": 195, "s": 173, "text": "Insert Student record" }, { "code": null, "e": 217, "s": 195, "text": "Delete student record" }, { "code": null, "e": 237, "s": 217, "text": "Show student record" }, { "code": null, "e": 259, "s": 237, "text": "Search student record" }, { "code": null, "e": 313, "s": 259, "text": "The student record should contain the following items" }, { "code": null, "e": 329, "s": 313, "text": "Name of Student" }, { "code": null, "e": 352, "s": 329, "text": "Roll Number of Student" }, { "code": null, "e": 388, "s": 352, "text": "Course in which Student is Enrolled" }, { "code": null, "e": 411, "s": 388, "text": "Total Marks of Student" }, { "code": null, "e": 654, "s": 411, "text": "Approach: With the basic knowledge of operations on Linked Lists like insertion, deletion of elements in the Linked list, the student record management system can be created. Below are the functionalities explained that are to be implemented:" }, { "code": null, "e": 856, "s": 654, "text": "Check Record: It is a utility function of creating a record it checks before insertion that the Record Already Exist or not. It uses the concept of checking for a Node with given Data in a linked list." }, { "code": null, "e": 987, "s": 856, "text": "Create Record: It is as simple as creating a new node in the Empty Linked list or inserting a new node in a non-Empty linked list." }, { "code": null, "e": 1166, "s": 987, "text": "Search Record: Search a Record is similar to searching for a key in the linked list. Here in the student record key is the roll number as roll number is unique for every student." }, { "code": null, "e": 1454, "s": 1166, "text": "Delete Record: Delete Record is similar to deleting a key from a linked list. Here the key is the roll number. Delete record is an integer returning function it returns -1 if no such record with a given roll number is found otherwise it deletes the node with the given key and returns 0." }, { "code": null, "e": 1547, "s": 1454, "text": "Show Record: It shows the record is similar to printing all the elements of the Linked list." }, { "code": null, "e": 1566, "s": 1547, "text": "Exception Handling" }, { "code": null, "e": 1708, "s": 1566, "text": "Although the implementation of exception handling is quite simple few things must be taken into consideration before designing such a system:" }, { "code": null, "e": 2001, "s": 1708, "text": "Roll Number must be used as a key to distinguish between two different records so while inserting record check whether this record already exists in our database or not if it already exists then immediately report to the user that record already exists and insert that record in the database." }, { "code": null, "e": 2140, "s": 2001, "text": "The record should be inserted in sorted order for this to make the roll number a key and use the inserting node in the sorted linked list." }, { "code": null, "e": 2191, "s": 2140, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2195, "s": 2191, "text": "C++" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node Classclass Node {public: int roll; string Name; string Dept; int Marks; Node* next;}; // Stores the head of the Linked ListNode* head = new Node(); // Check Function to check that if// Record Already Exist or Notbool check(int x){ // Base Case if (head == NULL) return false; Node* t = new Node; t = head; // Traverse the Linked List while (t != NULL) { if (t->roll == x) return true; t = t->next; } return false;} // Function to insert the recordvoid Insert_Record(int roll, string Name, string Dept, int Marks){ // if Record Already Exist if (check(roll)) { cout << \"Student with this \" << \"record Already Exists\\n\"; return; } // Create new Node to Insert Record Node* t = new Node(); t->roll = roll; t->Name = Name; t->Dept = Dept; t->Marks = Marks; t->next = NULL; // Insert at Begin if (head == NULL || (head->roll >= t->roll)) { t->next = head; head = t; } // Insert at middle or End else { Node* c = head; while (c->next != NULL && c->next->roll < t->roll) { c = c->next; } t->next = c->next; c->next = t; } cout << \"Record Inserted \" << \"Successfully\\n\";} // Function to search record for any// students Record with roll numbervoid Search_Record(int roll){ // if head is NULL if (!head) { cout << \"No such Record \" << \"Available\\n\"; return; } // Otherwise else { Node* p = head; while (p) { if (p->roll == roll) { cout << \"Roll Number\\t\" << p->roll << endl; cout << \"Name\\t\\t\" << p->Name << endl; cout << \"Department\\t\" << p->Dept << endl; cout << \"Marks\\t\\t\" << p->Marks << endl; return; } p = p->next; } if (p == NULL) cout << \"No such Record \" << \"Available\\n\"; }} // Function to delete record students// record with given roll number// if it existint Delete_Record(int roll){ Node* t = head; Node* p = NULL; // Deletion at Begin if (t != NULL && t->roll == roll) { head = t->next; delete t; cout << \"Record Deleted \" << \"Successfully\\n\"; return 0; } // Deletion Other than Begin while (t != NULL && t->roll != roll) { p = t; t = t->next; } if (t == NULL) { cout << \"Record does not Exist\\n\"; return -1; p->next = t->next; delete t; cout << \"Record Deleted \" << \"Successfully\\n\"; return 0; }} // Function to display the Student's// Recordvoid Show_Record(){ Node* p = head; if (p == NULL) { cout << \"No Record \" << \"Available\\n\"; } else { cout << \"Index\\tName\\tCourse\" << \"\\tMarks\\n\"; // Until p is not NULL while (p != NULL) { cout << p->roll << \" \\t\" << p->Name << \"\\t\" << p->Dept << \"\\t\" << p->Marks << endl; p = p->next; } }} // Driver codeint main(){ head = NULL; string Name, Course; int Roll, Marks; // Menu-driven program while (true) { cout << \"\\n\\t\\tWelcome to Student Record \" \"Management System\\n\\n\\tPress\\n\\t1 to \" \"create a new Record\\n\\t2 to delete a \" \"student record\\n\\t3 to Search a Student \" \"Record\\n\\t4 to view all students \" \"record\\n\\t5 to Exit\\n\"; cout << \"\\nEnter your Choice\\n\"; int Choice; // Enter Choice cin >> Choice; if (Choice == 1) { cout << \"Enter Name of Student\\n\"; cin >> Name; cout << \"Enter Roll Number of Student\\n\"; cin >> Roll; cout << \"Enter Course of Student \\n\"; cin >> Course; cout << \"Enter Total Marks of Student\\n\"; cin >> Marks; Insert_Record(Roll, Name, Course, Marks); } else if (Choice == 2) { cout << \"Enter Roll Number of Student whose \" \"record is to be deleted\\n\"; cin >> Roll; Delete_Record(Roll); } else if (Choice == 3) { cout << \"Enter Roll Number of Student whose \" \"record you want to Search\\n\"; cin >> Roll; Search_Record(Roll); } else if (Choice == 4) { Show_Record(); } else if (Choice == 5) { exit(0); } else { cout << \"Invalid Choice \" << \"Try Again\\n\"; } } return 0;}", "e": 7151, "s": 2195, "text": null }, { "code": null, "e": 7274, "s": 7151, "text": "Output: Below are the screenshots of the output of the various functions provided by the student record management system:" }, { "code": null, "e": 7291, "s": 7274, "text": "Create Record: " }, { "code": null, "e": 7306, "s": 7291, "text": "Show Record: " }, { "code": null, "e": 7323, "s": 7306, "text": "Delete Record: " }, { "code": null, "e": 7340, "s": 7323, "text": "Search Record: " }, { "code": null, "e": 7358, "s": 7340, "text": "Student Record: " }, { "code": null, "e": 7373, "s": 7358, "text": "sagar0719kumar" }, { "code": null, "e": 7386, "s": 7373, "text": "simmytarika5" }, { "code": null, "e": 7399, "s": 7386, "text": "Linked Lists" }, { "code": null, "e": 7423, "s": 7399, "text": "Technical Scripter 2020" }, { "code": null, "e": 7427, "s": 7423, "text": "C++" }, { "code": null, "e": 7440, "s": 7427, "text": "C++ Programs" }, { "code": null, "e": 7448, "s": 7440, "text": "Project" }, { "code": null, "e": 7467, "s": 7448, "text": "Technical Scripter" }, { "code": null, "e": 7471, "s": 7467, "text": "CPP" }, { "code": null, "e": 7569, "s": 7471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7593, "s": 7569, "text": "Sorting a vector in C++" }, { "code": null, "e": 7613, "s": 7593, "text": "Polymorphism in C++" }, { "code": null, "e": 7638, "s": 7613, "text": "std::string class in C++" }, { "code": null, "e": 7671, "s": 7638, "text": "Friend class and function in C++" }, { "code": null, "e": 7715, "s": 7671, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 7750, "s": 7715, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 7784, "s": 7750, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 7828, "s": 7784, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 7887, "s": 7828, "text": "How to return multiple values from a function in C or C++?" } ]
How to add Site Header, Site Title, Index Title in a Django Project?
08 Jun, 2022 Automatic admin interface one of the most powerful parts of Django. Metadata is read from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around. OVERVIEW: Add ‘django.contrib.admin’ along with its dependencies – django.contrib.auth, django.contrib.contenttypes, django.contrib.messages, and django.contrib.sessions – to your INSTALLED_APPS setting. Configure a DjangoTemplates backend in your TEMPLATES setting with django.template.context_processors.request, django.contrib.auth.context_processors.auth, and django.contrib.messages.context_processors.messages in the ‘context_processors’ option of OPTIONS. If you have used customised MIDDLEWARE setting, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware must be included. Make following changes in urls.py – python3 from django.contrib import adminfrom django.urls import path, include # Adds site header, site title, index title to the admin side.admin.site.site_header = 'Geeks For Geeks'admin.site.site_title = 'GFG'admin.site.index_title = 'Welcome Geeks' urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls),] Output – DJANGO ADMIN CUSTOMISATION: The Python code enables to add site_header, site_heading and index_title. vinayedula Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 374, "s": 28, "text": "Automatic admin interface one of the most powerful parts of Django. Metadata is read from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around." }, { "code": null, "e": 384, "s": 374, "text": "OVERVIEW:" }, { "code": null, "e": 578, "s": 384, "text": "Add ‘django.contrib.admin’ along with its dependencies – django.contrib.auth, django.contrib.contenttypes, django.contrib.messages, and django.contrib.sessions – to your INSTALLED_APPS setting." }, { "code": null, "e": 837, "s": 578, "text": "Configure a DjangoTemplates backend in your TEMPLATES setting with django.template.context_processors.request, django.contrib.auth.context_processors.auth, and django.contrib.messages.context_processors.messages in the ‘context_processors’ option of OPTIONS." }, { "code": null, "e": 1016, "s": 837, "text": "If you have used customised MIDDLEWARE setting, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware must be included." }, { "code": null, "e": 1053, "s": 1016, "text": "Make following changes in urls.py – " }, { "code": null, "e": 1061, "s": 1053, "text": "python3" }, { "code": "from django.contrib import adminfrom django.urls import path, include # Adds site header, site title, index title to the admin side.admin.site.site_header = 'Geeks For Geeks'admin.site.site_title = 'GFG'admin.site.index_title = 'Welcome Geeks' urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls),]", "e": 1393, "s": 1061, "text": null }, { "code": null, "e": 1403, "s": 1393, "text": "Output – " }, { "code": null, "e": 1432, "s": 1403, "text": "DJANGO ADMIN CUSTOMISATION: " }, { "code": null, "e": 1507, "s": 1432, "text": "The Python code enables to add site_header, site_heading and index_title." }, { "code": null, "e": 1518, "s": 1507, "text": "vinayedula" }, { "code": null, "e": 1532, "s": 1518, "text": "Python Django" }, { "code": null, "e": 1539, "s": 1532, "text": "Python" }, { "code": null, "e": 1637, "s": 1539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1655, "s": 1637, "text": "Python Dictionary" }, { "code": null, "e": 1677, "s": 1655, "text": "Enumerate() in Python" }, { "code": null, "e": 1712, "s": 1677, "text": "Read a file line by line in Python" }, { "code": null, "e": 1744, "s": 1712, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1770, "s": 1744, "text": "Python String | replace()" }, { "code": null, "e": 1799, "s": 1770, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1826, "s": 1799, "text": "Python Classes and Objects" }, { "code": null, "e": 1847, "s": 1826, "text": "Python OOPs Concepts" }, { "code": null, "e": 1877, "s": 1847, "text": "Iterate over a list in Python" } ]
HTML5 - Modernizr
Modernizr is a small JavaScript Library that detects the availability of native implementations for next-generation web technologies There are several new features which are being introduced through HTML5 and CSS3 but same time many browsers do not support these news features. Modernizr provides an easy way to detect any new feature so that you can take corresponding action. For example, if a browser does not support video feature then you would like to display a simple page. You can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new feature. You can download latest version of this utility from Modernizr Download. Before you start using Modernizr, you would have to include its javascript library in your HTML page header as follows − <script src="modernizr.min.js" type="text/javascript"></script> As mentioned above, you can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new featur. Following is the simple syntax to handle supported and non supported features − /* In your CSS: */ .no-audio #music { display: none; /* Don't show Audio options */ } .audio #music button { /* Style the Play and Pause buttons nicely */ } <!-- In your HTML: --> <div id="music"> <audio> <source src="audio.ogg" /> <source src="audio.mp3" /> </audio> <button id="play">Play</button> <button id="pause">Pause</button> </div> Here it is notable that you need to prefix "no-" to every feature/property you want to handle for the browser which does not support them. Following is the syntax to detect a particular feature through Javascript − if (Modernizr.audio) { /* properties for browsers that support audio */ } else{ /* properties for browsers that does not support audio */ } Following is the list of features which can be detected by Modernizr −
[ { "code": null, "e": 2875, "s": 2742, "text": "Modernizr is a small JavaScript Library that detects the availability of native implementations for next-generation web technologies" }, { "code": null, "e": 3020, "s": 2875, "text": "There are several new features which are being introduced through HTML5 and CSS3 but same time many browsers do not support these news features." }, { "code": null, "e": 3223, "s": 3020, "text": "Modernizr provides an easy way to detect any new feature so that you can take corresponding action. For example, if a browser does not support video feature then you would like to display a simple page." }, { "code": null, "e": 3382, "s": 3223, "text": "You can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new feature." }, { "code": null, "e": 3455, "s": 3382, "text": "You can download latest version of this utility from Modernizr Download." }, { "code": null, "e": 3576, "s": 3455, "text": "Before you start using Modernizr, you would have to include its javascript library in your HTML page header as follows −" }, { "code": null, "e": 3640, "s": 3576, "text": "<script src=\"modernizr.min.js\" type=\"text/javascript\"></script>" }, { "code": null, "e": 3818, "s": 3640, "text": "As mentioned above, you can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new featur." }, { "code": null, "e": 3898, "s": 3818, "text": "Following is the simple syntax to handle supported and non supported features −" }, { "code": null, "e": 4278, "s": 3898, "text": "/* In your CSS: */\n.no-audio #music {\n display: none; /* Don't show Audio options */\n}\n.audio #music button {\n /* Style the Play and Pause buttons nicely */\n}\n\n<!-- In your HTML: -->\n<div id=\"music\">\n \n <audio>\n <source src=\"audio.ogg\" />\n <source src=\"audio.mp3\" />\n </audio>\n \n <button id=\"play\">Play</button>\n <button id=\"pause\">Pause</button>\n</div>" }, { "code": null, "e": 4417, "s": 4278, "text": "Here it is notable that you need to prefix \"no-\" to every feature/property you want to handle for the browser which does not support them." }, { "code": null, "e": 4493, "s": 4417, "text": "Following is the syntax to detect a particular feature through Javascript −" }, { "code": null, "e": 4647, "s": 4493, "text": "if (Modernizr.audio) {\n /* properties for browsers that\n support audio */\n}\n\nelse{\n /* properties for browsers that\n does not support audio */\n}\n" } ]
Different ways to create an Object in C#
18 Aug, 2021 A fully object-oriented language means everything is represented as an object but can’t differentiate between primitive types and objects of classes but C# is not purely object oriented since it supports many procedural programming concepts such as pointers to an extent. An object is a basic unit of Object Oriented Programming and represents the real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. We can Create objects in C# in the following ways:1) Using the ‘new’ operator: A class is a reference type and at the run time, any object of the reference type is assigned a null value unless it is declared using the new operator. The new operator assigns space in the memory to the object only during run time which means the allocation is dynamic.Syntax: // The className() is a call // to the constructor className ObjectName = new className(); Note: The constructor can be a default constructor or a user-defined one.Example: csharp // C# Program to show the use// of the new Operatorusing System; namespace NewOperator { class Rectangle { public int length, breadth; // Parameterized Constructor // User defined public Rectangle(int l, int b) { length = l; breadth = b; } // Method to Calculate Area // of the rectangle public int Area() { return length * breadth; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Creating an object using 'new' // Calling the parameterized constructor // With parameters 10 and 12 Rectangle rect1 = new Rectangle(10, 12); // To display are of the Rectangle int area = rect1.Area(); Console.WriteLine("The area of the"+ " Rectangle is " + area); }}} The area of the Rectangle is 120 2) Creating Reference to Existing Object: The reference can be declared only with the class name and reference name. The reference cannot exist independently. It has to be assigned to an already existing object of the same class. Any changes made in the reference will be saved to the object it is referring to. It is kind of like an alias.Syntax: className RefName; RefName = objectName; Example: csharp // C# Program to show the use// of referencesusing System; namespace Reference { class Triangle { public int side, altitude; // Not defining a constructor // Method to calculate area // of the Triangle public double Area() { return (double)0.5 * side * altitude; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Creating an object using new // calls the default constructor Triangle tri1 = new Triangle(); // Only creates a reference of // type Triangle Triangle tri2; // Displaying area of tri1 Console.WriteLine("Area of tri1 is " + tri1.Area()); // Assigns the reference to tri1 tri2 = tri1; // Making changes in tri2 tri2.side = 5; tri2.altitude = 7; // Displaying area of tri1 // Changes made in the reference tri2 // are reflected in tri1 also Console.WriteLine("Area of tri1 is " + tri1.Area()); }}} Area of tri1 is 0 Area of tri1 is 17.5 3) Creating an Array of objects: If you need the multiple numbers of objects of the same class you can create an array of objects. This will require you to declare the array first and then initialize each element { object in this case }. You can use for loop for initialization.Syntax: className[] arrayName = new className[size]; csharp // C# Program to illustrate how to// create the array of objectsusing System; namespace ArrayofObjects { class Circle { public int radius; // Defining Constructor public Circle() { radius = 0; } // Method to set value of radius public void setValue(int r) { radius = r; } // Method to calculate the // area of the Circle public double Area() { return (double)3.14 * radius * radius; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // To declare an array of two objects Circle[] circleArray = new Circle[2]; // Initialize the objects circleArray[0] = new Circle(); circleArray[1] = new Circle(); // to set values for the radius circleArray[0].setValue(1); circleArray[1].setValue(2); // for loop to display areas for (int i = 0; i < circleArray.Length; i++) { Console.Write("Area of circle with radius " + (i + 1)); Console.Write(" is " + circleArray[i].Area() + "\n"); } }}} Area of circle with radius 1 is 3.14 Area of circle with radius 2 is 12.56 adnanirshad158 CSharp-OOP Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Replace() Method C# | Arrays C# | List Class
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2021" }, { "code": null, "e": 872, "s": 52, "text": "A fully object-oriented language means everything is represented as an object but can’t differentiate between primitive types and objects of classes but C# is not purely object oriented since it supports many procedural programming concepts such as pointers to an extent. An object is a basic unit of Object Oriented Programming and represents the real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. We can Create objects in C# in the following ways:1) Using the ‘new’ operator: A class is a reference type and at the run time, any object of the reference type is assigned a null value unless it is declared using the new operator. The new operator assigns space in the memory to the object only during run time which means the allocation is dynamic.Syntax: " }, { "code": null, "e": 966, "s": 872, "text": "// The className() is a call\n// to the constructor\nclassName ObjectName = new className(); " }, { "code": null, "e": 1049, "s": 966, "text": "Note: The constructor can be a default constructor or a user-defined one.Example: " }, { "code": null, "e": 1056, "s": 1049, "text": "csharp" }, { "code": "// C# Program to show the use// of the new Operatorusing System; namespace NewOperator { class Rectangle { public int length, breadth; // Parameterized Constructor // User defined public Rectangle(int l, int b) { length = l; breadth = b; } // Method to Calculate Area // of the rectangle public int Area() { return length * breadth; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Creating an object using 'new' // Calling the parameterized constructor // With parameters 10 and 12 Rectangle rect1 = new Rectangle(10, 12); // To display are of the Rectangle int area = rect1.Area(); Console.WriteLine(\"The area of the\"+ \" Rectangle is \" + area); }}}", "e": 1882, "s": 1056, "text": null }, { "code": null, "e": 1915, "s": 1882, "text": "The area of the Rectangle is 120" }, { "code": null, "e": 2267, "s": 1917, "text": "2) Creating Reference to Existing Object: The reference can be declared only with the class name and reference name. The reference cannot exist independently. It has to be assigned to an already existing object of the same class. Any changes made in the reference will be saved to the object it is referring to. It is kind of like an alias.Syntax: " }, { "code": null, "e": 2308, "s": 2267, "text": "className RefName;\nRefName = objectName;" }, { "code": null, "e": 2318, "s": 2308, "text": "Example: " }, { "code": null, "e": 2325, "s": 2318, "text": "csharp" }, { "code": "// C# Program to show the use// of referencesusing System; namespace Reference { class Triangle { public int side, altitude; // Not defining a constructor // Method to calculate area // of the Triangle public double Area() { return (double)0.5 * side * altitude; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // Creating an object using new // calls the default constructor Triangle tri1 = new Triangle(); // Only creates a reference of // type Triangle Triangle tri2; // Displaying area of tri1 Console.WriteLine(\"Area of tri1 is \" + tri1.Area()); // Assigns the reference to tri1 tri2 = tri1; // Making changes in tri2 tri2.side = 5; tri2.altitude = 7; // Displaying area of tri1 // Changes made in the reference tri2 // are reflected in tri1 also Console.WriteLine(\"Area of tri1 is \" + tri1.Area()); }}}", "e": 3392, "s": 2325, "text": null }, { "code": null, "e": 3431, "s": 3392, "text": "Area of tri1 is 0\nArea of tri1 is 17.5" }, { "code": null, "e": 3721, "s": 3433, "text": "3) Creating an Array of objects: If you need the multiple numbers of objects of the same class you can create an array of objects. This will require you to declare the array first and then initialize each element { object in this case }. You can use for loop for initialization.Syntax: " }, { "code": null, "e": 3766, "s": 3721, "text": "className[] arrayName = new className[size];" }, { "code": null, "e": 3775, "s": 3768, "text": "csharp" }, { "code": "// C# Program to illustrate how to// create the array of objectsusing System; namespace ArrayofObjects { class Circle { public int radius; // Defining Constructor public Circle() { radius = 0; } // Method to set value of radius public void setValue(int r) { radius = r; } // Method to calculate the // area of the Circle public double Area() { return (double)3.14 * radius * radius; }} // Driver Classclass Program { // Main Method static void Main(string[] args) { // To declare an array of two objects Circle[] circleArray = new Circle[2]; // Initialize the objects circleArray[0] = new Circle(); circleArray[1] = new Circle(); // to set values for the radius circleArray[0].setValue(1); circleArray[1].setValue(2); // for loop to display areas for (int i = 0; i < circleArray.Length; i++) { Console.Write(\"Area of circle with radius \" + (i + 1)); Console.Write(\" is \" + circleArray[i].Area() + \"\\n\"); } }}}", "e": 4874, "s": 3775, "text": null }, { "code": null, "e": 4949, "s": 4874, "text": "Area of circle with radius 1 is 3.14\nArea of circle with radius 2 is 12.56" }, { "code": null, "e": 4966, "s": 4951, "text": "adnanirshad158" }, { "code": null, "e": 4977, "s": 4966, "text": "CSharp-OOP" }, { "code": null, "e": 4984, "s": 4977, "text": "Picked" }, { "code": null, "e": 4987, "s": 4984, "text": "C#" }, { "code": null, "e": 5085, "s": 4987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5116, "s": 5085, "text": "Introduction to .NET Framework" }, { "code": null, "e": 5131, "s": 5116, "text": "C# | Delegates" }, { "code": null, "e": 5174, "s": 5131, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5223, "s": 5174, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5239, "s": 5223, "text": "C# | Data Types" }, { "code": null, "e": 5279, "s": 5239, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 5302, "s": 5279, "text": "Extension Method in C#" }, { "code": null, "e": 5324, "s": 5302, "text": "C# | Replace() Method" }, { "code": null, "e": 5336, "s": 5324, "text": "C# | Arrays" } ]
Priority Queue using Doubly Linked List
23 May, 2021 Given Nodes with their priority, implement a priority queue using doubly linked list. Prerequisite : Priority Queue push(): This function is used to insert a new data into the queue. pop(): This function removes the element with the lowest priority value form the queue. peek() / top(): This function is used to get the lowest priority element in the queue without removing it from the queue. Approach : 1. Create a doubly linked list having fields info(hold the information of the Node), priority(hold the priority of the Node), prev(point to previous Node), next(point to next Node). 2. Insert the element and priority in the Node. 3. Arrange the Nodes in the increasing order of priority. Below is the implementation of above steps : C++ C Java Python3 C# Javascript // C++ code to implement priority// queue using doubly linked list#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node { int info; int priority; struct Node *prev, *next;}; // Function to insert a new Nodevoid push(Node** fr, Node** rr, int n, int p){ Node* news = (Node*)malloc(sizeof(Node)); news->info = n; news->priority = p; // If linked list is empty if (*fr == NULL) { *fr = news; *rr = news; news->next = NULL; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (*fr)->priority) { news->next = *fr; (*fr)->prev = news->next; *fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (*rr)->priority) { news->next = NULL; (*rr)->next = news; news->prev = (*rr)->next; *rr = news; } // Handle other cases else { // Find position where we need to // insert. Node* start = (*fr)->next; while (start->priority > p) start = start->next; (start->prev)->next = news; news->next = start->prev; news->prev = (start->prev)->next; start->prev = news->next; } }} // Return the value at rearint peek(Node* fr) { return fr->info; } bool isEmpty(Node* fr) { return (fr == NULL); } // Removes the element with the// least priority value form the listint pop(Node** fr, Node** rr){ Node* temp = *fr; int res = temp->info; (*fr) = (*fr)->next; free(temp); if (*fr == NULL) *rr = NULL; return res;} // Driver codeint main(){ Node *front = NULL, *rear = NULL; push(&front, &rear, 2, 3); push(&front, &rear, 3, 4); push(&front, &rear, 4, 5); push(&front, &rear, 5, 6); push(&front, &rear, 6, 7); push(&front, &rear, 1, 2); cout << pop(&front, &rear) << endl; cout << peek(front); return 0;} // C code to implement priority// queue using doubly linked list#include <stdio.h>#include <stdlib.h> // Linked List Nodestruct Node { int info; int priority; struct Node *prev, *next;}; // Function to insert a new Nodevoid push(struct Node** fr, struct Node** rr, int n, int p){ struct Node* news = (struct Node*)malloc(sizeof(struct Node*)); news->info = n; news->priority = p; // If linked list is empty if (*fr == NULL) { *fr = news; *rr = news; news->next = NULL; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (*fr)->priority) { news->next = *fr; (*fr)->prev = news->next; *fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (*rr)->priority) { news->next = NULL; (*rr)->next = news; news->prev = (*rr)->next; *rr = news; } // Handle other cases else { // Find position where we need to // insert. struct Node* start = (*fr)->next; while (start->priority > p) start = start->next; (start->prev)->next = news; news->next = start->prev; news->prev = (start->prev)->next; start->prev = news->next; } }} // Return the value at rearint peek(struct Node* fr) { return fr->info; } int isEmpty(struct Node* fr) { return (fr == NULL); } // Removes the element with the// least priority value form the listint pop(struct Node** fr, struct Node** rr){ struct Node* temp = *fr; int res = temp->info; (*fr) = (*fr)->next; free(temp); if (*fr == NULL) *rr = NULL; return res;} // Driver codeint main(){ struct Node *front = NULL, *rear = NULL; push(&front, &rear, 2, 3); push(&front, &rear, 3, 4); push(&front, &rear, 4, 5); push(&front, &rear, 5, 6); push(&front, &rear, 6, 7); push(&front, &rear, 1, 2); printf("%d\n", pop(&front, &rear)); printf("%d\n", peek(front)); return 0;} // Java code to implement priority// queue using doubly linked list import java.util.*; class Solution { static Node front, rear; // Linked List Node static class Node { int info; int priority; Node prev, next; } // Function to insert a new Node static void push(Node fr, Node rr, int n, int p) { Node news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we need to // insert. Node start = (fr).next; while (start.priority > p) start = start.next; (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear static int peek(Node fr) { return fr.info; } static boolean isEmpty(Node fr) { return (fr == null); } // Removes the element with the // least priority value form the list static int pop(Node fr, Node rr) { Node temp = fr; int res = temp.info; (fr) = (fr).next; if (fr == null) rr = null; front = fr; rear = rr; return res; } // Driver code public static void main(String args[]) { push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); System.out.println(pop(front, rear)); System.out.println(peek(front)); }} // This code is contributed// by Arnab Kundu # Python3 code to implement priority# queue using doubly linked list # Linked List Nodeclass Node: def __init__(self): self.info = 0 self.priority = 0 self.next = None self.prev = None front = Nonerear = None # Function to insert a new Nodedef push(fr, rr, n, p): global front, rear news = Node() news.info = n news.priority = p # If linked list is empty if (fr == None): fr = news rr = news news.next = None else: # If p is less than or equal fr # node's priority, then insert at # the fr. if (p <= (fr).priority): news.next = fr (fr).prev = news.next fr = news # If p is more rr node's priority, # then insert after the rr. elif (p > (rr).priority): news.next = None (rr).next = news news.prev = (rr).next rr = news # Handle other cases else: # Find position where we need to # insert. start = (fr).next while (start.priority > p): start = start.next (start.prev).next = news news.next = start.prev news.prev = (start.prev).next start.prev = news.next front = fr rear = rr # Return the value at rrdef peek(fr): return fr.info def isEmpty(fr): return fr == None # Removes the element with the# least priority value form the listdef pop(fr, rr): global front , rear temp = fr res = temp.info (fr) = (fr).next if (fr == None): rr = None front = fr rear = rr return res # Driver codeif __name__=='__main__': push( front, rear, 2, 3) push( front, rear, 3, 4) push( front, rear, 4, 5) push( front, rear, 5, 6) push( front, rear, 6, 7) push( front, rear, 1, 2) print(pop(front, rear)) print(peek(front)) # This code is contributed by rutvik_56 // C# code to implement priority// queue using doubly linked listusing System; class GFG { public static Node front, rear; // Linked List Node public class Node { public int info; public int priority; public Node prev, next; } // Function to insert a new Node public static void push(Node fr, Node rr, int n, int p) { Node news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we // need to insert. Node start = (fr).next; while (start.priority > p) { start = start.next; } (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear public static int peek(Node fr) { return fr.info; } public static bool isEmpty(Node fr) { return (fr == null); } // Removes the element with the // least priority value form the list public static int pop(Node fr, Node rr) { Node temp = fr; int res = temp.info; (fr) = (fr).next; if (fr == null) { rr = null; } front = fr; rear = rr; return res; } // Driver code public static void Main(string[] args) { push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); Console.WriteLine(pop(front, rear)); Console.WriteLine(peek(front)); }} // This code is contributed by Shrikant13 <script>// javascript code to implement priority// queue using doubly linked listvar front, rear; // Linked List Node class Node { constructor(){ this.info = 0; this.priority = 0;this.prev = null;this.next = null;} } // Function to insert a new Node function push(fr, rr , n , p) {var news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we need to // insert. var start = (fr).next; while (start.priority > p) start = start.next; (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear function peek(fr) { return fr.info; } function isEmpty(fr) { return (fr == null); } // Removes the element with the // least priority value form the list function pop(fr, rr) {var temp = fr; var res = temp.info; (fr) = (fr).next; if (fr == null) rr = null; front = fr; rear = rr; return res; } // Driver code push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); document.write(pop(front, rear)+"<br/>"); document.write(peek(front)); // This code contributed by aashish1995</script> 1 2 Related Article : Priority Queue using Singly Linked List Time Complexities and Comparison with Binary Heap: peek() push() pop() ----------------------------------------- Linked List | O(1) O(n) O(1) | Binary Heap | O(1) O(Log n) O(Log n) andrew1234 shrikanth13 nidhi_biet debojyoti7 rutvik_56 aashish1995 doubly linked list priority-queue Linked List Queue Linked List Queue priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Rearrange a given linked list in-place. Types of Linked List Find first node of loop in a linked list Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2021" }, { "code": null, "e": 139, "s": 52, "text": "Given Nodes with their priority, implement a priority queue using doubly linked list. " }, { "code": null, "e": 169, "s": 139, "text": "Prerequisite : Priority Queue" }, { "code": null, "e": 236, "s": 169, "text": "push(): This function is used to insert a new data into the queue." }, { "code": null, "e": 324, "s": 236, "text": "pop(): This function removes the element with the lowest priority value form the queue." }, { "code": null, "e": 446, "s": 324, "text": "peek() / top(): This function is used to get the lowest priority element in the queue without removing it from the queue." }, { "code": null, "e": 458, "s": 446, "text": "Approach : " }, { "code": null, "e": 747, "s": 458, "text": "1. Create a doubly linked list having fields info(hold the information of the Node), priority(hold the priority of the Node), prev(point to previous Node), next(point to next Node). 2. Insert the element and priority in the Node. 3. Arrange the Nodes in the increasing order of priority. " }, { "code": null, "e": 794, "s": 747, "text": "Below is the implementation of above steps : " }, { "code": null, "e": 798, "s": 794, "text": "C++" }, { "code": null, "e": 800, "s": 798, "text": "C" }, { "code": null, "e": 805, "s": 800, "text": "Java" }, { "code": null, "e": 813, "s": 805, "text": "Python3" }, { "code": null, "e": 816, "s": 813, "text": "C#" }, { "code": null, "e": 827, "s": 816, "text": "Javascript" }, { "code": "// C++ code to implement priority// queue using doubly linked list#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node { int info; int priority; struct Node *prev, *next;}; // Function to insert a new Nodevoid push(Node** fr, Node** rr, int n, int p){ Node* news = (Node*)malloc(sizeof(Node)); news->info = n; news->priority = p; // If linked list is empty if (*fr == NULL) { *fr = news; *rr = news; news->next = NULL; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (*fr)->priority) { news->next = *fr; (*fr)->prev = news->next; *fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (*rr)->priority) { news->next = NULL; (*rr)->next = news; news->prev = (*rr)->next; *rr = news; } // Handle other cases else { // Find position where we need to // insert. Node* start = (*fr)->next; while (start->priority > p) start = start->next; (start->prev)->next = news; news->next = start->prev; news->prev = (start->prev)->next; start->prev = news->next; } }} // Return the value at rearint peek(Node* fr) { return fr->info; } bool isEmpty(Node* fr) { return (fr == NULL); } // Removes the element with the// least priority value form the listint pop(Node** fr, Node** rr){ Node* temp = *fr; int res = temp->info; (*fr) = (*fr)->next; free(temp); if (*fr == NULL) *rr = NULL; return res;} // Driver codeint main(){ Node *front = NULL, *rear = NULL; push(&front, &rear, 2, 3); push(&front, &rear, 3, 4); push(&front, &rear, 4, 5); push(&front, &rear, 5, 6); push(&front, &rear, 6, 7); push(&front, &rear, 1, 2); cout << pop(&front, &rear) << endl; cout << peek(front); return 0;}", "e": 2896, "s": 827, "text": null }, { "code": "// C code to implement priority// queue using doubly linked list#include <stdio.h>#include <stdlib.h> // Linked List Nodestruct Node { int info; int priority; struct Node *prev, *next;}; // Function to insert a new Nodevoid push(struct Node** fr, struct Node** rr, int n, int p){ struct Node* news = (struct Node*)malloc(sizeof(struct Node*)); news->info = n; news->priority = p; // If linked list is empty if (*fr == NULL) { *fr = news; *rr = news; news->next = NULL; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (*fr)->priority) { news->next = *fr; (*fr)->prev = news->next; *fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (*rr)->priority) { news->next = NULL; (*rr)->next = news; news->prev = (*rr)->next; *rr = news; } // Handle other cases else { // Find position where we need to // insert. struct Node* start = (*fr)->next; while (start->priority > p) start = start->next; (start->prev)->next = news; news->next = start->prev; news->prev = (start->prev)->next; start->prev = news->next; } }} // Return the value at rearint peek(struct Node* fr) { return fr->info; } int isEmpty(struct Node* fr) { return (fr == NULL); } // Removes the element with the// least priority value form the listint pop(struct Node** fr, struct Node** rr){ struct Node* temp = *fr; int res = temp->info; (*fr) = (*fr)->next; free(temp); if (*fr == NULL) *rr = NULL; return res;} // Driver codeint main(){ struct Node *front = NULL, *rear = NULL; push(&front, &rear, 2, 3); push(&front, &rear, 3, 4); push(&front, &rear, 4, 5); push(&front, &rear, 5, 6); push(&front, &rear, 6, 7); push(&front, &rear, 1, 2); printf(\"%d\\n\", pop(&front, &rear)); printf(\"%d\\n\", peek(front)); return 0;}", "e": 5054, "s": 2896, "text": null }, { "code": "// Java code to implement priority// queue using doubly linked list import java.util.*; class Solution { static Node front, rear; // Linked List Node static class Node { int info; int priority; Node prev, next; } // Function to insert a new Node static void push(Node fr, Node rr, int n, int p) { Node news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we need to // insert. Node start = (fr).next; while (start.priority > p) start = start.next; (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear static int peek(Node fr) { return fr.info; } static boolean isEmpty(Node fr) { return (fr == null); } // Removes the element with the // least priority value form the list static int pop(Node fr, Node rr) { Node temp = fr; int res = temp.info; (fr) = (fr).next; if (fr == null) rr = null; front = fr; rear = rr; return res; } // Driver code public static void main(String args[]) { push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); System.out.println(pop(front, rear)); System.out.println(peek(front)); }} // This code is contributed// by Arnab Kundu", "e": 7485, "s": 5054, "text": null }, { "code": "# Python3 code to implement priority# queue using doubly linked list # Linked List Nodeclass Node: def __init__(self): self.info = 0 self.priority = 0 self.next = None self.prev = None front = Nonerear = None # Function to insert a new Nodedef push(fr, rr, n, p): global front, rear news = Node() news.info = n news.priority = p # If linked list is empty if (fr == None): fr = news rr = news news.next = None else: # If p is less than or equal fr # node's priority, then insert at # the fr. if (p <= (fr).priority): news.next = fr (fr).prev = news.next fr = news # If p is more rr node's priority, # then insert after the rr. elif (p > (rr).priority): news.next = None (rr).next = news news.prev = (rr).next rr = news # Handle other cases else: # Find position where we need to # insert. start = (fr).next while (start.priority > p): start = start.next (start.prev).next = news news.next = start.prev news.prev = (start.prev).next start.prev = news.next front = fr rear = rr # Return the value at rrdef peek(fr): return fr.info def isEmpty(fr): return fr == None # Removes the element with the# least priority value form the listdef pop(fr, rr): global front , rear temp = fr res = temp.info (fr) = (fr).next if (fr == None): rr = None front = fr rear = rr return res # Driver codeif __name__=='__main__': push( front, rear, 2, 3) push( front, rear, 3, 4) push( front, rear, 4, 5) push( front, rear, 5, 6) push( front, rear, 6, 7) push( front, rear, 1, 2) print(pop(front, rear)) print(peek(front)) # This code is contributed by rutvik_56", "e": 9559, "s": 7485, "text": null }, { "code": "// C# code to implement priority// queue using doubly linked listusing System; class GFG { public static Node front, rear; // Linked List Node public class Node { public int info; public int priority; public Node prev, next; } // Function to insert a new Node public static void push(Node fr, Node rr, int n, int p) { Node news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we // need to insert. Node start = (fr).next; while (start.priority > p) { start = start.next; } (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear public static int peek(Node fr) { return fr.info; } public static bool isEmpty(Node fr) { return (fr == null); } // Removes the element with the // least priority value form the list public static int pop(Node fr, Node rr) { Node temp = fr; int res = temp.info; (fr) = (fr).next; if (fr == null) { rr = null; } front = fr; rear = rr; return res; } // Driver code public static void Main(string[] args) { push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); Console.WriteLine(pop(front, rear)); Console.WriteLine(peek(front)); }} // This code is contributed by Shrikant13", "e": 12065, "s": 9559, "text": null }, { "code": "<script>// javascript code to implement priority// queue using doubly linked listvar front, rear; // Linked List Node class Node { constructor(){ this.info = 0; this.priority = 0;this.prev = null;this.next = null;} } // Function to insert a new Node function push(fr, rr , n , p) {var news = new Node(); news.info = n; news.priority = p; // If linked list is empty if (fr == null) { fr = news; rr = news; news.next = null; } else { // If p is less than or equal front // node's priority, then insert at // the front. if (p <= (fr).priority) { news.next = fr; (fr).prev = news.next; fr = news; } // If p is more rear node's priority, // then insert after the rear. else if (p > (rr).priority) { news.next = null; (rr).next = news; news.prev = (rr).next; rr = news; } // Handle other cases else { // Find position where we need to // insert. var start = (fr).next; while (start.priority > p) start = start.next; (start.prev).next = news; news.next = start.prev; news.prev = (start.prev).next; start.prev = news.next; } } front = fr; rear = rr; } // Return the value at rear function peek(fr) { return fr.info; } function isEmpty(fr) { return (fr == null); } // Removes the element with the // least priority value form the list function pop(fr, rr) {var temp = fr; var res = temp.info; (fr) = (fr).next; if (fr == null) rr = null; front = fr; rear = rr; return res; } // Driver code push(front, rear, 2, 3); push(front, rear, 3, 4); push(front, rear, 4, 5); push(front, rear, 5, 6); push(front, rear, 6, 7); push(front, rear, 1, 2); document.write(pop(front, rear)+\"<br/>\"); document.write(peek(front)); // This code contributed by aashish1995</script>", "e": 14387, "s": 12065, "text": null }, { "code": null, "e": 14391, "s": 14387, "text": "1\n2" }, { "code": null, "e": 14451, "s": 14393, "text": "Related Article : Priority Queue using Singly Linked List" }, { "code": null, "e": 14504, "s": 14451, "text": "Time Complexities and Comparison with Binary Heap: " }, { "code": null, "e": 14686, "s": 14504, "text": " peek() push() pop()\n-----------------------------------------\nLinked List | O(1) O(n) O(1)\n |\nBinary Heap | O(1) O(Log n) O(Log n)" }, { "code": null, "e": 14699, "s": 14688, "text": "andrew1234" }, { "code": null, "e": 14711, "s": 14699, "text": "shrikanth13" }, { "code": null, "e": 14722, "s": 14711, "text": "nidhi_biet" }, { "code": null, "e": 14733, "s": 14722, "text": "debojyoti7" }, { "code": null, "e": 14743, "s": 14733, "text": "rutvik_56" }, { "code": null, "e": 14755, "s": 14743, "text": "aashish1995" }, { "code": null, "e": 14774, "s": 14755, "text": "doubly linked list" }, { "code": null, "e": 14789, "s": 14774, "text": "priority-queue" }, { "code": null, "e": 14801, "s": 14789, "text": "Linked List" }, { "code": null, "e": 14807, "s": 14801, "text": "Queue" }, { "code": null, "e": 14819, "s": 14807, "text": "Linked List" }, { "code": null, "e": 14825, "s": 14819, "text": "Queue" }, { "code": null, "e": 14840, "s": 14825, "text": "priority-queue" }, { "code": null, "e": 14938, "s": 14840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14970, "s": 14938, "text": "Introduction to Data Structures" }, { "code": null, "e": 15034, "s": 14970, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15074, "s": 15034, "text": "Rearrange a given linked list in-place." }, { "code": null, "e": 15095, "s": 15074, "text": "Types of Linked List" }, { "code": null, "e": 15136, "s": 15095, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 15176, "s": 15136, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 15210, "s": 15176, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 15226, "s": 15210, "text": "Queue in Python" }, { "code": null, "e": 15250, "s": 15226, "text": "Queue Interface In Java" } ]
Create Balanced Binary Tree using its Leaf Nodes without using extra space
05 Apr, 2022 Prerequisites: Binary Tree to Doubly Linked ListGiven a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree. Examples: Input: Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be: Input: Output: 13 21 29 7 15 Explanation: Required balanced binary tree is: 29 / \ 21 7 / \ 13 15 Approach: Follow the steps below to solve the problem: Find all the leaf nodes in the given binary tree and create a doubly linked list using them.To create a Balanced Binary Tree from the above doubly linked list do the following: Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree.Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered.Print the newly created balanced binary tree. Find all the leaf nodes in the given binary tree and create a doubly linked list using them. To create a Balanced Binary Tree from the above doubly linked list do the following: Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree.Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered. Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree. Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered. Print the newly created balanced binary tree. 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; // Structure for Linked list and treeclass Node {public: int data; Node *left, *right;}; // Function that returns the count of// nodes in the given linked listint countNodes(Node* head){ // Initialize count int count = 0; Node* temp = head; // Iterate till the end of LL while (temp) { temp = temp->right; // Increment the count count++; } // Return the final count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLNode* sortedListToBSTRecur( Node** head_ref, int n){ // Base Case if (n <= 0) return NULL; // Recursively construct // the left subtree Node* left = sortedListToBSTRecur( head_ref, n / 2); // head_ref now refers to // middle node, make middle node // as root of BST Node* root = *head_ref; // Set pointer to left subtree root->left = left; // Change head pointer of // Linked List for parent // recursive calls *head_ref = (*head_ref)->right; // Recursively construct the // right subtree and link it // with root root->right = sortedListToBSTRecur( head_ref, n - n / 2 - 1); // Return the root of Balanced BT return root;}Node* sortedListToBST(Node* head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur( &head, n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesNode* extractLeafList(Node* root, Node** head_ref){ // Base cases if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root->right = *head_ref; // Change left pointer // of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; // Return new root return NULL; } // Recur for right & left subtrees root->right = extractLeafList(root->right, head_ref); root->left = extractLeafList(root->left, head_ref); // Return the root return root;} // Function to allocating new Node// int Binary TreeNode* newNode(int data){ Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return node;} // Function for inorder traversalvoid print(Node* root){ // If root is not NULL if (root != NULL) { print(root->left); // Print the root's data cout << root->data << " "; print(root->right); }} // Function to display nodes of DLLvoid printList(Node* head){ while (head) { // Print the data cout << head->data << " "; head = head->right; }} // Driver Codeint main(){ // Given Binary Tree Node* head = NULL; Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); // Function Call to extract leaf Node root = extractLeafList( root, &head); // Function Call to create Balanced BT root = sortedListToBST(head); // Print Inorder traversal New Balanced BT print(root); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Structure for Linked// list and treestatic class Node{ public int data; Node left, right;}; static Node head; // Function that returns the// count of nodes in the given// linked liststatic int countNodes(Node head){ // Initialize count int count = 0; Node temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the final count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){ // Base Case if (n <= 0) return null; // Recursively construct // the left subtree Node left = sortedListToBSTRecur(n / 2); // head now refers to // middle node, make // middle node as root of BST Node root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - n / 2 - 1); // Return the root // of Balanced BT return root;} static Node sortedListToBST(){ // Count the number of // nodes in Linked List int n = countNodes(head); // Construct BST return sortedListToBSTRecur(n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){ // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList(root.right); root.left = extractLeafList(root.left); // Return the root return root;} // Function to allocating new// Node int Binary Treestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function for inorder traversalstatic void print(Node root){ // If root is not null if (root != null) { print(root.left); // Print the root's data System.out.print(root.data + " "); print(root.right); }} // Function to display nodes of DLLstatic void printList(Node head){ while (head != null) { // Print the data System.out.print(head.data + " "); head = head.right; }} // Driver Codepublic static void main(String[] args){ // Given Binary Tree head = null; Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function Call to // extract leaf Node root = extractLeafList(root); // Function Call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root);}} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Structure for Linked list and treeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None head = None # Function that returns the count of# nodes in the given linked listdef countNodes(head1): # Initialize count count = 0 temp = head1 # Iterate till the end of LL while (temp): temp = temp.right # Increment the count count += 1 # Return the final count return count # Function to return the root of# the newly created balanced binary# tree from the given doubly LLdef sortedListToBSTRecur(n): global head # Base Case if (n <= 0): return None # Recursively construct # the left subtree left = sortedListToBSTRecur(n // 2) # head_ref now refers to # middle node, make middle node # as root of BST root = head # Set pointer to left subtree root.left = left # Change head pointer of # Linked List for parent # recursive calls head = head.right # Recursively construct the # right subtree and link it # with root root.right = sortedListToBSTRecur(n - n // 2 - 1) # Return the root of Balanced BT return root def sortedListToBST(): global head # Count the number of nodes # in Linked List n = countNodes(head) # Construct BST return sortedListToBSTRecur(n) # Function to find the leaf nodes and# make the doubly linked list of# those nodesdef extractLeafList(root): global head # Base cases if (root == None): return None if (root.left == None and root.right == None): # This node is added to doubly # linked list of leaves, and # set right pointer of this # node as previous head of DLL root.right = head # Change left pointer # of previous head if (head != None): head.left = root # Change head of linked list head = root # Return new root return head # Recur for right & left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) # Return the root return root # Function for inorder traversaldef print1(root): # If root is not NULL if (root != None): print1(root.left) # Print the root's data print(root.data, end = " ") print1(root.right) # Function to display nodes of DLLdef printList(head): while(head): # Print the data print(head.data, end = " ") head = head.right # Driver Codeif __name__ == '__main__': # Given Binary Tree root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) root.left.left.left = newNode(7) root.left.left.right = newNode(8) root.right.right.left = newNode(9) root.right.right.right = newNode(10) # Function Call to extract leaf Node root = extractLeafList(root) # Function Call to create Balanced BT root = sortedListToBST() # Print Inorder traversal New Balanced BT print1(root) # This code is contributed by ipg2016107 // C# program for the above approachusing System; class GFG{ // Structure for Linked// list and treepublic class Node{ public int data; public Node left, right;}; static Node head; // Function that returns the// count of nodes in the given// linked liststatic int countNodes(Node head){ // Initialize count int count = 0; Node temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the readonly count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){ // Base Case if (n <= 0) return null; // Recursively construct // the left subtree Node left = sortedListToBSTRecur(n / 2); // head now refers to // middle node, make // middle node as root of BST Node root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - n / 2 - 1); // Return the root // of Balanced BT return root;} static Node sortedListToBST(){ // Count the number of // nodes in Linked List int n = countNodes(head); // Construct BST return sortedListToBSTRecur(n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){ // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList( root.right); root.left = extractLeafList( root.left); // Return the root return root;} // Function to allocating new// Node int Binary Treestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function for inorder traversalstatic void print(Node root){ // If root is not null if (root != null) { print(root.left); // Print the root's data Console.Write(root.data + " "); print(root.right); }} // Function to display nodes of DLLstatic void printList(Node head){ while (head != null) { // Print the data Console.Write(head.data + " "); head = head.right; }} // Driver Codepublic static void Main(String[] args){ // Given Binary Tree head = null; Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function call to // extract leaf Node root = extractLeafList(root); // Function call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root);}} // This code is contributed by Amit Katiyar <script> // Javascript program for the above approach // Structure for Linked // list and tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let head; // Function that returns the // count of nodes in the given // linked list function countNodes(head) { // Initialize count let count = 0; let temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the final count return count; } // Function to return the root of // the newly created balanced binary // tree from the given doubly LL function sortedListToBSTRecur(n) { // Base Case if (n <= 0) return null; // Recursively construct // the left subtree let left = sortedListToBSTRecur(parseInt(n / 2, 10)); // head now refers to // middle node, make // middle node as root of BST let root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - parseInt(n / 2, 10) - 1); // Return the root // of Balanced BT return root; } function sortedListToBST() { // Count the number of // nodes in Linked List let n = countNodes(head); // Construct BST return sortedListToBSTRecur(n); } // Function to find the leaf nodes and // make the doubly linked list of // those nodes function extractLeafList(root) { // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList(root.right); root.left = extractLeafList(root.left); // Return the root return root; } // Function to allocating new // Node int Binary Tree function newNode(data) { let node = new Node(data); return node; } // Function for inorder traversal function print(root) { // If root is not null if (root != null) { print(root.left); // Print the root's data document.write(root.data + " "); print(root.right); } } // Function to display nodes of DLL function printList(head) { while (head != null) { // Print the data document.write(head.data + " "); head = head.right; } } // Given Binary Tree head = null; let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function Call to // extract leaf Node root = extractLeafList(root); // Function Call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root); // This code is contributed by mukesh07.</script> 7 8 5 9 10 Time Complexity: O(N), where N is the number of nodes in the given tree. Auxiliary Space Complexity: O(1) nidhi_biet amit143katiyar ipg2016107 mukesh07 anikakapoor simmytarika5 surinderdawra388 Binary Tree Binary Search Tree Recursion Tree Recursion Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2022" }, { "code": null, "e": 192, "s": 28, "text": "Prerequisites: Binary Tree to Doubly Linked ListGiven a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree." }, { "code": null, "e": 203, "s": 192, "text": "Examples: " }, { "code": null, "e": 211, "s": 203, "text": "Input: " }, { "code": null, "e": 283, "s": 211, "text": "Output: 7 8 5 9 10 \nExplanation: Required balanced binary tree will be:" }, { "code": null, "e": 290, "s": 283, "text": "Input:" }, { "code": null, "e": 456, "s": 290, "text": "Output: 13 21 29 7 15\nExplanation: Required balanced binary tree is:\n 29\n / \\\n 21 7\n / \\\n 13 15" }, { "code": null, "e": 513, "s": 456, "text": "Approach: Follow the steps below to solve the problem: " }, { "code": null, "e": 991, "s": 513, "text": "Find all the leaf nodes in the given binary tree and create a doubly linked list using them.To create a Balanced Binary Tree from the above doubly linked list do the following: Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree.Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered.Print the newly created balanced binary tree." }, { "code": null, "e": 1084, "s": 991, "text": "Find all the leaf nodes in the given binary tree and create a doubly linked list using them." }, { "code": null, "e": 1425, "s": 1084, "text": "To create a Balanced Binary Tree from the above doubly linked list do the following: Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree.Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered." }, { "code": null, "e": 1534, "s": 1425, "text": "Find the middle node of the doubly linked list formed above and set it as a root node of the resultant tree." }, { "code": null, "e": 1682, "s": 1534, "text": "Recursively iterate for the left and right of the current middle node in the doubly linked list repeat the above steps until all nodes are covered." }, { "code": null, "e": 1728, "s": 1682, "text": "Print the newly created balanced binary tree." }, { "code": null, "e": 1781, "s": 1728, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1785, "s": 1781, "text": "C++" }, { "code": null, "e": 1790, "s": 1785, "text": "Java" }, { "code": null, "e": 1798, "s": 1790, "text": "Python3" }, { "code": null, "e": 1801, "s": 1798, "text": "C#" }, { "code": null, "e": 1812, "s": 1801, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure for Linked list and treeclass Node {public: int data; Node *left, *right;}; // Function that returns the count of// nodes in the given linked listint countNodes(Node* head){ // Initialize count int count = 0; Node* temp = head; // Iterate till the end of LL while (temp) { temp = temp->right; // Increment the count count++; } // Return the final count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLNode* sortedListToBSTRecur( Node** head_ref, int n){ // Base Case if (n <= 0) return NULL; // Recursively construct // the left subtree Node* left = sortedListToBSTRecur( head_ref, n / 2); // head_ref now refers to // middle node, make middle node // as root of BST Node* root = *head_ref; // Set pointer to left subtree root->left = left; // Change head pointer of // Linked List for parent // recursive calls *head_ref = (*head_ref)->right; // Recursively construct the // right subtree and link it // with root root->right = sortedListToBSTRecur( head_ref, n - n / 2 - 1); // Return the root of Balanced BT return root;}Node* sortedListToBST(Node* head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur( &head, n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesNode* extractLeafList(Node* root, Node** head_ref){ // Base cases if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root->right = *head_ref; // Change left pointer // of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; // Return new root return NULL; } // Recur for right & left subtrees root->right = extractLeafList(root->right, head_ref); root->left = extractLeafList(root->left, head_ref); // Return the root return root;} // Function to allocating new Node// int Binary TreeNode* newNode(int data){ Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return node;} // Function for inorder traversalvoid print(Node* root){ // If root is not NULL if (root != NULL) { print(root->left); // Print the root's data cout << root->data << \" \"; print(root->right); }} // Function to display nodes of DLLvoid printList(Node* head){ while (head) { // Print the data cout << head->data << \" \"; head = head->right; }} // Driver Codeint main(){ // Given Binary Tree Node* head = NULL; Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); // Function Call to extract leaf Node root = extractLeafList( root, &head); // Function Call to create Balanced BT root = sortedListToBST(head); // Print Inorder traversal New Balanced BT print(root); return 0;}", "e": 5591, "s": 1812, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Structure for Linked// list and treestatic class Node{ public int data; Node left, right;}; static Node head; // Function that returns the// count of nodes in the given// linked liststatic int countNodes(Node head){ // Initialize count int count = 0; Node temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the final count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){ // Base Case if (n <= 0) return null; // Recursively construct // the left subtree Node left = sortedListToBSTRecur(n / 2); // head now refers to // middle node, make // middle node as root of BST Node root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - n / 2 - 1); // Return the root // of Balanced BT return root;} static Node sortedListToBST(){ // Count the number of // nodes in Linked List int n = countNodes(head); // Construct BST return sortedListToBSTRecur(n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){ // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList(root.right); root.left = extractLeafList(root.left); // Return the root return root;} // Function to allocating new// Node int Binary Treestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function for inorder traversalstatic void print(Node root){ // If root is not null if (root != null) { print(root.left); // Print the root's data System.out.print(root.data + \" \"); print(root.right); }} // Function to display nodes of DLLstatic void printList(Node head){ while (head != null) { // Print the data System.out.print(head.data + \" \"); head = head.right; }} // Driver Codepublic static void main(String[] args){ // Given Binary Tree head = null; Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function Call to // extract leaf Node root = extractLeafList(root); // Function Call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root);}} // This code is contributed by Amit Katiyar", "e": 9000, "s": 5591, "text": null }, { "code": "# Python3 program for the above approach # Structure for Linked list and treeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None head = None # Function that returns the count of# nodes in the given linked listdef countNodes(head1): # Initialize count count = 0 temp = head1 # Iterate till the end of LL while (temp): temp = temp.right # Increment the count count += 1 # Return the final count return count # Function to return the root of# the newly created balanced binary# tree from the given doubly LLdef sortedListToBSTRecur(n): global head # Base Case if (n <= 0): return None # Recursively construct # the left subtree left = sortedListToBSTRecur(n // 2) # head_ref now refers to # middle node, make middle node # as root of BST root = head # Set pointer to left subtree root.left = left # Change head pointer of # Linked List for parent # recursive calls head = head.right # Recursively construct the # right subtree and link it # with root root.right = sortedListToBSTRecur(n - n // 2 - 1) # Return the root of Balanced BT return root def sortedListToBST(): global head # Count the number of nodes # in Linked List n = countNodes(head) # Construct BST return sortedListToBSTRecur(n) # Function to find the leaf nodes and# make the doubly linked list of# those nodesdef extractLeafList(root): global head # Base cases if (root == None): return None if (root.left == None and root.right == None): # This node is added to doubly # linked list of leaves, and # set right pointer of this # node as previous head of DLL root.right = head # Change left pointer # of previous head if (head != None): head.left = root # Change head of linked list head = root # Return new root return head # Recur for right & left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) # Return the root return root # Function for inorder traversaldef print1(root): # If root is not NULL if (root != None): print1(root.left) # Print the root's data print(root.data, end = \" \") print1(root.right) # Function to display nodes of DLLdef printList(head): while(head): # Print the data print(head.data, end = \" \") head = head.right # Driver Codeif __name__ == '__main__': # Given Binary Tree root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) root.left.left.left = newNode(7) root.left.left.right = newNode(8) root.right.right.left = newNode(9) root.right.right.right = newNode(10) # Function Call to extract leaf Node root = extractLeafList(root) # Function Call to create Balanced BT root = sortedListToBST() # Print Inorder traversal New Balanced BT print1(root) # This code is contributed by ipg2016107", "e": 12303, "s": 9000, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Structure for Linked// list and treepublic class Node{ public int data; public Node left, right;}; static Node head; // Function that returns the// count of nodes in the given// linked liststatic int countNodes(Node head){ // Initialize count int count = 0; Node temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the readonly count return count;} // Function to return the root of// the newly created balanced binary// tree from the given doubly LLstatic Node sortedListToBSTRecur(int n){ // Base Case if (n <= 0) return null; // Recursively construct // the left subtree Node left = sortedListToBSTRecur(n / 2); // head now refers to // middle node, make // middle node as root of BST Node root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - n / 2 - 1); // Return the root // of Balanced BT return root;} static Node sortedListToBST(){ // Count the number of // nodes in Linked List int n = countNodes(head); // Construct BST return sortedListToBSTRecur(n);} // Function to find the leaf nodes and// make the doubly linked list of// those nodesstatic Node extractLeafList(Node root){ // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList( root.right); root.left = extractLeafList( root.left); // Return the root return root;} // Function to allocating new// Node int Binary Treestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function for inorder traversalstatic void print(Node root){ // If root is not null if (root != null) { print(root.left); // Print the root's data Console.Write(root.data + \" \"); print(root.right); }} // Function to display nodes of DLLstatic void printList(Node head){ while (head != null) { // Print the data Console.Write(head.data + \" \"); head = head.right; }} // Driver Codepublic static void Main(String[] args){ // Given Binary Tree head = null; Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function call to // extract leaf Node root = extractLeafList(root); // Function call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root);}} // This code is contributed by Amit Katiyar", "e": 16156, "s": 12303, "text": null }, { "code": "<script> // Javascript program for the above approach // Structure for Linked // list and tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let head; // Function that returns the // count of nodes in the given // linked list function countNodes(head) { // Initialize count let count = 0; let temp = head; // Iterate till the // end of LL while (temp != null) { temp = temp.right; // Increment the count count++; } // Return the final count return count; } // Function to return the root of // the newly created balanced binary // tree from the given doubly LL function sortedListToBSTRecur(n) { // Base Case if (n <= 0) return null; // Recursively construct // the left subtree let left = sortedListToBSTRecur(parseInt(n / 2, 10)); // head now refers to // middle node, make // middle node as root of BST let root = head; // Set pointer to left subtree root.left = left; // Change head pointer of // Linked List for parent // recursive calls head = head.right; // Recursively construct the // right subtree and link it // with root root.right = sortedListToBSTRecur(n - parseInt(n / 2, 10) - 1); // Return the root // of Balanced BT return root; } function sortedListToBST() { // Count the number of // nodes in Linked List let n = countNodes(head); // Construct BST return sortedListToBSTRecur(n); } // Function to find the leaf nodes and // make the doubly linked list of // those nodes function extractLeafList(root) { // Base cases if (root == null) return null; if (root.left == null && root.right == null) { // This node is added to doubly // linked list of leaves, and // set right pointer of this // node as previous head of DLL root.right = head; // Change left pointer // of previous head if (head != null) head.left = root; // Change head of linked list head = root; // Return new root return head; } // Recur for right & // left subtrees root.right = extractLeafList(root.right); root.left = extractLeafList(root.left); // Return the root return root; } // Function to allocating new // Node int Binary Tree function newNode(data) { let node = new Node(data); return node; } // Function for inorder traversal function print(root) { // If root is not null if (root != null) { print(root.left); // Print the root's data document.write(root.data + \" \"); print(root.right); } } // Function to display nodes of DLL function printList(head) { while (head != null) { // Print the data document.write(head.data + \" \"); head = head.right; } } // Given Binary Tree head = null; let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); root.left.left.left = newNode(7); root.left.left.right = newNode(8); root.right.right.left = newNode(9); root.right.right.right = newNode(10); // Function Call to // extract leaf Node root = extractLeafList(root); // Function Call to create // Balanced BT root = sortedListToBST(); // Print Inorder traversal // New Balanced BT print(root); // This code is contributed by mukesh07.</script>", "e": 19999, "s": 16156, "text": null }, { "code": null, "e": 20010, "s": 19999, "text": "7 8 5 9 10" }, { "code": null, "e": 20118, "s": 20012, "text": "Time Complexity: O(N), where N is the number of nodes in the given tree. Auxiliary Space Complexity: O(1)" }, { "code": null, "e": 20131, "s": 20120, "text": "nidhi_biet" }, { "code": null, "e": 20146, "s": 20131, "text": "amit143katiyar" }, { "code": null, "e": 20157, "s": 20146, "text": "ipg2016107" }, { "code": null, "e": 20166, "s": 20157, "text": "mukesh07" }, { "code": null, "e": 20178, "s": 20166, "text": "anikakapoor" }, { "code": null, "e": 20191, "s": 20178, "text": "simmytarika5" }, { "code": null, "e": 20208, "s": 20191, "text": "surinderdawra388" }, { "code": null, "e": 20220, "s": 20208, "text": "Binary Tree" }, { "code": null, "e": 20239, "s": 20220, "text": "Binary Search Tree" }, { "code": null, "e": 20249, "s": 20239, "text": "Recursion" }, { "code": null, "e": 20254, "s": 20249, "text": "Tree" }, { "code": null, "e": 20264, "s": 20254, "text": "Recursion" }, { "code": null, "e": 20283, "s": 20264, "text": "Binary Search Tree" }, { "code": null, "e": 20288, "s": 20283, "text": "Tree" } ]
How to Hide Legend in ggplot2 in R ?
18 Jul, 2021 In this article we will discuss how can we hide a legend in R programming language, using ggplot2. Note: Here, a line plot is used for illustration the same can be applied to any other plot. Let us first draw a regular plot, with a legend, so that the difference is apparent. For this, firstly, import the required library and create dataframe, the dataframe should be such that it can be drawn on the basis of groups and is color differentiated because only then a legend will appear. Example: R library("ggplot2") year <- c(2000, 2001, 2002, 2003, 2004)winner <- c('A', 'B', 'B', 'A', 'B')score <- c(9, 7, 9, 8, 8) df <- data.frame(year, winner, score) ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point() Output: Now to hide the legend, theme() function is used after normally drawing the plot. theme() function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look. Syntax: theme (line, text, axis.title,legend.position) Parameter: line: all line elements (element_line()) text: all text elements (element_text()) axis.title: labels of axes (element_text()). Specify all axes’ labels (axis.title) legend.position: changes the legend position to some specified value. To hide the legend this function is called with legend.position parameter, to which “none” is passed to not make ut appear on the plot. Syntax: theme(legend.position=”none”) Code: R library("ggplot2") year<-c(2000,2001,2002,2003,2004)winner<-c('A','B','B','A','B')score<-c(9,7,9,8,8) df<-data.frame(year,winner,score) ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point()+theme(legend.position="none") Output: R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 127, "s": 28, "text": "In this article we will discuss how can we hide a legend in R programming language, using ggplot2." }, { "code": null, "e": 219, "s": 127, "text": "Note: Here, a line plot is used for illustration the same can be applied to any other plot." }, { "code": null, "e": 514, "s": 219, "text": "Let us first draw a regular plot, with a legend, so that the difference is apparent. For this, firstly, import the required library and create dataframe, the dataframe should be such that it can be drawn on the basis of groups and is color differentiated because only then a legend will appear." }, { "code": null, "e": 523, "s": 514, "text": "Example:" }, { "code": null, "e": 525, "s": 523, "text": "R" }, { "code": "library(\"ggplot2\") year <- c(2000, 2001, 2002, 2003, 2004)winner <- c('A', 'B', 'B', 'A', 'B')score <- c(9, 7, 9, 8, 8) df <- data.frame(year, winner, score) ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point()", "e": 772, "s": 525, "text": null }, { "code": null, "e": 780, "s": 772, "text": "Output:" }, { "code": null, "e": 862, "s": 780, "text": "Now to hide the legend, theme() function is used after normally drawing the plot." }, { "code": null, "e": 1088, "s": 862, "text": "theme() function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look." }, { "code": null, "e": 1096, "s": 1088, "text": "Syntax:" }, { "code": null, "e": 1143, "s": 1096, "text": "theme (line, text, axis.title,legend.position)" }, { "code": null, "e": 1154, "s": 1143, "text": "Parameter:" }, { "code": null, "e": 1195, "s": 1154, "text": "line: all line elements (element_line())" }, { "code": null, "e": 1236, "s": 1195, "text": "text: all text elements (element_text())" }, { "code": null, "e": 1319, "s": 1236, "text": "axis.title: labels of axes (element_text()). Specify all axes’ labels (axis.title)" }, { "code": null, "e": 1389, "s": 1319, "text": "legend.position: changes the legend position to some specified value." }, { "code": null, "e": 1525, "s": 1389, "text": "To hide the legend this function is called with legend.position parameter, to which “none” is passed to not make ut appear on the plot." }, { "code": null, "e": 1563, "s": 1525, "text": "Syntax: theme(legend.position=”none”)" }, { "code": null, "e": 1569, "s": 1563, "text": "Code:" }, { "code": null, "e": 1571, "s": 1569, "text": "R" }, { "code": "library(\"ggplot2\") year<-c(2000,2001,2002,2003,2004)winner<-c('A','B','B','A','B')score<-c(9,7,9,8,8) df<-data.frame(year,winner,score) ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point()+theme(legend.position=\"none\")", "e": 1826, "s": 1571, "text": null }, { "code": null, "e": 1834, "s": 1826, "text": "Output:" }, { "code": null, "e": 1843, "s": 1834, "text": "R-ggplot" }, { "code": null, "e": 1854, "s": 1843, "text": "R Language" } ]
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
01 Oct, 2020 Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and also reverse sorting by keys. keys() method returns a view object that displays a list of all the keys in the dictionary. sorted() is used to sort the keys of the dictionary. Examples: Input: my_dict = {'c':3, 'a':1, 'd':4, 'b':2} Output: a: 1 b: 2 c: 3 d: 4 Python3 # Initialising a dictionarymy_dict = {'c':3, 'a':1, 'd':4, 'b':2} # Sorting dictionarysorted_dict = my_dict.keys()sorted_dict = sorted(sorted_dict) # Printing sorted dictionaryprint("Sorted dictionary using sorted() and keys() is : ")for key in sorted_dict: print(key,':', my_dict[key]) Sorted dictionary using sorted() and keys() is : a : 1 b : 2 c : 3 d : 4 items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary’s (key, value) tuple pair. sorted() is used to sort the keys of the dictionary. Examples: Input: my_dict = {2:'three', 1:'two', 4:'five', 3:'four'} Output: 1 'two' 2 'three' 3 'Four' 4 'Five' Python3 # Initialising dictionarymy_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'} # Sorting dictionarysorted_dict = sorted(my_dict.items()) # Printing sorted dictionaryprint("Sorted dictionary using sorted() and items() is :")for k, v in sorted_dict: print(k, v) Sorted dictionary using sorted() and items() is : 1 two 2 three 3 four 4 five Here, we use both sorted() and keys() in a single line. Examples: Input: my_dict = {'c':3, 'a':1, 'd':4, 'b':2} Output: Sorted dictionary is : ['a','b','c','d'] Python3 # Initialising a dictionarymy_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}# Sorting dictionarysorted_dict = sorted(my_dict.keys()) # Printing sorted dictionaryprint("Sorted dictionary is : ", sorted_dict) Sorted dictionary is : ['a', 'b', 'c', 'd'] Here, we use both sorted() and items() in a single line. Examples: Input: my_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} Output: Sorted dictionary is : black :: #000000 green :: #008000 red :: #FF0000 white :: #FFFFFF Python3 # Initialising a dictionarymy_dict = {'red': '#FF0000', 'green': '#008000', 'black': '#000000', 'white': '#FFFFFF'} # Sorting dictionary in one linesorted_dict = dict(sorted(my_dict .items())) # Printing sorted dictionaryprint("Sorted dictionary is : ")for elem in sorted(sorted_dict.items()): print(elem[0], " ::", elem[1]) Sorted dictionary is : black :: #000000 green :: #008000 red :: #FF0000 white :: #FFFFFF The lambda function returns the key(0th element) for a specific item tuple, When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary. Examples: Input: my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90} Output: Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90} Python3 # Initialising a dictionarymy_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90} # Sorting dictionary using lambda functionsorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1])) # Printing sorted dictionaryprint("Sorted dictionary using lambda is : ", sorted_dict) Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90} 6. Using json : Python doesn’t allow sorting of a dictionary. But while converting the dictionary to a JSON, you can explicitly sort it so that the resulting JSON is sorted by keys. This is true for the multidimensional dictionary. Examples: Input: my_dict = {"b": 2, "c": 3, "a": 1,"d":4} Output: Sorted dictionary is : {"a": 1, "b": 2, "c": 3,"d":4} Python3 # Importing jsonimport json # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4} # Sorting and printind in a single lineprint("Sorted dictionary is : ", json.dumps(my_dict, sort_keys=True)) Sorted dictionary is : {"a": 1, "b": 2, "c": 3, "d": 4} The Python pprint module actually already sorts dictionaries by key. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. Examples: Input: my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} Output: Sorted dictionary is : {0: 0, 1: 2, 2: 1, 3: 4, 4: 3} Python3 # Importing pprintimport pprint # Initialising a dictionarymy_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} # Sorting and printing in a single lineprint("Sorted dictionary is :")pprint.pprint(my_dict) The OrderedDict is a standard library class, which is located in the collections module. OrderedDict maintains the orders of keys as inserted. Examples: Input: my_dict = {"b": 2, "c": 3, "a": 1,"d":4}1} Output: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) Python # Importing OrderedDictfrom collections import OrderedDict # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4} # Sorting dictionarysorted_dict = OrderedDict(sorted(my_dict.items())) # Printing sorted dictionaryprint(sorted_dict) OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) Using sortedcontainers and SortedDict : Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict is a sorted mutable mapping. Sorted dict inherits from dict to store items and maintains a sorted list of keys. For this, we need to install sortedcontainers. sudo pip install sortedcontainers Examples: Input: my_dict = {"b": 2, "c": 3, "a": 1,"d":4} Output: {"a": 1, "b": 2, "c": 3,"d":4} Python3 # Importing SortedDictfrom sortedcontainers import SortedDict # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4} # Sorting dictionarysorted_dict = SortedDict(my_dict) # Printing sorted dictionaryprint(sorted_dict) Output: SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) Examples: Input: {"b": 2, "c": 3, "a": 1,"d":4} Output: {"a": 1, "b": 2, "c": 3,"d":4} Python3 class SortedDisplayDict(dict): def __str__(self): return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}" # Initialising dictionary and calling classmy_dict = SortedDisplayDict({"b": 2, "c": 3, "a": 1,"d":4}) # Printing dictionaryprint(my_dict) {'a': 1, 'b': 2, 'c': 3, 'd': 4} Examples: Input: my_dict = {"b": 2, "c": 3, "a": 1,"d":4} Output: Sorted dictionary is : ['a','b','c','d'] Python3 # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4} # Reverse sorting a dictionarysorted_dict = sorted(my_dict, reverse=True) # Printing dictionaryprint("Sorted dictionary is :") for k in sorted_dict: print(k,':',my_dict[k]) Sorted dictionary is : d : 4 c : 3 b : 2 a : 1 python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Oct, 2020" }, { "code": null, "e": 91, "s": 54, "text": "Prerequisite: Dictionaries in Python" }, { "code": null, "e": 433, "s": 91, "text": "A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and also reverse sorting by keys." }, { "code": null, "e": 578, "s": 433, "text": "keys() method returns a view object that displays a list of all the keys in the dictionary. sorted() is used to sort the keys of the dictionary." }, { "code": null, "e": 588, "s": 578, "text": "Examples:" }, { "code": null, "e": 665, "s": 588, "text": "Input:\nmy_dict = {'c':3, 'a':1, 'd':4, 'b':2}\n\nOutput:\na: 1\nb: 2\nc: 3\nd: 4\n\n" }, { "code": null, "e": 673, "s": 665, "text": "Python3" }, { "code": "# Initialising a dictionarymy_dict = {'c':3, 'a':1, 'd':4, 'b':2} # Sorting dictionarysorted_dict = my_dict.keys()sorted_dict = sorted(sorted_dict) # Printing sorted dictionaryprint(\"Sorted dictionary using sorted() and keys() is : \")for key in sorted_dict: print(key,':', my_dict[key])", "e": 965, "s": 673, "text": null }, { "code": null, "e": 1040, "s": 965, "text": "Sorted dictionary using sorted() and keys() is : \na : 1\nb : 2\nc : 3\nd : 4\n" }, { "code": null, "e": 1268, "s": 1040, "text": "items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary’s (key, value) tuple pair. sorted() is used to sort the keys of the dictionary." }, { "code": null, "e": 1278, "s": 1268, "text": "Examples:" }, { "code": null, "e": 1386, "s": 1278, "text": "Input:\nmy_dict = {2:'three', 1:'two', 4:'five', 3:'four'}\n\nOutput:\n1 'two'\n2 'three'\n3 'Four'\n4 'Five'\n" }, { "code": null, "e": 1394, "s": 1386, "text": "Python3" }, { "code": "# Initialising dictionarymy_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'} # Sorting dictionarysorted_dict = sorted(my_dict.items()) # Printing sorted dictionaryprint(\"Sorted dictionary using sorted() and items() is :\")for k, v in sorted_dict: print(k, v)", "e": 1660, "s": 1394, "text": null }, { "code": null, "e": 1739, "s": 1660, "text": "Sorted dictionary using sorted() and items() is :\n1 two\n2 three\n3 four\n4 five\n" }, { "code": null, "e": 1795, "s": 1739, "text": "Here, we use both sorted() and keys() in a single line." }, { "code": null, "e": 1805, "s": 1795, "text": "Examples:" }, { "code": null, "e": 1903, "s": 1805, "text": "Input:\nmy_dict = {'c':3, 'a':1, 'd':4, 'b':2}\n\nOutput:\nSorted dictionary is : ['a','b','c','d']\n" }, { "code": null, "e": 1911, "s": 1903, "text": "Python3" }, { "code": "# Initialising a dictionarymy_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}# Sorting dictionarysorted_dict = sorted(my_dict.keys()) # Printing sorted dictionaryprint(\"Sorted dictionary is : \", sorted_dict)", "e": 2112, "s": 1911, "text": null }, { "code": null, "e": 2158, "s": 2112, "text": "Sorted dictionary is : ['a', 'b', 'c', 'd']\n" }, { "code": null, "e": 2215, "s": 2158, "text": "Here, we use both sorted() and items() in a single line." }, { "code": null, "e": 2225, "s": 2215, "text": "Examples:" }, { "code": null, "e": 2421, "s": 2225, "text": "Input:\nmy_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'}\n\nOutput:\nSorted dictionary is : \nblack :: #000000\ngreen :: #008000\nred :: #FF0000\nwhite :: #FFFFFF\n" }, { "code": null, "e": 2429, "s": 2421, "text": "Python3" }, { "code": "# Initialising a dictionarymy_dict = {'red': '#FF0000', 'green': '#008000', 'black': '#000000', 'white': '#FFFFFF'} # Sorting dictionary in one linesorted_dict = dict(sorted(my_dict .items())) # Printing sorted dictionaryprint(\"Sorted dictionary is : \")for elem in sorted(sorted_dict.items()): print(elem[0], \" ::\", elem[1])", "e": 2769, "s": 2429, "text": null }, { "code": null, "e": 2864, "s": 2769, "text": "Sorted dictionary is : \nblack :: #000000\ngreen :: #008000\nred :: #FF0000\nwhite :: #FFFFFF\n" }, { "code": null, "e": 3060, "s": 2864, "text": "The lambda function returns the key(0th element) for a specific item tuple, When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary." }, { "code": null, "e": 3070, "s": 3060, "text": "Examples:" }, { "code": null, "e": 3207, "s": 3070, "text": "Input:\nmy_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}\n\nOutput:\nSorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}\n\n" }, { "code": null, "e": 3215, "s": 3207, "text": "Python3" }, { "code": "# Initialising a dictionarymy_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90} # Sorting dictionary using lambda functionsorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1])) # Printing sorted dictionaryprint(\"Sorted dictionary using lambda is : \", sorted_dict)", "e": 3483, "s": 3215, "text": null }, { "code": null, "e": 3557, "s": 3483, "text": "Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}\n" }, { "code": null, "e": 3573, "s": 3557, "text": "6. Using json :" }, { "code": null, "e": 3789, "s": 3573, "text": "Python doesn’t allow sorting of a dictionary. But while converting the dictionary to a JSON, you can explicitly sort it so that the resulting JSON is sorted by keys. This is true for the multidimensional dictionary." }, { "code": null, "e": 3799, "s": 3789, "text": "Examples:" }, { "code": null, "e": 3912, "s": 3799, "text": "Input:\nmy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}\n\nOutput:\nSorted dictionary is : {\"a\": 1, \"b\": 2, \"c\": 3,\"d\":4}\n" }, { "code": null, "e": 3920, "s": 3912, "text": "Python3" }, { "code": "# Importing jsonimport json # Initialising a dictionarymy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4} # Sorting and printind in a single lineprint(\"Sorted dictionary is : \", json.dumps(my_dict, sort_keys=True))", "e": 4127, "s": 3920, "text": null }, { "code": null, "e": 4185, "s": 4127, "text": "Sorted dictionary is : {\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}\n" }, { "code": null, "e": 4402, "s": 4185, "text": "The Python pprint module actually already sorts dictionaries by key. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter." }, { "code": null, "e": 4412, "s": 4402, "text": "Examples:" }, { "code": null, "e": 4524, "s": 4412, "text": "Input:\nmy_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}\n\nOutput:\nSorted dictionary is :\n{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}\n" }, { "code": null, "e": 4532, "s": 4524, "text": "Python3" }, { "code": "# Importing pprintimport pprint # Initialising a dictionarymy_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} # Sorting and printing in a single lineprint(\"Sorted dictionary is :\")pprint.pprint(my_dict)", "e": 4727, "s": 4532, "text": null }, { "code": null, "e": 4870, "s": 4727, "text": "The OrderedDict is a standard library class, which is located in the collections module. OrderedDict maintains the orders of keys as inserted." }, { "code": null, "e": 4880, "s": 4870, "text": "Examples:" }, { "code": null, "e": 4994, "s": 4880, "text": "Input:\nmy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}1}\n\nOutput:\nOrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n" }, { "code": null, "e": 5001, "s": 4994, "text": "Python" }, { "code": "# Importing OrderedDictfrom collections import OrderedDict # Initialising a dictionarymy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4} # Sorting dictionarysorted_dict = OrderedDict(sorted(my_dict.items())) # Printing sorted dictionaryprint(sorted_dict)", "e": 5249, "s": 5001, "text": null }, { "code": null, "e": 5304, "s": 5249, "text": "OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n" }, { "code": null, "e": 5344, "s": 5304, "text": "Using sortedcontainers and SortedDict :" }, { "code": null, "e": 5601, "s": 5344, "text": "Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict is a sorted mutable mapping. Sorted dict inherits from dict to store items and maintains a sorted list of keys. For this, we need to install sortedcontainers." }, { "code": null, "e": 5636, "s": 5601, "text": "sudo pip install sortedcontainers " }, { "code": null, "e": 5646, "s": 5636, "text": "Examples:" }, { "code": null, "e": 5735, "s": 5646, "text": "Input:\nmy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}\n\nOutput:\n{\"a\": 1, \"b\": 2, \"c\": 3,\"d\":4}\n" }, { "code": null, "e": 5743, "s": 5735, "text": "Python3" }, { "code": "# Importing SortedDictfrom sortedcontainers import SortedDict # Initialising a dictionarymy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4} # Sorting dictionarysorted_dict = SortedDict(my_dict) # Printing sorted dictionaryprint(sorted_dict)", "e": 5977, "s": 5743, "text": null }, { "code": null, "e": 5985, "s": 5977, "text": "Output:" }, { "code": null, "e": 6030, "s": 5985, "text": "SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})" }, { "code": null, "e": 6040, "s": 6030, "text": "Examples:" }, { "code": null, "e": 6119, "s": 6040, "text": "Input:\n{\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}\n\nOutput:\n{\"a\": 1, \"b\": 2, \"c\": 3,\"d\":4}\n" }, { "code": null, "e": 6127, "s": 6119, "text": "Python3" }, { "code": "class SortedDisplayDict(dict): def __str__(self): return \"{\" + \", \".join(\"%r: %r\" % (key, self[key]) for key in sorted(self)) + \"}\" # Initialising dictionary and calling classmy_dict = SortedDisplayDict({\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}) # Printing dictionaryprint(my_dict)", "e": 6412, "s": 6127, "text": null }, { "code": null, "e": 6446, "s": 6412, "text": "{'a': 1, 'b': 2, 'c': 3, 'd': 4}\n" }, { "code": null, "e": 6456, "s": 6446, "text": "Examples:" }, { "code": null, "e": 6554, "s": 6456, "text": "Input:\nmy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4}\n\nOutput:\nSorted dictionary is :\n['a','b','c','d']" }, { "code": null, "e": 6562, "s": 6554, "text": "Python3" }, { "code": "# Initialising a dictionarymy_dict = {\"b\": 2, \"c\": 3, \"a\": 1,\"d\":4} # Reverse sorting a dictionarysorted_dict = sorted(my_dict, reverse=True) # Printing dictionaryprint(\"Sorted dictionary is :\") for k in sorted_dict: print(k,':',my_dict[k])", "e": 6807, "s": 6562, "text": null }, { "code": null, "e": 6855, "s": 6807, "text": "Sorted dictionary is :\nd : 4\nc : 3\nb : 2\na : 1\n" }, { "code": null, "e": 6867, "s": 6855, "text": "python-dict" }, { "code": null, "e": 6874, "s": 6867, "text": "Python" }, { "code": null, "e": 6886, "s": 6874, "text": "python-dict" }, { "code": null, "e": 6984, "s": 6886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7016, "s": 6984, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7043, "s": 7016, "text": "Python Classes and Objects" }, { "code": null, "e": 7064, "s": 7043, "text": "Python OOPs Concepts" }, { "code": null, "e": 7087, "s": 7064, "text": "Introduction To PYTHON" }, { "code": null, "e": 7143, "s": 7087, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7174, "s": 7143, "text": "Python | os.path.join() method" }, { "code": null, "e": 7216, "s": 7174, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7258, "s": 7216, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7297, "s": 7258, "text": "Python | Get unique values from a list" } ]
Remove infinite values from a given Pandas DataFrame
26 Jul, 2020 Let’s discuss how to Remove the infinite values from the Pandas dataframe. First let’s make a dataframe: Example: Python3 # Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, np.inf, -np.inf, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf Output: Method 1: Replacing infinite with Nan and then dropping rows with Nan We will first replace the infinite values with the NaN values and then use the dropna() method to remove the rows with infinite values. df.replace() method takes 2 positional arguments. First is the list of values you want to replace and second with which value you want to replace the values. Python3 # Replacing infinite with nandf.replace([np.inf, -np.inf], np.nan, inplace=True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf Output: Method 2: Changing Pandas option to consider infinite as Nan Pandas provide the option to use infinite as Nan. It makes the whole pandas module to consider the infinite values as nan. We can do this by using pd.set_option(). It sets the option globally throughout the complete Jupyter Notebook. Syntax: pd.set_option('mode.use_inf_as_na', True) It sets the options to use infinite as a Nan value throughout the session or until the options are not set back to the False. Python3 # Changing option to use infinite as nanpd.set_option('mode.use_inf_as_na', True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf Output: Method 3: Consider infinite as Nan but using option_context Instead of using pd.set_options(), which sets the option globally, we can use pd.option_context(), which changes option within the certain scope only. Python3 # Changing option to use infinite as nanwith pd.option_context('mode.use_inf_as_na', True): # Dropping the rows with nan # (or inf) values df.dropna(inplace=True) # Printing dfdf Output: Method 4: Using the filter We will first create a filter which returns a boolean dataframe and use this filter to mask the infinite values. Python3 # Creating filterdf_filter = df.isin([np.nan, np.inf, -np.inf]) # Masking df with the filterdf = df[~df_filter] # Dropping rows with nan valuesdf.dropna(inplace=True) # Printing dfdf Output: 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": "\n26 Jul, 2020" }, { "code": null, "e": 134, "s": 28, "text": "Let’s discuss how to Remove the infinite values from the Pandas dataframe. First let’s make a dataframe:" }, { "code": null, "e": 143, "s": 134, "text": "Example:" }, { "code": null, "e": 151, "s": 143, "text": "Python3" }, { "code": "# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, np.inf, -np.inf, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf", "e": 535, "s": 151, "text": null }, { "code": null, "e": 545, "s": 535, "text": "Output: " }, { "code": null, "e": 617, "s": 547, "text": "Method 1: Replacing infinite with Nan and then dropping rows with Nan" }, { "code": null, "e": 913, "s": 617, "text": "We will first replace the infinite values with the NaN values and then use the dropna() method to remove the rows with infinite values. df.replace() method takes 2 positional arguments. First is the list of values you want to replace and second with which value you want to replace the values. " }, { "code": null, "e": 921, "s": 913, "text": "Python3" }, { "code": "# Replacing infinite with nandf.replace([np.inf, -np.inf], np.nan, inplace=True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf", "e": 1083, "s": 921, "text": null }, { "code": null, "e": 1093, "s": 1083, "text": "Output: " }, { "code": null, "e": 1156, "s": 1095, "text": "Method 2: Changing Pandas option to consider infinite as Nan" }, { "code": null, "e": 1399, "s": 1156, "text": "Pandas provide the option to use infinite as Nan. It makes the whole pandas module to consider the infinite values as nan. We can do this by using pd.set_option(). It sets the option globally throughout the complete Jupyter Notebook. Syntax:" }, { "code": null, "e": 1442, "s": 1399, "text": "pd.set_option('mode.use_inf_as_na', True)\n" }, { "code": null, "e": 1570, "s": 1442, "text": "It sets the options to use infinite as a Nan value throughout the session or until the options are not set back to the False. " }, { "code": null, "e": 1578, "s": 1570, "text": "Python3" }, { "code": "# Changing option to use infinite as nanpd.set_option('mode.use_inf_as_na', True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf", "e": 1741, "s": 1578, "text": null }, { "code": null, "e": 1751, "s": 1741, "text": "Output: " }, { "code": null, "e": 1813, "s": 1753, "text": "Method 3: Consider infinite as Nan but using option_context" }, { "code": null, "e": 1965, "s": 1813, "text": "Instead of using pd.set_options(), which sets the option globally, we can use pd.option_context(), which changes option within the certain scope only. " }, { "code": null, "e": 1973, "s": 1965, "text": "Python3" }, { "code": "# Changing option to use infinite as nanwith pd.option_context('mode.use_inf_as_na', True): # Dropping the rows with nan # (or inf) values df.dropna(inplace=True) # Printing dfdf", "e": 2167, "s": 1973, "text": null }, { "code": null, "e": 2177, "s": 2167, "text": "Output: " }, { "code": null, "e": 2206, "s": 2179, "text": "Method 4: Using the filter" }, { "code": null, "e": 2321, "s": 2206, "text": "We will first create a filter which returns a boolean dataframe and use this filter to mask the infinite values. " }, { "code": null, "e": 2329, "s": 2321, "text": "Python3" }, { "code": "# Creating filterdf_filter = df.isin([np.nan, np.inf, -np.inf]) # Masking df with the filterdf = df[~df_filter] # Dropping rows with nan valuesdf.dropna(inplace=True) # Printing dfdf", "e": 2515, "s": 2329, "text": null }, { "code": null, "e": 2525, "s": 2515, "text": "Output: " }, { "code": null, "e": 2552, "s": 2527, "text": "pandas-dataframe-program" }, { "code": null, "e": 2576, "s": 2552, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2590, "s": 2576, "text": "Python-pandas" }, { "code": null, "e": 2597, "s": 2590, "text": "Python" } ]
HSQLDB - Joins
Whenever there is a requirement to retrieve data from multiple tables using a single query, you can use JOINS from RDBMS. You can use multiple tables in your single SQL query. The act of joining in HSQLDB refers to smashing two or more tables into a single table. Consider the following Customers and Orders tables. Customer: +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Orders: +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us try to retrieve the data of the customers and the order amount that the respective customer placed. This means we are retrieving the record data from both customers and orders table. We can achieve this by using the JOINS concept in HSQLDB. Following is the JOIN query for the same. SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID; After execution of the above query, you will receive the following output. +----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+ There are different types of joins available in HSQLDB. INNER JOIN − Returns the rows when there is a match in both tables. INNER JOIN − Returns the rows when there is a match in both tables. LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table. LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table. RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table. FULL JOIN − Returns the rows when there is a match in one of the tables. FULL JOIN − Returns the rows when there is a match in one of the tables. SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. The most frequently used and important of the joins is the INNER JOIN. It is also referred to as an EQUIJOIN. The INNER JOIN creates a new result table by combining the column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows, which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows A and B are combined into a result row. The basic syntax of INNER JOIN is as follows. SELECT table1.column1, table2.column2... FROM table1 INNER JOIN table2 ON table1.common_field = table2.common_field; Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ +-----+---------------------+-------------+--------+ | OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables using INNER JOIN query as follows − SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; After execution of the above query, you will receive the following output. +----+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +----+----------+--------+---------------------+ | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +----+----------+--------+---------------------+ The HSQLDB LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table, the join will still return a row in the result, but with NULL in each column from the right table. This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate. The basic syntax of LEFT JOIN is as follows − SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2 ON table1.common_field = table2.common_field; Here the given condition could be any given expression based on your requirement. Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ +-----+---------------------+-------------+--------+ | OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables using the LEFT JOIN query as follows − SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; After execution of the above query, you will receive the following output − +----+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +----+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | +----+----------+--------+---------------------+ The HSQLDB RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in the left table, the join will still return a row in the result, but with NULL in each column from the left table. This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate. The basic syntax of RIGHT JOIN is as follows − SELECT table1.column1, table2.column2... FROM table1 RIGHT JOIN table2 ON table1.common_field = table2.common_field; Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ +-----+---------------------+-------------+--------+ | OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables using the RIGHT JOIN query as follows − SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; After execution of the above query, you will receive the following result. +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +------+----------+--------+---------------------+ The HSQLDB FULL JOIN combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for the missing matches on either side. The basic syntax of FULL JOIN is as follows − SELECT table1.column1, table2.column2... FROM table1 FULL JOIN table2 ON table1.common_field = table2.common_field; Here the given condition could be any given expression based on your requirement. Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ +-----+---------------------+-------------+--------+ | OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables using the FULL JOIN query as follows − SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS FULL JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; After execution of the above query, you will receive the following result. +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +------+----------+--------+---------------------+ The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. The basic syntax of SELF JOIN is as follows − SELECT a.column_name, b.column_name... FROM table1 a, table1 b WHERE a.common_field = b.common_field; Here, the WHERE clause could be any given expression based on your requirement. Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now, let us join this table using the SELF JOIN query as follows − SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b WHERE a.SALARY > b.SALARY; After execution of the above query, you will receive the following output − +----+----------+---------+ | ID | NAME | SALARY | +----+----------+---------+ | 2 | Ramesh | 1500.00 | | 2 | kaushik | 1500.00 | | 1 | Chaitali | 2000.00 | | 2 | Chaitali | 1500.00 | | 3 | Chaitali | 2000.00 | | 6 | Chaitali | 4500.00 | | 1 | Hardik | 2000.00 | | 2 | Hardik | 1500.00 | | 3 | Hardik | 2000.00 | | 4 | Hardik | 6500.00 | | 6 | Hardik | 4500.00 | | 1 | Komal | 2000.00 | | 2 | Komal | 1500.00 | | 3 | Komal | 2000.00 | | 1 | Muffy | 2000.00 | | 2 | Muffy | 1500.00 | | 3 | Muffy | 2000.00 | | 4 | Muffy | 6500.00 | | 5 | Muffy | 8500.00 | | 6 | Muffy | 4500.00 | +----+----------+---------+ Print Add Notes Bookmark this page
[ { "code": null, "e": 2246, "s": 1982, "text": "Whenever there is a requirement to retrieve data from multiple tables using a single query, you can use JOINS from RDBMS. You can use multiple tables in your single SQL query. The act of joining in HSQLDB refers to smashing two or more tables into a single table." }, { "code": null, "e": 2298, "s": 2246, "text": "Consider the following Customers and Orders tables." }, { "code": null, "e": 3258, "s": 2298, "text": "Customer:\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\nOrders:\n+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n" }, { "code": null, "e": 3553, "s": 3258, "text": "Now, let us try to retrieve the data of the customers and the order amount that the respective customer placed. This means we are retrieving the record data from both customers and orders table. We can achieve this by using the JOINS concept in HSQLDB. Following is the JOIN query for the same." }, { "code": null, "e": 3646, "s": 3553, "text": "SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID =\nORDERS.CUSTOMER_ID;" }, { "code": null, "e": 3721, "s": 3646, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 3986, "s": 3721, "text": "+----+----------+-----+--------+\n| ID | NAME | AGE | AMOUNT |\n+----+----------+-----+--------+\n| 3 | kaushik | 23 | 3000 |\n| 3 | kaushik | 23 | 1500 |\n| 2 | Khilan | 25 | 1560 |\n| 4 | Chaitali | 25 | 2060 |\n+----+----------+-----+--------+\n" }, { "code": null, "e": 4042, "s": 3986, "text": "There are different types of joins available in HSQLDB." }, { "code": null, "e": 4110, "s": 4042, "text": "INNER JOIN − Returns the rows when there is a match in both tables." }, { "code": null, "e": 4178, "s": 4110, "text": "INNER JOIN − Returns the rows when there is a match in both tables." }, { "code": null, "e": 4277, "s": 4178, "text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table." }, { "code": null, "e": 4376, "s": 4277, "text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table." }, { "code": null, "e": 4476, "s": 4376, "text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table." }, { "code": null, "e": 4576, "s": 4476, "text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table." }, { "code": null, "e": 4649, "s": 4576, "text": "FULL JOIN − Returns the rows when there is a match in one of the tables." }, { "code": null, "e": 4722, "s": 4649, "text": "FULL JOIN − Returns the rows when there is a match in one of the tables." }, { "code": null, "e": 4860, "s": 4722, "text": "SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement." }, { "code": null, "e": 4998, "s": 4860, "text": "SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement." }, { "code": null, "e": 5108, "s": 4998, "text": "The most frequently used and important of the joins is the INNER JOIN. It is also referred to as an EQUIJOIN." }, { "code": null, "e": 5495, "s": 5108, "text": "The INNER JOIN creates a new result table by combining the column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows, which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows A and B are combined into a result row." }, { "code": null, "e": 5541, "s": 5495, "text": "The basic syntax of INNER JOIN is as follows." }, { "code": null, "e": 5658, "s": 5541, "text": "SELECT table1.column1, table2.column2...\nFROM table1\nINNER JOIN table2\nON table1.common_field = table2.common_field;" }, { "code": null, "e": 5771, "s": 5658, "text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −" }, { "code": null, "e": 6289, "s": 5771, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 6714, "s": 6289, "text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n" }, { "code": null, "e": 6784, "s": 6714, "text": "Now, let us join these two tables using INNER JOIN query as follows −" }, { "code": null, "e": 6885, "s": 6784, "text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nINNER JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 6960, "s": 6885, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 7353, "s": 6960, "text": "+----+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+----+----------+--------+---------------------+\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+----+----------+--------+---------------------+\n" }, { "code": null, "e": 7638, "s": 7353, "text": "The HSQLDB LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table, the join will still return a row in the result, but with NULL in each column from the right table." }, { "code": null, "e": 7798, "s": 7638, "text": "This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate." }, { "code": null, "e": 7844, "s": 7798, "text": "The basic syntax of LEFT JOIN is as follows −" }, { "code": null, "e": 7960, "s": 7844, "text": "SELECT table1.column1, table2.column2...\nFROM table1\nLEFT JOIN table2\nON table1.common_field = table2.common_field;" }, { "code": null, "e": 8042, "s": 7960, "text": "Here the given condition could be any given expression based on your requirement." }, { "code": null, "e": 8155, "s": 8042, "text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −" }, { "code": null, "e": 8673, "s": 8155, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 9098, "s": 8673, "text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n" }, { "code": null, "e": 9171, "s": 9098, "text": "Now, let us join these two tables using the LEFT JOIN query as follows −" }, { "code": null, "e": 9271, "s": 9171, "text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nLEFT JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 9347, "s": 9271, "text": "After execution of the above query, you will receive the following output −" }, { "code": null, "e": 9936, "s": 9347, "text": "+----+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+----+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n+----+----------+--------+---------------------+\n" }, { "code": null, "e": 10220, "s": 9936, "text": "The HSQLDB RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in the left table, the join will still return a row in the result, but with NULL in each column from the left table." }, { "code": null, "e": 10381, "s": 10220, "text": "This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate." }, { "code": null, "e": 10428, "s": 10381, "text": "The basic syntax of RIGHT JOIN is as follows −" }, { "code": null, "e": 10545, "s": 10428, "text": "SELECT table1.column1, table2.column2...\nFROM table1\nRIGHT JOIN table2\nON table1.common_field = table2.common_field;" }, { "code": null, "e": 10658, "s": 10545, "text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −" }, { "code": null, "e": 11176, "s": 10658, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 11601, "s": 11176, "text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n" }, { "code": null, "e": 11675, "s": 11601, "text": "Now, let us join these two tables using the RIGHT JOIN query as follows −" }, { "code": null, "e": 11776, "s": 11675, "text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nRIGHT JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 11851, "s": 11776, "text": "After execution of the above query, you will receive the following result." }, { "code": null, "e": 12260, "s": 11851, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 12338, "s": 12260, "text": "The HSQLDB FULL JOIN combines the results of both left and right outer joins." }, { "code": null, "e": 12456, "s": 12338, "text": "The joined table will contain all records from both tables, and fill in NULLs for the missing matches on either side." }, { "code": null, "e": 12502, "s": 12456, "text": "The basic syntax of FULL JOIN is as follows −" }, { "code": null, "e": 12619, "s": 12502, "text": "SELECT table1.column1, table2.column2...\nFROM table1\nFULL JOIN table2\nON table1.common_field = table2.common_field;\n" }, { "code": null, "e": 12701, "s": 12619, "text": "Here the given condition could be any given expression based on your requirement." }, { "code": null, "e": 12814, "s": 12701, "text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as\nORDERS table as follows −" }, { "code": null, "e": 13332, "s": 12814, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 13757, "s": 13332, "text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n" }, { "code": null, "e": 13830, "s": 13757, "text": "Now, let us join these two tables using the FULL JOIN query as follows −" }, { "code": null, "e": 13930, "s": 13830, "text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nFULL JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 14005, "s": 13930, "text": "After execution of the above query, you will receive the following result." }, { "code": null, "e": 14822, "s": 14005, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 14969, "s": 14822, "text": "The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement." }, { "code": null, "e": 15015, "s": 14969, "text": "The basic syntax of SELF JOIN is as follows −" }, { "code": null, "e": 15117, "s": 15015, "text": "SELECT a.column_name, b.column_name...\nFROM table1 a, table1 b\nWHERE a.common_field = b.common_field;" }, { "code": null, "e": 15197, "s": 15117, "text": "Here, the WHERE clause could be any given expression based on your requirement." }, { "code": null, "e": 15310, "s": 15197, "text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −" }, { "code": null, "e": 15828, "s": 15310, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 15895, "s": 15828, "text": "Now, let us join this table using the SELF JOIN query as follows −" }, { "code": null, "e": 15983, "s": 15895, "text": "SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b\nWHERE a.SALARY > b.SALARY;\n" }, { "code": null, "e": 16059, "s": 15983, "text": "After execution of the above query, you will receive the following output −" }, { "code": null, "e": 16732, "s": 16059, "text": "+----+----------+---------+\n| ID | NAME | SALARY |\n+----+----------+---------+\n| 2 | Ramesh | 1500.00 |\n| 2 | kaushik | 1500.00 |\n| 1 | Chaitali | 2000.00 |\n| 2 | Chaitali | 1500.00 |\n| 3 | Chaitali | 2000.00 |\n| 6 | Chaitali | 4500.00 |\n| 1 | Hardik | 2000.00 |\n| 2 | Hardik | 1500.00 |\n| 3 | Hardik | 2000.00 |\n| 4 | Hardik | 6500.00 |\n| 6 | Hardik | 4500.00 |\n| 1 | Komal | 2000.00 |\n| 2 | Komal | 1500.00 |\n| 3 | Komal | 2000.00 |\n| 1 | Muffy | 2000.00 |\n| 2 | Muffy | 1500.00 |\n| 3 | Muffy | 2000.00 |\n| 4 | Muffy | 6500.00 |\n| 5 | Muffy | 8500.00 |\n| 6 | Muffy | 4500.00 |\n+----+----------+---------+\n" }, { "code": null, "e": 16739, "s": 16732, "text": " Print" }, { "code": null, "e": 16750, "s": 16739, "text": " Add Notes" } ]
How to Add Text in the RichTextBox in C#? - GeeksforGeeks
17 Jul, 2019 In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to add text in the RichTextBox control which displays on the screen using Text Property. You can set this property in two different ways: 1. Design-Time: It is the easiest way to add text in the RichTextBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RichTextBox control to add text in the RichTextBox control.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can add text in the RichTextBox control programmatically with the help of given syntax: public override string Text { get; set; } Here, the value of this property is of System.String type. The following steps show how to set the Text property of the RichTextBox dynamically: Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); // Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); Step 2: After creating RichTextBox, set the Text property of the RichTextBox provided by the RichTextBox class.// Adding text in the control box rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding text in the control box rbox.Text = "!..Welcome to GeeksforGeeks..!"; Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form this.Controls.Add(rbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output: // Add this RichTextBox to the form this.Controls.Add(rbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Class and Object C# | Abstract Classes
[ { "code": null, "e": 24289, "s": 24261, "text": "\n17 Jul, 2019" }, { "code": null, "e": 24756, "s": 24289, "text": "In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to add text in the RichTextBox control which displays on the screen using Text Property. You can set this property in two different ways:" }, { "code": null, "e": 24858, "s": 24756, "text": "1. Design-Time: It is the easiest way to add text in the RichTextBox as shown in the following steps:" }, { "code": null, "e": 24974, "s": 24858, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 25161, "s": 24974, "text": "Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need." }, { "code": null, "e": 25293, "s": 25161, "text": "Step 3: After drag and drop you will go to the properties of the RichTextBox control to add text in the RichTextBox control.Output:" }, { "code": null, "e": 25301, "s": 25293, "text": "Output:" }, { "code": null, "e": 25473, "s": 25301, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can add text in the RichTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 25515, "s": 25473, "text": "public override string Text { get; set; }" }, { "code": null, "e": 25660, "s": 25515, "text": "Here, the value of this property is of System.String type. The following steps show how to set the Text property of the RichTextBox dynamically:" }, { "code": null, "e": 25861, "s": 25660, "text": "Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 25960, "s": 25861, "text": "// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 26152, "s": 25960, "text": "Step 2: After creating RichTextBox, set the Text property of the RichTextBox provided by the RichTextBox class.// Adding text in the control box\nrbox.Text = \"!..Welcome to GeeksforGeeks..!\";\n" }, { "code": null, "e": 26233, "s": 26152, "text": "// Adding text in the control box\nrbox.Text = \"!..Welcome to GeeksforGeeks..!\";\n" }, { "code": null, "e": 27363, "s": 26233, "text": "Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output:" }, { "code": null, "e": 27425, "s": 27363, "text": "// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\n" }, { "code": null, "e": 27434, "s": 27425, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}", "e": 28411, "s": 27434, "text": null }, { "code": null, "e": 28419, "s": 28411, "text": "Output:" }, { "code": null, "e": 28422, "s": 28419, "text": "C#" }, { "code": null, "e": 28520, "s": 28422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28529, "s": 28520, "text": "Comments" }, { "code": null, "e": 28542, "s": 28529, "text": "Old Comments" }, { "code": null, "e": 28565, "s": 28542, "text": "C# | Method Overriding" }, { "code": null, "e": 28593, "s": 28565, "text": "C# Dictionary with examples" }, { "code": null, "e": 28639, "s": 28593, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28654, "s": 28639, "text": "C# | Delegates" }, { "code": null, "e": 28694, "s": 28654, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28712, "s": 28694, "text": "C# | Constructors" }, { "code": null, "e": 28735, "s": 28712, "text": "Extension Method in C#" }, { "code": null, "e": 28766, "s": 28735, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28788, "s": 28766, "text": "C# | Class and Object" } ]
Tryit Editor v3.7
HTML Input attributes Tryit: The multiple attribute
[ { "code": null, "e": 32, "s": 10, "text": "HTML Input attributes" } ]
How to handle jQuery AJAX success event?
To handle jQuery AJAX success event, use the ajaxSuccess() method. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event. Here is the description of all the parameters used by this method − callback − The function to execute. The event object, XMLHttpRequest, and settings used for that request are passed as arguments to the callback. Let’s say we have the following HTML content in result.html − <h1>THIS IS RESULT...</h1> The following is an example showing the usage of this method − Live Demo <html> <head> <title>jQuery ajaxSuccess() method</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { /* Global variable */ var count = 0; $("#driver").click(function(event){ $('#stage0').load('result.html'); }); /* Gets called when request starts */ $(document).ajaxStart(function(){ count++; $("#stage1").html("<h1>Starts, Count :" + count + "</h1>"); }); /* Gets called when request is sent */ $(document).ajaxSend(function(evt, req, set){ count++; $("#stage2").html("<h1>Sends, Count :" + count + "</h1>"); $("#stage2").append("<h1>URL :" + set.url + "</h1>"); }); /* Gets called when request completes */ $(document).ajaxComplete(function(event,request,settings){ count++; $("#stage3").html("<h1>Completes,Count:" + count + "</h1>"); }); /* Gets called when request is stopped */ $(document).ajaxStop(function(event,request,settings){ count++; $("#stage4").html("<h1>Stops, Count :" + count + "</h1>"); }); /* Gets called when all request completes successfully */ $(document).ajaxSuccess(function(event,request,settings){ count++; $("#stage5").html("<h1>Success,Count :" + count + "</h1>"); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage0" style = "background-color:blue;"> STAGE - 0 </div> <div id = "stage1" style = "background-color:blue;"> STAGE - 1 </div> <div id = "stage2" style = "background-color:blue;"> STAGE - 2 </div> <div id = "stage3" style = "background-color:blue;"> STAGE - 3 </div> <div id = "stage4" style = "background-color:blue;"> STAGE - 4 </div> <div id = "stage5" style = "background-color:blue;"> STAGE - 5 </div> <input type = "button" id = "driver" value="Load Data" /> </body> </html>
[ { "code": null, "e": 1271, "s": 1062, "text": "To handle jQuery AJAX success event, use the ajaxSuccess() method. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event." }, { "code": null, "e": 1339, "s": 1271, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 1485, "s": 1339, "text": "callback − The function to execute. The event object, XMLHttpRequest, and settings used for that request are passed as arguments to the callback." }, { "code": null, "e": 1547, "s": 1485, "text": "Let’s say we have the following HTML content in result.html −" }, { "code": null, "e": 1574, "s": 1547, "text": "<h1>THIS IS RESULT...</h1>" }, { "code": null, "e": 1637, "s": 1574, "text": "The following is an example showing the usage of this method −" }, { "code": null, "e": 1647, "s": 1637, "text": "Live Demo" }, { "code": null, "e": 4201, "s": 1647, "text": "<html>\n\n <head>\n <title>jQuery ajaxSuccess() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n /* Global variable */\n var count = 0;\n\n $(\"#driver\").click(function(event){\n $('#stage0').load('result.html');\n });\n \n /* Gets called when request starts */\n $(document).ajaxStart(function(){\n count++;\n $(\"#stage1\").html(\"<h1>Starts, Count :\" + count + \"</h1>\");\n });\n \n /* Gets called when request is sent */\n $(document).ajaxSend(function(evt, req, set){\n count++;\n $(\"#stage2\").html(\"<h1>Sends, Count :\" + count + \"</h1>\");\n $(\"#stage2\").append(\"<h1>URL :\" + set.url + \"</h1>\");\n });\n \n /* Gets called when request completes */\n $(document).ajaxComplete(function(event,request,settings){\n count++;\n $(\"#stage3\").html(\"<h1>Completes,Count:\" + count + \"</h1>\");\n });\n \n /* Gets called when request is stopped */\n $(document).ajaxStop(function(event,request,settings){\n count++;\n $(\"#stage4\").html(\"<h1>Stops, Count :\" + count + \"</h1>\");\n });\n \n /* Gets called when all request completes successfully */\n $(document).ajaxSuccess(function(event,request,settings){\n count++;\n $(\"#stage5\").html(\"<h1>Success,Count :\" + count + \"</h1>\");\n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage0\" style = \"background-color:blue;\">\n STAGE - 0\n </div>\n \n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n \n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n \n <div id = \"stage3\" style = \"background-color:blue;\">\n STAGE - 3\n </div>\n \n <div id = \"stage4\" style = \"background-color:blue;\">\n STAGE - 4\n </div>\n \n <div id = \"stage5\" style = \"background-color:blue;\">\n STAGE - 5\n </div>\n \n <input type = \"button\" id = \"driver\" value=\"Load Data\" />\n \n </body>\n</html>" } ]
Introduction to GitHub Actions. For data scientists | by Déborah Mesquita | Towards Data Science
GitHub Actions can be a little confusing if you’re new to DevOps and the CI/CD world, so in this article, we’re going to explore some features and see what we can do using the tool. From the point of view of CI/CD, the main goal of GitHub Actions and Workflows is to test our software every time something changes. This way we can spot bugs and correct things as soon as the errors come up. Today we’ll learn more about GitHub Actions and learn how to use them using Bash scripting and Python. Nice, let’s get started! First, it’s good to state the difference between GitHub Actions and Workflows. As the GitHub Actions Documentation states, actions are “individual tasks that you can combine to create jobs and customize your workflow”. On the other hand, Workflows are “custom automated processes that you can set up in your repository to build, test, package, release, or deploy any project on GitHub”. In other words: Workflows: automated processes that run on your repository; workflows can have many GitHub Actions GitHub Actions: individual tasks; they can be written using Docker, JavaScript and now also shell scrips with the new Composite Run Steps; you can write your own actions or use an action someone else created Let’s first create a workflow with no action just to understand how it works. Workflows are defined using YAML files and you must store them in the .github/workflows directory in the root of your repository. To create a workflow we need to define these things: The event that triggers the workflow The machine each job should run The jobs that make the workflow (jobs contain a set of steps that perform individual tasks and run in parallel by default) The steps each job should run The basic syntax for a workflow is: on — the event that triggers the workflow runs-on — the machine each job should run jobs — the jobs that make the workflow steps —the tasks each job should run run —the command the step should run First, we need to define the event that triggers the workflow. In this example, we want to say greetings every time someone pushes to the repository. A workflow run is made up of one or more jobs. Each job runs in a machine specified by runs-on. The machine can be either a GitHub-hosted runner, or a self-hosted runner. We’re going to use the ubuntu-latest GitHub-hosted runner. A job contains a sequence of tasks called steps. Steps can run commands, run setup tasks, or run an action. Each step has can have a run command that uses the operating system’s shell. Here we’re going to echo a message. Confusing? Let’s see how it works. Go ahead and create a first_workflow.yml file inside .github/workflows on your repo, then paste this code: # your-repo-name/.github/workflows/first_workflow.ymlname: First Workflow on: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow! Now if you commit this file to your repository, push it and go to the Actions tab on the GitHub website you can see the new workflow, check all the runs and view the outputs: Actions are individual tasks and we can use them from three sources: Actions defined in the same repository as the workflow Actions defined in a public repository Actions defined in a published Docker container image They run as a step in our workflow. To call them we use the uses syntax. In this example, we’re going to use an Action that prints ASCII art text, written by Mike Coutermarsh. Since it’s defined in a public repository we just need to pass it’s name: # your-repo-name/.github/workflows/first_workflow.ymlname: First Workflowon: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow! - name: Show ASCII greeting uses: mscoutermarsh/ascii-art-action@master with: text: 'HELLO!' The with syntax is a map of input parameters defined by the action. Here is the result: As Data Scientists we use a lot of Python in our day to day, so it’s a good idea to learn how to use it in our workflows. Setting a specific version of Python or PyPy is the recommended way of using Python with GitHub Actions because it “ensures consistent behavior across different runners and different versions of Python”. To do that we’ll use an action: setup-python. After that, we can run the commands as we usually do in a machine. Here we’ll install Scrapy and run a script to get some TDS posts about GitHub Actions, just to see how it works. Since we want to run a script from our own repository we also need to use the checkout action to access it. Let’s create a new job to run the script: # your-repo-name/.github/workflows/first_workflow.ymlname: First Workflowon: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow! - name: Show ASCII greeting uses: mscoutermarsh/ascii-art-action@master with: text: 'HELLO!' get-posts-job: name: Get TDS posts runs-on: ubuntu-latest steps: - name: Check-out the repo under $GITHUB_WORKSPACE uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install Scrapy run: pip install scrapy - name: Get TDS posts about GitHub Actions run: scrapy runspider posts_spider.py -o posts.json I want to save the scraped posts to a file, so let’s learn how to do it. An artifact is a file or collection of files produced during a workflow run. We can pass an artifact to another job in the same workflow or download it using the GitHub UI. Let’s download the JSON file with the posts to see how it works. To work with artifacts we use the upload-artifact and download-artifact actions. To upload an artifact we need to specify the path to the file or directory and the name of the artifact: # your-repo-name/.github/workflows/first_workflow.yml# [...]get-posts-job: name: Get TDS posts runs-on: ubuntu-latest steps: - name: Check-out the repo under $GITHUB_WORKSPACE uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install Scrapy run: pip install scrapy - name: Get TDS posts about GitHub Actions run: scrapy runspider posts_spider.py -o posts.json - name: Upload artifact uses: actions/upload-artifact@v2 with: name: posts path: posts.json And now we can download the file using the GitHub UI: Actions can be created using Docker containers, JavaScript or you can create an action using shell scripts (a composite run steps action). The main use case for the composite run steps action is when you have a lot of shell scripts to automate tasks and writing a shell script to combine them is easier than JavaScript or Docker. The three main components of an action are runs , inputs and outputs. runs — (required) Configures the path to the action’s code and the application used to execute the code. inputs — (optional) Input parameters allow you to specify data that the action expects to use during runtime outputs — (optional) Output parameters allow you to declare data that an action sets The filename for an action must be either action.yml or action.yaml. Let’s use the example from GitHub Docs and create an action that prints a “Hey [user]” message. Since it’s a composite action we’ll use the using: "composite" syntax: # action.ymlname: 'Hey From a GitHub Action'description: 'Greet someone'inputs: user: # id of input description: 'Who to greet' required: true default: 'You'runs: using: "composite" steps: - run: echo Hey ${{ inputs.user }}. shell: bash If an action is defined in the same repository as the workflow we can refer to it using ./path-to-action-file. In this case, we need to access the file inside the repository, so we also need to use the checkout action. If the action is defined in a public repository we can refer to it using a specific commit, a version of a release or a branch. # .github/workflows/use-action-same-repo.ymlname: Action from the same repoon: push jobs: use-your-own-action: name: Say Hi using your own action runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: ./ # the action.yml file is in the root folder with: user: 'Déborah' # .github/workflows/use-action-public-repo.ymlname: Action from a public repositoryon: push jobs: use-your-own-action: name: Say Hi using your own action runs-on: ubuntu-latest steps: - uses: dmesquita/github-actions-tutorial@master with: user: 'Déborah' And that’s if for our tour. You can also use variables and secrets in your workflow, cache dependencies to speed up them and connect databases and service containers to manage workflow tools. In this guide, we didn’t use one of the main cool things of CI which is to test often so we can spot bugs early on in the process. But I think it’s good to understand how the actions and workflow work before doing that. I hope now it’ll be easier to start using CI tools, I plan to do that on the next tutorials. You can see all the code we used here: https://github.com/dmesquita/github-actions-tutorial That’s it for today, thanks for reading!
[ { "code": null, "e": 354, "s": 172, "text": "GitHub Actions can be a little confusing if you’re new to DevOps and the CI/CD world, so in this article, we’re going to explore some features and see what we can do using the tool." }, { "code": null, "e": 563, "s": 354, "text": "From the point of view of CI/CD, the main goal of GitHub Actions and Workflows is to test our software every time something changes. This way we can spot bugs and correct things as soon as the errors come up." }, { "code": null, "e": 691, "s": 563, "text": "Today we’ll learn more about GitHub Actions and learn how to use them using Bash scripting and Python. Nice, let’s get started!" }, { "code": null, "e": 1094, "s": 691, "text": "First, it’s good to state the difference between GitHub Actions and Workflows. As the GitHub Actions Documentation states, actions are “individual tasks that you can combine to create jobs and customize your workflow”. On the other hand, Workflows are “custom automated processes that you can set up in your repository to build, test, package, release, or deploy any project on GitHub”. In other words:" }, { "code": null, "e": 1193, "s": 1094, "text": "Workflows: automated processes that run on your repository; workflows can have many GitHub Actions" }, { "code": null, "e": 1401, "s": 1193, "text": "GitHub Actions: individual tasks; they can be written using Docker, JavaScript and now also shell scrips with the new Composite Run Steps; you can write your own actions or use an action someone else created" }, { "code": null, "e": 1609, "s": 1401, "text": "Let’s first create a workflow with no action just to understand how it works. Workflows are defined using YAML files and you must store them in the .github/workflows directory in the root of your repository." }, { "code": null, "e": 1662, "s": 1609, "text": "To create a workflow we need to define these things:" }, { "code": null, "e": 1699, "s": 1662, "text": "The event that triggers the workflow" }, { "code": null, "e": 1731, "s": 1699, "text": "The machine each job should run" }, { "code": null, "e": 1854, "s": 1731, "text": "The jobs that make the workflow (jobs contain a set of steps that perform individual tasks and run in parallel by default)" }, { "code": null, "e": 1884, "s": 1854, "text": "The steps each job should run" }, { "code": null, "e": 1920, "s": 1884, "text": "The basic syntax for a workflow is:" }, { "code": null, "e": 1962, "s": 1920, "text": "on — the event that triggers the workflow" }, { "code": null, "e": 2004, "s": 1962, "text": "runs-on — the machine each job should run" }, { "code": null, "e": 2043, "s": 2004, "text": "jobs — the jobs that make the workflow" }, { "code": null, "e": 2080, "s": 2043, "text": "steps —the tasks each job should run" }, { "code": null, "e": 2117, "s": 2080, "text": "run —the command the step should run" }, { "code": null, "e": 2267, "s": 2117, "text": "First, we need to define the event that triggers the workflow. In this example, we want to say greetings every time someone pushes to the repository." }, { "code": null, "e": 2497, "s": 2267, "text": "A workflow run is made up of one or more jobs. Each job runs in a machine specified by runs-on. The machine can be either a GitHub-hosted runner, or a self-hosted runner. We’re going to use the ubuntu-latest GitHub-hosted runner." }, { "code": null, "e": 2718, "s": 2497, "text": "A job contains a sequence of tasks called steps. Steps can run commands, run setup tasks, or run an action. Each step has can have a run command that uses the operating system’s shell. Here we’re going to echo a message." }, { "code": null, "e": 2860, "s": 2718, "text": "Confusing? Let’s see how it works. Go ahead and create a first_workflow.yml file inside .github/workflows on your repo, then paste this code:" }, { "code": null, "e": 3341, "s": 2860, "text": "# your-repo-name/.github/workflows/first_workflow.ymlname: First Workflow on: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow!" }, { "code": null, "e": 3516, "s": 3341, "text": "Now if you commit this file to your repository, push it and go to the Actions tab on the GitHub website you can see the new workflow, check all the runs and view the outputs:" }, { "code": null, "e": 3585, "s": 3516, "text": "Actions are individual tasks and we can use them from three sources:" }, { "code": null, "e": 3640, "s": 3585, "text": "Actions defined in the same repository as the workflow" }, { "code": null, "e": 3679, "s": 3640, "text": "Actions defined in a public repository" }, { "code": null, "e": 3733, "s": 3679, "text": "Actions defined in a published Docker container image" }, { "code": null, "e": 3983, "s": 3733, "text": "They run as a step in our workflow. To call them we use the uses syntax. In this example, we’re going to use an Action that prints ASCII art text, written by Mike Coutermarsh. Since it’s defined in a public repository we just need to pass it’s name:" }, { "code": null, "e": 4613, "s": 3983, "text": "# your-repo-name/.github/workflows/first_workflow.ymlname: First Workflowon: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow! - name: Show ASCII greeting uses: mscoutermarsh/ascii-art-action@master with: text: 'HELLO!'" }, { "code": null, "e": 4701, "s": 4613, "text": "The with syntax is a map of input parameters defined by the action. Here is the result:" }, { "code": null, "e": 5073, "s": 4701, "text": "As Data Scientists we use a lot of Python in our day to day, so it’s a good idea to learn how to use it in our workflows. Setting a specific version of Python or PyPy is the recommended way of using Python with GitHub Actions because it “ensures consistent behavior across different runners and different versions of Python”. To do that we’ll use an action: setup-python." }, { "code": null, "e": 5403, "s": 5073, "text": "After that, we can run the commands as we usually do in a machine. Here we’ll install Scrapy and run a script to get some TDS posts about GitHub Actions, just to see how it works. Since we want to run a script from our own repository we also need to use the checkout action to access it. Let’s create a new job to run the script:" }, { "code": null, "e": 6991, "s": 5403, "text": "# your-repo-name/.github/workflows/first_workflow.ymlname: First Workflowon: push jobs: first-job: name: Say hi runs-on: ubuntu-latest steps: - name: Print a greeting run: echo Hi from our first workflow! - name: Show ASCII greeting uses: mscoutermarsh/ascii-art-action@master with: text: 'HELLO!' get-posts-job: name: Get TDS posts runs-on: ubuntu-latest steps: - name: Check-out the repo under $GITHUB_WORKSPACE uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install Scrapy run: pip install scrapy - name: Get TDS posts about GitHub Actions run: scrapy runspider posts_spider.py -o posts.json" }, { "code": null, "e": 7064, "s": 6991, "text": "I want to save the scraped posts to a file, so let’s learn how to do it." }, { "code": null, "e": 7237, "s": 7064, "text": "An artifact is a file or collection of files produced during a workflow run. We can pass an artifact to another job in the same workflow or download it using the GitHub UI." }, { "code": null, "e": 7488, "s": 7237, "text": "Let’s download the JSON file with the posts to see how it works. To work with artifacts we use the upload-artifact and download-artifact actions. To upload an artifact we need to specify the path to the file or directory and the name of the artifact:" }, { "code": null, "e": 8634, "s": 7488, "text": "# your-repo-name/.github/workflows/first_workflow.yml# [...]get-posts-job: name: Get TDS posts runs-on: ubuntu-latest steps: - name: Check-out the repo under $GITHUB_WORKSPACE uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install Scrapy run: pip install scrapy - name: Get TDS posts about GitHub Actions run: scrapy runspider posts_spider.py -o posts.json - name: Upload artifact uses: actions/upload-artifact@v2 with: name: posts path: posts.json" }, { "code": null, "e": 8688, "s": 8634, "text": "And now we can download the file using the GitHub UI:" }, { "code": null, "e": 9018, "s": 8688, "text": "Actions can be created using Docker containers, JavaScript or you can create an action using shell scripts (a composite run steps action). The main use case for the composite run steps action is when you have a lot of shell scripts to automate tasks and writing a shell script to combine them is easier than JavaScript or Docker." }, { "code": null, "e": 9088, "s": 9018, "text": "The three main components of an action are runs , inputs and outputs." }, { "code": null, "e": 9193, "s": 9088, "text": "runs — (required) Configures the path to the action’s code and the application used to execute the code." }, { "code": null, "e": 9302, "s": 9193, "text": "inputs — (optional) Input parameters allow you to specify data that the action expects to use during runtime" }, { "code": null, "e": 9387, "s": 9302, "text": "outputs — (optional) Output parameters allow you to declare data that an action sets" }, { "code": null, "e": 9623, "s": 9387, "text": "The filename for an action must be either action.yml or action.yaml. Let’s use the example from GitHub Docs and create an action that prints a “Hey [user]” message. Since it’s a composite action we’ll use the using: \"composite\" syntax:" }, { "code": null, "e": 9882, "s": 9623, "text": "# action.ymlname: 'Hey From a GitHub Action'description: 'Greet someone'inputs: user: # id of input description: 'Who to greet' required: true default: 'You'runs: using: \"composite\" steps: - run: echo Hey ${{ inputs.user }}. shell: bash" }, { "code": null, "e": 10101, "s": 9882, "text": "If an action is defined in the same repository as the workflow we can refer to it using ./path-to-action-file. In this case, we need to access the file inside the repository, so we also need to use the checkout action." }, { "code": null, "e": 10229, "s": 10101, "text": "If the action is defined in a public repository we can refer to it using a specific commit, a version of a release or a branch." }, { "code": null, "e": 10883, "s": 10229, "text": "# .github/workflows/use-action-same-repo.ymlname: Action from the same repoon: push jobs: use-your-own-action: name: Say Hi using your own action runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: ./ # the action.yml file is in the root folder with: user: 'Déborah'" }, { "code": null, "e": 11462, "s": 10883, "text": "# .github/workflows/use-action-public-repo.ymlname: Action from a public repositoryon: push jobs: use-your-own-action: name: Say Hi using your own action runs-on: ubuntu-latest steps: - uses: dmesquita/github-actions-tutorial@master with: user: 'Déborah'" }, { "code": null, "e": 11654, "s": 11462, "text": "And that’s if for our tour. You can also use variables and secrets in your workflow, cache dependencies to speed up them and connect databases and service containers to manage workflow tools." }, { "code": null, "e": 11967, "s": 11654, "text": "In this guide, we didn’t use one of the main cool things of CI which is to test often so we can spot bugs early on in the process. But I think it’s good to understand how the actions and workflow work before doing that. I hope now it’ll be easier to start using CI tools, I plan to do that on the next tutorials." }, { "code": null, "e": 12059, "s": 11967, "text": "You can see all the code we used here: https://github.com/dmesquita/github-actions-tutorial" } ]
Java Examples - Search in a String
How to search a word inside a string ? This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1. public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) { System.out.println("Hello not found"); } else { System.out.println("Found Hello at index " + intIndex); } } } The above code sample will produce the following result. Found Hello at index 0 This example shows how we can search a word within a String object public class HelloWorld { public static void main(String[] args) { String text = "The cat is on the table"; System.out.print(text.contains("the")); } } The above code sample will produce the following result. true Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 2068, "text": "How to search a word inside a string ?" }, { "code": null, "e": 2292, "s": 2107, "text": "This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1." }, { "code": null, "e": 2631, "s": 2292, "text": "public class SearchStringEmp{\n public static void main(String[] args) {\n String strOrig = \"Hello readers\";\n int intIndex = strOrig.indexOf(\"Hello\");\n \n if(intIndex == - 1) {\n System.out.println(\"Hello not found\");\n } else {\n System.out.println(\"Found Hello at index \" + intIndex);\n }\n }\n}" }, { "code": null, "e": 2688, "s": 2631, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2712, "s": 2688, "text": "Found Hello at index 0\n" }, { "code": null, "e": 2779, "s": 2712, "text": "This example shows how we can search a word within a String object" }, { "code": null, "e": 2949, "s": 2779, "text": "public class HelloWorld {\n public static void main(String[] args) {\n String text = \"The cat is on the table\";\n System.out.print(text.contains(\"the\"));\n }\n}" }, { "code": null, "e": 3006, "s": 2949, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3012, "s": 3006, "text": "true\n" }, { "code": null, "e": 3019, "s": 3012, "text": " Print" }, { "code": null, "e": 3030, "s": 3019, "text": " Add Notes" } ]
Angular 4 - Overview
There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1. The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2. Angular 4 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4. Let us now see the new features and the changes made in Angular 4. The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4. Let us now see the new features added to Angular 4 − Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template. <span *ngIf="isavailable; else condition1">Condition is valid.</span> <ng-template #condition1>Condition is invalid</ng-template> With the help of as keyword you can store the value as shown below − <div *ngFor="let i of months | slice:0:5 as total"> Months: {{i}} Total: {{total.length}} </div> The variable total stores the output of the slice using the as keyword. Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect. Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4. Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project. Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase. <div> <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2> </div> The above line of code generates the following output – Angular 4 Titlecase. Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2. Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 1992, "text": "There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1." }, { "code": null, "e": 2470, "s": 2214, "text": "The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2." }, { "code": null, "e": 2638, "s": 2470, "text": "Angular 4 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4." }, { "code": null, "e": 2705, "s": 2638, "text": "Let us now see the new features and the changes made in Angular 4." }, { "code": null, "e": 2881, "s": 2705, "text": "The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4." }, { "code": null, "e": 2934, "s": 2881, "text": "Let us now see the new features added to Angular 4 −" }, { "code": null, "e": 3082, "s": 2934, "text": "Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template." }, { "code": null, "e": 3213, "s": 3082, "text": "<span *ngIf=\"isavailable; else condition1\">Condition is valid.</span>\n<ng-template #condition1>Condition is invalid</ng-template>\n" }, { "code": null, "e": 3282, "s": 3213, "text": "With the help of as keyword you can store the value as shown below −" }, { "code": null, "e": 3383, "s": 3282, "text": "<div *ngFor=\"let i of months | slice:0:5 as total\">\n Months: {{i}} Total: {{total.length}}\n</div>\n" }, { "code": null, "e": 3455, "s": 3383, "text": "The variable total stores the output of the slice using the as keyword." }, { "code": null, "e": 3679, "s": 3455, "text": "Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect." }, { "code": null, "e": 4014, "s": 3679, "text": "Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4." }, { "code": null, "e": 4160, "s": 4014, "text": "Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project." }, { "code": null, "e": 4263, "s": 4160, "text": "Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase." }, { "code": null, "e": 4329, "s": 4263, "text": "<div>\n <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2>\n</div>\n" }, { "code": null, "e": 4406, "s": 4329, "text": "The above line of code generates the following output – Angular 4 Titlecase." }, { "code": null, "e": 4542, "s": 4406, "text": "Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2." }, { "code": null, "e": 4719, "s": 4542, "text": "Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size." }, { "code": null, "e": 4754, "s": 4719, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4768, "s": 4754, "text": " Anadi Sharma" }, { "code": null, "e": 4803, "s": 4768, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4817, "s": 4803, "text": " Anadi Sharma" }, { "code": null, "e": 4852, "s": 4817, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4872, "s": 4852, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4907, "s": 4872, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4924, "s": 4907, "text": " Frahaan Hussain" }, { "code": null, "e": 4957, "s": 4924, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4969, "s": 4957, "text": " Senol Atac" }, { "code": null, "e": 5004, "s": 4969, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5016, "s": 5004, "text": " Senol Atac" }, { "code": null, "e": 5023, "s": 5016, "text": " Print" }, { "code": null, "e": 5034, "s": 5023, "text": " Add Notes" } ]
Building your own object detector — PyTorch vs TensorFlow and how to even get started? | by Maximilian Beckers | Towards Data Science
Having experienced some of the difficulties and headaches of implementing AI systems for object detection, I wanted to share some of the knowledge I gained on how to get started. The first step is always the hardest which is why this very practical approach is designed to ease people into the world of TensorFlow’s as well as PyTorch’s object detection frameworks. As I already was an experienced data scientist and had developed a few productive machine learning software components in the past years, I thought it should be a fairly easy job to get online, find a pre-trained CNN and train it further on an unseen data set to enable it to detect some previously unknown objects. Up until about a a year ago I had mostly worked with tree-based models, a lot of scikit-learn as well xgboost and of course tons and tons of pandas. As with many AI tasks, my first approach with this one turned out to be a classic version of a: “Not so fast!“ There are a few stepping stones on the way that you have to know of, that however not many articles and blogs seem to mention. After having spent many hours on this topic and having read a lot of TensorFlow source code I know the answers to questions like: “Why the heck is my example code from the official GitHub repos not working?” So I thought why not share my experience juggling with these tools with others and describe how I went about solving the issues I faced. So simply said, my goal was to develop my own object detector — a neural network that can classify and detect objects in an image, not just an off-the-shelf object detection algorithm, but one that would specifically be good at detecting images from my own data set — meaning I would have to do transfer learning. First of all, I went online, and freshened up my knowledge on how some of these algorithms work mathematically (I can really recommend Andrew Ng’s deeplearning.ai course on Convolutional Neural Nets on coursera. It has a full week dedicated to Object Detection that gets you up and running on the key concepts and nicely describes the math behind everything). So with the theory in mind, I had a look at some of the open-source data sets I could use for my task and stumbled across the following Raccoon data set by experiencor on GitHub https://github.com/experiencor/raccoon_dataset that I then decided to use. It already has annotations as well as images stored away neatly in respective folders and only a single class (raccoon) to detect and therefore makes a nice starting point. That being done, I had a look at two widely known deep learning frameworks, that let you use pre-trained networks for transfer learning (further training these networks to tailor them to your specific data set), TensorFlow’s object detection API as well as PyTorch’s torchvision package. And one thing I can say right away: I was able to complete my work in PyTorch in about half a day whereas figuring everything I wanted out in TensorFlow took me a few days! The fact that the tf object detection API was built on TensorFlow 1.x and we now already have version 2.x gave me so many compatibility problems that made it practically impossible to get stuff done without extensively going through their source code as some of the examples on their repo were based on 2.x whereas the core training code was still based on 1.x. I did my coding on Google Colab since they offer you a neat notebook experience and access to free CPU and GPU on their cloud as well as free storage in the form of google drive, that can easily be mounted to your Colab space. Getting the data was rather easy as I just had to navigate into a different folder (in my mounted google drive storage) and run ! git clone https://github.com/experiencor/raccoon_dataset.git Inspecting the data then works easily like such: from PIL import Imageimage = Image.open("<your path>/raccoon_dataset/images/raccoon-1.jpg")image When it comes to the labels for this image, we have to look inside the annotations folder. In case of object detection, a class for each object (in our case just the one for raccoon) and 4 coordinates per object that represent the bounding box make up the label. To have a quick look you can simply download the raccoon-1.xml file to your laptop and open it up with an editor (I used Atom). You then see the following: <annotation verified="yes"> <folder>images</folder> <filename>raccoon-1.jpg</filename> <path>/Users/datitran/Desktop/raccoon/images/raccoon-1.jpg</path> <source> <database>Unknown</database> </source> <size> <width>650</width> <height>417</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>raccoon</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>81</xmin> <ymin>88</ymin> <xmax>522</xmax> <ymax>408</ymax> </bndbox> </object></annotation> which tells you that this annotation file corresponds with the raccoon-1.jpg file, the class of the object is “raccoon” and the bounding box edges are represented by xmin, xmax, ymin and ymax. A very natural reaction would be to first check whether this is correct by simply drawing the box into the image. Pretty easily done by: from PIL import ImageDrawxmin = 81ymin = 88xmax = 522ymax = 408draw = ImageDraw.Draw(image)draw.rectangle([(xmin, ymin), (xmax, ymax)], outline =”red”)image So we don’t have to go through every file in the folder and collect the correct labels on each image there’s already a csv file containing all this info. Having a quick look at it can be done like this: import pandas as pdlabels = pd.read_csv("<your path>/raccoon_dataset/data/raccoon_labels.csv")labels.head() This is the starting point for both the TensorFlow as well as the PyTorch libraries and also where things are starting to differ between the two. Section A: TensorFlow Starting with TensorFlow object detection, is basically supposed to work like this: You clone their repo and install the API according to their installation guide. In practice what you have to do with Google Colab is in some parts easier and in some harder: Install TensorFlow and all other mentioned libraries (in Google Colab the magic command to pick a tf version is all you need, everything else is preinstalled) Install TensorFlow and all other mentioned libraries (in Google Colab the magic command to pick a tf version is all you need, everything else is preinstalled) %tensorflow_version 1.x 2. COCO API installation — is already preinstalled and can be checked with import pycocotools 3. Clone their repo ! git clone https://github.com/tensorflow/models.git 4. Navigate to the models/research folder import os os.chdir("<your path>/models/research") 5. Install protobufs ! protoc object_detection/protos/*.proto --python_out=. 6. Now to test your installation simply run: %%bashexport PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimpython object_detection/builders/model_builder_test.py 7. Super important: every bash command you do in Colab is like starting a new terminal session so it is very important that, every time you use the CLI for tf’s object detection, you MUST include export “PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim at the top of your cell! Since every interaction with the API is in command line fashion (to train a model you call something like): %% bash export “PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimpython”python object_detection/model_main.py \ --pipeline_config_path=${PIPELINE_CONFIG_PATH} \ --model_dir=${MODEL_DIR} \ --num_train_steps=${NUM_TRAIN_STEPS} \ --sample_1_of_n_eval_examples=$SAMPLE_1_OF_N_EVAL_EXAMPLES \ --alsologtostderr and I wanted to look under the hood of this CLI (plus a notebook environment isn’t really built for command-line executions) I added one key thing into my installation on Colab: 8. Enable the python kernel to find all imports made in the model_main.py file (called in the CLI above). import syssys.path.append("<your path>/models/research/object_detection")sys.path.append("<your path>/models/research/slim/") 9. Make sure you have numpy==1.17 installed, otherwise the evaluation scripts won’t work. Voila ready to get started! Having installed the necessary software and downloaded the training data we can finally think about AI. Which convolutional neural network architecture can we use? Which data set is it trained on? In TensorFlow’s object detection API we can choose from a variety of models available in their detection model zoo (love the name for this by the way :) ) trained on different industry and research standard image datasets. Perhaps the most famous one is the so-called COCO data set (common objects in context) that has many different images with labeled classes, bounding boxes, and even masks available as annotations. The data set is used for many competitions and is, quote “designed to push the state of the art in object detection forward”. Cool thing and pretty much what I was looking for. I picked a network called “Faster R-CNN”. I picked it because it is available in both the TensorFlow model zoo as well as the torchvision package and that way I could compare the two a little easier. Faster R-CNN is a region-proposal network (hence the R) that uses the technique of “anchor boxes” to localize objects and predict them. In a nutshell it’s a combination of two networks, one that detects regions within the image that have a high probability of containing an object, and the other predicting the bounding boxes as well as class probabilities in these regions. There’s plenty of more detailed explanations online. I personally like this one by Hao Gao. Once you made a choice on the model you first have to download it, meaning you download the network architecture and pre-trained weights. I chose the “faster_rcnn_inception_v2_coco_2018_01_28” model. This is done by running the following command from the models/research folder: %%bashwget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gztar -xvf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz You can now find a folder containing all the model files: import os os.listdir("faster_rcnn_inception_v2_coco_2018_01_28") which looks like this: ['model.ckpt.index', 'checkpoint', 'pipeline.config', 'model.ckpt.data-00000-of-00001', 'model.ckpt.meta', 'saved_model', 'frozen_inference_graph.pb'] There you can find checkpointing information which lets you reconstruct the model with the pre-trained weights, thus a model that is ready to do transfer learning. You also have a saved_model folder with an exported version of the downloaded model as well as a frozen_inference graph — just as the name proposes a tf graph that you can use for inference. Last but not least you find an example for a pipeline.config file. In this file you can specify exactly how you want your network to be trained, what training data to use, how many object classes you have, and so on. In here we can customize the pre-trained model to our specific needs. In TensorFlow’s object detection, the estimator API is used to handle the training and evaluation (and some more stuff like checkpointing etc.) process. This API expects the data in a tf.record format which you need to create first. Luckily this has already been done by the creator of the raccoon data set. Otherwise we could have transformed it ourselves as well: !python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=data/train.record We have a train.record and a test.record data set which will be used to feed data in batches to the tf.estimator object during training. In the pipeline.config file we have to adjust 5 areas. The fine_tune_checkpoint, the train_config, the valid_config, the num_classes and the second_stage_post_processing. Everything else can just stay the way it is. The fine_tune_checkpoint is the path to the pre-trained weights contained in the downloaded checkpoint files. All we do here is set it equal to fine_tune_checkpoint: "<your path >/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt" Don’t worry in case you find that there is no file exactly called model.ckpt, trust me it does work this way ;) The model can be rebuilt and the weights are inserted into the correct layers. The num_classes field is set to 1 (1 class only: raccoon). In the train_config section we can adjust all things concerning the training phase. I left everything at its default and only changed the necessary parts like the train_input_reader, where you have to set the input path to your train.record training data set as well as the label_map_path to a pbtxt file containing info on the labels. I first changed the label_map file to item { id: 1 name: 'raccoon'} then I set the train_input_reader to train_input_reader: { tf_record_input_reader { input_path: "<your path>/raccoon_dataset/data/train.record" } label_map_path: "<your path>/training/raccoon_label_map.pbtxt"} Next I changed the valid config section. Again the name explains it all here. I just set the eval_input_reader to my label_map file as well as the test.record test data set to eval_input_reader: { tf_record_input_reader { input_path: "<your path>/raccoon_dataset/data/test.record" }label_map_path: "<your path>/training/raccoon_label_map.pbtxt" shuffle: false num_readers: 1} Lastly I adjusted the second_stage_postprocessing. Here you can define what the model does with the output. Generally a detection model outputs a number of possible combinations of class probabilities and bounding box coordinates (e.g. one set per anchor) that is not equal to the number of objects in the image. As users we then have to use techniques such as non-max suppression to get the best-fit bounding boxes (Andrew Ngs Coursera course as mentioned above gives a really nice introduction to this!) to every object in the image. I picked the following here: second_stage_post_processing { batch_non_max_suppression { score_threshold: 0.5 iou_threshold: 0.6 max_detections_per_class: 5 max_total_detections: 5 } score_converter: SOFTMAX } meaning I will only allow 5 detections per image (ideally 5 different detections of different raccoons if existent in the image). The IoU (intersection over union) threshold, as well as the score threshold, are tailor towards only having a single bounding box per object. Once the pipeline.config file is good to go we can start the training. TensorFlow suggests doing this with a command-line job calling their model_main.py file with a variety of input parameters. However, as I wanted to look under the hood a little bit, I hopped into this file and ran the commands myself. For the training and evaluation of the model the object detection API is making use of tf’s estimator API. It takes care of training and evaluation for us nicely and integrates automatic checkpointing as well as model exporting. It also allows for transfer learning from a given checkpoint (which is exactly what we are doing) and writes automatic summaries during training that we can visualize with tensorboard to monitor performance. The estimator will need training and evaluation specs that incorporate and define all the things just mentioned and takes care of batching the data for us. tf’s object detection has predefined functions to instantiate these objects from our pipline.config file: Before we can start we need to import all the necessary libraries (just as it is done in the model_main.py file): from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionfrom absl import flagsimport tensorflow as tffrom object_detection import model_hparamsfrom object_detection import model_lib Now we can start by specifying a model directory: model_dir = "<your path>/faster_rcnn_inception_v2_coco_2018_01_28/model_dir" The API will write its log files as well as checkpoints and exported models to this directory. Then after specifying a run config, the path to our pipeline.config file, as well as the number of steps (one step is one run through a single batch of data) to train for: config = tf.estimator.RunConfig(model_dir=model_dir)pipeline_config_path= "<your path>/training/pipeline.config"num_train_steps=10000 we can instantiate all the objects and finally create the train and eval specs using the appropriate pre-built function. train_and_eval_dict = model_lib.create_estimator_and_inputs( run_config=config, hparams=model_hparams.create_hparams(None), pipeline_config_path = pipeline_config_path, train_steps =num_train_steps, sample_1_of_n_eval_examples = 1)estimator = train_and_eval_dict['estimator']train_input_fn = train_and_eval_dict['train_input_fn']eval_input_fns=train_and_eval_dict['eval_input_fns']eval_on_train_input_fn=train_and_eval_dict['eval_on_train_input_fn']predict_input_fn = train_and_eval_dict['predict_input_fn']train_steps = train_and_eval_dict['train_steps'] Estimator, train_spec and eval_spec are then used for training: tf.estimator.train_and_evaluate(estimator,train_spec,eval_specs[0]) A few things happen now that are worth mentioning. First of all the model gets trained using the appropriate optimizer settings from our pipeline.config file. Every config.save_checkpoints_secs the model writes checkpoints (a set of weights) to the model_dir. Then every eval_specs[0].throttle_secs we pause the training to run evaluation on the test set. In order for this to work we need to have a checkpoint available first. The eval_spec is configured to use the evaluation metrics of the COCO challenge (using the pycocotools library). Every config.save_summary_steps the estimator API writes out event files for visualization in tensorboard. I ran the model for 10.000 steps and got a final mAP of 0.65 on the test set. This already outputs some pretty decent bounding boxes when making predictions for the naked eye. But in order to see that, we first need to figure out how to do inference with this trained model. This is perhaps the hardest part to figure out in the whole object detection pipeline. In TensorFlow’s object detection repo there are some examples on how to do inference on pre-built models, however, the code relies on TensorFlow version 2.x. Using a saved model or a frozen inference Graph with TensorFlow 1.x code is (relative to tf 2.x) a lot more complicated since you have to work directly with the tf graph and session. Either way we first have to export the model in the correct fashion. It took me some experimenting to find out why the exporter that was already in the eval_specs and exports a saved model at the end of tf.estimator.train_and_evaluate doesn’t do the job. Essentially this is due to the serving function used in this automatic exporter. It is tailored towards using tf.example type data (e.g. test.record data), however, we are trying to input a 3D tensor representing an image. This is why we have to run an export job where we specify the input type. With the following imports: import tensorflow as tffrom google.protobuf import text_formatfrom object_detection import exporterfrom object_detection.protos import pipeline_pb2slim = tf.contrib.slimflags = tf.app.flags we have to provide an output directory, our pipeline.config file, the input type as well as a checkpoint from which we would like to export the model (just use the latest one) pipeline_config_path = "<your path>/training/pipeline.config"config_override = ""input_shape = Falsetrained_checkpoint_prefix ="<your path>/faster_rcnn_inception_v2_coco_2018_01_28/model_dir/model.ckpt-10000"output_directory = "<your path>faster_rcnn_inception_v2_coco_2018_01_28/output"input_type = "image_tensor"write_inference_graph = False and now we can run the exporter tf.reset_default_graph()pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()with tf.gfile.GFile(pipeline_config_path, 'r') as f: text_format.Merge(f.read(), pipeline_config)text_format.Merge(config_override, pipeline_config)if input_shape: input_shape = [ int(dim) if dim != '-1' else None for dim in input_shape.split(',') ]else: input_shape = Noneexporter.export_inference_graph( input_type, pipeline_config, trained_checkpoint_prefix, output_directory, input_shape=input_shape, write_inference_graph=write_inference_graph) For TensorFlow 2.x all we have to do is reload the runtime and select 2.x as version %tensorflow_version 2.x and pretty much just follow along their example notebook. You can then load the model with two lines of code: model = tf.saved_model.load("<your path>/faster_rcnn_inception_v2_coco_2018_01_28/output/saved_model")model = model.signatures['serving_default'] All we have to do now is load up an image from the test set (e.g raccoon-14.jpg) from PIL import Image, ImageDrawimport numpy as npimport pandas as pdfilename = "raccoon-14.jpg"img = Image.open("<your path>/raccoon_dataset/images/"+filename)test = pd.read_csv("<your path>/raccoon_dataset/data/test_labels.csv")true_labels = test[test["filename"] == filename][["xmin", "ymin", "xmax","ymax"]] and run the inference (as suggested by the tf inference scripts) image = np.asarray(img)# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.input_tensor = tf.convert_to_tensor(image)# The model expects a batch of images, so add an axis with `tf.newaxis`.input_tensor = input_tensor[tf.newaxis,...]# Run inferenceoutput_dict = model(input_tensor)# All outputs are batches tensors.# Convert to numpy arrays, and take index [0] to remove the batchdimension.# We're only interested in the first num_detections.num_detections = int(output_dict.pop('num_detections'))output_dict = {key:value[0, :num_detections].numpy() for key,value in output_dict.items()}output_dict['num_detections'] = num_detections# detection_classes should be ints.output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64) Now we can draw the learned bounding box(es) in red and the true labels in green: selected_boxes = output_dict["detection_boxes"]selected_scores = output_dict["detection_scores"]draw = ImageDraw.Draw(img)#draw predictions:for i in range(len(selected_scores)): draw.rectangle([(selected_boxes[i][1]*img.width, selected_boxes[i][0]*img.height), (selected_boxes[i][3]*img.width, selected_boxes[i][2]*img.height)], outline ="red", width = 3) draw.text((selected_boxes[i][1]*img.width, selected_boxes[i][0]*img.height), text = str(selected_scores[i]))# draw groundtruth:for i in range(len(true_labels["xmin"].values)): draw.rectangle([(true_labels["xmin"].values[i], true_labels["ymin"].values[i]), (true_labels["xmax"].values[i], true_labels["ymax"].values[i])], outline ="green", width = 3)img and we can see a pretty cool little raccoon doing some major housekeeping. Also the bounding boxes and probabilities are pretty good considering we only trained the network for 10.000 steps. Note: If you want to do this with tf version 1.x you can follow the scripts located here. Section B: PyTorch PyTorch has a package called torchvision that includes model architectures, data sets, and other helpful functions for computer vision. Torchvision also has a subpackage on object detection which we will be using in this section. A lot of the following setup and code is modeled according to torchvision’s object detection tutorial. We need to make sure that we have numpy version 1.17 installed.Check pycocotools installation We need to make sure that we have numpy version 1.17 installed. Check pycocotools installation import pycocotools 4. Change to a PyTorch object detection directory you created import osos.chdir("<your path>/pytorch object detection") 3. Clone the PyTorch vision repo and copy some python files %%bashgit clone https://github.com/pytorch/vision.gitcd visiongit checkout v0.3.0cp references/detection/utils.py ../cp references/detection/transforms.py ../cp references/detection/coco_eval.py ../cp references/detection/engine.py ../cp references/detection/coco_utils.py ../ 4. Now we can do all the necessary imports import numpy as npimport torchimport torch.utils.datafrom PIL import Imageimport pandas as pdfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictorfrom engine import train_one_epoch, evaluateimport utilsimport transforms as T As opposed to having to create a new type of data file for our training data (as with the training.record file in TensorFlow) we only have to write a data set python class that is later used by the model to parse the images and corresponding annotations. The class needs to inherit from torch.utils.data.Dataset and implement the __getitem__ and __len__ methods. As we are just going to use the same raccoon data set as earlier and the data folder in the repo already contains a raccoon_labels.csv file containing all the parsed annotations, all we have to do is write a little helper function: def parse_one_annot(path_to_data_file, filename): data = pd.read_csv(path_to_data_file) boxes_array = data[data["filename"] == filename][["xmin", "ymin", "xmax", "ymax"]].values return boxes_array which we can then use to write our RaccoonDataset class: class RaccoonDataset(torch.utils.data.Dataset): def __init__(self, root, data_file, transforms=None): self.root = root self.transforms = transforms self.imgs = sorted(os.listdir(os.path.join(root, "images"))) self.path_to_data_file = data_filedef __getitem__(self, idx): # load images and bounding boxes img_path = os.path.join(self.root, "images", self.imgs[idx]) img = Image.open(img_path).convert("RGB") box_list = parse_one_annot(self.path_to_data_file, self.imgs[idx]) boxes = torch.as_tensor(box_list, dtype=torch.float32)num_objs = len(box_list) # there is only one class labels = torch.ones((num_objs,), dtype=torch.int64) image_id = torch.tensor([idx]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) target = {} target["boxes"] = boxes target["labels"] = labels target["image_id"] = image_id target["area"] = area target["iscrowd"] = iscrowdif self.transforms is not None: img, target = self.transforms(img, target) return img, targetdef __len__(self): return len(self.imgs) We can run a quick check to see if everything is implemented correctly. Instantiate a RaccoonDataset object and run __getitem__ dataset = RaccoonDataset(root= "<your path>/raccoon_dataset",data_file= "<your path>/raccoon_dataset/data/raccoon_labels.csv")dataset.__getitem__(0) and the output should look like this (<PIL.Image.Image image mode=RGB size=650x417 at 0x7FE20F358908>, {'area': tensor([141120.]), 'boxes': tensor([[ 81., 88., 522., 408.]]), 'image_id': tensor([0]), 'iscrowd': tensor([0]), 'labels': tensor([1])}) Since we used a faster R-CNN earlier for TensorFlow we will also use one here. Also it’s not like torchvision gives us a big choice. They only have 2 pre-trained (on coco) models for object detection available on their website. A Faster R-CNN ResNet-50 FPN and a Mask R-CNN ResNet-50 FPN. In order to download the pre-trained faster r-cnn we can write a little get_model function that adjusts the last layer of the model to output a number of classes that suits our raccoon data set: def get_model(num_classes): # load an object detection model pre-trained on COCO model = torchvision.models.detection. fasterrcnn_resnet50_fpn(pretrained=True)# get the number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new on model.roi_heads.box_predictor = FastRCNNPredictor(in_features,/ num_classes) return model We can also add a little transformer function that enhances our training set by doing some basic data augmentation (horizontal flip of images) def get_transform(train): transforms = [] # converts the image, a PIL image, into a PyTorch Tensor transforms.append(T.ToTensor()) if train: # during training, randomly flip the training images # and ground-truth for data augmentation transforms.append(T.RandomHorizontalFlip(0.5)) return T.Compose(transforms) Now we can instantiate our training and testing data classes and assign them to data_loaders that control how images are loaded during training and testing (batch size etc). # use our dataset and defined transformationsdataset = RaccoonDataset(root= "<your path>/raccoon_dataset", data_file= "<your path>/raccoon_dataset/data/raccoon_labels.csv", transforms = get_transform(train=True))dataset_test = RaccoonDataset(root= "<your path>/raccoon_dataset" data_file= "<your path>/raccoon_dataset/data/raccoon_labels.csv", transforms = get_transform(train=False))# split the dataset in train and test settorch.manual_seed(1)indices = torch.randperm(len(dataset)).tolist()dataset = torch.utils.data.Subset(dataset, indices[:-40])dataset_test = torch.utils.data.Subset(dataset_test, indices[-40:])# define training and validation data loadersdata_loader = torch.utils.data.DataLoader( dataset, batch_size=2, shuffle=True, num_workers=4, collate_fn=utils.collate_fn)data_loader_test = torch.utils.data.DataLoader( dataset_test, batch_size=1, shuffle=False, num_workers=4, collate_fn=utils.collate_fn)print("We have: {} examples, {} are training and {} testing".format(len(indices), len(dataset), len(dataset_test))) First, we can use the following command to check whether the correct GPU settings are in place: torch.cuda.is_available() If you are running on Google Colab just switch the runtime time to GPU. Now we can set up the model using our get_model function. Also we have to specify an optimizer and a learning rate scheduler, that adjusts the learning rate over time. device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')# our dataset has two classes only - raccoon and not racoonnum_classes = 2# get the model using our helper functionmodel = get_model(num_classes)# move model to the right devicemodel.to(device)# construct an optimizerparams = [p for p in model.parameters() if p.requires_grad]optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)# and a learning rate scheduler which decreases the learning rate by # 10x every 3 epochslr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) In order to do the training we now must write our own for loop over the number of epochs we wish to train on, then call PyTorch’s train_one_epoch function, adjust the learning rate and finally evaluate once per epoch. # let's train it for 10 epochsnum_epochs = 10for epoch in range(num_epochs): # train for one epoch, printing every 10 iterations train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)# update the learning rate lr_scheduler.step() # evaluate on the test dataset evaluate(model, data_loader_test, device=device) In order to save the trained model (there is no automatic checkpointing) we can run the following command once we are done training: os.mkdir("<your path>/pytorch object detection/raccoon/")torch.save(model.state_dict(), "<your path>/pytorch object detection/raccoon/model") After 10 epochs I got a mAP of 0.66. We first have to load the model, which works by instantiating the same “empty” model with our get_model function from earlier and then loading the saved weights into the network architecture. loaded_model = get_model(num_classes = 2)loaded_model.load_state_dict(torch.load(“<your path>/pytorch object detection/raccoon/model”)) Now we can use our dataset_test class to get test images and their ground truth and run them through the predictor. idx = 0img, _ = dataset_test[idx]label_boxes = np.array(dataset_test[idx][1]["boxes"])#put the model in evaluation modeloaded_model.eval()with torch.no_grad(): prediction = loaded_model([img])image = Image.fromarray(img.mul(255).permute(1, 2,0).byte().numpy())draw = ImageDraw.Draw(image)# draw groundtruthfor elem in range(len(label_boxes)): draw.rectangle([(label_boxes[elem][0], label_boxes[elem][1]), (label_boxes[elem][2], label_boxes[elem][3])], outline ="green", width =3)for element in range(len(prediction[0]["boxes"])): boxes = prediction[0]["boxes"][element].cpu().numpy() score = np.round(prediction[0]["scores"][element].cpu().numpy(), decimals= 4) if score > 0.8: draw.rectangle([(boxes[0], boxes[1]), (boxes[2], boxes[3])], outline ="red", width =3) draw.text((boxes[0], boxes[1]), text = str(score))image All in all, it is safe to say that for people that are used to imperative style coding (code gets executed when written) and have been working with scikit-learn type ML frameworks a lot, PyTorch is most likely going to be easier for them to start with (this might also change once TensorFlow upgrades the object detection API to tf version 2.x). In this article I am only focusing on the “ease of use” side of things, not looking at performance speed, variability, or portability of the model. A lot of these features however are needed when trying to deploy such models into productive software environments. Here the higher-level API used in TensorFlow with the config.py file incorporates a lot more flexibility from the get-go within the framework, where the lower-level torchvision is held more open, meaning it is easier to look “behind the curtain” (you don’t have to work through a ton of TensorFlow source code), however only the standards are displayed in their tutorial. Anything outside of the standard must be written from scratch, whereas TensorFlow might have a section in the config file to address it. Also the TensorFlow model zoo just has way more pre-trained models available for people to use. Overall my experience resembles a very typical sentiment in the data science community, which is that PyTorche’s object detection framework might be better for research purposes and “understanding every detail” of an implementation, while TensorFlow’s API is a better choice for building productive models. I hope you guys got some valuable information out of this. Now it’s time to try it out yourselves. Happy coding :) TensorFlow Object detection: github.com Torchvision: pytorch.org Convolutional Neural Networks (coursera):
[ { "code": null, "e": 538, "s": 172, "text": "Having experienced some of the difficulties and headaches of implementing AI systems for object detection, I wanted to share some of the knowledge I gained on how to get started. The first step is always the hardest which is why this very practical approach is designed to ease people into the world of TensorFlow’s as well as PyTorch’s object detection frameworks." }, { "code": null, "e": 1371, "s": 538, "text": "As I already was an experienced data scientist and had developed a few productive machine learning software components in the past years, I thought it should be a fairly easy job to get online, find a pre-trained CNN and train it further on an unseen data set to enable it to detect some previously unknown objects. Up until about a a year ago I had mostly worked with tree-based models, a lot of scikit-learn as well xgboost and of course tons and tons of pandas. As with many AI tasks, my first approach with this one turned out to be a classic version of a: “Not so fast!“ There are a few stepping stones on the way that you have to know of, that however not many articles and blogs seem to mention. After having spent many hours on this topic and having read a lot of TensorFlow source code I know the answers to questions like:" }, { "code": null, "e": 1449, "s": 1371, "text": "“Why the heck is my example code from the official GitHub repos not working?”" }, { "code": null, "e": 1586, "s": 1449, "text": "So I thought why not share my experience juggling with these tools with others and describe how I went about solving the issues I faced." }, { "code": null, "e": 1900, "s": 1586, "text": "So simply said, my goal was to develop my own object detector — a neural network that can classify and detect objects in an image, not just an off-the-shelf object detection algorithm, but one that would specifically be good at detecting images from my own data set — meaning I would have to do transfer learning." }, { "code": null, "e": 2686, "s": 1900, "text": "First of all, I went online, and freshened up my knowledge on how some of these algorithms work mathematically (I can really recommend Andrew Ng’s deeplearning.ai course on Convolutional Neural Nets on coursera. It has a full week dedicated to Object Detection that gets you up and running on the key concepts and nicely describes the math behind everything). So with the theory in mind, I had a look at some of the open-source data sets I could use for my task and stumbled across the following Raccoon data set by experiencor on GitHub https://github.com/experiencor/raccoon_dataset that I then decided to use. It already has annotations as well as images stored away neatly in respective folders and only a single class (raccoon) to detect and therefore makes a nice starting point." }, { "code": null, "e": 3509, "s": 2686, "text": "That being done, I had a look at two widely known deep learning frameworks, that let you use pre-trained networks for transfer learning (further training these networks to tailor them to your specific data set), TensorFlow’s object detection API as well as PyTorch’s torchvision package. And one thing I can say right away: I was able to complete my work in PyTorch in about half a day whereas figuring everything I wanted out in TensorFlow took me a few days! The fact that the tf object detection API was built on TensorFlow 1.x and we now already have version 2.x gave me so many compatibility problems that made it practically impossible to get stuff done without extensively going through their source code as some of the examples on their repo were based on 2.x whereas the core training code was still based on 1.x." }, { "code": null, "e": 3736, "s": 3509, "text": "I did my coding on Google Colab since they offer you a neat notebook experience and access to free CPU and GPU on their cloud as well as free storage in the form of google drive, that can easily be mounted to your Colab space." }, { "code": null, "e": 3864, "s": 3736, "text": "Getting the data was rather easy as I just had to navigate into a different folder (in my mounted google drive storage) and run" }, { "code": null, "e": 3927, "s": 3864, "text": "! git clone https://github.com/experiencor/raccoon_dataset.git" }, { "code": null, "e": 3976, "s": 3927, "text": "Inspecting the data then works easily like such:" }, { "code": null, "e": 4073, "s": 3976, "text": "from PIL import Imageimage = Image.open(\"<your path>/raccoon_dataset/images/raccoon-1.jpg\")image" }, { "code": null, "e": 4492, "s": 4073, "text": "When it comes to the labels for this image, we have to look inside the annotations folder. In case of object detection, a class for each object (in our case just the one for raccoon) and 4 coordinates per object that represent the bounding box make up the label. To have a quick look you can simply download the raccoon-1.xml file to your laptop and open it up with an editor (I used Atom). You then see the following:" }, { "code": null, "e": 5021, "s": 4492, "text": "<annotation verified=\"yes\"> <folder>images</folder> <filename>raccoon-1.jpg</filename> <path>/Users/datitran/Desktop/raccoon/images/raccoon-1.jpg</path> <source> <database>Unknown</database> </source> <size> <width>650</width> <height>417</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>raccoon</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>81</xmin> <ymin>88</ymin> <xmax>522</xmax> <ymax>408</ymax> </bndbox> </object></annotation>" }, { "code": null, "e": 5328, "s": 5021, "text": "which tells you that this annotation file corresponds with the raccoon-1.jpg file, the class of the object is “raccoon” and the bounding box edges are represented by xmin, xmax, ymin and ymax. A very natural reaction would be to first check whether this is correct by simply drawing the box into the image." }, { "code": null, "e": 5351, "s": 5328, "text": "Pretty easily done by:" }, { "code": null, "e": 5508, "s": 5351, "text": "from PIL import ImageDrawxmin = 81ymin = 88xmax = 522ymax = 408draw = ImageDraw.Draw(image)draw.rectangle([(xmin, ymin), (xmax, ymax)], outline =”red”)image" }, { "code": null, "e": 5711, "s": 5508, "text": "So we don’t have to go through every file in the folder and collect the correct labels on each image there’s already a csv file containing all this info. Having a quick look at it can be done like this:" }, { "code": null, "e": 5819, "s": 5711, "text": "import pandas as pdlabels = pd.read_csv(\"<your path>/raccoon_dataset/data/raccoon_labels.csv\")labels.head()" }, { "code": null, "e": 5965, "s": 5819, "text": "This is the starting point for both the TensorFlow as well as the PyTorch libraries and also where things are starting to differ between the two." }, { "code": null, "e": 5987, "s": 5965, "text": "Section A: TensorFlow" }, { "code": null, "e": 6245, "s": 5987, "text": "Starting with TensorFlow object detection, is basically supposed to work like this: You clone their repo and install the API according to their installation guide. In practice what you have to do with Google Colab is in some parts easier and in some harder:" }, { "code": null, "e": 6404, "s": 6245, "text": "Install TensorFlow and all other mentioned libraries (in Google Colab the magic command to pick a tf version is all you need, everything else is preinstalled)" }, { "code": null, "e": 6563, "s": 6404, "text": "Install TensorFlow and all other mentioned libraries (in Google Colab the magic command to pick a tf version is all you need, everything else is preinstalled)" }, { "code": null, "e": 6587, "s": 6563, "text": "%tensorflow_version 1.x" }, { "code": null, "e": 6662, "s": 6587, "text": "2. COCO API installation — is already preinstalled and can be checked with" }, { "code": null, "e": 6681, "s": 6662, "text": "import pycocotools" }, { "code": null, "e": 6701, "s": 6681, "text": "3. Clone their repo" }, { "code": null, "e": 6754, "s": 6701, "text": "! git clone https://github.com/tensorflow/models.git" }, { "code": null, "e": 6796, "s": 6754, "text": "4. Navigate to the models/research folder" }, { "code": null, "e": 6846, "s": 6796, "text": "import os os.chdir(\"<your path>/models/research\")" }, { "code": null, "e": 6867, "s": 6846, "text": "5. Install protobufs" }, { "code": null, "e": 6923, "s": 6867, "text": "! protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 6968, "s": 6923, "text": "6. Now to test your installation simply run:" }, { "code": null, "e": 7075, "s": 6968, "text": "%%bashexport PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimpython object_detection/builders/model_builder_test.py" }, { "code": null, "e": 7271, "s": 7075, "text": "7. Super important: every bash command you do in Colab is like starting a new terminal session so it is very important that, every time you use the CLI for tf’s object detection, you MUST include" }, { "code": null, "e": 7319, "s": 7271, "text": "export “PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim" }, { "code": null, "e": 7344, "s": 7319, "text": "at the top of your cell!" }, { "code": null, "e": 7452, "s": 7344, "text": "Since every interaction with the API is in command line fashion (to train a model you call something like):" }, { "code": null, "e": 7763, "s": 7452, "text": "%% bash export “PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimpython”python object_detection/model_main.py \\ --pipeline_config_path=${PIPELINE_CONFIG_PATH} \\ --model_dir=${MODEL_DIR} \\ --num_train_steps=${NUM_TRAIN_STEPS} \\ --sample_1_of_n_eval_examples=$SAMPLE_1_OF_N_EVAL_EXAMPLES \\ --alsologtostderr" }, { "code": null, "e": 7941, "s": 7763, "text": "and I wanted to look under the hood of this CLI (plus a notebook environment isn’t really built for command-line executions) I added one key thing into my installation on Colab:" }, { "code": null, "e": 8047, "s": 7941, "text": "8. Enable the python kernel to find all imports made in the model_main.py file (called in the CLI above)." }, { "code": null, "e": 8173, "s": 8047, "text": "import syssys.path.append(\"<your path>/models/research/object_detection\")sys.path.append(\"<your path>/models/research/slim/\")" }, { "code": null, "e": 8263, "s": 8173, "text": "9. Make sure you have numpy==1.17 installed, otherwise the evaluation scripts won’t work." }, { "code": null, "e": 8291, "s": 8263, "text": "Voila ready to get started!" }, { "code": null, "e": 9752, "s": 8291, "text": "Having installed the necessary software and downloaded the training data we can finally think about AI. Which convolutional neural network architecture can we use? Which data set is it trained on? In TensorFlow’s object detection API we can choose from a variety of models available in their detection model zoo (love the name for this by the way :) ) trained on different industry and research standard image datasets. Perhaps the most famous one is the so-called COCO data set (common objects in context) that has many different images with labeled classes, bounding boxes, and even masks available as annotations. The data set is used for many competitions and is, quote “designed to push the state of the art in object detection forward”. Cool thing and pretty much what I was looking for. I picked a network called “Faster R-CNN”. I picked it because it is available in both the TensorFlow model zoo as well as the torchvision package and that way I could compare the two a little easier. Faster R-CNN is a region-proposal network (hence the R) that uses the technique of “anchor boxes” to localize objects and predict them. In a nutshell it’s a combination of two networks, one that detects regions within the image that have a high probability of containing an object, and the other predicting the bounding boxes as well as class probabilities in these regions. There’s plenty of more detailed explanations online. I personally like this one by Hao Gao." }, { "code": null, "e": 10031, "s": 9752, "text": "Once you made a choice on the model you first have to download it, meaning you download the network architecture and pre-trained weights. I chose the “faster_rcnn_inception_v2_coco_2018_01_28” model. This is done by running the following command from the models/research folder:" }, { "code": null, "e": 10201, "s": 10031, "text": "%%bashwget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gztar -xvf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz" }, { "code": null, "e": 10259, "s": 10201, "text": "You can now find a folder containing all the model files:" }, { "code": null, "e": 10324, "s": 10259, "text": "import os os.listdir(\"faster_rcnn_inception_v2_coco_2018_01_28\")" }, { "code": null, "e": 10347, "s": 10324, "text": "which looks like this:" }, { "code": null, "e": 10504, "s": 10347, "text": "['model.ckpt.index', 'checkpoint', 'pipeline.config', 'model.ckpt.data-00000-of-00001', 'model.ckpt.meta', 'saved_model', 'frozen_inference_graph.pb']" }, { "code": null, "e": 11146, "s": 10504, "text": "There you can find checkpointing information which lets you reconstruct the model with the pre-trained weights, thus a model that is ready to do transfer learning. You also have a saved_model folder with an exported version of the downloaded model as well as a frozen_inference graph — just as the name proposes a tf graph that you can use for inference. Last but not least you find an example for a pipeline.config file. In this file you can specify exactly how you want your network to be trained, what training data to use, how many object classes you have, and so on. In here we can customize the pre-trained model to our specific needs." }, { "code": null, "e": 11379, "s": 11146, "text": "In TensorFlow’s object detection, the estimator API is used to handle the training and evaluation (and some more stuff like checkpointing etc.) process. This API expects the data in a tf.record format which you need to create first." }, { "code": null, "e": 11512, "s": 11379, "text": "Luckily this has already been done by the creator of the raccoon data set. Otherwise we could have transformed it ourselves as well:" }, { "code": null, "e": 11608, "s": 11512, "text": "!python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=data/train.record" }, { "code": null, "e": 11745, "s": 11608, "text": "We have a train.record and a test.record data set which will be used to feed data in batches to the tf.estimator object during training." }, { "code": null, "e": 12105, "s": 11745, "text": "In the pipeline.config file we have to adjust 5 areas. The fine_tune_checkpoint, the train_config, the valid_config, the num_classes and the second_stage_post_processing. Everything else can just stay the way it is. The fine_tune_checkpoint is the path to the pre-trained weights contained in the downloaded checkpoint files. All we do here is set it equal to" }, { "code": null, "e": 12194, "s": 12105, "text": "fine_tune_checkpoint: \"<your path >/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt\"" }, { "code": null, "e": 12444, "s": 12194, "text": "Don’t worry in case you find that there is no file exactly called model.ckpt, trust me it does work this way ;) The model can be rebuilt and the weights are inserted into the correct layers. The num_classes field is set to 1 (1 class only: raccoon)." }, { "code": null, "e": 12818, "s": 12444, "text": "In the train_config section we can adjust all things concerning the training phase. I left everything at its default and only changed the necessary parts like the train_input_reader, where you have to set the input path to your train.record training data set as well as the label_map_path to a pbtxt file containing info on the labels. I first changed the label_map file to" }, { "code": null, "e": 12850, "s": 12818, "text": "item { id: 1 name: 'raccoon'}" }, { "code": null, "e": 12887, "s": 12850, "text": "then I set the train_input_reader to" }, { "code": null, "e": 13065, "s": 12887, "text": "train_input_reader: { tf_record_input_reader { input_path: \"<your path>/raccoon_dataset/data/train.record\" } label_map_path: \"<your path>/training/raccoon_label_map.pbtxt\"}" }, { "code": null, "e": 13241, "s": 13065, "text": "Next I changed the valid config section. Again the name explains it all here. I just set the eval_input_reader to my label_map file as well as the test.record test data set to" }, { "code": null, "e": 13447, "s": 13241, "text": "eval_input_reader: { tf_record_input_reader { input_path: \"<your path>/raccoon_dataset/data/test.record\" }label_map_path: \"<your path>/training/raccoon_label_map.pbtxt\" shuffle: false num_readers: 1}" }, { "code": null, "e": 14012, "s": 13447, "text": "Lastly I adjusted the second_stage_postprocessing. Here you can define what the model does with the output. Generally a detection model outputs a number of possible combinations of class probabilities and bounding box coordinates (e.g. one set per anchor) that is not equal to the number of objects in the image. As users we then have to use techniques such as non-max suppression to get the best-fit bounding boxes (Andrew Ngs Coursera course as mentioned above gives a really nice introduction to this!) to every object in the image. I picked the following here:" }, { "code": null, "e": 14238, "s": 14012, "text": "second_stage_post_processing { batch_non_max_suppression { score_threshold: 0.5 iou_threshold: 0.6 max_detections_per_class: 5 max_total_detections: 5 } score_converter: SOFTMAX }" }, { "code": null, "e": 14510, "s": 14238, "text": "meaning I will only allow 5 detections per image (ideally 5 different detections of different raccoons if existent in the image). The IoU (intersection over union) threshold, as well as the score threshold, are tailor towards only having a single bounding box per object." }, { "code": null, "e": 15253, "s": 14510, "text": "Once the pipeline.config file is good to go we can start the training. TensorFlow suggests doing this with a command-line job calling their model_main.py file with a variety of input parameters. However, as I wanted to look under the hood a little bit, I hopped into this file and ran the commands myself. For the training and evaluation of the model the object detection API is making use of tf’s estimator API. It takes care of training and evaluation for us nicely and integrates automatic checkpointing as well as model exporting. It also allows for transfer learning from a given checkpoint (which is exactly what we are doing) and writes automatic summaries during training that we can visualize with tensorboard to monitor performance." }, { "code": null, "e": 15515, "s": 15253, "text": "The estimator will need training and evaluation specs that incorporate and define all the things just mentioned and takes care of batching the data for us. tf’s object detection has predefined functions to instantiate these objects from our pipline.config file:" }, { "code": null, "e": 15629, "s": 15515, "text": "Before we can start we need to import all the necessary libraries (just as it is done in the model_main.py file):" }, { "code": null, "e": 15861, "s": 15629, "text": "from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionfrom absl import flagsimport tensorflow as tffrom object_detection import model_hparamsfrom object_detection import model_lib" }, { "code": null, "e": 15911, "s": 15861, "text": "Now we can start by specifying a model directory:" }, { "code": null, "e": 15988, "s": 15911, "text": "model_dir = \"<your path>/faster_rcnn_inception_v2_coco_2018_01_28/model_dir\"" }, { "code": null, "e": 16255, "s": 15988, "text": "The API will write its log files as well as checkpoints and exported models to this directory. Then after specifying a run config, the path to our pipeline.config file, as well as the number of steps (one step is one run through a single batch of data) to train for:" }, { "code": null, "e": 16389, "s": 16255, "text": "config = tf.estimator.RunConfig(model_dir=model_dir)pipeline_config_path= \"<your path>/training/pipeline.config\"num_train_steps=10000" }, { "code": null, "e": 16510, "s": 16389, "text": "we can instantiate all the objects and finally create the train and eval specs using the appropriate pre-built function." }, { "code": null, "e": 17181, "s": 16510, "text": "train_and_eval_dict = model_lib.create_estimator_and_inputs( run_config=config, hparams=model_hparams.create_hparams(None), pipeline_config_path = pipeline_config_path, train_steps =num_train_steps, sample_1_of_n_eval_examples = 1)estimator = train_and_eval_dict['estimator']train_input_fn = train_and_eval_dict['train_input_fn']eval_input_fns=train_and_eval_dict['eval_input_fns']eval_on_train_input_fn=train_and_eval_dict['eval_on_train_input_fn']predict_input_fn = train_and_eval_dict['predict_input_fn']train_steps = train_and_eval_dict['train_steps']" }, { "code": null, "e": 17245, "s": 17181, "text": "Estimator, train_spec and eval_spec are then used for training:" }, { "code": null, "e": 17313, "s": 17245, "text": "tf.estimator.train_and_evaluate(estimator,train_spec,eval_specs[0])" }, { "code": null, "e": 17961, "s": 17313, "text": "A few things happen now that are worth mentioning. First of all the model gets trained using the appropriate optimizer settings from our pipeline.config file. Every config.save_checkpoints_secs the model writes checkpoints (a set of weights) to the model_dir. Then every eval_specs[0].throttle_secs we pause the training to run evaluation on the test set. In order for this to work we need to have a checkpoint available first. The eval_spec is configured to use the evaluation metrics of the COCO challenge (using the pycocotools library). Every config.save_summary_steps the estimator API writes out event files for visualization in tensorboard." }, { "code": null, "e": 18236, "s": 17961, "text": "I ran the model for 10.000 steps and got a final mAP of 0.65 on the test set. This already outputs some pretty decent bounding boxes when making predictions for the naked eye. But in order to see that, we first need to figure out how to do inference with this trained model." }, { "code": null, "e": 18664, "s": 18236, "text": "This is perhaps the hardest part to figure out in the whole object detection pipeline. In TensorFlow’s object detection repo there are some examples on how to do inference on pre-built models, however, the code relies on TensorFlow version 2.x. Using a saved model or a frozen inference Graph with TensorFlow 1.x code is (relative to tf 2.x) a lot more complicated since you have to work directly with the tf graph and session." }, { "code": null, "e": 19216, "s": 18664, "text": "Either way we first have to export the model in the correct fashion. It took me some experimenting to find out why the exporter that was already in the eval_specs and exports a saved model at the end of tf.estimator.train_and_evaluate doesn’t do the job. Essentially this is due to the serving function used in this automatic exporter. It is tailored towards using tf.example type data (e.g. test.record data), however, we are trying to input a 3D tensor representing an image. This is why we have to run an export job where we specify the input type." }, { "code": null, "e": 19244, "s": 19216, "text": "With the following imports:" }, { "code": null, "e": 19434, "s": 19244, "text": "import tensorflow as tffrom google.protobuf import text_formatfrom object_detection import exporterfrom object_detection.protos import pipeline_pb2slim = tf.contrib.slimflags = tf.app.flags" }, { "code": null, "e": 19610, "s": 19434, "text": "we have to provide an output directory, our pipeline.config file, the input type as well as a checkpoint from which we would like to export the model (just use the latest one)" }, { "code": null, "e": 19954, "s": 19610, "text": "pipeline_config_path = \"<your path>/training/pipeline.config\"config_override = \"\"input_shape = Falsetrained_checkpoint_prefix =\"<your path>/faster_rcnn_inception_v2_coco_2018_01_28/model_dir/model.ckpt-10000\"output_directory = \"<your path>faster_rcnn_inception_v2_coco_2018_01_28/output\"input_type = \"image_tensor\"write_inference_graph = False" }, { "code": null, "e": 19986, "s": 19954, "text": "and now we can run the exporter" }, { "code": null, "e": 20546, "s": 19986, "text": "tf.reset_default_graph()pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()with tf.gfile.GFile(pipeline_config_path, 'r') as f: text_format.Merge(f.read(), pipeline_config)text_format.Merge(config_override, pipeline_config)if input_shape: input_shape = [ int(dim) if dim != '-1' else None for dim in input_shape.split(',') ]else: input_shape = Noneexporter.export_inference_graph( input_type, pipeline_config, trained_checkpoint_prefix, output_directory, input_shape=input_shape, write_inference_graph=write_inference_graph)" }, { "code": null, "e": 20631, "s": 20546, "text": "For TensorFlow 2.x all we have to do is reload the runtime and select 2.x as version" }, { "code": null, "e": 20655, "s": 20631, "text": "%tensorflow_version 2.x" }, { "code": null, "e": 20765, "s": 20655, "text": "and pretty much just follow along their example notebook. You can then load the model with two lines of code:" }, { "code": null, "e": 20911, "s": 20765, "text": "model = tf.saved_model.load(\"<your path>/faster_rcnn_inception_v2_coco_2018_01_28/output/saved_model\")model = model.signatures['serving_default']" }, { "code": null, "e": 20992, "s": 20911, "text": "All we have to do now is load up an image from the test set (e.g raccoon-14.jpg)" }, { "code": null, "e": 21305, "s": 20992, "text": "from PIL import Image, ImageDrawimport numpy as npimport pandas as pdfilename = \"raccoon-14.jpg\"img = Image.open(\"<your path>/raccoon_dataset/images/\"+filename)test = pd.read_csv(\"<your path>/raccoon_dataset/data/test_labels.csv\")true_labels = test[test[\"filename\"] == filename][[\"xmin\", \"ymin\", \"xmax\",\"ymax\"]]" }, { "code": null, "e": 21370, "s": 21305, "text": "and run the inference (as suggested by the tf inference scripts)" }, { "code": null, "e": 22160, "s": 21370, "text": "image = np.asarray(img)# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.input_tensor = tf.convert_to_tensor(image)# The model expects a batch of images, so add an axis with `tf.newaxis`.input_tensor = input_tensor[tf.newaxis,...]# Run inferenceoutput_dict = model(input_tensor)# All outputs are batches tensors.# Convert to numpy arrays, and take index [0] to remove the batchdimension.# We're only interested in the first num_detections.num_detections = int(output_dict.pop('num_detections'))output_dict = {key:value[0, :num_detections].numpy() for key,value in output_dict.items()}output_dict['num_detections'] = num_detections# detection_classes should be ints.output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)" }, { "code": null, "e": 22242, "s": 22160, "text": "Now we can draw the learned bounding box(es) in red and the true labels in green:" }, { "code": null, "e": 22979, "s": 22242, "text": "selected_boxes = output_dict[\"detection_boxes\"]selected_scores = output_dict[\"detection_scores\"]draw = ImageDraw.Draw(img)#draw predictions:for i in range(len(selected_scores)): draw.rectangle([(selected_boxes[i][1]*img.width, selected_boxes[i][0]*img.height), (selected_boxes[i][3]*img.width, selected_boxes[i][2]*img.height)], outline =\"red\", width = 3) draw.text((selected_boxes[i][1]*img.width, selected_boxes[i][0]*img.height), text = str(selected_scores[i]))# draw groundtruth:for i in range(len(true_labels[\"xmin\"].values)): draw.rectangle([(true_labels[\"xmin\"].values[i], true_labels[\"ymin\"].values[i]), (true_labels[\"xmax\"].values[i], true_labels[\"ymax\"].values[i])], outline =\"green\", width = 3)img" }, { "code": null, "e": 23170, "s": 22979, "text": "and we can see a pretty cool little raccoon doing some major housekeeping. Also the bounding boxes and probabilities are pretty good considering we only trained the network for 10.000 steps." }, { "code": null, "e": 23260, "s": 23170, "text": "Note: If you want to do this with tf version 1.x you can follow the scripts located here." }, { "code": null, "e": 23279, "s": 23260, "text": "Section B: PyTorch" }, { "code": null, "e": 23612, "s": 23279, "text": "PyTorch has a package called torchvision that includes model architectures, data sets, and other helpful functions for computer vision. Torchvision also has a subpackage on object detection which we will be using in this section. A lot of the following setup and code is modeled according to torchvision’s object detection tutorial." }, { "code": null, "e": 23706, "s": 23612, "text": "We need to make sure that we have numpy version 1.17 installed.Check pycocotools installation" }, { "code": null, "e": 23770, "s": 23706, "text": "We need to make sure that we have numpy version 1.17 installed." }, { "code": null, "e": 23801, "s": 23770, "text": "Check pycocotools installation" }, { "code": null, "e": 23820, "s": 23801, "text": "import pycocotools" }, { "code": null, "e": 23882, "s": 23820, "text": "4. Change to a PyTorch object detection directory you created" }, { "code": null, "e": 23940, "s": 23882, "text": "import osos.chdir(\"<your path>/pytorch object detection\")" }, { "code": null, "e": 24000, "s": 23940, "text": "3. Clone the PyTorch vision repo and copy some python files" }, { "code": null, "e": 24277, "s": 24000, "text": "%%bashgit clone https://github.com/pytorch/vision.gitcd visiongit checkout v0.3.0cp references/detection/utils.py ../cp references/detection/transforms.py ../cp references/detection/coco_eval.py ../cp references/detection/engine.py ../cp references/detection/coco_utils.py ../" }, { "code": null, "e": 24320, "s": 24277, "text": "4. Now we can do all the necessary imports" }, { "code": null, "e": 24562, "s": 24320, "text": "import numpy as npimport torchimport torch.utils.datafrom PIL import Imageimport pandas as pdfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictorfrom engine import train_one_epoch, evaluateimport utilsimport transforms as T" }, { "code": null, "e": 25157, "s": 24562, "text": "As opposed to having to create a new type of data file for our training data (as with the training.record file in TensorFlow) we only have to write a data set python class that is later used by the model to parse the images and corresponding annotations. The class needs to inherit from torch.utils.data.Dataset and implement the __getitem__ and __len__ methods. As we are just going to use the same raccoon data set as earlier and the data folder in the repo already contains a raccoon_labels.csv file containing all the parsed annotations, all we have to do is write a little helper function:" }, { "code": null, "e": 25373, "s": 25157, "text": "def parse_one_annot(path_to_data_file, filename): data = pd.read_csv(path_to_data_file) boxes_array = data[data[\"filename\"] == filename][[\"xmin\", \"ymin\", \"xmax\", \"ymax\"]].values return boxes_array" }, { "code": null, "e": 25430, "s": 25373, "text": "which we can then use to write our RaccoonDataset class:" }, { "code": null, "e": 26667, "s": 25430, "text": "class RaccoonDataset(torch.utils.data.Dataset): def __init__(self, root, data_file, transforms=None): self.root = root self.transforms = transforms self.imgs = sorted(os.listdir(os.path.join(root, \"images\"))) self.path_to_data_file = data_filedef __getitem__(self, idx): # load images and bounding boxes img_path = os.path.join(self.root, \"images\", self.imgs[idx]) img = Image.open(img_path).convert(\"RGB\") box_list = parse_one_annot(self.path_to_data_file, self.imgs[idx]) boxes = torch.as_tensor(box_list, dtype=torch.float32)num_objs = len(box_list) # there is only one class labels = torch.ones((num_objs,), dtype=torch.int64) image_id = torch.tensor([idx]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) target = {} target[\"boxes\"] = boxes target[\"labels\"] = labels target[\"image_id\"] = image_id target[\"area\"] = area target[\"iscrowd\"] = iscrowdif self.transforms is not None: img, target = self.transforms(img, target) return img, targetdef __len__(self): return len(self.imgs)" }, { "code": null, "e": 26795, "s": 26667, "text": "We can run a quick check to see if everything is implemented correctly. Instantiate a RaccoonDataset object and run __getitem__" }, { "code": null, "e": 26944, "s": 26795, "text": "dataset = RaccoonDataset(root= \"<your path>/raccoon_dataset\",data_file= \"<your path>/raccoon_dataset/data/raccoon_labels.csv\")dataset.__getitem__(0)" }, { "code": null, "e": 26981, "s": 26944, "text": "and the output should look like this" }, { "code": null, "e": 27203, "s": 26981, "text": "(<PIL.Image.Image image mode=RGB size=650x417 at 0x7FE20F358908>, {'area': tensor([141120.]), 'boxes': tensor([[ 81., 88., 522., 408.]]), 'image_id': tensor([0]), 'iscrowd': tensor([0]), 'labels': tensor([1])})" }, { "code": null, "e": 27492, "s": 27203, "text": "Since we used a faster R-CNN earlier for TensorFlow we will also use one here. Also it’s not like torchvision gives us a big choice. They only have 2 pre-trained (on coco) models for object detection available on their website. A Faster R-CNN ResNet-50 FPN and a Mask R-CNN ResNet-50 FPN." }, { "code": null, "e": 27687, "s": 27492, "text": "In order to download the pre-trained faster r-cnn we can write a little get_model function that adjusts the last layer of the model to output a number of classes that suits our raccoon data set:" }, { "code": null, "e": 28128, "s": 27687, "text": "def get_model(num_classes): # load an object detection model pre-trained on COCO model = torchvision.models.detection. fasterrcnn_resnet50_fpn(pretrained=True)# get the number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new on model.roi_heads.box_predictor = FastRCNNPredictor(in_features,/ num_classes) return model" }, { "code": null, "e": 28271, "s": 28128, "text": "We can also add a little transformer function that enhances our training set by doing some basic data augmentation (horizontal flip of images)" }, { "code": null, "e": 28607, "s": 28271, "text": "def get_transform(train): transforms = [] # converts the image, a PIL image, into a PyTorch Tensor transforms.append(T.ToTensor()) if train: # during training, randomly flip the training images # and ground-truth for data augmentation transforms.append(T.RandomHorizontalFlip(0.5)) return T.Compose(transforms)" }, { "code": null, "e": 28781, "s": 28607, "text": "Now we can instantiate our training and testing data classes and assign them to data_loaders that control how images are loaded during training and testing (batch size etc)." }, { "code": null, "e": 29927, "s": 28781, "text": "# use our dataset and defined transformationsdataset = RaccoonDataset(root= \"<your path>/raccoon_dataset\", data_file= \"<your path>/raccoon_dataset/data/raccoon_labels.csv\", transforms = get_transform(train=True))dataset_test = RaccoonDataset(root= \"<your path>/raccoon_dataset\" data_file= \"<your path>/raccoon_dataset/data/raccoon_labels.csv\", transforms = get_transform(train=False))# split the dataset in train and test settorch.manual_seed(1)indices = torch.randperm(len(dataset)).tolist()dataset = torch.utils.data.Subset(dataset, indices[:-40])dataset_test = torch.utils.data.Subset(dataset_test, indices[-40:])# define training and validation data loadersdata_loader = torch.utils.data.DataLoader( dataset, batch_size=2, shuffle=True, num_workers=4, collate_fn=utils.collate_fn)data_loader_test = torch.utils.data.DataLoader( dataset_test, batch_size=1, shuffle=False, num_workers=4, collate_fn=utils.collate_fn)print(\"We have: {} examples, {} are training and {} testing\".format(len(indices), len(dataset), len(dataset_test)))" }, { "code": null, "e": 30023, "s": 29927, "text": "First, we can use the following command to check whether the correct GPU settings are in place:" }, { "code": null, "e": 30049, "s": 30023, "text": "torch.cuda.is_available()" }, { "code": null, "e": 30121, "s": 30049, "text": "If you are running on Google Colab just switch the runtime time to GPU." }, { "code": null, "e": 30289, "s": 30121, "text": "Now we can set up the model using our get_model function. Also we have to specify an optimizer and a learning rate scheduler, that adjusts the learning rate over time." }, { "code": null, "e": 31018, "s": 30289, "text": "device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')# our dataset has two classes only - raccoon and not racoonnum_classes = 2# get the model using our helper functionmodel = get_model(num_classes)# move model to the right devicemodel.to(device)# construct an optimizerparams = [p for p in model.parameters() if p.requires_grad]optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)# and a learning rate scheduler which decreases the learning rate by # 10x every 3 epochslr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)" }, { "code": null, "e": 31236, "s": 31018, "text": "In order to do the training we now must write our own for loop over the number of epochs we wish to train on, then call PyTorch’s train_one_epoch function, adjust the learning rate and finally evaluate once per epoch." }, { "code": null, "e": 31596, "s": 31236, "text": "# let's train it for 10 epochsnum_epochs = 10for epoch in range(num_epochs): # train for one epoch, printing every 10 iterations train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)# update the learning rate lr_scheduler.step() # evaluate on the test dataset evaluate(model, data_loader_test, device=device)" }, { "code": null, "e": 31729, "s": 31596, "text": "In order to save the trained model (there is no automatic checkpointing) we can run the following command once we are done training:" }, { "code": null, "e": 31871, "s": 31729, "text": "os.mkdir(\"<your path>/pytorch object detection/raccoon/\")torch.save(model.state_dict(), \"<your path>/pytorch object detection/raccoon/model\")" }, { "code": null, "e": 31908, "s": 31871, "text": "After 10 epochs I got a mAP of 0.66." }, { "code": null, "e": 32100, "s": 31908, "text": "We first have to load the model, which works by instantiating the same “empty” model with our get_model function from earlier and then loading the saved weights into the network architecture." }, { "code": null, "e": 32236, "s": 32100, "text": "loaded_model = get_model(num_classes = 2)loaded_model.load_state_dict(torch.load(“<your path>/pytorch object detection/raccoon/model”))" }, { "code": null, "e": 32352, "s": 32236, "text": "Now we can use our dataset_test class to get test images and their ground truth and run them through the predictor." }, { "code": null, "e": 33223, "s": 32352, "text": "idx = 0img, _ = dataset_test[idx]label_boxes = np.array(dataset_test[idx][1][\"boxes\"])#put the model in evaluation modeloaded_model.eval()with torch.no_grad(): prediction = loaded_model([img])image = Image.fromarray(img.mul(255).permute(1, 2,0).byte().numpy())draw = ImageDraw.Draw(image)# draw groundtruthfor elem in range(len(label_boxes)): draw.rectangle([(label_boxes[elem][0], label_boxes[elem][1]), (label_boxes[elem][2], label_boxes[elem][3])], outline =\"green\", width =3)for element in range(len(prediction[0][\"boxes\"])): boxes = prediction[0][\"boxes\"][element].cpu().numpy() score = np.round(prediction[0][\"scores\"][element].cpu().numpy(), decimals= 4) if score > 0.8: draw.rectangle([(boxes[0], boxes[1]), (boxes[2], boxes[3])], outline =\"red\", width =3) draw.text((boxes[0], boxes[1]), text = str(score))image" }, { "code": null, "e": 34745, "s": 33223, "text": "All in all, it is safe to say that for people that are used to imperative style coding (code gets executed when written) and have been working with scikit-learn type ML frameworks a lot, PyTorch is most likely going to be easier for them to start with (this might also change once TensorFlow upgrades the object detection API to tf version 2.x). In this article I am only focusing on the “ease of use” side of things, not looking at performance speed, variability, or portability of the model. A lot of these features however are needed when trying to deploy such models into productive software environments. Here the higher-level API used in TensorFlow with the config.py file incorporates a lot more flexibility from the get-go within the framework, where the lower-level torchvision is held more open, meaning it is easier to look “behind the curtain” (you don’t have to work through a ton of TensorFlow source code), however only the standards are displayed in their tutorial. Anything outside of the standard must be written from scratch, whereas TensorFlow might have a section in the config file to address it. Also the TensorFlow model zoo just has way more pre-trained models available for people to use. Overall my experience resembles a very typical sentiment in the data science community, which is that PyTorche’s object detection framework might be better for research purposes and “understanding every detail” of an implementation, while TensorFlow’s API is a better choice for building productive models." }, { "code": null, "e": 34860, "s": 34745, "text": "I hope you guys got some valuable information out of this. Now it’s time to try it out yourselves. Happy coding :)" }, { "code": null, "e": 34889, "s": 34860, "text": "TensorFlow Object detection:" }, { "code": null, "e": 34900, "s": 34889, "text": "github.com" }, { "code": null, "e": 34913, "s": 34900, "text": "Torchvision:" }, { "code": null, "e": 34925, "s": 34913, "text": "pytorch.org" } ]
How to get file extension in Python? - GeeksforGeeks
16 Nov, 2020 In Python, we can extract the file extension using either of the two different approaches discussed below – Method 1: Using Python os module splitext() function This function splits the file path string into file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path). This function is preferred to use when the OS module is being used already. Example: Python3 import os # this will return a tuple of root and extensionsplit_tup = os.path.splitext('my_file.txt')print(split_tup) # extract the file name and extensionfile_name = split_tup[0]file_extension = split_tup[1] print("File Name: ", file_name)print("File Extension: ", file_extension) Output: ('my_file', '.txt') File Name: my_file File Extension: .txt Method 2: Using Pathlib module pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach. Example: Python3 import pathlib # function to return the file extensionfile_extension = pathlib.Path('my_file.txt').suffixprint("File Extension: ", file_extension) Output: File Extension: .txt Python file-handling-programs Python OS-path-module python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n16 Nov, 2020" }, { "code": null, "e": 24009, "s": 23901, "text": "In Python, we can extract the file extension using either of the two different approaches discussed below –" }, { "code": null, "e": 24062, "s": 24009, "text": "Method 1: Using Python os module splitext() function" }, { "code": null, "e": 24351, "s": 24062, "text": "This function splits the file path string into file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path). This function is preferred to use when the OS module is being used already." }, { "code": null, "e": 24360, "s": 24351, "text": "Example:" }, { "code": null, "e": 24368, "s": 24360, "text": "Python3" }, { "code": "import os # this will return a tuple of root and extensionsplit_tup = os.path.splitext('my_file.txt')print(split_tup) # extract the file name and extensionfile_name = split_tup[0]file_extension = split_tup[1] print(\"File Name: \", file_name)print(\"File Extension: \", file_extension)", "e": 24655, "s": 24368, "text": null }, { "code": null, "e": 24663, "s": 24655, "text": "Output:" }, { "code": null, "e": 24725, "s": 24663, "text": "('my_file', '.txt')\nFile Name: my_file\nFile Extension: .txt" }, { "code": null, "e": 24756, "s": 24725, "text": "Method 2: Using Pathlib module" }, { "code": null, "e": 24920, "s": 24756, "text": "pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach." }, { "code": null, "e": 24929, "s": 24920, "text": "Example:" }, { "code": null, "e": 24937, "s": 24929, "text": "Python3" }, { "code": "import pathlib # function to return the file extensionfile_extension = pathlib.Path('my_file.txt').suffixprint(\"File Extension: \", file_extension)", "e": 25085, "s": 24937, "text": null }, { "code": null, "e": 25093, "s": 25085, "text": "Output:" }, { "code": null, "e": 25115, "s": 25093, "text": "File Extension: .txt" }, { "code": null, "e": 25145, "s": 25115, "text": "Python file-handling-programs" }, { "code": null, "e": 25167, "s": 25145, "text": "Python OS-path-module" }, { "code": null, "e": 25188, "s": 25167, "text": "python-file-handling" }, { "code": null, "e": 25195, "s": 25188, "text": "Python" }, { "code": null, "e": 25293, "s": 25195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25302, "s": 25293, "text": "Comments" }, { "code": null, "e": 25315, "s": 25302, "text": "Old Comments" }, { "code": null, "e": 25347, "s": 25315, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25403, "s": 25347, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25445, "s": 25403, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25487, "s": 25445, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25523, "s": 25487, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25562, "s": 25523, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25584, "s": 25562, "text": "Defaultdict in Python" }, { "code": null, "e": 25615, "s": 25584, "text": "Python | os.path.join() method" }, { "code": null, "e": 25642, "s": 25615, "text": "Python Classes and Objects" } ]
ML | Credit Card Fraud Detection
20 Jan, 2022 The challenge is to recognize fraudulent credit card transactions so that the customers of credit card companies are not charged for items that they did not purchase. Main challenges involved in credit card fraud detection are: Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time.Imbalanced Data i.e most of the transactions (99.8%) are not fraudulent which makes it really hard for detecting the fraudulent onesData availability as the data is mostly private.Misclassified Data can be another major issue, as not every fraudulent transaction is caught and reported.Adaptive techniques used against the model by the scammers. Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time. Imbalanced Data i.e most of the transactions (99.8%) are not fraudulent which makes it really hard for detecting the fraudulent ones Data availability as the data is mostly private. Misclassified Data can be another major issue, as not every fraudulent transaction is caught and reported. Adaptive techniques used against the model by the scammers. How to tackle these challenges? The model used must be simple and fast enough to detect the anomaly and classify it as a fraudulent transaction as quickly as possible.Imbalance can be dealt with by properly using some methods which we will talk about in the next paragraphFor protecting the privacy of the user the dimensionality of the data can be reduced.A more trustworthy source must be taken which double-check the data, at least for training the model.We can make the model simple and interpretable so that when the scammer adapts to it with just some tweaks we can have a new model up and running to deploy. The model used must be simple and fast enough to detect the anomaly and classify it as a fraudulent transaction as quickly as possible. Imbalance can be dealt with by properly using some methods which we will talk about in the next paragraph For protecting the privacy of the user the dimensionality of the data can be reduced. A more trustworthy source must be taken which double-check the data, at least for training the model. We can make the model simple and interpretable so that when the scammer adapts to it with just some tweaks we can have a new model up and running to deploy. Before going to the code it is requested to work on a jupyter notebook. If not installed on your machine you can use Google colab.You can download the dataset from this linkIf the link is not working please go to this link and login to kaggle to download the dataset.Code : Importing all the necessary Libraries # import the necessary packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib import gridspec Code : Loading the Data # Load the dataset from the csv file using pandas# best way is to mount the drive on colab and# copy the path for the csv filedata = pd.read_csv("credit.csv") Code : Understanding the Data # Grab a peek at the datadata.head() Code : Describing the Data # Print the shape of the data# data = data.sample(frac = 0.1, random_state = 48)print(data.shape)print(data.describe()) Output : (284807, 31) Time V1 ... Amount Class count 284807.000000 2.848070e+05 ... 284807.000000 284807.000000 mean 94813.859575 3.919560e-15 ... 88.349619 0.001727 std 47488.145955 1.958696e+00 ... 250.120109 0.041527 min 0.000000 -5.640751e+01 ... 0.000000 0.000000 25% 54201.500000 -9.203734e-01 ... 5.600000 0.000000 50% 84692.000000 1.810880e-02 ... 22.000000 0.000000 75% 139320.500000 1.315642e+00 ... 77.165000 0.000000 max 172792.000000 2.454930e+00 ... 25691.160000 1.000000 [8 rows x 31 columns] Code : Imbalance in the dataTime to explain the data we are dealing with. # Determine number of fraud cases in datasetfraud = data[data['Class'] == 1]valid = data[data['Class'] == 0]outlierFraction = len(fraud)/float(len(valid))print(outlierFraction)print('Fraud Cases: {}'.format(len(data[data['Class'] == 1])))print('Valid Transactions: {}'.format(len(data[data['Class'] == 0]))) Only 0.17% fraudulent transaction out all the transactions. The data is highly Unbalanced. Lets first apply our models without balancing it and if we don’t get a good accuracy then we can find a way to balance this dataset. But first, let’s implement the model without it and will balance the data only if needed. Code : Print the amount details for Fraudulent Transaction print(“Amount details of the fraudulent transaction”)fraud.Amount.describe() Output : Amount details of the fraudulent transaction count 492.000000 mean 122.211321 std 256.683288 min 0.000000 25% 1.000000 50% 9.250000 75% 105.890000 max 2125.870000 Name: Amount, dtype: float64 Code : Print the amount details for Normal Transaction print(“details of valid transaction”)valid.Amount.describe() Output : Amount details of valid transaction count 284315.000000 mean 88.291022 std 250.105092 min 0.000000 25% 5.650000 50% 22.000000 75% 77.050000 max 25691.160000 Name: Amount, dtype: float64 As we can clearly notice from this, the average Money transaction for the fraudulent ones is more. This makes this problem crucial to deal with. Code : Plotting the Correlation MatrixThe correlation matrix graphically gives us an idea of how features correlate with each other and can help us predict what are the features that are most relevant for the prediction. # Correlation matrixcorrmat = data.corr()fig = plt.figure(figsize = (12, 9))sns.heatmap(corrmat, vmax = .8, square = True)plt.show() In the HeatMap we can clearly see that most of the features do not correlate to other features but there are some features that either has a positive or a negative correlation with each other. For example, V2 and V5 are highly negatively correlated with the feature called Amount. We also see some correlation with V20 and Amount. This gives us a deeper understanding of the Data available to us. Code : Separating the X and the Y valuesDividing the data into inputs parameters and outputs value format # dividing the X and the Y from the datasetX = data.drop(['Class'], axis = 1)Y = data["Class"]print(X.shape)print(Y.shape)# getting just the values for the sake of processing# (its a numpy array with no columns)xData = X.valuesyData = Y.values Output : (284807, 30) (284807, ) Training and Testing Data BifurcationWe will be dividing the dataset into two main groups. One for training the model and the other for Testing our trained model’s performance. # Using Skicit-learn to split data into training and testing setsfrom sklearn.model_selection import train_test_split# Split the data into training and testing setsxTrain, xTest, yTrain, yTest = train_test_split( xData, yData, test_size = 0.2, random_state = 42) Code : Building a Random Forest Model using skicit learn # Building the Random Forest Classifier (RANDOM FOREST)from sklearn.ensemble import RandomForestClassifier# random forest model creationrfc = RandomForestClassifier()rfc.fit(xTrain, yTrain)# predictionsyPred = rfc.predict(xTest) Code : Building all kinds of evaluating parameters # Evaluating the classifier# printing every score of the classifier# scoring in anythingfrom sklearn.metrics import classification_report, accuracy_scorefrom sklearn.metrics import precision_score, recall_scorefrom sklearn.metrics import f1_score, matthews_corrcoeffrom sklearn.metrics import confusion_matrix n_outliers = len(fraud)n_errors = (yPred != yTest).sum()print("The model used is Random Forest classifier") acc = accuracy_score(yTest, yPred)print("The accuracy is {}".format(acc)) prec = precision_score(yTest, yPred)print("The precision is {}".format(prec)) rec = recall_score(yTest, yPred)print("The recall is {}".format(rec)) f1 = f1_score(yTest, yPred)print("The F1-Score is {}".format(f1)) MCC = matthews_corrcoef(yTest, yPred)print("The Matthews correlation coefficient is{}".format(MCC)) Output : The model used is Random Forest classifier The accuracy is 0.9995611109160493 The precision is 0.9866666666666667 The recall is 0.7551020408163265 The F1-Score is 0.8554913294797689 The Matthews correlation coefficient is0.8629589216367891 Code : Visualizing the Confusion Matrix # printing the confusion matrixLABELS = ['Normal', 'Fraud']conf_matrix = confusion_matrix(yTest, yPred)plt.figure(figsize =(12, 12))sns.heatmap(conf_matrix, xticklabels = LABELS, yticklabels = LABELS, annot = True, fmt ="d");plt.title("Confusion matrix")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show() Output : Comparison with other algorithms without dealing with the imbalancing of the data. As you can see with our Random Forest Model we are getting a better result even for the recall which is the most tricky part. Akanksha_Rai ashwinsharmap sagar0719kumar Machine Learning Project Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2022" }, { "code": null, "e": 219, "s": 52, "text": "The challenge is to recognize fraudulent credit card transactions so that the customers of credit card companies are not charged for items that they did not purchase." }, { "code": null, "e": 280, "s": 219, "text": "Main challenges involved in credit card fraud detection are:" }, { "code": null, "e": 734, "s": 280, "text": "Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time.Imbalanced Data i.e most of the transactions (99.8%) are not fraudulent which makes it really hard for detecting the fraudulent onesData availability as the data is mostly private.Misclassified Data can be another major issue, as not every fraudulent transaction is caught and reported.Adaptive techniques used against the model by the scammers." }, { "code": null, "e": 843, "s": 734, "text": "Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time." }, { "code": null, "e": 976, "s": 843, "text": "Imbalanced Data i.e most of the transactions (99.8%) are not fraudulent which makes it really hard for detecting the fraudulent ones" }, { "code": null, "e": 1025, "s": 976, "text": "Data availability as the data is mostly private." }, { "code": null, "e": 1132, "s": 1025, "text": "Misclassified Data can be another major issue, as not every fraudulent transaction is caught and reported." }, { "code": null, "e": 1192, "s": 1132, "text": "Adaptive techniques used against the model by the scammers." }, { "code": null, "e": 1224, "s": 1192, "text": "How to tackle these challenges?" }, { "code": null, "e": 1807, "s": 1224, "text": "The model used must be simple and fast enough to detect the anomaly and classify it as a fraudulent transaction as quickly as possible.Imbalance can be dealt with by properly using some methods which we will talk about in the next paragraphFor protecting the privacy of the user the dimensionality of the data can be reduced.A more trustworthy source must be taken which double-check the data, at least for training the model.We can make the model simple and interpretable so that when the scammer adapts to it with just some tweaks we can have a new model up and running to deploy." }, { "code": null, "e": 1943, "s": 1807, "text": "The model used must be simple and fast enough to detect the anomaly and classify it as a fraudulent transaction as quickly as possible." }, { "code": null, "e": 2049, "s": 1943, "text": "Imbalance can be dealt with by properly using some methods which we will talk about in the next paragraph" }, { "code": null, "e": 2135, "s": 2049, "text": "For protecting the privacy of the user the dimensionality of the data can be reduced." }, { "code": null, "e": 2237, "s": 2135, "text": "A more trustworthy source must be taken which double-check the data, at least for training the model." }, { "code": null, "e": 2394, "s": 2237, "text": "We can make the model simple and interpretable so that when the scammer adapts to it with just some tweaks we can have a new model up and running to deploy." }, { "code": null, "e": 2706, "s": 2394, "text": "Before going to the code it is requested to work on a jupyter notebook. If not installed on your machine you can use Google colab.You can download the dataset from this linkIf the link is not working please go to this link and login to kaggle to download the dataset.Code : Importing all the necessary Libraries" }, { "code": "# import the necessary packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib import gridspec", "e": 2858, "s": 2706, "text": null }, { "code": null, "e": 2882, "s": 2858, "text": "Code : Loading the Data" }, { "code": "# Load the dataset from the csv file using pandas# best way is to mount the drive on colab and# copy the path for the csv filedata = pd.read_csv(\"credit.csv\")", "e": 3041, "s": 2882, "text": null }, { "code": null, "e": 3071, "s": 3041, "text": "Code : Understanding the Data" }, { "code": "# Grab a peek at the datadata.head()", "e": 3108, "s": 3071, "text": null }, { "code": null, "e": 3135, "s": 3108, "text": "Code : Describing the Data" }, { "code": "# Print the shape of the data# data = data.sample(frac = 0.1, random_state = 48)print(data.shape)print(data.describe())", "e": 3255, "s": 3135, "text": null }, { "code": null, "e": 3264, "s": 3255, "text": "Output :" }, { "code": null, "e": 3932, "s": 3264, "text": "(284807, 31)\n Time V1 ... Amount Class\ncount 284807.000000 2.848070e+05 ... 284807.000000 284807.000000\nmean 94813.859575 3.919560e-15 ... 88.349619 0.001727\nstd 47488.145955 1.958696e+00 ... 250.120109 0.041527\nmin 0.000000 -5.640751e+01 ... 0.000000 0.000000\n25% 54201.500000 -9.203734e-01 ... 5.600000 0.000000\n50% 84692.000000 1.810880e-02 ... 22.000000 0.000000\n75% 139320.500000 1.315642e+00 ... 77.165000 0.000000\nmax 172792.000000 2.454930e+00 ... 25691.160000 1.000000\n\n[8 rows x 31 columns]\n\n" }, { "code": null, "e": 4006, "s": 3932, "text": "Code : Imbalance in the dataTime to explain the data we are dealing with." }, { "code": "# Determine number of fraud cases in datasetfraud = data[data['Class'] == 1]valid = data[data['Class'] == 0]outlierFraction = len(fraud)/float(len(valid))print(outlierFraction)print('Fraud Cases: {}'.format(len(data[data['Class'] == 1])))print('Valid Transactions: {}'.format(len(data[data['Class'] == 0])))", "e": 4314, "s": 4006, "text": null }, { "code": null, "e": 4628, "s": 4314, "text": "Only 0.17% fraudulent transaction out all the transactions. The data is highly Unbalanced. Lets first apply our models without balancing it and if we don’t get a good accuracy then we can find a way to balance this dataset. But first, let’s implement the model without it and will balance the data only if needed." }, { "code": null, "e": 4687, "s": 4628, "text": "Code : Print the amount details for Fraudulent Transaction" }, { "code": "print(“Amount details of the fraudulent transaction”)fraud.Amount.describe()", "e": 4764, "s": 4687, "text": null }, { "code": null, "e": 4773, "s": 4764, "text": "Output :" }, { "code": null, "e": 5017, "s": 4773, "text": "Amount details of the fraudulent transaction\ncount 492.000000\nmean 122.211321\nstd 256.683288\nmin 0.000000\n25% 1.000000\n50% 9.250000\n75% 105.890000\nmax 2125.870000\nName: Amount, dtype: float64\n\n" }, { "code": null, "e": 5072, "s": 5017, "text": "Code : Print the amount details for Normal Transaction" }, { "code": "print(“details of valid transaction”)valid.Amount.describe()", "e": 5133, "s": 5072, "text": null }, { "code": null, "e": 5142, "s": 5133, "text": "Output :" }, { "code": null, "e": 5392, "s": 5142, "text": "Amount details of valid transaction\ncount 284315.000000\nmean 88.291022\nstd 250.105092\nmin 0.000000\n25% 5.650000\n50% 22.000000\n75% 77.050000\nmax 25691.160000\nName: Amount, dtype: float64\n" }, { "code": null, "e": 5537, "s": 5392, "text": "As we can clearly notice from this, the average Money transaction for the fraudulent ones is more. This makes this problem crucial to deal with." }, { "code": null, "e": 5758, "s": 5537, "text": "Code : Plotting the Correlation MatrixThe correlation matrix graphically gives us an idea of how features correlate with each other and can help us predict what are the features that are most relevant for the prediction." }, { "code": "# Correlation matrixcorrmat = data.corr()fig = plt.figure(figsize = (12, 9))sns.heatmap(corrmat, vmax = .8, square = True)plt.show()", "e": 5891, "s": 5758, "text": null }, { "code": null, "e": 6288, "s": 5891, "text": "In the HeatMap we can clearly see that most of the features do not correlate to other features but there are some features that either has a positive or a negative correlation with each other. For example, V2 and V5 are highly negatively correlated with the feature called Amount. We also see some correlation with V20 and Amount. This gives us a deeper understanding of the Data available to us." }, { "code": null, "e": 6394, "s": 6288, "text": "Code : Separating the X and the Y valuesDividing the data into inputs parameters and outputs value format" }, { "code": "# dividing the X and the Y from the datasetX = data.drop(['Class'], axis = 1)Y = data[\"Class\"]print(X.shape)print(Y.shape)# getting just the values for the sake of processing# (its a numpy array with no columns)xData = X.valuesyData = Y.values", "e": 6638, "s": 6394, "text": null }, { "code": null, "e": 6647, "s": 6638, "text": "Output :" }, { "code": null, "e": 6673, "s": 6647, "text": " \n(284807, 30)\n(284807, )" }, { "code": null, "e": 6850, "s": 6673, "text": "Training and Testing Data BifurcationWe will be dividing the dataset into two main groups. One for training the model and the other for Testing our trained model’s performance." }, { "code": "# Using Skicit-learn to split data into training and testing setsfrom sklearn.model_selection import train_test_split# Split the data into training and testing setsxTrain, xTest, yTrain, yTest = train_test_split( xData, yData, test_size = 0.2, random_state = 42)", "e": 7120, "s": 6850, "text": null }, { "code": null, "e": 7177, "s": 7120, "text": "Code : Building a Random Forest Model using skicit learn" }, { "code": "# Building the Random Forest Classifier (RANDOM FOREST)from sklearn.ensemble import RandomForestClassifier# random forest model creationrfc = RandomForestClassifier()rfc.fit(xTrain, yTrain)# predictionsyPred = rfc.predict(xTest)", "e": 7406, "s": 7177, "text": null }, { "code": null, "e": 7457, "s": 7406, "text": "Code : Building all kinds of evaluating parameters" }, { "code": "# Evaluating the classifier# printing every score of the classifier# scoring in anythingfrom sklearn.metrics import classification_report, accuracy_scorefrom sklearn.metrics import precision_score, recall_scorefrom sklearn.metrics import f1_score, matthews_corrcoeffrom sklearn.metrics import confusion_matrix n_outliers = len(fraud)n_errors = (yPred != yTest).sum()print(\"The model used is Random Forest classifier\") acc = accuracy_score(yTest, yPred)print(\"The accuracy is {}\".format(acc)) prec = precision_score(yTest, yPred)print(\"The precision is {}\".format(prec)) rec = recall_score(yTest, yPred)print(\"The recall is {}\".format(rec)) f1 = f1_score(yTest, yPred)print(\"The F1-Score is {}\".format(f1)) MCC = matthews_corrcoef(yTest, yPred)print(\"The Matthews correlation coefficient is{}\".format(MCC))", "e": 8263, "s": 7457, "text": null }, { "code": null, "e": 8272, "s": 8263, "text": "Output :" }, { "code": null, "e": 8514, "s": 8272, "text": "The model used is Random Forest classifier\nThe accuracy is 0.9995611109160493\nThe precision is 0.9866666666666667\nThe recall is 0.7551020408163265\nThe F1-Score is 0.8554913294797689\nThe Matthews correlation coefficient is0.8629589216367891\n" }, { "code": null, "e": 8554, "s": 8514, "text": "Code : Visualizing the Confusion Matrix" }, { "code": "# printing the confusion matrixLABELS = ['Normal', 'Fraud']conf_matrix = confusion_matrix(yTest, yPred)plt.figure(figsize =(12, 12))sns.heatmap(conf_matrix, xticklabels = LABELS, yticklabels = LABELS, annot = True, fmt =\"d\");plt.title(\"Confusion matrix\")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show()", "e": 8883, "s": 8554, "text": null }, { "code": null, "e": 8892, "s": 8883, "text": "Output :" }, { "code": null, "e": 8977, "s": 8894, "text": "Comparison with other algorithms without dealing with the imbalancing of the data." }, { "code": null, "e": 9103, "s": 8977, "text": "As you can see with our Random Forest Model we are getting a better result even for the recall which is the most tricky part." }, { "code": null, "e": 9116, "s": 9103, "text": "Akanksha_Rai" }, { "code": null, "e": 9130, "s": 9116, "text": "ashwinsharmap" }, { "code": null, "e": 9145, "s": 9130, "text": "sagar0719kumar" }, { "code": null, "e": 9162, "s": 9145, "text": "Machine Learning" }, { "code": null, "e": 9170, "s": 9162, "text": "Project" }, { "code": null, "e": 9177, "s": 9170, "text": "Python" }, { "code": null, "e": 9194, "s": 9177, "text": "Machine Learning" } ]
Program to print last 10 lines
16 Apr, 2019 Given some text lines in one string, each line is separated by ‘\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines. Source: Microsoft Interview | Set 10 Following are the steps1) Find the last occurrence of DELIM or ‘\n’2) Initialize target position as last occurrence of ‘\n’ and count as 0 , and do following while count < 10......2.a) Find the next instance of ‘\n’ and update target position.....2.b) Skip ‘\n’ and increment count of ‘\n’ and update target position3) Print the sub-string from target position. C++ C // C++ Program to print the last 10 lines. // If number of lines is less than 10,// then print all lines. #include <bits/stdc++.h>using namespace std; #define DELIM '\n' /* Function to print last n lines of a given string */void print_last_lines(char *str, int n) { /* Base case */ if (n <= 0) return; size_t cnt = 0; // To store count of '\n' or DELIM char *target_pos = NULL; // To store the output position in str /* Step 1: Find the last occurrence of DELIM or '\n' */ target_pos = strrchr(str, DELIM); /* Error if '\n' is not present at all */ if (target_pos == NULL) { cout << "ERROR: string doesn't contain '\\n' character\n"; return; } /* Step 2: Find the target position from where we need to print the string */ while (cnt < n) { // Step 2.a: Find the next instance of '\n' while (str < target_pos && *target_pos != DELIM) --target_pos; /* Step 2.b: skip '\n' and increment count of '\n' */ if (*target_pos == DELIM) --target_pos, ++cnt; /* str < target_pos means str has less than 10 '\n' characters, so break from loop */ else break; } /* In while loop, target_pos is decremented 2 times, that's why target_pos + 2 */ if (str < target_pos) target_pos += 2; // Step 3: Print the string from target_pos cout << target_pos << endl; } // Driver Codeint main(void) { char *str1 ="str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\nstr8\nstr9" "\nstr10\nstr11\nstr12\nstr13\nstr14\nstr15\nstr16\nstr17" "\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"; char *str2 ="str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7"; char *str3 ="\n"; char *str4 = ""; print_last_lines(str1, 10); cout << "-----------------\n"; print_last_lines(str2, 10); cout << "-----------------\n"; print_last_lines(str3, 10); cout << "-----------------\n";; print_last_lines(str4, 10); cout << "-----------------\n"; return 0; } // This is code is contributed by rathbhupendra /* Program to print the last 10 lines. If number of lines is less than 10, then print all lines. */ #include <stdio.h>#include <string.h>#define DELIM '\n' /* Function to print last n lines of a given string */void print_last_lines(char *str, int n){ /* Base case */ if (n <= 0) return; size_t cnt = 0; // To store count of '\n' or DELIM char *target_pos = NULL; // To store the output position in str /* Step 1: Find the last occurrence of DELIM or '\n' */ target_pos = strrchr(str, DELIM); /* Error if '\n' is not present at all */ if (target_pos == NULL) { fprintf(stderr, "ERROR: string doesn't contain '\\n' character\n"); return; } /* Step 2: Find the target position from where we need to print the string */ while (cnt < n) { // Step 2.a: Find the next instance of '\n' while (str < target_pos && *target_pos != DELIM) --target_pos; /* Step 2.b: skip '\n' and increment count of '\n' */ if (*target_pos == DELIM) --target_pos, ++cnt; /* str < target_pos means str has less than 10 '\n' characters, so break from loop */ else break; } /* In while loop, target_pos is decremented 2 times, that's why target_pos + 2 */ if (str < target_pos) target_pos += 2; // Step 3: Print the string from target_pos printf("%s\n", target_pos);} // Driver program to test above functionint main(void){ char *str1 = "str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\nstr8\nstr9" "\nstr10\nstr11\nstr12\nstr13\nstr14\nstr15\nstr16\nstr17" "\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"; char *str2 = "str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7"; char *str3 = "\n"; char *str4 = ""; print_last_lines(str1, 10); printf("-----------------\n"); print_last_lines(str2, 10); printf("-----------------\n"); print_last_lines(str3, 10); printf("-----------------\n"); print_last_lines(str4, 10); printf("-----------------\n"); return 0;} Output: str16 str17 str18 str19 str20 str21 str22 str23 str24 str25 ----------------- str1 str2 str3 str4 str5 str6 str7 ----------------- ----------------- ERROR: string doesn't contain '\n' character ----------------- Note: Above program can be modified to print last N lines by passing N instead of 10. N can store any integer value.This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Apr, 2019" }, { "code": null, "e": 217, "s": 54, "text": "Given some text lines in one string, each line is separated by ‘\\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines." }, { "code": null, "e": 254, "s": 217, "text": "Source: Microsoft Interview | Set 10" }, { "code": null, "e": 616, "s": 254, "text": "Following are the steps1) Find the last occurrence of DELIM or ‘\\n’2) Initialize target position as last occurrence of ‘\\n’ and count as 0 , and do following while count < 10......2.a) Find the next instance of ‘\\n’ and update target position.....2.b) Skip ‘\\n’ and increment count of ‘\\n’ and update target position3) Print the sub-string from target position." }, { "code": null, "e": 620, "s": 616, "text": "C++" }, { "code": null, "e": 622, "s": 620, "text": "C" }, { "code": "// C++ Program to print the last 10 lines. // If number of lines is less than 10,// then print all lines. #include <bits/stdc++.h>using namespace std; #define DELIM '\\n' /* Function to print last n lines of a given string */void print_last_lines(char *str, int n) { /* Base case */ if (n <= 0) return; size_t cnt = 0; // To store count of '\\n' or DELIM char *target_pos = NULL; // To store the output position in str /* Step 1: Find the last occurrence of DELIM or '\\n' */ target_pos = strrchr(str, DELIM); /* Error if '\\n' is not present at all */ if (target_pos == NULL) { cout << \"ERROR: string doesn't contain '\\\\n' character\\n\"; return; } /* Step 2: Find the target position from where we need to print the string */ while (cnt < n) { // Step 2.a: Find the next instance of '\\n' while (str < target_pos && *target_pos != DELIM) --target_pos; /* Step 2.b: skip '\\n' and increment count of '\\n' */ if (*target_pos == DELIM) --target_pos, ++cnt; /* str < target_pos means str has less than 10 '\\n' characters, so break from loop */ else break; } /* In while loop, target_pos is decremented 2 times, that's why target_pos + 2 */ if (str < target_pos) target_pos += 2; // Step 3: Print the string from target_pos cout << target_pos << endl; } // Driver Codeint main(void) { char *str1 =\"str1\\nstr2\\nstr3\\nstr4\\nstr5\\nstr6\\nstr7\\nstr8\\nstr9\" \"\\nstr10\\nstr11\\nstr12\\nstr13\\nstr14\\nstr15\\nstr16\\nstr17\" \"\\nstr18\\nstr19\\nstr20\\nstr21\\nstr22\\nstr23\\nstr24\\nstr25\"; char *str2 =\"str1\\nstr2\\nstr3\\nstr4\\nstr5\\nstr6\\nstr7\"; char *str3 =\"\\n\"; char *str4 = \"\"; print_last_lines(str1, 10); cout << \"-----------------\\n\"; print_last_lines(str2, 10); cout << \"-----------------\\n\"; print_last_lines(str3, 10); cout << \"-----------------\\n\";; print_last_lines(str4, 10); cout << \"-----------------\\n\"; return 0; } // This is code is contributed by rathbhupendra", "e": 2776, "s": 622, "text": null }, { "code": "/* Program to print the last 10 lines. If number of lines is less than 10, then print all lines. */ #include <stdio.h>#include <string.h>#define DELIM '\\n' /* Function to print last n lines of a given string */void print_last_lines(char *str, int n){ /* Base case */ if (n <= 0) return; size_t cnt = 0; // To store count of '\\n' or DELIM char *target_pos = NULL; // To store the output position in str /* Step 1: Find the last occurrence of DELIM or '\\n' */ target_pos = strrchr(str, DELIM); /* Error if '\\n' is not present at all */ if (target_pos == NULL) { fprintf(stderr, \"ERROR: string doesn't contain '\\\\n' character\\n\"); return; } /* Step 2: Find the target position from where we need to print the string */ while (cnt < n) { // Step 2.a: Find the next instance of '\\n' while (str < target_pos && *target_pos != DELIM) --target_pos; /* Step 2.b: skip '\\n' and increment count of '\\n' */ if (*target_pos == DELIM) --target_pos, ++cnt; /* str < target_pos means str has less than 10 '\\n' characters, so break from loop */ else break; } /* In while loop, target_pos is decremented 2 times, that's why target_pos + 2 */ if (str < target_pos) target_pos += 2; // Step 3: Print the string from target_pos printf(\"%s\\n\", target_pos);} // Driver program to test above functionint main(void){ char *str1 = \"str1\\nstr2\\nstr3\\nstr4\\nstr5\\nstr6\\nstr7\\nstr8\\nstr9\" \"\\nstr10\\nstr11\\nstr12\\nstr13\\nstr14\\nstr15\\nstr16\\nstr17\" \"\\nstr18\\nstr19\\nstr20\\nstr21\\nstr22\\nstr23\\nstr24\\nstr25\"; char *str2 = \"str1\\nstr2\\nstr3\\nstr4\\nstr5\\nstr6\\nstr7\"; char *str3 = \"\\n\"; char *str4 = \"\"; print_last_lines(str1, 10); printf(\"-----------------\\n\"); print_last_lines(str2, 10); printf(\"-----------------\\n\"); print_last_lines(str3, 10); printf(\"-----------------\\n\"); print_last_lines(str4, 10); printf(\"-----------------\\n\"); return 0;}", "e": 4870, "s": 2776, "text": null }, { "code": null, "e": 4878, "s": 4870, "text": "Output:" }, { "code": null, "e": 5091, "s": 4878, "text": "str16\nstr17\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25\n-----------------\nstr1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\n-----------------\n\n-----------------\nERROR: string doesn't contain '\\n' character\n-----------------" }, { "code": null, "e": 5381, "s": 5091, "text": "Note: Above program can be modified to print last N lines by passing N instead of 10. N can store any integer value.This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5395, "s": 5381, "text": "rathbhupendra" }, { "code": null, "e": 5406, "s": 5395, "text": "C Language" }, { "code": null, "e": 5410, "s": 5406, "text": "C++" }, { "code": null, "e": 5414, "s": 5410, "text": "CPP" }, { "code": null, "e": 5512, "s": 5414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5529, "s": 5512, "text": "Substring in C++" }, { "code": null, "e": 5564, "s": 5529, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 5586, "s": 5564, "text": "Function Pointer in C" }, { "code": null, "e": 5632, "s": 5586, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 5677, "s": 5632, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5695, "s": 5677, "text": "Vector in C++ STL" }, { "code": null, "e": 5738, "s": 5695, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 5784, "s": 5738, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 5827, "s": 5784, "text": "Set in C++ Standard Template Library (STL)" } ]
How to make an element “flash” in jQuery ?
14 May, 2020 In this article, we will create flashing elements using jQuery. There are two approaches that are discussed below. We will use the CDN link to include jQuery content. The CDN link of jQuery must be added to the HTML document. https://code.jquery.com/ We will use HTML5 and CSS3 to create the structure of our document and add the required elements. HTML Code: We will add some dummy text inside a div element with black border. Subsequently, we will make this text flash.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script></head> <body> <h2 class="header">Geeks for Geeks</h2> <div class="element"> <p class="text flash1"> This is the flashing element</p> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script></head> <body> <h2 class="header">Geeks for Geeks</h2> <div class="element"> <p class="text flash1"> This is the flashing element</p> </div></body> </html> CSS Code: Let us design the elements using CSS to make the page attractive.CSS code:<style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; }</style> CSS code: <style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; }</style> Output: Approach 1: Using fadeIn() and fadeOut() Method: In this approach, we will set consecutive fadeIn() and fadeOut() methods on the element and then set an interval to ensure the flashing continues indefinitely. $(document).ready(() => { setInterval(() => { $('p').fadeIn(); $('p').fadeOut(); }, 500);}); Example: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> How to make an element "flash" in jQuery? </title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } </style></head> <body> <h2 class="header">Geeks for Geeks</h2> <div class="element"> <p class="text flash1"> This is the flashing element </p> </div> <script> $(document).ready(() => { const lheight = $('.element').height(); setInterval(() => { $('p').fadeIn(); $('p').fadeOut(); // The following code keeps the // height of the div intact if ($('.element').height() !== 0) { $('.element').css('height', `${lheight}px`); } }, 500); }); </script></body> </html> Output: Approach 2: Using toggleClass() method: We will use the method to change CSS classes with different designs. As a result, the element will seem to be flash. Let us add the required CSS classes: <style> .header { color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } .flash1 { color: black; } .flash2 { color: rgb(0, 153, 0); }</style> The following JavaScript will help us to make the text element flash with a different color: $(document).ready(() => { setInterval(() => { switch ($("p").attr("class")) { case "text flash1": $("p").toggleClass("flash1 flash2"); break; case "text flash2": $("p").toggleClass("flash2 flash1"); } }, 500);}); Example: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width,initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <title> How to make an element "flash" in jQuery? </title> <style> .header { margin-left: 16px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } .flash1 { color: black; } .flash2 { color: rgb(0, 153, 0); } </style></head> <body> <h2 class="header">Geeks for Geeks</h2> <div class="element"> <p class="text flash1"> This is the flashing element </p> </div> <script> $(document).ready(() => { setInterval(() => { switch ($("p").attr("class")) { case "text flash1": $("p").toggleClass("flash1 flash2"); break; case "text flash2": $("p").toggleClass("flash2 flash1"); } }, 500); }); </script></body> </html> Output: CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2020" }, { "code": null, "e": 169, "s": 54, "text": "In this article, we will create flashing elements using jQuery. There are two approaches that are discussed below." }, { "code": null, "e": 280, "s": 169, "text": "We will use the CDN link to include jQuery content. The CDN link of jQuery must be added to the HTML document." }, { "code": null, "e": 305, "s": 280, "text": "https://code.jquery.com/" }, { "code": null, "e": 403, "s": 305, "text": "We will use HTML5 and CSS3 to create the structure of our document and add the required elements." }, { "code": null, "e": 1112, "s": 403, "text": "HTML Code: We will add some dummy text inside a div element with black border. Subsequently, we will make this text flash.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"> </script></head> <body> <h2 class=\"header\">Geeks for Geeks</h2> <div class=\"element\"> <p class=\"text flash1\"> This is the flashing element</p> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"> </script></head> <body> <h2 class=\"header\">Geeks for Geeks</h2> <div class=\"element\"> <p class=\"text flash1\"> This is the flashing element</p> </div></body> </html>", "e": 1699, "s": 1112, "text": null }, { "code": null, "e": 1967, "s": 1699, "text": "CSS Code: Let us design the elements using CSS to make the page attractive.CSS code:<style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; }</style>" }, { "code": null, "e": 1977, "s": 1967, "text": "CSS code:" }, { "code": "<style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; }</style>", "e": 2161, "s": 1977, "text": null }, { "code": null, "e": 2169, "s": 2161, "text": "Output:" }, { "code": null, "e": 2378, "s": 2169, "text": "Approach 1: Using fadeIn() and fadeOut() Method: In this approach, we will set consecutive fadeIn() and fadeOut() methods on the element and then set an interval to ensure the flashing continues indefinitely." }, { "code": "$(document).ready(() => { setInterval(() => { $('p').fadeIn(); $('p').fadeOut(); }, 500);});", "e": 2491, "s": 2378, "text": null }, { "code": null, "e": 2500, "s": 2491, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> How to make an element \"flash\" in jQuery? </title> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"> </script> <style> .header { margin-left: 18px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } </style></head> <body> <h2 class=\"header\">Geeks for Geeks</h2> <div class=\"element\"> <p class=\"text flash1\"> This is the flashing element </p> </div> <script> $(document).ready(() => { const lheight = $('.element').height(); setInterval(() => { $('p').fadeIn(); $('p').fadeOut(); // The following code keeps the // height of the div intact if ($('.element').height() !== 0) { $('.element').css('height', `${lheight}px`); } }, 500); }); </script></body> </html>", "e": 3790, "s": 2500, "text": null }, { "code": null, "e": 3798, "s": 3790, "text": "Output:" }, { "code": null, "e": 3955, "s": 3798, "text": "Approach 2: Using toggleClass() method: We will use the method to change CSS classes with different designs. As a result, the element will seem to be flash." }, { "code": null, "e": 3992, "s": 3955, "text": "Let us add the required CSS classes:" }, { "code": "<style> .header { color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } .flash1 { color: black; } .flash2 { color: rgb(0, 153, 0); }</style>", "e": 4241, "s": 3992, "text": null }, { "code": null, "e": 4334, "s": 4241, "text": "The following JavaScript will help us to make the text element flash with a different color:" }, { "code": "$(document).ready(() => { setInterval(() => { switch ($(\"p\").attr(\"class\")) { case \"text flash1\": $(\"p\").toggleClass(\"flash1 flash2\"); break; case \"text flash2\": $(\"p\").toggleClass(\"flash2 flash1\"); } }, 500);});", "e": 4648, "s": 4334, "text": null }, { "code": null, "e": 4657, "s": 4648, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width,initial-scale=1.0\"> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"> </script> <title> How to make an element \"flash\" in jQuery? </title> <style> .header { margin-left: 16px; color: rgb(0, 153, 0); } .element { border: 2px solid black; width: 12vw; padding: 5px; } .flash1 { color: black; } .flash2 { color: rgb(0, 153, 0); } </style></head> <body> <h2 class=\"header\">Geeks for Geeks</h2> <div class=\"element\"> <p class=\"text flash1\"> This is the flashing element </p> </div> <script> $(document).ready(() => { setInterval(() => { switch ($(\"p\").attr(\"class\")) { case \"text flash1\": $(\"p\").toggleClass(\"flash1 flash2\"); break; case \"text flash2\": $(\"p\").toggleClass(\"flash2 flash1\"); } }, 500); }); </script></body> </html>", "e": 6014, "s": 4657, "text": null }, { "code": null, "e": 6022, "s": 6014, "text": "Output:" }, { "code": null, "e": 6031, "s": 6022, "text": "CSS-Misc" }, { "code": null, "e": 6041, "s": 6031, "text": "HTML-Misc" }, { "code": null, "e": 6053, "s": 6041, "text": "jQuery-Misc" }, { "code": null, "e": 6060, "s": 6053, "text": "Picked" }, { "code": null, "e": 6064, "s": 6060, "text": "CSS" }, { "code": null, "e": 6069, "s": 6064, "text": "HTML" }, { "code": null, "e": 6076, "s": 6069, "text": "JQuery" }, { "code": null, "e": 6093, "s": 6076, "text": "Web Technologies" }, { "code": null, "e": 6120, "s": 6093, "text": "Web technologies Questions" }, { "code": null, "e": 6125, "s": 6120, "text": "HTML" } ]
How to connect ODBC Database with PHP?
03 Feb, 2021 The Microsoft Open Database Connectivity (ODBC) is a C application programming language interface. So the applications can access data from different database management systems. The designers of ODBC aimed to make it independent of database systems and operating systems. In this article, we are using the Microsoft Access database to establish a connection. Requirements: If ODBC Drivers are installed or the old version is installed, then update to the latest version or install the driver first Start XAMPP server by starting Apache Write PHP script for Access database connection. Run it in a local browser. The database is successfully connected. Steps to follow for ODBC connection to an MS Access Database: Open the Administrative tools icon in your control panel Double-click on the Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the System DSN tab. Select the Microsoft Access Driver, Click Finish In the next screen, click on select to locate the database Give the database a Data Source Name (DSN) as shown in the above image. Click ok. Example: The following example demonstrates the simple connection script. PHP <!DOCTYPE html><html> <body> <?php //Storing DSN(Data Source Name created) $dsn="raj"; $user="root"; $password=""; //storing connection id in $conn $conn=odbc_connect($dsn,$user, $password); //Checking connection id or reference if (!$conn) { echo (die(odbc_error())); } else { echo "Connection Successful !"; } //Resource releasing odbc_close($conn); ?> </body></html> Below output will be shown on the browser Output: Connection Successful ! coder36 PHP-Misc PHP PHP Programs PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between HTTP GET and POST Methods How to fetch data from localserver database and display on HTML table using PHP ? PHP Cookies How to create admin login page using PHP? Different ways for passing data to view in Laravel How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? Refresh a page using PHP PHP | Ternary Operator
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Feb, 2021" }, { "code": null, "e": 415, "s": 54, "text": "The Microsoft Open Database Connectivity (ODBC) is a C application programming language interface. So the applications can access data from different database management systems. The designers of ODBC aimed to make it independent of database systems and operating systems. In this article, we are using the Microsoft Access database to establish a connection." }, { "code": null, "e": 555, "s": 415, "text": "Requirements: If ODBC Drivers are installed or the old version is installed, then update to the latest version or install the driver first " }, { "code": null, "e": 593, "s": 555, "text": "Start XAMPP server by starting Apache" }, { "code": null, "e": 642, "s": 593, "text": "Write PHP script for Access database connection." }, { "code": null, "e": 669, "s": 642, "text": "Run it in a local browser." }, { "code": null, "e": 709, "s": 669, "text": "The database is successfully connected." }, { "code": null, "e": 771, "s": 709, "text": "Steps to follow for ODBC connection to an MS Access Database:" }, { "code": null, "e": 828, "s": 771, "text": "Open the Administrative tools icon in your control panel" }, { "code": null, "e": 881, "s": 828, "text": "Double-click on the Data Sources (ODBC) icon inside." }, { "code": null, "e": 908, "s": 881, "text": "Choose the System DSN tab." }, { "code": null, "e": 976, "s": 940, "text": "Click on Add in the System DSN tab." }, { "code": null, "e": 1025, "s": 976, "text": "Select the Microsoft Access Driver, Click Finish" }, { "code": null, "e": 1084, "s": 1025, "text": "In the next screen, click on select to locate the database" }, { "code": null, "e": 1166, "s": 1084, "text": "Give the database a Data Source Name (DSN) as shown in the above image. Click ok." }, { "code": null, "e": 1240, "s": 1166, "text": "Example: The following example demonstrates the simple connection script." }, { "code": null, "e": 1244, "s": 1240, "text": "PHP" }, { "code": "<!DOCTYPE html><html> <body> <?php //Storing DSN(Data Source Name created) $dsn=\"raj\"; $user=\"root\"; $password=\"\"; //storing connection id in $conn $conn=odbc_connect($dsn,$user, $password); //Checking connection id or reference if (!$conn) { echo (die(odbc_error())); } else { echo \"Connection Successful !\"; } //Resource releasing odbc_close($conn); ?> </body></html>", "e": 1647, "s": 1244, "text": null }, { "code": null, "e": 1690, "s": 1647, "text": " Below output will be shown on the browser" }, { "code": null, "e": 1699, "s": 1690, "text": "Output: " }, { "code": null, "e": 1723, "s": 1699, "text": "Connection Successful !" }, { "code": null, "e": 1733, "s": 1725, "text": "coder36" }, { "code": null, "e": 1742, "s": 1733, "text": "PHP-Misc" }, { "code": null, "e": 1746, "s": 1742, "text": "PHP" }, { "code": null, "e": 1759, "s": 1746, "text": "PHP Programs" }, { "code": null, "e": 1763, "s": 1759, "text": "PHP" }, { "code": null, "e": 1861, "s": 1763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1906, "s": 1861, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 1988, "s": 1906, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2000, "s": 1988, "text": "PHP Cookies" }, { "code": null, "e": 2042, "s": 2000, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 2093, "s": 2042, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2145, "s": 2093, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 2227, "s": 2145, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2269, "s": 2227, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 2294, "s": 2269, "text": "Refresh a page using PHP" } ]
Object.MemberwiseClone Method in C# with Examples
23 Mar, 2022 Object.MemberwiseClone Method is used to create a shallow copy or make clone of the current Object. Shallow copy is a bit-wise copy of an object. In this case, a new object is created and that object has an exact copy of the existing object. Basically, this method copies the non-static fields of the current object to the new object. If a field is a reference type, then the only reference is copied not the referred object. So here, the cloned object and the original object will refer to the same object. If the field is value type then the bit-by-bit copy of the field will be performed. Syntax: protected object MemberwiseClone (); Returns: This method returns a Object, which is the shallow copy of existing Object. Example 1: csharp // C# program to clone a object// using MemberwiseClone() methodusing System; class GFG1 { public int val; public GFG1(int val) { this.val = val; } } class GFG2 { public GFG1 gg; public GFG2(int val) { // copy the reference of GFG1 to gg this.gg = new GFG1(val); } // method for cloning public GFG2 Clone() { // return cloned value using // MemberwiseClone() method return ((GFG2)MemberwiseClone()); }} // Driver Codeclass Geek { // Main Method public static void Main() { // object of Class GFG2 with a value 3 GFG2 g = new GFG2(3); // calling Clone() // "cc" has the reference of Clone() GFG2 cc = g.Clone(); // accessing the main value Console.WriteLine("Value: " + g.gg.val); // accessing the cloned value Console.WriteLine("cloned value: " + cc.gg.val); // set a new value // in variable "val" cc.gg.val = 6; // accessing the main value Console.WriteLine("\nValue: " + g.gg.val); // accessing the cloned value Console.WriteLine("cloned value: " + cc.gg.val); }} Value: 3 cloned value: 3 Value: 6 cloned value: 6 Example 2: csharp // C# program to demonstrate the// MemberwiseClone() methodusing System; public class GFG : ICloneable { // data members public string Name; public string Surname; public int Age; // constructor public GFG(string name, string title, int age) { Name = name; Surname = title; Age = age; } // method for cloning public object Clone() { // return cloned value using // MemberwiseClone() method return MemberwiseClone(); } public override string ToString() { return string.Format("Name = {0}, Surname = {1}, Age {2}", Name, Surname, Age); }} // Driver Classpublic class MainClass { // Main Method public static void Main() { GFG g = new GFG("ABC", "XYZ", 26); // calling Clone() // "cg" has reference of Clone() GFG cg = (GFG)g.Clone(); Console.WriteLine("For Old values\nOriginal :"); Console.WriteLine(g); Console.WriteLine("Cloned :"); Console.WriteLine(cg); Console.WriteLine("\nAfter assigning new values"); g.Name = "LMN"; g.Surname = "QRS"; g.Age = 13; Console.WriteLine("Original :"); Console.WriteLine(g); Console.WriteLine("Cloned :"); // prints the old cloned value Console.WriteLine(cg); }} For Old values Original : Name = ABC, Surname = XYZ, Age 26 Cloned : Name = ABC, Surname = XYZ, Age 26 After assigning new values Original : Name = LMN, Surname = QRS, Age 13 Cloned : Name = ABC, Surname = XYZ, Age 26 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8 simmytarika5 CSharp Object Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 363, "s": 28, "text": "Object.MemberwiseClone Method is used to create a shallow copy or make clone of the current Object. Shallow copy is a bit-wise copy of an object. In this case, a new object is created and that object has an exact copy of the existing object. Basically, this method copies the non-static fields of the current object to the new object." }, { "code": null, "e": 536, "s": 363, "text": "If a field is a reference type, then the only reference is copied not the referred object. So here, the cloned object and the original object will refer to the same object." }, { "code": null, "e": 620, "s": 536, "text": "If the field is value type then the bit-by-bit copy of the field will be performed." }, { "code": null, "e": 628, "s": 620, "text": "Syntax:" }, { "code": null, "e": 665, "s": 628, "text": "protected object MemberwiseClone ();" }, { "code": null, "e": 762, "s": 665, "text": "Returns: This method returns a Object, which is the shallow copy of existing Object. Example 1: " }, { "code": null, "e": 769, "s": 762, "text": "csharp" }, { "code": "// C# program to clone a object// using MemberwiseClone() methodusing System; class GFG1 { public int val; public GFG1(int val) { this.val = val; } } class GFG2 { public GFG1 gg; public GFG2(int val) { // copy the reference of GFG1 to gg this.gg = new GFG1(val); } // method for cloning public GFG2 Clone() { // return cloned value using // MemberwiseClone() method return ((GFG2)MemberwiseClone()); }} // Driver Codeclass Geek { // Main Method public static void Main() { // object of Class GFG2 with a value 3 GFG2 g = new GFG2(3); // calling Clone() // \"cc\" has the reference of Clone() GFG2 cc = g.Clone(); // accessing the main value Console.WriteLine(\"Value: \" + g.gg.val); // accessing the cloned value Console.WriteLine(\"cloned value: \" + cc.gg.val); // set a new value // in variable \"val\" cc.gg.val = 6; // accessing the main value Console.WriteLine(\"\\nValue: \" + g.gg.val); // accessing the cloned value Console.WriteLine(\"cloned value: \" + cc.gg.val); }}", "e": 2020, "s": 769, "text": null }, { "code": null, "e": 2071, "s": 2020, "text": "Value: 3\ncloned value: 3\n\nValue: 6\ncloned value: 6" }, { "code": null, "e": 2083, "s": 2071, "text": "Example 2: " }, { "code": null, "e": 2090, "s": 2083, "text": "csharp" }, { "code": "// C# program to demonstrate the// MemberwiseClone() methodusing System; public class GFG : ICloneable { // data members public string Name; public string Surname; public int Age; // constructor public GFG(string name, string title, int age) { Name = name; Surname = title; Age = age; } // method for cloning public object Clone() { // return cloned value using // MemberwiseClone() method return MemberwiseClone(); } public override string ToString() { return string.Format(\"Name = {0}, Surname = {1}, Age {2}\", Name, Surname, Age); }} // Driver Classpublic class MainClass { // Main Method public static void Main() { GFG g = new GFG(\"ABC\", \"XYZ\", 26); // calling Clone() // \"cg\" has reference of Clone() GFG cg = (GFG)g.Clone(); Console.WriteLine(\"For Old values\\nOriginal :\"); Console.WriteLine(g); Console.WriteLine(\"Cloned :\"); Console.WriteLine(cg); Console.WriteLine(\"\\nAfter assigning new values\"); g.Name = \"LMN\"; g.Surname = \"QRS\"; g.Age = 13; Console.WriteLine(\"Original :\"); Console.WriteLine(g); Console.WriteLine(\"Cloned :\"); // prints the old cloned value Console.WriteLine(cg); }}", "e": 3493, "s": 2090, "text": null }, { "code": null, "e": 3712, "s": 3493, "text": "For Old values\nOriginal :\nName = ABC, Surname = XYZ, Age 26\nCloned :\nName = ABC, Surname = XYZ, Age 26\n\nAfter assigning new values\nOriginal :\nName = LMN, Surname = QRS, Age 13\nCloned :\nName = ABC, Surname = XYZ, Age 26" }, { "code": null, "e": 3723, "s": 3712, "text": "Reference:" }, { "code": null, "e": 3819, "s": 3723, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8" }, { "code": null, "e": 3832, "s": 3819, "text": "simmytarika5" }, { "code": null, "e": 3852, "s": 3832, "text": "CSharp Object Class" }, { "code": null, "e": 3866, "s": 3852, "text": "CSharp-method" }, { "code": null, "e": 3869, "s": 3866, "text": "C#" } ]
HTML <code> Tag
17 Mar, 2022 The <code> tag in HTML is used to define the piece of computer code. During the creation of web pages sometimes there is a need to display computer programming code. It could be done by any basic heading tag of HTML but HTML provides a separated tag which is <code>. The code tag is a specific type of text which represents computer output. HTML provides many methods for text-formatting but <code> tag is displayed with fixed letter size, font, and spacing. Some points about <code> tag: It is mainly used to display the code snippet into the web browser. This tag styles its element to match the computer’s default text format. The web browsers by default use a monospace font family for displaying <code< tags element content. Syntax: <code> Contents... </code> The below examples illustrates the HTML code Tag. Example 1: HTML <!DOCTYPE html><html> <body> <pre><!--code Tag starts here --> <code>#include<stdio.h>int main() { printf("Hello Geeks");}<!--code Tag starts here --> </code> </pre></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <body> <pre><!--code Tag starts here --> <code> class GFG { // Program begins with a call to main() // Print "Hello, World" to the terminal window public static void main(String args[]) { System.out.println("Hello, World"); } }<!--code Tag ends here --> </code> </pre> </body> </html> Output: The program which is written inside the <code> tag has some different font size and font type to the basic heading tag and paragraph tag. Note: <pre> tag is used to display code snippets because it always keeps the text formatting as it.Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Mar, 2022" }, { "code": null, "e": 322, "s": 54, "text": "The <code> tag in HTML is used to define the piece of computer code. During the creation of web pages sometimes there is a need to display computer programming code. It could be done by any basic heading tag of HTML but HTML provides a separated tag which is <code>. " }, { "code": null, "e": 514, "s": 322, "text": "The code tag is a specific type of text which represents computer output. HTML provides many methods for text-formatting but <code> tag is displayed with fixed letter size, font, and spacing." }, { "code": null, "e": 545, "s": 514, "text": "Some points about <code> tag: " }, { "code": null, "e": 613, "s": 545, "text": "It is mainly used to display the code snippet into the web browser." }, { "code": null, "e": 686, "s": 613, "text": "This tag styles its element to match the computer’s default text format." }, { "code": null, "e": 786, "s": 686, "text": "The web browsers by default use a monospace font family for displaying <code< tags element content." }, { "code": null, "e": 795, "s": 786, "text": "Syntax: " }, { "code": null, "e": 822, "s": 795, "text": "<code> Contents... </code>" }, { "code": null, "e": 872, "s": 822, "text": "The below examples illustrates the HTML code Tag." }, { "code": null, "e": 884, "s": 872, "text": "Example 1: " }, { "code": null, "e": 889, "s": 884, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <pre><!--code Tag starts here --> <code>#include<stdio.h>int main() { printf(\"Hello Geeks\");}<!--code Tag starts here --> </code> </pre></body> </html>", "e": 1089, "s": 889, "text": null }, { "code": null, "e": 1097, "s": 1089, "text": "Output:" }, { "code": null, "e": 1109, "s": 1097, "text": "Example 2: " }, { "code": null, "e": 1114, "s": 1109, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <pre><!--code Tag starts here --> <code> class GFG { // Program begins with a call to main() // Print \"Hello, World\" to the terminal window public static void main(String args[]) { System.out.println(\"Hello, World\"); } }<!--code Tag ends here --> </code> </pre> </body> </html>", "e": 1533, "s": 1114, "text": null }, { "code": null, "e": 1679, "s": 1533, "text": "Output: The program which is written inside the <code> tag has some different font size and font type to the basic heading tag and paragraph tag." }, { "code": null, "e": 1799, "s": 1679, "text": "Note: <pre> tag is used to display code snippets because it always keeps the text formatting as it.Supported Browsers: " }, { "code": null, "e": 1813, "s": 1799, "text": "Google Chrome" }, { "code": null, "e": 1831, "s": 1813, "text": "Internet Explorer" }, { "code": null, "e": 1839, "s": 1831, "text": "Firefox" }, { "code": null, "e": 1845, "s": 1839, "text": "Opera" }, { "code": null, "e": 1852, "s": 1845, "text": "Safari" }, { "code": null, "e": 1866, "s": 1852, "text": "shubhamyadav4" }, { "code": null, "e": 1876, "s": 1866, "text": "HTML-Tags" }, { "code": null, "e": 1881, "s": 1876, "text": "HTML" }, { "code": null, "e": 1886, "s": 1881, "text": "HTML" }, { "code": null, "e": 1984, "s": 1886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2032, "s": 1984, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2094, "s": 2032, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2144, "s": 2094, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2168, "s": 2144, "text": "REST API (Introduction)" }, { "code": null, "e": 2221, "s": 2168, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2281, "s": 2221, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2342, "s": 2281, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2392, "s": 2342, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2429, "s": 2392, "text": "Types of CSS (Cascading Style Sheet)" } ]
Nth term of a Custom Fibonacci series
10 Mar, 2022 Given three integers A, B and N. A Custom Fibonacci series is defined as F(x) = F(x – 1) + F(x + 1) where F(1) = A and F(2) = B. Now the task is to find the Nth term of this series.Examples: Input: A = 10, B = 17, N = 3 Output: 7 10, 17, 7, -10, -17, ...Input: A = 50, B = 12, N = 10 Output: -50 Approach: It can be observed that the series will go on like A, B, B – A, -A, -B, A – B, A, B, B – A, ...Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ implementation of the Custom Fibonacci series #include <bits/stdc++.h>using namespace std; // Function to return the nth term// of the required sequenceint nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codeint main(){ int a = 10, b = 17, n = 3; cout << nth_term(a, b, n); return 0;} // Java implementation of the// Custom Fibonacci seriesclass GFG{ // Function to return the nth term// of the required sequencestatic int nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codepublic static void main(String[] args){ int a = 10, b = 17, n = 3; System.out.println(nth_term(a, b, n));}} // This code is contributed by Rajput-Ji # Python 3 implementation of the# Custom Fibonacci series # Function to return the nth term# of the required sequencedef nth_term(a, b, n): z = 0 if (n % 6 == 1): z = a elif (n % 6 == 2): z = b elif (n % 6 == 3): z = b - a elif (n % 6 == 4): z = -a elif (n % 6 == 5): z = -b if (n % 6 == 0): z = -(b - a) return z # Driver codeif __name__ == '__main__': a = 10 b = 17 n = 3 print(nth_term(a, b, n)) # This code is contributed by Surendra_Gangwar // C# implementation of the// Custom Fibonacci seriesusing System; class GFG{ // Function to return the nth term// of the required sequencestatic int nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codestatic public void Main (){ int a = 10, b = 17, n = 3; Console.Write(nth_term(a, b, n));}} // This code is contributed by ajit. <script>// javascript implementation of the// Custom Fibonacci series // Function to return the nth term // of the required sequence function nth_term(a , b , n) { var z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z; } // Driver code var a = 10, b = 17, n = 3; document.write(nth_term(a, b, n)); // This code is contributed by Rajput-Ji</script> 7 Time Complexity: O(1) Auxiliary Space: O(1) Rajput-Ji SURENDRA_GANGWAR jit_t subhammahato348 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Mar, 2022" }, { "code": null, "e": 221, "s": 28, "text": "Given three integers A, B and N. A Custom Fibonacci series is defined as F(x) = F(x – 1) + F(x + 1) where F(1) = A and F(2) = B. Now the task is to find the Nth term of this series.Examples: " }, { "code": null, "e": 328, "s": 221, "text": "Input: A = 10, B = 17, N = 3 Output: 7 10, 17, 7, -10, -17, ...Input: A = 50, B = 12, N = 10 Output: -50 " }, { "code": null, "e": 488, "s": 330, "text": "Approach: It can be observed that the series will go on like A, B, B – A, -A, -B, A – B, A, B, B – A, ...Below is the implementation of the above approach: " }, { "code": null, "e": 492, "s": 488, "text": "C++" }, { "code": null, "e": 497, "s": 492, "text": "Java" }, { "code": null, "e": 506, "s": 497, "text": "Python 3" }, { "code": null, "e": 509, "s": 506, "text": "C#" }, { "code": null, "e": 520, "s": 509, "text": "Javascript" }, { "code": "// C++ implementation of the Custom Fibonacci series #include <bits/stdc++.h>using namespace std; // Function to return the nth term// of the required sequenceint nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codeint main(){ int a = 10, b = 17, n = 3; cout << nth_term(a, b, n); return 0;}", "e": 1075, "s": 520, "text": null }, { "code": "// Java implementation of the// Custom Fibonacci seriesclass GFG{ // Function to return the nth term// of the required sequencestatic int nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codepublic static void main(String[] args){ int a = 10, b = 17, n = 3; System.out.println(nth_term(a, b, n));}} // This code is contributed by Rajput-Ji", "e": 1673, "s": 1075, "text": null }, { "code": "# Python 3 implementation of the# Custom Fibonacci series # Function to return the nth term# of the required sequencedef nth_term(a, b, n): z = 0 if (n % 6 == 1): z = a elif (n % 6 == 2): z = b elif (n % 6 == 3): z = b - a elif (n % 6 == 4): z = -a elif (n % 6 == 5): z = -b if (n % 6 == 0): z = -(b - a) return z # Driver codeif __name__ == '__main__': a = 10 b = 17 n = 3 print(nth_term(a, b, n)) # This code is contributed by Surendra_Gangwar", "e": 2202, "s": 1673, "text": null }, { "code": "// C# implementation of the// Custom Fibonacci seriesusing System; class GFG{ // Function to return the nth term// of the required sequencestatic int nth_term(int a, int b, int n){ int z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z;} // Driver codestatic public void Main (){ int a = 10, b = 17, n = 3; Console.Write(nth_term(a, b, n));}} // This code is contributed by ajit.", "e": 2795, "s": 2202, "text": null }, { "code": "<script>// javascript implementation of the// Custom Fibonacci series // Function to return the nth term // of the required sequence function nth_term(a , b , n) { var z = 0; if (n % 6 == 1) z = a; else if (n % 6 == 2) z = b; else if (n % 6 == 3) z = b - a; else if (n % 6 == 4) z = -a; else if (n % 6 == 5) z = -b; if (n % 6 == 0) z = -(b - a); return z; } // Driver code var a = 10, b = 17, n = 3; document.write(nth_term(a, b, n)); // This code is contributed by Rajput-Ji</script>", "e": 3427, "s": 2795, "text": null }, { "code": null, "e": 3429, "s": 3427, "text": "7" }, { "code": null, "e": 3453, "s": 3431, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3475, "s": 3453, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3485, "s": 3475, "text": "Rajput-Ji" }, { "code": null, "e": 3502, "s": 3485, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 3508, "s": 3502, "text": "jit_t" }, { "code": null, "e": 3524, "s": 3508, "text": "subhammahato348" }, { "code": null, "e": 3531, "s": 3524, "text": "series" }, { "code": null, "e": 3544, "s": 3531, "text": "Mathematical" }, { "code": null, "e": 3557, "s": 3544, "text": "Mathematical" }, { "code": null, "e": 3564, "s": 3557, "text": "series" } ]
How to Install and Set Up SAS University Edition
01 Apr, 2019 Statistical Analysis System (SAS) , one of the most powerful data analytical software in the market which has recently released a university edition of its software. Despite being proprietary software, the developers have decided to do so, to help the students learn the basics of SAS programming. This edition offers the user all the basic functionalities of the industry level SAS software suite and hence it is a good place to start your journey into SAS programming from here. This walk-through is up-to-date with the recent changes that SAS has made to the setup process, which also includes the complimentary installation of JupyterLab. The SAS University Edition can be downloaded from here. This will direct you to the page shown below. Here, you can select the appropriate Operating System and move ahead with the process. The first step involves downloading the Oracle VM Virtual Box by click here, which will be used to run the SAS Studio. Download the software for your preferred OS and install the Virtual Box. On successful completion of the installation process, it will show like below: Just like any other application, SAS Studio has to assign a working directory. All files (may it be SAS programs or data sets) will be uploaded/downloaded into this directory. Choose your desired directory, and create a new folder named as SASUniversityEdition (with no spaces). Inside this newly created folder, create another folder called myfolders (again, with no spaces). These folders will now act as SAS Studio’s primary workspace. The next step involves downloading the SAS University Edition vApp, which will later be loaded into the Virtual Machine to create a local instance of the SAS Studio. However, to download the file, a SAS profile is needed. So, quick signup into the website will allow you to continue with the download. Clicking on the download button will redirect you to this web page, where you’ll need to either sign in or sign up. Once you sign in and agree to the terms and conditions, you’ll be able to download the SAS vApp file. The download might take a while since it’s a big file ~1.7GB. Step 1: Launch the Oracle VM virtual Box. Step 2: Import the SAS Studio OVA file from the Downloads folder. On completion of step 2, your Virtual Box should look like this. Step 3: Select the SAS University Edition vApp, and click on the Machine menu and select the settings part of it. Step 4: Select the shared folders option and then click the Add Folder icon (+). Step 5: Choose the “Other” option under the Folder Path input, and select the myfolders present in the SASUniversityEdition folder. Make sure the Read-Only option is not selected else, SAS Studio won’t be able to save files to this directory. Step 6: Click ok to finish the work space set up process. Step 7: Select the SAS University Edition app, and click the Machine->Start option. If you have successfully completed all the steps till now, you will end up with this screen. Step 8: Launch your browser, and go to the URL http://localhost:10080 . You will be greeted by this screen. You have also received a complimentary installation of JupyterLabs!. Now you can launch SAS Studio and get started on programming! To close the SAS Studio, all you need to do is turn off the Virtual Machine. GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 671, "s": 28, "text": "Statistical Analysis System (SAS) , one of the most powerful data analytical software in the market which has recently released a university edition of its software. Despite being proprietary software, the developers have decided to do so, to help the students learn the basics of SAS programming. This edition offers the user all the basic functionalities of the industry level SAS software suite and hence it is a good place to start your journey into SAS programming from here. This walk-through is up-to-date with the recent changes that SAS has made to the setup process, which also includes the complimentary installation of JupyterLab." }, { "code": null, "e": 773, "s": 671, "text": "The SAS University Edition can be downloaded from here. This will direct you to the page shown below." }, { "code": null, "e": 860, "s": 773, "text": "Here, you can select the appropriate Operating System and move ahead with the process." }, { "code": null, "e": 1052, "s": 860, "text": "The first step involves downloading the Oracle VM Virtual Box by click here, which will be used to run the SAS Studio. Download the software for your preferred OS and install the Virtual Box." }, { "code": null, "e": 1131, "s": 1052, "text": "On successful completion of the installation process, it will show like below:" }, { "code": null, "e": 1570, "s": 1131, "text": "Just like any other application, SAS Studio has to assign a working directory. All files (may it be SAS programs or data sets) will be uploaded/downloaded into this directory. Choose your desired directory, and create a new folder named as SASUniversityEdition (with no spaces). Inside this newly created folder, create another folder called myfolders (again, with no spaces). These folders will now act as SAS Studio’s primary workspace." }, { "code": null, "e": 1872, "s": 1570, "text": "The next step involves downloading the SAS University Edition vApp, which will later be loaded into the Virtual Machine to create a local instance of the SAS Studio. However, to download the file, a SAS profile is needed. So, quick signup into the website will allow you to continue with the download." }, { "code": null, "e": 1988, "s": 1872, "text": "Clicking on the download button will redirect you to this web page, where you’ll need to either sign in or sign up." }, { "code": null, "e": 2152, "s": 1988, "text": "Once you sign in and agree to the terms and conditions, you’ll be able to download the SAS vApp file. The download might take a while since it’s a big file ~1.7GB." }, { "code": null, "e": 2194, "s": 2152, "text": "Step 1: Launch the Oracle VM virtual Box." }, { "code": null, "e": 2260, "s": 2194, "text": "Step 2: Import the SAS Studio OVA file from the Downloads folder." }, { "code": null, "e": 2325, "s": 2260, "text": "On completion of step 2, your Virtual Box should look like this." }, { "code": null, "e": 2439, "s": 2325, "text": "Step 3: Select the SAS University Edition vApp, and click on the Machine menu and select the settings part of it." }, { "code": null, "e": 2520, "s": 2439, "text": "Step 4: Select the shared folders option and then click the Add Folder icon (+)." }, { "code": null, "e": 2763, "s": 2520, "text": "Step 5: Choose the “Other” option under the Folder Path input, and select the myfolders present in the SASUniversityEdition folder. Make sure the Read-Only option is not selected else, SAS Studio won’t be able to save files to this directory." }, { "code": null, "e": 2821, "s": 2763, "text": "Step 6: Click ok to finish the work space set up process." }, { "code": null, "e": 2905, "s": 2821, "text": "Step 7: Select the SAS University Edition app, and click the Machine->Start option." }, { "code": null, "e": 2998, "s": 2905, "text": "If you have successfully completed all the steps till now, you will end up with this screen." }, { "code": null, "e": 3106, "s": 2998, "text": "Step 8: Launch your browser, and go to the URL http://localhost:10080 . You will be greeted by this screen." }, { "code": null, "e": 3237, "s": 3106, "text": "You have also received a complimentary installation of JupyterLabs!. Now you can launch SAS Studio and get started on programming!" }, { "code": null, "e": 3314, "s": 3237, "text": "To close the SAS Studio, all you need to do is turn off the Virtual Machine." }, { "code": null, "e": 3320, "s": 3314, "text": "GBlog" } ]
How to open a website in iOS's web browser from my application?
In this post we will learn how to open website in iOS browser. We will open Facebook in iOS browser. Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “OpenBrowser” Step 2 − Open Main.storyboard and add a button as shown below. I have given the button title as “Open Facebook” Step 3 − Attach one @IBAction function in ViewController, name it openBrowser Step 4 − In openBrowserFunction write the code to open URL like shown below @IBAction func openBrowsere(_ sender: Any) { let url = URL(string: "https://www.facebook.com")! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } In the above code as you can see we are using canOpenURL and openURL APIs. canOpenURL checks whether the given URL can be opened by the app. Then openURL actually opens the given URL with appropriate app. Step 5 − Run the app. Click on open Facebook button. You should see the browser opening the Facebook page.
[ { "code": null, "e": 1125, "s": 1062, "text": "In this post we will learn how to open website in iOS browser." }, { "code": null, "e": 1163, "s": 1125, "text": "We will open Facebook in iOS browser." }, { "code": null, "e": 1253, "s": 1163, "text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “OpenBrowser”" }, { "code": null, "e": 1365, "s": 1253, "text": "Step 2 − Open Main.storyboard and add a button as shown below. I have given the button title as “Open Facebook”" }, { "code": null, "e": 1443, "s": 1365, "text": "Step 3 − Attach one @IBAction function in ViewController, name it openBrowser" }, { "code": null, "e": 1519, "s": 1443, "text": "Step 4 − In openBrowserFunction write the code to open URL like shown below" }, { "code": null, "e": 1745, "s": 1519, "text": "@IBAction func openBrowsere(_ sender: Any) {\n let url = URL(string: \"https://www.facebook.com\")!\n if UIApplication.shared.canOpenURL(url) {\n UIApplication.shared.open(url, options: [:], completionHandler: nil)\n }\n}" }, { "code": null, "e": 1820, "s": 1745, "text": "In the above code as you can see we are using canOpenURL and openURL APIs." }, { "code": null, "e": 1950, "s": 1820, "text": "canOpenURL checks whether the given URL can be opened by the app. Then openURL actually opens the given URL with appropriate app." }, { "code": null, "e": 2057, "s": 1950, "text": "Step 5 − Run the app. Click on open Facebook button. You should see the browser opening the Facebook page." } ]
Difference between Maskable and Non Maskable Interrupt - GeeksforGeeks
14 May, 2020 An interrupt is an event caused by a component other than the CPU. It indicates the CPU of an external event that requires immediate attention. Interrupts occur asynchronously. Maskable and non-maskable interrupts are two types of interrupts. 1. Maskable Interrupt :An Interrupt that can be disabled or ignored by the instructions of CPU are called as Maskable Interrupt.The interrupts are either edge-triggered or level-triggered or level-triggered. Eg: RST6.5,RST7.5,RST5.5 of 8085 2. Non-Maskable Interrupt :An interrupt that cannot be disabled or ignored by the instructions of CPU are called as Non-Maskable Interrupt.A Non-maskable interrupt is often used when response time is critical or when an interrupt should never be disable during normal system operation. Such uses include reporting non-recoverable hardware errors, system debugging and profiling and handling of species cases like system resets. Eg: Trap of 8085 Difference between maskable and nonmaskable interrupt : Computer Organization & Architecture Difference Between GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Computer Organization | RISC and CISC Memory Hierarchy Design and its Characteristics Direct Access Media (DMA) Controller in Computer Architecture 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 Differences between IPv4 and IPv6
[ { "code": null, "e": 25861, "s": 25833, "text": "\n14 May, 2020" }, { "code": null, "e": 26104, "s": 25861, "text": "An interrupt is an event caused by a component other than the CPU. It indicates the CPU of an external event that requires immediate attention. Interrupts occur asynchronously. Maskable and non-maskable interrupts are two types of interrupts." }, { "code": null, "e": 26312, "s": 26104, "text": "1. Maskable Interrupt :An Interrupt that can be disabled or ignored by the instructions of CPU are called as Maskable Interrupt.The interrupts are either edge-triggered or level-triggered or level-triggered." }, { "code": null, "e": 26347, "s": 26312, "text": "Eg: \nRST6.5,RST7.5,RST5.5 of 8085 " }, { "code": null, "e": 26775, "s": 26347, "text": "2. Non-Maskable Interrupt :An interrupt that cannot be disabled or ignored by the instructions of CPU are called as Non-Maskable Interrupt.A Non-maskable interrupt is often used when response time is critical or when an interrupt should never be disable during normal system operation. Such uses include reporting non-recoverable hardware errors, system debugging and profiling and handling of species cases like system resets." }, { "code": null, "e": 26793, "s": 26775, "text": "Eg:\nTrap of 8085 " }, { "code": null, "e": 26849, "s": 26793, "text": "Difference between maskable and nonmaskable interrupt :" }, { "code": null, "e": 26886, "s": 26849, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26905, "s": 26886, "text": "Difference Between" }, { "code": null, "e": 26913, "s": 26905, "text": "GATE CS" }, { "code": null, "e": 27011, "s": 26913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27060, "s": 27011, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27155, "s": 27060, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27193, "s": 27155, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 27241, "s": 27193, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27303, "s": 27241, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 27334, "s": 27303, "text": "Difference between BFS and DFS" }, { "code": null, "e": 27374, "s": 27334, "text": "Class method vs Static method in Python" }, { "code": null, "e": 27406, "s": 27374, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27467, "s": 27406, "text": "Difference between var, let and const keywords in JavaScript" } ]
Count subsequences which contains both the maximum and minimum array element - GeeksforGeeks
07 May, 2021 Given an array arr[] consisting of N integers, the task is to find the number of subsequences which contain the maximum as well as the minimum element present in the given array. Example : Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: There are 4 subsequence {1, 4}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3, 4} which contains the maximum array element(= 4) and the minimum array element(= 1). Input: arr[] = {4, 4, 4, 4}Output: 15 Naive Approach: The simplest approach is to first, traverse the array and find the maximum and minimum of the array and then generate all possible subsequences of the given array. For each subsequence, check if it contains both the maximum and the minimum array element. For all such subsequences, increase the count by 1. Finally, print the count of such subsequences. Time Complexity: O(2N)Auxiliary Space: O(N) Efficient Approach: Follow the steps below to optimize the above approach: Find the count of occurrences of the maximum element and the minimum element. Let i and j be the respective count. Check if the maximum and the minimum element are the same or not. If found to be true, then the possible subsequences are all non-empty subsequences of the array. Otherwise, for satisfying the condition of the subsequence, it should contain at least 1 element from i and at least 1 element from j. Therefore, the required count of subsequences is given by the following equation: (pow(2, i) -1 ) * ( pow(2, j) -1 ) * pow(2, n-i-j) 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; int count(int arr[], int n, int value); // Function to calculate the// count of subsequencesdouble countSubSequence(int arr[], int n){ // Find the maximum // from the array int maximum = *max_element(arr, arr + n); // Find the minimum // from the array int minimum = *min_element(arr, arr + n); // If array contains only // one distinct element if (maximum == minimum) return pow(2, n) - 1; // Find the count of maximum int i = count(arr, n, maximum); // Find the count of minimum int j = count(arr, n, minimum); // Finding the result // with given condition double res = (pow(2, i) - 1) * (pow(2, j) - 1) * pow(2, n - i - j); return res;} int count(int arr[], int n, int value){ int sum = 0; for(int i = 0; i < n; i++) if (arr[i] == value) sum++; return sum;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << countSubSequence(arr, n) << endl;} // This code is contributed by rutvik_56 // Java program for the above approachimport java.util.Arrays; class GFG{ // Function to calculate the// count of subsequencesstatic double countSubSequence(int[] arr, int n){ // Find the maximum // from the array int maximum = Arrays.stream(arr).max().getAsInt(); // Find the minimum // from the array int minimum = Arrays.stream(arr).min().getAsInt(); // If array contains only // one distinct element if (maximum == minimum) return Math.pow(2, n) - 1; // Find the count of maximum int i = count(arr, maximum); // Find the count of minimum int j = count(arr, minimum); // Finding the result // with given condition double res = (Math.pow(2, i) - 1) * (Math.pow(2, j) - 1) * Math.pow(2, n - i - j); return res;} static int count(int[] arr, int value){ int sum = 0; for(int i = 0; i < arr.length; i++) if (arr[i] == value) sum++; return sum;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4 }; int n = arr.length; // Function call System.out.println(countSubSequence(arr, n));}} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Function to calculate the# count of subsequencesdef countSubSequence(arr, n): # Find the maximum # from the array maximum = max(arr) # Find the minimum # from the array minimum = min(arr) # If array contains only # one distinct element if maximum == minimum: return pow(2, n)-1 # Find the count of maximum i = arr.count(maximum) # Find the count of minimum j = arr.count(minimum) # Finding the result # with given condition res = (pow(2, i) - 1) * (pow(2, j) - 1) * pow(2, n-i-j) return res # Driver Codearr = [1, 2, 3, 4]n = len(arr) # Function callprint(countSubSequence(arr, n)) // C# program for// the above approachusing System;using System.Linq;class GFG{ // Function to calculate the// count of subsequencesstatic double countSubSequence(int[] arr, int n){ // Find the maximum // from the array int maximum = arr.Max(); // Find the minimum // from the array int minimum = arr.Min(); // If array contains only // one distinct element if (maximum == minimum) return Math.Pow(2, n) - 1; // Find the count of maximum int i = count(arr, maximum); // Find the count of minimum int j = count(arr, minimum); // Finding the result // with given condition double res = (Math.Pow(2, i) - 1) * (Math.Pow(2, j) - 1) * Math.Pow(2, n - i - j); return res;} static int count(int[] arr, int value){ int sum = 0; for(int i = 0; i < arr.Length; i++) if (arr[i] == value) sum++; return sum;} // Driver Codepublic static void Main(String[] args){ int[] arr = {1, 2, 3, 4}; int n = arr.Length; // Function call Console.WriteLine(countSubSequence(arr, n));}} // This code is contributed by shikhasingrajput <script> // JavaScript program for the above approach // Function to calculate the// count of subsequencesfunction countSubSequence(arr, n){ // Find the maximum // from the array let maximum = Math.max(...arr); // Find the minimum // from the array let minimum = Math.min(...arr); // If array contains only // one distinct element if (maximum == minimum) return Math.pow(2, n) - 1; // Find the count of maximum let i = count(arr, maximum); // Find the count of minimum let j = count(arr, minimum); // Finding the result // with given condition let res = (Math.pow(2, i) - 1) * (Math.pow(2, j) - 1) * Math.pow(2, n - i - j); return res;} function count(arr, value){ let sum = 0; for(let i = 0; i < arr.length; i++) if (arr[i] == value) sum++; return sum;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let n = arr.length; // Function call document.write(countSubSequence(arr, n)); // This code is contributed by souravghosh0416.</script> 4 Time Complexity: O(N)Auxiliary Space: O(1) amit143katiyar shikhasingrajput rutvik_56 souravghosh0416 frequency-counting subsequence Arrays Mathematical Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26043, "s": 26015, "text": "\n07 May, 2021" }, { "code": null, "e": 26222, "s": 26043, "text": "Given an array arr[] consisting of N integers, the task is to find the number of subsequences which contain the maximum as well as the minimum element present in the given array." }, { "code": null, "e": 26232, "s": 26222, "text": "Example :" }, { "code": null, "e": 26432, "s": 26232, "text": "Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: There are 4 subsequence {1, 4}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3, 4} which contains the maximum array element(= 4) and the minimum array element(= 1)." }, { "code": null, "e": 26470, "s": 26432, "text": "Input: arr[] = {4, 4, 4, 4}Output: 15" }, { "code": null, "e": 26840, "s": 26470, "text": "Naive Approach: The simplest approach is to first, traverse the array and find the maximum and minimum of the array and then generate all possible subsequences of the given array. For each subsequence, check if it contains both the maximum and the minimum array element. For all such subsequences, increase the count by 1. Finally, print the count of such subsequences." }, { "code": null, "e": 26884, "s": 26840, "text": "Time Complexity: O(2N)Auxiliary Space: O(N)" }, { "code": null, "e": 26960, "s": 26884, "text": "Efficient Approach: Follow the steps below to optimize the above approach:" }, { "code": null, "e": 27075, "s": 26960, "text": "Find the count of occurrences of the maximum element and the minimum element. Let i and j be the respective count." }, { "code": null, "e": 27238, "s": 27075, "text": "Check if the maximum and the minimum element are the same or not. If found to be true, then the possible subsequences are all non-empty subsequences of the array." }, { "code": null, "e": 27455, "s": 27238, "text": "Otherwise, for satisfying the condition of the subsequence, it should contain at least 1 element from i and at least 1 element from j. Therefore, the required count of subsequences is given by the following equation:" }, { "code": null, "e": 27508, "s": 27455, "text": " (pow(2, i) -1 ) * ( pow(2, j) -1 ) * pow(2, n-i-j)" }, { "code": null, "e": 27559, "s": 27508, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27563, "s": 27559, "text": "C++" }, { "code": null, "e": 27568, "s": 27563, "text": "Java" }, { "code": null, "e": 27576, "s": 27568, "text": "Python3" }, { "code": null, "e": 27579, "s": 27576, "text": "C#" }, { "code": null, "e": 27590, "s": 27579, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; int count(int arr[], int n, int value); // Function to calculate the// count of subsequencesdouble countSubSequence(int arr[], int n){ // Find the maximum // from the array int maximum = *max_element(arr, arr + n); // Find the minimum // from the array int minimum = *min_element(arr, arr + n); // If array contains only // one distinct element if (maximum == minimum) return pow(2, n) - 1; // Find the count of maximum int i = count(arr, n, maximum); // Find the count of minimum int j = count(arr, n, minimum); // Finding the result // with given condition double res = (pow(2, i) - 1) * (pow(2, j) - 1) * pow(2, n - i - j); return res;} int count(int arr[], int n, int value){ int sum = 0; for(int i = 0; i < n; i++) if (arr[i] == value) sum++; return sum;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << countSubSequence(arr, n) << endl;} // This code is contributed by rutvik_56", "e": 28794, "s": 27590, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to calculate the// count of subsequencesstatic double countSubSequence(int[] arr, int n){ // Find the maximum // from the array int maximum = Arrays.stream(arr).max().getAsInt(); // Find the minimum // from the array int minimum = Arrays.stream(arr).min().getAsInt(); // If array contains only // one distinct element if (maximum == minimum) return Math.pow(2, n) - 1; // Find the count of maximum int i = count(arr, maximum); // Find the count of minimum int j = count(arr, minimum); // Finding the result // with given condition double res = (Math.pow(2, i) - 1) * (Math.pow(2, j) - 1) * Math.pow(2, n - i - j); return res;} static int count(int[] arr, int value){ int sum = 0; for(int i = 0; i < arr.length; i++) if (arr[i] == value) sum++; return sum;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4 }; int n = arr.length; // Function call System.out.println(countSubSequence(arr, n));}} // This code is contributed by Amit Katiyar", "e": 30012, "s": 28794, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate the# count of subsequencesdef countSubSequence(arr, n): # Find the maximum # from the array maximum = max(arr) # Find the minimum # from the array minimum = min(arr) # If array contains only # one distinct element if maximum == minimum: return pow(2, n)-1 # Find the count of maximum i = arr.count(maximum) # Find the count of minimum j = arr.count(minimum) # Finding the result # with given condition res = (pow(2, i) - 1) * (pow(2, j) - 1) * pow(2, n-i-j) return res # Driver Codearr = [1, 2, 3, 4]n = len(arr) # Function callprint(countSubSequence(arr, n))", "e": 30703, "s": 30012, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Linq;class GFG{ // Function to calculate the// count of subsequencesstatic double countSubSequence(int[] arr, int n){ // Find the maximum // from the array int maximum = arr.Max(); // Find the minimum // from the array int minimum = arr.Min(); // If array contains only // one distinct element if (maximum == minimum) return Math.Pow(2, n) - 1; // Find the count of maximum int i = count(arr, maximum); // Find the count of minimum int j = count(arr, minimum); // Finding the result // with given condition double res = (Math.Pow(2, i) - 1) * (Math.Pow(2, j) - 1) * Math.Pow(2, n - i - j); return res;} static int count(int[] arr, int value){ int sum = 0; for(int i = 0; i < arr.Length; i++) if (arr[i] == value) sum++; return sum;} // Driver Codepublic static void Main(String[] args){ int[] arr = {1, 2, 3, 4}; int n = arr.Length; // Function call Console.WriteLine(countSubSequence(arr, n));}} // This code is contributed by shikhasingrajput", "e": 31822, "s": 30703, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to calculate the// count of subsequencesfunction countSubSequence(arr, n){ // Find the maximum // from the array let maximum = Math.max(...arr); // Find the minimum // from the array let minimum = Math.min(...arr); // If array contains only // one distinct element if (maximum == minimum) return Math.pow(2, n) - 1; // Find the count of maximum let i = count(arr, maximum); // Find the count of minimum let j = count(arr, minimum); // Finding the result // with given condition let res = (Math.pow(2, i) - 1) * (Math.pow(2, j) - 1) * Math.pow(2, n - i - j); return res;} function count(arr, value){ let sum = 0; for(let i = 0; i < arr.length; i++) if (arr[i] == value) sum++; return sum;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let n = arr.length; // Function call document.write(countSubSequence(arr, n)); // This code is contributed by souravghosh0416.</script>", "e": 32929, "s": 31822, "text": null }, { "code": null, "e": 32931, "s": 32929, "text": "4" }, { "code": null, "e": 32974, "s": 32931, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 32989, "s": 32974, "text": "amit143katiyar" }, { "code": null, "e": 33006, "s": 32989, "text": "shikhasingrajput" }, { "code": null, "e": 33016, "s": 33006, "text": "rutvik_56" }, { "code": null, "e": 33032, "s": 33016, "text": "souravghosh0416" }, { "code": null, "e": 33051, "s": 33032, "text": "frequency-counting" }, { "code": null, "e": 33063, "s": 33051, "text": "subsequence" }, { "code": null, "e": 33070, "s": 33063, "text": "Arrays" }, { "code": null, "e": 33083, "s": 33070, "text": "Mathematical" }, { "code": null, "e": 33093, "s": 33083, "text": "Searching" }, { "code": null, "e": 33100, "s": 33093, "text": "Arrays" }, { "code": null, "e": 33110, "s": 33100, "text": "Searching" }, { "code": null, "e": 33123, "s": 33110, "text": "Mathematical" }, { "code": null, "e": 33221, "s": 33123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33289, "s": 33221, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33312, "s": 33289, "text": "Introduction to Arrays" }, { "code": null, "e": 33344, "s": 33312, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33358, "s": 33344, "text": "Linear Search" }, { "code": null, "e": 33379, "s": 33358, "text": "Linked List vs Array" }, { "code": null, "e": 33409, "s": 33379, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33469, "s": 33409, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33484, "s": 33469, "text": "C++ Data Types" }, { "code": null, "e": 33527, "s": 33484, "text": "Set in C++ Standard Template Library (STL)" } ]
Groovy - Generics
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types. The collections classes such as the List class can be generalized so that only collections of that type are accepted in the application. An example of the generalized ArrayList is shown below. What the following statement does is that it only accepts list items which are of the type string − List<String> list = new ArrayList<String>(); In the following code example, we are doing the following − Creating a Generalized ArrayList collection which will hold only Strings. Add 3 strings to the list. For each item in the list, printing the value of the strings. class Example { static void main(String[] args) { // Creating a generic List collection List<String> list = new ArrayList<String>(); list.add("First String"); list.add("Second String"); list.add("Third String"); for(String str : list) { println(str); } } } The output of the above program would be − First String Second String Third String The entire class can also be generalized. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomplish this. In the following program, we are carrying out the following steps − We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T> We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T> The generic class has simple getter and setter methods to work with the member variable defined in the class. The generic class has simple getter and setter methods to work with the member variable defined in the class. In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String. In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String. class Example { static void main(String[] args) { // Creating a generic List collection ListType<String> lststr = new ListType<>(); lststr.set("First String"); println(lststr.get()); ListType<Integer> lstint = new ListType<>(); lstint.set(1); println(lstint.get()); } } public class ListType<T> { private T localt; public T get() { return this.localt; } public void set(T plocal) { this.localt = plocal; } } The output of the above program would be − First String 1 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2238, "text": "Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types." }, { "code": null, "e": 2916, "s": 2623, "text": "The collections classes such as the List class can be generalized so that only collections of that type are accepted in the application. An example of the generalized ArrayList is shown below. What the following statement does is that it only accepts list items which are of the type string −" }, { "code": null, "e": 2961, "s": 2916, "text": "List<String> list = new ArrayList<String>();" }, { "code": null, "e": 3021, "s": 2961, "text": "In the following code example, we are doing the following −" }, { "code": null, "e": 3095, "s": 3021, "text": "Creating a Generalized ArrayList collection which will hold only Strings." }, { "code": null, "e": 3122, "s": 3095, "text": "Add 3 strings to the list." }, { "code": null, "e": 3184, "s": 3122, "text": "For each item in the list, printing the value of the strings." }, { "code": null, "e": 3502, "s": 3184, "text": "class Example {\n static void main(String[] args) {\n // Creating a generic List collection\n List<String> list = new ArrayList<String>();\n list.add(\"First String\");\n list.add(\"Second String\");\n list.add(\"Third String\");\n\t\t\n for(String str : list) {\n println(str);\n }\n } \n}" }, { "code": null, "e": 3545, "s": 3502, "text": "The output of the above program would be −" }, { "code": null, "e": 3588, "s": 3545, "text": "First String \nSecond String \nThird String\n" }, { "code": null, "e": 3786, "s": 3588, "text": "The entire class can also be generalized. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomplish this." }, { "code": null, "e": 3854, "s": 3786, "text": "In the following program, we are carrying out the following steps −" }, { "code": null, "e": 4167, "s": 3854, "text": "We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T>" }, { "code": null, "e": 4480, "s": 4167, "text": "We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T>" }, { "code": null, "e": 4590, "s": 4480, "text": "The generic class has simple getter and setter methods to work with the member variable defined in the class." }, { "code": null, "e": 4700, "s": 4590, "text": "The generic class has simple getter and setter methods to work with the member variable defined in the class." }, { "code": null, "e": 4890, "s": 4700, "text": "In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String." }, { "code": null, "e": 5080, "s": 4890, "text": "In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String." }, { "code": null, "e": 5575, "s": 5080, "text": "class Example {\n static void main(String[] args) {\n // Creating a generic List collection \n ListType<String> lststr = new ListType<>();\n lststr.set(\"First String\");\n println(lststr.get()); \n\t\t\n ListType<Integer> lstint = new ListType<>();\n lstint.set(1);\n println(lstint.get());\n }\n} \n\npublic class ListType<T> {\n private T localt;\n\t\n public T get() {\n return this.localt;\n }\n\t\n public void set(T plocal) {\n this.localt = plocal;\n } \n}" }, { "code": null, "e": 5618, "s": 5575, "text": "The output of the above program would be −" }, { "code": null, "e": 5635, "s": 5618, "text": "First String \n1\n" }, { "code": null, "e": 5668, "s": 5635, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 5686, "s": 5668, "text": " Krishna Sakinala" }, { "code": null, "e": 5721, "s": 5686, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5739, "s": 5721, "text": " Packt Publishing" }, { "code": null, "e": 5746, "s": 5739, "text": " Print" }, { "code": null, "e": 5757, "s": 5746, "text": " Add Notes" } ]
Bootstrap Panels
A panel in bootstrap is a bordered box with some padding around its content: Panels are created with the .panel class, and content inside the panel has a .panel-body class: The .panel-default class is used to style the color of the panel. See the last example on this page for more contextual classes. The .panel-heading class adds a heading to the panel: The .panel-footer class adds a footer to the panel: To group many panels together, wrap a <div> with class .panel-group around them. The .panel-group class clears the bottom-margin of each panel: To color the panel, use contextual classes (.panel-default, .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger): Create a basic (default) Bootstrap Panel with the words: "Hello World". <div class=""> <div class="">Hello World</div> </div> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 77, "s": 0, "text": "A panel in bootstrap is a bordered box with some padding around its content:" }, { "code": null, "e": 174, "s": 77, "text": "Panels are created with the .panel class, and content inside the panel has a \n.panel-body class:" }, { "code": null, "e": 304, "s": 174, "text": "The .panel-default class is used to style the color of the \npanel. See the last example on this page for more contextual classes." }, { "code": null, "e": 358, "s": 304, "text": "The .panel-heading class adds a heading to the panel:" }, { "code": null, "e": 410, "s": 358, "text": "The .panel-footer class adds a footer to the panel:" }, { "code": null, "e": 492, "s": 410, "text": "To group many panels together, wrap a <div> with class \n.panel-group around them." }, { "code": null, "e": 555, "s": 492, "text": "The .panel-group class clears the bottom-margin of each panel:" }, { "code": null, "e": 695, "s": 555, "text": "To color the panel, use contextual classes (.panel-default, .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger):" }, { "code": null, "e": 767, "s": 695, "text": "Create a basic (default) Bootstrap Panel with the words: \"Hello World\"." }, { "code": null, "e": 824, "s": 767, "text": "<div class=\"\">\n <div class=\"\">Hello World</div>\n</div>\n" }, { "code": null, "e": 843, "s": 824, "text": "Start the Exercise" }, { "code": null, "e": 876, "s": 843, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 918, "s": 876, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1025, "s": 918, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1044, "s": 1025, "text": "[email protected]" } ]
Find most significant set bit of a number in C++
Here we will see if a number is given, then how to find the value of Most Significant Bit value, that is set. The value is power of 2. So if the number is 10, MSB value will be 8. We have to find the position of MSB, then find the value of the number with a set-bit at kth position. #include<iostream> #include<cmath> using namespace std; int msbBitValue(int n) { int k = (int)(log2(n)); return (int)(pow(2, k)); } int main() { int n = 150; cout << "MSB bit value is: "<< msbBitValue(n); } MSB bit value is: 128
[ { "code": null, "e": 1242, "s": 1062, "text": "Here we will see if a number is given, then how to find the value of Most Significant Bit value, that is set. The value is power of 2. So if the number is 10, MSB value will be 8." }, { "code": null, "e": 1345, "s": 1242, "text": "We have to find the position of MSB, then find the value of the number with a set-bit at kth position." }, { "code": null, "e": 1564, "s": 1345, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\nint msbBitValue(int n) {\n int k = (int)(log2(n));\n return (int)(pow(2, k));\n}\nint main() {\n int n = 150;\n cout << \"MSB bit value is: \"<< msbBitValue(n);\n}" }, { "code": null, "e": 1586, "s": 1564, "text": "MSB bit value is: 128" } ]
Python program for most frequent word in Strings List
When it is required to find the most frequent word in a list of strings, the list is iterated over and the ‘max’ method is used to get the count of the highest string. Below is a demonstration of the same from collections import defaultdict my_list = ["python is best for coders", "python is fun", "python is easy to learn"] print("The list is :") print(my_list) my_temp = defaultdict(int) for sub in my_list: for word in sub.split(): my_temp[word] += 1 result = max(my_temp, key=my_temp.get) print("The word that has the maximum frequency :") print(result) The list is : ['python is best for coders', 'python is fun', 'python is easy to learn'] The word that has the maximum frequency : python The required packages are imported into the environment. The required packages are imported into the environment. A list of strings is defined and is displayed on the console. A list of strings is defined and is displayed on the console. A dictionary of integers is created and assigned to a variable. A dictionary of integers is created and assigned to a variable. The list of strings is iterated over and split based on spaces. The list of strings is iterated over and split based on spaces. The count of every word is determined. The count of every word is determined. The maximum of these values is determined using the ‘max’ method. The maximum of these values is determined using the ‘max’ method. This is assigned to a variable. This is assigned to a variable. This is displayed as output on the console. This is displayed as output on the console.
[ { "code": null, "e": 1230, "s": 1062, "text": "When it is required to find the most frequent word in a list of strings, the list is iterated over and the ‘max’ method is used to get the count of the highest string." }, { "code": null, "e": 1267, "s": 1230, "text": "Below is a demonstration of the same" }, { "code": null, "e": 1634, "s": 1267, "text": "from collections import defaultdict\nmy_list = [\"python is best for coders\", \"python is fun\", \"python is easy to learn\"]\n\nprint(\"The list is :\")\nprint(my_list)\n\nmy_temp = defaultdict(int)\n\nfor sub in my_list:\n for word in sub.split():\n my_temp[word] += 1\n\nresult = max(my_temp, key=my_temp.get)\n\nprint(\"The word that has the maximum frequency :\")\nprint(result)" }, { "code": null, "e": 1771, "s": 1634, "text": "The list is :\n['python is best for coders', 'python is fun', 'python is easy to learn']\nThe word that has the maximum frequency :\npython" }, { "code": null, "e": 1828, "s": 1771, "text": "The required packages are imported into the environment." }, { "code": null, "e": 1885, "s": 1828, "text": "The required packages are imported into the environment." }, { "code": null, "e": 1947, "s": 1885, "text": "A list of strings is defined and is displayed on the console." }, { "code": null, "e": 2009, "s": 1947, "text": "A list of strings is defined and is displayed on the console." }, { "code": null, "e": 2073, "s": 2009, "text": "A dictionary of integers is created and assigned to a variable." }, { "code": null, "e": 2137, "s": 2073, "text": "A dictionary of integers is created and assigned to a variable." }, { "code": null, "e": 2201, "s": 2137, "text": "The list of strings is iterated over and split based on spaces." }, { "code": null, "e": 2265, "s": 2201, "text": "The list of strings is iterated over and split based on spaces." }, { "code": null, "e": 2304, "s": 2265, "text": "The count of every word is determined." }, { "code": null, "e": 2343, "s": 2304, "text": "The count of every word is determined." }, { "code": null, "e": 2409, "s": 2343, "text": "The maximum of these values is determined using the ‘max’ method." }, { "code": null, "e": 2475, "s": 2409, "text": "The maximum of these values is determined using the ‘max’ method." }, { "code": null, "e": 2507, "s": 2475, "text": "This is assigned to a variable." }, { "code": null, "e": 2539, "s": 2507, "text": "This is assigned to a variable." }, { "code": null, "e": 2583, "s": 2539, "text": "This is displayed as output on the console." }, { "code": null, "e": 2627, "s": 2583, "text": "This is displayed as output on the console." } ]
Different types of Object States in Hibernate - 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 Object states in Hibernate play a vital role in the execution of code in an application. Hibernate has provided three different states for an object. These three states are also called as hibernate’s life cycle states of an object. The three states defined by hibernate are: Transient State Persistent State Detached State An object that is created for the first time using the new() operator, then it is under the state of Transient. As it is a newly created object, it doesn’t have any connection with the Hibernate Session. This object becomes persistent when it is mapped with a database or an identifier value. It means, when we save an object, initially the object being added to the cache. This state is considered to be a persistent state. A Transient object can be destroyed automatically by the garbage collector if any active session object is not referring to it. The state of an object is being associated with the hibernate session is called a Persistent state. The Persistent object represents the database entity, and its unique identifier value represents the database table primary column. The values associated with the persistent object are sync with the database. It means, if we change the values in persistent state objects, the changes will automatically get affected in the database, no need to execute insert/update operations. On the above diagram, the student is created for the first time using a new() , then the object is in a Transient state. This object is get converted to Persistent state, once the student object attached with the session.save() method. In place of session.save(), we can also use session.persist(). Both these methods result in SQL INSERT. The differences between the two functions are as follows: Save() method is used to save entities to the database immediately. This method can be invoked from both inside and outside a function. Save() method returns a Serializable object. If the database table already contains a primary key, save() function will not update its values. It is not useful for long-running conversations. Like Save(), Persist() is also used to save entities to the database. Persist() executes only within a method. It will not execute if it is called outside a method. This method does not return any value. This method coverts a transient instance to a persistent instance. Persist() is beneficial in long-running conversations. The object can go into the detached state when we close the session. We can detach an object from the session by using the three mechanisms. session.clear(); session.evict(student); session.close(); session.clear() will clear all the objects which are associated with the specified session. Whereas session.evict(student) will only delete the student object from the session object. session.close() is used to close the session while closing the session all the objects from the session will be removed. package com.onlinetutorialspoint.service; import com.onlinetutorialspoint.pojo.Student; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class ObjectStatesDemo { public static void main(String[] args) { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); // Transient State Student student = new Student(); student.setId(101); student.setName("chandrashekhar"); student.setRollNumber(10); Transaction transaction = session.beginTransaction(); // Going to Persistent State session.save(student); student.setName("Goka"); // Updated in database transaction.commit(); session.close(); // Detatched state student.setRollNumber(40); // Not Updated in Database } } Here are different methods, used to alter the hibernate object states. save(), persist() and saveOrUpdate() methods are used to take the transient state object to persistent state. Whenever we get the data from the database using get() or load() methods, the data would be in the persistent state only. close(), evict(), and clear() methods are used to take the hibernate persistent object state to detached state. The update() and merge() methods are used to reattach the detached objects to a session. Both will do the same thing, but there are some significant differences between update() and merge(). package com.onlinetutorialspoint.service; import com.onlinetutorialspoint.pojo.Student; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateStatesExample { public static void main(String[] args) { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); // Transient State Student student = new Student(); student.setId(111); student.setName("chandrashekhar"); student.setRollNumber(10); Transaction transaction = session.beginTransaction(); // Going to Persistent State session.save(student); student.setName("Goka"); // Updated in database transaction.commit(); session.close(); // Detatched state Session session2 = factory.openSession(); Transaction transaction2 = session2.beginTransaction(); session2.update(student); // reattaching student.setRollNumber(40); // Updated in Database session2.evict(student); // Detaching student object from session student.setId(300); // not update to Database. Student student2 = session2.get(Student.class, 111); student2.setRollNumber(500); // Updated in Database session2.update(student2); transaction2.commit(); session2.close(); } } Happy Learning 🙂 Difference between update vs merge in Hibernate example Hibernate cache first level example hbm2ddl.auto Example in Hibernate XML Config Hibernate Native SQL Query Example HQL update, delete Query Example Hibernate Interceptor Example Basic Hibernate Example with XML Configuration Hibernate Composite Key Mapping Example Hibernate 4 Example with Annotations Mysql Hibernate session differences between load() and get() Top 7 Interview Questions in Hibernate Custom Generator Class in Hibernate 4 ways to create an Object in Java How to convert Java Object to JSON How to convert JSON to Java Object Example Difference between update vs merge in Hibernate example Hibernate cache first level example hbm2ddl.auto Example in Hibernate XML Config Hibernate Native SQL Query Example HQL update, delete Query Example Hibernate Interceptor Example Basic Hibernate Example with XML Configuration Hibernate Composite Key Mapping Example Hibernate 4 Example with Annotations Mysql Hibernate session differences between load() and get() Top 7 Interview Questions in Hibernate Custom Generator Class in Hibernate 4 ways to create an Object in Java How to convert Java Object to JSON How to convert JSON to Java Object Example Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "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": 631, "s": 398, "text": " Object states in Hibernate play a vital role in the execution of code in an application. Hibernate has provided three different states for an object. These three states are also called as hibernate’s life cycle states of an object." }, { "code": null, "e": 675, "s": 631, "text": "The three states defined by hibernate are:\n" }, { "code": null, "e": 691, "s": 675, "text": "Transient State" }, { "code": null, "e": 708, "s": 691, "text": "Persistent State" }, { "code": null, "e": 723, "s": 708, "text": "Detached State" }, { "code": null, "e": 927, "s": 723, "text": "An object that is created for the first time using the new() operator, then it is under the state of Transient. As it is a newly created object, it doesn’t have any connection with the Hibernate Session." }, { "code": null, "e": 1148, "s": 927, "text": "This object becomes persistent when it is mapped with a database or an identifier value. It means, when we save an object, initially the object being added to the cache. This state is considered to be a persistent state." }, { "code": null, "e": 1276, "s": 1148, "text": "A Transient object can be destroyed automatically by the garbage collector if any active session object is not referring to it." }, { "code": null, "e": 1508, "s": 1276, "text": "The state of an object is being associated with the hibernate session is called a Persistent state. The Persistent object represents the database entity, and its unique identifier value represents the database table primary column." }, { "code": null, "e": 1754, "s": 1508, "text": "The values associated with the persistent object are sync with the database. It means, if we change the values in persistent state objects, the changes will automatically get affected in the database, no need to execute insert/update operations." }, { "code": null, "e": 1990, "s": 1754, "text": "On the above diagram, the student is created for the first time using a new() , then the object is in a Transient state. This object is get converted to Persistent state, once the student object attached with the session.save() method." }, { "code": null, "e": 2094, "s": 1990, "text": "In place of session.save(), we can also use session.persist(). Both these methods result in SQL INSERT." }, { "code": null, "e": 2152, "s": 2094, "text": "The differences between the two functions are as follows:" }, { "code": null, "e": 2220, "s": 2152, "text": "Save() method is used to save entities to the database immediately." }, { "code": null, "e": 2288, "s": 2220, "text": "This method can be invoked from both inside and outside a function." }, { "code": null, "e": 2333, "s": 2288, "text": "Save() method returns a Serializable object." }, { "code": null, "e": 2431, "s": 2333, "text": "If the database table already contains a primary key, save() function will not update its values." }, { "code": null, "e": 2480, "s": 2431, "text": "It is not useful for long-running conversations." }, { "code": null, "e": 2550, "s": 2480, "text": "Like Save(), Persist() is also used to save entities to the database." }, { "code": null, "e": 2645, "s": 2550, "text": "Persist() executes only within a method. It will not execute if it is called outside a method." }, { "code": null, "e": 2684, "s": 2645, "text": "This method does not return any value." }, { "code": null, "e": 2751, "s": 2684, "text": "This method coverts a transient instance to a persistent instance." }, { "code": null, "e": 2806, "s": 2751, "text": "Persist() is beneficial in long-running conversations." }, { "code": null, "e": 2875, "s": 2806, "text": "The object can go into the detached state when we close the session." }, { "code": null, "e": 2949, "s": 2877, "text": "We can detach an object from the session by using the three mechanisms." }, { "code": null, "e": 2966, "s": 2949, "text": "session.clear();" }, { "code": null, "e": 2990, "s": 2966, "text": "session.evict(student);" }, { "code": null, "e": 3007, "s": 2990, "text": "session.close();" }, { "code": null, "e": 3191, "s": 3007, "text": "session.clear() will clear all the objects which are associated with the specified session. Whereas session.evict(student) will only delete the student object from the session object." }, { "code": null, "e": 3312, "s": 3191, "text": "session.close() is used to close the session while closing the session all the objects from the session will be removed." }, { "code": null, "e": 4343, "s": 3312, "text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport org.hibernate.cfg.Configuration;\n\npublic class ObjectStatesDemo {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n// Transient State\n Student student = new Student();\n student.setId(101);\n student.setName(\"chandrashekhar\");\n student.setRollNumber(10);\n Transaction transaction = session.beginTransaction();\n// Going to Persistent State\n session.save(student);\n\n student.setName(\"Goka\"); // Updated in database\n transaction.commit();\n session.close();\n// Detatched state\n\n student.setRollNumber(40); // Not Updated in Database\n }\n}" }, { "code": null, "e": 4418, "s": 4347, "text": "Here are different methods, used to alter the hibernate object states." }, { "code": null, "e": 4528, "s": 4418, "text": "save(), persist() and saveOrUpdate() methods are used to take the transient state object to persistent state." }, { "code": null, "e": 4650, "s": 4528, "text": "Whenever we get the data from the database using get() or load() methods, the data would be in the persistent state only." }, { "code": null, "e": 4762, "s": 4650, "text": "close(), evict(), and clear() methods are used to take the hibernate persistent object state to detached state." }, { "code": null, "e": 4957, "s": 4766, "text": "The update() and merge() methods are used to reattach the detached objects to a session. Both will do the same thing, but there are some significant differences between update() and merge()." }, { "code": null, "e": 6507, "s": 4957, "text": "\npackage com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateStatesExample {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n// Transient State\n Student student = new Student();\n student.setId(111);\n student.setName(\"chandrashekhar\");\n student.setRollNumber(10);\n Transaction transaction = session.beginTransaction();\n// Going to Persistent State\n session.save(student);\n\n student.setName(\"Goka\"); // Updated in database\n transaction.commit();\n session.close();\n// Detatched state\n\n Session session2 = factory.openSession();\n Transaction transaction2 = session2.beginTransaction();\n session2.update(student); // reattaching\n\n student.setRollNumber(40); // Updated in Database\n\n session2.evict(student); // Detaching student object from session\n\n student.setId(300); // not update to Database.\n\n Student student2 = session2.get(Student.class, 111);\n\n student2.setRollNumber(500); // Updated in Database\n\n session2.update(student2);\n transaction2.commit();\n session2.close();\n }\n}" }, { "code": null, "e": 6528, "s": 6511, "text": "Happy Learning 🙂" }, { "code": null, "e": 7138, "s": 6528, "text": "\nDifference between update vs merge in Hibernate example\nHibernate cache first level example\nhbm2ddl.auto Example in Hibernate XML Config\nHibernate Native SQL Query Example\nHQL update, delete Query Example\nHibernate Interceptor Example\nBasic Hibernate Example with XML Configuration\nHibernate Composite Key Mapping Example\nHibernate 4 Example with Annotations Mysql\nHibernate session differences between load() and get()\nTop 7 Interview Questions in Hibernate\nCustom Generator Class in Hibernate\n4 ways to create an Object in Java\nHow to convert Java Object to JSON\nHow to convert JSON to Java Object Example\n" }, { "code": null, "e": 7194, "s": 7138, "text": "Difference between update vs merge in Hibernate example" }, { "code": null, "e": 7230, "s": 7194, "text": "Hibernate cache first level example" }, { "code": null, "e": 7275, "s": 7230, "text": "hbm2ddl.auto Example in Hibernate XML Config" }, { "code": null, "e": 7310, "s": 7275, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 7343, "s": 7310, "text": "HQL update, delete Query Example" }, { "code": null, "e": 7373, "s": 7343, "text": "Hibernate Interceptor Example" }, { "code": null, "e": 7420, "s": 7373, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 7460, "s": 7420, "text": "Hibernate Composite Key Mapping Example" }, { "code": null, "e": 7503, "s": 7460, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 7558, "s": 7503, "text": "Hibernate session differences between load() and get()" }, { "code": null, "e": 7597, "s": 7558, "text": "Top 7 Interview Questions in Hibernate" }, { "code": null, "e": 7633, "s": 7597, "text": "Custom Generator Class in Hibernate" }, { "code": null, "e": 7668, "s": 7633, "text": "4 ways to create an Object in Java" }, { "code": null, "e": 7703, "s": 7668, "text": "How to convert Java Object to JSON" }, { "code": null, "e": 7746, "s": 7703, "text": "How to convert JSON to Java Object Example" }, { "code": null, "e": 7752, "s": 7750, "text": "Δ" }, { "code": null, "e": 7778, "s": 7752, "text": " Hibernate – Introduction" }, { "code": null, "e": 7802, "s": 7778, "text": " Hibernate – Advantages" }, { "code": null, "e": 7834, "s": 7802, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 7864, "s": 7834, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 7894, "s": 7864, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 7932, "s": 7894, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 7959, "s": 7932, "text": " Hibernate – Object States" }, { "code": null, "e": 7997, "s": 7959, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 8035, "s": 7997, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 8085, "s": 8035, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 8115, "s": 8085, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 8154, "s": 8115, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 8194, "s": 8154, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 8225, "s": 8194, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 8260, "s": 8225, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 8285, "s": 8260, "text": " Hibernate – Named Query" }, { "code": null, "e": 8315, "s": 8285, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 8344, "s": 8315, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 8381, "s": 8344, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 8407, "s": 8381, "text": " Hibernate – Restrictions" }, { "code": null, "e": 8431, "s": 8407, "text": " Hibernate – Projection" }, { "code": null, "e": 8465, "s": 8431, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 8499, "s": 8465, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 8529, "s": 8499, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 8562, "s": 8529, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 8594, "s": 8562, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 8620, "s": 8594, "text": " Hibernate – Update Query" }, { "code": null, "e": 8649, "s": 8620, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 8673, "s": 8649, "text": " Hibernate – Right Join" }, { "code": null, "e": 8696, "s": 8673, "text": " Hibernate – Left Join" }, { "code": null, "e": 8720, "s": 8696, "text": " Hibernate – Pagination" }, { "code": null, "e": 8751, "s": 8720, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 8781, "s": 8751, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 8815, "s": 8781, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 8844, "s": 8815, "text": " Hibernate – Table per Class" }, { "code": null, "e": 8877, "s": 8844, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 8915, "s": 8877, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 8957, "s": 8915, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 8988, "s": 8957, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 9021, "s": 8988, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 9059, "s": 9021, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 9084, "s": 9059, "text": " Hibernate – Interceptor" }, { "code": null, "e": 9130, "s": 9084, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
How to Design Professional Venn Diagrams in Python | by Chaitanya Baweja | Towards Data Science
Last week I was designing some reading material for my Python Class. The lecture topic was Python Sets. For illustrating some functions, I wanted to plot Venn Diagrams. Yes, the overlapping circle charts that you often find in data presentations. My search for open-source tools for designing professional looking Venn Diagrams lead me to tools like Canva, Meta-Chart, and Creately. While they had appealing designs, none of them had the required elegance and were seldom customizable. Somewhere in the depth of google search, I encountered matplotlib-venn and fell in love with it. The matplotlib-venn library allows you to completely customize your Venn diagrams, from the size of the circles to border type and line width. Here is a sample plot generated using this library. After using this library for multiple projects, I decided to share what I have learned through this tutorial. I will explain how to use matplotlib-venn to create your own professional Venn diagrams. All the examples in this tutorial were tested on a Jupyter notebook running Python 3.7. We will be using matplotlib-venn in this tutorial. There is an accompanying Jupyter notebook for this tutorial here. A Venn diagram is an illustration used to depict logical relationships between different groups or sets. Each group is represented using a circle. The size of each circle corresponds to the size/importance of the group. Overlaps between these circles represent the intersection between the two sets. These diagrams are thus, especially useful for identifying shared elements between each set. Let us look at an example for better clarification. Suppose you have a group of students that take multiple subjects. Two of these subjects are English and French. English = {'John', 'Amy', 'Howard', 'Lucy', 'Alice', 'George', 'Jacob', 'Rajesh', 'Remy', 'Tom'}French = {'Arthur', 'Leonard', 'Karan', 'Debby', 'Bernadette', 'Alice', 'Ron', 'Penny', 'Sheldon', 'John'} Both subjects have ten students each. Alice and John take both English and French. Now, we will visualize these sets using a Venn Diagram. Both circles are of the same size. This is because both these sets have the same number of students. The overlap between the two circles contains two objects: Alice and John. Now, that we understand what Venn diagrams are, let us design some using Python. The first step is to import the required libraries: matplotlib-venn and matplotlib. Then, we define the sets that we wish to plot: Finally, we will plot our Venn Diagram using the venn2 function of matplotlib-venn: venn2([English,French]) Output: The function takes as argument a list of the two sets and plots the required Venn diagram. We can also add labels to the plot and individual circles. Output: Now, let us consider two more subjects: Math and Science. Math = {'Amy', 'Leo', 'Ash', 'Brandon', 'Sara', 'Alice', 'Ron', 'Annie', 'Jake', 'Zac'}Science = {'Dexter', 'Geeta', 'James', 'Charles', 'Sammy', 'Brandon', 'Aayush', 'Josephy', 'Casey', 'Will'} We will now plot a Venn diagram with three sets: English, French, and Maths. We do this using the venn3 function: Output: As expected, there are overlaps among all three sets. All sets have Alice in common. Now, let us consider using Science as the third set rather than Math. Output: We see that Science is a disjoint set, without any overlap with the other circles. Suppose there is a mandatory subject called Fire Safety that must be taken by everyone. We can define it by taking a set union of all subjects. Output: Sometimes we do not have the set definitions available to us. We only know the size of these sets and the amount of overlap between them. In such situations, we use the subsets parameter: subsets is a tuple containing three values: Contained in set A, but not BContained in Set B, but not AIntersection of set A and B Contained in set A, but not B Contained in Set B, but not A Intersection of set A and B venn2(subsets = (50, 20, 10), set_labels = ('Set A', 'Set B')) You can find more details and examples using subsets here. While the default colors, red and green, are suitable in most situations, you can choose different colors as per your convenience. The set_colors parameter allows us to set the color of a group. The alpha parameter allows us to control transparency. venn2([English, French], set_labels = ('English Class', 'French Class'), set_colors=('darkblue', 'yellow'), alpha = 0.8); Output: We can also add custom borders to our Venn Diagram. We achieve this by overlaying a customized outline over the original. We plot this outline using venn2_circles and venn3_circles. Take a look: We can also select the width and style of our border using linewidth and linestyle parameters respectively. More examples can be found here. We can also access each element of the Venn Diagram using their id. The figure below denotes the IDs for each area of the 2-group and 3-group Venn diagrams. You can customize the colors of each area of the diagram with the get_patch_by_id method. We can also customize the text for each region using the get_label_by_id method. Take a look: Notice that the intersection area is now purple-colored, and the left circle has ‘New Text’ written on it. More details about customization are available here. The matplotlib-venn library allows you to completely customize your Venn diagrams, from the size of the circles to border type and line width. It can be used to make both two and three group Venn diagrams. It is advised not to design Venn diagrams with over three groups. This is still an open issue in the library. You can find all the snippets in this accompanying Jupyter Notebook. Hope you found this tutorial useful. Chaitanya Baweja aspires to solve real world problems with engineering solutions. Follow his journey on Twitter and Linkedin.
[ { "code": null, "e": 276, "s": 172, "text": "Last week I was designing some reading material for my Python Class. The lecture topic was Python Sets." }, { "code": null, "e": 419, "s": 276, "text": "For illustrating some functions, I wanted to plot Venn Diagrams. Yes, the overlapping circle charts that you often find in data presentations." }, { "code": null, "e": 658, "s": 419, "text": "My search for open-source tools for designing professional looking Venn Diagrams lead me to tools like Canva, Meta-Chart, and Creately. While they had appealing designs, none of them had the required elegance and were seldom customizable." }, { "code": null, "e": 755, "s": 658, "text": "Somewhere in the depth of google search, I encountered matplotlib-venn and fell in love with it." }, { "code": null, "e": 950, "s": 755, "text": "The matplotlib-venn library allows you to completely customize your Venn diagrams, from the size of the circles to border type and line width. Here is a sample plot generated using this library." }, { "code": null, "e": 1149, "s": 950, "text": "After using this library for multiple projects, I decided to share what I have learned through this tutorial. I will explain how to use matplotlib-venn to create your own professional Venn diagrams." }, { "code": null, "e": 1288, "s": 1149, "text": "All the examples in this tutorial were tested on a Jupyter notebook running Python 3.7. We will be using matplotlib-venn in this tutorial." }, { "code": null, "e": 1354, "s": 1288, "text": "There is an accompanying Jupyter notebook for this tutorial here." }, { "code": null, "e": 1459, "s": 1354, "text": "A Venn diagram is an illustration used to depict logical relationships between different groups or sets." }, { "code": null, "e": 1574, "s": 1459, "text": "Each group is represented using a circle. The size of each circle corresponds to the size/importance of the group." }, { "code": null, "e": 1747, "s": 1574, "text": "Overlaps between these circles represent the intersection between the two sets. These diagrams are thus, especially useful for identifying shared elements between each set." }, { "code": null, "e": 1911, "s": 1747, "text": "Let us look at an example for better clarification. Suppose you have a group of students that take multiple subjects. Two of these subjects are English and French." }, { "code": null, "e": 2114, "s": 1911, "text": "English = {'John', 'Amy', 'Howard', 'Lucy', 'Alice', 'George', 'Jacob', 'Rajesh', 'Remy', 'Tom'}French = {'Arthur', 'Leonard', 'Karan', 'Debby', 'Bernadette', 'Alice', 'Ron', 'Penny', 'Sheldon', 'John'}" }, { "code": null, "e": 2197, "s": 2114, "text": "Both subjects have ten students each. Alice and John take both English and French." }, { "code": null, "e": 2253, "s": 2197, "text": "Now, we will visualize these sets using a Venn Diagram." }, { "code": null, "e": 2354, "s": 2253, "text": "Both circles are of the same size. This is because both these sets have the same number of students." }, { "code": null, "e": 2428, "s": 2354, "text": "The overlap between the two circles contains two objects: Alice and John." }, { "code": null, "e": 2509, "s": 2428, "text": "Now, that we understand what Venn diagrams are, let us design some using Python." }, { "code": null, "e": 2640, "s": 2509, "text": "The first step is to import the required libraries: matplotlib-venn and matplotlib. Then, we define the sets that we wish to plot:" }, { "code": null, "e": 2724, "s": 2640, "text": "Finally, we will plot our Venn Diagram using the venn2 function of matplotlib-venn:" }, { "code": null, "e": 2748, "s": 2724, "text": "venn2([English,French])" }, { "code": null, "e": 2756, "s": 2748, "text": "Output:" }, { "code": null, "e": 2847, "s": 2756, "text": "The function takes as argument a list of the two sets and plots the required Venn diagram." }, { "code": null, "e": 2906, "s": 2847, "text": "We can also add labels to the plot and individual circles." }, { "code": null, "e": 2914, "s": 2906, "text": "Output:" }, { "code": null, "e": 2972, "s": 2914, "text": "Now, let us consider two more subjects: Math and Science." }, { "code": null, "e": 3167, "s": 2972, "text": "Math = {'Amy', 'Leo', 'Ash', 'Brandon', 'Sara', 'Alice', 'Ron', 'Annie', 'Jake', 'Zac'}Science = {'Dexter', 'Geeta', 'James', 'Charles', 'Sammy', 'Brandon', 'Aayush', 'Josephy', 'Casey', 'Will'}" }, { "code": null, "e": 3281, "s": 3167, "text": "We will now plot a Venn diagram with three sets: English, French, and Maths. We do this using the venn3 function:" }, { "code": null, "e": 3289, "s": 3281, "text": "Output:" }, { "code": null, "e": 3374, "s": 3289, "text": "As expected, there are overlaps among all three sets. All sets have Alice in common." }, { "code": null, "e": 3444, "s": 3374, "text": "Now, let us consider using Science as the third set rather than Math." }, { "code": null, "e": 3452, "s": 3444, "text": "Output:" }, { "code": null, "e": 3535, "s": 3452, "text": "We see that Science is a disjoint set, without any overlap with the other circles." }, { "code": null, "e": 3679, "s": 3535, "text": "Suppose there is a mandatory subject called Fire Safety that must be taken by everyone. We can define it by taking a set union of all subjects." }, { "code": null, "e": 3687, "s": 3679, "text": "Output:" }, { "code": null, "e": 3875, "s": 3687, "text": "Sometimes we do not have the set definitions available to us. We only know the size of these sets and the amount of overlap between them. In such situations, we use the subsets parameter:" }, { "code": null, "e": 3919, "s": 3875, "text": "subsets is a tuple containing three values:" }, { "code": null, "e": 4005, "s": 3919, "text": "Contained in set A, but not BContained in Set B, but not AIntersection of set A and B" }, { "code": null, "e": 4035, "s": 4005, "text": "Contained in set A, but not B" }, { "code": null, "e": 4065, "s": 4035, "text": "Contained in Set B, but not A" }, { "code": null, "e": 4093, "s": 4065, "text": "Intersection of set A and B" }, { "code": null, "e": 4156, "s": 4093, "text": "venn2(subsets = (50, 20, 10), set_labels = ('Set A', 'Set B'))" }, { "code": null, "e": 4215, "s": 4156, "text": "You can find more details and examples using subsets here." }, { "code": null, "e": 4346, "s": 4215, "text": "While the default colors, red and green, are suitable in most situations, you can choose different colors as per your convenience." }, { "code": null, "e": 4410, "s": 4346, "text": "The set_colors parameter allows us to set the color of a group." }, { "code": null, "e": 4465, "s": 4410, "text": "The alpha parameter allows us to control transparency." }, { "code": null, "e": 4587, "s": 4465, "text": "venn2([English, French], set_labels = ('English Class', 'French Class'), set_colors=('darkblue', 'yellow'), alpha = 0.8);" }, { "code": null, "e": 4595, "s": 4587, "text": "Output:" }, { "code": null, "e": 4717, "s": 4595, "text": "We can also add custom borders to our Venn Diagram. We achieve this by overlaying a customized outline over the original." }, { "code": null, "e": 4790, "s": 4717, "text": "We plot this outline using venn2_circles and venn3_circles. Take a look:" }, { "code": null, "e": 4898, "s": 4790, "text": "We can also select the width and style of our border using linewidth and linestyle parameters respectively." }, { "code": null, "e": 4931, "s": 4898, "text": "More examples can be found here." }, { "code": null, "e": 4999, "s": 4931, "text": "We can also access each element of the Venn Diagram using their id." }, { "code": null, "e": 5088, "s": 4999, "text": "The figure below denotes the IDs for each area of the 2-group and 3-group Venn diagrams." }, { "code": null, "e": 5259, "s": 5088, "text": "You can customize the colors of each area of the diagram with the get_patch_by_id method. We can also customize the text for each region using the get_label_by_id method." }, { "code": null, "e": 5272, "s": 5259, "text": "Take a look:" }, { "code": null, "e": 5379, "s": 5272, "text": "Notice that the intersection area is now purple-colored, and the left circle has ‘New Text’ written on it." }, { "code": null, "e": 5432, "s": 5379, "text": "More details about customization are available here." }, { "code": null, "e": 5638, "s": 5432, "text": "The matplotlib-venn library allows you to completely customize your Venn diagrams, from the size of the circles to border type and line width. It can be used to make both two and three group Venn diagrams." }, { "code": null, "e": 5748, "s": 5638, "text": "It is advised not to design Venn diagrams with over three groups. This is still an open issue in the library." }, { "code": null, "e": 5817, "s": 5748, "text": "You can find all the snippets in this accompanying Jupyter Notebook." }, { "code": null, "e": 5854, "s": 5817, "text": "Hope you found this tutorial useful." } ]
Dealing with Rows and Columns in Pandas DataFrame - GeeksforGeeks
13 Oct, 2021 A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can perform basic operations on rows/columns like selecting, deleting, adding, and renaming. In this article, we are using nba.csv file. In order to deal with columns, we perform basic operations on columns like selecting, deleting, adding and renaming. Column Selection:In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select two columnsprint(df[['Name', 'Qualification']]) Output:For more examples refer to How to select multiple columns in a pandas dataframe Column Addition:In Order to add a column in Pandas DataFrame, we can declare a new list as a column and add to a existing Dataframe. # Import pandas package import pandas as pd # Define a dictionary containing Students datadata = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Height': [5.1, 6.2, 5.1, 5.2], 'Qualification': ['Msc', 'MA', 'Msc', 'Msc']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Declare a list that is to be converted into a columnaddress = ['Delhi', 'Bangalore', 'Chennai', 'Patna'] # Using 'Address' as the column name# and equating it to the listdf['Address'] = address # Observe the resultprint(df) Output:For more examples refer to Adding new column to existing DataFrame in Pandas Column Deletion:In Order to delete a column in Pandas DataFrame, we can use the drop() method. Columns is deleted by dropping columns with column names. # importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name" ) # dropping passed columnsdata.drop(["Team", "Weight"], axis = 1, inplace = True) # displayprint(data) Output:As shown in the output images, the new output doesn’t have the passed columns. Those values were dropped since axis was set equal to 1 and the changes were made in the original data frame since inplace was True.Data Frame before Dropping Columns-Data Frame after Dropping Columns-For more examples refer to Delete columns from DataFrame using Pandas.drop() In order to deal with rows, we can perform basic operations on rows like selecting, deleting, adding and renaming. Row Selection:Pandas provide a unique method to retrieve rows from a Data frame.DataFrame.loc[] method is used to retrieve rows from Pandas DataFrame. Rows can also be selected by passing integer location to an iloc[] function. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving row by loc methodfirst = data.loc["Avery Bradley"]second = data.loc["R.J. Hunter"] print(first, "\n\n\n", second) Output:As shown in the output image, two series were returned since there was only one parameter both of the times.For more examples refer to Pandas Extracting rows using .loc[] Row Addition:In Order to add a Row in Pandas DataFrame, we can concat the old dataframe with new one. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv", index_col ="Name") df.head(10) new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0])# simply concatenate both dataframesdf = pd.concat([new_row, df]).reset_index(drop = True)df.head(5) Output:Data Frame before Adding Row-Data Frame after Adding Row-For more examples refer to Add a row at top in pandas DataFrame Row Deletion:In Order to delete a row in Pandas DataFrame, we can use the drop() method. Rows is deleted by dropping Rows by index label. # importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name" ) # dropping passed valuesdata.drop(["Avery Bradley", "John Holland", "R.J. Hunter", "R.J. Hunter"], inplace = True) # displaydata Output:As shown in the output images, the new output doesn’t have the passed values. Those values were dropped and the changes were made in the original data frame since inplace was True.Data Frame before Dropping values-Data Frame after Dropping values-For more examples refer to Delete rows from DataFrame using Pandas.drop() Problem related to Columns: How to get column names in Pandas dataframe How to rename columns in Pandas DataFrame How to drop one or multiple columns in Pandas Dataframe Get unique values from a column in Pandas DataFrame How to lowercase column names in Pandas dataframe Apply uppercase to a column in Pandas dataframe Capitalize first letter of a column in Pandas dataframe Get n-largest values from a particular column in Pandas DataFrame Get n-smallest values from a particular column in Pandas DataFrame Convert a column to row name/index in Pandas Problem related to Rows: Apply function to every row in a Pandas DataFrame How to get rows names in Pandas dataframe puja84375 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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()
[ { "code": null, "e": 41553, "s": 41525, "text": "\n13 Oct, 2021" }, { "code": null, "e": 41807, "s": 41553, "text": "A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can perform basic operations on rows/columns like selecting, deleting, adding, and renaming. In this article, we are using nba.csv file." }, { "code": null, "e": 41924, "s": 41807, "text": "In order to deal with columns, we perform basic operations on columns like selecting, deleting, adding and renaming." }, { "code": null, "e": 42062, "s": 41924, "text": "Column Selection:In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select two columnsprint(df[['Name', 'Qualification']])", "e": 42472, "s": 42062, "text": null }, { "code": null, "e": 42692, "s": 42472, "text": "Output:For more examples refer to How to select multiple columns in a pandas dataframe Column Addition:In Order to add a column in Pandas DataFrame, we can declare a new list as a column and add to a existing Dataframe." }, { "code": "# Import pandas package import pandas as pd # Define a dictionary containing Students datadata = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Height': [5.1, 6.2, 5.1, 5.2], 'Qualification': ['Msc', 'MA', 'Msc', 'Msc']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Declare a list that is to be converted into a columnaddress = ['Delhi', 'Bangalore', 'Chennai', 'Patna'] # Using 'Address' as the column name# and equating it to the listdf['Address'] = address # Observe the resultprint(df)", "e": 43221, "s": 42692, "text": null }, { "code": null, "e": 43458, "s": 43221, "text": "Output:For more examples refer to Adding new column to existing DataFrame in Pandas Column Deletion:In Order to delete a column in Pandas DataFrame, we can use the drop() method. Columns is deleted by dropping columns with column names." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\" ) # dropping passed columnsdata.drop([\"Team\", \"Weight\"], axis = 1, inplace = True) # displayprint(data)", "e": 43691, "s": 43458, "text": null }, { "code": null, "e": 44055, "s": 43691, "text": "Output:As shown in the output images, the new output doesn’t have the passed columns. Those values were dropped since axis was set equal to 1 and the changes were made in the original data frame since inplace was True.Data Frame before Dropping Columns-Data Frame after Dropping Columns-For more examples refer to Delete columns from DataFrame using Pandas.drop()" }, { "code": null, "e": 44170, "s": 44055, "text": "In order to deal with rows, we can perform basic operations on rows like selecting, deleting, adding and renaming." }, { "code": null, "e": 44398, "s": 44170, "text": "Row Selection:Pandas provide a unique method to retrieve rows from a Data frame.DataFrame.loc[] method is used to retrieve rows from Pandas DataFrame. Rows can also be selected by passing integer location to an iloc[] function." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving row by loc methodfirst = data.loc[\"Avery Bradley\"]second = data.loc[\"R.J. Hunter\"] print(first, \"\\n\\n\\n\", second)", "e": 44658, "s": 44398, "text": null }, { "code": null, "e": 44938, "s": 44658, "text": "Output:As shown in the output image, two series were returned since there was only one parameter both of the times.For more examples refer to Pandas Extracting rows using .loc[] Row Addition:In Order to add a Row in Pandas DataFrame, we can concat the old dataframe with new one." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\", index_col =\"Name\") df.head(10) new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0])# simply concatenate both dataframesdf = pd.concat([new_row, df]).reset_index(drop = True)df.head(5)", "e": 45447, "s": 44938, "text": null }, { "code": null, "e": 45713, "s": 45447, "text": "Output:Data Frame before Adding Row-Data Frame after Adding Row-For more examples refer to Add a row at top in pandas DataFrame Row Deletion:In Order to delete a row in Pandas DataFrame, we can use the drop() method. Rows is deleted by dropping Rows by index label." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\" ) # dropping passed valuesdata.drop([\"Avery Bradley\", \"John Holland\", \"R.J. Hunter\", \"R.J. Hunter\"], inplace = True) # displaydata", "e": 46000, "s": 45713, "text": null }, { "code": null, "e": 46356, "s": 46000, "text": "Output:As shown in the output images, the new output doesn’t have the passed values. Those values were dropped and the changes were made in the original data frame since inplace was True.Data Frame before Dropping values-Data Frame after Dropping values-For more examples refer to Delete rows from DataFrame using Pandas.drop() Problem related to Columns:" }, { "code": null, "e": 46400, "s": 46356, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 46442, "s": 46400, "text": "How to rename columns in Pandas DataFrame" }, { "code": null, "e": 46498, "s": 46442, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 46550, "s": 46498, "text": "Get unique values from a column in Pandas DataFrame" }, { "code": null, "e": 46600, "s": 46550, "text": "How to lowercase column names in Pandas dataframe" }, { "code": null, "e": 46648, "s": 46600, "text": "Apply uppercase to a column in Pandas dataframe" }, { "code": null, "e": 46704, "s": 46648, "text": "Capitalize first letter of a column in Pandas dataframe" }, { "code": null, "e": 46770, "s": 46704, "text": "Get n-largest values from a particular column in Pandas DataFrame" }, { "code": null, "e": 46837, "s": 46770, "text": "Get n-smallest values from a particular column in Pandas DataFrame" }, { "code": null, "e": 46882, "s": 46837, "text": "Convert a column to row name/index in Pandas" }, { "code": null, "e": 46907, "s": 46882, "text": "Problem related to Rows:" }, { "code": null, "e": 46957, "s": 46907, "text": "Apply function to every row in a Pandas DataFrame" }, { "code": null, "e": 46999, "s": 46957, "text": "How to get rows names in Pandas dataframe" }, { "code": null, "e": 47009, "s": 46999, "text": "puja84375" }, { "code": null, "e": 47033, "s": 47009, "text": "Python pandas-dataFrame" }, { "code": null, "e": 47047, "s": 47033, "text": "Python-pandas" }, { "code": null, "e": 47054, "s": 47047, "text": "Python" }, { "code": null, "e": 47152, "s": 47054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47180, "s": 47152, "text": "Read JSON file using Python" }, { "code": null, "e": 47230, "s": 47180, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 47252, "s": 47230, "text": "Python map() function" }, { "code": null, "e": 47296, "s": 47252, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 47331, "s": 47296, "text": "Read a file line by line in Python" }, { "code": null, "e": 47353, "s": 47331, "text": "Enumerate() in Python" }, { "code": null, "e": 47385, "s": 47353, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 47415, "s": 47385, "text": "Iterate over a list in Python" }, { "code": null, "e": 47457, "s": 47415, "text": "Different ways to create Pandas Dataframe" } ]
Rotation | Practice | GeeksforGeeks
Given an ascending sorted rotated array Arr of distinct integers of size N. The array is right rotated K times. Find the value of K. Example 1: Input: N = 5 Arr[] = {5, 1, 2, 3, 4} Output: 1 Explanation: The given array is 5 1 2 3 4. The original sorted array is 1 2 3 4 5. We can see that the array was rotated 1 times to the right. Example 2: Input: N = 5 Arr[] = {1, 2, 3, 4, 5} Output: 0 Explanation: The given array is not rotated. Your Task: Complete the function findKRotation() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs. Expected Time Complexity: O(log(N)) Expected Auxiliary Space: O(1) Constraints: 1 <= N <=105 1 <= Arri <= 107 0 ashutos17sharma89892 weeks ago JAVA Binary Search class Solution { int findKRotation(int arr[], int n) { // code here int[] nums=arr; int low =0,high=nums.length-1; while(low<=high){ int mid =(low+high)/2; int prev=mid==0?n-1:(mid-1); int next =mid==n-1?0:(mid+1); if((nums[mid]<=nums[next] && nums[mid]<=nums[prev]) ){ return mid; }else if (nums[mid] > nums[high]) { low = mid + 1; } else { high = mid - 1; } } return 0; } } -1 ashutos17sharma89892 weeks ago class Solution { int findKRotation(int arr[], int n) { // code here for(int i=0;i<n-1;i++){ if(arr[i]<arr[i+1]){ continue; } return i+1; } return 0; } } 0 amrit_kumar2 weeks ago binary search int findKRotation(int arr[], int n) { int result = 0; int l = 0; int r = n-1; while(l<=r) { int mid = l+(r-l)/2; int left = (mid-1+n)%n; int right = (mid+1)%n; if(arr[left]>arr[mid]&&arr[mid]<arr[right]) { return mid; } else if(arr[mid]<arr[r]) { r = mid-1; } else { l= mid+1; } } return result; } 0 parasrockz812 weeks ago class Solution{public: int findKRotation(int arr[], int n) { for(int x = 0;x < n-1 ;x++) { if(arr[x] > arr[x+1]) { return x+1; } } return 0;} }; 0 swapniltayal4223 weeks ago public: int findKRotation(int arr[], int n) { // code here for (int i=1; i<n; i++){ if (arr[i] <= arr[i-1]){ return i; } }return 0;} 0 kumarsurajroy36553 weeks ago // User function Template for Java class Solution { int findKRotation(int arr[], int n) { // code here int count=0; for(int i=1;i<n;i++){ if(arr[i-1]>arr[i] || count!=0) count++; } return (n-count)%n; }} 0 ajay7yadav953 weeks ago //javaScript lover ------------→ by A7 findKRotation(arr,n) { let count = 0; for(let i=0;i<arr.length;i++){ if(arr[i]>arr[n-1]) { count++; }else{ break; } } return count; } 0 mohammadtanveer75403 weeks ago class Solution{ public: int findKRotation(int arr[], int n) { int ct=0, temp = arr[n-1]; for(int i=0;i<n-1;i++){ if(arr[i]>temp) ct++; else break; } return ct; } }; -3 uk85664 weeks ago class Solution { int findKRotation(int arr[], int n) { int[] temp = new int[n]; System.arraycopy(arr,0,temp,0,n); Arrays.sort(temp); int firstVal= temp[0]; for(int i=0;i<n;i++){ if(firstVal == arr[i]){ return i; } } return -1; }} 0 araj626301 month ago class Solution: def findKRotation(self,Arr, n): start=0 end=n-1 while start<=end: if Arr[start] <= Arr[end]: return start mid=start+(end-start)//2 nextt=(mid+1)%n prevv=(mid+n-1)%n if Arr[mid]<=Arr[nextt] and Arr[mid]<=Arr[prevv]: return mid elif Arr[mid] >= Arr[start]: start=mid+1 else: end=mid-1 We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 371, "s": 238, "text": "Given an ascending sorted rotated array Arr of distinct integers of size N. The array is right rotated K times. Find the value of K." }, { "code": null, "e": 382, "s": 371, "text": "Example 1:" }, { "code": null, "e": 576, "s": 382, "text": "Input:\nN = 5\nArr[] = {5, 1, 2, 3, 4}\nOutput: 1\nExplanation: The given array is 5 1 2 3 4. \nThe original sorted array is 1 2 3 4 5. \nWe can see that the array was rotated \n1 times to the right.\n" }, { "code": null, "e": 587, "s": 576, "text": "Example 2:" }, { "code": null, "e": 680, "s": 587, "text": "Input:\nN = 5\nArr[] = {1, 2, 3, 4, 5}\nOutput: 0\nExplanation: The given array is not rotated.\n" }, { "code": null, "e": 873, "s": 680, "text": "Your Task:\nComplete the function findKRotation() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs." }, { "code": null, "e": 940, "s": 873, "text": "Expected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 983, "s": 940, "text": "Constraints:\n1 <= N <=105\n1 <= Arri <= 107" }, { "code": null, "e": 987, "s": 985, "text": "0" }, { "code": null, "e": 1018, "s": 987, "text": "ashutos17sharma89892 weeks ago" }, { "code": null, "e": 1038, "s": 1018, "text": "JAVA Binary Search " }, { "code": null, "e": 1606, "s": 1040, "text": "class Solution {\n int findKRotation(int arr[], int n) {\n // code here\n int[] nums=arr;\n int low =0,high=nums.length-1;\n while(low<=high){\n int mid =(low+high)/2;\n int prev=mid==0?n-1:(mid-1);\n int next =mid==n-1?0:(mid+1);\n if((nums[mid]<=nums[next] && nums[mid]<=nums[prev]) ){\n return mid;\n }else if (nums[mid] > nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n return 0;\n }\n}" }, { "code": null, "e": 1609, "s": 1606, "text": "-1" }, { "code": null, "e": 1640, "s": 1609, "text": "ashutos17sharma89892 weeks ago" }, { "code": null, "e": 1885, "s": 1640, "text": "class Solution {\n int findKRotation(int arr[], int n) {\n // code here\n for(int i=0;i<n-1;i++){\n if(arr[i]<arr[i+1]){\n continue;\n }\n return i+1; \n }\n return 0;\n }\n}" }, { "code": null, "e": 1887, "s": 1885, "text": "0" }, { "code": null, "e": 1910, "s": 1887, "text": "amrit_kumar2 weeks ago" }, { "code": null, "e": 1924, "s": 1910, "text": "binary search" }, { "code": null, "e": 2409, "s": 1926, "text": "int findKRotation(int arr[], int n) \n\t{\n\t int result = 0;\n\t int l = 0;\n\t int r = n-1;\n\t while(l<=r)\n\t {\n\t int mid = l+(r-l)/2;\n\t int left = (mid-1+n)%n;\n\t int right = (mid+1)%n;\n\t if(arr[left]>arr[mid]&&arr[mid]<arr[right])\n\t {\n\t return mid;\n\t }\n\t else if(arr[mid]<arr[r])\n\t {\n\t r = mid-1;\n\t }\n\t else\n\t {\n\t l= mid+1;\n\t }\n\t }\n\t return result;\n\t}" }, { "code": null, "e": 2411, "s": 2409, "text": "0" }, { "code": null, "e": 2435, "s": 2411, "text": "parasrockz812 weeks ago" }, { "code": null, "e": 2621, "s": 2435, "text": "class Solution{public: int findKRotation(int arr[], int n) { for(int x = 0;x < n-1 ;x++) { if(arr[x] > arr[x+1]) { return x+1; } } return 0;}" }, { "code": null, "e": 2624, "s": 2621, "text": "};" }, { "code": null, "e": 2626, "s": 2624, "text": "0" }, { "code": null, "e": 2653, "s": 2626, "text": "swapniltayal4223 weeks ago" }, { "code": null, "e": 2824, "s": 2653, "text": "public: int findKRotation(int arr[], int n) { // code here for (int i=1; i<n; i++){ if (arr[i] <= arr[i-1]){ return i; } }return 0;}" }, { "code": null, "e": 2826, "s": 2824, "text": "0" }, { "code": null, "e": 2855, "s": 2826, "text": "kumarsurajroy36553 weeks ago" }, { "code": null, "e": 2890, "s": 2855, "text": "// User function Template for Java" }, { "code": null, "e": 3128, "s": 2890, "text": "class Solution { int findKRotation(int arr[], int n) { // code here int count=0; for(int i=1;i<n;i++){ if(arr[i-1]>arr[i] || count!=0) count++; } return (n-count)%n; }}" }, { "code": null, "e": 3130, "s": 3128, "text": "0" }, { "code": null, "e": 3154, "s": 3130, "text": "ajay7yadav953 weeks ago" }, { "code": null, "e": 3195, "s": 3154, "text": "//javaScript lover ------------→ by A7" }, { "code": null, "e": 3427, "s": 3195, "text": " findKRotation(arr,n) { let count = 0; for(let i=0;i<arr.length;i++){ if(arr[i]>arr[n-1]) { count++; }else{ break; } } return count; }" }, { "code": null, "e": 3429, "s": 3427, "text": "0" }, { "code": null, "e": 3460, "s": 3429, "text": "mohammadtanveer75403 weeks ago" }, { "code": null, "e": 3717, "s": 3460, "text": "class Solution{\npublic:\t\n\tint findKRotation(int arr[], int n) {\n int ct=0, temp = arr[n-1];\n for(int i=0;i<n-1;i++){\n if(arr[i]>temp)\n ct++;\n else \n break;\n }\n return ct;\n\t}\n};" }, { "code": null, "e": 3720, "s": 3717, "text": "-3" }, { "code": null, "e": 3738, "s": 3720, "text": "uk85664 weeks ago" }, { "code": null, "e": 4049, "s": 3738, "text": "class Solution { int findKRotation(int arr[], int n) { int[] temp = new int[n]; System.arraycopy(arr,0,temp,0,n); Arrays.sort(temp); int firstVal= temp[0]; for(int i=0;i<n;i++){ if(firstVal == arr[i]){ return i; } } return -1; }}" }, { "code": null, "e": 4051, "s": 4049, "text": "0" }, { "code": null, "e": 4072, "s": 4051, "text": "araj626301 month ago" }, { "code": null, "e": 4549, "s": 4072, "text": "class Solution:\n def findKRotation(self,Arr, n):\n start=0\n end=n-1\n while start<=end:\n if Arr[start] <= Arr[end]:\n return start\n mid=start+(end-start)//2\n nextt=(mid+1)%n\n prevv=(mid+n-1)%n\n if Arr[mid]<=Arr[nextt] and Arr[mid]<=Arr[prevv]:\n return mid\n elif Arr[mid] >= Arr[start]:\n start=mid+1\n else:\n end=mid-1\n" }, { "code": null, "e": 4695, "s": 4549, "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": 4731, "s": 4695, "text": " Login to access your submissions. " }, { "code": null, "e": 4741, "s": 4731, "text": "\nProblem\n" }, { "code": null, "e": 4751, "s": 4741, "text": "\nContest\n" }, { "code": null, "e": 4814, "s": 4751, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4962, "s": 4814, "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": 5170, "s": 4962, "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": 5276, "s": 5170, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Assigning Values to Variables in Python
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example − Live Demo #!/usr/bin/python counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print counter print miles print name Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces the following result − 100 1000.0 John
[ { "code": null, "e": 1272, "s": 1062, "text": "Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables." }, { "code": null, "e": 1440, "s": 1272, "text": "The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −" }, { "code": null, "e": 1451, "s": 1440, "text": " Live Demo" }, { "code": null, "e": 1603, "s": 1451, "text": "#!/usr/bin/python\ncounter = 100 # An integer assignment\nmiles = 1000.0 # A floating point\nname = \"John\" # A string\nprint counter\nprint miles\nprint name" }, { "code": null, "e": 1709, "s": 1603, "text": "Here, 100, 1000.0 and \"John\" are the values assigned to counter, miles, and name variables, respectively." }, { "code": null, "e": 1746, "s": 1709, "text": "This produces the following result −" }, { "code": null, "e": 1762, "s": 1746, "text": "100\n1000.0\nJohn" } ]
PostgreSQL - CURRENT_TIME Function - GeeksforGeeks
09 Dec, 2021 The PostgreSQL CURRENT_TIME function returns the current time and the currentthe time zone. Syntax: CURRENT_TIME(precision) Let’s analyze the above syntax: The precision argument is used to set the precision of the returned TIMESTAMP type value in fractional seconds precision. By default the function returns a full available precision if not precision data is provided to the function. The CURRENT_TIME function returns a TIME WITH TIME ZONE value. This value is nothing but the current time with the the current time zone. Example 1: The following statement can be used to get the current time: SELECT CURRENT_TIME; Output: Example 2: The following statement shows the process of using the CURRENT_TIME function with the precision of 2: SELECT CURRENT_TIME(2); Output: Example 3: The CURRENT_TIME function can also be used as the default value of the TIME columns. To demonstrate this, create a table named log: CREATE TABLE log ( log_id SERIAL PRIMARY KEY, message VARCHAR(255) NOT NULL, created_at TIME DEFAULT CURRENT_TIME, created_on DATE DEFAULT CURRENT_DATE ); The log table has the created_at column whose default value is the value returned by the CURRENT_TIME function. Now insert some data to the demo table: INSERT INTO log( message ) VALUES('Testing the CURRENT_TIME function'); Now verify if the row was inserted into the log table with the created_at column added correctly by using the following query: SELECT * FROM log; Output: sooda367 simmytarika5 PostgreSQL-Date-function PostgreSQL-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - LEFT JOIN PostgreSQL - ROW_NUMBER Function PostgreSQL - Copy Table PostgreSQL - Cursor PostgreSQL - SELECT PostgreSQL - Record type variable PostgreSQL - Select Into PostgreSQL - TEXT Data Type
[ { "code": null, "e": 23747, "s": 23719, "text": "\n09 Dec, 2021" }, { "code": null, "e": 23839, "s": 23747, "text": "The PostgreSQL CURRENT_TIME function returns the current time and the currentthe time zone." }, { "code": null, "e": 23871, "s": 23839, "text": "Syntax: CURRENT_TIME(precision)" }, { "code": null, "e": 23903, "s": 23871, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 24135, "s": 23903, "text": "The precision argument is used to set the precision of the returned TIMESTAMP type value in fractional seconds precision. By default the function returns a full available precision if not precision data is provided to the function." }, { "code": null, "e": 24273, "s": 24135, "text": "The CURRENT_TIME function returns a TIME WITH TIME ZONE value. This value is nothing but the current time with the the current time zone." }, { "code": null, "e": 24284, "s": 24273, "text": "Example 1:" }, { "code": null, "e": 24345, "s": 24284, "text": "The following statement can be used to get the current time:" }, { "code": null, "e": 24366, "s": 24345, "text": "SELECT CURRENT_TIME;" }, { "code": null, "e": 24374, "s": 24366, "text": "Output:" }, { "code": null, "e": 24385, "s": 24374, "text": "Example 2:" }, { "code": null, "e": 24487, "s": 24385, "text": "The following statement shows the process of using the CURRENT_TIME function with the precision of 2:" }, { "code": null, "e": 24511, "s": 24487, "text": "SELECT CURRENT_TIME(2);" }, { "code": null, "e": 24519, "s": 24511, "text": "Output:" }, { "code": null, "e": 24530, "s": 24519, "text": "Example 3:" }, { "code": null, "e": 24662, "s": 24530, "text": "The CURRENT_TIME function can also be used as the default value of the TIME columns. To demonstrate this, create a table named log:" }, { "code": null, "e": 24833, "s": 24662, "text": "CREATE TABLE log (\n log_id SERIAL PRIMARY KEY,\n message VARCHAR(255) NOT NULL,\n created_at TIME DEFAULT CURRENT_TIME,\n created_on DATE DEFAULT CURRENT_DATE\n);" }, { "code": null, "e": 24985, "s": 24833, "text": "The log table has the created_at column whose default value is the value returned by the CURRENT_TIME function. Now insert some data to the demo table:" }, { "code": null, "e": 25057, "s": 24985, "text": "INSERT INTO log( message )\nVALUES('Testing the CURRENT_TIME function');" }, { "code": null, "e": 25184, "s": 25057, "text": "Now verify if the row was inserted into the log table with the created_at column added correctly by using the following query:" }, { "code": null, "e": 25203, "s": 25184, "text": "SELECT * FROM log;" }, { "code": null, "e": 25211, "s": 25203, "text": "Output:" }, { "code": null, "e": 25220, "s": 25211, "text": "sooda367" }, { "code": null, "e": 25233, "s": 25220, "text": "simmytarika5" }, { "code": null, "e": 25258, "s": 25233, "text": "PostgreSQL-Date-function" }, { "code": null, "e": 25278, "s": 25258, "text": "PostgreSQL-function" }, { "code": null, "e": 25289, "s": 25278, "text": "PostgreSQL" }, { "code": null, "e": 25387, "s": 25289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25396, "s": 25387, "text": "Comments" }, { "code": null, "e": 25409, "s": 25396, "text": "Old Comments" }, { "code": null, "e": 25438, "s": 25409, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 25462, "s": 25438, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 25485, "s": 25462, "text": "PostgreSQL - LEFT JOIN" }, { "code": null, "e": 25518, "s": 25485, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 25542, "s": 25518, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 25562, "s": 25542, "text": "PostgreSQL - Cursor" }, { "code": null, "e": 25582, "s": 25562, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 25616, "s": 25582, "text": "PostgreSQL - Record type variable" }, { "code": null, "e": 25641, "s": 25616, "text": "PostgreSQL - Select Into" } ]