title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
jQuery | hide() with Examples
13 Feb, 2019 The hide() is an inbuilt method in jQuery used to hide the selected element.Syntax: $(selector).hide(duration, easing, call_function); Here selector is the selected element.Parameter: It accepts three parameters which are specified below- duration: It specifies the speed of the hide effect. easing: It specifies the speed of the element at different point of animation. call_function: This is call back function to be executed after hide operation. Return Value: It does not return any value. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(".b1").click(function() { $("p").hide(); }); }); </script> <style> div { width: 50%; height: 80px; padding: 20px; margin: 10px; border: 2px solid green; font-size: 30px; } .b1 { margin: 10px; } </style></head> <body> <div> <p>GeeksforGeeks !.</p> </div> <!-- click on this button and above paragraph will disappear --> <button class="b1">Click me !</button> </body> </html> Output:Before clicking on “Click me!” button- After clicking on “Click me!” button- Code #2:In the below code, parameter is passed to this method. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(".btn1").click(function() { $("p").hide(1000, function() { alert("Hide() method has finished its working!"); }); }); }); </script> <style> p { width: 40%; padding: 20px; height: 50px; border: 2px solid green; } </style></head> <body> <p>GeeksforGeeks.!</p> <!-- click on this button and above paragraph will hide --> <button class="btn1">Click to Hide</button> </body> </html> Output:Before clicking on the “Click to Hide” button- After clicking on the “Click to Hide” button- jQuery-Effects JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 112, "s": 28, "text": "The hide() is an inbuilt method in jQuery used to hide the selected element.Syntax:" }, { "code": null, "e": 164, "s": 112, "text": "$(selector).hide(duration, easing, call_function);\n" }, { "code": null, "e": 268, "s": 164, "text": "Here selector is the selected element.Parameter: It accepts three parameters which are specified below-" }, { "code": null, "e": 321, "s": 268, "text": "duration: It specifies the speed of the hide effect." }, { "code": null, "e": 400, "s": 321, "text": "easing: It specifies the speed of the element at different point of animation." }, { "code": null, "e": 479, "s": 400, "text": "call_function: This is call back function to be executed after hide operation." }, { "code": null, "e": 523, "s": 479, "text": "Return Value: It does not return any value." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\".b1\").click(function() { $(\"p\").hide(); }); }); </script> <style> div { width: 50%; height: 80px; padding: 20px; margin: 10px; border: 2px solid green; font-size: 30px; } .b1 { margin: 10px; } </style></head> <body> <div> <p>GeeksforGeeks !.</p> </div> <!-- click on this button and above paragraph will disappear --> <button class=\"b1\">Click me !</button> </body> </html>", "e": 1314, "s": 523, "text": null }, { "code": null, "e": 1360, "s": 1314, "text": "Output:Before clicking on “Click me!” button-" }, { "code": null, "e": 1398, "s": 1360, "text": "After clicking on “Click me!” button-" }, { "code": null, "e": 1461, "s": 1398, "text": "Code #2:In the below code, parameter is passed to this method." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(\".btn1\").click(function() { $(\"p\").hide(1000, function() { alert(\"Hide() method has finished its working!\"); }); }); }); </script> <style> p { width: 40%; padding: 20px; height: 50px; border: 2px solid green; } </style></head> <body> <p>GeeksforGeeks.!</p> <!-- click on this button and above paragraph will hide --> <button class=\"btn1\">Click to Hide</button> </body> </html>", "e": 2227, "s": 1461, "text": null }, { "code": null, "e": 2281, "s": 2227, "text": "Output:Before clicking on the “Click to Hide” button-" }, { "code": null, "e": 2327, "s": 2281, "text": "After clicking on the “Click to Hide” button-" }, { "code": null, "e": 2342, "s": 2327, "text": "jQuery-Effects" }, { "code": null, "e": 2353, "s": 2342, "text": "JavaScript" }, { "code": null, "e": 2360, "s": 2353, "text": "JQuery" } ]
How to use CSS variables with TailwindCSS ?
12 May, 2021 Tailwind CSS allows users to predefined classes instead of using the pure CSS properties. We have to install the Tailwind CSS. Create the main CSS file (Global.css) which will look like the below code. Global.css: In the following code, the entire body is wrapped into a single selector. The entire body is selected by using class root or id root. @tailwind base; @tailwind components; @tailwind utilities; .root, #root, #docs-root { --primary-color: green; --secondary-color: blue; } tailwind.config.js: The following code is the content for the tailwind config file with new CSS variables. We simply want to extend the config to add new values. Javascript module.exports = { theme: { extend: { colors: { header: "var(--header)", primary: "var(--primary)", secondary: "var(--secondary)", main: "var(--main)", background: "var(--background)", accent: "var(--accent)", footer: "var(--footer)" }, }, },}; HTML code: After completing the above steps, we can use CSS variables in the following HTML code. HTML <!DOCTYPE html><head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <script src="tailwind.config.js"> </script> <link href="Global.css" rel="stylesheet"></head> <body class="text-center"><center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS flex Class</b> <div class="flex bg-green-200 p-4 mx-16 "> <div class="flex-1 bg-green-500 rounded-lg">1</div> <div class="flex-1 bg-green-500 rounded-lg">2</div> <div class="flex-1 bg-green-500 rounded-lg">3</div> </div></center></body> </html> Output: Picked Tailwind CSS CSS 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": "\n12 May, 2021" }, { "code": null, "e": 120, "s": 28, "text": "Tailwind CSS allows users to predefined classes instead of using the pure CSS properties. " }, { "code": null, "e": 233, "s": 120, "text": "We have to install the Tailwind CSS. Create the main CSS file (Global.css) which will look like the below code." }, { "code": null, "e": 379, "s": 233, "text": "Global.css: In the following code, the entire body is wrapped into a single selector. The entire body is selected by using class root or id root." }, { "code": null, "e": 521, "s": 379, "text": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n.root,\n#root,\n#docs-root {\n --primary-color: green;\n --secondary-color: blue;\n}" }, { "code": null, "e": 683, "s": 521, "text": "tailwind.config.js: The following code is the content for the tailwind config file with new CSS variables. We simply want to extend the config to add new values." }, { "code": null, "e": 694, "s": 683, "text": "Javascript" }, { "code": "module.exports = { theme: { extend: { colors: { header: \"var(--header)\", primary: \"var(--primary)\", secondary: \"var(--secondary)\", main: \"var(--main)\", background: \"var(--background)\", accent: \"var(--accent)\", footer: \"var(--footer)\" }, }, },};", "e": 1006, "s": 694, "text": null }, { "code": null, "e": 1105, "s": 1006, "text": "HTML code: After completing the above steps, we can use CSS variables in the following HTML code. " }, { "code": null, "e": 1110, "s": 1105, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <script src=\"tailwind.config.js\"> </script> <link href=\"Global.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"><center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS flex Class</b> <div class=\"flex bg-green-200 p-4 mx-16 \"> <div class=\"flex-1 bg-green-500 rounded-lg\">1</div> <div class=\"flex-1 bg-green-500 rounded-lg\">2</div> <div class=\"flex-1 bg-green-500 rounded-lg\">3</div> </div></center></body> </html>", "e": 1754, "s": 1110, "text": null }, { "code": null, "e": 1762, "s": 1754, "text": "Output:" }, { "code": null, "e": 1769, "s": 1762, "text": "Picked" }, { "code": null, "e": 1782, "s": 1769, "text": "Tailwind CSS" }, { "code": null, "e": 1786, "s": 1782, "text": "CSS" }, { "code": null, "e": 1803, "s": 1786, "text": "Web Technologies" } ]
Python program to check if the given string is IPv4 or IPv6 or Invalid
28 Jul, 2020 Given a string. The task is to check if the given string is IPv4 or IPv6 or Invalid. Examples: Input : “192.168.0.1”Output : IPv4Explanation : It is a valid IPv4 address Input : “2001:0db8:85a3:0000:0000:8a2e:0370:7334”Output : IPv6Explanation : It is a valid IPv6 address Input : “255.32.555.5”Output : InvalidExplanation : It is an invalid IPv4 address as the 3rd octet value(i.e 555) is greater 255. Input : “250.32:555.5”Output : InvalidExplanation : The given string is invalid as it consists of both : and . To implement the above problem, we will use the ipaddress module in Python. This module provides the capabilities to create, manipulate, and operate on IPv4 and IPv6 addresses and networks. Below is the implementation. from ipaddress import ip_address, IPv4Address def validIPAddress(IP: str) -> str: try: return "IPv4" if type(ip_address(IP)) is IPv4Address else "IPv6" except ValueError: return "Invalid" if __name__ == '__main__' : # Enter the Ip address Ip = "192.168.0.1" print(validIPAddress(Ip)) Ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" print(validIPAddress(Ip)) Ip = "256.32.555.5" print(validIPAddress(Ip)) Ip = "250.32:555.5" print(validIPAddress(Ip)) Output : IPv4 IPv6 Invalid Invalid Python string-programs python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jul, 2020" }, { "code": null, "e": 137, "s": 52, "text": "Given a string. The task is to check if the given string is IPv4 or IPv6 or Invalid." }, { "code": null, "e": 147, "s": 137, "text": "Examples:" }, { "code": null, "e": 222, "s": 147, "text": "Input : “192.168.0.1”Output : IPv4Explanation : It is a valid IPv4 address" }, { "code": null, "e": 325, "s": 222, "text": "Input : “2001:0db8:85a3:0000:0000:8a2e:0370:7334”Output : IPv6Explanation : It is a valid IPv6 address" }, { "code": null, "e": 455, "s": 325, "text": "Input : “255.32.555.5”Output : InvalidExplanation : It is an invalid IPv4 address as the 3rd octet value(i.e 555) is greater 255." }, { "code": null, "e": 566, "s": 455, "text": "Input : “250.32:555.5”Output : InvalidExplanation : The given string is invalid as it consists of both : and ." }, { "code": null, "e": 756, "s": 566, "text": "To implement the above problem, we will use the ipaddress module in Python. This module provides the capabilities to create, manipulate, and operate on IPv4 and IPv6 addresses and networks." }, { "code": null, "e": 785, "s": 756, "text": "Below is the implementation." }, { "code": "from ipaddress import ip_address, IPv4Address def validIPAddress(IP: str) -> str: try: return \"IPv4\" if type(ip_address(IP)) is IPv4Address else \"IPv6\" except ValueError: return \"Invalid\" if __name__ == '__main__' : # Enter the Ip address Ip = \"192.168.0.1\" print(validIPAddress(Ip)) Ip = \"2001:0db8:85a3:0000:0000:8a2e:0370:7334\" print(validIPAddress(Ip)) Ip = \"256.32.555.5\" print(validIPAddress(Ip)) Ip = \"250.32:555.5\" print(validIPAddress(Ip))", "e": 1304, "s": 785, "text": null }, { "code": null, "e": 1313, "s": 1304, "text": "Output :" }, { "code": null, "e": 1339, "s": 1313, "text": "IPv4\nIPv6\nInvalid\nInvalid" }, { "code": null, "e": 1362, "s": 1339, "text": "Python string-programs" }, { "code": null, "e": 1377, "s": 1362, "text": "python-utility" }, { "code": null, "e": 1384, "s": 1377, "text": "Python" }, { "code": null, "e": 1400, "s": 1384, "text": "Python Programs" } ]
Most frequent element in an array
15 Jul, 2022 Given an array, find the most frequent element in it. If there are multiple elements that appear a maximum number of times, print any one of them. Examples: Input : arr[] = {1, 3, 2, 1, 4, 1}Output : 1Explanation: 1 appears three times in array which is maximum frequency. Input : arr[] = {10, 20, 10, 20, 30, 20, 20}Output : 20 A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far. C++ Java C# // CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int *arr, int n) { // code here int maxcount=0; int element_having_max_freq; for(int i=0;i<n;i++) { int count=0; for(int j=0;j<n;j++) { if(arr[i] == arr[j]) count++; } if(count>maxcount) { maxcount=count; element_having_max_freq = arr[i]; } } return element_having_max_freq;} // Driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;} // This code is contributed by Arpit Jain public class GFG{ // Java program to find the most frequent element // in an array. public static int mostFrequent(int[] arr, int n) { int maxcount = 0; int element_having_max_freq = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxcount) { maxcount = count; element_having_max_freq = arr[i]; } } return element_having_max_freq; } // Driver program public static void main(String[] args) { int[] arr = { 40, 50, 30, 40, 50, 30, 30 }; int n = arr.length; System.out.print(mostFrequent(arr, n)); }} // This code is contributed by Aarti_Rathi // C# program to find the most frequent element// in an arrayusing System;public class GFG{ // C# program to find the most frequent element // in an array. public static int mostFrequent(int[] arr, int n) { int maxcount = 0; int element_having_max_freq = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxcount) { maxcount = count; element_having_max_freq = arr[i]; } } return element_having_max_freq; } // Driver program public static void Main(String[] args) { int[] arr = { 40, 50, 30, 40, 50, 30, 30 }; int n = arr.Length; Console.Write(mostFrequent(arr, n)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403) 30 The time complexity of this solution is O(n2) since 2 loops are running from i=0 to i=n we can improve its time complexity by taking a visited array and skipping numbers for which we already calculated the frequency. A better solution is to do the sorting. We first sort the array, then linearly traverse the array. C++ C Java Python3 C# PHP Javascript // CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int arr[], int n){ // Sort the array sort(arr, arr + n); // Find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res;} // Driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // CPP program to find the most frequent element// in an array.#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} int mostFrequent(int arr[], int n){ // Sort the array qsort(arr, n, sizeof(int), cmpfunc); // find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res;} // driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", mostFrequent(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to find the most frequent element// in an arrayimport java.util.*; class GFG { static int mostFrequent(int arr[], int n) { // Sort the array Arrays.sort(arr); // find the max frequency using linear traversal int max_count = 1, res = arr[0]; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver program public static void main(String[] args) { int arr[] = { 40,50,30,40,50,30,30}; int n = arr.length; System.out.println(mostFrequent(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program to find the most# frequent element in an array. def mostFrequent(arr, n): # Sort the array arr.sort() # find the max frequency using # linear traversal max_count = 1 res = arr[0] curr_count = 1 for i in range(1, n): if (arr[i] == arr[i - 1]): curr_count += 1 else: curr_count = 1 # If last element is most frequent if (curr_count > max_count): max_count = curr_count res = arr[i - 1] return res # Driver Codearr = [40,50,30,40,50,30,30]n = len(arr)print(mostFrequent(arr, n)) # This code is contributed by Smitha Dinesh Semwal. // C# program to find the most// frequent element in an arrayusing System; class GFG { static int mostFrequent(int[] arr, int n) { // Sort the array Array.Sort(arr); // find the max frequency using // linear traversal int max_count = 1, res = arr[0]; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; // If last element is most frequent if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver code public static void Main() { int[] arr = {40,50,30,40,50,30,30 }; int n = arr.Length; Console.WriteLine(mostFrequent(arr, n)); }} // This code is contributed by vt_m. <?php// PHP program to find the// most frequent element// in an array. function mostFrequent( $arr, $n){ // Sort the array sort($arr); sort($arr , $n); // find the max frequency // using linear traversal $max_count = 1; $res = $arr[0]; $curr_count = 1; for ($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) $curr_count++; else $curr_count = 1; if ($curr_count > $max_count) { $max_count = $curr_count; $res = $arr[$i - 1]; } } return $res;} // Driver Code{ $arr = array(40,50,30,40,50,30,30); $n = sizeof($arr) / sizeof($arr[0]); echo mostFrequent($arr, $n); return 0;} // This code is contributed by nitin mittal?> <script>// JavaScript program to find the most frequent element//in an array function mostFrequent(arr, n) { // Sort the array arr.sort(); // find the max frequency using linear // traversal let max_count = 1, res = arr[0]; let curr_count = 1; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver Code let arr = [40,50,30,40,50,30,30]; let n = arr.length; document.write(mostFrequent(arr,n)); // This code is contributed by code_hunt.</script> 30 Time Complexity: O(nlog(n)) Auxiliary Space: O(1) An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key-value pairs. Finally, we traverse the hash table and print the key with the maximum value. C++ Java Python3 C# Javascript // CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int arr[], int n){ // Insert all elements in hash. unordered_map<int, int> hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the max frequency int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } return res;} // driver programint main(){ int arr[] = {40,50,30,40,50,30,30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;} //Java program to find the most frequent element//in an arrayimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry; class GFG { static int mostFrequent(int arr[], int n) { // Insert all elements in hash Map<Integer, Integer> hp = new HashMap<Integer, Integer>(); for(int i = 0; i < n; i++) { int key = arr[i]; if(hp.containsKey(key)) { int freq = hp.get(key); freq++; hp.put(key, freq); } else { hp.put(key, 1); } } // find max frequency. int max_count = 0, res = -1; for(Entry<Integer, Integer> val : hp.entrySet()) { if (max_count < val.getValue()) { res = val.getKey(); max_count = val.getValue(); } } return res; } // Driver code public static void main (String[] args) { int arr[] = {40,50,30,40,50,30,30}; int n = arr.length; System.out.println(mostFrequent(arr, n)); }} // This code is contributed by Akash Singh. # Python3 program to find the most# frequent element in an array.import math as mt def mostFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency max_count = 0 res = -1 for i in Hash: if (max_count < Hash[i]): res = i max_count = Hash[i] return res # Driver Codearr = [ 40,50,30,40,50,30,30]n = len(arr)print(mostFrequent(arr, n)) # This code is contributed# by Mohit kumar 29 // C# program to find the most// frequent element in an arrayusing System;using System.Collections.Generic; class GFG{ static int mostFrequent(int []arr, int n) { // Insert all elements in hash Dictionary<int, int> hp = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { int key = arr[i]; if(hp.ContainsKey(key)) { int freq = hp[key]; freq++; hp[key] = freq; } else hp.Add(key, 1); } // find max frequency. int min_count = 0, res = -1; foreach (KeyValuePair<int, int> pair in hp) { if (min_count < pair.Value) { res = pair.Key; min_count = pair.Value; } } return res; } // Driver code static void Main () { int []arr = new int[]{40,50,30,40,50,30,30}; int n = arr.Length; Console.Write(mostFrequent(arr, n)); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // Javascript program to find// the most frequent element// in an array. function mostFrequent(arr, n){ // Insert all elements in hash. var hash = new Map(); for (var i = 0; i < n; i++) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1) } // find the max frequency var max_count = 0, res = -1; hash.forEach((value,key) => { if (max_count < value) { res = key; max_count = value; } }); return res;} // driver programvar arr = [40,50,30,40,50,30,30];var n = arr.length;document.write( mostFrequent(arr, n)); </script> 30 Time Complexity: O(n) Auxiliary Space: O(n) An efficient solution to this problem can be to solve this problem by Moore’s voting Algorithm. NOTE: THE ABOVE VOTING ALGORITHM ONLY WORKS WHEN THE MAXIMUM OCCURRING ELEMENT IS MORE THAN (SIZEOFARRAY/2) TIMES; In this method, we will find the maximum occurred integer by counting the votes a number has. C++ Java Python3 C# Javascript #include <iostream>using namespace std; int maxFreq(int *arr, int n) { //using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} int main(){ int arr[] = {40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } cout <<"Element " << maxFreq(arr , n) << " occurs " << count << " times" << endl;; return 0; //This code is contributed by Ashish Kumar Shakya} import java.io.*;class GFG{ static int maxFreq(int []arr, int n){ // using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} // Driver codepublic static void main (String[] args) { int arr[] = {40,50,30,40,50,30,30}; int n = arr.length; int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } System.out.println("Element " +maxFreq(arr , n) +" occurs " +count +" times" );} } // This code is contributed by shivanisinghss2110 def maxFreq(arr, n): # Using moore's voting algorithm res = 0 count = 1 for i in range(1, n): if (arr[i] == arr[res]): count += 1 else: count -= 1 if (count == 0): res = i count = 1 return arr[res] # Driver codearr = [ 40, 50, 30, 40, 50, 30, 30 ]n = len(arr)freq = maxFreq(arr, n)count = 0 for i in range (n): if(arr[i] == freq): count += 1 print("Element ", maxFreq(arr , n), " occurs ", count, " times") # This code is contributed by shivanisinghss2110 using System;class GFG{ static int maxFreq(int []arr, int n){ // using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} // Driver codepublic static void Main (String[] args) { int []arr = {40,50,30,40,50,30,30}; int n = arr.Length; int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } Console.Write("Element " +maxFreq(arr , n) +" occurs " +count +" times" );} } // This code is contributed by shivanisinghss2110 <script> function maxFreq(arr, n) { //using moore's voting algorithm var res = 0; var count = 1; for (var i = 1; i < n; i++) { if (arr[i] === arr[res]) { count++; } else { count--; } if (count === 0) { res = i; count = 1; } } return arr[res]; } var arr = [40, 50, 30, 40, 50, 30, 30]; var n = arr.length; var freq = maxFreq(arr, n); var count = 0; for (var i = 0; i < n; i++) { if (arr[i] === freq) { count++; } } document.write( "Element " + maxFreq(arr, n) + " occurs " + count + " times" + "<br>" ); </script> Element 30 occurs 3 times Time Complexity: O(n)Auxiliary Space: O(1) vt_m nitin mittal dipesh_jain manishshaw1 mohit kumar 29 code_hunt rutvik_56 ashishskkumar321 jayadeepbose rdtank saurabh1990aror noboruwatanabe shivanisinghss2110 adityakumar129 kalaiabster avtarkumar719 111arpit1 codewithmini Hash Searching Sorting Searching Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2022" }, { "code": null, "e": 199, "s": 52, "text": "Given an array, find the most frequent element in it. If there are multiple elements that appear a maximum number of times, print any one of them." }, { "code": null, "e": 210, "s": 199, "text": "Examples: " }, { "code": null, "e": 326, "s": 210, "text": "Input : arr[] = {1, 3, 2, 1, 4, 1}Output : 1Explanation: 1 appears three times in array which is maximum frequency." }, { "code": null, "e": 382, "s": 326, "text": "Input : arr[] = {10, 20, 10, 20, 30, 20, 20}Output : 20" }, { "code": null, "e": 566, "s": 382, "text": "A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far. " }, { "code": null, "e": 570, "s": 566, "text": "C++" }, { "code": null, "e": 575, "s": 570, "text": "Java" }, { "code": null, "e": 578, "s": 575, "text": "C#" }, { "code": "// CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int *arr, int n) { // code here int maxcount=0; int element_having_max_freq; for(int i=0;i<n;i++) { int count=0; for(int j=0;j<n;j++) { if(arr[i] == arr[j]) count++; } if(count>maxcount) { maxcount=count; element_having_max_freq = arr[i]; } } return element_having_max_freq;} // Driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;} // This code is contributed by Arpit Jain", "e": 1235, "s": 578, "text": null }, { "code": "public class GFG{ // Java program to find the most frequent element // in an array. public static int mostFrequent(int[] arr, int n) { int maxcount = 0; int element_having_max_freq = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxcount) { maxcount = count; element_having_max_freq = arr[i]; } } return element_having_max_freq; } // Driver program public static void main(String[] args) { int[] arr = { 40, 50, 30, 40, 50, 30, 30 }; int n = arr.length; System.out.print(mostFrequent(arr, n)); }} // This code is contributed by Aarti_Rathi", "e": 1957, "s": 1235, "text": null }, { "code": "// C# program to find the most frequent element// in an arrayusing System;public class GFG{ // C# program to find the most frequent element // in an array. public static int mostFrequent(int[] arr, int n) { int maxcount = 0; int element_having_max_freq = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxcount) { maxcount = count; element_having_max_freq = arr[i]; } } return element_having_max_freq; } // Driver program public static void Main(String[] args) { int[] arr = { 40, 50, 30, 40, 50, 30, 30 }; int n = arr.Length; Console.Write(mostFrequent(arr, n)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 2766, "s": 1957, "text": null }, { "code": null, "e": 2769, "s": 2766, "text": "30" }, { "code": null, "e": 2987, "s": 2769, "text": "The time complexity of this solution is O(n2) since 2 loops are running from i=0 to i=n we can improve its time complexity by taking a visited array and skipping numbers for which we already calculated the frequency." }, { "code": null, "e": 3087, "s": 2987, "text": "A better solution is to do the sorting. We first sort the array, then linearly traverse the array. " }, { "code": null, "e": 3093, "s": 3089, "text": "C++" }, { "code": null, "e": 3095, "s": 3093, "text": "C" }, { "code": null, "e": 3100, "s": 3095, "text": "Java" }, { "code": null, "e": 3108, "s": 3100, "text": "Python3" }, { "code": null, "e": 3111, "s": 3108, "text": "C#" }, { "code": null, "e": 3115, "s": 3111, "text": "PHP" }, { "code": null, "e": 3126, "s": 3115, "text": "Javascript" }, { "code": "// CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int arr[], int n){ // Sort the array sort(arr, arr + n); // Find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res;} // Driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3906, "s": 3126, "text": null }, { "code": "// CPP program to find the most frequent element// in an array.#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} int mostFrequent(int arr[], int n){ // Sort the array qsort(arr, n, sizeof(int), cmpfunc); // find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res;} // driver programint main(){ int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", mostFrequent(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4782, "s": 3906, "text": null }, { "code": "// Java program to find the most frequent element// in an arrayimport java.util.*; class GFG { static int mostFrequent(int arr[], int n) { // Sort the array Arrays.sort(arr); // find the max frequency using linear traversal int max_count = 1, res = arr[0]; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver program public static void main(String[] args) { int arr[] = { 40,50,30,40,50,30,30}; int n = arr.length; System.out.println(mostFrequent(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 5669, "s": 4782, "text": null }, { "code": "# Python3 program to find the most# frequent element in an array. def mostFrequent(arr, n): # Sort the array arr.sort() # find the max frequency using # linear traversal max_count = 1 res = arr[0] curr_count = 1 for i in range(1, n): if (arr[i] == arr[i - 1]): curr_count += 1 else: curr_count = 1 # If last element is most frequent if (curr_count > max_count): max_count = curr_count res = arr[i - 1] return res # Driver Codearr = [40,50,30,40,50,30,30]n = len(arr)print(mostFrequent(arr, n)) # This code is contributed by Smitha Dinesh Semwal.", "e": 6322, "s": 5669, "text": null }, { "code": "// C# program to find the most// frequent element in an arrayusing System; class GFG { static int mostFrequent(int[] arr, int n) { // Sort the array Array.Sort(arr); // find the max frequency using // linear traversal int max_count = 1, res = arr[0]; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; // If last element is most frequent if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver code public static void Main() { int[] arr = {40,50,30,40,50,30,30 }; int n = arr.Length; Console.WriteLine(mostFrequent(arr, n)); }} // This code is contributed by vt_m.", "e": 7220, "s": 6322, "text": null }, { "code": "<?php// PHP program to find the// most frequent element// in an array. function mostFrequent( $arr, $n){ // Sort the array sort($arr); sort($arr , $n); // find the max frequency // using linear traversal $max_count = 1; $res = $arr[0]; $curr_count = 1; for ($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) $curr_count++; else $curr_count = 1; if ($curr_count > $max_count) { $max_count = $curr_count; $res = $arr[$i - 1]; } } return $res;} // Driver Code{ $arr = array(40,50,30,40,50,30,30); $n = sizeof($arr) / sizeof($arr[0]); echo mostFrequent($arr, $n); return 0;} // This code is contributed by nitin mittal?>", "e": 7994, "s": 7220, "text": null }, { "code": "<script>// JavaScript program to find the most frequent element//in an array function mostFrequent(arr, n) { // Sort the array arr.sort(); // find the max frequency using linear // traversal let max_count = 1, res = arr[0]; let curr_count = 1; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver Code let arr = [40,50,30,40,50,30,30]; let n = arr.length; document.write(mostFrequent(arr,n)); // This code is contributed by code_hunt.</script>", "e": 8854, "s": 7994, "text": null }, { "code": null, "e": 8857, "s": 8854, "text": "30" }, { "code": null, "e": 8907, "s": 8857, "text": "Time Complexity: O(nlog(n)) Auxiliary Space: O(1)" }, { "code": null, "e": 9117, "s": 8907, "text": "An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key-value pairs. Finally, we traverse the hash table and print the key with the maximum value. " }, { "code": null, "e": 9121, "s": 9117, "text": "C++" }, { "code": null, "e": 9126, "s": 9121, "text": "Java" }, { "code": null, "e": 9134, "s": 9126, "text": "Python3" }, { "code": null, "e": 9137, "s": 9134, "text": "C#" }, { "code": null, "e": 9148, "s": 9137, "text": "Javascript" }, { "code": "// CPP program to find the most frequent element// in an array.#include <bits/stdc++.h>using namespace std; int mostFrequent(int arr[], int n){ // Insert all elements in hash. unordered_map<int, int> hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the max frequency int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } return res;} // driver programint main(){ int arr[] = {40,50,30,40,50,30,30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0;}", "e": 9783, "s": 9148, "text": null }, { "code": "//Java program to find the most frequent element//in an arrayimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry; class GFG { static int mostFrequent(int arr[], int n) { // Insert all elements in hash Map<Integer, Integer> hp = new HashMap<Integer, Integer>(); for(int i = 0; i < n; i++) { int key = arr[i]; if(hp.containsKey(key)) { int freq = hp.get(key); freq++; hp.put(key, freq); } else { hp.put(key, 1); } } // find max frequency. int max_count = 0, res = -1; for(Entry<Integer, Integer> val : hp.entrySet()) { if (max_count < val.getValue()) { res = val.getKey(); max_count = val.getValue(); } } return res; } // Driver code public static void main (String[] args) { int arr[] = {40,50,30,40,50,30,30}; int n = arr.length; System.out.println(mostFrequent(arr, n)); }} // This code is contributed by Akash Singh.", "e": 11026, "s": 9783, "text": null }, { "code": "# Python3 program to find the most# frequent element in an array.import math as mt def mostFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency max_count = 0 res = -1 for i in Hash: if (max_count < Hash[i]): res = i max_count = Hash[i] return res # Driver Codearr = [ 40,50,30,40,50,30,30]n = len(arr)print(mostFrequent(arr, n)) # This code is contributed# by Mohit kumar 29", "e": 11622, "s": 11026, "text": null }, { "code": "// C# program to find the most// frequent element in an arrayusing System;using System.Collections.Generic; class GFG{ static int mostFrequent(int []arr, int n) { // Insert all elements in hash Dictionary<int, int> hp = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { int key = arr[i]; if(hp.ContainsKey(key)) { int freq = hp[key]; freq++; hp[key] = freq; } else hp.Add(key, 1); } // find max frequency. int min_count = 0, res = -1; foreach (KeyValuePair<int, int> pair in hp) { if (min_count < pair.Value) { res = pair.Key; min_count = pair.Value; } } return res; } // Driver code static void Main () { int []arr = new int[]{40,50,30,40,50,30,30}; int n = arr.Length; Console.Write(mostFrequent(arr, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 12802, "s": 11622, "text": null }, { "code": "<script> // Javascript program to find// the most frequent element// in an array. function mostFrequent(arr, n){ // Insert all elements in hash. var hash = new Map(); for (var i = 0; i < n; i++) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1) } // find the max frequency var max_count = 0, res = -1; hash.forEach((value,key) => { if (max_count < value) { res = key; max_count = value; } }); return res;} // driver programvar arr = [40,50,30,40,50,30,30];var n = arr.length;document.write( mostFrequent(arr, n)); </script>", "e": 13475, "s": 12802, "text": null }, { "code": null, "e": 13478, "s": 13475, "text": "30" }, { "code": null, "e": 13522, "s": 13478, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 13618, "s": 13522, "text": "An efficient solution to this problem can be to solve this problem by Moore’s voting Algorithm." }, { "code": null, "e": 13733, "s": 13618, "text": "NOTE: THE ABOVE VOTING ALGORITHM ONLY WORKS WHEN THE MAXIMUM OCCURRING ELEMENT IS MORE THAN (SIZEOFARRAY/2) TIMES;" }, { "code": null, "e": 13827, "s": 13733, "text": "In this method, we will find the maximum occurred integer by counting the votes a number has." }, { "code": null, "e": 13831, "s": 13827, "text": "C++" }, { "code": null, "e": 13836, "s": 13831, "text": "Java" }, { "code": null, "e": 13844, "s": 13836, "text": "Python3" }, { "code": null, "e": 13847, "s": 13844, "text": "C#" }, { "code": null, "e": 13858, "s": 13847, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int maxFreq(int *arr, int n) { //using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} int main(){ int arr[] = {40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } cout <<\"Element \" << maxFreq(arr , n) << \" occurs \" << count << \" times\" << endl;; return 0; //This code is contributed by Ashish Kumar Shakya}", "e": 14642, "s": 13858, "text": null }, { "code": "import java.io.*;class GFG{ static int maxFreq(int []arr, int n){ // using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} // Driver codepublic static void main (String[] args) { int arr[] = {40,50,30,40,50,30,30}; int n = arr.length; int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } System.out.println(\"Element \" +maxFreq(arr , n) +\" occurs \" +count +\" times\" );} } // This code is contributed by shivanisinghss2110", "e": 15441, "s": 14642, "text": null }, { "code": "def maxFreq(arr, n): # Using moore's voting algorithm res = 0 count = 1 for i in range(1, n): if (arr[i] == arr[res]): count += 1 else: count -= 1 if (count == 0): res = i count = 1 return arr[res] # Driver codearr = [ 40, 50, 30, 40, 50, 30, 30 ]n = len(arr)freq = maxFreq(arr, n)count = 0 for i in range (n): if(arr[i] == freq): count += 1 print(\"Element \", maxFreq(arr , n), \" occurs \", count, \" times\") # This code is contributed by shivanisinghss2110", "e": 16037, "s": 15441, "text": null }, { "code": "using System;class GFG{ static int maxFreq(int []arr, int n){ // using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res];} // Driver codepublic static void Main (String[] args) { int []arr = {40,50,30,40,50,30,30}; int n = arr.Length; int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } Console.Write(\"Element \" +maxFreq(arr , n) +\" occurs \" +count +\" times\" );} } // This code is contributed by shivanisinghss2110", "e": 16827, "s": 16037, "text": null }, { "code": "<script> function maxFreq(arr, n) { //using moore's voting algorithm var res = 0; var count = 1; for (var i = 1; i < n; i++) { if (arr[i] === arr[res]) { count++; } else { count--; } if (count === 0) { res = i; count = 1; } } return arr[res]; } var arr = [40, 50, 30, 40, 50, 30, 30]; var n = arr.length; var freq = maxFreq(arr, n); var count = 0; for (var i = 0; i < n; i++) { if (arr[i] === freq) { count++; } } document.write( \"Element \" + maxFreq(arr, n) + \" occurs \" + count + \" times\" + \"<br>\" ); </script>", "e": 17568, "s": 16827, "text": null }, { "code": null, "e": 17594, "s": 17568, "text": "Element 30 occurs 3 times" }, { "code": null, "e": 17637, "s": 17594, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 17642, "s": 17637, "text": "vt_m" }, { "code": null, "e": 17655, "s": 17642, "text": "nitin mittal" }, { "code": null, "e": 17667, "s": 17655, "text": "dipesh_jain" }, { "code": null, "e": 17679, "s": 17667, "text": "manishshaw1" }, { "code": null, "e": 17694, "s": 17679, "text": "mohit kumar 29" }, { "code": null, "e": 17704, "s": 17694, "text": "code_hunt" }, { "code": null, "e": 17714, "s": 17704, "text": "rutvik_56" }, { "code": null, "e": 17731, "s": 17714, "text": "ashishskkumar321" }, { "code": null, "e": 17744, "s": 17731, "text": "jayadeepbose" }, { "code": null, "e": 17751, "s": 17744, "text": "rdtank" }, { "code": null, "e": 17767, "s": 17751, "text": "saurabh1990aror" }, { "code": null, "e": 17782, "s": 17767, "text": "noboruwatanabe" }, { "code": null, "e": 17801, "s": 17782, "text": "shivanisinghss2110" }, { "code": null, "e": 17816, "s": 17801, "text": "adityakumar129" }, { "code": null, "e": 17828, "s": 17816, "text": "kalaiabster" }, { "code": null, "e": 17842, "s": 17828, "text": "avtarkumar719" }, { "code": null, "e": 17852, "s": 17842, "text": "111arpit1" }, { "code": null, "e": 17865, "s": 17852, "text": "codewithmini" }, { "code": null, "e": 17870, "s": 17865, "text": "Hash" }, { "code": null, "e": 17880, "s": 17870, "text": "Searching" }, { "code": null, "e": 17888, "s": 17880, "text": "Sorting" }, { "code": null, "e": 17898, "s": 17888, "text": "Searching" }, { "code": null, "e": 17903, "s": 17898, "text": "Hash" }, { "code": null, "e": 17911, "s": 17903, "text": "Sorting" } ]
Extended Binary Tree
09 Apr, 2022 Extended binary tree is a type of binary tree in which all the null sub tree of the original tree are replaced with special nodes called external nodes whereas other nodes are called internal nodes Here the circles represent the internal nodes and the boxes represent the external nodes.Properties of External binary tree The nodes from the original tree are internal nodes and the special nodes are external nodes.All external nodes are leaf nodes and the internal nodes are non-leaf nodes.Every internal node has exactly two children and every external node is a leaf. It displays the result which is a complete binary tree. The nodes from the original tree are internal nodes and the special nodes are external nodes. All external nodes are leaf nodes and the internal nodes are non-leaf nodes. Every internal node has exactly two children and every external node is a leaf. It displays the result which is a complete binary tree. Uses: 1. It is useful for representation in algebraic expressions. Below is an example of making an extended binary tree in C++ by making all the external nodes as ‘-1’ C++ Java C# Javascript Python3 // C++ program to make an extended binary tree#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to// create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function for inorder traversalvoid traverse(Node* root){ if (root != NULL) { traverse(root->left); cout << root->key << " "; traverse(root->right); } else { // Making external nodes root = newNode(-1); cout << root->key << " "; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(5); root->right->right = newNode(4); traverse(root); return 0;} // Java program to make an extended binary treeclass GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function for inorder traversalstatic void traverse(Node root){ if (root != null) { traverse(root.left); System.out.print(root.key + " "); traverse(root.right); } else { // Making external nodes root = newNode(-1); System.out.print(root.key + " "); }} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(5); root.right.right = newNode(4); traverse(root);}} // This code is contributed by Arnab Kundu // C# program to make an extended binary treeusing System; class GFG{ // A Tree node public class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Function for inorder traversal static void traverse(Node root) { if (root != null) { traverse(root.left); Console.Write(root.key + " "); traverse(root.right); } else { // Making external nodes root = newNode(-1); Console.Write(root.key + " "); } } // Driver code public static void Main() { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(5); root.right.right = newNode(4); traverse(root); }} // This code is contributed by AnkitRai01 <script> // Javascript program to make an extended binary tree // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function for inorder traversalfunction traverse(root){ if (root != null) { traverse(root.left); document.write(root.key + " "); traverse(root.right); } else { // Making external nodes root = newNode(-1); document.write(root.key + " "); }} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(5);root.right.right = newNode(4);traverse(root); </script> # Python 3 program to make an extended binary tree # A Tree nodeclass Node : def __init__(self): self.key=-1 self.left=self.right=None # Utility function to# create a new nodedef newNode(key): temp = Node() temp.key = key temp.left = temp.right = None return temp # Function for inorder traversaldef traverse(root): if (root != None) : traverse(root.left) print(root.key,end=" ") traverse(root.right) else : # Making external nodes root = newNode(-1) print(root.key,end=" ") # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(5) root.right.right = newNode(4) traverse(root) print()# This code was added by Amartya Ghosh -1 5 -1 2 -1 1 -1 3 -1 4 -1 Time Complexity: O(N). Auxiliary Space: O(N). Application of extended binary tree: Calculate weighted path length: It is used to calculate total path length in case of weighted tree. Calculate weighted path length: It is used to calculate total path length in case of weighted tree. Here, the sum of total weights is already calculated and stored in the external nodes and thus makes it very easier to calculate the total path length of a tree with given weights. The same technique can be used to update routing tables in a network.To convert binary tree in Complete binary tree: The above-given tree having removed all the external nodes, is not a complete binary tree. To introduce any tree as complete tree, external nodes are added onto it. Heap is a great example of a complete binary tree and thus each binary tree can be expressed as heap if external nodes are added to it. Here, the sum of total weights is already calculated and stored in the external nodes and thus makes it very easier to calculate the total path length of a tree with given weights. The same technique can be used to update routing tables in a network. To convert binary tree in Complete binary tree: The above-given tree having removed all the external nodes, is not a complete binary tree. To introduce any tree as complete tree, external nodes are added onto it. Heap is a great example of a complete binary tree and thus each binary tree can be expressed as heap if external nodes are added to it. andrew1234 ankthon importantly pankajsharmagfg amartyaghoshgfg s29962590 Binary Tree Data Structures Tree Data Structures Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Apr, 2022" }, { "code": null, "e": 253, "s": 53, "text": "Extended binary tree is a type of binary tree in which all the null sub tree of the original tree are replaced with special nodes called external nodes whereas other nodes are called internal nodes " }, { "code": null, "e": 379, "s": 253, "text": "Here the circles represent the internal nodes and the boxes represent the external nodes.Properties of External binary tree " }, { "code": null, "e": 684, "s": 379, "text": "The nodes from the original tree are internal nodes and the special nodes are external nodes.All external nodes are leaf nodes and the internal nodes are non-leaf nodes.Every internal node has exactly two children and every external node is a leaf. It displays the result which is a complete binary tree." }, { "code": null, "e": 778, "s": 684, "text": "The nodes from the original tree are internal nodes and the special nodes are external nodes." }, { "code": null, "e": 855, "s": 778, "text": "All external nodes are leaf nodes and the internal nodes are non-leaf nodes." }, { "code": null, "e": 991, "s": 855, "text": "Every internal node has exactly two children and every external node is a leaf. It displays the result which is a complete binary tree." }, { "code": null, "e": 997, "s": 991, "text": "Uses:" }, { "code": null, "e": 1059, "s": 997, "text": "1. It is useful for representation in algebraic expressions. " }, { "code": null, "e": 1163, "s": 1059, "text": "Below is an example of making an extended binary tree in C++ by making all the external nodes as ‘-1’ " }, { "code": null, "e": 1167, "s": 1163, "text": "C++" }, { "code": null, "e": 1172, "s": 1167, "text": "Java" }, { "code": null, "e": 1175, "s": 1172, "text": "C#" }, { "code": null, "e": 1186, "s": 1175, "text": "Javascript" }, { "code": null, "e": 1194, "s": 1186, "text": "Python3" }, { "code": "// C++ program to make an extended binary tree#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to// create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function for inorder traversalvoid traverse(Node* root){ if (root != NULL) { traverse(root->left); cout << root->key << \" \"; traverse(root->right); } else { // Making external nodes root = newNode(-1); cout << root->key << \" \"; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(5); root->right->right = newNode(4); traverse(root); return 0;}", "e": 2029, "s": 1194, "text": null }, { "code": "// Java program to make an extended binary treeclass GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function for inorder traversalstatic void traverse(Node root){ if (root != null) { traverse(root.left); System.out.print(root.key + \" \"); traverse(root.right); } else { // Making external nodes root = newNode(-1); System.out.print(root.key + \" \"); }} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(5); root.right.right = newNode(4); traverse(root);}} // This code is contributed by Arnab Kundu", "e": 2910, "s": 2029, "text": null }, { "code": "// C# program to make an extended binary treeusing System; class GFG{ // A Tree node public class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Function for inorder traversal static void traverse(Node root) { if (root != null) { traverse(root.left); Console.Write(root.key + \" \"); traverse(root.right); } else { // Making external nodes root = newNode(-1); Console.Write(root.key + \" \"); } } // Driver code public static void Main() { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(5); root.right.right = newNode(4); traverse(root); }} // This code is contributed by AnkitRai01", "e": 3981, "s": 2910, "text": null }, { "code": "<script> // Javascript program to make an extended binary tree // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function for inorder traversalfunction traverse(root){ if (root != null) { traverse(root.left); document.write(root.key + \" \"); traverse(root.right); } else { // Making external nodes root = newNode(-1); document.write(root.key + \" \"); }} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(5);root.right.right = newNode(4);traverse(root); </script>", "e": 4806, "s": 3981, "text": null }, { "code": "# Python 3 program to make an extended binary tree # A Tree nodeclass Node : def __init__(self): self.key=-1 self.left=self.right=None # Utility function to# create a new nodedef newNode(key): temp = Node() temp.key = key temp.left = temp.right = None return temp # Function for inorder traversaldef traverse(root): if (root != None) : traverse(root.left) print(root.key,end=\" \") traverse(root.right) else : # Making external nodes root = newNode(-1) print(root.key,end=\" \") # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(5) root.right.right = newNode(4) traverse(root) print()# This code was added by Amartya Ghosh", "e": 5618, "s": 4806, "text": null }, { "code": null, "e": 5646, "s": 5618, "text": "-1 5 -1 2 -1 1 -1 3 -1 4 -1" }, { "code": null, "e": 5734, "s": 5648, "text": "Time Complexity: O(N). Auxiliary Space: O(N). Application of extended binary tree: " }, { "code": null, "e": 5834, "s": 5734, "text": "Calculate weighted path length: It is used to calculate total path length in case of weighted tree." }, { "code": null, "e": 5934, "s": 5834, "text": "Calculate weighted path length: It is used to calculate total path length in case of weighted tree." }, { "code": null, "e": 6533, "s": 5934, "text": "Here, the sum of total weights is already calculated and stored in the external nodes and thus makes it very easier to calculate the total path length of a tree with given weights. The same technique can be used to update routing tables in a network.To convert binary tree in Complete binary tree: The above-given tree having removed all the external nodes, is not a complete binary tree. To introduce any tree as complete tree, external nodes are added onto it. Heap is a great example of a complete binary tree and thus each binary tree can be expressed as heap if external nodes are added to it." }, { "code": null, "e": 6784, "s": 6533, "text": "Here, the sum of total weights is already calculated and stored in the external nodes and thus makes it very easier to calculate the total path length of a tree with given weights. The same technique can be used to update routing tables in a network." }, { "code": null, "e": 7133, "s": 6784, "text": "To convert binary tree in Complete binary tree: The above-given tree having removed all the external nodes, is not a complete binary tree. To introduce any tree as complete tree, external nodes are added onto it. Heap is a great example of a complete binary tree and thus each binary tree can be expressed as heap if external nodes are added to it." }, { "code": null, "e": 7144, "s": 7133, "text": "andrew1234" }, { "code": null, "e": 7152, "s": 7144, "text": "ankthon" }, { "code": null, "e": 7164, "s": 7152, "text": "importantly" }, { "code": null, "e": 7180, "s": 7164, "text": "pankajsharmagfg" }, { "code": null, "e": 7196, "s": 7180, "text": "amartyaghoshgfg" }, { "code": null, "e": 7206, "s": 7196, "text": "s29962590" }, { "code": null, "e": 7218, "s": 7206, "text": "Binary Tree" }, { "code": null, "e": 7234, "s": 7218, "text": "Data Structures" }, { "code": null, "e": 7239, "s": 7234, "text": "Tree" }, { "code": null, "e": 7255, "s": 7239, "text": "Data Structures" }, { "code": null, "e": 7260, "s": 7255, "text": "Tree" } ]
Fibonacci Number modulo M and Pisano Period
29 Mar, 2022 Given two number N and M. The task is to find the N-th fibonacci number mod M.In general let FN be the N-th fibonacci number then the output should be FN % M. The Fibonacci sequence is a series of numbers in which each no. is the sum of two preceding nos. It is defined by the recurrence relation: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 These nos. are in the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...Here N can be large. Examples: Input: N = 438, M = 900 Output: 44 Input: N = 1548276540, M = 235 Output: 185 Approach: However, for such values of N, a simple recursive approach to keep calculating N Fibonacci numbers with a time complexity of O(2N) should be avoided. Even an iterative or a Dynamic Programming approach with an algorithm looping for N iterations will not be time-efficient.This problem can be solved using the properties of Pisano Period. For a given value of N and M >= 2, the series generated with Fi modulo M (for i in range(N)) is periodic. The period always starts with 01. The Pisano Period is defined as the length of the period of this series.To understand it further, let’s see what happens when M is small: For M = 2, the period is 011 and has length 3 while for M = 3 the sequence repeats after 8 nos. Example: So to compute, say F2019 mod 5, we’ll find the remainder of 2019 when divided by 20 (Pisano Period of 5 is 20). 2019 mod 20 is 19. Therefore, F2019 mod 5 = F19 mod 5 = 1. This property is true in general. We need to find the remainder when N is divided by the Pisano Period of M. Then calculate F(N)remainder mod M for the newly calculated N. Below is the implementation of FN modulo M: C++ Java Python3 C# Javascript // C++ program to calculate// Fibonacci no. modulo m using// Pisano Period#include <bits/stdc++.h>using namespace std; // Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mlong pisano(long m){ long prev = 0; long curr = 1; long res = 0; for(int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res;} // Calculate Fn mod mlong fibonacciModulo(long n, long m){ // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} // Driver Codeint main(){ long n = 1548276540; long m = 235; cout << (fibonacciModulo(n, m)); return 0;} // This code is contributed by subhammahato348 // Java program to calculate// Fibonacci no. modulo m using// Pisano Periodimport java.io.*; class GFG{ // Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mpublic static long pisano(long m){ long prev = 0; long curr = 1; long res = 0; for(int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res= i + 1; } return res;} // Calculate Fn mod mpublic static long fibonacciModulo(long n, long m){ // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} // Driver Codepublic static void main(String[] args){ long n = 1548276540; long m = 235; System.out.println(fibonacciModulo(n, m));}} // This code is contributor by Parag Pallav Singh # Python3 program to calculate# Fibonacci no. modulo m using# Pisano Period # Calculate and return Pisano Period# The length of a Pisano Period for# a given m ranges from 3 to m * mdef pisanoPeriod(m): previous, current = 0, 1 for i in range(0, m * m): previous, current \ = current, (previous + current) % m # A Pisano Period starts with 01 if (previous == 0 and current == 1): return i + 1 # Calculate Fn mod mdef fibonacciModulo(n, m): # Getting the period pisano_period = pisanoPeriod(m) # Taking mod of N with # period length n = n % pisano_period previous, current = 0, 1 if n==0: return 0 elif n==1: return 1 for i in range(n-1): previous, current \ = current, previous + current return (current % m) # Driver Codeif __name__ == '__main__': n = 1548276540 m = 235 print(fibonacciModulo(n, m)) // C# program to calculate// Fibonacci no. modulo m using// Pisano Periodusing System; class GFG { // Calculate and return Pisano Period // The length of a Pisano Period for // a given m ranges from 3 to m * m public static long pisano(long m) { long prev = 0; long curr = 1; long res = 0; for (int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res; } // Calculate Fn mod m public static long fibonacciModulo(long n, long m) { // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for (int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m; } // Driver Code public static void Main() { long n = 1548276540; long m = 235; Console.Write(fibonacciModulo(n, m)); }} // This code is contributed by subham348. <script> // javascript program to calculate// Fibonacci no. modulo m using// Pisano Period// Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mfunction pisano(m){ let prev = 0; let curr = 1; let res = 0; for(let i = 0; i < m * m; i++) { let temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res;} // Calculate Fn mod mfunction fibonacciModulo(n,m){ // Getting the period let pisanoPeriod = pisano(m); n = n % pisanoPeriod; let prev = 0; let curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(let i = 0; i < n - 1; i++) { let temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} let n = 1548276540; let m = 235; document.write(fibonacciModulo(n, m)); // This code is contributed by vaibhavrabadiya117.</script> 185 Pisano Period of 235 is 160. 1548276540 mod 160 is 60. F60 mod 235 = 185. Using Pisano Period, we now need to calculate Fibonacci nos. iteratively for a relatively lower N than specified in the original problem and then calculate FN modulo M.Time Complexity: O(M2) Auxiliary Space: O(1) devkapilbansal ParagPallavSingh1 subham348 subhammahato348 vaibhavrabadiya117 Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Mar, 2022" }, { "code": null, "e": 213, "s": 54, "text": "Given two number N and M. The task is to find the N-th fibonacci number mod M.In general let FN be the N-th fibonacci number then the output should be FN % M." }, { "code": null, "e": 353, "s": 213, "text": "The Fibonacci sequence is a series of numbers in which each no. is the sum of two preceding nos. It is defined by the recurrence relation: " }, { "code": null, "e": 384, "s": 353, "text": "F0 = 0\nF1 = 1\nFn = Fn-1 + Fn-2" }, { "code": null, "e": 487, "s": 384, "text": "These nos. are in the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...Here N can be large." }, { "code": null, "e": 498, "s": 487, "text": "Examples: " }, { "code": null, "e": 533, "s": 498, "text": "Input: N = 438, M = 900 Output: 44" }, { "code": null, "e": 578, "s": 533, "text": "Input: N = 1548276540, M = 235 Output: 185 " }, { "code": null, "e": 1033, "s": 578, "text": "Approach: However, for such values of N, a simple recursive approach to keep calculating N Fibonacci numbers with a time complexity of O(2N) should be avoided. Even an iterative or a Dynamic Programming approach with an algorithm looping for N iterations will not be time-efficient.This problem can be solved using the properties of Pisano Period. For a given value of N and M >= 2, the series generated with Fi modulo M (for i in range(N)) is periodic. " }, { "code": null, "e": 1205, "s": 1033, "text": "The period always starts with 01. The Pisano Period is defined as the length of the period of this series.To understand it further, let’s see what happens when M is small:" }, { "code": null, "e": 1301, "s": 1205, "text": "For M = 2, the period is 011 and has length 3 while for M = 3 the sequence repeats after 8 nos." }, { "code": null, "e": 1653, "s": 1301, "text": "Example: So to compute, say F2019 mod 5, we’ll find the remainder of 2019 when divided by 20 (Pisano Period of 5 is 20). 2019 mod 20 is 19. Therefore, F2019 mod 5 = F19 mod 5 = 1. This property is true in general. We need to find the remainder when N is divided by the Pisano Period of M. Then calculate F(N)remainder mod M for the newly calculated N." }, { "code": null, "e": 1697, "s": 1653, "text": "Below is the implementation of FN modulo M:" }, { "code": null, "e": 1701, "s": 1697, "text": "C++" }, { "code": null, "e": 1706, "s": 1701, "text": "Java" }, { "code": null, "e": 1714, "s": 1706, "text": "Python3" }, { "code": null, "e": 1717, "s": 1714, "text": "C#" }, { "code": null, "e": 1728, "s": 1717, "text": "Javascript" }, { "code": "// C++ program to calculate// Fibonacci no. modulo m using// Pisano Period#include <bits/stdc++.h>using namespace std; // Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mlong pisano(long m){ long prev = 0; long curr = 1; long res = 0; for(int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res;} // Calculate Fn mod mlong fibonacciModulo(long n, long m){ // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} // Driver Codeint main(){ long n = 1548276540; long m = 235; cout << (fibonacciModulo(n, m)); return 0;} // This code is contributed by subhammahato348", "e": 2827, "s": 1728, "text": null }, { "code": "// Java program to calculate// Fibonacci no. modulo m using// Pisano Periodimport java.io.*; class GFG{ // Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mpublic static long pisano(long m){ long prev = 0; long curr = 1; long res = 0; for(int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res= i + 1; } return res;} // Calculate Fn mod mpublic static long fibonacciModulo(long n, long m){ // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} // Driver Codepublic static void main(String[] args){ long n = 1548276540; long m = 235; System.out.println(fibonacciModulo(n, m));}} // This code is contributor by Parag Pallav Singh", "e": 4037, "s": 2827, "text": null }, { "code": "# Python3 program to calculate# Fibonacci no. modulo m using# Pisano Period # Calculate and return Pisano Period# The length of a Pisano Period for# a given m ranges from 3 to m * mdef pisanoPeriod(m): previous, current = 0, 1 for i in range(0, m * m): previous, current \\ = current, (previous + current) % m # A Pisano Period starts with 01 if (previous == 0 and current == 1): return i + 1 # Calculate Fn mod mdef fibonacciModulo(n, m): # Getting the period pisano_period = pisanoPeriod(m) # Taking mod of N with # period length n = n % pisano_period previous, current = 0, 1 if n==0: return 0 elif n==1: return 1 for i in range(n-1): previous, current \\ = current, previous + current return (current % m) # Driver Codeif __name__ == '__main__': n = 1548276540 m = 235 print(fibonacciModulo(n, m))", "e": 4982, "s": 4037, "text": null }, { "code": "// C# program to calculate// Fibonacci no. modulo m using// Pisano Periodusing System; class GFG { // Calculate and return Pisano Period // The length of a Pisano Period for // a given m ranges from 3 to m * m public static long pisano(long m) { long prev = 0; long curr = 1; long res = 0; for (int i = 0; i < m * m; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res; } // Calculate Fn mod m public static long fibonacciModulo(long n, long m) { // Getting the period long pisanoPeriod = pisano(m); n = n % pisanoPeriod; long prev = 0; long curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for (int i = 0; i < n - 1; i++) { long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m; } // Driver Code public static void Main() { long n = 1548276540; long m = 235; Console.Write(fibonacciModulo(n, m)); }} // This code is contributed by subham348.", "e": 6264, "s": 4982, "text": null }, { "code": "<script> // javascript program to calculate// Fibonacci no. modulo m using// Pisano Period// Calculate and return Pisano Period// The length of a Pisano Period for// a given m ranges from 3 to m * mfunction pisano(m){ let prev = 0; let curr = 1; let res = 0; for(let i = 0; i < m * m; i++) { let temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if (prev == 0 && curr == 1) res = i + 1; } return res;} // Calculate Fn mod mfunction fibonacciModulo(n,m){ // Getting the period let pisanoPeriod = pisano(m); n = n % pisanoPeriod; let prev = 0; let curr = 1; if (n == 0) return 0; else if (n == 1) return 1; for(let i = 0; i < n - 1; i++) { let temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m;} let n = 1548276540; let m = 235; document.write(fibonacciModulo(n, m)); // This code is contributed by vaibhavrabadiya117.</script>", "e": 7305, "s": 6264, "text": null }, { "code": null, "e": 7309, "s": 7305, "text": "185" }, { "code": null, "e": 7576, "s": 7311, "text": "Pisano Period of 235 is 160. 1548276540 mod 160 is 60. F60 mod 235 = 185. Using Pisano Period, we now need to calculate Fibonacci nos. iteratively for a relatively lower N than specified in the original problem and then calculate FN modulo M.Time Complexity: O(M2)" }, { "code": null, "e": 7599, "s": 7576, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 7614, "s": 7599, "text": "devkapilbansal" }, { "code": null, "e": 7632, "s": 7614, "text": "ParagPallavSingh1" }, { "code": null, "e": 7642, "s": 7632, "text": "subham348" }, { "code": null, "e": 7658, "s": 7642, "text": "subhammahato348" }, { "code": null, "e": 7677, "s": 7658, "text": "vaibhavrabadiya117" }, { "code": null, "e": 7687, "s": 7677, "text": "Fibonacci" }, { "code": null, "e": 7700, "s": 7687, "text": "Mathematical" }, { "code": null, "e": 7713, "s": 7700, "text": "Mathematical" }, { "code": null, "e": 7723, "s": 7713, "text": "Fibonacci" } ]
Python | Pandas tseries.offsets.DateOffset
23 Apr, 2019 Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created. Pandas tseries.offsets.DateOffset is used to create standard kind of date increment used for a date range. Syntax: pandas.tseries.offsets.DateOffset(n=1, normalize=False, **kwds) Parameter :n : The number of time periods the offset represents.normalize : Whether to round the result of a DateOffset addition down to the previous midnight.level : int, str, default None**kwds : Temporal parameter that add to or replace the offset value. Parameters that add to the offset (like Timedelta): years, months etc. Returns : DateOffsets Example #1: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 2 days. # importing pandas as pdimport pandas as pd # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11') # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(n = 2) # Print the Timestampprint(ts) # Print the DateOffsetprint(do) Output : Now we will add the dateoffset to the given timestamp object to create an offset of 2 days from the given date. # Adding the dateoffset to the given timestampnew_timestamp = ts + do # Print the updated timestampprint(new_timestamp) Output : As we can see in the output, we have successfully created an offset of 2 days and added it to the given timestamp object to move the date forward by 2 days. Example #2: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 10 days and 2 hours. # importing pandas as pdimport pandas as pd # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11') # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(days = 10, hours = 2) # Print the Timestampprint(ts) # Print the DateOffsetprint(do) Output : Now we will add the dateoffset to the given timestamp object to create an offset of 10 days and 2 hours from the given date. # Adding the dateoffset to the given timestampnew_timestamp = ts + do # Print the updated timestampprint(new_timestamp) Output : As we can see in the output, we have successfully created an offset of 10 days and 2 hours and added it to the given timestamp object to move the date forward by 10 days and 2 hours. Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2019" }, { "code": null, "e": 366, "s": 28, "text": "Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F)." }, { "code": null, "e": 634, "s": 366, "text": "DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created." }, { "code": null, "e": 741, "s": 634, "text": "Pandas tseries.offsets.DateOffset is used to create standard kind of date increment used for a date range." }, { "code": null, "e": 813, "s": 741, "text": "Syntax: pandas.tseries.offsets.DateOffset(n=1, normalize=False, **kwds)" }, { "code": null, "e": 1142, "s": 813, "text": "Parameter :n : The number of time periods the offset represents.normalize : Whether to round the result of a DateOffset addition down to the previous midnight.level : int, str, default None**kwds : Temporal parameter that add to or replace the offset value. Parameters that add to the offset (like Timedelta): years, months etc." }, { "code": null, "e": 1164, "s": 1142, "text": "Returns : DateOffsets" }, { "code": null, "e": 1256, "s": 1164, "text": "Example #1: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 2 days." }, { "code": "# importing pandas as pdimport pandas as pd # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11') # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(n = 2) # Print the Timestampprint(ts) # Print the DateOffsetprint(do)", "e": 1493, "s": 1256, "text": null }, { "code": null, "e": 1502, "s": 1493, "text": "Output :" }, { "code": null, "e": 1614, "s": 1502, "text": "Now we will add the dateoffset to the given timestamp object to create an offset of 2 days from the given date." }, { "code": "# Adding the dateoffset to the given timestampnew_timestamp = ts + do # Print the updated timestampprint(new_timestamp)", "e": 1735, "s": 1614, "text": null }, { "code": null, "e": 1744, "s": 1735, "text": "Output :" }, { "code": null, "e": 1901, "s": 1744, "text": "As we can see in the output, we have successfully created an offset of 2 days and added it to the given timestamp object to move the date forward by 2 days." }, { "code": null, "e": 2006, "s": 1901, "text": "Example #2: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 10 days and 2 hours." }, { "code": "# importing pandas as pdimport pandas as pd # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11') # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(days = 10, hours = 2) # Print the Timestampprint(ts) # Print the DateOffsetprint(do)", "e": 2258, "s": 2006, "text": null }, { "code": null, "e": 2267, "s": 2258, "text": "Output :" }, { "code": null, "e": 2392, "s": 2267, "text": "Now we will add the dateoffset to the given timestamp object to create an offset of 10 days and 2 hours from the given date." }, { "code": "# Adding the dateoffset to the given timestampnew_timestamp = ts + do # Print the updated timestampprint(new_timestamp)", "e": 2513, "s": 2392, "text": null }, { "code": null, "e": 2522, "s": 2513, "text": "Output :" }, { "code": null, "e": 2705, "s": 2522, "text": "As we can see in the output, we have successfully created an offset of 10 days and 2 hours and added it to the given timestamp object to move the date forward by 10 days and 2 hours." }, { "code": null, "e": 2728, "s": 2705, "text": "Python pandas-datetime" }, { "code": null, "e": 2742, "s": 2728, "text": "Python-pandas" }, { "code": null, "e": 2749, "s": 2742, "text": "Python" } ]
Data Analysis and Visualization in Python?
Python provides numerous libraries for data analysis and visualization mainly numpy, pandas, matplotlib, seaborn etc. In this section, we are going to discuss pandas library for data analysis and visualization which is an open source library built on top of numpy. It allows us to do fast analysis and data cleaning and preparation.Pandas also provides numerous built-in visualization feautures which we are going to see below. To install pandas, run the below command in your terminal − pipinstall pandas Orwe have anaconda, you can use condainstall pandas Data framesa re the main tools when we are working with pandas. import numpy as np import pandas as pd from numpy.random import randn np.random.seed(50) df = pd.DataFrame(randn(6,4), ['a','b','c','d','e','f'],['w','x','y','z']) df Weare going to see some convenient ways to deal with missing data inpandas, which automatically gets filled with zero's or nan. import numpy as np import pandas as pd from numpy.random import randn d = {'A': [1,2,np.nan], 'B': [9, np.nan, np.nan], 'C': [1,4,9]} df = pd.DataFrame(d) df So,we are having 3 missing value in above. df.dropna() df.dropna(axis = 1) df.dropna(thresh = 2) df.fillna(value = df.mean()) We are going to read the csv file which is either stored in our local machine(in my case) or we can directly fetch from the web. #import pandas library import pandas as pd #Read csv file and assigned it to dataframe variable df = pd.read_csv("SYB61_T03_Population Growth Rates in Urban areas and Capital cities.csv",encoding = "ISO-8859-1") #Read first five element from the dataframe df.head() Toread the number of rows and columns in our dataframe or csv file. #Countthe number of rows and columns in our dataframe. df.shape (4166,9) Operationson dataframes can be done using various tools of pandas forstatistics #To computes various summary statistics, excluding NaN values df.describe() # computes numerical data ranks df.rank() ..... ..... import matplotlib.pyplot as plt years = [1981, 1991, 2001, 2011, 2016] Average_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000] plt.plot(years, Average_populations) plt.title("Census of India: sample registration system") plt.xlabel("Year") plt.ylabel("Average_populations") plt.show() plt.scatter(years,Average_populations) import matplotlib.pyplot as plt Average_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000] plt.hist(Average_populations, bins = 10) plt.xlabel("Average_populations") plt.ylabel("Frequency") plt.show()
[ { "code": null, "e": 1327, "s": 1062, "text": "Python provides numerous libraries for data analysis and visualization mainly numpy, pandas, matplotlib, seaborn etc. In this section, we are going to discuss pandas library for data analysis and visualization which is an open source library built on top of numpy." }, { "code": null, "e": 1490, "s": 1327, "text": "It allows us to do fast analysis and data cleaning and preparation.Pandas also provides numerous built-in visualization feautures which we are going to see below." }, { "code": null, "e": 1550, "s": 1490, "text": "To install pandas, run the below command in your terminal −" }, { "code": null, "e": 1568, "s": 1550, "text": "pipinstall pandas" }, { "code": null, "e": 1600, "s": 1568, "text": "Orwe have anaconda, you can use" }, { "code": null, "e": 1620, "s": 1600, "text": "condainstall pandas" }, { "code": null, "e": 1684, "s": 1620, "text": "Data framesa re the main tools when we are working with pandas." }, { "code": null, "e": 1851, "s": 1684, "text": "import numpy as np\nimport pandas as pd\nfrom numpy.random import randn\nnp.random.seed(50)\ndf = pd.DataFrame(randn(6,4), ['a','b','c','d','e','f'],['w','x','y','z'])\ndf" }, { "code": null, "e": 1979, "s": 1851, "text": "Weare going to see some convenient ways to deal with missing data inpandas, which automatically gets filled with zero's or nan." }, { "code": null, "e": 2137, "s": 1979, "text": "import numpy as np\nimport pandas as pd\nfrom numpy.random import randn\nd = {'A': [1,2,np.nan], 'B': [9, np.nan, np.nan], 'C': [1,4,9]}\ndf = pd.DataFrame(d)\ndf" }, { "code": null, "e": 2180, "s": 2137, "text": "So,we are having 3 missing value in above." }, { "code": null, "e": 2192, "s": 2180, "text": "df.dropna()" }, { "code": null, "e": 2212, "s": 2192, "text": "df.dropna(axis = 1)" }, { "code": null, "e": 2234, "s": 2212, "text": "df.dropna(thresh = 2)" }, { "code": null, "e": 2263, "s": 2234, "text": "df.fillna(value = df.mean())" }, { "code": null, "e": 2392, "s": 2263, "text": "We are going to read the csv file which is either stored in our local machine(in my case) or we can directly fetch from the web." }, { "code": null, "e": 2660, "s": 2392, "text": "#import pandas library\nimport pandas as pd\n\n#Read csv file and assigned it to dataframe variable\ndf = pd.read_csv(\"SYB61_T03_Population Growth Rates in Urban areas and Capital cities.csv\",encoding = \"ISO-8859-1\")\n\n#Read first five element from the dataframe\ndf.head()" }, { "code": null, "e": 2728, "s": 2660, "text": "Toread the number of rows and columns in our dataframe or csv file." }, { "code": null, "e": 2792, "s": 2728, "text": "#Countthe number of rows and columns in our dataframe.\ndf.shape" }, { "code": null, "e": 2801, "s": 2792, "text": "(4166,9)" }, { "code": null, "e": 2881, "s": 2801, "text": "Operationson dataframes can be done using various tools of pandas forstatistics" }, { "code": null, "e": 2957, "s": 2881, "text": "#To computes various summary statistics, excluding NaN values\ndf.describe()" }, { "code": null, "e": 2999, "s": 2957, "text": "# computes numerical data ranks\ndf.rank()" }, { "code": null, "e": 3005, "s": 2999, "text": "....." }, { "code": null, "e": 3011, "s": 3005, "text": "....." }, { "code": null, "e": 3323, "s": 3011, "text": "import matplotlib.pyplot as plt\nyears = [1981, 1991, 2001, 2011, 2016]\n\nAverage_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000]\n\nplt.plot(years, Average_populations)\nplt.title(\"Census of India: sample registration system\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Average_populations\")\nplt.show()" }, { "code": null, "e": 3362, "s": 3323, "text": "plt.scatter(years,Average_populations)" }, { "code": null, "e": 3588, "s": 3362, "text": "import matplotlib.pyplot as plt\n\nAverage_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000]\n\nplt.hist(Average_populations, bins = 10)\nplt.xlabel(\"Average_populations\")\nplt.ylabel(\"Frequency\")\n\nplt.show()" } ]
TIKA - Quick Guide
Apache Tika is a library that is used for document type detection and content extraction from various file formats. Apache Tika is a library that is used for document type detection and content extraction from various file formats. Internally, Tika uses existing various document parsers and document type detection techniques to detect and extract data. Internally, Tika uses existing various document parsers and document type detection techniques to detect and extract data. Using Tika, one can develop a universal type detector and content extractor to extract both structured text as well as metadata from different types of documents such as spreadsheets, text documents, images, PDFs and even multimedia input formats to a certain extent. Using Tika, one can develop a universal type detector and content extractor to extract both structured text as well as metadata from different types of documents such as spreadsheets, text documents, images, PDFs and even multimedia input formats to a certain extent. Tika provides a single generic API for parsing different file formats. It uses existing specialized parser libraries for each document type. Tika provides a single generic API for parsing different file formats. It uses existing specialized parser libraries for each document type. All these parser libraries are encapsulated under a single interface called the Parser interface. All these parser libraries are encapsulated under a single interface called the Parser interface. According to filext.com, there are about 15k to 51k content types, and this number is growing day by day. Data is being stored in various formats such as text documents, excel spreadsheet, PDFs, images, and multimedia files, to name a few. Therefore, applications such as search engines and content management systems need additional support for easy extraction of data from these document types. Apache Tika serves this purpose by providing a generic API to locate and extract data from multiple file formats. There are various applications that make use of Apache Tika. Here we will discuss a few prominent applications that depend heavily on Apache Tika. Tika is widely used while developing search engines to index the text contents of digital documents. Search engines are information processing systems designed to search information and indexed documents from the Web. Search engines are information processing systems designed to search information and indexed documents from the Web. Crawler is an important component of a search engine that crawls through the Web to fetch the documents that are to be indexed using some indexing technique. Thereafter, the crawler transfers these indexed documents to an extraction component. Crawler is an important component of a search engine that crawls through the Web to fetch the documents that are to be indexed using some indexing technique. Thereafter, the crawler transfers these indexed documents to an extraction component. The duty of extraction component is to extract the text and metadata from the document. Such extracted content and metadata are very useful for a search engine. This extraction component contains Tika. The duty of extraction component is to extract the text and metadata from the document. Such extracted content and metadata are very useful for a search engine. This extraction component contains Tika. The extracted content is then passed to the indexer of the search engine that uses it to build a search index. Apart from this, the search engine uses the extracted content in many other ways as well. The extracted content is then passed to the indexer of the search engine that uses it to build a search index. Apart from this, the search engine uses the extracted content in many other ways as well. In the field of artificial intelligence, there are certain tools to analyze documents automatically at semantic level and extract all kinds of data from them. In the field of artificial intelligence, there are certain tools to analyze documents automatically at semantic level and extract all kinds of data from them. In such applications, the documents are classified based on the prominent terms in the extracted content of the document. In such applications, the documents are classified based on the prominent terms in the extracted content of the document. These tools make use of Tika for content extraction to analyze documents varying from plain text to digital documents. These tools make use of Tika for content extraction to analyze documents varying from plain text to digital documents. Some organizations manage their digital assets such as photographs, ebooks, drawings, music and video using a special application known as digital asset management (DAM). Some organizations manage their digital assets such as photographs, ebooks, drawings, music and video using a special application known as digital asset management (DAM). Such applications take the help of document type detectors and metadata extractor to classify the various documents. Such applications take the help of document type detectors and metadata extractor to classify the various documents. Websites like Amazon recommend newly released contents of their website to individual users according to their interests. To do so, these websites follow machine learning techniques, or take the help of social media websites like Facebook to extract required information such as likes and interests of the users. This gathered information will be in the form of html tags or other formats that require further content type detection and extraction. Websites like Amazon recommend newly released contents of their website to individual users according to their interests. To do so, these websites follow machine learning techniques, or take the help of social media websites like Facebook to extract required information such as likes and interests of the users. This gathered information will be in the form of html tags or other formats that require further content type detection and extraction. For content analysis of a document, we have technologies that implement machine learning techniques such as UIMA and Mahout. These technologies are useful in clustering and analyzing the data in the documents. For content analysis of a document, we have technologies that implement machine learning techniques such as UIMA and Mahout. These technologies are useful in clustering and analyzing the data in the documents. Apache Mahout is a framework which provides ML algorithms on Apache Hadoop – a cloud computing platform. Mahout provides an architecture by following certain clustering and filtering techniques. By following this architecture, programmers can write their own ML algorithms to produce recommendations by taking various text and metadata combinations. To provide inputs to these algorithms, recent versions of Mahout use Tika to extract text and metadata from binary content. Apache Mahout is a framework which provides ML algorithms on Apache Hadoop – a cloud computing platform. Mahout provides an architecture by following certain clustering and filtering techniques. By following this architecture, programmers can write their own ML algorithms to produce recommendations by taking various text and metadata combinations. To provide inputs to these algorithms, recent versions of Mahout use Tika to extract text and metadata from binary content. Apache UIMA analyzes and processes various programming languages and produces UIMA annotations. Internally it uses Tika Annotator to extract document text and metadata. Apache UIMA analyzes and processes various programming languages and produces UIMA annotations. Internally it uses Tika Annotator to extract document text and metadata. Application programmers can easily integrate Tika in their applications. Tika provides a Command Line Interface and a GUI to make it user friendly. In this chapter, we will discuss the four important modules that constitute the Tika architecture. The following illustration shows the architecture of Tika along with its four modules − Language detection mechanism. MIME detection mechanism. Parser interface. Tika Facade class. Whenever a text document is passed to Tika, it will detect the language in which it was written. It accepts documents without language annotation and adds that information in the metadata of the document by detecting the language. To support language identification, Tika has a class called Language Identifier in the package org.apache.tika.language, and a language identification repository inside which contains algorithms for language detection from a given text. Tika internally uses N-gram algorithm for language detection. Tika can detect the document type according to the MIME standards. Default MIME type detection in Tika is done using org.apache.tika.mime.mimeTypes. It uses the org.apache.tika.detect.Detector interface for most of the content type detection. Internally Tika uses several techniques like file globs, content-type hints, magic bytes, character encodings, and several other techniques. The parser interface of org.apache.tika.parser is the key interface for parsing documents in Tika. This Interface extracts the text and the metadata from a document and summarizes it for external users who are willing to write parser plugins. Using different concrete parser classes, specific for individual document types, Tika supports a lot of document formats. These format specific classes provide support for different document formats, either by directly implementing the parser logic or by using external parser libraries. Using Tika facade class is the simplest and direct way of calling Tika from Java, and it follows the facade design pattern. You can find the Tika facade class in the org.apache.tika package of Tika API. By implementing basic use cases, Tika acts as a broker of landscape. It abstracts the underlying complexity of the Tika library such as MIME detection mechanism, parser interface, and language detection mechanism, and provides the users a simple interface to use. Unified parser Interface − Tika encapsulates all the third party parser libraries within a single parser interface. Due to this feature, the user escapes from the burden of selecting the suitable parser library and use it according to the file type encountered. Unified parser Interface − Tika encapsulates all the third party parser libraries within a single parser interface. Due to this feature, the user escapes from the burden of selecting the suitable parser library and use it according to the file type encountered. Low memory usage − Tika consumes less memory resources therefore it is easily embeddable with Java applications. We can also use Tika within the application which run on platforms with less resources like mobile PDA. Low memory usage − Tika consumes less memory resources therefore it is easily embeddable with Java applications. We can also use Tika within the application which run on platforms with less resources like mobile PDA. Fast processing − Quick content detection and extraction from applications can be expected. Fast processing − Quick content detection and extraction from applications can be expected. Flexible metadata − Tika understands all the metadata models which are used to describe files. Flexible metadata − Tika understands all the metadata models which are used to describe files. Parser integration − Tika can use various parser libraries available for each document type in a single application. Parser integration − Tika can use various parser libraries available for each document type in a single application. MIME type detection − Tika can detect and extract content from all the media types included in the MIME standards. MIME type detection − Tika can detect and extract content from all the media types included in the MIME standards. Language detection − Tika includes language identification feature, therefore can be used in documents based on language type in a multi lingual websites. Language detection − Tika includes language identification feature, therefore can be used in documents based on language type in a multi lingual websites. Tika supports various functionalities − Document type detection Content extraction Metadata extraction Language detection Tika uses various detection techniques and detects the type of the document given to it. Tika has a parser library that can parse the content of various document formats and extract them. After detecting the type of the document, it selects the appropriate parser from the parser repository and passes the document. Different classes of Tika have methods to parse different document formats. Along with the content, Tika extracts the metadata of the document with the same procedure as in content extraction. For some document types, Tika have classes to extract metadata. Internally, Tika follows algorithms like n-gram to detect the language of the content in a given document. Tika depends on classes like Languageidentifier and Profiler for language identification. This chapter takes you through the process of setting up Apache Tika on Windows and Linux. User administration is needed while installing the Apache Tika. To verify Java installation, open the console and execute the following java command. If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on. Java version "1.7.0_60" Java (TM) SE Run Time Environment (build 1.7.0_60-b19) Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode) java version "1.7.0_25" Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode) We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial. We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example, Append the full path of the Java compiler location to the System Path. Verify the command java-version from command prompt as explained above. Programmers can integrate Apache Tika in their environment by using Command line, Tika API, Command line interface (CLI) of Tika, Graphical User interface (GUI) of Tika, or the source code. For any of these approaches, first of all, you have to download the source code of Tika. You will find the source code of Tika at https://Tika.apache.org/download.html, where you will find two links − apache-tika-1.6-src.zip − It contains the source code of Tika, and apache-tika-1.6-src.zip − It contains the source code of Tika, and Tika -app-1.6.jar − It is a jar file that contains the Tika application. Tika -app-1.6.jar − It is a jar file that contains the Tika application. Download these two files. A snapshot of the official website of Tika is shown below. After downloading the files, set the classpath for the jar file tika-app-1.6.jar. Add the complete path of the jar file as shown in the table below. Export CLASSPATH = $CLASSPATH − /usr/share/jars/Tika-app-1.6.tar − Apache provides Tika application, a Graphical User Interface (GUI) application using Eclipse. Open eclipse and create a new project. Open eclipse and create a new project. If you do not having Maven in your Eclipse, set it up by following the given steps. Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format If you do not having Maven in your Eclipse, set it up by following the given steps. Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format Pick the latest version and save the path of the url in p2 url column. Pick the latest version and save the path of the url in p2 url column. Now revisit eclipse, in the menu bar, click Help, and choose Install New Software from the dropdown menu Now revisit eclipse, in the menu bar, click Help, and choose Install New Software from the dropdown menu Click the Add button, type any desired name, as it is optional. Now paste the saved url in the Location field. Click the Add button, type any desired name, as it is optional. Now paste the saved url in the Location field. A new plugin will be added with the name you have chosen in the previous step, check the checkbox in front of it, and click Next. A new plugin will be added with the name you have chosen in the previous step, check the checkbox in front of it, and click Next. Proceed with the installation. Once completed, restart the Eclipse. Proceed with the installation. Once completed, restart the Eclipse. Now right click on the project, and in the configure option, select convert to maven project. Now right click on the project, and in the configure option, select convert to maven project. A new wizard for creating a new pom appears. Enter the Group Id as org.apache.tika, enter the latest version of Tika, select the packaging as jar, and click Finish. A new wizard for creating a new pom appears. Enter the Group Id as org.apache.tika, enter the latest version of Tika, select the packaging as jar, and click Finish. The Maven project is successfully installed, and your project is converted into Maven. Now you have to configure the pom.xml file. Get the Tika maven dependency from https://mvnrepository.com/artifact/org.apache.tika Shown below is the complete Maven dependency of Apache Tika. <dependency> <groupId>org.apache.Tika</groupId> <artifactId>Tika-core</artifactId> <version>1.6</version> <groupId>org.apache.Tika</groupId> <artifactId> Tika-parsers</artifactId> <version> 1.6</version> <groupId> org.apache.Tika</groupId> <artifactId>Tika</artifactId> <version>1.6</version> <groupId>org.apache.Tika</groupId> < artifactId>Tika-serialization</artifactId> < version>1.6< /version> < groupId>org.apache.Tika< /groupId> < artifactId>Tika-app< /artifactId> < version>1.6< /version> <groupId>org.apache.Tika</groupId> <artifactId>Tika-bundle</artifactId> <version>1.6</version> </dependency> Users can embed Tika in their applications using the Tika facade class. It has methods to explore all the functionalities of Tika. Since it is a facade class, Tika abstracts the complexity behind its functions. In addition to this, users can also use the various classes of Tika in their applications. This is the most prominent class of the Tika library and follows the facade design pattern. Therefore, it abstracts all the internal implementations and provides simple methods to access the Tika functionalities. The following table lists the constructors of this class along with their descriptions. package − org.apache.tika class − Tika Tika () Uses default configuration and constructs the Tika class. Tika (Detector detector) Creates a Tika facade by accepting the detector instance as parameter Tika (Detector detector, Parser parser) Creates a Tika facade by accepting the detector and parser instances as parameters. Tika (Detector detector, Parser parser, Translator translator) Creates a Tika facade by accepting the detector, the parser, and the translator instance as parameters. Tika (TikaConfig config) Creates a Tika facade by accepting the object of the TikaConfig class as parameter. The following are the important methods of Tika facade class − parseToString (File file) This method and all its variants parses the file passed as parameter and returns the extracted text content in the String format. By default, the length of this string parameter is limited. int getMaxStringLength () Returns the maximum length of strings returned by the parseToString methods. void setMaxStringLength (int maxStringLength) Sets the maximum length of strings returned by the parseToString methods. Reader parse (File file) This method and all its variants parses the file passed as parameter and returns the extracted text content in the form of java.io.reader object. String detect (InputStream stream, Metadata metadata) This method and all its variants accepts an InputStream object and a Metadata object as parameters, detects the type of the given document, and returns the document type name as String object. This method abstracts the detection mechanisms used by Tika. String translate (InputStream text, String targetLanguage) This method and all its variants accepts the InputStream object and a String representing the language that we want our text to be translated, and translates the given text to the desired language, attempting to auto-detect the source language. This is the interface that is implemented by all the parser classes of Tika package. package − org.apache.tika.parser Interface − Parser The following is the important method of Tika Parser interface − parse (InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) This method parses the given document into a sequence of XHTML and SAX events. After parsing, it places the extracted document content in the object of the ContentHandler class and the metadata in the object of the Metadata class. This class implements various interfaces such as CreativeCommons, Geographic, HttpHeaders, Message, MSOffice, ClimateForcast, TIFF, TikaMetadataKeys, TikaMimeKeys, Serializable to support various data models. The following tables list the constructors and methods of this class along with their descriptions. package − org.apache.tika.metadata class − Metadata Metadata() Constructs a new, empty metadata. add (Property property, String value) Adds a metadata property/value mapping to a given document. Using this function, we can set the value to a property. add (String name, String value) Adds a metadata property/value mapping to a given document. Using this method, we can set a new name value to the existing metadata of a document. String get (Property property) Returns the value (if any) of the metadata property given. String get (String name) Returns the value (if any) of the metadata name given. Date getDate (Property property) Returns the value of Date metadata property. String[] getValues (Property property) Returns all the values of a metadata property. String[] getValues (String name) Returns all the values of a given metadata name. String[] names() Returns all the names of metadata elements in a metadata object. set (Property property, Date date) Sets the date value of the given metadata property set(Property property, String[] values) Sets multiple values to a metadata property. This class identifies the language of the given content. The following tables list the constructors of this class along with their descriptions. package − org.apache.tika.language class − Language Identifier LanguageIdentifier (LanguageProfile profile) Instantiates the language identifier. Here you have to pass a LanguageProfile object as parameter. LanguageIdentifier (String content) This constructor can instantiate a language identifier by passing on a String from text content. String getLanguage () Returns the language given to the current LanguageIdentifier object. The following table shows the file formats Tika supports. org.apache.tika.parser.microsoft org.apache.tika.parser.microsoft.ooxml and it uses Apache Poi library OfficeParser(ole2) OOXMLParser (ooxml) Multipurpose Internet Mail Extensions (MIME) standards are the best available standards for identifying document types. The knowledge of these standards helps the browser during internal interactions. Whenever the browser encounters a media file, it chooses a compatible software available with it to display its contents. In case it does not have any suitable application to run a particular media file, it recommends the user to get the suitable plugin software for it. Tika supports all the Internet media document types provided in MIME. Whenever a file is passed through Tika, it detects the file and its document type. To detect media types, Tika internally uses the following mechanisms. Checking the file extensions is the simplest and most-widely used method to detect the format of a file. Many applications and operating systems provide support for these extensions. Shown below are the extension of a few known file types. Whenever you retrieve a file from a database or attach it to another document, you may lose the file’s name or extension. In such cases, the metadata supplied with the file is used to detect the file extension. Observing the raw bytes of a file, you can find some unique character patterns for each file. Some files have special byte prefixes called magic bytes that are specially made and included in a file for the purpose of identifying the file type For example, you can find CA FE BA BE (hexadecimal format) in a java file and %PDF (ASCII format) in a pdf file. Tika uses this information to identify the media type of a file. Files with plain text are encoded using different types of character encoding. The main challenge here is to identify the type of character encoding used in the files. Tika follows character encoding techniques like Bom markers and Byte Frequencies to identify the encoding system used by the plain text content. To detect XML documents, Tika parses the xml documents and extracts the information such as root elements, namespaces, and referenced schemas from where the true media type of the files can be found. The detect() method of facade class is used to detect the document type. This method accepts a file as input. Shown below is an example program for document type detection with Tika facade class. import java.io.File; import org.apache.tika.Tika; public class Typedetection { public static void main(String[] args) throws Exception { //assume example.mp3 is in your current directory File file = new File("example.mp3");// //Instantiating tika facade class Tika tika = new Tika(); //detecting the file type using detect method String filetype = tika.detect(file); System.out.println(filetype); } } Save the above code as TypeDetection.java and run it from the command prompt using the following commands − javac TypeDetection.java java TypeDetection audio/mpeg Tika uses various parser libraries to extract content from given parsers. It chooses the right parser for extracting the given document type. For parsing documents, the parseToString() method of Tika facade class is generally used. Shown below are the steps involved in the parsing process and these are abstracted by the Tika ParsertoString() method. Abstracting the parsing process − Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type. Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type. Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries. Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries. Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats. Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats. Given below is the program for extracting text from a file using Tika facade class − import java.io.File; import java.io.IOException; import org.apache.tika.Tika; import org.apache.tika.exception.TikaException; import org.xml.sax.SAXException; public class TikaExtraction { public static void main(final String[] args) throws IOException, TikaException { //Assume sample.txt is in your current directory File file = new File("sample.txt"); //Instantiating Tika facade class Tika tika = new Tika(); String filecontent = tika.parseToString(file); System.out.println("Extracted Content: " + filecontent); } } Save the above code as TikaExtraction.java and run it from the command prompt − javac TikaExtraction.java java TikaExtraction Given below is the content of sample.txt. Hi students welcome to tutorialspoint It gives you the following output − Extracted Content: Hi students welcome to tutorialspoint The parser package of Tika provides several interfaces and classes using which we can parse a text document. Given below is the block diagram of the org.apache.tika.parser package. There are several parser classes available, e.g., pdf parser, Mp3Passer, OfficeParser, etc., to parse respective documents individually. All these classes implement the parser interface. The given diagram shows Tika’s general-purpose parser classes: CompositeParser and AutoDetectParser. Since the CompositeParser class follows composite design pattern, you can use a group of parser instances as a single parser. The CompositeParser class also allows access to all the classes that implement the parser interface. This is a subclass of CompositeParser and it provides automatic type detection. Using this functionality, the AutoDetectParser automatically sends the incoming documents to the appropriate parser classes using the composite methodology. Along with parseToString(), you can also use the parse() method of the parser Interface. The prototype of this method is shown below. parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) The following table lists the four objects it accepts as parameters. InputStream stream Any Inputstream object that contains the content of the file ContentHandler handler Tika passes the document as XHTML content to this handler, thereafter the document is processed using SAX API. It provides efficient postprocessing of the contents in a document. Metadata metadata The metadata object is used both as a source and a target of document metadata. ParseContext context This object is used in cases where the client application wants to customize the parsing process. Given below is an example that shows how the parse() method is used. Step 1 − To use the parse() method of the parser interface, instantiate any of the classes providing the implementation for this interface. There are individual parser classes such as PDFParser, OfficeParser, XMLParser, etc. You can use any of these individual document parsers. Alternatively, you can use either CompositeParser or AutoDetectParser that uses all the parser classes internally and extracts the contents of a document using a suitable parser. Parser parser = new AutoDetectParser(); (or) Parser parser = new CompositeParser(); (or) object of any individual parsers given in Tika Library Step 2 − Create a handler class object. Given below are the three content handlers − BodyContentHandler This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance. LinkContentHandler This class detects and picks all the H-Ref tags of the XHTML document and forwards those for the use of tools like web crawlers. TeeContentHandler This class helps in using multiple tools simultaneously. Since our target is to extract the text contents from a document, instantiate BodyContentHandler as shown below − BodyContentHandler handler = new BodyContentHandler( ); Step 3 − Create the Metadata object as shown below − Metadata metadata = new Metadata(); Step 4 − Create any of the input stream objects, and pass your file that should be extracted to it. Instantiate a file object by passing the file path as parameter and pass this object to the FileInputStream class constructor. Note − The path passed to the file object should not contain spaces. The problem with these input stream classes is that they don’t support random access reads, which is required to process some file formats efficiently. To resolve this problem, Tika provides TikaInputStream. File file = new File(filepath) FileInputStream inputstream = new FileInputStream(file); (or) InputStream stream = TikaInputStream.get(new File(filename)); Step 5 − Create a parse context object as shown below − ParseContext context =new ParseContext(); Step 6 − Instantiate the parser object, invoke the parse method, and pass all the objects required, as shown in the prototype below − parser.parse(inputstream, handler, metadata, context); Given below is the program for content extraction using the parser interface − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class ParserExtraction { public static void main(final String[] args) throws IOException,SAXException, TikaException { //Assume sample.txt is in your current directory File file = new File("sample.txt"); //parse method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); //parsing the file parser.parse(inputstream, handler, metadata, context); System.out.println("File content : " + Handler.toString()); } } Save the above code as ParserExtraction.java and run it from the command prompt − javac ParserExtraction.java java ParserExtraction Given below is the content of sample.txt Hi students welcome to tutorialspoint If you execute the above program, it will give you the following output − File content : Hi students welcome to tutorialspoint Besides content, Tika also extracts the metadata from a file. Metadata is nothing but the additional information supplied with a file. If we consider an audio file, the artist name, album name, title comes under metadata. The Extensible Metadata Platform (XMP) is a standard for processing and storing information related to the content of a file. It was created by Adobe Systems Inc. XMP provides standards for defining, creating, and processing of metadata. You can embed this standard into several file formats such as PDF, JPEG, JPEG, GIF, jpg, HTML etc. Tika uses the Property class to follow XMP property definition. It provides the PropertyType and ValueType enums to capture the name and value of a metadata. This class implements various interfaces such as ClimateForcast, CativeCommons, Geographic, TIFF etc. to provide support for various metadata models. In addition, this class provides various methods to extract the content from a file. We can extract the list of all metadata names of a file from its metadata object using the method names(). It returns all the names as a string array. Using the name of the metadata, we can get the value using the get() method. It takes a metadata name and returns a value associated with it. String[] metadaNames = metadata.names(); String value = metadata.get(name); Whenever we parse a file using parse(), we pass an empty metadata object as one of the parameters. This method extracts the metadata of the given file (if that file contains any), and places them in the metadata object. Therefore, after parsing the file using parse(), we can extract the metadata from that object. Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); //empty metadata object FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); parser.parse(inputstream, handler, metadata, context); // now this metadata object contains the extracted metadata of the given file. metadata.metadata.names(); Given below is the complete program to extract metadata from a text file. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class GetMetadata { public static void main(final String[] args) throws IOException, TikaException { //Assume that boy.jpg is in your current directory File file = new File("boy.jpg"); //Parser method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); parser.parse(inputstream, handler, metadata, context); System.out.println(handler.toString()); //getting the list of all meta data elements String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as GetMetadata.java and run it from the command prompt using the following commands − javac GetMetadata .java java GetMetadata Given below is the snapshot of boy.jpg If you execute the above program, it will give you the following output − X-Parsed-By: org.apache.tika.parser.DefaultParser Resolution Units: inch Compression Type: Baseline Data Precision: 8 bits Number of Components: 3 tiff:ImageLength: 3000 Component 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert Component 1: Y component: Quantization table 0, Sampling factors 2 horiz/2 vert Image Height: 3000 pixels X Resolution: 300 dots Original Transmission Reference: 53616c7465645f5f2368da84ca932841b336ac1a49edb1a93fae938b8db2cb3ec9cc4dc28d7383f1 Image Width: 4000 pixels IPTC-NAA record: 92 bytes binary data Component 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert tiff:BitsPerSample: 8 Application Record Version: 4 tiff:ImageWidth: 4000 Content-Type: image/jpeg Y Resolution: 300 dots We can also get our desired metadata values. We can add new metadata values using the add() method of the metadata class. Given below is the syntax of this method. Here we are adding the author name. metadata.add(“author”,”Tutorials point”); The Metadata class has predefined properties including the properties inherited from classes like ClimateForcast, CativeCommons, Geographic, etc., to support various data models. Shown below is the usage of the SOFTWARE data type inherited from the TIFF interface implemented by Tika to follow XMP metadata standards for TIFF image formats. metadata.add(Metadata.SOFTWARE,"ms paint"); Given below is the complete program that demonstrates how to add metadata values to a given file. Here the list of the metadata elements is displayed in the output so that you can observe the change in the list after adding new values. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class AddMetadata { public static void main(final String[] args) throws IOException, SAXException, TikaException { //create a file object and assume sample.txt is in your current directory File file = new File("Example.txt"); //Parser method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); //parsing the document parser.parse(inputstream, handler, metadata, context); //list of meta data elements before adding new elements System.out.println( " metadata elements :" +Arrays.toString(metadata.names())); //adding new meta data name value pair metadata.add("Author","Tutorials Point"); System.out.println(" metadata name value pair is successfully added"); //printing all the meta data elements after adding new elements System.out.println("Here is the list of all the metadata elements after adding new elements"); System.out.println( Arrays.toString(metadata.names())); } } Save the above code as AddMetadata.java class and run it from the command prompt − javac AddMetadata .java java AddMetadata Given below is the content of Example.txt Hi students welcome to tutorialspoint If you execute the above program, it will give you the following output − metadata elements of the given file : [Content-Encoding, Content-Type] enter the number of metadata name value pairs to be added 1 enter metadata1name: Author enter metadata1value: Tutorials point metadata name value pair is successfully added Here is the list of all the metadata elements after adding new elements [Content-Encoding, Author, Content-Type] You can set values to the existing metadata elements using the set() method. The syntax of setting the date property using the set() method is as follows − metadata.set(Metadata.DATE, new Date()); You can also set multiple values to the properties using the set() method. The syntax of setting multiple values to the Author property using the set() method is as follows − metadata.set(Metadata.AUTHOR, "ram ,raheem ,robin "); Given below is the complete program demonstrating the set() method. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Date; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class SetMetadata { public static void main(final String[] args) throws IOException,SAXException, TikaException { //Create a file object and assume example.txt is in your current directory File file = new File("example.txt"); //parameters of parse() method Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); //Parsing the given file parser.parse(inputstream, handler, metadata, context); //list of meta data elements elements System.out.println( " metadata elements and values of the given file :"); String[] metadataNamesb4 = metadata.names(); for(String name : metadataNamesb4) { System.out.println(name + ": " + metadata.get(name)); } //setting date meta data metadata.set(Metadata.DATE, new Date()); //setting multiple values to author property metadata.set(Metadata.AUTHOR, "ram ,raheem ,robin "); //printing all the meta data elements with new elements System.out.println("List of all the metadata elements after adding new elements "); String[] metadataNamesafter = metadata.names(); for(String name : metadataNamesafter) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as SetMetadata.java and run it from the command prompt − javac SetMetadata.java java SetMetadata Given below is the content of example.txt. Hi students welcome to tutorialspoint If you execute the above program it will give you the following output. In the output, you can observe the newly added metadata elements. metadata elements and values of the given file : Content-Encoding: ISO-8859-1 Content-Type: text/plain; charset = ISO-8859-1 Here is the list of all the metadata elements after adding new elements date: 2014-09-24T07:01:32Z Content-Encoding: ISO-8859-1 Author: ram, raheem, robin Content-Type: text/plain; charset = ISO-8859-1 For classification of documents based on the language they are written in a multilingual website, a language detection tool is needed. This tool should accept documents without language annotation (metadata) and add that information in the metadata of the document by detecting the language. To detect the language of a document, a language profile is constructed and compared with the profile of the known languages. The text set of these known languages is known as a corpus. A corpus is a collection of texts of a written language that explains how the language is used in real situations. The corpus is developed from books, transcripts, and other data resources like the Internet. The accuracy of the corpus depends upon the profiling algorithm we use to frame the corpus. The common way of detecting languages is by using dictionaries. The words used in a given piece of text will be matched with those that are in the dictionaries. A list of common words used in a language will be the most simple and effective corpus for detecting a particular language, for example, articles a, an, the in English. Using word sets, a simple algorithm is framed to find the distance between two corpora, which will be equal to the sum of differences between the frequencies of matching words. Such algorithms suffer from the following problems − Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match. Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match. It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks. It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks. Due to these difficulties in using word sets as corpus, individual characters or character groups are considered. Since the characters that are commonly used in a language are finite in number, it is easy to apply an algorithm based on word frequencies rather than characters. This algorithm works even better in case of certain character sets used in one or very few languages. This algorithm suffers from the following drawbacks − It is difficult to differentiate two languages having similar character frequencies. It is difficult to differentiate two languages having similar character frequencies. There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages. There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages. The drawbacks stated above gave rise to a new approach of using character sequences of a given length for profiling corpus. Such sequence of characters are called as N-grams in general, where N represents the length of the character sequence. N-gram algorithm is an effective approach for language detection, especially in case of European languages like English. N-gram algorithm is an effective approach for language detection, especially in case of European languages like English. This algorithm works fine with short texts. This algorithm works fine with short texts. Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations. Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations. Among all the 184 standard languages standardized by ISO 639-1, Tika can detect 18 languages. Language detection in Tika is done using the getLanguage() method of the LanguageIdentifier class. This method returns the code name of the language in String format. Given below is the list of the 18 language-code pairs detected by Tika − While instantiating the LanguageIdentifier class, you should pass the String format of the content to be extracted, or a LanguageProfile class object. LanguageIdentifier object = new LanguageIdentifier(“this is english”); Given below is the example program for Language detection in Tika. import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.language.LanguageIdentifier; import org.xml.sax.SAXException; public class LanguageDetection { public static void main(String args[])throws IOException, SAXException, TikaException { LanguageIdentifier identifier = new LanguageIdentifier("this is english "); String language = identifier.getLanguage(); System.out.println("Language of the given content is : " + language); } } Save the above code as LanguageDetection.java and run it from the command prompt using the following commands − javac LanguageDetection.java java LanguageDetection If you execute the above program it gives the following outpu− Language of the given content is : en To detect the language of a given document, you have to parse it using the parse() method. The parse() method parses the content and stores it in the handler object, which was passed to it as one of the arguments. Pass the String format of the handler object to the constructor of the LanguageIdentifier class as shown below − parser.parse(inputstream, handler, metadata, context); LanguageIdentifier object = new LanguageIdentifier(handler.toString()); Given below is the complete program that demonstrates how to detect the language of a given document − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.language.*; import org.xml.sax.SAXException; public class DocumentLanguageDetection { public static void main(final String[] args) throws IOException, SAXException, TikaException { //Instantiating a file object File file = new File("Example.txt"); //Parser method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream content = new FileInputStream(file); //Parsing the given document parser.parse(content, handler, metadata, new ParseContext()); LanguageIdentifier object = new LanguageIdentifier(handler.toString()); System.out.println("Language name :" + object.getLanguage()); } } Save the above code as SetMetadata.java and run it from the command prompt − javac SetMetadata.java java SetMetadata Given below is the content of Example.txt. Hi students welcome to tutorialspoint If you execute the above program, it will give you the following output − Language name :en Along with the Tika jar, Tika provides a Graphical User Interface application (GUI) and a Command Line Interface (CLI) application. You can execute a Tika application from the command prompt too like other Java applications. Tika provides a jar file along with its source code in the following link https://tika.apache.org/download.html. Tika provides a jar file along with its source code in the following link https://tika.apache.org/download.html. Download both the files, set the classpath for the jar file. Download both the files, set the classpath for the jar file. Extract the source code zip folder, open the tika-app folder. Extract the source code zip folder, open the tika-app folder. In the extracted folder at “tika-1.6\tika-app\src\main\java\org\apache\Tika\gui” you will see two class files: ParsingTransferHandler.java and TikaGUI.java. In the extracted folder at “tika-1.6\tika-app\src\main\java\org\apache\Tika\gui” you will see two class files: ParsingTransferHandler.java and TikaGUI.java. Compile both the class files and execute the TikaGUI.java class file, it opens the following window. Compile both the class files and execute the TikaGUI.java class file, it opens the following window. Let us now see how to make use of the Tika GUI. On the GUI, click open, browse and select a file that is to be extracted, or drag it onto the whitespace of the window. Tika extracts the content of the files and displays it in five different formats, viz. metadata, formatted text, plain text, main content, and structured text. You can choose any of the format you want. In the same way, you will also find the CLI class in the “tika-1.6\tikaapp\src\main\java\org\apache\tika\cli” folder. The following illustration shows what Tika can do. When we drop the image on the GUI, Tika extracts and displays its metadata. Given below is the program to extract content and metadata from a PDF. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.pdf.PDFParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class PdfParse { public static void main(final String[] args) throws IOException,TikaException { BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("Example.pdf")); ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); pdfparser.parse(inputstream, handler, metadata,pcontext); //getting the content of the document System.out.println("Contents of the PDF :" + handler.toString()); //getting metadata of the document System.out.println("Metadata of the PDF:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name+ " : " + metadata.get(name)); } } } Save the above code as PdfParse.java, and compile it from the command prompt by using the following commands − javac PdfParse.java java PdfParse Below give is the snapshot of example.pdf The PDF we are passing has the following properties − After compiling the program, you will get the output as shown below. Output − Contents of the PDF: Apache Tika is a framework for content type detection and content extraction which was designed by Apache software foundation. It detects and extracts metadata and structured text content from different types of documents such as spreadsheets, text documents, images or PDFs including audio or video input formats to certain extent. Metadata of the PDF: dcterms:modified : 2014-09-28T12:31:16Z meta:creation-date : 2014-09-28T12:31:16Z meta:save-date : 2014-09-28T12:31:16Z dc:creator : Krishna Kasyap pdf:PDFVersion : 1.5 Last-Modified : 2014-09-28T12:31:16Z Author : Krishna Kasyap dcterms:created : 2014-09-28T12:31:16Z date : 2014-09-28T12:31:16Z modified : 2014-09-28T12:31:16Z creator : Krishna Kasyap xmpTPg:NPages : 1 Creation-Date : 2014-09-28T12:31:16Z pdf:encrypted : false meta:author : Krishna Kasyap created : Sun Sep 28 05:31:16 PDT 2014 dc:format : application/pdf; version = 1.5 producer : Microsoft® Word 2013 Content-Type : application/pdf xmp:CreatorTool : Microsoft® Word 2013 Last-Save-Date : 2014-09-28T12:31:16Z Given below is the program to extract content and metadata from Open Office Document Format (ODF). import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.odf.OpenDocumentParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class OpenDocumentParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example_open_document_presentation.odp")); ParseContext pcontext = new ParseContext(); //Open Document Parser OpenDocumentParser openofficeparser = new OpenDocumentParser (); openofficeparser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + " : " + metadata.get(name)); } } } Save the above code as OpenDocumentParse.java, and compile it in the command prompt by using the following commands − javac OpenDocumentParse.java java OpenDocumentParse Given below is snapshot of example_open_document_presentation.odp file. This document has the following properties − After compiling the program, you will get the following output. Output − Contents of the document: Apache Tika Apache Tika is a framework for content type detection and content extraction which was designed by Apache software foundation. It detects and extracts metadata and structured text content from different types of documents such as spreadsheets, text documents, images or PDFs including audio or video input formats to certain extent. Metadata of the document: editing-cycles: 4 meta:creation-date: 2009-04-16T11:32:32.86 dcterms:modified: 2014-09-28T07:46:13.03 meta:save-date: 2014-09-28T07:46:13.03 Last-Modified: 2014-09-28T07:46:13.03 dcterms:created: 2009-04-16T11:32:32.86 date: 2014-09-28T07:46:13.03 modified: 2014-09-28T07:46:13.03 nbObject: 36 Edit-Time: PT32M6S Creation-Date: 2009-04-16T11:32:32.86 Object-Count: 36 meta:object-count: 36 generator: OpenOffice/4.1.0$Win32 OpenOffice.org_project/410m18$Build-9764 Content-Type: application/vnd.oasis.opendocument.presentation Last-Save-Date: 2014-09-28T07:46:13.03 Given below is the program to extract content and metadata from a Microsoft Office Document. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.microsoft.ooxml.OOXMLParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class MSExcelParse { public static void main(final String[] args) throws IOException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example_msExcel.xlsx")); ParseContext pcontext = new ParseContext(); //OOXml parser OOXMLParser msofficeparser = new OOXMLParser (); msofficeparser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as MSExelParse.java, and compile it from the command prompt by using the following commands − javac MSExcelParse.java java MSExcelParse Here we are passing the following sample Excel file. The given Excel file has the following properties − After executing the above program you will get the following output. Output − Contents of the document: Sheet1 Name Age Designation Salary Ramu 50 Manager 50,000 Raheem 40 Assistant manager 40,000 Robert 30 Superviser 30,000 sita 25 Clerk 25,000 sameer 25 Section in-charge 20,000 Metadata of the document: meta:creation-date: 2006-09-16T00:00:00Z dcterms:modified: 2014-09-28T15:18:41Z meta:save-date: 2014-09-28T15:18:41Z Application-Name: Microsoft Excel extended-properties:Company: dcterms:created: 2006-09-16T00:00:00Z Last-Modified: 2014-09-28T15:18:41Z Application-Version: 15.0300 date: 2014-09-28T15:18:41Z publisher: modified: 2014-09-28T15:18:41Z Creation-Date: 2006-09-16T00:00:00Z extended-properties:AppVersion: 15.0300 protected: false dc:publisher: extended-properties:Application: Microsoft Excel Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Last-Save-Date: 2014-09-28T15:18:41Z Given below is the program to extract content and metadata from a Text document − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.parser.txt.TXTParser; import org.xml.sax.SAXException; public class TextParser { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example.txt")); ParseContext pcontext=new ParseContext(); //Text document parser TXTParser TexTParser = new TXTParser(); TexTParser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + " : " + metadata.get(name)); } } } Save the above code as TextParser.java, and compile it from the command prompt by using the following commands − javac TextParser.java java TextParser Given below is the snapshot of sample.txt file − The text document has the following properties − If you execute the above program it will give you the following output. Output − Contents of the document: At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose in the domains of Academics, Information Technology, Management and Computer Programming Languages. The endeavour started by Mohtashim, an AMU alumni, who is the founder and the managing director of Tutorials Point (I) Pvt. Ltd. He came up with the website tutorialspoint.com in year 2006 with the help of handpicked freelancers, with an array of tutorials for computer programming languages. Metadata of the document: Content-Encoding: windows-1252 Content-Type: text/plain; charset = windows-1252 Given below is the program to extract content and metadata from an HTML document. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.html.HtmlParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class HtmlParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example.html")); ParseContext pcontext = new ParseContext(); //Html parser HtmlParser htmlparser = new HtmlParser(); htmlparser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as HtmlParse.java, and compile it from the command prompt by using the following commands − javac HtmlParse.java java HtmlParse Given below is the snapshot of example.txt file. The HTML document has the following properties− If you execute the above program it will give you the following output. Output − Contents of the document: Name Salary age Ramesh Raman 50000 20 Shabbir Hussein 70000 25 Umesh Raman 50000 30 Somesh 50000 35 Metadata of the document: title: HTML Table Header Content-Encoding: windows-1252 Content-Type: text/html; charset = windows-1252 dc:title: HTML Table Header Given below is the program to extract content and metadata from an XML document − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.xml.XMLParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class XmlParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("pom.xml")); ParseContext pcontext = new ParseContext(); //Xml parser XMLParser xmlparser = new XMLParser(); xmlparser.parse(inputstream, handler, metadata, pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as XmlParse.java, and compile it from the command prompt by using the following commands − javac XmlParse.java java XmlParse Given below is the snapshot of example.xml file This document has the following properties − If you execute the above program it will give you the following output − Output − Contents of the document: 4.0.0 org.apache.tika tika 1.6 org.apache.tika tika-core 1.6 org.apache.tika tika-parsers 1.6 src maven-compiler-plugin 3.1 1.7 1.7 Metadata of the document: Content-Type: application/xml Given below is the program to extract content and metadata from a .class file. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.asm.ClassParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class JavaClassParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("Example.class")); ParseContext pcontext = new ParseContext(); //Html parser ClassParser ClassParser = new ClassParser(); ClassParser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + " : " + metadata.get(name)); } } } Save the above code as JavaClassParse.java, and compile it from the command prompt by using the following commands − javac JavaClassParse.java java JavaClassParse Given below is the snapshot of Example.java which will generate Example.class after compilation. Example.class file has the following properties − After executing the above program, you will get the following output. Output − Contents of the document: package tutorialspoint.tika.examples; public synchronized class Example { public void Example(); public static void main(String[]); } Metadata of the document: title: Example resourceName: Example.class dc:title: Example Given below is the program to extract content and metadata from a Java Archive (jar) file − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.parser.pkg.PackageParser; import org.xml.sax.SAXException; public class PackageParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("Example.jar")); ParseContext pcontext = new ParseContext(); //Package parser PackageParser packageparser = new PackageParser(); packageparser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document: " + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as PackageParse.java, and compile it from the command prompt by using the following commands − javac PackageParse.java java PackageParse Given below is the snapshot of Example.java that resides inside the package. The jar file has the following properties − After executing the above program, it will give you the following output − Output − Contents of the document: META-INF/MANIFEST.MF tutorialspoint/tika/examples/Example.class Metadata of the document: Content-Type: application/zip Given below is the program to extract content and meta data from a JPEG image. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.jpeg.JpegParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class JpegParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("boy.jpg")); ParseContext pcontext = new ParseContext(); //Jpeg Parse JpegParser JpegParser = new JpegParser(); JpegParser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands − javac JpegParse.java java JpegParse Given below is the snapshot of Example.jpeg − The JPEG file has the following properties − After executing the program, you will get the following output. Output − Contents of the document: Meta data of the document: Resolution Units: inch Compression Type: Baseline Data Precision: 8 bits Number of Components: 3 tiff:ImageLength: 3000 Component 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert Component 1: Y component: Quantization table 0, Sampling factors 2 horiz/2 vert Image Height: 3000 pixels X Resolution: 300 dots Original Transmission Reference: 53616c7465645f5f2368da84ca932841b336ac1a49edb1a93fae938b8db2cb3ec9cc4dc28d7383f1 Image Width: 4000 pixels IPTC-NAA record: 92 bytes binary data Component 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert tiff:BitsPerSample: 8 Application Record Version: 4 tiff:ImageWidth: 4000 Y Resolution: 300 dots Given below is the program to extract content and metadata from mp4 files − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.mp4.MP4Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class Mp4Parse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example.mp4")); ParseContext pcontext = new ParseContext(); //Html parser MP4Parser MP4Parser = new MP4Parser(); MP4Parser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document: :" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands − javac Mp4Parse.java java Mp4Parse Given below is the snapshot of properties of Example.mp4 file. After executing the above program, you will get the following output − Output − Contents of the document: Metadata of the document: dcterms:modified: 2014-01-06T12:10:27Z meta:creation-date: 1904-01-01T00:00:00Z meta:save-date: 2014-01-06T12:10:27Z Last-Modified: 2014-01-06T12:10:27Z dcterms:created: 1904-01-01T00:00:00Z date: 2014-01-06T12:10:27Z tiff:ImageLength: 360 modified: 2014-01-06T12:10:27Z Creation-Date: 1904-01-01T00:00:00Z tiff:ImageWidth: 640 Content-Type: video/mp4 Last-Save-Date: 2014-01-06T12:10:27Z Given below is the program to extract content and metadata from mp3 files − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.mp3.LyricsHandler; import org.apache.tika.parser.mp3.Mp3Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class Mp3Parse { public static void main(final String[] args) throws Exception, IOException, SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("example.mp3")); ParseContext pcontext = new ParseContext(); //Mp3 parser Mp3Parser Mp3Parser = new Mp3Parser(); Mp3Parser.parse(inputstream, handler, metadata, pcontext); LyricsHandler lyrics = new LyricsHandler(inputstream,handler); while(lyrics.hasLyrics()) { System.out.println(lyrics.toString()); } System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } } } Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands − javac Mp3Parse.java java Mp3Parse Example.mp3 file has the following properties − You will get the following output after executing the program. If the given file has any lyrics, our application will capture and display that along with the output. Output − Contents of the document: Kanulanu Thaake Arijit Singh Manam (2014), track 01/06 2014 Soundtrack 30171.65 eng - DRGM Arijit Singh Manam (2014), track 01/06 2014 Soundtrack 30171.65 eng - DRGM Metadata of the document: xmpDM:releaseDate: 2014 xmpDM:duration: 30171.650390625 xmpDM:audioChannelType: Stereo dc:creator: Arijit Singh xmpDM:album: Manam (2014) Author: Arijit Singh xmpDM:artist: Arijit Singh channels: 2 xmpDM:audioSampleRate: 44100 xmpDM:logComment: eng - DRGM xmpDM:trackNumber: 01/06 version: MPEG 3 Layer III Version 1 creator: Arijit Singh xmpDM:composer: Music : Anoop Rubens | Lyrics : Vanamali xmpDM:audioCompressor: MP3 title: Kanulanu Thaake samplerate: 44100 meta:author: Arijit Singh xmpDM:genre: Soundtrack Content-Type: audio/mpeg xmpDM:albumArtist: Manam (2014) dc:title: Kanulanu Thaake Print Add Notes Bookmark this page
[ { "code": null, "e": 2226, "s": 2110, "text": "Apache Tika is a library that is used for document type detection and content extraction from various file formats." }, { "code": null, "e": 2342, "s": 2226, "text": "Apache Tika is a library that is used for document type detection and content extraction from various file formats." }, { "code": null, "e": 2465, "s": 2342, "text": "Internally, Tika uses existing various document parsers and document type detection techniques to detect and extract data." }, { "code": null, "e": 2588, "s": 2465, "text": "Internally, Tika uses existing various document parsers and document type detection techniques to detect and extract data." }, { "code": null, "e": 2856, "s": 2588, "text": "Using Tika, one can develop a universal type detector and content extractor to extract both structured text as well as metadata from different types of documents such as spreadsheets, text documents, images, PDFs and even multimedia input formats to a certain extent." }, { "code": null, "e": 3124, "s": 2856, "text": "Using Tika, one can develop a universal type detector and content extractor to extract both structured text as well as metadata from different types of documents such as spreadsheets, text documents, images, PDFs and even multimedia input formats to a certain extent." }, { "code": null, "e": 3266, "s": 3124, "text": "Tika provides a single generic API for parsing different file formats. It uses existing specialized parser libraries for each document type." }, { "code": null, "e": 3408, "s": 3266, "text": "Tika provides a single generic API for parsing different file formats. It uses existing specialized parser libraries for each document type." }, { "code": null, "e": 3506, "s": 3408, "text": "All these parser libraries are encapsulated under a single interface called the Parser interface." }, { "code": null, "e": 3604, "s": 3506, "text": "All these parser libraries are encapsulated under a single interface called the Parser interface." }, { "code": null, "e": 4115, "s": 3604, "text": "According to filext.com, there are about 15k to 51k content types, and this number is growing day by day. Data is being stored in various formats such as text documents, excel spreadsheet, PDFs, images, and multimedia files, to name a few. Therefore, applications such as search engines and content management systems need additional support for easy extraction of data from these document types. Apache Tika serves this purpose by providing a generic API to locate and extract data from multiple file formats." }, { "code": null, "e": 4262, "s": 4115, "text": "There are various applications that make use of Apache Tika. Here we will discuss a few prominent applications that depend heavily on Apache Tika." }, { "code": null, "e": 4363, "s": 4262, "text": "Tika is widely used while developing search engines to index the text contents of digital documents." }, { "code": null, "e": 4480, "s": 4363, "text": "Search engines are information processing systems designed to search information and indexed documents from the Web." }, { "code": null, "e": 4597, "s": 4480, "text": "Search engines are information processing systems designed to search information and indexed documents from the Web." }, { "code": null, "e": 4841, "s": 4597, "text": "Crawler is an important component of a search engine that crawls through the Web to fetch the documents that are to be indexed using some indexing technique. Thereafter, the crawler transfers these indexed documents to an extraction component." }, { "code": null, "e": 5085, "s": 4841, "text": "Crawler is an important component of a search engine that crawls through the Web to fetch the documents that are to be indexed using some indexing technique. Thereafter, the crawler transfers these indexed documents to an extraction component." }, { "code": null, "e": 5287, "s": 5085, "text": "The duty of extraction component is to extract the text and metadata from the document. Such extracted content and metadata are very useful for a search engine. This extraction component contains Tika." }, { "code": null, "e": 5489, "s": 5287, "text": "The duty of extraction component is to extract the text and metadata from the document. Such extracted content and metadata are very useful for a search engine. This extraction component contains Tika." }, { "code": null, "e": 5690, "s": 5489, "text": "The extracted content is then passed to the indexer of the search engine that uses it to build a search index. Apart from this, the search engine uses the extracted content in many other ways as well." }, { "code": null, "e": 5891, "s": 5690, "text": "The extracted content is then passed to the indexer of the search engine that uses it to build a search index. Apart from this, the search engine uses the extracted content in many other ways as well." }, { "code": null, "e": 6050, "s": 5891, "text": "In the field of artificial intelligence, there are certain tools to analyze documents automatically at semantic level and extract all kinds of data from them." }, { "code": null, "e": 6209, "s": 6050, "text": "In the field of artificial intelligence, there are certain tools to analyze documents automatically at semantic level and extract all kinds of data from them." }, { "code": null, "e": 6331, "s": 6209, "text": "In such applications, the documents are classified based on the prominent terms in the extracted content of the document." }, { "code": null, "e": 6453, "s": 6331, "text": "In such applications, the documents are classified based on the prominent terms in the extracted content of the document." }, { "code": null, "e": 6572, "s": 6453, "text": "These tools make use of Tika for content extraction to analyze documents varying from plain text to digital documents." }, { "code": null, "e": 6691, "s": 6572, "text": "These tools make use of Tika for content extraction to analyze documents varying from plain text to digital documents." }, { "code": null, "e": 6862, "s": 6691, "text": "Some organizations manage their digital assets such as photographs, ebooks, drawings, music and video using a special application known as digital asset management (DAM)." }, { "code": null, "e": 7033, "s": 6862, "text": "Some organizations manage their digital assets such as photographs, ebooks, drawings, music and video using a special application known as digital asset management (DAM)." }, { "code": null, "e": 7150, "s": 7033, "text": "Such applications take the help of document type detectors and metadata extractor to classify the various documents." }, { "code": null, "e": 7267, "s": 7150, "text": "Such applications take the help of document type detectors and metadata extractor to classify the various documents." }, { "code": null, "e": 7716, "s": 7267, "text": "Websites like Amazon recommend newly released contents of their website to individual users according to their interests. To do so, these websites follow machine learning techniques, or take the help of social media websites like Facebook to extract required information such as likes and interests of the users. This gathered information will be in the form of html tags or other formats that require further content type detection and extraction." }, { "code": null, "e": 8165, "s": 7716, "text": "Websites like Amazon recommend newly released contents of their website to individual users according to their interests. To do so, these websites follow machine learning techniques, or take the help of social media websites like Facebook to extract required information such as likes and interests of the users. This gathered information will be in the form of html tags or other formats that require further content type detection and extraction." }, { "code": null, "e": 8375, "s": 8165, "text": "For content analysis of a document, we have technologies that implement machine learning techniques such as UIMA and Mahout. These technologies are useful in clustering and analyzing the data in the documents." }, { "code": null, "e": 8585, "s": 8375, "text": "For content analysis of a document, we have technologies that implement machine learning techniques such as UIMA and Mahout. These technologies are useful in clustering and analyzing the data in the documents." }, { "code": null, "e": 9059, "s": 8585, "text": "Apache Mahout is a framework which provides ML algorithms on Apache Hadoop – a cloud computing platform. Mahout provides an architecture by following certain clustering and filtering techniques. By following this architecture, programmers can write their own ML algorithms to produce recommendations by taking various text and metadata combinations. To provide inputs to these algorithms, recent versions of Mahout use Tika to extract text and metadata from binary content." }, { "code": null, "e": 9533, "s": 9059, "text": "Apache Mahout is a framework which provides ML algorithms on Apache Hadoop – a cloud computing platform. Mahout provides an architecture by following certain clustering and filtering techniques. By following this architecture, programmers can write their own ML algorithms to produce recommendations by taking various text and metadata combinations. To provide inputs to these algorithms, recent versions of Mahout use Tika to extract text and metadata from binary content." }, { "code": null, "e": 9702, "s": 9533, "text": "Apache UIMA analyzes and processes various programming languages and produces UIMA annotations. Internally it uses Tika Annotator to extract document text and metadata." }, { "code": null, "e": 9871, "s": 9702, "text": "Apache UIMA analyzes and processes various programming languages and produces UIMA annotations. Internally it uses Tika Annotator to extract document text and metadata." }, { "code": null, "e": 10019, "s": 9871, "text": "Application programmers can easily integrate Tika in their applications. Tika provides a Command Line Interface and a GUI to make it user friendly." }, { "code": null, "e": 10206, "s": 10019, "text": "In this chapter, we will discuss the four important modules that constitute the Tika architecture. The following illustration shows the architecture of Tika along with its four modules −" }, { "code": null, "e": 10236, "s": 10206, "text": "Language detection mechanism." }, { "code": null, "e": 10262, "s": 10236, "text": "MIME detection mechanism." }, { "code": null, "e": 10280, "s": 10262, "text": "Parser interface." }, { "code": null, "e": 10299, "s": 10280, "text": "Tika Facade class." }, { "code": null, "e": 10530, "s": 10299, "text": "Whenever a text document is passed to Tika, it will detect the language in which it was written. It accepts documents without language annotation and adds that information in the metadata of the document by detecting the language." }, { "code": null, "e": 10829, "s": 10530, "text": "To support language identification, Tika has a class called Language Identifier in the package org.apache.tika.language, and a language identification repository inside which contains algorithms for language detection from a given text. Tika internally uses N-gram algorithm for language detection." }, { "code": null, "e": 11072, "s": 10829, "text": "Tika can detect the document type according to the MIME standards. Default MIME type detection in Tika is done using org.apache.tika.mime.mimeTypes. It uses the org.apache.tika.detect.Detector interface for most of the content type detection." }, { "code": null, "e": 11213, "s": 11072, "text": "Internally Tika uses several techniques like file globs, content-type hints, magic bytes, character encodings, and several other techniques." }, { "code": null, "e": 11456, "s": 11213, "text": "The parser interface of org.apache.tika.parser is the key interface for parsing documents in Tika. This Interface extracts the text and the metadata from a document and summarizes it for external users who are willing to write parser plugins." }, { "code": null, "e": 11744, "s": 11456, "text": "Using different concrete parser classes, specific for individual document types, Tika supports a lot of document formats. These format specific classes provide support for different document formats, either by directly implementing the parser logic or by using external parser libraries." }, { "code": null, "e": 11947, "s": 11744, "text": "Using Tika facade class is the simplest and direct way of calling Tika from Java, and it follows the facade design pattern. You can find the Tika facade class in the org.apache.tika package of Tika API." }, { "code": null, "e": 12211, "s": 11947, "text": "By implementing basic use cases, Tika acts as a broker of landscape. It abstracts the underlying complexity of the Tika library such as MIME detection mechanism, parser interface, and language detection mechanism, and provides the users a simple interface to use." }, { "code": null, "e": 12473, "s": 12211, "text": "Unified parser Interface − Tika encapsulates all the third party parser libraries within a single parser interface. Due to this feature, the user escapes from the burden of selecting the suitable parser library and use it according to the file type encountered." }, { "code": null, "e": 12735, "s": 12473, "text": "Unified parser Interface − Tika encapsulates all the third party parser libraries within a single parser interface. Due to this feature, the user escapes from the burden of selecting the suitable parser library and use it according to the file type encountered." }, { "code": null, "e": 12952, "s": 12735, "text": "Low memory usage − Tika consumes less memory resources therefore it is easily embeddable with Java applications. We can also use Tika within the application which run on platforms with less resources like mobile PDA." }, { "code": null, "e": 13169, "s": 12952, "text": "Low memory usage − Tika consumes less memory resources therefore it is easily embeddable with Java applications. We can also use Tika within the application which run on platforms with less resources like mobile PDA." }, { "code": null, "e": 13261, "s": 13169, "text": "Fast processing − Quick content detection and extraction from applications can be expected." }, { "code": null, "e": 13353, "s": 13261, "text": "Fast processing − Quick content detection and extraction from applications can be expected." }, { "code": null, "e": 13448, "s": 13353, "text": "Flexible metadata − Tika understands all the metadata models which are used to describe files." }, { "code": null, "e": 13543, "s": 13448, "text": "Flexible metadata − Tika understands all the metadata models which are used to describe files." }, { "code": null, "e": 13660, "s": 13543, "text": "Parser integration − Tika can use various parser libraries available for each document type in a single application." }, { "code": null, "e": 13777, "s": 13660, "text": "Parser integration − Tika can use various parser libraries available for each document type in a single application." }, { "code": null, "e": 13892, "s": 13777, "text": "MIME type detection − Tika can detect and extract content from all the media types included in the MIME standards." }, { "code": null, "e": 14007, "s": 13892, "text": "MIME type detection − Tika can detect and extract content from all the media types included in the MIME standards." }, { "code": null, "e": 14162, "s": 14007, "text": "Language detection − Tika includes language identification feature, therefore can be used in documents based on language type in a multi lingual websites." }, { "code": null, "e": 14317, "s": 14162, "text": "Language detection − Tika includes language identification feature, therefore can be used in documents based on language type in a multi lingual websites." }, { "code": null, "e": 14357, "s": 14317, "text": "Tika supports various functionalities −" }, { "code": null, "e": 14381, "s": 14357, "text": "Document type detection" }, { "code": null, "e": 14400, "s": 14381, "text": "Content extraction" }, { "code": null, "e": 14420, "s": 14400, "text": "Metadata extraction" }, { "code": null, "e": 14439, "s": 14420, "text": "Language detection" }, { "code": null, "e": 14528, "s": 14439, "text": "Tika uses various detection techniques and detects the type of the document given to it." }, { "code": null, "e": 14831, "s": 14528, "text": "Tika has a parser library that can parse the content of various document formats and extract them. After detecting the type of the document, it selects the appropriate parser from the parser repository and passes the document. Different classes of Tika have methods to parse different document formats." }, { "code": null, "e": 15012, "s": 14831, "text": "Along with the content, Tika extracts the metadata of the document with the same procedure as in content extraction. For some document types, Tika have classes to extract metadata." }, { "code": null, "e": 15209, "s": 15012, "text": "Internally, Tika follows algorithms like n-gram to detect the language of the content in a given document. Tika depends on classes like Languageidentifier and Profiler for language identification." }, { "code": null, "e": 15364, "s": 15209, "text": "This chapter takes you through the process of setting up Apache Tika on Windows and Linux. User administration is needed while installing the Apache Tika." }, { "code": null, "e": 15450, "s": 15364, "text": "To verify Java installation, open the console and execute the following java command." }, { "code": null, "e": 15598, "s": 15450, "text": "If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on." }, { "code": null, "e": 15622, "s": 15598, "text": "Java version \"1.7.0_60\"" }, { "code": null, "e": 15679, "s": 15624, "text": "Java (TM) SE Run Time Environment (build 1.7.0_60-b19)" }, { "code": null, "e": 15744, "s": 15679, "text": "Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode)" }, { "code": null, "e": 15768, "s": 15744, "text": "java version \"1.7.0_25\"" }, { "code": null, "e": 15826, "s": 15768, "text": "Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)" }, { "code": null, "e": 15881, "s": 15826, "text": "Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)" }, { "code": null, "e": 16002, "s": 15881, "text": "We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial." }, { "code": null, "e": 16123, "s": 16002, "text": "We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial." }, { "code": null, "e": 16282, "s": 16123, "text": "In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed." }, { "code": null, "e": 16441, "s": 16282, "text": "In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed." }, { "code": null, "e": 16574, "s": 16441, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example," }, { "code": null, "e": 16645, "s": 16574, "text": "Append the full path of the Java compiler location to the System Path." }, { "code": null, "e": 16717, "s": 16645, "text": "Verify the command java-version from command prompt as explained above." }, { "code": null, "e": 16785, "s": 16717, "text": "Programmers can integrate Apache Tika in their environment by using" }, { "code": null, "e": 16799, "s": 16785, "text": "Command line," }, { "code": null, "e": 16809, "s": 16799, "text": "Tika API," }, { "code": null, "e": 16847, "s": 16809, "text": "Command line interface (CLI) of Tika," }, { "code": null, "e": 16890, "s": 16847, "text": "Graphical User interface (GUI) of Tika, or" }, { "code": null, "e": 16907, "s": 16890, "text": "the source code." }, { "code": null, "e": 16996, "s": 16907, "text": "For any of these approaches, first of all, you have to download the source code of Tika." }, { "code": null, "e": 17108, "s": 16996, "text": "You will find the source code of Tika at https://Tika.apache.org/download.html, where you will find two links −" }, { "code": null, "e": 17175, "s": 17108, "text": "apache-tika-1.6-src.zip − It contains the source code of Tika, and" }, { "code": null, "e": 17242, "s": 17175, "text": "apache-tika-1.6-src.zip − It contains the source code of Tika, and" }, { "code": null, "e": 17315, "s": 17242, "text": "Tika -app-1.6.jar − It is a jar file that contains the Tika application." }, { "code": null, "e": 17388, "s": 17315, "text": "Tika -app-1.6.jar − It is a jar file that contains the Tika application." }, { "code": null, "e": 17473, "s": 17388, "text": "Download these two files. A snapshot of the official website of Tika is shown below." }, { "code": null, "e": 17622, "s": 17473, "text": "After downloading the files, set the classpath for the jar file tika-app-1.6.jar. Add the complete path of the jar file as shown in the table below." }, { "code": null, "e": 17654, "s": 17622, "text": "Export CLASSPATH = $CLASSPATH −" }, { "code": null, "e": 17689, "s": 17654, "text": "/usr/share/jars/Tika-app-1.6.tar −" }, { "code": null, "e": 17783, "s": 17689, "text": "Apache provides Tika application, a Graphical User Interface (GUI) application using Eclipse." }, { "code": null, "e": 17822, "s": 17783, "text": "Open eclipse and create a new project." }, { "code": null, "e": 17861, "s": 17822, "text": "Open eclipse and create a new project." }, { "code": null, "e": 18079, "s": 17861, "text": "If you do not having Maven in your Eclipse, set it up by following the given steps.\n\nOpen the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format\n\n" }, { "code": null, "e": 18163, "s": 18079, "text": "If you do not having Maven in your Eclipse, set it up by following the given steps." }, { "code": null, "e": 18294, "s": 18163, "text": "Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format" }, { "code": null, "e": 18425, "s": 18294, "text": "Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format" }, { "code": null, "e": 18496, "s": 18425, "text": "Pick the latest version and save the path of the url in p2 url column." }, { "code": null, "e": 18567, "s": 18496, "text": "Pick the latest version and save the path of the url in p2 url column." }, { "code": null, "e": 18672, "s": 18567, "text": "Now revisit eclipse, in the menu bar, click Help, and choose Install New Software from the dropdown menu" }, { "code": null, "e": 18777, "s": 18672, "text": "Now revisit eclipse, in the menu bar, click Help, and choose Install New Software from the dropdown menu" }, { "code": null, "e": 18888, "s": 18777, "text": "Click the Add button, type any desired name, as it is optional. Now paste the saved url in the Location field." }, { "code": null, "e": 18999, "s": 18888, "text": "Click the Add button, type any desired name, as it is optional. Now paste the saved url in the Location field." }, { "code": null, "e": 19129, "s": 18999, "text": "A new plugin will be added with the name you have chosen in the previous step, check the checkbox in front of it, and click Next." }, { "code": null, "e": 19259, "s": 19129, "text": "A new plugin will be added with the name you have chosen in the previous step, check the checkbox in front of it, and click Next." }, { "code": null, "e": 19327, "s": 19259, "text": "Proceed with the installation. Once completed, restart the Eclipse." }, { "code": null, "e": 19395, "s": 19327, "text": "Proceed with the installation. Once completed, restart the Eclipse." }, { "code": null, "e": 19489, "s": 19395, "text": "Now right click on the project, and in the configure option, select convert to maven project." }, { "code": null, "e": 19583, "s": 19489, "text": "Now right click on the project, and in the configure option, select convert to maven project." }, { "code": null, "e": 19748, "s": 19583, "text": "A new wizard for creating a new pom appears. Enter the Group Id as org.apache.tika, enter the latest version of Tika, select the packaging as jar, and click Finish." }, { "code": null, "e": 19913, "s": 19748, "text": "A new wizard for creating a new pom appears. Enter the Group Id as org.apache.tika, enter the latest version of Tika, select the packaging as jar, and click Finish." }, { "code": null, "e": 20044, "s": 19913, "text": "The Maven project is successfully installed, and your project is converted into Maven. Now you have to configure the pom.xml file." }, { "code": null, "e": 20130, "s": 20044, "text": "Get the Tika maven dependency from https://mvnrepository.com/artifact/org.apache.tika" }, { "code": null, "e": 20191, "s": 20130, "text": "Shown below is the complete Maven dependency of Apache Tika." }, { "code": null, "e": 20855, "s": 20191, "text": "<dependency>\n <groupId>org.apache.Tika</groupId>\n <artifactId>Tika-core</artifactId>\n <version>1.6</version>\n\n <groupId>org.apache.Tika</groupId>\n <artifactId> Tika-parsers</artifactId>\n <version> 1.6</version>\n\n <groupId> org.apache.Tika</groupId>\n <artifactId>Tika</artifactId>\n <version>1.6</version>\n\n <groupId>org.apache.Tika</groupId>\n < artifactId>Tika-serialization</artifactId>\n < version>1.6< /version>\n\n < groupId>org.apache.Tika< /groupId>\n < artifactId>Tika-app< /artifactId>\n < version>1.6< /version>\n\n <groupId>org.apache.Tika</groupId>\n <artifactId>Tika-bundle</artifactId>\n <version>1.6</version>\n</dependency>" }, { "code": null, "e": 21157, "s": 20855, "text": "Users can embed Tika in their applications using the Tika facade class. It has methods to explore all the functionalities of Tika. Since it is a facade class, Tika abstracts the complexity behind its functions. In addition to this, users can also use the various classes of Tika in their applications." }, { "code": null, "e": 21458, "s": 21157, "text": "This is the most prominent class of the Tika library and follows the facade design pattern. Therefore, it abstracts all the internal implementations and provides simple methods to access the Tika functionalities. The following table lists the constructors of this class along with their descriptions." }, { "code": null, "e": 21484, "s": 21458, "text": "package − org.apache.tika" }, { "code": null, "e": 21497, "s": 21484, "text": "class − Tika" }, { "code": null, "e": 21505, "s": 21497, "text": "Tika ()" }, { "code": null, "e": 21563, "s": 21505, "text": "Uses default configuration and constructs the Tika class." }, { "code": null, "e": 21588, "s": 21563, "text": "Tika (Detector detector)" }, { "code": null, "e": 21658, "s": 21588, "text": "Creates a Tika facade by accepting the detector instance as parameter" }, { "code": null, "e": 21698, "s": 21658, "text": "Tika (Detector detector, Parser parser)" }, { "code": null, "e": 21782, "s": 21698, "text": "Creates a Tika facade by accepting the detector and parser instances as parameters." }, { "code": null, "e": 21845, "s": 21782, "text": "Tika (Detector detector, Parser parser, Translator translator)" }, { "code": null, "e": 21949, "s": 21845, "text": "Creates a Tika facade by accepting the detector, the parser, and the translator instance as parameters." }, { "code": null, "e": 21974, "s": 21949, "text": "Tika (TikaConfig config)" }, { "code": null, "e": 22058, "s": 21974, "text": "Creates a Tika facade by accepting the object of the TikaConfig class as parameter." }, { "code": null, "e": 22121, "s": 22058, "text": "The following are the important methods of Tika facade class −" }, { "code": null, "e": 22147, "s": 22121, "text": "parseToString (File file)" }, { "code": null, "e": 22337, "s": 22147, "text": "This method and all its variants parses the file passed as parameter and returns the extracted text content in the String format. By default, the length of this string parameter is limited." }, { "code": null, "e": 22363, "s": 22337, "text": "int getMaxStringLength ()" }, { "code": null, "e": 22440, "s": 22363, "text": "Returns the maximum length of strings returned by the parseToString methods." }, { "code": null, "e": 22486, "s": 22440, "text": "void setMaxStringLength (int maxStringLength)" }, { "code": null, "e": 22560, "s": 22486, "text": "Sets the maximum length of strings returned by the parseToString methods." }, { "code": null, "e": 22585, "s": 22560, "text": "Reader parse (File file)" }, { "code": null, "e": 22731, "s": 22585, "text": "This method and all its variants parses the file passed as parameter and returns the extracted text content in the form of java.io.reader object." }, { "code": null, "e": 22785, "s": 22731, "text": "String detect (InputStream stream, Metadata metadata)" }, { "code": null, "e": 23039, "s": 22785, "text": "This method and all its variants accepts an InputStream object and a Metadata object as parameters, detects the type of the given document, and returns the document type name as String object. This method abstracts the detection mechanisms used by Tika." }, { "code": null, "e": 23098, "s": 23039, "text": "String translate (InputStream text, String targetLanguage)" }, { "code": null, "e": 23343, "s": 23098, "text": "This method and all its variants accepts the InputStream object and a String representing the language that we want our text to be translated, and translates the given text to the desired language, attempting to auto-detect the source language." }, { "code": null, "e": 23428, "s": 23343, "text": "This is the interface that is implemented by all the parser classes of Tika package." }, { "code": null, "e": 23461, "s": 23428, "text": "package − org.apache.tika.parser" }, { "code": null, "e": 23480, "s": 23461, "text": "Interface − Parser" }, { "code": null, "e": 23545, "s": 23480, "text": "The following is the important method of Tika Parser interface −" }, { "code": null, "e": 23637, "s": 23545, "text": "parse (InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)" }, { "code": null, "e": 23868, "s": 23637, "text": "This method parses the given document into a sequence of XHTML and SAX events. After parsing, it places the extracted document content in the object of the ContentHandler class and the metadata in the object of the Metadata class." }, { "code": null, "e": 24177, "s": 23868, "text": "This class implements various interfaces such as CreativeCommons, Geographic, HttpHeaders, Message, MSOffice, ClimateForcast, TIFF, TikaMetadataKeys, TikaMimeKeys, Serializable to support various data models. The following tables list the constructors and methods of this class along with their descriptions." }, { "code": null, "e": 24212, "s": 24177, "text": "package − org.apache.tika.metadata" }, { "code": null, "e": 24229, "s": 24212, "text": "class − Metadata" }, { "code": null, "e": 24240, "s": 24229, "text": "Metadata()" }, { "code": null, "e": 24274, "s": 24240, "text": "Constructs a new, empty metadata." }, { "code": null, "e": 24312, "s": 24274, "text": "add (Property property, String value)" }, { "code": null, "e": 24429, "s": 24312, "text": "Adds a metadata property/value mapping to a given document. Using this function, we can set the value to a property." }, { "code": null, "e": 24461, "s": 24429, "text": "add (String name, String value)" }, { "code": null, "e": 24608, "s": 24461, "text": "Adds a metadata property/value mapping to a given document. Using this method, we can set a new name value to the existing metadata of a document." }, { "code": null, "e": 24639, "s": 24608, "text": "String get (Property property)" }, { "code": null, "e": 24698, "s": 24639, "text": "Returns the value (if any) of the metadata property given." }, { "code": null, "e": 24723, "s": 24698, "text": "String get (String name)" }, { "code": null, "e": 24778, "s": 24723, "text": "Returns the value (if any) of the metadata name given." }, { "code": null, "e": 24811, "s": 24778, "text": "Date getDate (Property property)" }, { "code": null, "e": 24856, "s": 24811, "text": "Returns the value of Date metadata property." }, { "code": null, "e": 24895, "s": 24856, "text": "String[] getValues (Property property)" }, { "code": null, "e": 24942, "s": 24895, "text": "Returns all the values of a metadata property." }, { "code": null, "e": 24975, "s": 24942, "text": "String[] getValues (String name)" }, { "code": null, "e": 25024, "s": 24975, "text": "Returns all the values of a given metadata name." }, { "code": null, "e": 25041, "s": 25024, "text": "String[] names()" }, { "code": null, "e": 25106, "s": 25041, "text": "Returns all the names of metadata elements in a metadata object." }, { "code": null, "e": 25141, "s": 25106, "text": "set (Property property, Date date)" }, { "code": null, "e": 25193, "s": 25141, "text": " Sets the date value of the given metadata property" }, { "code": null, "e": 25233, "s": 25193, "text": "set(Property property, String[] values)" }, { "code": null, "e": 25278, "s": 25233, "text": "Sets multiple values to a metadata property." }, { "code": null, "e": 25423, "s": 25278, "text": "This class identifies the language of the given content. The following tables list the constructors of this class along with their descriptions." }, { "code": null, "e": 25458, "s": 25423, "text": "package − org.apache.tika.language" }, { "code": null, "e": 25486, "s": 25458, "text": "class − Language Identifier" }, { "code": null, "e": 25531, "s": 25486, "text": "LanguageIdentifier (LanguageProfile profile)" }, { "code": null, "e": 25630, "s": 25531, "text": "Instantiates the language identifier. Here you have to pass a LanguageProfile object as parameter." }, { "code": null, "e": 25666, "s": 25630, "text": "LanguageIdentifier (String content)" }, { "code": null, "e": 25763, "s": 25666, "text": "This constructor can instantiate a language identifier by passing on a String from text content." }, { "code": null, "e": 25785, "s": 25763, "text": "String getLanguage ()" }, { "code": null, "e": 25854, "s": 25785, "text": "Returns the language given to the current LanguageIdentifier object." }, { "code": null, "e": 25912, "s": 25854, "text": "The following table shows the file formats Tika supports." }, { "code": null, "e": 25945, "s": 25912, "text": "org.apache.tika.parser.microsoft" }, { "code": null, "e": 26015, "s": 25945, "text": "org.apache.tika.parser.microsoft.ooxml and it uses Apache Poi library" }, { "code": null, "e": 26034, "s": 26015, "text": "OfficeParser(ole2)" }, { "code": null, "e": 26054, "s": 26034, "text": "OOXMLParser (ooxml)" }, { "code": null, "e": 26255, "s": 26054, "text": "Multipurpose Internet Mail Extensions (MIME) standards are the best available standards for identifying document types. The knowledge of these standards helps the browser during internal interactions." }, { "code": null, "e": 26526, "s": 26255, "text": "Whenever the browser encounters a media file, it chooses a compatible software available with it to display its contents. In case it does not have any suitable application to run a particular media file, it recommends the user to get the suitable plugin software for it." }, { "code": null, "e": 26749, "s": 26526, "text": "Tika supports all the Internet media document types provided in MIME. Whenever a file is passed through Tika, it detects the file and its document type. To detect media types, Tika internally uses the following mechanisms." }, { "code": null, "e": 26989, "s": 26749, "text": "Checking the file extensions is the simplest and most-widely used method to detect the format of a file. Many applications and operating systems provide support for these extensions. Shown below are the extension of a few known file types." }, { "code": null, "e": 27200, "s": 26989, "text": "Whenever you retrieve a file from a database or attach it to another document, you may lose the file’s name or extension. In such cases, the metadata supplied with the file is used to detect the file extension." }, { "code": null, "e": 27443, "s": 27200, "text": "Observing the raw bytes of a file, you can find some unique character patterns for each file. Some files have special byte prefixes called magic bytes that are specially made and included in a file for the purpose of identifying the file type" }, { "code": null, "e": 27621, "s": 27443, "text": "For example, you can find CA FE BA BE (hexadecimal format) in a java file and %PDF (ASCII format) in a pdf file. Tika uses this information to identify the media type of a file." }, { "code": null, "e": 27934, "s": 27621, "text": "Files with plain text are encoded using different types of character encoding. The main challenge here is to identify the type of character encoding used in the files. Tika follows character encoding techniques like Bom markers and Byte Frequencies to identify the encoding system used by the plain text content." }, { "code": null, "e": 28134, "s": 27934, "text": "To detect XML documents, Tika parses the xml documents and extracts the information such as root elements, namespaces, and referenced schemas from where the true media type of the files can be found." }, { "code": null, "e": 28330, "s": 28134, "text": "The detect() method of facade class is used to detect the document type. This method accepts a file as input. Shown below is an example program for document type detection with Tika facade class." }, { "code": null, "e": 28798, "s": 28330, "text": "import java.io.File;\n\nimport org.apache.tika.Tika;\n\npublic class Typedetection {\n\n public static void main(String[] args) throws Exception {\n\n //assume example.mp3 is in your current directory\n File file = new File(\"example.mp3\");//\n \n //Instantiating tika facade class \n Tika tika = new Tika();\n \n //detecting the file type using detect method\n String filetype = tika.detect(file);\n System.out.println(filetype);\n }\n}" }, { "code": null, "e": 28906, "s": 28798, "text": "Save the above code as TypeDetection.java and run it from the command prompt using the following commands −" }, { "code": null, "e": 28963, "s": 28906, "text": "javac TypeDetection.java\njava TypeDetection \n\naudio/mpeg" }, { "code": null, "e": 29105, "s": 28963, "text": "Tika uses various parser libraries to extract content from given parsers. It chooses the right parser for extracting the given document type." }, { "code": null, "e": 29315, "s": 29105, "text": "For parsing documents, the parseToString() method of Tika facade class is generally used. Shown below are the steps involved in the parsing process and these are abstracted by the Tika ParsertoString() method." }, { "code": null, "e": 29349, "s": 29315, "text": "Abstracting the parsing process −" }, { "code": null, "e": 29485, "s": 29349, "text": "Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type." }, { "code": null, "e": 29621, "s": 29485, "text": "Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type." }, { "code": null, "e": 29787, "s": 29621, "text": "Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries." }, { "code": null, "e": 29953, "s": 29787, "text": "Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries." }, { "code": null, "e": 30100, "s": 29953, "text": "Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats." }, { "code": null, "e": 30247, "s": 30100, "text": "Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats." }, { "code": null, "e": 30332, "s": 30247, "text": "Given below is the program for extracting text from a file using Tika facade class −" }, { "code": null, "e": 30921, "s": 30332, "text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.tika.Tika;\nimport org.apache.tika.exception.TikaException;\n\nimport org.xml.sax.SAXException;\n\npublic class TikaExtraction {\n\t\n public static void main(final String[] args) throws IOException, TikaException {\n\n //Assume sample.txt is in your current directory\t\t \n File file = new File(\"sample.txt\");\n \n //Instantiating Tika facade class\n Tika tika = new Tika();\n String filecontent = tika.parseToString(file);\n System.out.println(\"Extracted Content: \" + filecontent);\n }\t\t \n}" }, { "code": null, "e": 31001, "s": 30921, "text": "Save the above code as TikaExtraction.java and run it from the command prompt −" }, { "code": null, "e": 31049, "s": 31001, "text": "javac TikaExtraction.java \njava TikaExtraction\n" }, { "code": null, "e": 31091, "s": 31049, "text": "Given below is the content of sample.txt." }, { "code": null, "e": 31130, "s": 31091, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 31166, "s": 31130, "text": "It gives you the following output −" }, { "code": null, "e": 31224, "s": 31166, "text": "Extracted Content: Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 31405, "s": 31224, "text": "The parser package of Tika provides several interfaces and classes using which we can parse a text document. Given below is the block diagram of the org.apache.tika.parser package." }, { "code": null, "e": 31592, "s": 31405, "text": "There are several parser classes available, e.g., pdf parser, Mp3Passer, OfficeParser, etc., to parse respective documents individually. All these classes implement the parser interface." }, { "code": null, "e": 31920, "s": 31592, "text": "The given diagram shows Tika’s general-purpose parser classes: CompositeParser and AutoDetectParser. Since the CompositeParser class follows composite design pattern, you can use a group of parser instances as a single parser. The CompositeParser class also allows access to all the classes that implement the parser interface." }, { "code": null, "e": 32157, "s": 31920, "text": "This is a subclass of CompositeParser and it provides automatic type detection. Using this functionality, the AutoDetectParser automatically sends the incoming documents to the appropriate parser classes using the composite methodology." }, { "code": null, "e": 32291, "s": 32157, "text": "Along with parseToString(), you can also use the parse() method of the parser Interface. The prototype of this method is shown below." }, { "code": null, "e": 32382, "s": 32291, "text": "parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)" }, { "code": null, "e": 32451, "s": 32382, "text": "The following table lists the four objects it accepts as parameters." }, { "code": null, "e": 32470, "s": 32451, "text": "InputStream stream" }, { "code": null, "e": 32531, "s": 32470, "text": "Any Inputstream object that contains the content of the file" }, { "code": null, "e": 32554, "s": 32531, "text": "ContentHandler handler" }, { "code": null, "e": 32733, "s": 32554, "text": "Tika passes the document as XHTML content to this handler, thereafter the document is processed using SAX API. It provides efficient postprocessing of the contents in a document." }, { "code": null, "e": 32751, "s": 32733, "text": "Metadata metadata" }, { "code": null, "e": 32831, "s": 32751, "text": "The metadata object is used both as a source and a target of document metadata." }, { "code": null, "e": 32852, "s": 32831, "text": "ParseContext context" }, { "code": null, "e": 32950, "s": 32852, "text": "This object is used in cases where the client application wants to customize the parsing process." }, { "code": null, "e": 33019, "s": 32950, "text": "Given below is an example that shows how the parse() method is used." }, { "code": null, "e": 33028, "s": 33019, "text": "Step 1 −" }, { "code": null, "e": 33159, "s": 33028, "text": "To use the parse() method of the parser interface, instantiate any of the classes providing the implementation for this interface." }, { "code": null, "e": 33477, "s": 33159, "text": "There are individual parser classes such as PDFParser, OfficeParser, XMLParser, etc. You can use any of these individual document parsers. Alternatively, you can use either CompositeParser or AutoDetectParser that uses all the parser classes internally and extracts the contents of a document using a suitable parser." }, { "code": null, "e": 33638, "s": 33477, "text": "Parser parser = new AutoDetectParser();\n (or)\nParser parser = new CompositeParser(); \n (or) \nobject of any individual parsers given in Tika Library " }, { "code": null, "e": 33647, "s": 33638, "text": "Step 2 −" }, { "code": null, "e": 33723, "s": 33647, "text": "Create a handler class object. Given below are the three content handlers −" }, { "code": null, "e": 33742, "s": 33723, "text": "BodyContentHandler" }, { "code": null, "e": 33929, "s": 33742, "text": "This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance." }, { "code": null, "e": 33948, "s": 33929, "text": "LinkContentHandler" }, { "code": null, "e": 34077, "s": 33948, "text": "This class detects and picks all the H-Ref tags of the XHTML document and forwards those for the use of tools like web crawlers." }, { "code": null, "e": 34095, "s": 34077, "text": "TeeContentHandler" }, { "code": null, "e": 34152, "s": 34095, "text": "This class helps in using multiple tools simultaneously." }, { "code": null, "e": 34266, "s": 34152, "text": "Since our target is to extract the text contents from a document, instantiate BodyContentHandler as shown below −" }, { "code": null, "e": 34322, "s": 34266, "text": "BodyContentHandler handler = new BodyContentHandler( );" }, { "code": null, "e": 34331, "s": 34322, "text": "Step 3 −" }, { "code": null, "e": 34375, "s": 34331, "text": "Create the Metadata object as shown below −" }, { "code": null, "e": 34411, "s": 34375, "text": "Metadata metadata = new Metadata();" }, { "code": null, "e": 34420, "s": 34411, "text": "Step 4 −" }, { "code": null, "e": 34511, "s": 34420, "text": "Create any of the input stream objects, and pass your file that should be extracted to it." }, { "code": null, "e": 34638, "s": 34511, "text": "Instantiate a file object by passing the file path as parameter and pass this object to the FileInputStream class constructor." }, { "code": null, "e": 34707, "s": 34638, "text": "Note − The path passed to the file object should not contain spaces." }, { "code": null, "e": 34915, "s": 34707, "text": "The problem with these input stream classes is that they don’t support random access reads, which is required to process some file formats efficiently. To resolve this problem, Tika provides TikaInputStream." }, { "code": null, "e": 35074, "s": 34915, "text": "File file = new File(filepath)\nFileInputStream inputstream = new FileInputStream(file);\n (or)\nInputStream stream = TikaInputStream.get(new File(filename));" }, { "code": null, "e": 35083, "s": 35074, "text": "Step 5 −" }, { "code": null, "e": 35130, "s": 35083, "text": "Create a parse context object as shown below −" }, { "code": null, "e": 35172, "s": 35130, "text": "ParseContext context =new ParseContext();" }, { "code": null, "e": 35181, "s": 35172, "text": "Step 6 −" }, { "code": null, "e": 35306, "s": 35181, "text": "Instantiate the parser object, invoke the parse method, and pass all the objects required, as shown in the prototype below −" }, { "code": null, "e": 35361, "s": 35306, "text": "parser.parse(inputstream, handler, metadata, context);" }, { "code": null, "e": 35440, "s": 35361, "text": "Given below is the program for content extraction using the parser interface −" }, { "code": null, "e": 36519, "s": 35440, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class ParserExtraction {\n\t\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //Assume sample.txt is in your current directory\n File file = new File(\"sample.txt\");\n \n //parse method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(file);\n ParseContext context = new ParseContext();\n \n //parsing the file\n parser.parse(inputstream, handler, metadata, context);\n System.out.println(\"File content : \" + Handler.toString());\n }\n}" }, { "code": null, "e": 36601, "s": 36519, "text": "Save the above code as ParserExtraction.java and run it from the command prompt −" }, { "code": null, "e": 36655, "s": 36601, "text": "javac ParserExtraction.java \njava ParserExtraction\n" }, { "code": null, "e": 36696, "s": 36655, "text": "Given below is the content of sample.txt" }, { "code": null, "e": 36735, "s": 36696, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 36809, "s": 36735, "text": "If you execute the above program, it will give you the following output −" }, { "code": null, "e": 36863, "s": 36809, "text": "File content : Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 37085, "s": 36863, "text": "Besides content, Tika also extracts the metadata from a file. Metadata is nothing but the additional information supplied with a file. If we consider an audio file, the artist name, album name, title comes under metadata." }, { "code": null, "e": 37422, "s": 37085, "text": "The Extensible Metadata Platform (XMP) is a standard for processing and storing information related to the content of a file. It was created by Adobe Systems Inc. XMP provides standards for defining, creating, and processing of metadata. You can embed this standard into several file formats such as PDF, JPEG, JPEG, GIF, jpg, HTML etc." }, { "code": null, "e": 37580, "s": 37422, "text": "Tika uses the Property class to follow XMP property definition. It provides the PropertyType and ValueType enums to capture the name and value of a metadata." }, { "code": null, "e": 37815, "s": 37580, "text": "This class implements various interfaces such as ClimateForcast, CativeCommons, Geographic, TIFF etc. to provide support for various metadata models. In addition, this class provides various methods to extract the content from a file." }, { "code": null, "e": 38108, "s": 37815, "text": "We can extract the list of all metadata names of a file from its metadata object using the method names(). It returns all the names as a string array. Using the name of the metadata, we can get the value using the get() method. It takes a metadata name and returns a value associated with it." }, { "code": null, "e": 38186, "s": 38108, "text": "String[] metadaNames = metadata.names();\n\nString value = metadata.get(name);\n" }, { "code": null, "e": 38501, "s": 38186, "text": "Whenever we parse a file using parse(), we pass an empty metadata object as one of the parameters. This method extracts the metadata of the given file (if that file contains any), and places them in the metadata object. Therefore, after parsing the file using parse(), we can extract the metadata from that object." }, { "code": null, "e": 38922, "s": 38501, "text": "Parser parser = new AutoDetectParser();\nBodyContentHandler handler = new BodyContentHandler();\nMetadata metadata = new Metadata(); //empty metadata object \nFileInputStream inputstream = new FileInputStream(file);\nParseContext context = new ParseContext();\nparser.parse(inputstream, handler, metadata, context);\n\n// now this metadata object contains the extracted metadata of the given file.\nmetadata.metadata.names();\n" }, { "code": null, "e": 38996, "s": 38922, "text": "Given below is the complete program to extract metadata from a text file." }, { "code": null, "e": 40232, "s": 38996, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class GetMetadata {\n\t\n public static void main(final String[] args) throws IOException, TikaException {\n\t\n //Assume that boy.jpg is in your current directory\n File file = new File(\"boy.jpg\");\n\n //Parser method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(file);\n ParseContext context = new ParseContext();\n \n parser.parse(inputstream, handler, metadata, context);\n System.out.println(handler.toString());\n\n //getting the list of all meta data elements \n String[] metadataNames = metadata.names();\n\n for(String name : metadataNames) {\t\t \n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 40338, "s": 40232, "text": "Save the above code as GetMetadata.java and run it from the command prompt using the following commands −" }, { "code": null, "e": 40382, "s": 40338, "text": "javac GetMetadata .java\njava GetMetadata\n" }, { "code": null, "e": 40421, "s": 40382, "text": "Given below is the snapshot of boy.jpg" }, { "code": null, "e": 40495, "s": 40421, "text": "If you execute the above program, it will give you the following output −" }, { "code": null, "e": 41259, "s": 40495, "text": "X-Parsed-By: org.apache.tika.parser.DefaultParser\nResolution Units: inch\nCompression Type: Baseline\nData Precision: 8 bits\nNumber of Components: 3\ntiff:ImageLength: 3000\nComponent 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert\nComponent 1: Y component: Quantization table 0, Sampling factors 2 horiz/2 vert\nImage Height: 3000 pixels\nX Resolution: 300 dots\nOriginal Transmission Reference:\n 53616c7465645f5f2368da84ca932841b336ac1a49edb1a93fae938b8db2cb3ec9cc4dc28d7383f1\nImage Width: 4000 pixels\nIPTC-NAA record: 92 bytes binary data\nComponent 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert\ntiff:BitsPerSample: 8\nApplication Record Version: 4\ntiff:ImageWidth: 4000\nContent-Type: image/jpeg\nY Resolution: 300 dots\n" }, { "code": null, "e": 41304, "s": 41259, "text": "We can also get our desired metadata values." }, { "code": null, "e": 41459, "s": 41304, "text": "We can add new metadata values using the add() method of the metadata class. Given below is the syntax of this method. Here we are adding the author name." }, { "code": null, "e": 41503, "s": 41459, "text": "metadata.add(“author”,”Tutorials point”); \n" }, { "code": null, "e": 41844, "s": 41503, "text": "The Metadata class has predefined properties including the properties inherited from classes like ClimateForcast, CativeCommons, Geographic, etc., to support various data models. Shown below is the usage of the SOFTWARE data type inherited from the TIFF interface implemented by Tika to follow XMP metadata standards for TIFF image formats." }, { "code": null, "e": 41889, "s": 41844, "text": "metadata.add(Metadata.SOFTWARE,\"ms paint\");\n" }, { "code": null, "e": 42125, "s": 41889, "text": "Given below is the complete program that demonstrates how to add metadata values to a given file. Here the list of the metadata elements is displayed in the output so that you can observe the change in the list after adding new values." }, { "code": null, "e": 43748, "s": 42125, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.Arrays;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class AddMetadata {\n\n public static void main(final String[] args) throws IOException, SAXException, TikaException {\n\n //create a file object and assume sample.txt is in your current directory\n File file = new File(\"Example.txt\");\n\n //Parser method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(file);\n ParseContext context = new ParseContext();\n\n //parsing the document\n parser.parse(inputstream, handler, metadata, context);\n\n //list of meta data elements before adding new elements\n System.out.println( \" metadata elements :\" +Arrays.toString(metadata.names()));\n\n //adding new meta data name value pair\n metadata.add(\"Author\",\"Tutorials Point\");\n System.out.println(\" metadata name value pair is successfully added\");\n \n //printing all the meta data elements after adding new elements\n System.out.println(\"Here is the list of all the metadata \n elements after adding new elements\");\n System.out.println( Arrays.toString(metadata.names()));\n }\n}" }, { "code": null, "e": 43831, "s": 43748, "text": "Save the above code as AddMetadata.java class and run it from the command prompt −" }, { "code": null, "e": 43876, "s": 43831, "text": "javac AddMetadata .java \njava AddMetadata\n" }, { "code": null, "e": 43918, "s": 43876, "text": "Given below is the content of Example.txt" }, { "code": null, "e": 43957, "s": 43918, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 44031, "s": 43957, "text": "If you execute the above program, it will give you the following output −" }, { "code": null, "e": 44395, "s": 44031, "text": "metadata elements of the given file :\n[Content-Encoding, Content-Type] \nenter the number of metadata name value pairs to be added 1\nenter metadata1name: \nAuthor enter metadata1value: \nTutorials point metadata name value pair is successfully added\nHere is the list of all the metadata elements after adding new elements\n[Content-Encoding, Author, Content-Type] \n" }, { "code": null, "e": 44551, "s": 44395, "text": "You can set values to the existing metadata elements using the set() method. The syntax of setting the date property using the set() method is as follows −" }, { "code": null, "e": 44593, "s": 44551, "text": "metadata.set(Metadata.DATE, new Date());\n" }, { "code": null, "e": 44768, "s": 44593, "text": "You can also set multiple values to the properties using the set() method. The syntax of setting multiple values to the Author property using the set() method is as follows −" }, { "code": null, "e": 44823, "s": 44768, "text": "metadata.set(Metadata.AUTHOR, \"ram ,raheem ,robin \");\n" }, { "code": null, "e": 44891, "s": 44823, "text": "Given below is the complete program demonstrating the set() method." }, { "code": null, "e": 46813, "s": 44891, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport java.util.Date;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class SetMetadata {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n \n //Create a file object and assume example.txt is in your current directory\n File file = new File(\"example.txt\");\n \n //parameters of parse() method\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(file);\n ParseContext context = new ParseContext();\n \n //Parsing the given file\n parser.parse(inputstream, handler, metadata, context);\n \n //list of meta data elements elements\n System.out.println( \" metadata elements and values of the given file :\");\n String[] metadataNamesb4 = metadata.names();\n \n for(String name : metadataNamesb4) {\n \t System.out.println(name + \": \" + metadata.get(name));\n }\n \n //setting date meta data \n metadata.set(Metadata.DATE, new Date());\n \n //setting multiple values to author property\n metadata.set(Metadata.AUTHOR, \"ram ,raheem ,robin \");\n \n //printing all the meta data elements with new elements\n System.out.println(\"List of all the metadata elements after adding new elements \");\n String[] metadataNamesafter = metadata.names();\n \n for(String name : metadataNamesafter) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}\t\t \t\t" }, { "code": null, "e": 46890, "s": 46813, "text": "Save the above code as SetMetadata.java and run it from the command prompt −" }, { "code": null, "e": 46934, "s": 46890, "text": "javac SetMetadata.java \njava SetMetadata\n" }, { "code": null, "e": 46977, "s": 46934, "text": "Given below is the content of example.txt." }, { "code": null, "e": 47016, "s": 46977, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 47154, "s": 47016, "text": "If you execute the above program it will give you the following output. In the output, you can observe the newly added metadata elements." }, { "code": null, "e": 47485, "s": 47154, "text": "metadata elements and values of the given file :\nContent-Encoding: ISO-8859-1\nContent-Type: text/plain; charset = ISO-8859-1\nHere is the list of all the metadata elements after adding new elements \ndate: 2014-09-24T07:01:32Z\nContent-Encoding: ISO-8859-1\nAuthor: ram, raheem, robin \nContent-Type: text/plain; charset = ISO-8859-1\n" }, { "code": null, "e": 47777, "s": 47485, "text": "For classification of documents based on the language they are written in a multilingual website, a language detection tool is needed. This tool should accept documents without language annotation (metadata) and add that information in the metadata of the document by detecting the language." }, { "code": null, "e": 47963, "s": 47777, "text": "To detect the language of a document, a language profile is constructed and compared with the profile of the known languages. The text set of these known languages is known as a corpus." }, { "code": null, "e": 48078, "s": 47963, "text": "A corpus is a collection of texts of a written language that explains how the language is used in real situations." }, { "code": null, "e": 48263, "s": 48078, "text": "The corpus is developed from books, transcripts, and other data resources like the Internet. The accuracy of the corpus depends upon the profiling algorithm we use to frame the corpus." }, { "code": null, "e": 48424, "s": 48263, "text": "The common way of detecting languages is by using dictionaries. The words used in a given piece of text will be matched with those that are in the dictionaries." }, { "code": null, "e": 48593, "s": 48424, "text": "A list of common words used in a language will be the most simple and effective corpus for detecting a particular language, for example, articles a, an, the in English." }, { "code": null, "e": 48770, "s": 48593, "text": "Using word sets, a simple algorithm is framed to find the distance between two corpora, which will be equal to the sum of differences between the frequencies of matching words." }, { "code": null, "e": 48823, "s": 48770, "text": "Such algorithms suffer from the following problems −" }, { "code": null, "e": 48995, "s": 48823, "text": "Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match." }, { "code": null, "e": 49167, "s": 48995, "text": "Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match." }, { "code": null, "e": 49309, "s": 49167, "text": "It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks." }, { "code": null, "e": 49451, "s": 49309, "text": "It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks." }, { "code": null, "e": 49565, "s": 49451, "text": "Due to these difficulties in using word sets as corpus, individual characters or character groups are considered." }, { "code": null, "e": 49830, "s": 49565, "text": "Since the characters that are commonly used in a language are finite in number, it is easy to apply an algorithm based on word frequencies rather than characters. This algorithm works even better in case of certain character sets used in one or very few languages." }, { "code": null, "e": 49884, "s": 49830, "text": "This algorithm suffers from the following drawbacks −" }, { "code": null, "e": 49969, "s": 49884, "text": "It is difficult to differentiate two languages having similar character frequencies." }, { "code": null, "e": 50054, "s": 49969, "text": "It is difficult to differentiate two languages having similar character frequencies." }, { "code": null, "e": 50204, "s": 50054, "text": "There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages." }, { "code": null, "e": 50354, "s": 50204, "text": "There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages." }, { "code": null, "e": 50597, "s": 50354, "text": "The drawbacks stated above gave rise to a new approach of using character sequences of a given length for profiling corpus. Such sequence of characters are called as N-grams in general, where N represents the length of the character sequence." }, { "code": null, "e": 50718, "s": 50597, "text": "N-gram algorithm is an effective approach for language detection, especially in case of European languages like English." }, { "code": null, "e": 50839, "s": 50718, "text": "N-gram algorithm is an effective approach for language detection, especially in case of European languages like English." }, { "code": null, "e": 50883, "s": 50839, "text": "This algorithm works fine with short texts." }, { "code": null, "e": 50927, "s": 50883, "text": "This algorithm works fine with short texts." }, { "code": null, "e": 51153, "s": 50927, "text": "Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations." }, { "code": null, "e": 51379, "s": 51153, "text": "Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations." }, { "code": null, "e": 51713, "s": 51379, "text": "Among all the 184 standard languages standardized by ISO 639-1, Tika can detect 18 languages. Language detection in Tika is done using the getLanguage() method of the LanguageIdentifier class. This method returns the code name of the language in String format. Given below is the list of the 18 language-code pairs detected by Tika −" }, { "code": null, "e": 51864, "s": 51713, "text": "While instantiating the LanguageIdentifier class, you should pass the String format of the content to be extracted, or a LanguageProfile class object." }, { "code": null, "e": 51935, "s": 51864, "text": "LanguageIdentifier object = new LanguageIdentifier(“this is english”);" }, { "code": null, "e": 52002, "s": 51935, "text": "Given below is the example program for Language detection in Tika." }, { "code": null, "e": 52507, "s": 52002, "text": "import java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.language.LanguageIdentifier;\n\nimport org.xml.sax.SAXException;\n\npublic class LanguageDetection {\n\n public static void main(String args[])throws IOException, SAXException, TikaException {\n\n LanguageIdentifier identifier = new LanguageIdentifier(\"this is english \");\n String language = identifier.getLanguage();\n System.out.println(\"Language of the given content is : \" + language);\n }\n}" }, { "code": null, "e": 52619, "s": 52507, "text": "Save the above code as LanguageDetection.java and run it from the command prompt using the following commands −" }, { "code": null, "e": 52676, "s": 52619, "text": "javac LanguageDetection.java \njava LanguageDetection \n" }, { "code": null, "e": 52740, "s": 52676, "text": " If you execute the above program it gives the following outpu−" }, { "code": null, "e": 52779, "s": 52740, "text": "Language of the given content is : en\n" }, { "code": null, "e": 53106, "s": 52779, "text": "To detect the language of a given document, you have to parse it using the parse() method. The parse() method parses the content and stores it in the handler object, which was passed to it as one of the arguments. Pass the String format of the handler object to the constructor of the LanguageIdentifier class as shown below −" }, { "code": null, "e": 53233, "s": 53106, "text": "parser.parse(inputstream, handler, metadata, context);\nLanguageIdentifier object = new LanguageIdentifier(handler.toString());" }, { "code": null, "e": 53336, "s": 53233, "text": "Given below is the complete program that demonstrates how to detect the language of a given document −" }, { "code": null, "e": 54475, "s": 53336, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.apache.tika.language.*;\n\nimport org.xml.sax.SAXException;\n\npublic class DocumentLanguageDetection {\n\n public static void main(final String[] args) throws IOException, SAXException, TikaException {\n\n //Instantiating a file object\n File file = new File(\"Example.txt\");\n\n //Parser method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream content = new FileInputStream(file);\n\n //Parsing the given document\n parser.parse(content, handler, metadata, new ParseContext());\n\n LanguageIdentifier object = new LanguageIdentifier(handler.toString());\n System.out.println(\"Language name :\" + object.getLanguage());\n }\n}" }, { "code": null, "e": 54552, "s": 54475, "text": "Save the above code as SetMetadata.java and run it from the command prompt −" }, { "code": null, "e": 54597, "s": 54552, "text": "javac SetMetadata.java \njava SetMetadata \n" }, { "code": null, "e": 54640, "s": 54597, "text": "Given below is the content of Example.txt." }, { "code": null, "e": 54679, "s": 54640, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 54753, "s": 54679, "text": "If you execute the above program, it will give you the following output −" }, { "code": null, "e": 54772, "s": 54753, "text": "Language name :en\n" }, { "code": null, "e": 54997, "s": 54772, "text": "Along with the Tika jar, Tika provides a Graphical User Interface application (GUI) and a Command Line Interface (CLI) application. You can execute a Tika application from the command prompt too like other Java applications." }, { "code": null, "e": 55110, "s": 54997, "text": "Tika provides a jar file along with its source code in the following link https://tika.apache.org/download.html." }, { "code": null, "e": 55223, "s": 55110, "text": "Tika provides a jar file along with its source code in the following link https://tika.apache.org/download.html." }, { "code": null, "e": 55284, "s": 55223, "text": "Download both the files, set the classpath for the jar file." }, { "code": null, "e": 55345, "s": 55284, "text": "Download both the files, set the classpath for the jar file." }, { "code": null, "e": 55407, "s": 55345, "text": "Extract the source code zip folder, open the tika-app folder." }, { "code": null, "e": 55469, "s": 55407, "text": "Extract the source code zip folder, open the tika-app folder." }, { "code": null, "e": 55626, "s": 55469, "text": "In the extracted folder at “tika-1.6\\tika-app\\src\\main\\java\\org\\apache\\Tika\\gui” you will see two class files: ParsingTransferHandler.java and TikaGUI.java." }, { "code": null, "e": 55783, "s": 55626, "text": "In the extracted folder at “tika-1.6\\tika-app\\src\\main\\java\\org\\apache\\Tika\\gui” you will see two class files: ParsingTransferHandler.java and TikaGUI.java." }, { "code": null, "e": 55884, "s": 55783, "text": "Compile both the class files and execute the TikaGUI.java class file, it opens the following window." }, { "code": null, "e": 55985, "s": 55884, "text": "Compile both the class files and execute the TikaGUI.java class file, it opens the following window." }, { "code": null, "e": 56033, "s": 55985, "text": "Let us now see how to make use of the Tika GUI." }, { "code": null, "e": 56153, "s": 56033, "text": "On the GUI, click open, browse and select a file that is to be extracted, or drag it onto the whitespace of the window." }, { "code": null, "e": 56356, "s": 56153, "text": "Tika extracts the content of the files and displays it in five different formats, viz. metadata, formatted text, plain text, main content, and structured text. You can choose any of the format you want." }, { "code": null, "e": 56474, "s": 56356, "text": "In the same way, you will also find the CLI class in the “tika-1.6\\tikaapp\\src\\main\\java\\org\\apache\\tika\\cli” folder." }, { "code": null, "e": 56601, "s": 56474, "text": "The following illustration shows what Tika can do. When we drop the image on the GUI, Tika extracts and displays its metadata." }, { "code": null, "e": 56672, "s": 56601, "text": "Given below is the program to extract content and metadata from a PDF." }, { "code": null, "e": 57918, "s": 56672, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.pdf.PDFParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class PdfParse {\n\n public static void main(final String[] args) throws IOException,TikaException {\n\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"Example.pdf\"));\n ParseContext pcontext = new ParseContext();\n \n //parsing the document using PDF parser\n PDFParser pdfparser = new PDFParser(); \n pdfparser.parse(inputstream, handler, metadata,pcontext);\n \n //getting the content of the document\n System.out.println(\"Contents of the PDF :\" + handler.toString());\n \n //getting metadata of the document\n System.out.println(\"Metadata of the PDF:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name+ \" : \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 58029, "s": 57918, "text": "Save the above code as PdfParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 58064, "s": 58029, "text": "javac PdfParse.java\njava PdfParse\n" }, { "code": null, "e": 58106, "s": 58064, "text": "Below give is the snapshot of example.pdf" }, { "code": null, "e": 58160, "s": 58106, "text": "The PDF we are passing has the following properties −" }, { "code": null, "e": 58229, "s": 58160, "text": "After compiling the program, you will get the output as shown below." }, { "code": null, "e": 58238, "s": 58229, "text": "Output −" }, { "code": null, "e": 59386, "s": 58238, "text": "Contents of the PDF:\n\nApache Tika is a framework for content type detection and content extraction \nwhich was designed by Apache software foundation. It detects and extracts metadata \nand structured text content from different types of documents such as spreadsheets, \ntext documents, images or PDFs including audio or video input formats to certain extent.\n\nMetadata of the PDF:\n\ndcterms:modified : 2014-09-28T12:31:16Z\nmeta:creation-date : 2014-09-28T12:31:16Z\nmeta:save-date : 2014-09-28T12:31:16Z\ndc:creator : Krishna Kasyap\npdf:PDFVersion : 1.5\nLast-Modified : 2014-09-28T12:31:16Z\nAuthor : Krishna Kasyap\ndcterms:created : 2014-09-28T12:31:16Z\ndate : 2014-09-28T12:31:16Z\nmodified : 2014-09-28T12:31:16Z\ncreator : Krishna Kasyap\nxmpTPg:NPages : 1\nCreation-Date : 2014-09-28T12:31:16Z\npdf:encrypted : false\nmeta:author : Krishna Kasyap\ncreated : Sun Sep 28 05:31:16 PDT 2014\ndc:format : application/pdf; version = 1.5\nproducer : Microsoft® Word 2013\nContent-Type : application/pdf\nxmp:CreatorTool : Microsoft® Word 2013\nLast-Save-Date : 2014-09-28T12:31:16Z\n" }, { "code": null, "e": 59485, "s": 59386, "text": "Given below is the program to extract content and metadata from Open Office Document Format (ODF)." }, { "code": null, "e": 60762, "s": 59485, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.odf.OpenDocumentParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class OpenDocumentParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example_open_document_presentation.odp\"));\n ParseContext pcontext = new ParseContext();\n \n //Open Document Parser\n OpenDocumentParser openofficeparser = new OpenDocumentParser (); \n openofficeparser.parse(inputstream, handler, metadata,pcontext); \n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\t\t \n System.out.println(name + \" : \" + metadata.get(name)); \n }\n }\n}" }, { "code": null, "e": 60880, "s": 60762, "text": "Save the above code as OpenDocumentParse.java, and compile it in the command prompt by using the following commands −" }, { "code": null, "e": 60933, "s": 60880, "text": "javac OpenDocumentParse.java\njava OpenDocumentParse\n" }, { "code": null, "e": 61005, "s": 60933, "text": "Given below is snapshot of example_open_document_presentation.odp file." }, { "code": null, "e": 61050, "s": 61005, "text": "This document has the following properties −" }, { "code": null, "e": 61114, "s": 61050, "text": "After compiling the program, you will get the following output." }, { "code": null, "e": 61123, "s": 61114, "text": "Output −" }, { "code": null, "e": 62126, "s": 61123, "text": "Contents of the document:\n\nApache Tika\nApache Tika is a framework for content type detection and content extraction which was designed \nby Apache software foundation. It detects and extracts metadata and structured text content from \ndifferent types of documents such as spreadsheets, text documents, images or PDFs including audio \nor video input formats to certain extent. \n\nMetadata of the document:\n\nediting-cycles: 4\nmeta:creation-date: 2009-04-16T11:32:32.86\ndcterms:modified: 2014-09-28T07:46:13.03\nmeta:save-date: 2014-09-28T07:46:13.03\nLast-Modified: 2014-09-28T07:46:13.03\ndcterms:created: 2009-04-16T11:32:32.86\ndate: 2014-09-28T07:46:13.03\nmodified: 2014-09-28T07:46:13.03\nnbObject: 36\nEdit-Time: PT32M6S\nCreation-Date: 2009-04-16T11:32:32.86\nObject-Count: 36\nmeta:object-count: 36\ngenerator: OpenOffice/4.1.0$Win32 OpenOffice.org_project/410m18$Build-9764\nContent-Type: application/vnd.oasis.opendocument.presentation\nLast-Save-Date: 2014-09-28T07:46:13.03\n" }, { "code": null, "e": 62219, "s": 62126, "text": "Given below is the program to extract content and metadata from a Microsoft Office Document." }, { "code": null, "e": 63432, "s": 62219, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.microsoft.ooxml.OOXMLParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class MSExcelParse {\n\n public static void main(final String[] args) throws IOException, TikaException {\n \n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example_msExcel.xlsx\"));\n ParseContext pcontext = new ParseContext();\n \n //OOXml parser\n OOXMLParser msofficeparser = new OOXMLParser (); \n msofficeparser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 63546, "s": 63432, "text": "Save the above code as MSExelParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 63590, "s": 63546, "text": "javac MSExcelParse.java\njava MSExcelParse \n" }, { "code": null, "e": 63643, "s": 63590, "text": "Here we are passing the following sample Excel file." }, { "code": null, "e": 63695, "s": 63643, "text": "The given Excel file has the following properties −" }, { "code": null, "e": 63764, "s": 63695, "text": "After executing the above program you will get the following output." }, { "code": null, "e": 63773, "s": 63764, "text": "Output −" }, { "code": null, "e": 64694, "s": 63773, "text": "Contents of the document:\n\nSheet1\nName\tAge\tDesignation\t\tSalary\nRamu\t50\tManager\t\t\t50,000\nRaheem\t40\tAssistant manager\t40,000\nRobert\t30\tSuperviser\t\t30,000\nsita\t25\tClerk\t\t\t25,000\nsameer\t25\tSection in-charge\t20,000\n\nMetadata of the document:\n\nmeta:creation-date: 2006-09-16T00:00:00Z\ndcterms:modified: 2014-09-28T15:18:41Z\nmeta:save-date: 2014-09-28T15:18:41Z\nApplication-Name: Microsoft Excel\nextended-properties:Company: \ndcterms:created: 2006-09-16T00:00:00Z\nLast-Modified: 2014-09-28T15:18:41Z\nApplication-Version: 15.0300\ndate: 2014-09-28T15:18:41Z\npublisher: \nmodified: 2014-09-28T15:18:41Z\nCreation-Date: 2006-09-16T00:00:00Z\nextended-properties:AppVersion: 15.0300\nprotected: false\ndc:publisher: \nextended-properties:Application: Microsoft Excel\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\nLast-Save-Date: 2014-09-28T15:18:41Z\n" }, { "code": null, "e": 64776, "s": 64694, "text": "Given below is the program to extract content and metadata from a Text document −" }, { "code": null, "e": 65964, "s": 64776, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.apache.tika.parser.txt.TXTParser;\n\nimport org.xml.sax.SAXException;\n\npublic class TextParser {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example.txt\"));\n ParseContext pcontext=new ParseContext();\n \n //Text document parser\n TXTParser TexTParser = new TXTParser();\n TexTParser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \" : \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 66077, "s": 65964, "text": "Save the above code as TextParser.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 66116, "s": 66077, "text": "javac TextParser.java\njava TextParser\n" }, { "code": null, "e": 66165, "s": 66116, "text": "Given below is the snapshot of sample.txt file −" }, { "code": null, "e": 66214, "s": 66165, "text": "The text document has the following properties −" }, { "code": null, "e": 66286, "s": 66214, "text": "If you execute the above program it will give you the following output." }, { "code": null, "e": 66295, "s": 66286, "text": "Output −" }, { "code": null, "e": 66926, "s": 66295, "text": "Contents of the document:\n\nAt tutorialspoint.com, we strive hard to provide quality tutorials for self-learning \npurpose in the domains of Academics, Information Technology, Management and Computer \nProgramming Languages.\nThe endeavour started by Mohtashim, an AMU alumni, who is the founder and the managing \ndirector of Tutorials Point (I) Pvt. Ltd. He came up with the website tutorialspoint.com \nin year 2006 with the help of handpicked freelancers, with an array of tutorials for \ncomputer programming languages.\n\nMetadata of the document:\n\nContent-Encoding: windows-1252\nContent-Type: text/plain; charset = windows-1252\n" }, { "code": null, "e": 67008, "s": 66926, "text": "Given below is the program to extract content and metadata from an HTML document." }, { "code": null, "e": 68196, "s": 67008, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.html.HtmlParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class HtmlParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example.html\"));\n ParseContext pcontext = new ParseContext();\n \n //Html parser \n HtmlParser htmlparser = new HtmlParser();\n htmlparser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name)); \n }\n }\n}" }, { "code": null, "e": 68308, "s": 68196, "text": "Save the above code as HtmlParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 68346, "s": 68308, "text": "javac HtmlParse.java\njava HtmlParse \n" }, { "code": null, "e": 68395, "s": 68346, "text": "Given below is the snapshot of example.txt file." }, { "code": null, "e": 68443, "s": 68395, "text": "The HTML document has the following properties−" }, { "code": null, "e": 68515, "s": 68443, "text": "If you execute the above program it will give you the following output." }, { "code": null, "e": 68524, "s": 68515, "text": "Output −" }, { "code": null, "e": 68931, "s": 68524, "text": "Contents of the document:\n\n\tName\t Salary\t age\n\tRamesh Raman\t 50000\t 20\n\tShabbir Hussein\t 70000 25\n\tUmesh Raman\t 50000\t 30\n\tSomesh\t 50000\t 35\n\nMetadata of the document:\n\ntitle: HTML Table Header\nContent-Encoding: windows-1252\nContent-Type: text/html; charset = windows-1252\ndc:title: HTML Table Header\n" }, { "code": null, "e": 69013, "s": 68931, "text": "Given below is the program to extract content and metadata from an XML document −" }, { "code": null, "e": 70185, "s": 69013, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.xml.XMLParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class XmlParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"pom.xml\"));\n ParseContext pcontext = new ParseContext();\n \n //Xml parser\n XMLParser xmlparser = new XMLParser(); \n xmlparser.parse(inputstream, handler, metadata, pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 70296, "s": 70185, "text": "Save the above code as XmlParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 70332, "s": 70296, "text": "javac XmlParse.java\njava XmlParse \n" }, { "code": null, "e": 70380, "s": 70332, "text": "Given below is the snapshot of example.xml file" }, { "code": null, "e": 70425, "s": 70380, "text": "This document has the following properties −" }, { "code": null, "e": 70498, "s": 70425, "text": "If you execute the above program it will give you the following output −" }, { "code": null, "e": 70507, "s": 70498, "text": "Output −" }, { "code": null, "e": 70730, "s": 70507, "text": "Contents of the document:\n \n4.0.0\norg.apache.tika\ntika\n1.6\norg.apache.tika\ntika-core\n1.6\norg.apache.tika\ntika-parsers\n1.6\nsrc\nmaven-compiler-plugin\n3.1\n1.7\n1.7\n\nMetadata of the document:\n\nContent-Type: application/xml \n" }, { "code": null, "e": 70809, "s": 70730, "text": "Given below is the program to extract content and metadata from a .class file." }, { "code": null, "e": 72012, "s": 70809, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.asm.ClassParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class JavaClassParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"Example.class\"));\n ParseContext pcontext = new ParseContext();\n\n //Html parser\n ClassParser ClassParser = new ClassParser();\n ClassParser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\t\t \n System.out.println(name + \" : \" + metadata.get(name)); \n }\n }\n}" }, { "code": null, "e": 72129, "s": 72012, "text": "Save the above code as JavaClassParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 72177, "s": 72129, "text": "javac JavaClassParse.java\njava JavaClassParse \n" }, { "code": null, "e": 72274, "s": 72177, "text": "Given below is the snapshot of Example.java which will generate Example.class after compilation." }, { "code": null, "e": 72324, "s": 72274, "text": "Example.class file has the following properties −" }, { "code": null, "e": 72394, "s": 72324, "text": "After executing the above program, you will get the following output." }, { "code": null, "e": 72403, "s": 72394, "text": "Output −" }, { "code": null, "e": 72660, "s": 72403, "text": "Contents of the document:\n\npackage tutorialspoint.tika.examples;\npublic synchronized class Example {\n public void Example();\n public static void main(String[]);\n}\n\nMetadata of the document:\n\ntitle: Example\nresourceName: Example.class\ndc:title: Example\n" }, { "code": null, "e": 72752, "s": 72660, "text": "Given below is the program to extract content and metadata from a Java Archive (jar) file −" }, { "code": null, "e": 73958, "s": 72752, "text": "\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.apache.tika.parser.pkg.PackageParser;\n\nimport org.xml.sax.SAXException;\n\npublic class PackageParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"Example.jar\"));\n ParseContext pcontext = new ParseContext();\n \n //Package parser\n PackageParser packageparser = new PackageParser();\n packageparser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document: \" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 74073, "s": 73958, "text": "Save the above code as PackageParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 74117, "s": 74073, "text": "javac PackageParse.java\njava PackageParse \n" }, { "code": null, "e": 74194, "s": 74117, "text": "Given below is the snapshot of Example.java that resides inside the package." }, { "code": null, "e": 74238, "s": 74194, "text": "The jar file has the following properties −" }, { "code": null, "e": 74313, "s": 74238, "text": "After executing the above program, it will give you the following output −" }, { "code": null, "e": 74322, "s": 74313, "text": "Output −" }, { "code": null, "e": 74474, "s": 74322, "text": "Contents of the document:\n\nMETA-INF/MANIFEST.MF\ntutorialspoint/tika/examples/Example.class\n\nMetadata of the document:\n\nContent-Type: application/zip\n" }, { "code": null, "e": 74553, "s": 74474, "text": "Given below is the program to extract content and meta data from a JPEG image." }, { "code": null, "e": 75742, "s": 74553, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.jpeg.JpegParser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class JpegParse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"boy.jpg\"));\n ParseContext pcontext = new ParseContext();\n \n //Jpeg Parse\n JpegParser JpegParser = new JpegParser();\n JpegParser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) { \t\t \n System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 75854, "s": 75742, "text": "Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 75892, "s": 75854, "text": "javac JpegParse.java\njava JpegParse \n" }, { "code": null, "e": 75938, "s": 75892, "text": "Given below is the snapshot of Example.jpeg −" }, { "code": null, "e": 75983, "s": 75938, "text": "The JPEG file has the following properties −" }, { "code": null, "e": 76047, "s": 75983, "text": "After executing the program, you will get the following output." }, { "code": null, "e": 76056, "s": 76047, "text": "Output −" }, { "code": null, "e": 76797, "s": 76056, "text": "Contents of the document:\n\nMeta data of the document:\n\nResolution Units: inch\nCompression Type: Baseline\nData Precision: 8 bits\nNumber of Components: 3\ntiff:ImageLength: 3000\nComponent 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert\nComponent 1: Y component: Quantization table 0, Sampling factors 2 horiz/2 vert\nImage Height: 3000 pixels\nX Resolution: 300 dots\nOriginal Transmission Reference: 53616c7465645f5f2368da84ca932841b336ac1a49edb1a93fae938b8db2cb3ec9cc4dc28d7383f1\nImage Width: 4000 pixels\nIPTC-NAA record: 92 bytes binary data\nComponent 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert\ntiff:BitsPerSample: 8\nApplication Record Version: 4\ntiff:ImageWidth: 4000\nY Resolution: 300 dots\n" }, { "code": null, "e": 76873, "s": 76797, "text": "Given below is the program to extract content and metadata from mp4 files −" }, { "code": null, "e": 78053, "s": 76873, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.mp4.MP4Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class Mp4Parse {\n\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example.mp4\"));\n ParseContext pcontext = new ParseContext();\n \n //Html parser\n MP4Parser MP4Parser = new MP4Parser();\n MP4Parser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document: :\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n \n for(String name : metadataNames) {\n System.out.println(name + \": \" + metadata.get(name));\n }\n } \n}" }, { "code": null, "e": 78165, "s": 78053, "text": "Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 78201, "s": 78165, "text": "javac Mp4Parse.java\njava Mp4Parse \n" }, { "code": null, "e": 78266, "s": 78201, "text": "Given below is the snapshot of properties of Example.mp4 file." }, { "code": null, "e": 78337, "s": 78266, "text": "After executing the above program, you will get the following output −" }, { "code": null, "e": 78346, "s": 78337, "text": "Output −" }, { "code": null, "e": 78790, "s": 78346, "text": "Contents of the document:\n\nMetadata of the document:\n\ndcterms:modified: 2014-01-06T12:10:27Z\nmeta:creation-date: 1904-01-01T00:00:00Z\nmeta:save-date: 2014-01-06T12:10:27Z\nLast-Modified: 2014-01-06T12:10:27Z\ndcterms:created: 1904-01-01T00:00:00Z\ndate: 2014-01-06T12:10:27Z\ntiff:ImageLength: 360\nmodified: 2014-01-06T12:10:27Z\nCreation-Date: 1904-01-01T00:00:00Z\ntiff:ImageWidth: 640\nContent-Type: video/mp4\nLast-Save-Date: 2014-01-06T12:10:27Z\n" }, { "code": null, "e": 78866, "s": 78790, "text": "Given below is the program to extract content and metadata from mp3 files −" }, { "code": null, "e": 80277, "s": 78866, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.mp3.LyricsHandler;\nimport org.apache.tika.parser.mp3.Mp3Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class Mp3Parse {\n\n public static void main(final String[] args) throws Exception, IOException, SAXException, TikaException {\n\n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\"example.mp3\"));\n ParseContext pcontext = new ParseContext();\n \n //Mp3 parser\n Mp3Parser Mp3Parser = new Mp3Parser();\n Mp3Parser.parse(inputstream, handler, metadata, pcontext);\n LyricsHandler lyrics = new LyricsHandler(inputstream,handler);\n \n while(lyrics.hasLyrics()) {\n \t System.out.println(lyrics.toString());\n }\n \n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n\n for(String name : metadataNames) {\t\t \n \t System.out.println(name + \": \" + metadata.get(name));\n }\n }\n}" }, { "code": null, "e": 80389, "s": 80277, "text": "Save the above code as JpegParse.java, and compile it from the command prompt by using the following commands −" }, { "code": null, "e": 80425, "s": 80389, "text": "javac Mp3Parse.java\njava Mp3Parse \n" }, { "code": null, "e": 80473, "s": 80425, "text": "Example.mp3 file has the following properties −" }, { "code": null, "e": 80639, "s": 80473, "text": "You will get the following output after executing the program. If the given file has any lyrics, our application will capture and display that along with the output." }, { "code": null, "e": 80648, "s": 80639, "text": "Output −" }, { "code": null, "e": 81470, "s": 80648, "text": "Contents of the document:\n\nKanulanu Thaake\nArijit Singh\nManam (2014), track 01/06\n2014\nSoundtrack\n30171.65\neng - \nDRGM\nArijit Singh\nManam (2014), track 01/06\n2014\nSoundtrack\n30171.65\neng - \nDRGM\n\nMetadata of the document:\n\nxmpDM:releaseDate: 2014\nxmpDM:duration: 30171.650390625\nxmpDM:audioChannelType: Stereo\ndc:creator: Arijit Singh\nxmpDM:album: Manam (2014)\nAuthor: Arijit Singh\nxmpDM:artist: Arijit Singh\nchannels: 2\nxmpDM:audioSampleRate: 44100\nxmpDM:logComment: eng - \nDRGM\nxmpDM:trackNumber: 01/06\nversion: MPEG 3 Layer III Version 1\ncreator: Arijit Singh\nxmpDM:composer: Music : Anoop Rubens | Lyrics : Vanamali\nxmpDM:audioCompressor: MP3\ntitle: Kanulanu Thaake\nsamplerate: 44100\nmeta:author: Arijit Singh\nxmpDM:genre: Soundtrack\nContent-Type: audio/mpeg\nxmpDM:albumArtist: Manam (2014)\ndc:title: Kanulanu Thaake\n" }, { "code": null, "e": 81477, "s": 81470, "text": " Print" }, { "code": null, "e": 81488, "s": 81477, "text": " Add Notes" } ]
C# program to copy a range of bytes from one array to another
Use the Buffer.BlockCopy method to copy a range of bytes from one array to another − Set a byte array − byte[] b1 = new byte[] {22, 49}; byte[] b2 = new byte[5]; Copy bytes from one array to another − Buffer.BlockCopy(b1, 0, b2, 0, 2); The following is the complete code − Live Demo using System; class Demo { static void Main(){ // byte arrays byte[] b1 = new byte[] {22, 49}; byte[] b2 = new byte[5]; // copying bytes from one to another Buffer.BlockCopy(b1, 0, b2, 0, 2); /* calling the method with the byte array b2 that has the copied elements */ bufferFunc(b2); } static void bufferFunc(byte[] a) { for (int j = 0; j < a.Length; j++) { Console.Write(a[j]); } Console.WriteLine(); } } 2249000
[ { "code": null, "e": 1147, "s": 1062, "text": "Use the Buffer.BlockCopy method to copy a range of bytes from one array to another −" }, { "code": null, "e": 1166, "s": 1147, "text": "Set a byte array −" }, { "code": null, "e": 1224, "s": 1166, "text": "byte[] b1 = new byte[] {22, 49};\nbyte[] b2 = new byte[5];" }, { "code": null, "e": 1263, "s": 1224, "text": "Copy bytes from one array to another −" }, { "code": null, "e": 1298, "s": 1263, "text": "Buffer.BlockCopy(b1, 0, b2, 0, 2);" }, { "code": null, "e": 1335, "s": 1298, "text": "The following is the complete code −" }, { "code": null, "e": 1346, "s": 1335, "text": " Live Demo" }, { "code": null, "e": 1834, "s": 1346, "text": "using System;\nclass Demo {\n static void Main(){\n // byte arrays\n byte[] b1 = new byte[] {22, 49};\n byte[] b2 = new byte[5];\n // copying bytes from one to another\n Buffer.BlockCopy(b1, 0, b2, 0, 2);\n /* calling the method with the byte array b2 that has the copied elements */\n bufferFunc(b2);\n }\n static void bufferFunc(byte[] a) {\n for (int j = 0; j < a.Length; j++) {\n Console.Write(a[j]);\n }\n Console.WriteLine();\n }\n}" }, { "code": null, "e": 1842, "s": 1834, "text": "2249000" } ]
How to create a frequency column for categorical variable in an R data frame?
To create a frequency column for categorical variable in an R data frame, we can use the transform function by defining the length of categorical variable using ave function. The output will have the duplicated frequencies as one value in the categorical column is likely to be repeated. Check out the below examples to understand how it can be done. Consider the below data frame − Live Demo Country<-sample(c("India","China","Egypt"),20,replace=TRUE) Response<-rnorm(20) df1<-data.frame(Country,Response) df1 Country Response 1 Egypt -0.6591480 2 China -1.8163343 3 India -1.0608470 4 Egypt 0.6736968 5 Egypt 0.7686130 6 India -0.5509014 7 Egypt -1.4049758 8 India -0.1783958 9 China -0.3233439 10 China 0.5749841 11 China 0.3870373 12 China -0.9342403 13 China 0.2300502 14 Egypt -0.4034456 15 Egypt -0.5925468 16 India -1.0564102 17 India 0.1227065 18 China 1.7980140 19 China -1.3700720 20 India 0.9327951 Creating a frequency column for Country column in df1 − transform(df1,Country_Frequency=ave(seq(nrow(df1)),Country,FUN=length)) Country Response Country_Frequency 1 Egypt -0.6591480 6 2 China -1.8163343 8 3 India -1.0608470 6 4 Egypt 0.6736968 6 5 Egypt 0.7686130 6 6 India -0.5509014 6 7 Egypt -1.4049758 6 8 India -0.1783958 6 9 China -0.3233439 8 10 China 0.5749841 8 11 China 0.3870373 8 12 China -0.9342403 8 13 China 0.2300502 8 14 Egypt -0.4034456 6 15 Egypt -0.5925468 6 16 India -1.0564102 6 17 India 0.1227065 6 18 China 1.7980140 8 19 China -1.3700720 8 20 India 0.9327951 6 Live Demo Temp<-sample(c("Hot","Cold"),20,replace=TRUE) Y<-rpois(20,2) df2<-data.frame(Temp,Y) df2 Temp Y 1 Cold 1 2 Hot 1 3 Cold 4 4 Hot 1 5 Hot 2 6 Hot 4 7 Hot 1 8 Hot 1 9 Cold 2 10 Hot 1 11 Cold 1 12 Hot 2 13 Hot 3 14 Cold 2 15 Cold 0 16 Cold 4 17 Hot 4 18 Hot 0 19 Cold 1 20 Cold 1 Creating a frequency column for Temp column in df2 − transform(df2,Temp_Frequency=ave(seq(nrow(df2)),Temp,FUN=length)) Temp Y Temp_Frequency 1 Cold 1 9 2 Hot 1 11 3 Cold 4 9 4 Hot 1 11 5 Hot 2 11 6 Hot 4 11 7 Hot 1 11 8 Hot 1 11 9 Cold 2 9 10 Hot 1 11 11 Cold 1 9 12 Hot 2 11 13 Hot 3 11 14 Cold 2 9 15 Cold 0 9 16 Cold 4 9 17 Hot 4 11 18 Hot 0 11 19 Cold 1 9 20 Cold 1 9
[ { "code": null, "e": 1413, "s": 1062, "text": "To create a frequency column for categorical variable in an R data frame, we can use the transform function by defining the length of categorical variable using ave function. The output will have the duplicated frequencies as one value in the categorical column is likely to be repeated. Check out the below examples to understand how it can be done." }, { "code": null, "e": 1445, "s": 1413, "text": "Consider the below data frame −" }, { "code": null, "e": 1456, "s": 1445, "text": " Live Demo" }, { "code": null, "e": 1574, "s": 1456, "text": "Country<-sample(c(\"India\",\"China\",\"Egypt\"),20,replace=TRUE)\nResponse<-rnorm(20)\ndf1<-data.frame(Country,Response)\ndf1" }, { "code": null, "e": 2035, "s": 1574, "text": " Country Response\n1 Egypt -0.6591480\n2 China -1.8163343\n3 India -1.0608470\n4 Egypt 0.6736968\n5 Egypt 0.7686130\n6 India -0.5509014\n7 Egypt -1.4049758\n8 India -0.1783958\n9 China -0.3233439\n10 China 0.5749841\n11 China 0.3870373\n12 China -0.9342403\n13 China 0.2300502\n14 Egypt -0.4034456\n15 Egypt -0.5925468\n16 India -1.0564102\n17 India 0.1227065\n18 China 1.7980140\n19 China -1.3700720\n20 India 0.9327951" }, { "code": null, "e": 2091, "s": 2035, "text": "Creating a frequency column for Country column in df1 −" }, { "code": null, "e": 2163, "s": 2091, "text": "transform(df1,Country_Frequency=ave(seq(nrow(df1)),Country,FUN=length))" }, { "code": null, "e": 2702, "s": 2163, "text": " Country Response Country_Frequency\n1 Egypt -0.6591480 6\n2 China -1.8163343 8\n3 India -1.0608470 6\n4 Egypt 0.6736968 6\n5 Egypt 0.7686130 6\n6 India -0.5509014 6\n7 Egypt -1.4049758 6\n8 India -0.1783958 6\n9 China -0.3233439 8\n10 China 0.5749841 8\n11 China 0.3870373 8\n12 China -0.9342403 8\n13 China 0.2300502 8\n14 Egypt -0.4034456 6\n15 Egypt -0.5925468 6\n16 India -1.0564102 6\n17 India 0.1227065 6\n18 China 1.7980140 8\n19 China -1.3700720 8\n20 India 0.9327951 6" }, { "code": null, "e": 2713, "s": 2702, "text": " Live Demo" }, { "code": null, "e": 2802, "s": 2713, "text": "Temp<-sample(c(\"Hot\",\"Cold\"),20,replace=TRUE)\nY<-rpois(20,2)\ndf2<-data.frame(Temp,Y)\ndf2" }, { "code": null, "e": 3056, "s": 2802, "text": " Temp Y\n1 Cold 1\n2 Hot 1\n3 Cold 4\n4 Hot 1\n5 Hot 2 \n6 Hot 4\n7 Hot 1\n8 Hot 1\n9 Cold 2\n10 Hot 1\n11 Cold 1\n12 Hot 2\n13 Hot 3\n14 Cold 2\n15 Cold 0\n16 Cold 4\n17 Hot 4\n18 Hot 0\n19 Cold 1\n20 Cold 1" }, { "code": null, "e": 3109, "s": 3056, "text": "Creating a frequency column for Temp column in df2 −" }, { "code": null, "e": 3175, "s": 3109, "text": "transform(df2,Temp_Frequency=ave(seq(nrow(df2)),Temp,FUN=length))" }, { "code": null, "e": 3502, "s": 3175, "text": " Temp Y Temp_Frequency\n1 Cold 1 9\n2 Hot 1 11\n3 Cold 4 9\n4 Hot 1 11\n5 Hot 2 11\n6 Hot 4 11\n7 Hot 1 11\n8 Hot 1 11\n9 Cold 2 9\n10 Hot 1 11\n11 Cold 1 9\n12 Hot 2 11\n13 Hot 3 11\n14 Cold 2 9\n15 Cold 0 9\n16 Cold 4 9\n17 Hot 4 11\n18 Hot 0 11\n19 Cold 1 9\n20 Cold 1 9" } ]
Modular Multiplicative Inverse | Practice | GeeksforGeeks
Given two integers ‘a’ and ‘m’. The task is to find the smallest modular multiplicative inverse of ‘a’ under modulo ‘m’. Example 1: Input: a = 3 m = 11 Output: 4 Explanation: Since (4*3) mod 11 = 1, 4 is modulo inverse of 3. One might think, 15 also as a valid output as "(15*3) mod 11" is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not valid. Example 2: Input: a = 10 m = 17 Output: 12 Explanation: Since (12*10) mod 17 = 1, 12 is the modulo inverse of 10. Your Task: You don't need to read input or print anything. Your task is to complete the function function modInverse() that takes a and m as input parameters and returns modular multiplicative inverse of ‘a’ under modulo ‘m’. If the modular multiplicative inverse doesn't exist return -1. Expected Time Complexity : O(m) Expected Auxilliary Space : O(1) Constraints: 1 <= a <= 104 1 <= m <= 104 0 crawler2 weeks ago Total Time Taken: 0.01/2.2 class Solution{ public: //Complete this function int __gcd(int a, int b){ return (b == 0 ? a : __gcd(b, a%b)); } int modInverse(int a, int m) { if(__gcd(a, m) > 1) return -1; for(int i = 1; i <= m; i++){ if((a*i)%m == 1) return i; } return -1; } }; 0 mail2rajab011 month ago // Simple Java Solution Total Time Taken: 0.2/1.2 class Solution{ public int modInverse(int a, int m) { //Your code here int ans=-1; for(int i=1;i<m;i++){ if((a*i)%m==1){ ans=i; break; } } return ans; } } 0 lawbindpandey01w1 month ago This passed all the test cases and time complexity is O(log(max(a,m))).. you need to use Extended Euclidean algorithm .. one can also use Fermat's little theorem but only when m is always prime number. class Solution{ public: //Complete this function int x,d,y; void fun(int a,int m){ if(m == 0){ x = 1; d = a; y = 0; } else{ fun(m, a%m); int temp = x; x = y; y = temp - y * (a / m); } } int modInverse(int a, int m) { //Your code here fun(a,m); x = (x%m + m)%m; if((a*x)%m == 1) return (x%m + m)%m; return -1; }}; +1 deekshakulshreshtha112 months ago class Solution{ public: //Complete this function int modInverse(int a, int m) { for(int i = 0; i<m; i++){ if(((i*a) % m)==1){ return i; } } return -1; } }; When I'm attempting the code, I got an error that expected ) before mod after searching for a while I got the reason of that error that mod is not working in cpp. instead that % symbol is used in cpp. My accuracy score is 25% is someone getting higher then kindly ping me. 0 nikhilbarot16022 months ago C++ Solution: All test cases passed. Time-Complexity: O(m) (0.0/2.2) int modInverse(int a, int m) { for(int i = 1; i <= m; i++){ if((i * a) % m == 1) return i; } return -1; } 0 saurabhsharma295203 months ago int gcd(int a,int b){ if (a == 0) return b; return gcd(b % a, a); } int modInverse(int a, int m) { if((gcd(a,m)) != 1 || m == 1) return -1; int res = 999999, t = 0; for(int i = 1;i<m;i++){ if(res>(a*i)%m){ res = (a*i)%m; t = i; } } return t; } 0 bhawanipareek20193 months ago class Solution{ public: //Complete this function int modInverse(int a, int m) { for(int x=1;x<m;x++){ if(((a%m) * (x%m)) % m == 1){ return x;} } return -1; }}; 0 lavanyadg4444 months ago attempt 1 class Solution{ public: //Complete this function int modInverse(int a, int m) { //Your code here for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return -1; }}; -1 nagesh_nagshakti6 months ago int modInverse(int a, int m) { //Your code here for(int i = 1;i<m;i++){ if(a*i%m==1) return i; } return -1; } -1 jimmypi6546 months ago class Solution: ##Complete this function def modInverse(self,a,m): ##Your code here for t in range(1, m): if self.isInt(a, m, t): return t return -1 def isInt(self, a, m, t): return a * t % m == 1 We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 347, "s": 226, "text": "Given two integers ‘a’ and ‘m’. The task is to find the smallest modular multiplicative inverse of ‘a’ under modulo ‘m’." }, { "code": null, "e": 360, "s": 349, "text": "Example 1:" }, { "code": null, "e": 584, "s": 360, "text": "Input:\na = 3\nm = 11\nOutput: 4\nExplanation: Since (4*3) mod 11 = 1, 4 \nis modulo inverse of 3. One might think,\n15 also as a valid output as \"(15*3)\nmod 11\" is also 1, but 15 is not in \nring {0, 1, 2, ... 10}, so not valid." }, { "code": null, "e": 597, "s": 586, "text": "Example 2:" }, { "code": null, "e": 700, "s": 597, "text": "Input:\na = 10\nm = 17\nOutput: 12\nExplanation: Since (12*10) mod 17 = 1,\n12 is the modulo inverse of 10." }, { "code": null, "e": 992, "s": 702, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function function modInverse() that takes a and m as input parameters and returns modular multiplicative inverse of ‘a’ under modulo ‘m’. If the modular multiplicative inverse doesn't exist return -1." }, { "code": null, "e": 1059, "s": 994, "text": "Expected Time Complexity : O(m)\nExpected Auxilliary Space : O(1)" }, { "code": null, "e": 1102, "s": 1061, "text": "Constraints:\n1 <= a <= 104\n1 <= m <= 104" }, { "code": null, "e": 1104, "s": 1102, "text": "0" }, { "code": null, "e": 1123, "s": 1104, "text": "crawler2 weeks ago" }, { "code": null, "e": 1150, "s": 1123, "text": "Total Time Taken: 0.01/2.2" }, { "code": null, "e": 1507, "s": 1150, "text": "class Solution{\n public:\n //Complete this function\n int __gcd(int a, int b){\n return (b == 0 ? a : __gcd(b, a%b));\n }\n int modInverse(int a, int m)\n {\n if(__gcd(a, m) > 1)\n return -1;\n for(int i = 1; i <= m; i++){\n if((a*i)%m == 1)\n return i;\n }\n return -1;\n }\n};" }, { "code": null, "e": 1509, "s": 1507, "text": "0" }, { "code": null, "e": 1533, "s": 1509, "text": "mail2rajab011 month ago" }, { "code": null, "e": 1557, "s": 1533, "text": "// Simple Java Solution" }, { "code": null, "e": 1583, "s": 1557, "text": "Total Time Taken: 0.2/1.2" }, { "code": null, "e": 1805, "s": 1585, "text": "class Solution{ public int modInverse(int a, int m) { //Your code here int ans=-1; for(int i=1;i<m;i++){ if((a*i)%m==1){ ans=i; break; } } return ans; }" }, { "code": null, "e": 1807, "s": 1805, "text": "}" }, { "code": null, "e": 1811, "s": 1809, "text": "0" }, { "code": null, "e": 1839, "s": 1811, "text": "lawbindpandey01w1 month ago" }, { "code": null, "e": 2043, "s": 1839, "text": "This passed all the test cases and time complexity is O(log(max(a,m))).. you need to use Extended Euclidean algorithm .. one can also use Fermat's little theorem but only when m is always prime number." }, { "code": null, "e": 2555, "s": 2047, "text": "class Solution{ public: //Complete this function int x,d,y; void fun(int a,int m){ if(m == 0){ x = 1; d = a; y = 0; } else{ fun(m, a%m); int temp = x; x = y; y = temp - y * (a / m); } } int modInverse(int a, int m) { //Your code here fun(a,m); x = (x%m + m)%m; if((a*x)%m == 1) return (x%m + m)%m; return -1; }};" }, { "code": null, "e": 2558, "s": 2555, "text": "+1" }, { "code": null, "e": 2592, "s": 2558, "text": "deekshakulshreshtha112 months ago" }, { "code": null, "e": 2842, "s": 2592, "text": "\nclass Solution{\n public:\n //Complete this function\n int modInverse(int a, int m)\n {\n for(int i = 0; i<m; i++){\n if(((i*a) % m)==1){\n return i;\n }\n }\n return -1; \n \n }\n};" }, { "code": null, "e": 3043, "s": 2842, "text": "When I'm attempting the code, I got an error that expected ) before mod after searching for a while I got the reason of that error that mod is not working in cpp. instead that % symbol is used in cpp." }, { "code": null, "e": 3118, "s": 3045, "text": "My accuracy score is 25% is someone getting higher then kindly ping me. " }, { "code": null, "e": 3120, "s": 3118, "text": "0" }, { "code": null, "e": 3148, "s": 3120, "text": "nikhilbarot16022 months ago" }, { "code": null, "e": 3162, "s": 3148, "text": "C++ Solution:" }, { "code": null, "e": 3187, "s": 3164, "text": "All test cases passed." }, { "code": null, "e": 3219, "s": 3187, "text": "Time-Complexity: O(m) (0.0/2.2)" }, { "code": null, "e": 3385, "s": 3219, "text": "int modInverse(int a, int m)\n {\n for(int i = 1; i <= m; i++){\n if((i * a) % m == 1)\n return i;\n }\n return -1;\n }" }, { "code": null, "e": 3387, "s": 3385, "text": "0" }, { "code": null, "e": 3418, "s": 3387, "text": "saurabhsharma295203 months ago" }, { "code": null, "e": 3759, "s": 3418, "text": "int gcd(int a,int b){ if (a == 0) return b; return gcd(b % a, a); } int modInverse(int a, int m) { if((gcd(a,m)) != 1 || m == 1) return -1; int res = 999999, t = 0; for(int i = 1;i<m;i++){ if(res>(a*i)%m){ res = (a*i)%m; t = i; } } return t; }" }, { "code": null, "e": 3761, "s": 3759, "text": "0" }, { "code": null, "e": 3791, "s": 3761, "text": "bhawanipareek20193 months ago" }, { "code": null, "e": 4021, "s": 3791, "text": "class Solution{ public: //Complete this function int modInverse(int a, int m) { for(int x=1;x<m;x++){ if(((a%m) * (x%m)) % m == 1){ return x;} } return -1; }};" }, { "code": null, "e": 4023, "s": 4021, "text": "0" }, { "code": null, "e": 4048, "s": 4023, "text": "lavanyadg4444 months ago" }, { "code": null, "e": 4058, "s": 4048, "text": "attempt 1" }, { "code": null, "e": 4289, "s": 4058, "text": "class Solution{ public: //Complete this function int modInverse(int a, int m) { //Your code here for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return -1; }};" }, { "code": null, "e": 4292, "s": 4289, "text": "-1" }, { "code": null, "e": 4321, "s": 4292, "text": "nagesh_nagshakti6 months ago" }, { "code": null, "e": 4503, "s": 4321, "text": " int modInverse(int a, int m)\n {\n //Your code here\n for(int i = 1;i<m;i++){\n if(a*i%m==1)\n return i;\n }\n return -1;\n }" }, { "code": null, "e": 4506, "s": 4503, "text": "-1" }, { "code": null, "e": 4529, "s": 4506, "text": "jimmypi6546 months ago" }, { "code": null, "e": 4833, "s": 4529, "text": "class Solution: \n ##Complete this function\n def modInverse(self,a,m):\n ##Your code here\n for t in range(1, m):\n if self.isInt(a, m, t):\n return t\n \n return -1\n \n \n def isInt(self, a, m, t):\n return a * t % m == 1" }, { "code": null, "e": 4979, "s": 4833, "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": 5015, "s": 4979, "text": " Login to access your submissions. " }, { "code": null, "e": 5025, "s": 5015, "text": "\nProblem\n" }, { "code": null, "e": 5035, "s": 5025, "text": "\nContest\n" }, { "code": null, "e": 5098, "s": 5035, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5246, "s": 5098, "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": 5454, "s": 5246, "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": 5560, "s": 5454, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What are JSP comments?
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out", a part of your JSP page. Following is the syntax of the JSP comments − <%-- This is JSP comment --%> Following example shows the JSP Comments − <html> <head> <title>A Comment Test</title> </head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html> The above code will generate the following result − A Test of Comments
[ { "code": null, "e": 1226, "s": 1062, "text": "JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or \"comment out\", a part of your JSP page." }, { "code": null, "e": 1272, "s": 1226, "text": "Following is the syntax of the JSP comments −" }, { "code": null, "e": 1302, "s": 1272, "text": "<%-- This is JSP comment --%>" }, { "code": null, "e": 1345, "s": 1302, "text": "Following example shows the JSP Comments −" }, { "code": null, "e": 1540, "s": 1345, "text": "<html>\n <head>\n <title>A Comment Test</title>\n </head>\n <body>\n <h2>A Test of Comments</h2>\n <%-- This comment will not be visible in the page source --%>\n </body>\n</html>" }, { "code": null, "e": 1592, "s": 1540, "text": "The above code will generate the following result −" }, { "code": null, "e": 1611, "s": 1592, "text": "A Test of Comments" } ]
SQL using C/C++ and SQLite
In this section, you will learn how to use SQLite in C/C++ programs. Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process. Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation. sqlite3_open(const char *filename, sqlite3 **ppDb) sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg) sqlite3_close(sqlite3*) Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. #include <stdio.h> #include <sqlite3.h> int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } sqlite3_close(db); } $gcc test.c -l sqlite3 $./a.out Opened database successfully Following C code segment will be used to create a table in the previously created database − #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" \ "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Table created successfully\n"); } sqlite3_close(db); return 0; } -rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out -rw-r--r--. 1 root root 1207 May 8 02:31 test.c -rw-r--r--. 1 root root 3072 May 8 02:31 test.db Following C code segment shows how you can create records in COMPANY table created in the above example – #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; } Opened database successfully Records created successfully Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration – typedef int (*sqlite3_callback)( void*, /* Data provided in the 4th argument of sqlite3_exec() */ int, /* The number of columns in row */ char**, /* An array of strings representing fields in the row */ char** /* An array of strings representing column names */ ); If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument. Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example – #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName) { int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully
[ { "code": null, "e": 1131, "s": 1062, "text": "In this section, you will learn how to use SQLite in C/C++ programs." }, { "code": null, "e": 1340, "s": 1131, "text": "Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process." }, { "code": null, "e": 1597, "s": 1340, "text": "Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation." }, { "code": null, "e": 1648, "s": 1597, "text": "sqlite3_open(const char *filename, sqlite3 **ppDb)" }, { "code": null, "e": 1732, "s": 1648, "text": "sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)" }, { "code": null, "e": 1756, "s": 1732, "text": "sqlite3_close(sqlite3*)" }, { "code": null, "e": 1931, "s": 1756, "text": "Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned." }, { "code": null, "e": 2294, "s": 1931, "text": "#include <stdio.h>\n#include <sqlite3.h>\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n sqlite3_close(db);\n}" }, { "code": null, "e": 2355, "s": 2294, "text": "$gcc test.c -l sqlite3\n$./a.out\nOpened database successfully" }, { "code": null, "e": 2448, "s": 2355, "text": "Following C code segment will be used to create a table in the previously created database −" }, { "code": null, "e": 3582, "s": 2448, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stdout, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"CREATE TABLE COMPANY(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"NAME TEXT NOT NULL,\" \\\n \"AGE INT NOT NULL,\" \\\n \"ADDRESS CHAR(50),\" \\\n \"SALARY REAL );\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Table created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 3726, "s": 3582, "text": "-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out\n-rw-r--r--. 1 root root 1207 May 8 02:31 test.c\n-rw-r--r--. 1 root root 3072 May 8 02:31 test.db" }, { "code": null, "e": 3832, "s": 3726, "text": "Following C code segment shows how you can create records in COMPANY table created in the above example –" }, { "code": null, "e": 5255, "s": 3832, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (1, 'Paul', 32, 'California', 20000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Records created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 5313, "s": 5255, "text": "Opened database successfully\nRecords created successfully" }, { "code": null, "e": 5567, "s": 5313, "text": "Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration –" }, { "code": null, "e": 5844, "s": 5567, "text": "typedef int (*sqlite3_callback)(\n void*, /* Data provided in the 4th argument of sqlite3_exec() */\n int, /* The number of columns in row */\n char**, /* An array of strings representing fields in the row */\n char** /* An array of strings representing column names */\n);" }, { "code": null, "e": 6051, "s": 5844, "text": "If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument." }, { "code": null, "e": 6174, "s": 6051, "text": "Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example –" }, { "code": null, "e": 7263, "s": 6174, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *data, int argc, char **argv, char **azColName) {\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"SELECT * from COMPANY\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 7680, "s": 7263, "text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\nOperation done successfully" } ]
A Python tool for Data Processing, Analysis, and ML Automation in a few lines of code | by Satyam Kumar | Towards Data Science
A data science model development pipeline involves various components including data collection, data processing, Exploratory data analysis, modeling, and deployment. Before training a machine learning or deep learning model, it’s essential to clean or process the dataset and fit it for training. Processes like handling missing records, removing redundant features, and feature analysis are part of the data processing component. Often, these processes are repetitive and involve most of the model development work time. Various open-sourced Auto-ML libraries automate the entire pipeline in few lines of Python code, but most of them behave as a black-box and do not give intuition about how they processed the dataset. To overcome this problem, we have an open-sourced Python library called dabl — data analysis baseline library, that can automate most of the parts of the machine learning model development pipeline. This article will cover the hands-on implementation of the package dabl including data preprocessing, feature visualization, and analysis, followed by modeling. dabl is a data analysis baseline library that makes supervised machine learning modeling easier and accessible for beginners or folks with no knowledge of data science. dabl is inspired by the Scikit-learn library and it tries to democratize machine learning modeling by reducing the boilerplate task and automating the components. dabl library includes various features that make it easier to process, analyze and model the data in a few lines of Python code. dabl can be installed from PyPI using pip install dabl We will be using the Titanic dataset downloaded from Kaggle for implementation of the library. dabl automates the data preprocessing pipeline in a few lines of Python code. The pre-processing steps performed by dabl include identifying missing values, removing the redundant features, and understanding the features' datatypes to further perform feature engineering. The list of detected feature types by dabl includes: The list of detected feature types by dabl includes:1. continuous2. categorical3. date4. Dirty_float5. Low_card_int6. free_string7. Useless All the dataset features are automatically categorized into the above-mentioned datatypes by dabl using a single line of Python code. df_clean = dabl.clean(df, verbose=1) The raw Titanic dataset has 12 features, and they are automatically categorized into the above-mentioned datatypes by dabl for further feature engineering. dabl also provides capabilities to change the data type of any feature based on requirements. db_clean = dabl.clean(db, type_hints={"Cabin": "categorical"}) One can have a look at the assigned datatype for each feature using detect_types() function. EDA is an essential component of the data science model development life cycle. Seaborn, Matplotlib, etc are popular libraries to perform various analyses to get a better understanding of the dataset. dabl makes the EDA very simple and saves worktime. dabl.plot(df_clean, target_col="Survived") plot() function in dabl can feature visualization by plotting various plots including: Bar plot for target distribution Scatter Pair plots Linear Discriminant Analysis dabl automatically performs PCA on the dataset and also shows the discriminant PCA graph for all the features in the dataset. It also displays the variance preserved by applying PCA. dabl speeds up the modeling workflow by training various baseline machine learning algorithms on the training data and returns with the best-performing model. dabl makes simple assumptions and generates metrics for baseline models. Modeling can be performed in 1 line of code using SimpleClassifier() function in dabl. dabl returns with the best model (Decision Tree Classifier) in almost no time. dabl is a recently developed library and provides basic methods for model training. Dabl is a handy tool that makes supervised machine learning more accessible and fast. It simplifies data cleaning, feature visualization, and developing baseline models in a few lines of Python code. dabl is a recently developed library and needs a lot of improvement, and it’s not recommended for production use. [1] dabl GitHub: https://github.com/amueller/dabl Thank You for Reading
[ { "code": null, "e": 603, "s": 171, "text": "A data science model development pipeline involves various components including data collection, data processing, Exploratory data analysis, modeling, and deployment. Before training a machine learning or deep learning model, it’s essential to clean or process the dataset and fit it for training. Processes like handling missing records, removing redundant features, and feature analysis are part of the data processing component." }, { "code": null, "e": 894, "s": 603, "text": "Often, these processes are repetitive and involve most of the model development work time. Various open-sourced Auto-ML libraries automate the entire pipeline in few lines of Python code, but most of them behave as a black-box and do not give intuition about how they processed the dataset." }, { "code": null, "e": 1254, "s": 894, "text": "To overcome this problem, we have an open-sourced Python library called dabl — data analysis baseline library, that can automate most of the parts of the machine learning model development pipeline. This article will cover the hands-on implementation of the package dabl including data preprocessing, feature visualization, and analysis, followed by modeling." }, { "code": null, "e": 1586, "s": 1254, "text": "dabl is a data analysis baseline library that makes supervised machine learning modeling easier and accessible for beginners or folks with no knowledge of data science. dabl is inspired by the Scikit-learn library and it tries to democratize machine learning modeling by reducing the boilerplate task and automating the components." }, { "code": null, "e": 1715, "s": 1586, "text": "dabl library includes various features that make it easier to process, analyze and model the data in a few lines of Python code." }, { "code": null, "e": 1753, "s": 1715, "text": "dabl can be installed from PyPI using" }, { "code": null, "e": 1770, "s": 1753, "text": "pip install dabl" }, { "code": null, "e": 1865, "s": 1770, "text": "We will be using the Titanic dataset downloaded from Kaggle for implementation of the library." }, { "code": null, "e": 2137, "s": 1865, "text": "dabl automates the data preprocessing pipeline in a few lines of Python code. The pre-processing steps performed by dabl include identifying missing values, removing the redundant features, and understanding the features' datatypes to further perform feature engineering." }, { "code": null, "e": 2190, "s": 2137, "text": "The list of detected feature types by dabl includes:" }, { "code": null, "e": 2330, "s": 2190, "text": "The list of detected feature types by dabl includes:1. continuous2. categorical3. date4. Dirty_float5. Low_card_int6. free_string7. Useless" }, { "code": null, "e": 2464, "s": 2330, "text": "All the dataset features are automatically categorized into the above-mentioned datatypes by dabl using a single line of Python code." }, { "code": null, "e": 2501, "s": 2464, "text": "df_clean = dabl.clean(df, verbose=1)" }, { "code": null, "e": 2751, "s": 2501, "text": "The raw Titanic dataset has 12 features, and they are automatically categorized into the above-mentioned datatypes by dabl for further feature engineering. dabl also provides capabilities to change the data type of any feature based on requirements." }, { "code": null, "e": 2814, "s": 2751, "text": "db_clean = dabl.clean(db, type_hints={\"Cabin\": \"categorical\"})" }, { "code": null, "e": 2907, "s": 2814, "text": "One can have a look at the assigned datatype for each feature using detect_types() function." }, { "code": null, "e": 3159, "s": 2907, "text": "EDA is an essential component of the data science model development life cycle. Seaborn, Matplotlib, etc are popular libraries to perform various analyses to get a better understanding of the dataset. dabl makes the EDA very simple and saves worktime." }, { "code": null, "e": 3202, "s": 3159, "text": "dabl.plot(df_clean, target_col=\"Survived\")" }, { "code": null, "e": 3289, "s": 3202, "text": "plot() function in dabl can feature visualization by plotting various plots including:" }, { "code": null, "e": 3322, "s": 3289, "text": "Bar plot for target distribution" }, { "code": null, "e": 3341, "s": 3322, "text": "Scatter Pair plots" }, { "code": null, "e": 3370, "s": 3341, "text": "Linear Discriminant Analysis" }, { "code": null, "e": 3553, "s": 3370, "text": "dabl automatically performs PCA on the dataset and also shows the discriminant PCA graph for all the features in the dataset. It also displays the variance preserved by applying PCA." }, { "code": null, "e": 3785, "s": 3553, "text": "dabl speeds up the modeling workflow by training various baseline machine learning algorithms on the training data and returns with the best-performing model. dabl makes simple assumptions and generates metrics for baseline models." }, { "code": null, "e": 3872, "s": 3785, "text": "Modeling can be performed in 1 line of code using SimpleClassifier() function in dabl." }, { "code": null, "e": 4035, "s": 3872, "text": "dabl returns with the best model (Decision Tree Classifier) in almost no time. dabl is a recently developed library and provides basic methods for model training." }, { "code": null, "e": 4349, "s": 4035, "text": "Dabl is a handy tool that makes supervised machine learning more accessible and fast. It simplifies data cleaning, feature visualization, and developing baseline models in a few lines of Python code. dabl is a recently developed library and needs a lot of improvement, and it’s not recommended for production use." }, { "code": null, "e": 4399, "s": 4349, "text": "[1] dabl GitHub: https://github.com/amueller/dabl" } ]
Convert Photo into Pixel Art using Python | by Abhijith Chandradas | Towards Data Science
Withe the rise in popularity of NFTs and crypto art, there is a rise in demand for programmers who can perform image manipulation and generate procedural art. Pixel art has also seen a resurgence in popularity of late, especially among the connoisseurs of digital art. In this article I will explain how to perform image manipulation in python to convert any photo into pixel art. I will use a cropped version(800px X 800px ) of the above image for the purpose of demonstration. We will use Pillow Library for image manipulation and Matplotlib library for displaying and saving images. #Import Librariesfrom PIL import Imageimport matplotlib.pyplot as plt Image can be read by providing the path to the image as an argument to the open function of Image module of Pillow library. Since our image is in the same folder as the notebook, just the name of the image is sufficient. Once the image is read, it can be displayed using imshow function of matplotlib. #Read imageimg=Image.open('mario.jpg')#show imageplt.imshow(img)plt.show() The first step in creating a pixelated image is conversion of the input image image into a small image using Bilinear interpolation resampling technique. You can visit the below page to know more about different image resampling techniques. www.cambridgeincolour.com This can be achieved by using the resize method by providing the size and resampling technique as arguments.We can convert the 800px X 800px image into 8px by 8px image as below: small_img=img.resize((8,8),Image.BILINEAR) The small image is then resized to the desired output size, again by using the resize function.We will use Nearest Neighbour resampling technique which is essentially enlarging each pixel.The default resampling technique is bicubic interpolation, which will sharpen the image.The below code will convert the small image (8px X 8px) into an image which has dimensions 1000 px X 1000px. #resizeo_size=(1000,1000) #output sizeres=small_img.resize(o_size,Image.NEAREST)#save imageres.save('mario_8x8.png')#display imageplt.imshow(res)plt.show() Note that we have used save function to save the image locally with filename mario_8x8.png. The above image contains only 0.01% of the data as that in the original image. Hence it is not surprising if you are not able to recognize the original image from this image.A good pixel art must contain enough data from the original image so that it can be recognized. However, the the fine features will be lost in the process.If the original figure has a lot of fine features which need to be conserved, we should use a much larger size for the initial resizing.The appropriate small image size can be obtained by trial and error method. The next step is streamlining the processed discussed above by creating a function which generates pixel art from any image. The function must incorporate the following functionalities:i. Read the photo ii. Convert it to pixel art taking the small image size and the output image size as argumentsiii. Save the generated imageiv. Display the original image and the pixel art side by side for comparison This function can be used to try different small image sizes for the mario image to find an appropriate size to obtain the most visually pleasing pixel art. We will convert the image to 32px X 32px size to pixelate the image. img.size can be used to get the size of the original image. By providing img.size as the output size, we can generate a pixel art which is of the same size as that of the original image. photo2pixelart(image='mario.jpg',i_size=(32,32), o_size=img.size) We can observe that the new pixel art shows much more detailing compared to initial one. This figure contains 16 times more data compared to the the 8px version. However it contains only 0.16% data from the original image. We will scale down the length and breadth of the image by 10%, i.e, 80px X 80px for the next image. This figure would contain 1% data of the original image. #Function Callphoto2pixelart(image='mario.jpg',i_size=(80,80), o_size=img.size) This image is smoother than the previous image with the features of the image more recognizable. The code for this tutorial and all the images used and generated are available in my GitHub Repo. I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
[ { "code": null, "e": 553, "s": 172, "text": "Withe the rise in popularity of NFTs and crypto art, there is a rise in demand for programmers who can perform image manipulation and generate procedural art. Pixel art has also seen a resurgence in popularity of late, especially among the connoisseurs of digital art. In this article I will explain how to perform image manipulation in python to convert any photo into pixel art." }, { "code": null, "e": 651, "s": 553, "text": "I will use a cropped version(800px X 800px ) of the above image for the purpose of demonstration." }, { "code": null, "e": 758, "s": 651, "text": "We will use Pillow Library for image manipulation and Matplotlib library for displaying and saving images." }, { "code": null, "e": 828, "s": 758, "text": "#Import Librariesfrom PIL import Imageimport matplotlib.pyplot as plt" }, { "code": null, "e": 1049, "s": 828, "text": "Image can be read by providing the path to the image as an argument to the open function of Image module of Pillow library. Since our image is in the same folder as the notebook, just the name of the image is sufficient." }, { "code": null, "e": 1130, "s": 1049, "text": "Once the image is read, it can be displayed using imshow function of matplotlib." }, { "code": null, "e": 1205, "s": 1130, "text": "#Read imageimg=Image.open('mario.jpg')#show imageplt.imshow(img)plt.show()" }, { "code": null, "e": 1359, "s": 1205, "text": "The first step in creating a pixelated image is conversion of the input image image into a small image using Bilinear interpolation resampling technique." }, { "code": null, "e": 1446, "s": 1359, "text": "You can visit the below page to know more about different image resampling techniques." }, { "code": null, "e": 1472, "s": 1446, "text": "www.cambridgeincolour.com" }, { "code": null, "e": 1651, "s": 1472, "text": "This can be achieved by using the resize method by providing the size and resampling technique as arguments.We can convert the 800px X 800px image into 8px by 8px image as below:" }, { "code": null, "e": 1694, "s": 1651, "text": "small_img=img.resize((8,8),Image.BILINEAR)" }, { "code": null, "e": 2079, "s": 1694, "text": "The small image is then resized to the desired output size, again by using the resize function.We will use Nearest Neighbour resampling technique which is essentially enlarging each pixel.The default resampling technique is bicubic interpolation, which will sharpen the image.The below code will convert the small image (8px X 8px) into an image which has dimensions 1000 px X 1000px." }, { "code": null, "e": 2235, "s": 2079, "text": "#resizeo_size=(1000,1000) #output sizeres=small_img.resize(o_size,Image.NEAREST)#save imageres.save('mario_8x8.png')#display imageplt.imshow(res)plt.show()" }, { "code": null, "e": 2327, "s": 2235, "text": "Note that we have used save function to save the image locally with filename mario_8x8.png." }, { "code": null, "e": 2868, "s": 2327, "text": "The above image contains only 0.01% of the data as that in the original image. Hence it is not surprising if you are not able to recognize the original image from this image.A good pixel art must contain enough data from the original image so that it can be recognized. However, the the fine features will be lost in the process.If the original figure has a lot of fine features which need to be conserved, we should use a much larger size for the initial resizing.The appropriate small image size can be obtained by trial and error method." }, { "code": null, "e": 3271, "s": 2868, "text": "The next step is streamlining the processed discussed above by creating a function which generates pixel art from any image. The function must incorporate the following functionalities:i. Read the photo ii. Convert it to pixel art taking the small image size and the output image size as argumentsiii. Save the generated imageiv. Display the original image and the pixel art side by side for comparison" }, { "code": null, "e": 3428, "s": 3271, "text": "This function can be used to try different small image sizes for the mario image to find an appropriate size to obtain the most visually pleasing pixel art." }, { "code": null, "e": 3684, "s": 3428, "text": "We will convert the image to 32px X 32px size to pixelate the image. img.size can be used to get the size of the original image. By providing img.size as the output size, we can generate a pixel art which is of the same size as that of the original image." }, { "code": null, "e": 3769, "s": 3684, "text": "photo2pixelart(image='mario.jpg',i_size=(32,32), o_size=img.size)" }, { "code": null, "e": 3992, "s": 3769, "text": "We can observe that the new pixel art shows much more detailing compared to initial one. This figure contains 16 times more data compared to the the 8px version. However it contains only 0.16% data from the original image." }, { "code": null, "e": 4149, "s": 3992, "text": "We will scale down the length and breadth of the image by 10%, i.e, 80px X 80px for the next image. This figure would contain 1% data of the original image." }, { "code": null, "e": 4248, "s": 4149, "text": "#Function Callphoto2pixelart(image='mario.jpg',i_size=(80,80), o_size=img.size)" }, { "code": null, "e": 4345, "s": 4248, "text": "This image is smoother than the previous image with the features of the image more recognizable." }, { "code": null, "e": 4443, "s": 4345, "text": "The code for this tutorial and all the images used and generated are available in my GitHub Repo." } ]
How to check if a string in Python is in ASCII?
The simplest way is to loop over the characters of the string and check if each character is ASCII or not. def is_ascii(s): return all(ord(c) < 128 for c in s) print is_ascii('ӓmsterdӒm') This will give the output: False But this method is very inefficient. A better way is to decode the string using str.decode('ascii') and check for exceptions. mystring = 'ӓmsterdӓm' try: mystring.decode('ascii') except UnicodeDecodeError: print "Not an ASCII-encoded string" else: print "May be an ASCII-encoded string" This will give the output: Not an ASCII-encoded string
[ { "code": null, "e": 1170, "s": 1062, "text": "The simplest way is to loop over the characters of the string and check if each character is ASCII or not. " }, { "code": null, "e": 1257, "s": 1170, "text": "def is_ascii(s):\n return all(ord(c) < 128 for c in s)\nprint is_ascii('ӓmsterdӒm')" }, { "code": null, "e": 1284, "s": 1257, "text": "This will give the output:" }, { "code": null, "e": 1290, "s": 1284, "text": "False" }, { "code": null, "e": 1417, "s": 1290, "text": "But this method is very inefficient. A better way is to decode the string using str.decode('ascii') and check for exceptions. " }, { "code": null, "e": 1592, "s": 1417, "text": "mystring = 'ӓmsterdӓm'\ntry:\n mystring.decode('ascii')\nexcept UnicodeDecodeError:\n print \"Not an ASCII-encoded string\"\nelse:\n print \"May be an ASCII-encoded string\"" }, { "code": null, "e": 1619, "s": 1592, "text": "This will give the output:" }, { "code": null, "e": 1647, "s": 1619, "text": "Not an ASCII-encoded string" } ]
HTML | <input> src Attribute - GeeksforGeeks
21 Feb, 2022 The HTML <input> src Attribute is used to specify the URL of the image to be used as a submit button. This attribute can only be used with <input type=”image”>.Syntax: <input src="URL"> Attribute Values: It contains a single value URL that specifies the link of the source image. There are two types of URL links which are listed below: Absolute URL: It points to another webpage. Relative URL: It points to other files of the same web page. Example: html <!DOCTYPE html><html> <head> <title> HTML Input src Attribute </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML Input src Attribute</h2> <form> <input id="myImage" type="image" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="70" height="48" /> </form></body> </html> Output: Supported Browsers: The browsers supported by HTML <input> src Attribute are listed below: Google Chrome 1.0 Internet Explorer 2.0 Firefox 1.0 Apple Safari 1.0 Opera 1.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) 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": 24341, "s": 24313, "text": "\n21 Feb, 2022" }, { "code": null, "e": 24511, "s": 24341, "text": "The HTML <input> src Attribute is used to specify the URL of the image to be used as a submit button. This attribute can only be used with <input type=”image”>.Syntax: " }, { "code": null, "e": 24529, "s": 24511, "text": "<input src=\"URL\">" }, { "code": null, "e": 24682, "s": 24529, "text": "Attribute Values: It contains a single value URL that specifies the link of the source image. There are two types of URL links which are listed below: " }, { "code": null, "e": 24726, "s": 24682, "text": "Absolute URL: It points to another webpage." }, { "code": null, "e": 24787, "s": 24726, "text": "Relative URL: It points to other files of the same web page." }, { "code": null, "e": 24798, "s": 24787, "text": "Example: " }, { "code": null, "e": 24803, "s": 24798, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Input src Attribute </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML Input src Attribute</h2> <form> <input id=\"myImage\" type=\"image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"70\" height=\"48\" /> </form></body> </html>", "e": 25287, "s": 24803, "text": null }, { "code": null, "e": 25297, "s": 25287, "text": "Output: " }, { "code": null, "e": 25390, "s": 25297, "text": "Supported Browsers: The browsers supported by HTML <input> src Attribute are listed below: " }, { "code": null, "e": 25408, "s": 25390, "text": "Google Chrome 1.0" }, { "code": null, "e": 25430, "s": 25408, "text": "Internet Explorer 2.0" }, { "code": null, "e": 25442, "s": 25430, "text": "Firefox 1.0" }, { "code": null, "e": 25459, "s": 25442, "text": "Apple Safari 1.0" }, { "code": null, "e": 25469, "s": 25459, "text": "Opera 1.0" }, { "code": null, "e": 25608, "s": 25471, "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": 25628, "s": 25608, "text": "hritikbhatnagar2182" }, { "code": null, "e": 25644, "s": 25628, "text": "HTML-Attributes" }, { "code": null, "e": 25649, "s": 25644, "text": "HTML" }, { "code": null, "e": 25666, "s": 25649, "text": "Web Technologies" }, { "code": null, "e": 25671, "s": 25666, "text": "HTML" }, { "code": null, "e": 25769, "s": 25671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25778, "s": 25769, "text": "Comments" }, { "code": null, "e": 25791, "s": 25778, "text": "Old Comments" }, { "code": null, "e": 25839, "s": 25791, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25876, "s": 25839, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 25926, "s": 25876, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25976, "s": 25926, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26000, "s": 25976, "text": "REST API (Introduction)" }, { "code": null, "e": 26056, "s": 26000, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26089, "s": 26056, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26132, "s": 26089, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26193, "s": 26132, "text": "Difference between var, let and const keywords in JavaScript" } ]
CBSE Class 11 | Computer Science - Python Syllabus - GeeksforGeeks
11 Nov, 2021 (Optional for the academic year 2018-19 and mandatory for the academic year 2019-20 onwards) 1. Prerequisites : No major prerequisites are required for this course other than basic Mathematical skills. However, it will be helpful if the student has a basic knowledge of Computer Applications. 2. Learning Outcomes : Develop basic computational thinking. Learn how to reason with variables, state transitions, conditionals, and iteration.Understand the notion of data types, and higher order data structures such as lists, tuples, and dictionaries.Appreciate the notion of an algorithm, and understand its structure, including how algorithms handle corner cases.Develop a basic understanding of computer systems – architecture, OS, mobile and cloud computing.Learn basic SQL programming.Learn all about cyber safety. Develop basic computational thinking. Learn how to reason with variables, state transitions, conditionals, and iteration. Understand the notion of data types, and higher order data structures such as lists, tuples, and dictionaries. Appreciate the notion of an algorithm, and understand its structure, including how algorithms handle corner cases. Develop a basic understanding of computer systems – architecture, OS, mobile and cloud computing. Learn basic SQL programming. Learn all about cyber safety. 3. Distribution of Marks Unit No. Unit Name Marks 1. Programming and Computational Thinking - 1 35 2. Computer Systems and Organisation 10 3. Data Management - 1 15 4. Society, Law and Ethics - 1 10 5. Practical 30 Total 100 4.1 Unit 1: Programming and Computational Thinking (PCT-1) (80 Theory + 70 Practical) Familiarization with the basics of Python programming: a simple “hello world” program, process of writing a program, running it, and print statements; simple data-types: integer, float, string. Introduce the notion of a variable, and methods to manipulate it (concept of L-value and Rvalue even if not taught explicitly), Knowledge of data types and operators: accepting input from the console, assignment statement, expressions, operators and their precedence. Conditional statements: if, if-else, if-elif-else; simple programs: e.g.: absolute value, sort 3 numbers, and divisibility, Notion of iterative computation and control flow : for, while, flowcharts, decision trees and pseudo code; write a lot of programs: interest calculation, primarily testing, and factorials. Idea of debugging: errors and exceptions; debugging: pdb, break points. Sequence datatype: Lists, tuples and dictionary: finding the maximum, minimum, mean; linear search on list/tuple of numbers, and counting the frequency of elements in a list using a dictionary. Introduce the notion of accessing elements in a collection using numbers and names. Sorting algorithm: bubble and insertion sort; count the number of operations while sorting. Strings: Strings in Python : compare, concatenate, substring; notion of states and transitions using state transition diagrams. 4.2. Unit 2: Computer Systems and Organisation (CSO) (20 Theory + 6 Practical) Basic computer organisation: description of a computer system and mobile system, CPU, memory, hard disk, I/O, battery, power. Types of software:Types of Software – System Software, Utility Software and Application Software Language of Bits: bit, byte, MB, GB, TB, and PB. Boolean logic: OR, AND, NAND, NOR, XOR, NOT, truth tables, De Morgan’s laws Number representation: numbers in base 2, 8, 16, unsigned integers, binary addition Strings: ASCII, UTF8, UTF32, ISCII (Indian script code) Execution of a program: basic flow of compilation – program binary execution, Running a program: Notion of an operating system, idea of loading, Interpreters (process one line at a time), difference between a compiler and an interpreter, how an operating system runs a program, operating system as a resource manager. Cloud Computing: Concept of cloud computers, cloud storage (public/private), and brief introduction to parallel computing. 4.3. Unit 3: Data Management (DM-1) (30 Theory+ 24 Practical) Relational databases: idea of a database and the need for it, relations, keys, primary key, foreign key; use SQL commands to create a table, foreign keys; insert/delete an entry, delete a table. SQL commands: select, project, and join; indexes, and a lot of in-class practice. Basics of NoSQL databases: Mongo DB. Unit 4: Society, Law and Ethics (SLE-1) – Cyber safety (10 Theory) Cyber safety: safely browsing the web, identity protection, confidentiality, social networks, cyber trolls and bullying Appropriate usage of social networks: spread of rumours, and common social networking sites (Twitter, LinkedIn, and Facebook) and specific usage rules. Safely accessing web sites: malware, adware, viruses, Trojans Safely communicating data: secure connections, eavesdropping, phishing and identity verification. 5. Practical 5.1. Programming in Python: At least the following Python concepts should be covered in the lab sessions: expressions, conditionals, loops, list, dictionary, and strings. The following are some representative lab assignments. Find the largest and smallest numbers in a list.Find the third largest number in a list.Test for primarily.Find whether a string is a palindrome or not.Given two integers x and n, compute x n. Compute the greatest common divisor and the least common multiple of two integers.Test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers. Find the largest and smallest numbers in a list. Find the third largest number in a list. Test for primarily. Find whether a string is a palindrome or not. Given two integers x and n, compute x n. Compute the greatest common divisor and the least common multiple of two integers. Test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers. 5.2. Data Management: SQL Commands At least the following SQL commands should be covered during the labs: create, insert, delete, select, and join. The following are some representative assignments. Create a student table with the student id, name, and marks as attributes where the student id is the primary key.Insert the details of a new student in the above table.Delete the details of a particular student in the above table.Use the select command to get the details of the students with marks more than 80. Create a new table (name, date of birth) by joining two tables (student id, name) and (student id, date of birth).Create a new table (order ID, customer Name, and order Date) by joining two tables (order ID, customer ID, and order Date) and (customer ID, customer Name, contact Name, country). Create a student table with the student id, name, and marks as attributes where the student id is the primary key. Insert the details of a new student in the above table. Delete the details of a particular student in the above table. Use the select command to get the details of the students with marks more than 80. Create a new table (name, date of birth) by joining two tables (student id, name) and (student id, date of birth). Create a new table (order ID, customer Name, and order Date) by joining two tables (order ID, customer ID, and order Date) and (customer ID, customer Name, contact Name, country). Source : CBSE chhabradhanvi Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25087, "s": 25059, "text": "\n11 Nov, 2021" }, { "code": null, "e": 25405, "s": 25087, "text": "(Optional for the academic year 2018-19 and mandatory for the academic year 2019-20 onwards) 1. Prerequisites : No major prerequisites are required for this course other than basic Mathematical skills. However, it will be helpful if the student has a basic knowledge of Computer Applications. 2. Learning Outcomes : " }, { "code": null, "e": 25905, "s": 25405, "text": "Develop basic computational thinking. Learn how to reason with variables, state transitions, conditionals, and iteration.Understand the notion of data types, and higher order data structures such as lists, tuples, and dictionaries.Appreciate the notion of an algorithm, and understand its structure, including how algorithms handle corner cases.Develop a basic understanding of computer systems – architecture, OS, mobile and cloud computing.Learn basic SQL programming.Learn all about cyber safety." }, { "code": null, "e": 26027, "s": 25905, "text": "Develop basic computational thinking. Learn how to reason with variables, state transitions, conditionals, and iteration." }, { "code": null, "e": 26138, "s": 26027, "text": "Understand the notion of data types, and higher order data structures such as lists, tuples, and dictionaries." }, { "code": null, "e": 26253, "s": 26138, "text": "Appreciate the notion of an algorithm, and understand its structure, including how algorithms handle corner cases." }, { "code": null, "e": 26351, "s": 26253, "text": "Develop a basic understanding of computer systems – architecture, OS, mobile and cloud computing." }, { "code": null, "e": 26380, "s": 26351, "text": "Learn basic SQL programming." }, { "code": null, "e": 26410, "s": 26380, "text": "Learn all about cyber safety." }, { "code": null, "e": 26435, "s": 26410, "text": "3. Distribution of Marks" }, { "code": null, "e": 26836, "s": 26435, "text": "Unit No. Unit Name Marks\n1. Programming and Computational Thinking - 1 35\n2. Computer Systems and Organisation 10\n3. Data Management - 1 15\n4. Society, Law and Ethics - 1 10\n5. Practical 30\nTotal 100" }, { "code": null, "e": 28268, "s": 26836, "text": "4.1 Unit 1: Programming and Computational Thinking (PCT-1) (80 Theory + 70 Practical) Familiarization with the basics of Python programming: a simple “hello world” program, process of writing a program, running it, and print statements; simple data-types: integer, float, string. Introduce the notion of a variable, and methods to manipulate it (concept of L-value and Rvalue even if not taught explicitly), Knowledge of data types and operators: accepting input from the console, assignment statement, expressions, operators and their precedence. Conditional statements: if, if-else, if-elif-else; simple programs: e.g.: absolute value, sort 3 numbers, and divisibility, Notion of iterative computation and control flow : for, while, flowcharts, decision trees and pseudo code; write a lot of programs: interest calculation, primarily testing, and factorials. Idea of debugging: errors and exceptions; debugging: pdb, break points. Sequence datatype: Lists, tuples and dictionary: finding the maximum, minimum, mean; linear search on list/tuple of numbers, and counting the frequency of elements in a list using a dictionary. Introduce the notion of accessing elements in a collection using numbers and names. Sorting algorithm: bubble and insertion sort; count the number of operations while sorting. Strings: Strings in Python : compare, concatenate, substring; notion of states and transitions using state transition diagrams. " }, { "code": null, "e": 29277, "s": 28268, "text": "4.2. Unit 2: Computer Systems and Organisation (CSO) (20 Theory + 6 Practical) Basic computer organisation: description of a computer system and mobile system, CPU, memory, hard disk, I/O, battery, power. Types of software:Types of Software – System Software, Utility Software and Application Software Language of Bits: bit, byte, MB, GB, TB, and PB. Boolean logic: OR, AND, NAND, NOR, XOR, NOT, truth tables, De Morgan’s laws Number representation: numbers in base 2, 8, 16, unsigned integers, binary addition Strings: ASCII, UTF8, UTF32, ISCII (Indian script code) Execution of a program: basic flow of compilation – program binary execution, Running a program: Notion of an operating system, idea of loading, Interpreters (process one line at a time), difference between a compiler and an interpreter, how an operating system runs a program, operating system as a resource manager. Cloud Computing: Concept of cloud computers, cloud storage (public/private), and brief introduction to parallel computing. " }, { "code": null, "e": 29654, "s": 29277, "text": "4.3. Unit 3: Data Management (DM-1) (30 Theory+ 24 Practical) Relational databases: idea of a database and the need for it, relations, keys, primary key, foreign key; use SQL commands to create a table, foreign keys; insert/delete an entry, delete a table. SQL commands: select, project, and join; indexes, and a lot of in-class practice. Basics of NoSQL databases: Mongo DB. " }, { "code": null, "e": 30154, "s": 29654, "text": "Unit 4: Society, Law and Ethics (SLE-1) – Cyber safety (10 Theory) Cyber safety: safely browsing the web, identity protection, confidentiality, social networks, cyber trolls and bullying Appropriate usage of social networks: spread of rumours, and common social networking sites (Twitter, LinkedIn, and Facebook) and specific usage rules. Safely accessing web sites: malware, adware, viruses, Trojans Safely communicating data: secure connections, eavesdropping, phishing and identity verification. " }, { "code": null, "e": 30169, "s": 30154, "text": "5. Practical " }, { "code": null, "e": 30397, "s": 30169, "text": "5.1. Programming in Python: At least the following Python concepts should be covered in the lab sessions: expressions, conditionals, loops, list, dictionary, and strings. The following are some representative lab assignments. " }, { "code": null, "e": 30781, "s": 30397, "text": "Find the largest and smallest numbers in a list.Find the third largest number in a list.Test for primarily.Find whether a string is a palindrome or not.Given two integers x and n, compute x n. Compute the greatest common divisor and the least common multiple of two integers.Test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers." }, { "code": null, "e": 30830, "s": 30781, "text": "Find the largest and smallest numbers in a list." }, { "code": null, "e": 30871, "s": 30830, "text": "Find the third largest number in a list." }, { "code": null, "e": 30891, "s": 30871, "text": "Test for primarily." }, { "code": null, "e": 30937, "s": 30891, "text": "Find whether a string is a palindrome or not." }, { "code": null, "e": 31061, "s": 30937, "text": "Given two integers x and n, compute x n. Compute the greatest common divisor and the least common multiple of two integers." }, { "code": null, "e": 31170, "s": 31061, "text": "Test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers." }, { "code": null, "e": 31371, "s": 31170, "text": "5.2. Data Management: SQL Commands At least the following SQL commands should be covered during the labs: create, insert, delete, select, and join. The following are some representative assignments. " }, { "code": null, "e": 31979, "s": 31371, "text": "Create a student table with the student id, name, and marks as attributes where the student id is the primary key.Insert the details of a new student in the above table.Delete the details of a particular student in the above table.Use the select command to get the details of the students with marks more than 80. Create a new table (name, date of birth) by joining two tables (student id, name) and (student id, date of birth).Create a new table (order ID, customer Name, and order Date) by joining two tables (order ID, customer ID, and order Date) and (customer ID, customer Name, contact Name, country)." }, { "code": null, "e": 32094, "s": 31979, "text": "Create a student table with the student id, name, and marks as attributes where the student id is the primary key." }, { "code": null, "e": 32150, "s": 32094, "text": "Insert the details of a new student in the above table." }, { "code": null, "e": 32213, "s": 32150, "text": "Delete the details of a particular student in the above table." }, { "code": null, "e": 32411, "s": 32213, "text": "Use the select command to get the details of the students with marks more than 80. Create a new table (name, date of birth) by joining two tables (student id, name) and (student id, date of birth)." }, { "code": null, "e": 32591, "s": 32411, "text": "Create a new table (order ID, customer Name, and order Date) by joining two tables (order ID, customer ID, and order Date) and (customer ID, customer Name, contact Name, country)." }, { "code": null, "e": 32606, "s": 32591, "text": "Source : CBSE " }, { "code": null, "e": 32620, "s": 32606, "text": "chhabradhanvi" }, { "code": null, "e": 32627, "s": 32620, "text": "Python" }, { "code": null, "e": 32646, "s": 32627, "text": "School Programming" }, { "code": null, "e": 32744, "s": 32646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32762, "s": 32744, "text": "Python Dictionary" }, { "code": null, "e": 32784, "s": 32762, "text": "Enumerate() in Python" }, { "code": null, "e": 32816, "s": 32784, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32858, "s": 32816, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32884, "s": 32858, "text": "Python String | replace()" }, { "code": null, "e": 32902, "s": 32884, "text": "Python Dictionary" }, { "code": null, "e": 32918, "s": 32902, "text": "Arrays in C/C++" }, { "code": null, "e": 32937, "s": 32918, "text": "Inheritance in C++" }, { "code": null, "e": 32962, "s": 32937, "text": "Reverse a string in Java" } ]
A Simple Method for Numerical Integration in Python | by Harrison Hoffman | Towards Data Science
In this article, we will introduce a simple method for computing integrals in python. We will first derive the integration formula and then implement it on a few functions in python. This article assumes you have a basic understanding of probability and integral calculus, but if you don’t you can always skip ahead to the examples. Enjoy! We must first state the definition of the expected value of a continuous random variable. Suppose X is a random variable with with probability density function f(x). The expected value of X is defined as follows: Next, we use the expectation formula to derive a simple equation for computing an integral. We would like to estimate the following integral: We first rewrite the integral as follows: We can then define a function h(x) as: This allows us to rewrite the integral in a familiar form: All of the computation in the integral has been reduced down to an expectation, and we know how to find the expected value of a set of data. The final approximation becomes: We will start simple by integrating the quadratic function f(x) = x2 from 0 to 1. # Dependenciesimport numpy as npimport scipy.integrate as integrateimport matplotlib.pyplot as plt# Our integral approximation functiondef integral_approximation(f, a, b): return (b-a)*np.mean(f)# Integrate f(x) = x^2def f1(x): return x**2# Define bounds of integrala = 0b = 1# Generate function valuesx_range = np.arange(a,b+0.0001,.0001)fx = f1(x_range)# Approximate integralapprox = integral_approximation(fx,a,b)approx Our integral approximation comes out to be: This is about what we would expect since the true value of the integral is 1/3. However, we can also compare our result to Scipy’s “quad” function. # Scipy approximationintegrate.quad(f1,a,b) The resulting value: I’m sure this example has you on the edge of your seat, but let’s see if we can’t integrate a more complicated function. The gaussian function is notorious for being extremely difficult to integrate. In this example, we will put our method to the test by integrating the standard normal distribution. # Integrating a random functionnp.random.seed(42)def gaussian(x, mu, sigma): return np.exp((-1*(x - mu)**2) / (2 * sigma**2))# Define mu and sigmamu = 0sigma = 1# Define bounds of integrala = -3b = 3# Generate function valuesx_range = np.linspace(-3,3,200)fx = gaussian(x_range, mu, sigma) The resulting function looks like this: The nice thing about our integral approximation is that the complexity of the function does affect the difficulty of the computation. In every case, all we need is the bounds of integration and the function values. # Our approximationapprox = integral_approximation(fx,a,b)approx Comparing to the Scipy solution: # Scipy approximationintegrate.quad(lambda x: np.exp((-1*(x - mu)**2) / (2 * sigma**2)),a,b) I hope that you found this article easy to follow and interesting!
[ { "code": null, "e": 511, "s": 171, "text": "In this article, we will introduce a simple method for computing integrals in python. We will first derive the integration formula and then implement it on a few functions in python. This article assumes you have a basic understanding of probability and integral calculus, but if you don’t you can always skip ahead to the examples. Enjoy!" }, { "code": null, "e": 601, "s": 511, "text": "We must first state the definition of the expected value of a continuous random variable." }, { "code": null, "e": 724, "s": 601, "text": "Suppose X is a random variable with with probability density function f(x). The expected value of X is defined as follows:" }, { "code": null, "e": 866, "s": 724, "text": "Next, we use the expectation formula to derive a simple equation for computing an integral. We would like to estimate the following integral:" }, { "code": null, "e": 908, "s": 866, "text": "We first rewrite the integral as follows:" }, { "code": null, "e": 947, "s": 908, "text": "We can then define a function h(x) as:" }, { "code": null, "e": 1006, "s": 947, "text": "This allows us to rewrite the integral in a familiar form:" }, { "code": null, "e": 1180, "s": 1006, "text": "All of the computation in the integral has been reduced down to an expectation, and we know how to find the expected value of a set of data. The final approximation becomes:" }, { "code": null, "e": 1262, "s": 1180, "text": "We will start simple by integrating the quadratic function f(x) = x2 from 0 to 1." }, { "code": null, "e": 1691, "s": 1262, "text": "# Dependenciesimport numpy as npimport scipy.integrate as integrateimport matplotlib.pyplot as plt# Our integral approximation functiondef integral_approximation(f, a, b): return (b-a)*np.mean(f)# Integrate f(x) = x^2def f1(x): return x**2# Define bounds of integrala = 0b = 1# Generate function valuesx_range = np.arange(a,b+0.0001,.0001)fx = f1(x_range)# Approximate integralapprox = integral_approximation(fx,a,b)approx" }, { "code": null, "e": 1735, "s": 1691, "text": "Our integral approximation comes out to be:" }, { "code": null, "e": 1883, "s": 1735, "text": "This is about what we would expect since the true value of the integral is 1/3. However, we can also compare our result to Scipy’s “quad” function." }, { "code": null, "e": 1927, "s": 1883, "text": "# Scipy approximationintegrate.quad(f1,a,b)" }, { "code": null, "e": 1948, "s": 1927, "text": "The resulting value:" }, { "code": null, "e": 2069, "s": 1948, "text": "I’m sure this example has you on the edge of your seat, but let’s see if we can’t integrate a more complicated function." }, { "code": null, "e": 2249, "s": 2069, "text": "The gaussian function is notorious for being extremely difficult to integrate. In this example, we will put our method to the test by integrating the standard normal distribution." }, { "code": null, "e": 2542, "s": 2249, "text": "# Integrating a random functionnp.random.seed(42)def gaussian(x, mu, sigma): return np.exp((-1*(x - mu)**2) / (2 * sigma**2))# Define mu and sigmamu = 0sigma = 1# Define bounds of integrala = -3b = 3# Generate function valuesx_range = np.linspace(-3,3,200)fx = gaussian(x_range, mu, sigma)" }, { "code": null, "e": 2582, "s": 2542, "text": "The resulting function looks like this:" }, { "code": null, "e": 2797, "s": 2582, "text": "The nice thing about our integral approximation is that the complexity of the function does affect the difficulty of the computation. In every case, all we need is the bounds of integration and the function values." }, { "code": null, "e": 2862, "s": 2797, "text": "# Our approximationapprox = integral_approximation(fx,a,b)approx" }, { "code": null, "e": 2895, "s": 2862, "text": "Comparing to the Scipy solution:" }, { "code": null, "e": 2988, "s": 2895, "text": "# Scipy approximationintegrate.quad(lambda x: np.exp((-1*(x - mu)**2) / (2 * sigma**2)),a,b)" } ]
An Unsupervised Mathematical Scoring Model | by Abhishek Mungoli | Towards Data Science
A Mathematical model is a description of a system using mathematical equations. The system is governed by a set of mathematical equations that can be linear, non-linear, static, or dynamic. The model can learn the parameters of the equation from available data and even predict the future. In this blog, I will discuss one such practical mathematical model that can be utilized in a variety of problems in the absence of labeled data with some prior domain knowledge. All the codes and datasets used in this blog can be found here. Logistic function commonly known as the Sigmoid function is a mathematical function having a characteristic “S”-shaped curve or sigmoid curve. where, X0 = the X value of the sigmoid’s midpoint L = the curve’s maximum value k = the logistic growth rate or steepness of the curve. The logistic function can take any value of x between -∞ to +∞. For x approaching +∞, f(x) approaches L and for x approaching -∞, f(x) approaches 0. The standard sigmoid function returns a value in the range 0 to 1. The equation is given by For x = 0, S(x=0) = 0.5 x < 0, S(x<0) < 0.5 and x >0, S(x>0) > 0.5 So, the Sigmoid function is 0-centered. We have financial data of customers available. One feature from it is the credit amount i.e. the credit already in the name of the customer. Now, depending on the amount of credit we intend to generate a risk score between 0–1. The distribution of the data can vary in different datasets and among different features. Let’s see the distribution of credit_amount. The credit_amount is skewed towards the right. In different datasets and use-cases, the skewness or distribution of data may vary. We wish to come up with a scoring mechanism that penalizes the outliers more. In our case, we will come up with an ideal behavior and try to learn the parameters for the logistic function that can best mimic the ideal behavior. Let’s define the ideal behavior: The Risk score to be in range 0 to 1.The data to be centered at the 65th percentile of data. (Assumption since we want to penalize the outliers more)Ideally, we wish the score for 65th percentile to be 0.50, for 75th percentile to be 0.65, for 80th percentile to be 0.70, and 85th percentile to be 0.75. For the rest of the data, we wish the scores to vary accordingly.Different features may have a different distribution and range, so we wish to come up with a technique that can learn the parameters of the logistic function to match the ideal behavior defined in Step 3. The Risk score to be in range 0 to 1. The data to be centered at the 65th percentile of data. (Assumption since we want to penalize the outliers more) Ideally, we wish the score for 65th percentile to be 0.50, for 75th percentile to be 0.65, for 80th percentile to be 0.70, and 85th percentile to be 0.75. For the rest of the data, we wish the scores to vary accordingly. Different features may have a different distribution and range, so we wish to come up with a technique that can learn the parameters of the logistic function to match the ideal behavior defined in Step 3. For our problem of defining a risk score for credit_amount using the logistic function, let’s decode the parameters. where, X0 = the X value of the sigmoid’s midpoint L = the curve’s maximum value k = the logistic growth rate or steepness of the curve. Since we want the risk score range between 0 and 1, L = 1. Since we want the logistic function to be centered around 65th percentile of data, X0 = 65th percentile of credit amount The growth rate k, we will learn through Random search, which can best mimic the ideal behavior with minimum Mean squared error from the ideal behavior defined in Step 3. # Logistic function ~ b denotes X0 and c denotes k(growth rate)def sigmoid(x,b,c): return 1 / (1 + math.exp(-c * (x-b))) Calculating error for a probable growth rate ‘k’ # Mean Squared error between ideal and observed behavior# b denotes X0 and c denotes k(growth rate)def cal_error(c,pcts,values_expected): error = math.pow(sigmoid(pcts[0],pcts[3],c) - values_expected[0],2) + math.pow(sigmoid(pcts[1],pcts[3],c) - values_expected[1],2) + math.pow(sigmoid(pcts[2],pcts[3],c) - values_expected[2],2) + math.pow(sigmoid(pcts[3],pcts[3],c) - values_expected[3],2) return error Random search to find the best ‘k’, growth rate def find_best_decay_parameter(pcts,values_expected): best_error = 999999 best_c = 1.0 iterations = 5000 for i in range(iterations): tmp = random.random() error = cal_error(tmp,pcts,values_expected) if error<best_error: best_error = error best_c = tmp return best_c Calling the function percentiles = [85,80,75,65]values_expected = [0.75,0.70,0.65,0.50]b,c = find_decay_parameter(df.credit_amount,values_expected) Output Best value of Growth rate 'k' = 0.00047Value of L = 1value of X0 = 3187 65th 75th 80th 85thValue 3187 3972 4720 5969Expected Score 0.50 0.65 0.70 0.75Observed Score 0.50 0.59 0.67 0.79 I checked how the score varies with the different credit amounts credit_amounts = [100,500,1200,3000,4000,5200,6000,7500,10000,12000,20000,25000]risk = []mp_values = {}for credit_amount in credit_amounts: mp_values[credit_amount] = round(sigmoid(credit_amount,b,c),2) Output: With finding the right value for parameters ‘L’, ‘X0’, and ‘k’, we have fit a mathematical model to get the risk score close to the ideal score behavior we wanted i.e. penalizing the outliers more. In the above section, we saw the risk score as a function of one variable i.e. credit_amount. But, what if we have more than one variable and we want the risk score to be a function of all these variables. In that case, we can first find the weightage/importance of each variable such that the weights add up to 1. Then we can fit an individual logistic function to each variable and finally do the weighted sum of the individual risk score. Let’s take an example with 3 variables and their risk scores and weights. Final Risk Score = 0.72 * 0.3 + 0.65 * 0.25 + 0.81 * 0.45 = 0.743 Through this blogpost, we understood what a mathematical model is and looked at one such mathematical model using the Logistic function. Such models can be utilized in a variety of problems in the absence of labeled data with some prior domain knowledge like the feature’s importance and feature’s distribution. All the codes and datasets used in this blog can be found here. If you have any doubts or queries, do reach out to me. I will be interested to know if you think you have a use-case in which one such mathematical model can be utilized. My Youtube channel for more content: www.youtube.com About the author-: Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc. My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me on Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs - Dimensionality Reduction: PCA versus Autoencoders Experience the power of the Genetic Algorithm 5 Mistakes every Data Scientist should avoid Decomposing Time Series in a simple & intuitive way How GPU Computing literally saved me at work? Information Theory & KL Divergence Part I and Part II Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets A Semi-Supervised Embedding based Fuzzy Clustering Compare which Machine Learning Model performs Better Analyzing Fitbit Data to Demystify Bodily Pattern Changes Amid Pandemic Lockdown Myths and Reality around Correlation A Guide to Becoming Business-Oriented Data Scientist
[ { "code": null, "e": 462, "s": 172, "text": "A Mathematical model is a description of a system using mathematical equations. The system is governed by a set of mathematical equations that can be linear, non-linear, static, or dynamic. The model can learn the parameters of the equation from available data and even predict the future." }, { "code": null, "e": 704, "s": 462, "text": "In this blog, I will discuss one such practical mathematical model that can be utilized in a variety of problems in the absence of labeled data with some prior domain knowledge. All the codes and datasets used in this blog can be found here." }, { "code": null, "e": 847, "s": 704, "text": "Logistic function commonly known as the Sigmoid function is a mathematical function having a characteristic “S”-shaped curve or sigmoid curve." }, { "code": null, "e": 854, "s": 847, "text": "where," }, { "code": null, "e": 897, "s": 854, "text": "X0 = the X value of the sigmoid’s midpoint" }, { "code": null, "e": 927, "s": 897, "text": "L = the curve’s maximum value" }, { "code": null, "e": 983, "s": 927, "text": "k = the logistic growth rate or steepness of the curve." }, { "code": null, "e": 1132, "s": 983, "text": "The logistic function can take any value of x between -∞ to +∞. For x approaching +∞, f(x) approaches L and for x approaching -∞, f(x) approaches 0." }, { "code": null, "e": 1224, "s": 1132, "text": "The standard sigmoid function returns a value in the range 0 to 1. The equation is given by" }, { "code": null, "e": 1248, "s": 1224, "text": "For x = 0, S(x=0) = 0.5" }, { "code": null, "e": 1291, "s": 1248, "text": "x < 0, S(x<0) < 0.5 and x >0, S(x>0) > 0.5" }, { "code": null, "e": 1331, "s": 1291, "text": "So, the Sigmoid function is 0-centered." }, { "code": null, "e": 1559, "s": 1331, "text": "We have financial data of customers available. One feature from it is the credit amount i.e. the credit already in the name of the customer. Now, depending on the amount of credit we intend to generate a risk score between 0–1." }, { "code": null, "e": 1694, "s": 1559, "text": "The distribution of the data can vary in different datasets and among different features. Let’s see the distribution of credit_amount." }, { "code": null, "e": 1825, "s": 1694, "text": "The credit_amount is skewed towards the right. In different datasets and use-cases, the skewness or distribution of data may vary." }, { "code": null, "e": 1903, "s": 1825, "text": "We wish to come up with a scoring mechanism that penalizes the outliers more." }, { "code": null, "e": 2086, "s": 1903, "text": "In our case, we will come up with an ideal behavior and try to learn the parameters for the logistic function that can best mimic the ideal behavior. Let’s define the ideal behavior:" }, { "code": null, "e": 2660, "s": 2086, "text": "The Risk score to be in range 0 to 1.The data to be centered at the 65th percentile of data. (Assumption since we want to penalize the outliers more)Ideally, we wish the score for 65th percentile to be 0.50, for 75th percentile to be 0.65, for 80th percentile to be 0.70, and 85th percentile to be 0.75. For the rest of the data, we wish the scores to vary accordingly.Different features may have a different distribution and range, so we wish to come up with a technique that can learn the parameters of the logistic function to match the ideal behavior defined in Step 3." }, { "code": null, "e": 2698, "s": 2660, "text": "The Risk score to be in range 0 to 1." }, { "code": null, "e": 2811, "s": 2698, "text": "The data to be centered at the 65th percentile of data. (Assumption since we want to penalize the outliers more)" }, { "code": null, "e": 3032, "s": 2811, "text": "Ideally, we wish the score for 65th percentile to be 0.50, for 75th percentile to be 0.65, for 80th percentile to be 0.70, and 85th percentile to be 0.75. For the rest of the data, we wish the scores to vary accordingly." }, { "code": null, "e": 3237, "s": 3032, "text": "Different features may have a different distribution and range, so we wish to come up with a technique that can learn the parameters of the logistic function to match the ideal behavior defined in Step 3." }, { "code": null, "e": 3354, "s": 3237, "text": "For our problem of defining a risk score for credit_amount using the logistic function, let’s decode the parameters." }, { "code": null, "e": 3361, "s": 3354, "text": "where," }, { "code": null, "e": 3404, "s": 3361, "text": "X0 = the X value of the sigmoid’s midpoint" }, { "code": null, "e": 3434, "s": 3404, "text": "L = the curve’s maximum value" }, { "code": null, "e": 3490, "s": 3434, "text": "k = the logistic growth rate or steepness of the curve." }, { "code": null, "e": 3549, "s": 3490, "text": "Since we want the risk score range between 0 and 1, L = 1." }, { "code": null, "e": 3670, "s": 3549, "text": "Since we want the logistic function to be centered around 65th percentile of data, X0 = 65th percentile of credit amount" }, { "code": null, "e": 3841, "s": 3670, "text": "The growth rate k, we will learn through Random search, which can best mimic the ideal behavior with minimum Mean squared error from the ideal behavior defined in Step 3." }, { "code": null, "e": 3965, "s": 3841, "text": "# Logistic function ~ b denotes X0 and c denotes k(growth rate)def sigmoid(x,b,c): return 1 / (1 + math.exp(-c * (x-b)))" }, { "code": null, "e": 4014, "s": 3965, "text": "Calculating error for a probable growth rate ‘k’" }, { "code": null, "e": 4425, "s": 4014, "text": "# Mean Squared error between ideal and observed behavior# b denotes X0 and c denotes k(growth rate)def cal_error(c,pcts,values_expected): error = math.pow(sigmoid(pcts[0],pcts[3],c) - values_expected[0],2) + math.pow(sigmoid(pcts[1],pcts[3],c) - values_expected[1],2) + math.pow(sigmoid(pcts[2],pcts[3],c) - values_expected[2],2) + math.pow(sigmoid(pcts[3],pcts[3],c) - values_expected[3],2) return error" }, { "code": null, "e": 4473, "s": 4425, "text": "Random search to find the best ‘k’, growth rate" }, { "code": null, "e": 4796, "s": 4473, "text": "def find_best_decay_parameter(pcts,values_expected): best_error = 999999 best_c = 1.0 iterations = 5000 for i in range(iterations): tmp = random.random() error = cal_error(tmp,pcts,values_expected) if error<best_error: best_error = error best_c = tmp return best_c" }, { "code": null, "e": 4817, "s": 4796, "text": "Calling the function" }, { "code": null, "e": 4948, "s": 4817, "text": "percentiles = [85,80,75,65]values_expected = [0.75,0.70,0.65,0.50]b,c = find_decay_parameter(df.credit_amount,values_expected)" }, { "code": null, "e": 4955, "s": 4948, "text": "Output" }, { "code": null, "e": 5192, "s": 4955, "text": "Best value of Growth rate 'k' = 0.00047Value of L = 1value of X0 = 3187 65th 75th 80th 85thValue 3187 3972 4720 5969Expected Score 0.50 0.65 0.70 0.75Observed Score 0.50 0.59 0.67 0.79" }, { "code": null, "e": 5257, "s": 5192, "text": "I checked how the score varies with the different credit amounts" }, { "code": null, "e": 5463, "s": 5257, "text": "credit_amounts = [100,500,1200,3000,4000,5200,6000,7500,10000,12000,20000,25000]risk = []mp_values = {}for credit_amount in credit_amounts: mp_values[credit_amount] = round(sigmoid(credit_amount,b,c),2)" }, { "code": null, "e": 5471, "s": 5463, "text": "Output:" }, { "code": null, "e": 5669, "s": 5471, "text": "With finding the right value for parameters ‘L’, ‘X0’, and ‘k’, we have fit a mathematical model to get the risk score close to the ideal score behavior we wanted i.e. penalizing the outliers more." }, { "code": null, "e": 5875, "s": 5669, "text": "In the above section, we saw the risk score as a function of one variable i.e. credit_amount. But, what if we have more than one variable and we want the risk score to be a function of all these variables." }, { "code": null, "e": 6111, "s": 5875, "text": "In that case, we can first find the weightage/importance of each variable such that the weights add up to 1. Then we can fit an individual logistic function to each variable and finally do the weighted sum of the individual risk score." }, { "code": null, "e": 6185, "s": 6111, "text": "Let’s take an example with 3 variables and their risk scores and weights." }, { "code": null, "e": 6251, "s": 6185, "text": "Final Risk Score = 0.72 * 0.3 + 0.65 * 0.25 + 0.81 * 0.45 = 0.743" }, { "code": null, "e": 6627, "s": 6251, "text": "Through this blogpost, we understood what a mathematical model is and looked at one such mathematical model using the Logistic function. Such models can be utilized in a variety of problems in the absence of labeled data with some prior domain knowledge like the feature’s importance and feature’s distribution. All the codes and datasets used in this blog can be found here." }, { "code": null, "e": 6798, "s": 6627, "text": "If you have any doubts or queries, do reach out to me. I will be interested to know if you think you have a use-case in which one such mathematical model can be utilized." }, { "code": null, "e": 6835, "s": 6798, "text": "My Youtube channel for more content:" }, { "code": null, "e": 6851, "s": 6835, "text": "www.youtube.com" }, { "code": null, "e": 6870, "s": 6851, "text": "About the author-:" }, { "code": null, "e": 7250, "s": 6870, "text": "Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc." }, { "code": null, "e": 7630, "s": 7250, "text": "My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me on Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs -" }, { "code": null, "e": 7680, "s": 7630, "text": "Dimensionality Reduction: PCA versus Autoencoders" }, { "code": null, "e": 7726, "s": 7680, "text": "Experience the power of the Genetic Algorithm" }, { "code": null, "e": 7771, "s": 7726, "text": "5 Mistakes every Data Scientist should avoid" }, { "code": null, "e": 7823, "s": 7771, "text": "Decomposing Time Series in a simple & intuitive way" }, { "code": null, "e": 7869, "s": 7823, "text": "How GPU Computing literally saved me at work?" }, { "code": null, "e": 7923, "s": 7869, "text": "Information Theory & KL Divergence Part I and Part II" }, { "code": null, "e": 7989, "s": 7923, "text": "Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets" }, { "code": null, "e": 8040, "s": 7989, "text": "A Semi-Supervised Embedding based Fuzzy Clustering" }, { "code": null, "e": 8093, "s": 8040, "text": "Compare which Machine Learning Model performs Better" }, { "code": null, "e": 8174, "s": 8093, "text": "Analyzing Fitbit Data to Demystify Bodily Pattern Changes Amid Pandemic Lockdown" }, { "code": null, "e": 8211, "s": 8174, "text": "Myths and Reality around Correlation" } ]
VBScript Number Conversion Functions
Variable_name = Conversion_function_name(expression) Number functions help us to convert a given number from one data subtype to another data subtype. CDbl A Function, which converts a given number of any variant subtype to double CInt A Function, which converts a given number of any variant subtype to Integer CLng A Function, which converts a given number of any variant subtype to Long CSng A Function, which converts a given number of any variant subtype to Single Hex A Function, which converts a given number of any variant subtype to Hexadecimal Try the following example to understand all the Number Conversion Functions available in VBScript. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> x = 123 y = 123.882 document.write("x value after converting to double - " & CDbl(x) & "<br />") document.write("y value after converting to double - " & CDbl(y) & "<br />") document.write("x value after converting to Int -" & CInt(x) & "<br />") document.write("y value after converting to Int -" & CInt(y) & "<br />") document.write("x value after converting to Long -" & CLng(x) & "<br />") document.write("y value after converting to Long -" & CLng(y) & "<br />") document.write("x value after converting to Single -" & CSng(x) & "<br />") document.write("y value after converting to Single -" & CSng(y) & "<br />") document.write("x value after converting to Hex -" & Hex(x) & "<br />") document.write("y value after converting to Hex -" & Hex(y) & "<br />") </script> </body> </html> When executed, the above script will produce the following output − x value after converting to double - 123 y value after converting to double - 123.882 x value after converting to Int -123 y value after converting to Int -124 x value after converting to Long -123 y value after converting to Long -124 x value after converting to Single -123 y value after converting to Single -123.882 x value after converting to Hex -7B y value after converting to Hex -7C 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 2080, "text": "Variable_name = Conversion_function_name(expression)" }, { "code": null, "e": 2231, "s": 2133, "text": "Number functions help us to convert a given number from one data subtype to another data subtype." }, { "code": null, "e": 2236, "s": 2231, "text": "CDbl" }, { "code": null, "e": 2311, "s": 2236, "text": "A Function, which converts a given number of any variant subtype to double" }, { "code": null, "e": 2316, "s": 2311, "text": "CInt" }, { "code": null, "e": 2392, "s": 2316, "text": "A Function, which converts a given number of any variant subtype to Integer" }, { "code": null, "e": 2397, "s": 2392, "text": "CLng" }, { "code": null, "e": 2470, "s": 2397, "text": "A Function, which converts a given number of any variant subtype to Long" }, { "code": null, "e": 2475, "s": 2470, "text": "CSng" }, { "code": null, "e": 2550, "s": 2475, "text": "A Function, which converts a given number of any variant subtype to Single" }, { "code": null, "e": 2554, "s": 2550, "text": "Hex" }, { "code": null, "e": 2634, "s": 2554, "text": "A Function, which converts a given number of any variant subtype to Hexadecimal" }, { "code": null, "e": 2733, "s": 2634, "text": "Try the following example to understand all the Number Conversion Functions available in VBScript." }, { "code": null, "e": 3826, "s": 2733, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n x = 123\n y = 123.882\n document.write(\"x value after converting to double - \" & CDbl(x) & \"<br />\")\n \n document.write(\"y value after converting to double - \" & CDbl(y) & \"<br />\")\n \n document.write(\"x value after converting to Int -\" & CInt(x) & \"<br />\")\n \n document.write(\"y value after converting to Int -\" & CInt(y) & \"<br />\")\n \n document.write(\"x value after converting to Long -\" & CLng(x) & \"<br />\")\n \n document.write(\"y value after converting to Long -\" & CLng(y) & \"<br />\") \n \n document.write(\"x value after converting to Single -\" & CSng(x) & \"<br />\")\n \n document.write(\"y value after converting to Single -\" & CSng(y) & \"<br />\") \n \n document.write(\"x value after converting to Hex -\" & Hex(x) & \"<br />\")\n \n document.write(\"y value after converting to Hex -\" & Hex(y) & \"<br />\") \n </script>\n </body>\n</html>" }, { "code": null, "e": 3894, "s": 3826, "text": "When executed, the above script will produce the following output −" }, { "code": null, "e": 4287, "s": 3894, "text": "x value after converting to double - 123\ny value after converting to double - 123.882\nx value after converting to Int -123\ny value after converting to Int -124\nx value after converting to Long -123\ny value after converting to Long -124\nx value after converting to Single -123\ny value after converting to Single -123.882\nx value after converting to Hex -7B\ny value after converting to Hex -7C\n" }, { "code": null, "e": 4320, "s": 4287, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 4337, "s": 4320, "text": " Frahaan Hussain" }, { "code": null, "e": 4344, "s": 4337, "text": " Print" }, { "code": null, "e": 4355, "s": 4344, "text": " Add Notes" } ]
Match multiple occurrences in a string with JavaScript?
To match multiple occurrences in a string, use regular expressions. Following is the code − function checkMultipleOccurrences(sentence) { var matchExpression = /(JavaScript?[^\s]+)|(typescript?[^\s]+)/g; return sentence.match(matchExpression); } var sentence="This is my first JavaScript Program which is the subset of typescript"; console.log(sentence); console.log(checkMultipleOccurrences(sentence)); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo70.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo70.js This is my first JavaScript Program which is the subset of typescript [ 'JavaScript', 'typescript' ]
[ { "code": null, "e": 1154, "s": 1062, "text": "To match multiple occurrences in a string, use regular expressions. Following is the code −" }, { "code": null, "e": 1472, "s": 1154, "text": "function checkMultipleOccurrences(sentence) {\n var matchExpression = /(JavaScript?[^\\s]+)|(typescript?[^\\s]+)/g;\n return sentence.match(matchExpression);\n}\nvar sentence=\"This is my first JavaScript Program which is the subset\nof typescript\";\nconsole.log(sentence);\nconsole.log(checkMultipleOccurrences(sentence));" }, { "code": null, "e": 1538, "s": 1472, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1556, "s": 1538, "text": "node fileName.js." }, { "code": null, "e": 1589, "s": 1556, "text": "Here, my file name is demo70.js." }, { "code": null, "e": 1630, "s": 1589, "text": "This will produce the following output −" }, { "code": null, "e": 1780, "s": 1630, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo70.js\nThis is my first JavaScript Program which is the subset of typescript\n[ 'JavaScript', 'typescript' ]" } ]
Machine Learning Pipelines with Kubeflow | by George Novack | Towards Data Science
A lot of attention is being given now to the idea of Machine Learning Pipelines, which are meant to automate and orchestrate the various steps involved in training a machine learning model; however, it’s not always made clear what the benefits are of modeling machine learning workflows as automated pipelines. When tasked with training a new ML model, most Data Scientists and ML Engineers will probably start by developing some new Python scripts or interactive notebooks that perform the data extraction and preprocessing necessary to construct a clean set of data on which to train the model. Then, they might create several additional scripts or notebooks to try out different types of models or different machine learning frameworks. And finally, they’ll gather and explore metrics to evaluate how each model performed on a test dataset, and then determine which model to deploy to production. This is obviously an over-simplification of a true machine learning workflow, but the key point is that this general approach requires a lot of manual involvement, and is not reusable or easily repeatable by anyone but the engineer(s) that initially developed it. We can use Machine Learning Pipelines to address these concerns. Rather than treating the data preparation, model training, model validation, and model deployment as a single codebase meant for the specific model that we’re working on, we can treat this workflow as a sequence of separate, modular steps that each focus on a specific task. There are a number of benefits of modeling our machine learning workflows as Machine Learning Pipelines: Automation: By removing the need for manual intervention, we can schedule our pipeline to retrain the model on a specific cadence, making sure our model adapts to drift in the training data over time. Reuse: Since the steps of a pipeline are separate from the pipeline itself, we can easily reuse a single step in multiple pipelines. Repeatability: Any Data Scientist or Engineer can rerun a pipeline, whereas, with the manual workflow, it might now always be clear what order different scripts or notebooks need to be run in. Decoupling of Environment: By keeping the steps of a Machine Learning Pipeline decoupled, we can run different steps in different types of environments. For example, some of the data preparation steps might need to run on a large cluster of machines, whereas the model deployment step could probably run on a single machine. If you’re interested in a deeper dive into Machine Learning pipelines and their benefits, Google Cloud has a great article that describes a natural progression toward better, more automated practices (including ML Pipelines) that teams can adopt to mature their ML workflows: MLOps: Continuous delivery and automation pipelines in machine learning Kubeflow is an open-source platform, built on Kubernetes, that aims to simplify the development and deployment of machine learning systems. Described in the official documentation as the ML toolkit for Kubernetes, Kubeflow consists of several components that span the various steps of the machine learning development lifecycle. These components include notebook development environments, hyperparameter tuning, feature management, model serving, and, of course, machine learning pipelines. In this article, we’ll just be focused on the Pipelines component of Kubeflow. To run the example pipeline, I used a Kubernetes cluster running on bare metal, but you can run the example code on any Kubernetes cluster where Kubeflow is installed. The only dependency needed locally is the Kubeflow Pipelines SDK. You can install the SDK using pip: pip install kfp Pipelines in Kubeflow are made up of one or more components, which represent individual steps in a pipeline. Each component is executed in its own Docker container, which means that each step in the pipeline can have its own set of dependencies, independent of the other components. For each component we develop, we’ll create a separate Docker image that accepts some inputs, performs an operation, then exposes some outputs. We’ll also have a separate python script, pipeline.py that creates pipeline components out of each Docker image, then constructs a pipeline using the components. We’ll create four components in all: preprocess-data: this component will load the Boston Housing dataset from sklearn.datasets and then split the dataset into training and test sets. train-model: this component will train a model to predict the median value of homes in Boston using the Boston Housing dataset. test-model: this component will compute and output the mean squared error of the model on the test dataset deploy-model: we won’t be focusing on model deployment or serving in this article, so this component will just log a message saying that it’s deploying the model. In a real-world scenario, this could be a generic component for deploying any model to a QA or Production environment. If all this talk of components and Docker images sounds confusing: don’t worry, it should all start to make more sense when we get into the code. The first component in our pipeline will use sklearn.datasets to load in the Boston Housing dataset. We’ll split this dataset into train and test sets using Sci-kit learn’s train_test_split function, then we’ll use np.save to save our dataset to disk so that it can be reused by later components. So far this is just a simple Python script. Now we need to create a Docker image that executes this script. We’ll write a Dockerfile to build the image: Starting from the python:3.7-slim base image, we’ll install the necessary packages using pip , copy the preprocess Python script from our local machine to the container, and then specify the preprocess.py script as the container entrypoint, which means that when the container starts, it will execute our script. Now we’ll get started on the pipeline. First, you’ll need to make sure that the Docker image that we defined above is accessible from your Kubernetes cluster. For the purpose of this example, I used GitHub Actions to build the image and push it to Docker Hub. Now let’s define a component. Each component is defined as a function that returns an object of type ContainerOp . This type comes from the kfp SDK that we installed earlier. Here is a component definition for the first component in our pipeline: Notice that for the image argument, we’re passing the name of the Docker image defined by the Dockerfile above, and for the file_outputs argument, we’re specifying the file paths of the four .npy files that are saved to disk by our component Python script. By specifying these four files as File Outputs, we make them available for other components in the pipeline. Note: It’s not a very good practice to hard-code file paths in our components, because, as you can see from the code above, this requires that the person creating the component definition knows specific details about the component implementation (that is, the implementation contained in the Docker image). It would be much cleaner to have our component accept the file paths as command-line arguments. This way the person defining the component has full control over where to expect the output files. I’ve left it hard-coded this way to hopefully make it easier to see how all of these pieces fit together. With our first component defined, we can create a pipeline that uses the preprocess-data component. The pipeline definition is a Python function decorated with the @dsl.pipeline annotation. Within the function, we can use the component like we would any other function. To execute the pipeline, we create a kfp.Client object and invoke the create_run_from_pipeline_func function, passing in the function that defines our pipeline. If we execute this script, then navigate to the Experiments view in the Pipelines section of the Kubeflow central dashboard, we’ll see the execution of our pipeline. We can also see the four file outputs from the preprocess-data component by clicking on the component in the graph view of the pipeline. So we can execute our pipeline and visualize it in the GUI, but a pipeline with a single step isn’t all that exciting. Let’s create the remaining components. For the train-model component, we’ll create a simple python script that trains a regression model using Sci-kit learn. This should look similar to the python script for the preprocessor component. The big difference is that here we’re using argparse to accept the file paths to the training data as command-line arguments. The Dockerfile, likewise, is very similar to the one we used for the first component. We start with the base image, install the necessary packages, copy the python script into the container, then execute the script. The two other components, test-model and deploy-model, follow this same pattern. In fact, they’re so similar to the two components we’ve already implemented, that for the sake of brevity I won’t show them here. If you’re interested, you can find all of the code for the pipeline in this GitHub repository: https://github.com/gnovack/kubeflow-pipelines Just like with the preprocess-data component from earlier, we’ll build Docker images out of these three components and push them to Docker Hub: train-model: gnovack/boston_pipeline_train test-model: gnovack/boston_pipeline_test deploy-model: gnovack/boston_pipeline_deploy Now it’s time to create the full machine learning pipeline. First, we’ll create component definitions for the train-model, test-model, and deploy-model components. The only major difference between the definition of the train-model component and that of the preprocess-data component from earlier is that train-model accepts two arguments, x_train and y_train which will be passed to the container as command-line arguments, and will be parsed out in the component implementation using the argparse module. Now the definitions for the test-model and deploy-model components: With the four pipeline components defined, we’ll now revisit the boston_pipeline function from earlier and use all of our components together. Let’s break this down: Notice on line 6, when we invoke the preprocess_op() function, we store the output of the function in a variable called _preprocess_op . To access the outputs of the preprocess-data component, we call _preprocess_op.outputs['NAME_OF_OUTPUT'] . By default, when we access the file_outputs from a component, we get the contents of the file rather than the file path. In our case, since these aren’t plain text files, we can’t just pass the file contents into the component Docker containers as command-line arguments. To access the file path, we use dsl.InputArgumentPath() and pass in the component output. Now if we create a run from the pipeline and navigate to the Pipelines UI in the Kubeflow central dashboard, we should see all four components displayed in the pipeline graph. In this article, we created a very simple machine learning pipeline that loads in some data, trains a model, evaluates it on a holdout dataset, and then “deploys” it. By using Kubeflow Pipelines, we were able to encapsulate each step in this workflow into Pipeline Components that each run in their very own, isolated Docker container environments. This encapsulation promotes loose coupling between the steps in our machine learning workflow and opens up the possibility of reusing components in future pipelines. For example, there wasn’t anything in our training component specific to the Boston Housing dataset. We might be able to reuse this component any time we want to train a regression model using Sci-kit learn. We just scratched the surface of what’s possible with Kubeflow Pipelines, but hopefully, this article helped you understand the basics of components, and how we can use them together to create and execute pipelines. If you’re interested in exploring the whole codebase used in this article, you can find it all in this GitHub repo: https://github.com/gnovack/kubeflow-pipelines References https://kubeflow-pipelines.readthedocs.io/en/latest/index.html https://www.kubeflow.org/docs/pipelines/sdk/build-component/ MLOps: Continuous delivery and automation pipelines in machine learning Thanks for reading! Feel free to reach out with any questions or comments.
[ { "code": null, "e": 358, "s": 47, "text": "A lot of attention is being given now to the idea of Machine Learning Pipelines, which are meant to automate and orchestrate the various steps involved in training a machine learning model; however, it’s not always made clear what the benefits are of modeling machine learning workflows as automated pipelines." }, { "code": null, "e": 947, "s": 358, "text": "When tasked with training a new ML model, most Data Scientists and ML Engineers will probably start by developing some new Python scripts or interactive notebooks that perform the data extraction and preprocessing necessary to construct a clean set of data on which to train the model. Then, they might create several additional scripts or notebooks to try out different types of models or different machine learning frameworks. And finally, they’ll gather and explore metrics to evaluate how each model performed on a test dataset, and then determine which model to deploy to production." }, { "code": null, "e": 1211, "s": 947, "text": "This is obviously an over-simplification of a true machine learning workflow, but the key point is that this general approach requires a lot of manual involvement, and is not reusable or easily repeatable by anyone but the engineer(s) that initially developed it." }, { "code": null, "e": 1551, "s": 1211, "text": "We can use Machine Learning Pipelines to address these concerns. Rather than treating the data preparation, model training, model validation, and model deployment as a single codebase meant for the specific model that we’re working on, we can treat this workflow as a sequence of separate, modular steps that each focus on a specific task." }, { "code": null, "e": 1656, "s": 1551, "text": "There are a number of benefits of modeling our machine learning workflows as Machine Learning Pipelines:" }, { "code": null, "e": 1857, "s": 1656, "text": "Automation: By removing the need for manual intervention, we can schedule our pipeline to retrain the model on a specific cadence, making sure our model adapts to drift in the training data over time." }, { "code": null, "e": 1990, "s": 1857, "text": "Reuse: Since the steps of a pipeline are separate from the pipeline itself, we can easily reuse a single step in multiple pipelines." }, { "code": null, "e": 2183, "s": 1990, "text": "Repeatability: Any Data Scientist or Engineer can rerun a pipeline, whereas, with the manual workflow, it might now always be clear what order different scripts or notebooks need to be run in." }, { "code": null, "e": 2508, "s": 2183, "text": "Decoupling of Environment: By keeping the steps of a Machine Learning Pipeline decoupled, we can run different steps in different types of environments. For example, some of the data preparation steps might need to run on a large cluster of machines, whereas the model deployment step could probably run on a single machine." }, { "code": null, "e": 2856, "s": 2508, "text": "If you’re interested in a deeper dive into Machine Learning pipelines and their benefits, Google Cloud has a great article that describes a natural progression toward better, more automated practices (including ML Pipelines) that teams can adopt to mature their ML workflows: MLOps: Continuous delivery and automation pipelines in machine learning" }, { "code": null, "e": 3347, "s": 2856, "text": "Kubeflow is an open-source platform, built on Kubernetes, that aims to simplify the development and deployment of machine learning systems. Described in the official documentation as the ML toolkit for Kubernetes, Kubeflow consists of several components that span the various steps of the machine learning development lifecycle. These components include notebook development environments, hyperparameter tuning, feature management, model serving, and, of course, machine learning pipelines." }, { "code": null, "e": 3426, "s": 3347, "text": "In this article, we’ll just be focused on the Pipelines component of Kubeflow." }, { "code": null, "e": 3594, "s": 3426, "text": "To run the example pipeline, I used a Kubernetes cluster running on bare metal, but you can run the example code on any Kubernetes cluster where Kubeflow is installed." }, { "code": null, "e": 3695, "s": 3594, "text": "The only dependency needed locally is the Kubeflow Pipelines SDK. You can install the SDK using pip:" }, { "code": null, "e": 3711, "s": 3695, "text": "pip install kfp" }, { "code": null, "e": 3994, "s": 3711, "text": "Pipelines in Kubeflow are made up of one or more components, which represent individual steps in a pipeline. Each component is executed in its own Docker container, which means that each step in the pipeline can have its own set of dependencies, independent of the other components." }, { "code": null, "e": 4300, "s": 3994, "text": "For each component we develop, we’ll create a separate Docker image that accepts some inputs, performs an operation, then exposes some outputs. We’ll also have a separate python script, pipeline.py that creates pipeline components out of each Docker image, then constructs a pipeline using the components." }, { "code": null, "e": 4337, "s": 4300, "text": "We’ll create four components in all:" }, { "code": null, "e": 4484, "s": 4337, "text": "preprocess-data: this component will load the Boston Housing dataset from sklearn.datasets and then split the dataset into training and test sets." }, { "code": null, "e": 4612, "s": 4484, "text": "train-model: this component will train a model to predict the median value of homes in Boston using the Boston Housing dataset." }, { "code": null, "e": 4719, "s": 4612, "text": "test-model: this component will compute and output the mean squared error of the model on the test dataset" }, { "code": null, "e": 5001, "s": 4719, "text": "deploy-model: we won’t be focusing on model deployment or serving in this article, so this component will just log a message saying that it’s deploying the model. In a real-world scenario, this could be a generic component for deploying any model to a QA or Production environment." }, { "code": null, "e": 5147, "s": 5001, "text": "If all this talk of components and Docker images sounds confusing: don’t worry, it should all start to make more sense when we get into the code." }, { "code": null, "e": 5444, "s": 5147, "text": "The first component in our pipeline will use sklearn.datasets to load in the Boston Housing dataset. We’ll split this dataset into train and test sets using Sci-kit learn’s train_test_split function, then we’ll use np.save to save our dataset to disk so that it can be reused by later components." }, { "code": null, "e": 5597, "s": 5444, "text": "So far this is just a simple Python script. Now we need to create a Docker image that executes this script. We’ll write a Dockerfile to build the image:" }, { "code": null, "e": 5910, "s": 5597, "text": "Starting from the python:3.7-slim base image, we’ll install the necessary packages using pip , copy the preprocess Python script from our local machine to the container, and then specify the preprocess.py script as the container entrypoint, which means that when the container starts, it will execute our script." }, { "code": null, "e": 6170, "s": 5910, "text": "Now we’ll get started on the pipeline. First, you’ll need to make sure that the Docker image that we defined above is accessible from your Kubernetes cluster. For the purpose of this example, I used GitHub Actions to build the image and push it to Docker Hub." }, { "code": null, "e": 6417, "s": 6170, "text": "Now let’s define a component. Each component is defined as a function that returns an object of type ContainerOp . This type comes from the kfp SDK that we installed earlier. Here is a component definition for the first component in our pipeline:" }, { "code": null, "e": 6674, "s": 6417, "text": "Notice that for the image argument, we’re passing the name of the Docker image defined by the Dockerfile above, and for the file_outputs argument, we’re specifying the file paths of the four .npy files that are saved to disk by our component Python script." }, { "code": null, "e": 6783, "s": 6674, "text": "By specifying these four files as File Outputs, we make them available for other components in the pipeline." }, { "code": null, "e": 7391, "s": 6783, "text": "Note: It’s not a very good practice to hard-code file paths in our components, because, as you can see from the code above, this requires that the person creating the component definition knows specific details about the component implementation (that is, the implementation contained in the Docker image). It would be much cleaner to have our component accept the file paths as command-line arguments. This way the person defining the component has full control over where to expect the output files. I’ve left it hard-coded this way to hopefully make it easier to see how all of these pieces fit together." }, { "code": null, "e": 7491, "s": 7391, "text": "With our first component defined, we can create a pipeline that uses the preprocess-data component." }, { "code": null, "e": 7661, "s": 7491, "text": "The pipeline definition is a Python function decorated with the @dsl.pipeline annotation. Within the function, we can use the component like we would any other function." }, { "code": null, "e": 7822, "s": 7661, "text": "To execute the pipeline, we create a kfp.Client object and invoke the create_run_from_pipeline_func function, passing in the function that defines our pipeline." }, { "code": null, "e": 8125, "s": 7822, "text": "If we execute this script, then navigate to the Experiments view in the Pipelines section of the Kubeflow central dashboard, we’ll see the execution of our pipeline. We can also see the four file outputs from the preprocess-data component by clicking on the component in the graph view of the pipeline." }, { "code": null, "e": 8283, "s": 8125, "text": "So we can execute our pipeline and visualize it in the GUI, but a pipeline with a single step isn’t all that exciting. Let’s create the remaining components." }, { "code": null, "e": 8606, "s": 8283, "text": "For the train-model component, we’ll create a simple python script that trains a regression model using Sci-kit learn. This should look similar to the python script for the preprocessor component. The big difference is that here we’re using argparse to accept the file paths to the training data as command-line arguments." }, { "code": null, "e": 8822, "s": 8606, "text": "The Dockerfile, likewise, is very similar to the one we used for the first component. We start with the base image, install the necessary packages, copy the python script into the container, then execute the script." }, { "code": null, "e": 9174, "s": 8822, "text": "The two other components, test-model and deploy-model, follow this same pattern. In fact, they’re so similar to the two components we’ve already implemented, that for the sake of brevity I won’t show them here. If you’re interested, you can find all of the code for the pipeline in this GitHub repository: https://github.com/gnovack/kubeflow-pipelines" }, { "code": null, "e": 9318, "s": 9174, "text": "Just like with the preprocess-data component from earlier, we’ll build Docker images out of these three components and push them to Docker Hub:" }, { "code": null, "e": 9361, "s": 9318, "text": "train-model: gnovack/boston_pipeline_train" }, { "code": null, "e": 9402, "s": 9361, "text": "test-model: gnovack/boston_pipeline_test" }, { "code": null, "e": 9447, "s": 9402, "text": "deploy-model: gnovack/boston_pipeline_deploy" }, { "code": null, "e": 9507, "s": 9447, "text": "Now it’s time to create the full machine learning pipeline." }, { "code": null, "e": 9611, "s": 9507, "text": "First, we’ll create component definitions for the train-model, test-model, and deploy-model components." }, { "code": null, "e": 9954, "s": 9611, "text": "The only major difference between the definition of the train-model component and that of the preprocess-data component from earlier is that train-model accepts two arguments, x_train and y_train which will be passed to the container as command-line arguments, and will be parsed out in the component implementation using the argparse module." }, { "code": null, "e": 10022, "s": 9954, "text": "Now the definitions for the test-model and deploy-model components:" }, { "code": null, "e": 10165, "s": 10022, "text": "With the four pipeline components defined, we’ll now revisit the boston_pipeline function from earlier and use all of our components together." }, { "code": null, "e": 10188, "s": 10165, "text": "Let’s break this down:" }, { "code": null, "e": 10432, "s": 10188, "text": "Notice on line 6, when we invoke the preprocess_op() function, we store the output of the function in a variable called _preprocess_op . To access the outputs of the preprocess-data component, we call _preprocess_op.outputs['NAME_OF_OUTPUT'] ." }, { "code": null, "e": 10794, "s": 10432, "text": "By default, when we access the file_outputs from a component, we get the contents of the file rather than the file path. In our case, since these aren’t plain text files, we can’t just pass the file contents into the component Docker containers as command-line arguments. To access the file path, we use dsl.InputArgumentPath() and pass in the component output." }, { "code": null, "e": 10970, "s": 10794, "text": "Now if we create a run from the pipeline and navigate to the Pipelines UI in the Kubeflow central dashboard, we should see all four components displayed in the pipeline graph." }, { "code": null, "e": 11319, "s": 10970, "text": "In this article, we created a very simple machine learning pipeline that loads in some data, trains a model, evaluates it on a holdout dataset, and then “deploys” it. By using Kubeflow Pipelines, we were able to encapsulate each step in this workflow into Pipeline Components that each run in their very own, isolated Docker container environments." }, { "code": null, "e": 11693, "s": 11319, "text": "This encapsulation promotes loose coupling between the steps in our machine learning workflow and opens up the possibility of reusing components in future pipelines. For example, there wasn’t anything in our training component specific to the Boston Housing dataset. We might be able to reuse this component any time we want to train a regression model using Sci-kit learn." }, { "code": null, "e": 11909, "s": 11693, "text": "We just scratched the surface of what’s possible with Kubeflow Pipelines, but hopefully, this article helped you understand the basics of components, and how we can use them together to create and execute pipelines." }, { "code": null, "e": 12071, "s": 11909, "text": "If you’re interested in exploring the whole codebase used in this article, you can find it all in this GitHub repo: https://github.com/gnovack/kubeflow-pipelines" }, { "code": null, "e": 12082, "s": 12071, "text": "References" }, { "code": null, "e": 12145, "s": 12082, "text": "https://kubeflow-pipelines.readthedocs.io/en/latest/index.html" }, { "code": null, "e": 12206, "s": 12145, "text": "https://www.kubeflow.org/docs/pipelines/sdk/build-component/" }, { "code": null, "e": 12278, "s": 12206, "text": "MLOps: Continuous delivery and automation pipelines in machine learning" } ]
Ruby - XML, XSLT and XPath Tutorial
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone. There are two different flavors available for XML parsers − SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory. SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory. DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files. SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects. The most common way to manipulate XML is with the REXML library by Sean Russell. Since 2002, REXML has been part of the standard Ruby distribution. REXML is a pure-Ruby XML processor conforming to the XML 1.0 standard. It is a non-validating processor, passing all of the OASIS non-validating conformance tests. REXML parser has the following advantages over other available parsers − It is written 100 percent in Ruby. It can be used for both SAX and DOM parsing. It is lightweight, less than 2000 lines of code. Methods and classes are really easy-to-understand. SAX2-based API and Full XPath support. Shipped with Ruby installation and no separate installation is required. For all our XML code examples, let's use a simple XML file as an input − <collection shelf = "New Arrivals"> <movie title = "Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = "Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = "Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title = "Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> Let's first parse our XML data in tree fashion. We begin by requiring the rexml/document library; often we do an include REXML to import into the top-level namespace for convenience. #!/usr/bin/ruby -w require 'rexml/document' include REXML xmlfile = File.new("movies.xml") xmldoc = Document.new(xmlfile) # Now get the root element root = xmldoc.root puts "Root element : " + root.attributes["shelf"] # This will output all the movie titles. xmldoc.elements.each("collection/movie"){ |e| puts "Movie Title : " + e.attributes["title"] } # This will output all the movie types. xmldoc.elements.each("collection/movie/type") { |e| puts "Movie Type : " + e.text } # This will output all the movie description. xmldoc.elements.each("collection/movie/description") { |e| puts "Movie Description : " + e.text } This will produce the following result − Root element : New Arrivals Movie Title : Enemy Behind Movie Title : Transformers Movie Title : Trigun Movie Title : Ishtar Movie Type : War, Thriller Movie Type : Anime, Science Fiction Movie Type : Anime, Action Movie Type : Comedy Movie Description : Talk about a US-Japan war Movie Description : A schientific fiction Movie Description : Vash the Stampede! Movie Description : Viewable boredom To process the same data, movies.xml, file in a stream-oriented way we will define a listener class whose methods will be the target of callbacks from the parser. NOTE − It is not suggested to use SAX-like parsing for a small file, this is just for a demo example. #!/usr/bin/ruby -w require 'rexml/document' require 'rexml/streamlistener' include REXML class MyListener include REXML::StreamListener def tag_start(*args) puts "tag_start: #{args.map {|x| x.inspect}.join(', ')}" end def text(data) return if data =~ /^\w*$/ # whitespace only abbrev = data[0..40] + (data.length > 40 ? "..." : "") puts " text : #{abbrev.inspect}" end end list = MyListener.new xmlfile = File.new("movies.xml") Document.parse_stream(xmlfile, list) This will produce the following result − tag_start: "collection", {"shelf"=>"New Arrivals"} tag_start: "movie", {"title"=>"Enemy Behind"} tag_start: "type", {} text : "War, Thriller" tag_start: "format", {} tag_start: "year", {} tag_start: "rating", {} tag_start: "stars", {} tag_start: "description", {} text : "Talk about a US-Japan war" tag_start: "movie", {"title"=>"Transformers"} tag_start: "type", {} text : "Anime, Science Fiction" tag_start: "format", {} tag_start: "year", {} tag_start: "rating", {} tag_start: "stars", {} tag_start: "description", {} text : "A schientific fiction" tag_start: "movie", {"title"=>"Trigun"} tag_start: "type", {} text : "Anime, Action" tag_start: "format", {} tag_start: "episodes", {} tag_start: "rating", {} tag_start: "stars", {} tag_start: "description", {} text : "Vash the Stampede!" tag_start: "movie", {"title"=>"Ishtar"} tag_start: "type", {} tag_start: "format", {} tag_start: "rating", {} tag_start: "stars", {} tag_start: "description", {} text : "Viewable boredom" An alternative way to view XML is XPath. This is a kind of pseudo-language that describes how to locate specific elements and attributes in an XML document, treating that document as a logical ordered tree. REXML has XPath support via the XPath class. It assumes tree-based parsing (document object model) as we have seen above. #!/usr/bin/ruby -w require 'rexml/document' include REXML xmlfile = File.new("movies.xml") xmldoc = Document.new(xmlfile) # Info for the first movie found movie = XPath.first(xmldoc, "//movie") p movie # Print out all the movie types XPath.each(xmldoc, "//type") { |e| puts e.text } # Get an array of all of the movie formats. names = XPath.match(xmldoc, "//format").map {|x| x.text } p names This will produce the following result − <movie title = 'Enemy Behind'> ... </> War, Thriller Anime, Science Fiction Anime, Action Comedy ["DVD", "DVD", "DVD", "VHS"] There are two XSLT parsers available that Ruby can use. A brief description of each is given here. This parser is written and maintained by Masayoshi Takahashi. This is written primarily for Linux OS and requires the following libraries − Sablot Iconv Expat You can find this module at Ruby-Sablotron. XSLT4R is written by Michael Neumann and can be found at the RAA in the Library section under XML. XSLT4R uses a simple commandline interface, though it can alternatively be used within a third-party application to transform an XML document. XSLT4R needs XMLScan to operate, which is included within the XSLT4R archive and which is also a 100 percent Ruby module. These modules can be installed using standard Ruby installation method (i.e., ruby install.rb). XSLT4R has the following syntax − ruby xslt.rb stylesheet.xsl document.xml [arguments] If you want to use XSLT4R from within an application, you can include XSLT and input the parameters you need. Here is the example − require "xslt" stylesheet = File.readlines("stylesheet.xsl").to_s xml_doc = File.readlines("document.xml").to_s arguments = { 'image_dir' => '/....' } sheet = XSLT::Stylesheet.new( stylesheet, arguments ) # output to StdOut sheet.apply( xml_doc ) # output to 'str' str = "" sheet.output = [ str ] sheet.apply( xml_doc ) For a complete detail on REXML Parser, please refer to standard documentation for REXML Parser Documentation. For a complete detail on REXML Parser, please refer to standard documentation for REXML Parser Documentation. You can download XSLT4R from RAA Repository. You can download XSLT4R from RAA Repository. 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2464, "s": 2294, "text": "The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard." }, { "code": null, "e": 2654, "s": 2464, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language." }, { "code": null, "e": 2771, "s": 2654, "text": "XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone." }, { "code": null, "e": 2831, "s": 2771, "text": "There are two different flavors available for XML parsers −" }, { "code": null, "e": 3136, "s": 2831, "text": "SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory." }, { "code": null, "e": 3441, "s": 3136, "text": "SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory." }, { "code": null, "e": 3667, "s": 3441, "text": "DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document." }, { "code": null, "e": 3893, "s": 3667, "text": "DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document." }, { "code": null, "e": 4100, "s": 3893, "text": "SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files." }, { "code": null, "e": 4290, "s": 4100, "text": "SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects." }, { "code": null, "e": 4438, "s": 4290, "text": "The most common way to manipulate XML is with the REXML library by Sean Russell. Since 2002, REXML has been part of the standard Ruby distribution." }, { "code": null, "e": 4602, "s": 4438, "text": "REXML is a pure-Ruby XML processor conforming to the XML 1.0 standard. It is a non-validating processor, passing all of the OASIS non-validating conformance tests." }, { "code": null, "e": 4675, "s": 4602, "text": "REXML parser has the following advantages over other available parsers −" }, { "code": null, "e": 4710, "s": 4675, "text": "It is written 100 percent in Ruby." }, { "code": null, "e": 4755, "s": 4710, "text": "It can be used for both SAX and DOM parsing." }, { "code": null, "e": 4804, "s": 4755, "text": "It is lightweight, less than 2000 lines of code." }, { "code": null, "e": 4855, "s": 4804, "text": "Methods and classes are really easy-to-understand." }, { "code": null, "e": 4894, "s": 4855, "text": "SAX2-based API and Full XPath support." }, { "code": null, "e": 4967, "s": 4894, "text": "Shipped with Ruby installation and no separate installation is required." }, { "code": null, "e": 5040, "s": 4967, "text": "For all our XML code examples, let's use a simple XML file as an input −" }, { "code": null, "e": 5994, "s": 5040, "text": "<collection shelf = \"New Arrivals\">\n <movie title = \"Enemy Behind\">\n <type>War, Thriller</type>\n <format>DVD</format>\n <year>2003</year>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Talk about a US-Japan war</description>\n </movie>\n <movie title = \"Transformers\">\n <type>Anime, Science Fiction</type>\n <format>DVD</format>\n <year>1989</year>\n <rating>R</rating>\n <stars>8</stars>\n <description>A schientific fiction</description>\n </movie>\n <movie title = \"Trigun\">\n <type>Anime, Action</type>\n <format>DVD</format>\n <episodes>4</episodes>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Vash the Stampede!</description>\n </movie>\n <movie title = \"Ishtar\">\n <type>Comedy</type>\n <format>VHS</format>\n <rating>PG</rating>\n <stars>2</stars>\n <description>Viewable boredom</description>\n </movie>\n</collection>" }, { "code": null, "e": 6177, "s": 5994, "text": "Let's first parse our XML data in tree fashion. We begin by requiring the rexml/document library; often we do an include REXML to import into the top-level namespace for convenience." }, { "code": null, "e": 6817, "s": 6177, "text": "#!/usr/bin/ruby -w\n\nrequire 'rexml/document'\ninclude REXML\n\nxmlfile = File.new(\"movies.xml\")\nxmldoc = Document.new(xmlfile)\n\n# Now get the root element\nroot = xmldoc.root\nputs \"Root element : \" + root.attributes[\"shelf\"]\n\n# This will output all the movie titles.\nxmldoc.elements.each(\"collection/movie\"){ \n |e| puts \"Movie Title : \" + e.attributes[\"title\"] \n}\n\n# This will output all the movie types.\nxmldoc.elements.each(\"collection/movie/type\") {\n |e| puts \"Movie Type : \" + e.text \n}\n\n# This will output all the movie description.\nxmldoc.elements.each(\"collection/movie/description\") {\n |e| puts \"Movie Description : \" + e.text \n}" }, { "code": null, "e": 6858, "s": 6817, "text": "This will produce the following result −" }, { "code": null, "e": 7257, "s": 6858, "text": "Root element : New Arrivals\nMovie Title : Enemy Behind\nMovie Title : Transformers\nMovie Title : Trigun\nMovie Title : Ishtar\nMovie Type : War, Thriller\nMovie Type : Anime, Science Fiction\nMovie Type : Anime, Action\nMovie Type : Comedy\nMovie Description : Talk about a US-Japan war\nMovie Description : A schientific fiction\nMovie Description : Vash the Stampede!\nMovie Description : Viewable boredom\n" }, { "code": null, "e": 7420, "s": 7257, "text": "To process the same data, movies.xml, file in a stream-oriented way we will define a listener class whose methods will be the target of callbacks from the parser." }, { "code": null, "e": 7522, "s": 7420, "text": "NOTE − It is not suggested to use SAX-like parsing for a small file, this is just for a demo example." }, { "code": null, "e": 8039, "s": 7522, "text": "#!/usr/bin/ruby -w\n\nrequire 'rexml/document'\nrequire 'rexml/streamlistener'\ninclude REXML\n\nclass MyListener\n include REXML::StreamListener\n def tag_start(*args)\n puts \"tag_start: #{args.map {|x| x.inspect}.join(', ')}\"\n end\n\n def text(data)\n return if data =~ /^\\w*$/ # whitespace only\n abbrev = data[0..40] + (data.length > 40 ? \"...\" : \"\")\n puts \" text : #{abbrev.inspect}\"\n end\nend\n\nlist = MyListener.new\nxmlfile = File.new(\"movies.xml\")\nDocument.parse_stream(xmlfile, list)" }, { "code": null, "e": 8080, "s": 8039, "text": "This will produce the following result −" }, { "code": null, "e": 9109, "s": 8080, "text": "tag_start: \"collection\", {\"shelf\"=>\"New Arrivals\"}\ntag_start: \"movie\", {\"title\"=>\"Enemy Behind\"}\ntag_start: \"type\", {}\n text : \"War, Thriller\"\ntag_start: \"format\", {}\ntag_start: \"year\", {}\ntag_start: \"rating\", {}\ntag_start: \"stars\", {}\ntag_start: \"description\", {}\n text : \"Talk about a US-Japan war\"\ntag_start: \"movie\", {\"title\"=>\"Transformers\"}\ntag_start: \"type\", {}\n text : \"Anime, Science Fiction\"\ntag_start: \"format\", {}\ntag_start: \"year\", {}\ntag_start: \"rating\", {}\ntag_start: \"stars\", {}\ntag_start: \"description\", {}\n text : \"A schientific fiction\"\ntag_start: \"movie\", {\"title\"=>\"Trigun\"}\ntag_start: \"type\", {}\n text : \"Anime, Action\"\ntag_start: \"format\", {}\ntag_start: \"episodes\", {}\ntag_start: \"rating\", {}\ntag_start: \"stars\", {}\ntag_start: \"description\", {}\n text : \"Vash the Stampede!\"\ntag_start: \"movie\", {\"title\"=>\"Ishtar\"}\ntag_start: \"type\", {}\ntag_start: \"format\", {}\ntag_start: \"rating\", {}\ntag_start: \"stars\", {}\ntag_start: \"description\", {}\n text : \"Viewable boredom\"\n" }, { "code": null, "e": 9316, "s": 9109, "text": "An alternative way to view XML is XPath. This is a kind of pseudo-language that describes how to locate specific elements and attributes in an XML document, treating that document as a logical ordered tree." }, { "code": null, "e": 9438, "s": 9316, "text": "REXML has XPath support via the XPath class. It assumes tree-based parsing (document object model) as we have seen above." }, { "code": null, "e": 9836, "s": 9438, "text": "#!/usr/bin/ruby -w\n\nrequire 'rexml/document'\ninclude REXML\n\nxmlfile = File.new(\"movies.xml\")\nxmldoc = Document.new(xmlfile)\n\n# Info for the first movie found\nmovie = XPath.first(xmldoc, \"//movie\")\np movie\n\n# Print out all the movie types\nXPath.each(xmldoc, \"//type\") { |e| puts e.text }\n\n# Get an array of all of the movie formats.\nnames = XPath.match(xmldoc, \"//format\").map {|x| x.text }\np names" }, { "code": null, "e": 9877, "s": 9836, "text": "This will produce the following result −" }, { "code": null, "e": 10004, "s": 9877, "text": "<movie title = 'Enemy Behind'> ... </>\nWar, Thriller\nAnime, Science Fiction\nAnime, Action\nComedy\n[\"DVD\", \"DVD\", \"DVD\", \"VHS\"]\n" }, { "code": null, "e": 10103, "s": 10004, "text": "There are two XSLT parsers available that Ruby can use. A brief description of each is given here." }, { "code": null, "e": 10243, "s": 10103, "text": "This parser is written and maintained by Masayoshi Takahashi. This is written primarily for Linux OS and requires the following libraries −" }, { "code": null, "e": 10250, "s": 10243, "text": "Sablot" }, { "code": null, "e": 10256, "s": 10250, "text": "Iconv" }, { "code": null, "e": 10262, "s": 10256, "text": "Expat" }, { "code": null, "e": 10306, "s": 10262, "text": "You can find this module at Ruby-Sablotron." }, { "code": null, "e": 10548, "s": 10306, "text": "XSLT4R is written by Michael Neumann and can be found at the RAA in the Library section under XML. XSLT4R uses a simple commandline interface, though it can alternatively be used within a third-party application to transform an XML document." }, { "code": null, "e": 10766, "s": 10548, "text": "XSLT4R needs XMLScan to operate, which is included within the XSLT4R archive and which is also a 100 percent Ruby module. These modules can be installed using standard Ruby installation method (i.e., ruby install.rb)." }, { "code": null, "e": 10800, "s": 10766, "text": "XSLT4R has the following syntax −" }, { "code": null, "e": 10854, "s": 10800, "text": "ruby xslt.rb stylesheet.xsl document.xml [arguments]\n" }, { "code": null, "e": 10986, "s": 10854, "text": "If you want to use XSLT4R from within an application, you can include XSLT and input the parameters you need. Here is the example −" }, { "code": null, "e": 11309, "s": 10986, "text": "require \"xslt\"\n\nstylesheet = File.readlines(\"stylesheet.xsl\").to_s\nxml_doc = File.readlines(\"document.xml\").to_s\narguments = { 'image_dir' => '/....' }\nsheet = XSLT::Stylesheet.new( stylesheet, arguments )\n\n# output to StdOut\nsheet.apply( xml_doc )\n\n# output to 'str'\nstr = \"\"\nsheet.output = [ str ]\nsheet.apply( xml_doc )" }, { "code": null, "e": 11419, "s": 11309, "text": "For a complete detail on REXML Parser, please refer to standard documentation for REXML Parser Documentation." }, { "code": null, "e": 11529, "s": 11419, "text": "For a complete detail on REXML Parser, please refer to standard documentation for REXML Parser Documentation." }, { "code": null, "e": 11574, "s": 11529, "text": "You can download XSLT4R from RAA Repository." }, { "code": null, "e": 11619, "s": 11574, "text": "You can download XSLT4R from RAA Repository." }, { "code": null, "e": 11654, "s": 11619, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 11682, "s": 11654, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11717, "s": 11682, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11737, "s": 11717, "text": " Skillbakerystudios" }, { "code": null, "e": 11772, "s": 11737, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 11782, "s": 11772, "text": " YouAccel" }, { "code": null, "e": 11816, "s": 11782, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 11834, "s": 11816, "text": " Programming Line" }, { "code": null, "e": 11867, "s": 11834, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 11890, "s": 11867, "text": " Stone River ELearning" }, { "code": null, "e": 11925, "s": 11890, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11948, "s": 11925, "text": " Stone River ELearning" }, { "code": null, "e": 11955, "s": 11948, "text": " Print" }, { "code": null, "e": 11966, "s": 11955, "text": " Add Notes" } ]
How do you convert a list collection into an array in C#?
Firstly, set a list collection − List < string > myList = new List < string > (); myList.Add("RedHat"); myList.Add("Ubuntu"); Now, use ToArray() to convert the list to an array − string[] str = myList.ToArray(); The following is the complete code − Live Demo using System; using System.Collections.Generic; public class Program { public static void Main() { List < string > myList = new List < string > (); myList.Add("RedHat"); myList.Add("Ubuntu"); Console.WriteLine("List..."); foreach(string value in myList) { Console.WriteLine(value); } Console.WriteLine("Converting to Array..."); string[] str = myList.ToArray(); foreach(string s in myList) { Console.WriteLine(s); } } } List... RedHat Ubuntu Converting to Array... RedHat Ubuntu
[ { "code": null, "e": 1095, "s": 1062, "text": "Firstly, set a list collection −" }, { "code": null, "e": 1188, "s": 1095, "text": "List < string > myList = new List < string > ();\nmyList.Add(\"RedHat\");\nmyList.Add(\"Ubuntu\");" }, { "code": null, "e": 1241, "s": 1188, "text": "Now, use ToArray() to convert the list to an array −" }, { "code": null, "e": 1274, "s": 1241, "text": "string[] str = myList.ToArray();" }, { "code": null, "e": 1311, "s": 1274, "text": "The following is the complete code −" }, { "code": null, "e": 1322, "s": 1311, "text": " Live Demo" }, { "code": null, "e": 1831, "s": 1322, "text": "using System;\nusing System.Collections.Generic;\n\npublic class Program {\n public static void Main() {\n\n List < string > myList = new List < string > ();\n myList.Add(\"RedHat\");\n myList.Add(\"Ubuntu\");\n\n Console.WriteLine(\"List...\");\n foreach(string value in myList) {\n Console.WriteLine(value);\n }\n\n Console.WriteLine(\"Converting to Array...\");\n string[] str = myList.ToArray();\n\n foreach(string s in myList) {\n Console.WriteLine(s);\n }\n }\n}" }, { "code": null, "e": 1890, "s": 1831, "text": "List...\nRedHat\nUbuntu\nConverting to Array...\nRedHat\nUbuntu" } ]
Kubernetes - Replica Sets
Replica Set ensures how many replica of pod should be running. It can be considered as a replacement of replication controller. The key difference between the replica set and the replication controller is, the replication controller only supports equality-based selector whereas the replica set supports set-based selector. apiVersion: extensions/v1beta1 --------------------->1 kind: ReplicaSet --------------------------> 2 metadata: name: Tomcat-ReplicaSet spec: replicas: 3 selector: matchLables: tier: Backend ------------------> 3 matchExpression: { key: tier, operation: In, values: [Backend]} --------------> 4 template: metadata: lables: app: Tomcat-ReplicaSet tier: Backend labels: app: App component: neo4j spec: containers: - name: Tomcat image: tomcat: 8.0 ports: - containerPort: 7474 apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set. apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set. kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set. kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set. tier: Backend → We have defined the label tier as backend which creates a matching selector. tier: Backend → We have defined the label tier as backend which creates a matching selector. {key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details. {key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details. Run the above file using kubectl and create the backend replica set with the provided definition in the yaml file. 41 Lectures 5 hours AR Shankar 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Nigel Poulton 25 Lectures 1.5 hours Pranjal Srivastava 18 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2519, "s": 2195, "text": "Replica Set ensures how many replica of pod should be running. It can be considered as a replacement of replication controller. The key difference between the replica set and the replication controller is, the replication controller only supports equality-based selector whereas the replica set supports set-based selector." }, { "code": null, "e": 3109, "s": 2519, "text": "apiVersion: extensions/v1beta1 --------------------->1\nkind: ReplicaSet --------------------------> 2\nmetadata:\n name: Tomcat-ReplicaSet\nspec:\n replicas: 3\n selector:\n matchLables:\n tier: Backend ------------------> 3\n matchExpression:\n{ key: tier, operation: In, values: [Backend]} --------------> 4\ntemplate:\n metadata:\n lables:\n app: Tomcat-ReplicaSet\n tier: Backend\n labels:\n app: App\n component: neo4j\n spec:\n containers:\n - name: Tomcat\n image: tomcat: 8.0\n ports:\n - containerPort: 7474\n" }, { "code": null, "e": 3263, "s": 3109, "text": "apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set." }, { "code": null, "e": 3417, "s": 3263, "text": "apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set." }, { "code": null, "e": 3561, "s": 3417, "text": "kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set." }, { "code": null, "e": 3705, "s": 3561, "text": "kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set." }, { "code": null, "e": 3798, "s": 3705, "text": "tier: Backend → We have defined the label tier as backend which creates a matching selector." }, { "code": null, "e": 3891, "s": 3798, "text": "tier: Backend → We have defined the label tier as backend which creates a matching selector." }, { "code": null, "e": 4089, "s": 3891, "text": "{key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details." }, { "code": null, "e": 4287, "s": 4089, "text": "{key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details." }, { "code": null, "e": 4402, "s": 4287, "text": "Run the above file using kubectl and create the backend replica set with the provided definition in the yaml file." }, { "code": null, "e": 4435, "s": 4402, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 4447, "s": 4435, "text": " AR Shankar" }, { "code": null, "e": 4480, "s": 4447, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 4520, "s": 4480, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 4555, "s": 4520, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4570, "s": 4555, "text": " Nigel Poulton" }, { "code": null, "e": 4605, "s": 4570, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4625, "s": 4605, "text": " Pranjal Srivastava" }, { "code": null, "e": 4658, "s": 4625, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 4678, "s": 4658, "text": " Pranjal Srivastava" }, { "code": null, "e": 4713, "s": 4678, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4733, "s": 4713, "text": " Pranjal Srivastava" }, { "code": null, "e": 4740, "s": 4733, "text": " Print" }, { "code": null, "e": 4751, "s": 4740, "text": " Add Notes" } ]
LSTM to Predict Stock Prices — Time-Series Data | by Sarit Maitra | Towards Data Science
PREDICTION of financial series is always a complex task and has attracted major attention from academics, investment companies, banks etc. Price prediction are typically evaluated on the basis of statistical criteria, such as mean error, mean absolute error (MAE), or root mean squared error (RMSE). We have already seen the relationships among multiple time series (Gold prices, Silver prices, Crude Oil prices, Stock index , Interest Rate and USD rate) and how they influence each other. Let’s use the same data set and try to solve our prediction problem with Recurrent Neural network (RNN) algorithm. Neural networks are well known for their efficiency with multiple input variables. Let’s load the data which is already processed earlier; if there is any data error, hopefully our model will learn to ignore. Let’s understand the mathematical intuition of feed-forward network. where, x1, x2....xk are input series, ŷ is output series and in between a bunch of hidden layers. However, here the issues are- information does not account for time ordering inputs are processed independently no mechanism to keep the past information “Feed-Forward network architecture does not have a memory built-in. Moreover, it appears a situation where a deep multilayer feed-forward network is unable to propagate useful gradient information from the output end of the model back to the layers near the input end of the model” To overcome these difficulties, RNN was introduced which comes with a network architecture that can- retain the past information track the state of the world update the state of the world as the network moves faster “RNN handles variable-length sequence by having a recurrent hidden state whose activation at each time is dependent on that of the previous time” Below diagram and equations give a clear idea about how RNN works — where, xt represents inputs, ht expresses the hidden layers from input to output, yt is output. On the top of that, it has a recurrent loop which loop back to the past to express that, the output is not only a function of new input but also a function of past hidden layer and that way the network keeps growing. However, it has a problem of exploding and vanishing gradient. Recurrent Neural Networks (LSTM) addresses this issue. They are networks with loops in them, allowing information to persist. The most important concept for LSTM is the state of the cell, and this information is transmitted to each other between cells with yt data embedded on the top of the cell. In the above diagram, a chunk of neural network, A, looks at some input xt and outputs a value ht. A loop allows information to be passed from one step of the network to the next. These loops make recurrent neural networks kind of mysterious object. However, they aren’t all that different than a normal Neural Network. A Recurrent Neural Network is the multiple copies of the same network, each passing a message to a successor. The cell state works like a conveyor belt and is carried through the entire chain. Cells may make small changes to this information. There are gates inside the cells. These gates contain a sigmoid function and open and close the sigmoid function according to the output value. Then the gate output value and yt value are subjected to multiplication. The sigmoid function outputs can take values between 0 and 1, while a value of zero closes the information transition and moves a value across the entire information. If the loop is unrolled as shown in below diagram- This chain-like nature reveals that recurrent neural networks are intimately related to sequences and lists. They’re the natural architecture of neural network to use for such data. Let’s consider the hidden state ht at time step t. The first thing the LSTM cell needs to decide is to report the cell status. This decision is made by the forget gate layer. The forget gate layer generates a value between 0 and 1 for each yt−1 by looking at ht−1 and xt. 1 means that data is stored and 0 means that it will be forgotten. The mathematical expression of the process performed by forget gate layer : The next step is about whether to record the new information in the cell state. Input gate layer decides which value to update. The input gate layer and the output of the input gate layer can be formulated as : A non-linear function layer (tanh) which generates a vector of new candidate values, ŷt which could be added to the state. The old cell state is then updated and the yt value representing the new cell state is determined. The below equation can be written for obtaining the new yt value. Finally, to ensure that the output value is between -1 and 1 and filter the output, the output functions can be specified as : LSTM suffers from vanishing gradients as well, but not as much as the basic RNN. The difference is for the basic RNN, the gradient decays with wσ′(⋅) while for the LSTM the gradient decays with σ(⋅). For the LSTM, there’s is a set of weights which can be learned such that σ(⋅)≈1. Assuming vt + k = wx for some weight w and input x, then Neural Network can learn a large w to prevent gradients from vanishing. For the basic RNN, there is no set of weights which can be learned such that : The LSTM model in Keras assumes that the data is divided into input (x) and output (y) components. This can be achieve this by using the observation from the last time step (t-1) as the input and the observation at the current time step (t) as the output in a time series. Let’s add a “pred” column as our output and shift it. Scaling and normalizing is an important activity in the formation of Neural Network Architecture. If we check the data, it has a wide range of values (1.336, 13592.79) and neural network do not perform well in this kind of range. We have defined a function to specify the look back interval (60 time steps) and the predicted column as below. Here, I have split the data in 80/20 ratio. Moreover, we need to reshape the data to 3D array for LSTM to read and train the model. We can see the training set contains 4103 data points and testing set has 966 data points. Now, we add the LSTM layers and few Dropout layers to prevent overfitting. I have added 3 extra layers in the network. The following arguments are considered for the network architecture: 50 units which is the dimensionality of the output space, return_sequences = True, which determines whether to return the last output in the output sequence, or the full sequence, input_shape as the shape of the training set, The Dropout layers specified as 0.2, i.e. 20% of the layers will be dropped, Thereafter, I have added the Dense layer that specifies the output of 1 unit, Next, the model was fit to run on 100 epochs with a batch size of 32. Instead of training the RNN on the complete sequences of observations, we have used a batch of shorter sub-sequences (32) picked at random from the training-data. model_lstm = tf.keras.Sequential()model_lstm.add(tf.keras.layers.LSTM(75, return_sequence = True, input_shape = (xtrain.shape[1], xtrain.shape[2])))model_lstm.add(tf.keras.layers.LSTM(units=30, return_sequence=True))model_lstm.add(tf.keras.layers.LSTM(units=30))model_lstm.add(tf.keras.layers.Dense(units=1))model_lstm.Compile(loss = 'mae', optimizer = 'adam')model_lstm.summary()history_lstm = model_lstm.fit(xtrain, ytrain, epochs = 15, batch_size=32, validation_data = (xtest, ytest), shuffle=False) A line plot of model accuracy on the train and test sets is created, showing the change in performance over all 15 training epochs. The line plot below of the test data (blue) vs the predicted values (orange) providing the context for the model skill. The model is fit to the training data; therefore, it can be used to make forecasts. Now, used the trained model to predict the “pred” values in test dataset. I have used fixed approach here for prediction. Fixed approach : We can decide to fit the model once on all of the training data, then predict each new time step one at a time from the test data Dynamic approach: We can re-fit the model or update the model each time step of the test data as new observations from the test data are made available. We must invert the scale on forecasts to return the values back to the original scale so that the results can be interpreted and a comparable error score can be calculated. Now we can see, we are not quite there yet. The result is not that impressive. We can check the difference between these two and compare the results in various ways & optimize the model before we build the trading strategy. Let’s see if we can improve the model performance by shifting 10 time steps and doing some hyper parameter adjustments. Here the line plot visually looks better than the previous two on both training and testing set. The model appears to rapidly learn the problem, converging on a solution in about 20 epochs. The loss metrics e.g. RMSE, MAE can be obtained similar way as shown earlier. Though there is some improvement, but in terms of prediction, we still have rooms for improvement. An important factor here is that, we have used daily prices in this model so the data points are really less only 5,129 data points for Neural Network Architecture. I would recommend to use more than 100,000 data points using minute or tick data for training the model while building ANN or any other Deep Learning model to be most effective. Six different time series were used in order to measure the performance of the network fairly. We have found these series are causing each other by using Granger’s Causality. The estimation results obtained are compared with the graphs. RMSE and R values were examined as predictive success criteria. However, it is possible to achieve more successful results with more data points and by changing the hyper parameters of the LSTM network. I can be reached here.
[ { "code": null, "e": 662, "s": 172, "text": "PREDICTION of financial series is always a complex task and has attracted major attention from academics, investment companies, banks etc. Price prediction are typically evaluated on the basis of statistical criteria, such as mean error, mean absolute error (MAE), or root mean squared error (RMSE). We have already seen the relationships among multiple time series (Gold prices, Silver prices, Crude Oil prices, Stock index , Interest Rate and USD rate) and how they influence each other." }, { "code": null, "e": 860, "s": 662, "text": "Let’s use the same data set and try to solve our prediction problem with Recurrent Neural network (RNN) algorithm. Neural networks are well known for their efficiency with multiple input variables." }, { "code": null, "e": 986, "s": 860, "text": "Let’s load the data which is already processed earlier; if there is any data error, hopefully our model will learn to ignore." }, { "code": null, "e": 1055, "s": 986, "text": "Let’s understand the mathematical intuition of feed-forward network." }, { "code": null, "e": 1184, "s": 1055, "text": "where, x1, x2....xk are input series, ŷ is output series and in between a bunch of hidden layers. However, here the issues are-" }, { "code": null, "e": 1231, "s": 1184, "text": "information does not account for time ordering" }, { "code": null, "e": 1266, "s": 1231, "text": "inputs are processed independently" }, { "code": null, "e": 1308, "s": 1266, "text": "no mechanism to keep the past information" }, { "code": null, "e": 1590, "s": 1308, "text": "“Feed-Forward network architecture does not have a memory built-in. Moreover, it appears a situation where a deep multilayer feed-forward network is unable to propagate useful gradient information from the output end of the model back to the layers near the input end of the model”" }, { "code": null, "e": 1691, "s": 1590, "text": "To overcome these difficulties, RNN was introduced which comes with a network architecture that can-" }, { "code": null, "e": 1719, "s": 1691, "text": "retain the past information" }, { "code": null, "e": 1748, "s": 1719, "text": "track the state of the world" }, { "code": null, "e": 1806, "s": 1748, "text": "update the state of the world as the network moves faster" }, { "code": null, "e": 1952, "s": 1806, "text": "“RNN handles variable-length sequence by having a recurrent hidden state whose activation at each time is dependent on that of the previous time”" }, { "code": null, "e": 2020, "s": 1952, "text": "Below diagram and equations give a clear idea about how RNN works —" }, { "code": null, "e": 2694, "s": 2020, "text": "where, xt represents inputs, ht expresses the hidden layers from input to output, yt is output. On the top of that, it has a recurrent loop which loop back to the past to express that, the output is not only a function of new input but also a function of past hidden layer and that way the network keeps growing. However, it has a problem of exploding and vanishing gradient. Recurrent Neural Networks (LSTM) addresses this issue. They are networks with loops in them, allowing information to persist. The most important concept for LSTM is the state of the cell, and this information is transmitted to each other between cells with yt data embedded on the top of the cell." }, { "code": null, "e": 3692, "s": 2694, "text": "In the above diagram, a chunk of neural network, A, looks at some input xt and outputs a value ht. A loop allows information to be passed from one step of the network to the next. These loops make recurrent neural networks kind of mysterious object. However, they aren’t all that different than a normal Neural Network. A Recurrent Neural Network is the multiple copies of the same network, each passing a message to a successor. The cell state works like a conveyor belt and is carried through the entire chain. Cells may make small changes to this information. There are gates inside the cells. These gates contain a sigmoid function and open and close the sigmoid function according to the output value. Then the gate output value and yt value are subjected to multiplication. The sigmoid function outputs can take values between 0 and 1, while a value of zero closes the information transition and moves a value across the entire information. If the loop is unrolled as shown in below diagram-" }, { "code": null, "e": 4289, "s": 3692, "text": "This chain-like nature reveals that recurrent neural networks are intimately related to sequences and lists. They’re the natural architecture of neural network to use for such data. Let’s consider the hidden state ht at time step t. The first thing the LSTM cell needs to decide is to report the cell status. This decision is made by the forget gate layer. The forget gate layer generates a value between 0 and 1 for each yt−1 by looking at ht−1 and xt. 1 means that data is stored and 0 means that it will be forgotten. The mathematical expression of the process performed by forget gate layer :" }, { "code": null, "e": 4500, "s": 4289, "text": "The next step is about whether to record the new information in the cell state. Input gate layer decides which value to update. The input gate layer and the output of the input gate layer can be formulated as :" }, { "code": null, "e": 4624, "s": 4500, "text": "A non-linear function layer (tanh) which generates a vector of new candidate values, ŷt which could be added to the state." }, { "code": null, "e": 4789, "s": 4624, "text": "The old cell state is then updated and the yt value representing the new cell state is determined. The below equation can be written for obtaining the new yt value." }, { "code": null, "e": 4916, "s": 4789, "text": "Finally, to ensure that the output value is between -1 and 1 and filter the output, the output functions can be specified as :" }, { "code": null, "e": 5405, "s": 4916, "text": "LSTM suffers from vanishing gradients as well, but not as much as the basic RNN. The difference is for the basic RNN, the gradient decays with wσ′(⋅) while for the LSTM the gradient decays with σ(⋅). For the LSTM, there’s is a set of weights which can be learned such that σ(⋅)≈1. Assuming vt + k = wx for some weight w and input x, then Neural Network can learn a large w to prevent gradients from vanishing. For the basic RNN, there is no set of weights which can be learned such that :" }, { "code": null, "e": 5678, "s": 5405, "text": "The LSTM model in Keras assumes that the data is divided into input (x) and output (y) components. This can be achieve this by using the observation from the last time step (t-1) as the input and the observation at the current time step (t) as the output in a time series." }, { "code": null, "e": 5732, "s": 5678, "text": "Let’s add a “pred” column as our output and shift it." }, { "code": null, "e": 5830, "s": 5732, "text": "Scaling and normalizing is an important activity in the formation of Neural Network Architecture." }, { "code": null, "e": 5962, "s": 5830, "text": "If we check the data, it has a wide range of values (1.336, 13592.79) and neural network do not perform well in this kind of range." }, { "code": null, "e": 6074, "s": 5962, "text": "We have defined a function to specify the look back interval (60 time steps) and the predicted column as below." }, { "code": null, "e": 6206, "s": 6074, "text": "Here, I have split the data in 80/20 ratio. Moreover, we need to reshape the data to 3D array for LSTM to read and train the model." }, { "code": null, "e": 6297, "s": 6206, "text": "We can see the training set contains 4103 data points and testing set has 966 data points." }, { "code": null, "e": 6485, "s": 6297, "text": "Now, we add the LSTM layers and few Dropout layers to prevent overfitting. I have added 3 extra layers in the network. The following arguments are considered for the network architecture:" }, { "code": null, "e": 6543, "s": 6485, "text": "50 units which is the dimensionality of the output space," }, { "code": null, "e": 6665, "s": 6543, "text": "return_sequences = True, which determines whether to return the last output in the output sequence, or the full sequence," }, { "code": null, "e": 6711, "s": 6665, "text": "input_shape as the shape of the training set," }, { "code": null, "e": 6788, "s": 6711, "text": "The Dropout layers specified as 0.2, i.e. 20% of the layers will be dropped," }, { "code": null, "e": 6866, "s": 6788, "text": "Thereafter, I have added the Dense layer that specifies the output of 1 unit," }, { "code": null, "e": 7099, "s": 6866, "text": "Next, the model was fit to run on 100 epochs with a batch size of 32. Instead of training the RNN on the complete sequences of observations, we have used a batch of shorter sub-sequences (32) picked at random from the training-data." }, { "code": null, "e": 7609, "s": 7099, "text": "model_lstm = tf.keras.Sequential()model_lstm.add(tf.keras.layers.LSTM(75, return_sequence = True, input_shape = (xtrain.shape[1], xtrain.shape[2])))model_lstm.add(tf.keras.layers.LSTM(units=30, return_sequence=True))model_lstm.add(tf.keras.layers.LSTM(units=30))model_lstm.add(tf.keras.layers.Dense(units=1))model_lstm.Compile(loss = 'mae', optimizer = 'adam')model_lstm.summary()history_lstm = model_lstm.fit(xtrain, ytrain, epochs = 15, batch_size=32, validation_data = (xtest, ytest), shuffle=False)" }, { "code": null, "e": 7861, "s": 7609, "text": "A line plot of model accuracy on the train and test sets is created, showing the change in performance over all 15 training epochs. The line plot below of the test data (blue) vs the predicted values (orange) providing the context for the model skill." }, { "code": null, "e": 8067, "s": 7861, "text": "The model is fit to the training data; therefore, it can be used to make forecasts. Now, used the trained model to predict the “pred” values in test dataset. I have used fixed approach here for prediction." }, { "code": null, "e": 8214, "s": 8067, "text": "Fixed approach : We can decide to fit the model once on all of the training data, then predict each new time step one at a time from the test data" }, { "code": null, "e": 8367, "s": 8214, "text": "Dynamic approach: We can re-fit the model or update the model each time step of the test data as new observations from the test data are made available." }, { "code": null, "e": 8540, "s": 8367, "text": "We must invert the scale on forecasts to return the values back to the original scale so that the results can be interpreted and a comparable error score can be calculated." }, { "code": null, "e": 8764, "s": 8540, "text": "Now we can see, we are not quite there yet. The result is not that impressive. We can check the difference between these two and compare the results in various ways & optimize the model before we build the trading strategy." }, { "code": null, "e": 8884, "s": 8764, "text": "Let’s see if we can improve the model performance by shifting 10 time steps and doing some hyper parameter adjustments." }, { "code": null, "e": 9152, "s": 8884, "text": "Here the line plot visually looks better than the previous two on both training and testing set. The model appears to rapidly learn the problem, converging on a solution in about 20 epochs. The loss metrics e.g. RMSE, MAE can be obtained similar way as shown earlier." }, { "code": null, "e": 9594, "s": 9152, "text": "Though there is some improvement, but in terms of prediction, we still have rooms for improvement. An important factor here is that, we have used daily prices in this model so the data points are really less only 5,129 data points for Neural Network Architecture. I would recommend to use more than 100,000 data points using minute or tick data for training the model while building ANN or any other Deep Learning model to be most effective." }, { "code": null, "e": 10034, "s": 9594, "text": "Six different time series were used in order to measure the performance of the network fairly. We have found these series are causing each other by using Granger’s Causality. The estimation results obtained are compared with the graphs. RMSE and R values were examined as predictive success criteria. However, it is possible to achieve more successful results with more data points and by changing the hyper parameters of the LSTM network." } ]
How to replace the last occurrence of an expression in a string in Python?
This problem can be solved by reversing the string, reversing the string to be replaced,replacing the string with reverse of string to be replaced with and finally reversing the string to get the result. You can reverse strings by simple slicing notation - [::-1]. To replace the string you can use str.replace(old, new, count). For example, def rreplace(s, old, new): return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1] rreplace('Helloworld, hello world, hello world', 'hello', 'hi') This will give the output: 'Hello world,hello world, hi world' Another method by which you can do this is to reverse split the string once on the old string and join the list with the new string. For example, def rreplace(s, old, new): li = s.rsplit(old, 1) #Split only once return new.join(li) rreplace('Helloworld, hello world, hello world', 'hello', 'hi') This will give the output: 'Hello world, hello world, hi world'
[ { "code": null, "e": 1267, "s": 1062, "text": "This problem can be solved by reversing the string, reversing the string to be replaced,replacing the string with reverse of string to be replaced with and finally reversing the string to get the result. " }, { "code": null, "e": 1405, "s": 1267, "text": "You can reverse strings by simple slicing notation - [::-1]. To replace the string you can use str.replace(old, new, count). For example," }, { "code": null, "e": 1557, "s": 1405, "text": " def rreplace(s, old, new):\n return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1]\n rreplace('Helloworld, hello world, hello world', 'hello', 'hi')" }, { "code": null, "e": 1585, "s": 1557, "text": " This will give the output:" }, { "code": null, "e": 1621, "s": 1585, "text": "'Hello world,hello world, hi world'" }, { "code": null, "e": 1767, "s": 1621, "text": "Another method by which you can do this is to reverse split the string once on the old string and join the list with the new string. For example," }, { "code": null, "e": 1927, "s": 1767, "text": " def rreplace(s, old, new):\n li = s.rsplit(old, 1) #Split only once\n return new.join(li)\n rreplace('Helloworld, hello world, hello world', 'hello', 'hi')" }, { "code": null, "e": 1955, "s": 1927, "text": " This will give the output:" }, { "code": null, "e": 1992, "s": 1955, "text": "'Hello world, hello world, hi world'" } ]
C# Round-trip ("R") Format Specifier
This round-trip ("R") format specifier is supported for the Single, Double, and BigInteger types. It ensures that a numeric value converted to a string is parsed back into the same numeric value. Let us see an example − Firstly, we have a double variable. double doubleVal = 0.91234582637; Now, use the ToString() method: and set the Round-trip format specifier. doubleVal.ToString("R", CultureInfo.InvariantCulture); Let us see the complete example − Live Demo using System; using System.Numerics; using System.Globalization; class Demo { static void Main() { double doubleVal = 0.91234582637; string str = doubleVal.ToString("R", CultureInfo.InvariantCulture); double resRound = double.Parse(str, CultureInfo.InvariantCulture); // round-trip Double with 'R' Console.WriteLine(doubleVal.Equals(resRound)); } } True
[ { "code": null, "e": 1160, "s": 1062, "text": "This round-trip (\"R\") format specifier is supported for the Single, Double, and BigInteger types." }, { "code": null, "e": 1258, "s": 1160, "text": "It ensures that a numeric value converted to a string is parsed back into the same numeric value." }, { "code": null, "e": 1282, "s": 1258, "text": "Let us see an example −" }, { "code": null, "e": 1318, "s": 1282, "text": "Firstly, we have a double variable." }, { "code": null, "e": 1352, "s": 1318, "text": "double doubleVal = 0.91234582637;" }, { "code": null, "e": 1425, "s": 1352, "text": "Now, use the ToString() method: and set the Round-trip format specifier." }, { "code": null, "e": 1480, "s": 1425, "text": "doubleVal.ToString(\"R\", CultureInfo.InvariantCulture);" }, { "code": null, "e": 1514, "s": 1480, "text": "Let us see the complete example −" }, { "code": null, "e": 1525, "s": 1514, "text": " Live Demo" }, { "code": null, "e": 1910, "s": 1525, "text": "using System;\nusing System.Numerics;\nusing System.Globalization;\nclass Demo {\n static void Main() {\n double doubleVal = 0.91234582637;\n string str = doubleVal.ToString(\"R\", CultureInfo.InvariantCulture);\n double resRound = double.Parse(str, CultureInfo.InvariantCulture);\n // round-trip Double with 'R'\n Console.WriteLine(doubleVal.Equals(resRound));\n }\n}" }, { "code": null, "e": 1915, "s": 1910, "text": "True" } ]
Project Idea - Searching news from Old Newspaper using NLP - GeeksforGeeks
18 Aug, 2021 We know that the newspaper is an enriched source of knowledge. When a person needs some information about a particular topic or subject he searches online, but it is difficult to get all old news articles from regional local newspapers related to our search. As not every local newspaper provides an online search for people.In this article, we will present an idea to overcome this problem. This project uses images or pdf of newspaper images from old regional newspapers as input for the database. The model will extract the text from images using Pytesseract. The text from the Pytesseract would be cleaned by NLP practices to simplify and eliminate the words (stop words) that are not helpful for us. The data will be saved in the form of key-value pair in which keys have an image path and values have keywords in the image. Searching: When the user visits the website he will type the topic name or entity name in the search box then images of the newspaper will load on the screen. Newspaper articles contain many articles, prepositions, and other stop words that are not useful to us, so NLP helps us to remove those stop words. It also helps to get unique words. NLTK Python Google colab pytesseract: image to text. NLTK: text pre-processing, filtering. pandas: storing dataframe. First, Install required libraries on colab. Python3 !pip install nltk!pip install pytesseract !sudo apt install tesseract-ocr # to check if it installed properly# !which tesseract# pytesseract.pytesseract.tesseract_cmd = (# r'/usr/bin/tesseract'# ) Let’s import all the necessary libraries: Python3 import ioimport globimport osfrom PIL import Imageimport cv2import pytesseract # /usr/bin/tesseractimport pandas as pdimport nltknltk.download('popular')nltk.download('stopwords')nltk.download('wordnet')from nltk.tokenize import RegexpTokenizerfrom nltk.corpus import stopwordsfrom nltk.stem.wordnet import WordNetLemmatizerfrom IPython.display import Imagefrom google.colab.patches import cv2_imshow This will clean the text to get important names, keywords, etc. Stop words and duplicate words are removed by the below function. Python3 def pre(text): text = text.lower() tokenizer = RegexpTokenizer(r'\w+') new_words = tokenizer.tokenize(text) stop_words = list(stopwords.words("english")) filtered_words = [] for w in new_words: if w not in stop_words: filtered_words.append(w) unique = [] for w in filtered_words: if w not in unique: unique.append(w) res = ' '.join([str(elem) for elem in unique]) res = res.lower() return res when given image path as a parameter it returns preprocessed text in the text variable. then this text is passed as a parameter to pre(). this function returns a dictionary with filename and important text. Python def to_df(imgno): text = pytesseract.image_to_string(imgno) out = pre(text) data = {'filename':imgno, 'text':out} return data here we are defining the dataframe to store the dictionary which has an image path and the text inside the image. We will use this dataframe for searching. Python3 i=0dff=pd.DataFrame() Listing all images in the content folder. Python3 images = []folder = "/content/" for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder, filename)) if img is not None: print(filename) images.append(filename) getting all images For loop to get all news images from the folder. Python3 for u in images: i += 1 data = to_df(u) dff = dff.append(pd.DataFrame(data, index=[i])) print(dff) dataframe Processing the images Python3 # sample text output after processing imagedff.iloc[0]['text'] Saving the dataframe to database. sample text after preprocessing Saving the dataframe Python3 # saving the dataframedff.to_csv('save newsdf.csv') saved Dataframe Open the dataframe file from storage. Python3 data = pd.read_csv('/content/save newsdf.csv')data open dataframe from storage We provide a string as input for the function to get an image in which the keyword is present. Python3 txt= 'modi'index= data['text'].str.find(txt )index the non -1 row th images contain word ‘modi’ Showing the result Python3 # we are showing the first result herefor i in range(len(index)): if (index[i] != -1): a.append(i) try: res = data.iloc[a[0]]['filename']except: print("no file") Image(res) Result of the project We have searched for the word ‘modi‘. The first newspaper which has our searched word in it so it’s shown here. We could use a dedicated database, like lucent or elastic search to make the search more efficient and fast. But for the time being, we use the pandas library to get the path of the image to display to the user. Voter Helper: As elections are coming and Aman is a voter who doesn’t know that much about the politician whom he’s going to vote for. In this situation, he opens our local news.search.in, then he searches for the politician. The website will show the no of the article from the national newspapers as well as from the regional local newspapers, related to the searched person. Now he is ready to decide his vote. Student Research made easy: It can be useful for students who are researching for the topic, as this will give every article from all newspapers related to their topic in image form so they can make notes out of it. Search Engine for Newspaper company: It can be used for press companies to have a search feature on their website. ProGeek 2021 Python-nltk Machine Learning ProGeek Project Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Normalization vs Standardization Difference between Informed and Uninformed Search in AI E-commerce Website using Django College Management System using Django - Python Project How to Build a Simple Note Android App using MVVM and Room Database? Handwritten Digit Recognition using Neural Network How to Make a Scientific Calculator Android App using Android Studio?
[ { "code": null, "e": 24370, "s": 24342, "text": "\n18 Aug, 2021" }, { "code": null, "e": 24762, "s": 24370, "text": "We know that the newspaper is an enriched source of knowledge. When a person needs some information about a particular topic or subject he searches online, but it is difficult to get all old news articles from regional local newspapers related to our search. As not every local newspaper provides an online search for people.In this article, we will present an idea to overcome this problem." }, { "code": null, "e": 24870, "s": 24762, "text": "This project uses images or pdf of newspaper images from old regional newspapers as input for the database." }, { "code": null, "e": 24933, "s": 24870, "text": "The model will extract the text from images using Pytesseract." }, { "code": null, "e": 25075, "s": 24933, "text": "The text from the Pytesseract would be cleaned by NLP practices to simplify and eliminate the words (stop words) that are not helpful for us." }, { "code": null, "e": 25200, "s": 25075, "text": "The data will be saved in the form of key-value pair in which keys have an image path and values have keywords in the image." }, { "code": null, "e": 25359, "s": 25200, "text": "Searching: When the user visits the website he will type the topic name or entity name in the search box then images of the newspaper will load on the screen." }, { "code": null, "e": 25542, "s": 25359, "text": "Newspaper articles contain many articles, prepositions, and other stop words that are not useful to us, so NLP helps us to remove those stop words. It also helps to get unique words." }, { "code": null, "e": 25547, "s": 25542, "text": "NLTK" }, { "code": null, "e": 25554, "s": 25547, "text": "Python" }, { "code": null, "e": 25567, "s": 25554, "text": "Google colab" }, { "code": null, "e": 25595, "s": 25567, "text": "pytesseract: image to text." }, { "code": null, "e": 25633, "s": 25595, "text": "NLTK: text pre-processing, filtering." }, { "code": null, "e": 25660, "s": 25633, "text": "pandas: storing dataframe." }, { "code": null, "e": 25705, "s": 25660, "text": "First, Install required libraries on colab. " }, { "code": null, "e": 25713, "s": 25705, "text": "Python3" }, { "code": "!pip install nltk!pip install pytesseract !sudo apt install tesseract-ocr # to check if it installed properly# !which tesseract# pytesseract.pytesseract.tesseract_cmd = (# r'/usr/bin/tesseract'# )", "e": 25916, "s": 25713, "text": null }, { "code": null, "e": 25958, "s": 25916, "text": "Let’s import all the necessary libraries:" }, { "code": null, "e": 25966, "s": 25958, "text": "Python3" }, { "code": "import ioimport globimport osfrom PIL import Imageimport cv2import pytesseract # /usr/bin/tesseractimport pandas as pdimport nltknltk.download('popular')nltk.download('stopwords')nltk.download('wordnet')from nltk.tokenize import RegexpTokenizerfrom nltk.corpus import stopwordsfrom nltk.stem.wordnet import WordNetLemmatizerfrom IPython.display import Imagefrom google.colab.patches import cv2_imshow", "e": 26367, "s": 25966, "text": null }, { "code": null, "e": 26497, "s": 26367, "text": "This will clean the text to get important names, keywords, etc. Stop words and duplicate words are removed by the below function." }, { "code": null, "e": 26505, "s": 26497, "text": "Python3" }, { "code": "def pre(text): text = text.lower() tokenizer = RegexpTokenizer(r'\\w+') new_words = tokenizer.tokenize(text) stop_words = list(stopwords.words(\"english\")) filtered_words = [] for w in new_words: if w not in stop_words: filtered_words.append(w) unique = [] for w in filtered_words: if w not in unique: unique.append(w) res = ' '.join([str(elem) for elem in unique]) res = res.lower() return res", "e": 26981, "s": 26505, "text": null }, { "code": null, "e": 27188, "s": 26981, "text": "when given image path as a parameter it returns preprocessed text in the text variable. then this text is passed as a parameter to pre(). this function returns a dictionary with filename and important text." }, { "code": null, "e": 27195, "s": 27188, "text": "Python" }, { "code": "def to_df(imgno): text = pytesseract.image_to_string(imgno) out = pre(text) data = {'filename':imgno, 'text':out} return data", "e": 27334, "s": 27195, "text": null }, { "code": null, "e": 27490, "s": 27334, "text": "here we are defining the dataframe to store the dictionary which has an image path and the text inside the image. We will use this dataframe for searching." }, { "code": null, "e": 27498, "s": 27490, "text": "Python3" }, { "code": "i=0dff=pd.DataFrame()", "e": 27520, "s": 27498, "text": null }, { "code": null, "e": 27562, "s": 27520, "text": "Listing all images in the content folder." }, { "code": null, "e": 27570, "s": 27562, "text": "Python3" }, { "code": "images = []folder = \"/content/\" for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder, filename)) if img is not None: print(filename) images.append(filename)", "e": 27774, "s": 27570, "text": null }, { "code": null, "e": 27794, "s": 27774, "text": "getting all images " }, { "code": null, "e": 27843, "s": 27794, "text": "For loop to get all news images from the folder." }, { "code": null, "e": 27851, "s": 27843, "text": "Python3" }, { "code": "for u in images: i += 1 data = to_df(u) dff = dff.append(pd.DataFrame(data, index=[i])) print(dff)", "e": 27954, "s": 27851, "text": null }, { "code": null, "e": 27965, "s": 27954, "text": "dataframe " }, { "code": null, "e": 27987, "s": 27965, "text": "Processing the images" }, { "code": null, "e": 27995, "s": 27987, "text": "Python3" }, { "code": "# sample text output after processing imagedff.iloc[0]['text']", "e": 28058, "s": 27995, "text": null }, { "code": null, "e": 28092, "s": 28058, "text": "Saving the dataframe to database." }, { "code": null, "e": 28124, "s": 28092, "text": "sample text after preprocessing" }, { "code": null, "e": 28145, "s": 28124, "text": "Saving the dataframe" }, { "code": null, "e": 28153, "s": 28145, "text": "Python3" }, { "code": "# saving the dataframedff.to_csv('save newsdf.csv')", "e": 28205, "s": 28153, "text": null }, { "code": null, "e": 28222, "s": 28205, "text": "saved Dataframe " }, { "code": null, "e": 28260, "s": 28222, "text": "Open the dataframe file from storage." }, { "code": null, "e": 28268, "s": 28260, "text": "Python3" }, { "code": "data = pd.read_csv('/content/save newsdf.csv')data", "e": 28319, "s": 28268, "text": null }, { "code": null, "e": 28347, "s": 28319, "text": "open dataframe from storage" }, { "code": null, "e": 28442, "s": 28347, "text": "We provide a string as input for the function to get an image in which the keyword is present." }, { "code": null, "e": 28450, "s": 28442, "text": "Python3" }, { "code": "txt= 'modi'index= data['text'].str.find(txt )index", "e": 28501, "s": 28450, "text": null }, { "code": null, "e": 28546, "s": 28501, "text": "the non -1 row th images contain word ‘modi’" }, { "code": null, "e": 28565, "s": 28546, "text": "Showing the result" }, { "code": null, "e": 28573, "s": 28565, "text": "Python3" }, { "code": "# we are showing the first result herefor i in range(len(index)): if (index[i] != -1): a.append(i) try: res = data.iloc[a[0]]['filename']except: print(\"no file\") Image(res)", "e": 28771, "s": 28573, "text": null }, { "code": null, "e": 28793, "s": 28771, "text": "Result of the project" }, { "code": null, "e": 28905, "s": 28793, "text": "We have searched for the word ‘modi‘. The first newspaper which has our searched word in it so it’s shown here." }, { "code": null, "e": 29118, "s": 28905, "text": "We could use a dedicated database, like lucent or elastic search to make the search more efficient and fast. But for the time being, we use the pandas library to get the path of the image to display to the user." }, { "code": null, "e": 29533, "s": 29118, "text": "Voter Helper: As elections are coming and Aman is a voter who doesn’t know that much about the politician whom he’s going to vote for. In this situation, he opens our local news.search.in, then he searches for the politician. The website will show the no of the article from the national newspapers as well as from the regional local newspapers, related to the searched person. Now he is ready to decide his vote." }, { "code": null, "e": 29750, "s": 29533, "text": "Student Research made easy: It can be useful for students who are researching for the topic, as this will give every article from all newspapers related to their topic in image form so they can make notes out of it. " }, { "code": null, "e": 29865, "s": 29750, "text": "Search Engine for Newspaper company: It can be used for press companies to have a search feature on their website." }, { "code": null, "e": 29878, "s": 29865, "text": "ProGeek 2021" }, { "code": null, "e": 29890, "s": 29878, "text": "Python-nltk" }, { "code": null, "e": 29907, "s": 29890, "text": "Machine Learning" }, { "code": null, "e": 29915, "s": 29907, "text": "ProGeek" }, { "code": null, "e": 29923, "s": 29915, "text": "Project" }, { "code": null, "e": 29930, "s": 29923, "text": "Python" }, { "code": null, "e": 29947, "s": 29930, "text": "Machine Learning" }, { "code": null, "e": 30045, "s": 29947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30054, "s": 30045, "text": "Comments" }, { "code": null, "e": 30067, "s": 30054, "text": "Old Comments" }, { "code": null, "e": 30100, "s": 30067, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 30139, "s": 30100, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 30174, "s": 30139, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 30207, "s": 30174, "text": "Normalization vs Standardization" }, { "code": null, "e": 30263, "s": 30207, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 30295, "s": 30263, "text": "E-commerce Website using Django" }, { "code": null, "e": 30351, "s": 30295, "text": "College Management System using Django - Python Project" }, { "code": null, "e": 30420, "s": 30351, "text": "How to Build a Simple Note Android App using MVVM and Room Database?" }, { "code": null, "e": 30471, "s": 30420, "text": "Handwritten Digit Recognition using Neural Network" } ]
PyTorch Layer Dimensions: The Complete Cheat Sheet | Towards Data Science
Preface This article covers defining tensors, and properly initializing neural network layers in PyTorch, and more! (Formerly titled PyTorch layer dimensions: What size and why?) You might be asking: “How do I initialize my layer dimensions in PyTorch without getting yelled at?” Is it all just trial and error? No, really... What are they supposed to be? For starters, did you know that the first two required arguments of a torch.nn.Conv2d layer, and a torch.nn.Linear layer ask for completely different aspects of the exact same tensor data? If you didn’t know this, keep reading. Example 1: Same, same, but different. Constructing a convolution layer and linear layer are syntactically similar, but the args do not expect similar things, despite being able to operate on the exact same input data (although that data should be sized differently). # The __init__ method of a nn.Module class:...def __init__(self):"""Initialize neural net layers.""" super(Net, self).__init__() # Intialize my 2 layers here: self.conv = nn.Conv2d(1, 20, 3) # Give me depth of input. self.dense = nn.Linear(2048, 10) # Give me features of input.... You need to develop your understanding of how PyTorch models would like to consume data before just throwing a dataset at some network layers. Below are some common tensor sizes encountered in PyTorch and typical examples of when to utilize them. It’s important to know what you’re looking at, because their structures are not as predictable as one might desire (this somewhat unintuitive design choice was implemented primarily for performance benefits, which is OK... I guess). One mental anchor we have when feeding tensors into convolutional or linear layers (although not RNN’s) is that the first dimension is always batch size (N). Whereas, the remaining dimensions depend on what phase the moon is in and the intermittent frequency of cricket (Acheta domesticus) chirps at moonrise in your region. Just kidding, it’s not that simple. You have to learn them by rote. So start roting (Example 2 below). It’s important to know how PyTorch expects its tensors to be shaped— because you might be perfectly satisfied that your 28 x 28 pixel image shows up as a tensor of torch.Size([28, 28]). Whereas PyTorch on the other hand, thinks you want it to be looking at your 28 batches of 28 feature vectors. Suffice it to say, you’re not going to be friends with each other for a little while until you learn how to see things her way — so, don’t be that guy. Study your tensor dimensions! Example 2: The tensor dimensions PyTorch likes. """Example tensor size outputs, how PyTorch reads them, and where you encounter them in the wild. Note: the values below are only examples. Focus on the rank of the tensor (how many dimensions it has).""">>> torch.Size([32]) # 1d: [batch_size] # use for target labels or predictions.>>> torch.Size([12, 256]) # 2d: [batch_size, num_features (aka: C * H * W)] # use for nn.Linear() input.>>> torch.Size([10, 1, 2048]) # 3d: [batch_size, channels, num_features (aka: H * W)] # when used as nn.Conv1d() input. # (but [seq_len, batch_size, num_features] # if feeding an RNN).>>> torch.Size([16, 3, 28, 28]) # 4d: [batch_size, channels, height, width] # use for nn.Conv2d() input.>>> torch.Size([32, 1, 5, 15, 15]) # 5D: [batch_size, channels, depth, height, width] # use for nn.Conv3d() input. Notice how the Conv2d layer wants a 4d tensor? How about the 1d or 3d layers? So, if you wanted to load a grey scale, 28 x 28 pixel image into a Conv2d network layer, find the layer type in the example above. Since it wants a 4d tensor, and you already have a 2d tensor with height and width, just add batch_size, and channels (see rule of thumb for channels below) to pad out the extra dimensions, like so: [1, 1, 28, 28]. That way, you and PyTorch can make up and be friends again. The documentation describes a Conv2d layer like this: """Class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')Parametersin_channels (int) - Number of channels in the input imageout_channels (int) - Number of channels produced by the convolution""" Remember which dimension your input channels are? See Lesson 1 if you forgot. Simply use that number for your in_channels argument in the first convolutional layer. Done. Rule of thumb for “in_channels” on your first Conv2d layer: — If your image is black and white, it is 1 channel. (You can ensure this by running transforms.Grayscale(1) in the transforms argument of the dataloader.) — If your image is color, it is 3 channels (RGB). — If there is an alpha (transparency) channel, it has 4 channels. This means for your first Conv2d layer, even if your image size is something enormous like 1080px by 1080px, your in_channels will typically be either 1 or 3. Note: If you tested this with some randomly generated tensor and it throws up at you still and you’re yelling at your computer right now, breathe. It’s OK. Make sure it has the right dimensions. Did you unsqueeze() the tensor? Pytorch wants batches. The unsqueeze() function will add a dimension of 1 representing a batch size of 1. What about the out_channels you say? That’s your choice for how deep you want your network to be. Basically, your out_channels dimension, defined by Pytorch is: out_channels (int) — Number of channels produced by the convolution For each convolutional kernel you use, your output tensor becomes one channel deeper when passing through that layer. If you want a ton of kernels, make this number high like 121, if you want just a few, make this number low like 8 or 12. Whatever number you choose here will be the value for channels_in of the next convolutional layer, and so on and so forth. Note: The value of kernel_size is custom, and although important, doesn’t lead to head-scratching errors, so it is omitted from this tutorial. Just make it an odd number, typically between 3–11, but sizes may vary between your applications. Generally, convolutional layers at the front half of a network get deeper and deeper, while fully-connected (aka: linear, or dense) layers at the end of a network get smaller and smaller. Here’s a valid example from the 60-minute-beginner-blitz (notice the out_channel of self.conv1 becomes the in_channel of self.conv2): class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 3x3 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 3) self.conv2 = nn.Conv2d(6, 16, 3) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) Let’s talk about fully connected layers now. Documentation for Linear layers tells us the following: """Class torch.nn.Linear(in_features, out_features, bias=True)Parametersin_features – size of each input sampleout_features – size of each output sample""" I know these look similar, but do not be confused: “in_features” and “in_channels” are completely different, beginners often mix them up and think they’re the same attribute. # Asks for in_channels, out_channels, kernel_size, etcself.conv1 = nn.Conv2d(1, 20, 3)# Asks for in_features, out_featuresself.fc1 = nn.Linear(2048, 10) There are two, specifically important arguments for all nn.Linear layer networks that you should be aware of no matter how many layers deep your network is. The very first argument, and the very last argument. It doesn’t matter how many fully connected layers you have in between, those dimensions are easy, as you’ll soon see. If you want to pass in your 28 x 28 image into a linear layer, you have to know two things: Your 28 x 28 pixel image can’t be input as a [28, 28] tensor. This is because nn.Linear will read it as 28 batches of 28-feature-length vectors. Since it expects an input of [batch_size, num_features], you have to transpose it somehow (see view() below).Your batch size passes unchanged through all your layers. No matter how your data changes as it passes through a network, your first dimension will end up being your batch_size even if you never see that number explicitly written anywhere in your network module’s definition. Your 28 x 28 pixel image can’t be input as a [28, 28] tensor. This is because nn.Linear will read it as 28 batches of 28-feature-length vectors. Since it expects an input of [batch_size, num_features], you have to transpose it somehow (see view() below). Your batch size passes unchanged through all your layers. No matter how your data changes as it passes through a network, your first dimension will end up being your batch_size even if you never see that number explicitly written anywhere in your network module’s definition. Use view() to change your tensor’s dimensions. image = image.view(batch_size, -1) You supply your batch_size as the first number, and then “-1” basically tells Pytorch, “you figure out this other number for me... please.” Your tensor will now feed properly into any linear layer. Now we’re talking! So then, to initialize the very first argument of your linear layer, pass it the number of features of your input data. For 28 x 28, our new view tensor is of size [1, 784] (1 * 28 * 28): Example 3: Resize with view() to fit into a linear layer batch_size = 1# Simulate a 28 x 28 pixel, grayscale "image"input = torch.randn(1, 28, 28)# Use view() to get [batch_size, num_features].# -1 calculates the missing value given the other dim.input = input.view(batch_size, -1) # torch.Size([1, 784])# Intialize the linear layer.fc = torch.nn.Linear(784, 10)# Pass in the simulated image to the layer.output = fc(input)print(output.shape)>>> torch.Size([1, 10]) Remember this — if you’re ever transitioning from a convolutional layer output to a linear layer input, you must resize it from 4d to 2d using view, as described with image example above. So, a conv output of [32, 21, 50, 50] should be “flattened” to become a [32, 21 * 50 * 50] tensor. And the in_features of the linear layer should also be set to [21 * 50 * 50]. The second argument of a linear layer, if you’re passing it on to more layers, is called H for hidden layer. You just kind of play positional ping-pong with H and make it the last of the previous and the first of the next, like this: """The in-between dimensions are the hidden layer dimensions, you just pass in the last of the previous as the first of the next."""fc1 = torch.nn.Linear(784, 100) # 100 is last.fc2 = torch.nn.Linear(100, 50) # 100 is first, 50 is last.fc3 = torch.nn.Linear(50, 20) # 50 is first, 20 is last.fc4 = torch.nn.Linear(20, 10) # 20 is first. """This is the same pattern for convolutional layers as well, only it's channels, and not features that get passed along.""" The very last output, aka your output layer depends on your model and your loss function. If you have 10 classes like in MNIST, and you’re doing a classification problem, you want all of your network architecture to eventually consolidate into those final 10 units so that you can determine which of those 10 classes your input is predicting. The last layer is dependent on what you want to infer from your data. The operations you can do to get the answer you need is a topic for another article, because there is a lot to cover. But for now you should have all the basics covered. That’s it! You should now be able to build a network without scratching your head or getting shouted at by the interpreter. Remember, your batch_size or dim 0 is the same, all the way through. Your convolution layers care about depth (channels), and your linear layers care about feature counts. And learn how to read those tensors! Please leave a comment, or share this article if you liked it and found it helpful!
[ { "code": null, "e": 180, "s": 172, "text": "Preface" }, { "code": null, "e": 351, "s": 180, "text": "This article covers defining tensors, and properly initializing neural network layers in PyTorch, and more! (Formerly titled PyTorch layer dimensions: What size and why?)" }, { "code": null, "e": 756, "s": 351, "text": "You might be asking: “How do I initialize my layer dimensions in PyTorch without getting yelled at?” Is it all just trial and error? No, really... What are they supposed to be? For starters, did you know that the first two required arguments of a torch.nn.Conv2d layer, and a torch.nn.Linear layer ask for completely different aspects of the exact same tensor data? If you didn’t know this, keep reading." }, { "code": null, "e": 794, "s": 756, "text": "Example 1: Same, same, but different." }, { "code": null, "e": 1023, "s": 794, "text": "Constructing a convolution layer and linear layer are syntactically similar, but the args do not expect similar things, despite being able to operate on the exact same input data (although that data should be sized differently)." }, { "code": null, "e": 1321, "s": 1023, "text": "# The __init__ method of a nn.Module class:...def __init__(self):\"\"\"Initialize neural net layers.\"\"\" super(Net, self).__init__() # Intialize my 2 layers here: self.conv = nn.Conv2d(1, 20, 3) # Give me depth of input. self.dense = nn.Linear(2048, 10) # Give me features of input...." }, { "code": null, "e": 1464, "s": 1321, "text": "You need to develop your understanding of how PyTorch models would like to consume data before just throwing a dataset at some network layers." }, { "code": null, "e": 1801, "s": 1464, "text": "Below are some common tensor sizes encountered in PyTorch and typical examples of when to utilize them. It’s important to know what you’re looking at, because their structures are not as predictable as one might desire (this somewhat unintuitive design choice was implemented primarily for performance benefits, which is OK... I guess)." }, { "code": null, "e": 2229, "s": 1801, "text": "One mental anchor we have when feeding tensors into convolutional or linear layers (although not RNN’s) is that the first dimension is always batch size (N). Whereas, the remaining dimensions depend on what phase the moon is in and the intermittent frequency of cricket (Acheta domesticus) chirps at moonrise in your region. Just kidding, it’s not that simple. You have to learn them by rote. So start roting (Example 2 below)." }, { "code": null, "e": 2707, "s": 2229, "text": "It’s important to know how PyTorch expects its tensors to be shaped— because you might be perfectly satisfied that your 28 x 28 pixel image shows up as a tensor of torch.Size([28, 28]). Whereas PyTorch on the other hand, thinks you want it to be looking at your 28 batches of 28 feature vectors. Suffice it to say, you’re not going to be friends with each other for a little while until you learn how to see things her way — so, don’t be that guy. Study your tensor dimensions!" }, { "code": null, "e": 2755, "s": 2707, "text": "Example 2: The tensor dimensions PyTorch likes." }, { "code": null, "e": 3583, "s": 2755, "text": "\"\"\"Example tensor size outputs, how PyTorch reads them, and where you encounter them in the wild. Note: the values below are only examples. Focus on the rank of the tensor (how many dimensions it has).\"\"\">>> torch.Size([32]) # 1d: [batch_size] # use for target labels or predictions.>>> torch.Size([12, 256]) # 2d: [batch_size, num_features (aka: C * H * W)] # use for nn.Linear() input.>>> torch.Size([10, 1, 2048]) # 3d: [batch_size, channels, num_features (aka: H * W)] # when used as nn.Conv1d() input. # (but [seq_len, batch_size, num_features] # if feeding an RNN).>>> torch.Size([16, 3, 28, 28]) # 4d: [batch_size, channels, height, width] # use for nn.Conv2d() input.>>> torch.Size([32, 1, 5, 15, 15]) # 5D: [batch_size, channels, depth, height, width] # use for nn.Conv3d() input." }, { "code": null, "e": 3661, "s": 3583, "text": "Notice how the Conv2d layer wants a 4d tensor? How about the 1d or 3d layers?" }, { "code": null, "e": 4067, "s": 3661, "text": "So, if you wanted to load a grey scale, 28 x 28 pixel image into a Conv2d network layer, find the layer type in the example above. Since it wants a 4d tensor, and you already have a 2d tensor with height and width, just add batch_size, and channels (see rule of thumb for channels below) to pad out the extra dimensions, like so: [1, 1, 28, 28]. That way, you and PyTorch can make up and be friends again." }, { "code": null, "e": 4121, "s": 4067, "text": "The documentation describes a Conv2d layer like this:" }, { "code": null, "e": 4399, "s": 4121, "text": "\"\"\"Class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')Parametersin_channels (int) - Number of channels in the input imageout_channels (int) - Number of channels produced by the convolution\"\"\"" }, { "code": null, "e": 4570, "s": 4399, "text": "Remember which dimension your input channels are? See Lesson 1 if you forgot. Simply use that number for your in_channels argument in the first convolutional layer. Done." }, { "code": null, "e": 4630, "s": 4570, "text": "Rule of thumb for “in_channels” on your first Conv2d layer:" }, { "code": null, "e": 4786, "s": 4630, "text": "— If your image is black and white, it is 1 channel. (You can ensure this by running transforms.Grayscale(1) in the transforms argument of the dataloader.)" }, { "code": null, "e": 4836, "s": 4786, "text": "— If your image is color, it is 3 channels (RGB)." }, { "code": null, "e": 4902, "s": 4836, "text": "— If there is an alpha (transparency) channel, it has 4 channels." }, { "code": null, "e": 5061, "s": 4902, "text": "This means for your first Conv2d layer, even if your image size is something enormous like 1080px by 1080px, your in_channels will typically be either 1 or 3." }, { "code": null, "e": 5394, "s": 5061, "text": "Note: If you tested this with some randomly generated tensor and it throws up at you still and you’re yelling at your computer right now, breathe. It’s OK. Make sure it has the right dimensions. Did you unsqueeze() the tensor? Pytorch wants batches. The unsqueeze() function will add a dimension of 1 representing a batch size of 1." }, { "code": null, "e": 5555, "s": 5394, "text": "What about the out_channels you say? That’s your choice for how deep you want your network to be. Basically, your out_channels dimension, defined by Pytorch is:" }, { "code": null, "e": 5623, "s": 5555, "text": "out_channels (int) — Number of channels produced by the convolution" }, { "code": null, "e": 5985, "s": 5623, "text": "For each convolutional kernel you use, your output tensor becomes one channel deeper when passing through that layer. If you want a ton of kernels, make this number high like 121, if you want just a few, make this number low like 8 or 12. Whatever number you choose here will be the value for channels_in of the next convolutional layer, and so on and so forth." }, { "code": null, "e": 6226, "s": 5985, "text": "Note: The value of kernel_size is custom, and although important, doesn’t lead to head-scratching errors, so it is omitted from this tutorial. Just make it an odd number, typically between 3–11, but sizes may vary between your applications." }, { "code": null, "e": 6548, "s": 6226, "text": "Generally, convolutional layers at the front half of a network get deeper and deeper, while fully-connected (aka: linear, or dense) layers at the end of a network get smaller and smaller. Here’s a valid example from the 60-minute-beginner-blitz (notice the out_channel of self.conv1 becomes the in_channel of self.conv2):" }, { "code": null, "e": 6984, "s": 6548, "text": "class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 3x3 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 3) self.conv2 = nn.Conv2d(6, 16, 3) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)" }, { "code": null, "e": 7029, "s": 6984, "text": "Let’s talk about fully connected layers now." }, { "code": null, "e": 7085, "s": 7029, "text": "Documentation for Linear layers tells us the following:" }, { "code": null, "e": 7242, "s": 7085, "text": "\"\"\"Class torch.nn.Linear(in_features, out_features, bias=True)Parametersin_features – size of each input sampleout_features – size of each output sample\"\"\"" }, { "code": null, "e": 7417, "s": 7242, "text": "I know these look similar, but do not be confused: “in_features” and “in_channels” are completely different, beginners often mix them up and think they’re the same attribute." }, { "code": null, "e": 7570, "s": 7417, "text": "# Asks for in_channels, out_channels, kernel_size, etcself.conv1 = nn.Conv2d(1, 20, 3)# Asks for in_features, out_featuresself.fc1 = nn.Linear(2048, 10)" }, { "code": null, "e": 7898, "s": 7570, "text": "There are two, specifically important arguments for all nn.Linear layer networks that you should be aware of no matter how many layers deep your network is. The very first argument, and the very last argument. It doesn’t matter how many fully connected layers you have in between, those dimensions are easy, as you’ll soon see." }, { "code": null, "e": 7990, "s": 7898, "text": "If you want to pass in your 28 x 28 image into a linear layer, you have to know two things:" }, { "code": null, "e": 8520, "s": 7990, "text": "Your 28 x 28 pixel image can’t be input as a [28, 28] tensor. This is because nn.Linear will read it as 28 batches of 28-feature-length vectors. Since it expects an input of [batch_size, num_features], you have to transpose it somehow (see view() below).Your batch size passes unchanged through all your layers. No matter how your data changes as it passes through a network, your first dimension will end up being your batch_size even if you never see that number explicitly written anywhere in your network module’s definition." }, { "code": null, "e": 8775, "s": 8520, "text": "Your 28 x 28 pixel image can’t be input as a [28, 28] tensor. This is because nn.Linear will read it as 28 batches of 28-feature-length vectors. Since it expects an input of [batch_size, num_features], you have to transpose it somehow (see view() below)." }, { "code": null, "e": 9051, "s": 8775, "text": "Your batch size passes unchanged through all your layers. No matter how your data changes as it passes through a network, your first dimension will end up being your batch_size even if you never see that number explicitly written anywhere in your network module’s definition." }, { "code": null, "e": 9098, "s": 9051, "text": "Use view() to change your tensor’s dimensions." }, { "code": null, "e": 9133, "s": 9098, "text": "image = image.view(batch_size, -1)" }, { "code": null, "e": 9350, "s": 9133, "text": "You supply your batch_size as the first number, and then “-1” basically tells Pytorch, “you figure out this other number for me... please.” Your tensor will now feed properly into any linear layer. Now we’re talking!" }, { "code": null, "e": 9538, "s": 9350, "text": "So then, to initialize the very first argument of your linear layer, pass it the number of features of your input data. For 28 x 28, our new view tensor is of size [1, 784] (1 * 28 * 28):" }, { "code": null, "e": 9595, "s": 9538, "text": "Example 3: Resize with view() to fit into a linear layer" }, { "code": null, "e": 10004, "s": 9595, "text": "batch_size = 1# Simulate a 28 x 28 pixel, grayscale \"image\"input = torch.randn(1, 28, 28)# Use view() to get [batch_size, num_features].# -1 calculates the missing value given the other dim.input = input.view(batch_size, -1) # torch.Size([1, 784])# Intialize the linear layer.fc = torch.nn.Linear(784, 10)# Pass in the simulated image to the layer.output = fc(input)print(output.shape)>>> torch.Size([1, 10])" }, { "code": null, "e": 10192, "s": 10004, "text": "Remember this — if you’re ever transitioning from a convolutional layer output to a linear layer input, you must resize it from 4d to 2d using view, as described with image example above." }, { "code": null, "e": 10369, "s": 10192, "text": "So, a conv output of [32, 21, 50, 50] should be “flattened” to become a [32, 21 * 50 * 50] tensor. And the in_features of the linear layer should also be set to [21 * 50 * 50]." }, { "code": null, "e": 10603, "s": 10369, "text": "The second argument of a linear layer, if you’re passing it on to more layers, is called H for hidden layer. You just kind of play positional ping-pong with H and make it the last of the previous and the first of the next, like this:" }, { "code": null, "e": 11065, "s": 10603, "text": "\"\"\"The in-between dimensions are the hidden layer dimensions, you just pass in the last of the previous as the first of the next.\"\"\"fc1 = torch.nn.Linear(784, 100) # 100 is last.fc2 = torch.nn.Linear(100, 50) # 100 is first, 50 is last.fc3 = torch.nn.Linear(50, 20) # 50 is first, 20 is last.fc4 = torch.nn.Linear(20, 10) # 20 is first. \"\"\"This is the same pattern for convolutional layers as well, only it's channels, and not features that get passed along.\"\"\"" }, { "code": null, "e": 11408, "s": 11065, "text": "The very last output, aka your output layer depends on your model and your loss function. If you have 10 classes like in MNIST, and you’re doing a classification problem, you want all of your network architecture to eventually consolidate into those final 10 units so that you can determine which of those 10 classes your input is predicting." }, { "code": null, "e": 11648, "s": 11408, "text": "The last layer is dependent on what you want to infer from your data. The operations you can do to get the answer you need is a topic for another article, because there is a lot to cover. But for now you should have all the basics covered." }, { "code": null, "e": 11659, "s": 11648, "text": "That’s it!" }, { "code": null, "e": 11981, "s": 11659, "text": "You should now be able to build a network without scratching your head or getting shouted at by the interpreter. Remember, your batch_size or dim 0 is the same, all the way through. Your convolution layers care about depth (channels), and your linear layers care about feature counts. And learn how to read those tensors!" } ]
Python - Date and Time
Often in data science we need analysis which is based on temporal values. Python can handle the various formats of date and time gracefully. The datetime library provides necessary methods and functions to handle the following scenarios. Date Time Representation Date Time Arithmetic Date Time Comparison We will study them one by one. A date and its various parts are represented by using different datetime functions. Also, there are format specifiers which play a role in displaying the alphabetical parts of a date like name of the month or week day. The following code shows today's date and various parts of the date. import datetime print 'The Date Today is :', datetime.datetime.today() date_today = datetime.date.today() print date_today print 'This Year :', date_today.year print 'This Month :', date_today.month print 'Month Name:',date_today.strftime('%B') print 'This Week Day :', date_today.day print 'Week Day Name:',date_today.strftime('%A') When we execute the above code, it produces the following result. The Date Today is : 2018-04-22 15:38:35.835000 2018-04-22 This Year : 2018 This Month : 4 Month Name: April This Week Day : 22 Week Day Name: Sunday For calculations involving dates we store the various dates into variables and apply the relevant mathematical operator to these variables. import datetime #Capture the First Date day1 = datetime.date(2018, 2, 12) print 'day1:', day1.ctime() # Capture the Second Date day2 = datetime.date(2017, 8, 18) print 'day2:', day2.ctime() # Find the difference between the dates print 'Number of Days:', day1-day2 date_today = datetime.date.today() # Create a delta of Four Days no_of_days = datetime.timedelta(days=4) # Use Delta for Past Date before_four_days = date_today - no_of_days print 'Before Four Days:', before_four_days # Use Delta for future Date after_four_days = date_today + no_of_days print 'After Four Days:', after_four_days When we execute the above code, it produces the following result. day1: Mon Feb 12 00:00:00 2018 day2: Fri Aug 18 00:00:00 2017 Number of Days: 178 days, 0:00:00 Before Four Days: 2018-04-18 After Four Days: 2018-04-26 Date and time are compared using logical operators. But we must be careful in comparing the right parts of the dates with each other. In the below examples we take the future and past dates and compare them using the python if clause along with logical operators. import datetime date_today = datetime.date.today() print 'Today is: ', date_today # Create a delta of Four Days no_of_days = datetime.timedelta(days=4) # Use Delta for Past Date before_four_days = date_today - no_of_days print 'Before Four Days:', before_four_days after_four_days = date_today + no_of_days date1 = datetime.date(2018,4,4) print 'date1:',date1 if date1 == before_four_days : print 'Same Dates' if date_today > date1: print 'Past Date' if date1 < after_four_days: print 'Future Date' When we execute the above code, it produces the following result. Today is: 2018-04-22 Before Four Days: 2018-04-18 date1: 2018-04-04 Past Date Future Date 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2768, "s": 2529, "text": "Often in data science we need analysis which is based on temporal values. Python can handle the various formats of date and time gracefully. The datetime library \nprovides necessary methods and functions to handle the following scenarios." }, { "code": null, "e": 2793, "s": 2768, "text": "Date Time Representation" }, { "code": null, "e": 2814, "s": 2793, "text": "Date Time Arithmetic" }, { "code": null, "e": 2835, "s": 2814, "text": "Date Time Comparison" }, { "code": null, "e": 2866, "s": 2835, "text": "We will study them one by one." }, { "code": null, "e": 3154, "s": 2866, "text": "A date and its various parts are represented by using different datetime functions. Also, there are format specifiers which play a role in displaying the alphabetical parts of a date like name of the month or week day. The following code shows today's date and various parts of the date." }, { "code": null, "e": 3499, "s": 3154, "text": "import datetime\n\nprint 'The Date Today is :', datetime.datetime.today()\n\ndate_today = datetime.date.today()\nprint date_today\nprint 'This Year :', date_today.year\nprint 'This Month :', date_today.month\nprint 'Month Name:',date_today.strftime('%B')\nprint 'This Week Day :', date_today.day\nprint 'Week Day Name:',date_today.strftime('%A')" }, { "code": null, "e": 3565, "s": 3499, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 3723, "s": 3565, "text": "The Date Today is : 2018-04-22 15:38:35.835000\n2018-04-22\nThis Year : 2018\nThis Month : 4\nMonth Name: April\nThis Week Day : 22\nWeek Day Name: Sunday" }, { "code": null, "e": 3864, "s": 3723, "text": "For calculations involving dates we store the various dates into variables and apply the relevant mathematical operator to these variables. " }, { "code": null, "e": 4478, "s": 3864, "text": "import datetime \n \n#Capture the First Date\nday1 = datetime.date(2018, 2, 12)\nprint 'day1:', day1.ctime()\n\n# Capture the Second Date\nday2 = datetime.date(2017, 8, 18)\nprint 'day2:', day2.ctime()\n\n# Find the difference between the dates\nprint 'Number of Days:', day1-day2\n\n\ndate_today = datetime.date.today() \n\n# Create a delta of Four Days \nno_of_days = datetime.timedelta(days=4) \n\n# Use Delta for Past Date\nbefore_four_days = date_today - no_of_days \nprint 'Before Four Days:', before_four_days \n \n# Use Delta for future Date\nafter_four_days = date_today + no_of_days \nprint 'After Four Days:', after_four_days " }, { "code": null, "e": 4544, "s": 4478, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 4697, "s": 4544, "text": "day1: Mon Feb 12 00:00:00 2018\nday2: Fri Aug 18 00:00:00 2017\nNumber of Days: 178 days, 0:00:00\nBefore Four Days: 2018-04-18\nAfter Four Days: 2018-04-26" }, { "code": null, "e": 4963, "s": 4697, "text": "Date and time are compared using logical operators. But we must be careful in comparing the right parts of the dates with each other. In the below examples\nwe take the future and past dates and compare them using the python if clause along with logical operators. " }, { "code": null, "e": 5488, "s": 4963, "text": "import datetime\n\ndate_today = datetime.date.today() \n\nprint 'Today is: ', date_today\n# Create a delta of Four Days \nno_of_days = datetime.timedelta(days=4) \n\n# Use Delta for Past Date\nbefore_four_days = date_today - no_of_days \nprint 'Before Four Days:', before_four_days \n\nafter_four_days = date_today + no_of_days\n\ndate1 = datetime.date(2018,4,4)\n\nprint 'date1:',date1\n\nif date1 == before_four_days :\n print 'Same Dates'\nif date_today > date1:\n print 'Past Date'\nif date1 < after_four_days:\n print 'Future Date'" }, { "code": null, "e": 5554, "s": 5488, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 5645, "s": 5554, "text": "Today is: 2018-04-22\nBefore Four Days: 2018-04-18\ndate1: 2018-04-04\nPast Date\nFuture Date" }, { "code": null, "e": 5682, "s": 5645, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5698, "s": 5682, "text": " Malhar Lathkar" }, { "code": null, "e": 5731, "s": 5698, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5750, "s": 5731, "text": " Arnab Chakraborty" }, { "code": null, "e": 5785, "s": 5750, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5807, "s": 5785, "text": " In28Minutes Official" }, { "code": null, "e": 5841, "s": 5807, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5869, "s": 5841, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5904, "s": 5869, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5918, "s": 5904, "text": " Lets Kode It" }, { "code": null, "e": 5951, "s": 5918, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5968, "s": 5951, "text": " Abhilash Nelson" }, { "code": null, "e": 5975, "s": 5968, "text": " Print" }, { "code": null, "e": 5986, "s": 5975, "text": " Add Notes" } ]
DAX Aggregation - GENERATE function
Returns a table with the Cartesian product between each row in table1 and the table that results from evaluating table2 in the context of the current row from table1. GENERATE (<table1>, <table2>) table1 Table or a DAX expression that returns a table. table2 Table or a DAX expression that returns a table. A table that can be passed as a parameter to a DAX function. If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row. If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row. All column names from table1 and table2 must be different or an error is returned. All column names from table1 and table2 must be different or an error is returned. = GENERATE ( SUMMARIZE(Salesperson,Salesperson[Salesperson]), SUMMARIZE(SalesTarget,SalesTarget[SalesTarget], "MaxTarget",MAX(Sales Target[SalesTarget])) ) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2168, "s": 2001, "text": "Returns a table with the Cartesian product between each row in table1 and the table that results from evaluating table2 in the context of the current row from table1." }, { "code": null, "e": 2199, "s": 2168, "text": "GENERATE (<table1>, <table2>)\n" }, { "code": null, "e": 2206, "s": 2199, "text": "table1" }, { "code": null, "e": 2254, "s": 2206, "text": "Table or a DAX expression that returns a table." }, { "code": null, "e": 2261, "s": 2254, "text": "table2" }, { "code": null, "e": 2309, "s": 2261, "text": "Table or a DAX expression that returns a table." }, { "code": null, "e": 2370, "s": 2309, "text": "A table that can be passed as a parameter to a DAX function." }, { "code": null, "e": 2697, "s": 2370, "text": "If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row." }, { "code": null, "e": 3024, "s": 2697, "text": "If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row." }, { "code": null, "e": 3107, "s": 3024, "text": "All column names from table1 and table2 must be different or an error is returned." }, { "code": null, "e": 3190, "s": 3107, "text": "All column names from table1 and table2 must be different or an error is returned." }, { "code": null, "e": 3362, "s": 3190, "text": "= GENERATE ( \n SUMMARIZE(Salesperson,Salesperson[Salesperson]),\n SUMMARIZE(SalesTarget,SalesTarget[SalesTarget],\n \"MaxTarget\",MAX(Sales Target[SalesTarget]))\n)" }, { "code": null, "e": 3397, "s": 3362, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3411, "s": 3397, "text": " Abhay Gadiya" }, { "code": null, "e": 3444, "s": 3411, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3458, "s": 3444, "text": " Randy Minder" }, { "code": null, "e": 3493, "s": 3458, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3507, "s": 3493, "text": " Randy Minder" }, { "code": null, "e": 3514, "s": 3507, "text": " Print" }, { "code": null, "e": 3525, "s": 3514, "text": " Add Notes" } ]
std::stod, std::stof, std::stold in C++ - GeeksforGeeks
29 Oct, 2018 std::stod() : It convert string into double.Syntax:double stod( const std::string& str, std::size_t* pos = 0 ); double stod( const std::wstring& str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This parameter can also be a null pointer, in which case it is not used. // CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = "y=4.4786754x+5.6"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the "value" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;}Output:5.6 Another Example :// CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = "5"; double a = stod(b); int c = stoi(b); cout << b << " " << a << " " << c << endl;}Output:5 5 5 If conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior.std::stof : It convert string into float.Syntax:float stof( const string& str, size_t* pos = 0 ); float stof( const wstring& str, size_t* pos = 0 ); Parameters str : the string to convert pos : address of an integer to store the number of characters processed This parameter can also be a null pointer, in which case it is not used. Return value: it returns value of type float.Example 1:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = "20"; float y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:22.5 Example 2:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = "5000.5"; float x = std::stof(str); std::cout << x; return 0;}Output:5000.5 If no conversion could be performed, an invalid_argument exception is thrown.std::stold : It convert string into long double.Syntax:long double stold( const string& str, size_t *pos = 0 ); long double stold (const wstring& str, size_t* pos = 0); Parameters : str : the string to convert pos : address of integer to store the index of the first unconverted character. This parameter can also be a null pointer, in which case it is not used. Return value : it returns value of type long double. Examples 1:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = "500087"; long double x = std::stold(str); std::cout << x; return 0;}Output:500087 Example 2:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = "2075"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:2077.5 std::stod() : It convert string into double.Syntax:double stod( const std::string& str, std::size_t* pos = 0 ); double stod( const std::wstring& str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This parameter can also be a null pointer, in which case it is not used. // CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = "y=4.4786754x+5.6"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the "value" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;}Output:5.6 Another Example :// CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = "5"; double a = stod(b); int c = stoi(b); cout << b << " " << a << " " << c << endl;}Output:5 5 5 If conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior. double stod( const std::string& str, std::size_t* pos = 0 ); double stod( const std::wstring& str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This parameter can also be a null pointer, in which case it is not used. // CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = "y=4.4786754x+5.6"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the "value" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;} Output: 5.6 Another Example : // CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = "5"; double a = stod(b); int c = stoi(b); cout << b << " " << a << " " << c << endl;} Output: 5 5 5 If conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior. std::stof : It convert string into float.Syntax:float stof( const string& str, size_t* pos = 0 ); float stof( const wstring& str, size_t* pos = 0 ); Parameters str : the string to convert pos : address of an integer to store the number of characters processed This parameter can also be a null pointer, in which case it is not used. Return value: it returns value of type float.Example 1:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = "20"; float y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:22.5 Example 2:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = "5000.5"; float x = std::stof(str); std::cout << x; return 0;}Output:5000.5 If no conversion could be performed, an invalid_argument exception is thrown. float stof( const string& str, size_t* pos = 0 ); float stof( const wstring& str, size_t* pos = 0 ); Parameters str : the string to convert pos : address of an integer to store the number of characters processed This parameter can also be a null pointer, in which case it is not used. Return value: it returns value of type float. Example 1: // CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = "20"; float y = std::stof(x) + 2.5; std::cout << y; return 0;} Output: 22.5 Example 2: // CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = "5000.5"; float x = std::stof(str); std::cout << x; return 0;} Output: 5000.5 If no conversion could be performed, an invalid_argument exception is thrown. std::stold : It convert string into long double.Syntax:long double stold( const string& str, size_t *pos = 0 ); long double stold (const wstring& str, size_t* pos = 0); Parameters : str : the string to convert pos : address of integer to store the index of the first unconverted character. This parameter can also be a null pointer, in which case it is not used. Return value : it returns value of type long double. Examples 1:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = "500087"; long double x = std::stold(str); std::cout << x; return 0;}Output:500087 Example 2:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = "2075"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:2077.5 long double stold( const string& str, size_t *pos = 0 ); long double stold (const wstring& str, size_t* pos = 0); Parameters : str : the string to convert pos : address of integer to store the index of the first unconverted character. This parameter can also be a null pointer, in which case it is not used. Return value : it returns value of type long double. Examples 1: // CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = "500087"; long double x = std::stold(str); std::cout << x; return 0;} Output: 500087 Example 2: // CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = "2075"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;} Output: 2077.5 This article is contributed by Shivani Ghughtyal. 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. papun007 CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++ C++ Classes and Objects Socket Programming in C/C++ Bitwise Operators in C/C++ Operator Overloading in C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples
[ { "code": null, "e": 24267, "s": 24239, "text": "\n29 Oct, 2018" }, { "code": null, "e": 27279, "s": 24267, "text": "std::stod() : It convert string into double.Syntax:double stod( const std::string& str, std::size_t* pos = 0 );\ndouble stod( const std::wstring& str, std::size_t* pos = 0 );\nReturn Value: return a value of type double\nParameters\nstr : the string to convert\npos : address of an integer to store the \nnumber of characters processed. This parameter can also be \na null pointer, in which case it is not used.\n// CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = \"y=4.4786754x+5.6\"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the \"value\" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;}Output:5.6\nAnother Example :// CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = \"5\"; double a = stod(b); int c = stoi(b); cout << b << \" \" << a << \" \" << c << endl;}Output:5 5 5\nIf conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior.std::stof : It convert string into float.Syntax:float stof( const string& str, size_t* pos = 0 );\nfloat stof( const wstring& str, size_t* pos = 0 );\nParameters\nstr : the string to convert\npos : address of an integer to store the number of characters processed\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value: it returns value of type float.Example 1:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = \"20\"; float y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:22.5\nExample 2:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = \"5000.5\"; float x = std::stof(str); std::cout << x; return 0;}Output:5000.5\nIf no conversion could be performed, an invalid_argument exception is thrown.std::stold : It convert string into long double.Syntax:long double stold( const string& str, size_t *pos = 0 );\nlong double stold (const wstring& str, size_t* pos = 0);\nParameters : \nstr : the string to convert\npos : address of integer to store the index of the first unconverted character.\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value : it returns value of type long double.\nExamples 1:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = \"500087\"; long double x = std::stold(str); std::cout << x; return 0;}Output:500087\nExample 2:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = \"2075\"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:2077.5\n" }, { "code": null, "e": 28571, "s": 27279, "text": "std::stod() : It convert string into double.Syntax:double stod( const std::string& str, std::size_t* pos = 0 );\ndouble stod( const std::wstring& str, std::size_t* pos = 0 );\nReturn Value: return a value of type double\nParameters\nstr : the string to convert\npos : address of an integer to store the \nnumber of characters processed. This parameter can also be \na null pointer, in which case it is not used.\n// CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = \"y=4.4786754x+5.6\"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the \"value\" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;}Output:5.6\nAnother Example :// CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = \"5\"; double a = stod(b); int c = stoi(b); cout << b << \" \" << a << \" \" << c << endl;}Output:5 5 5\nIf conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior." }, { "code": null, "e": 28926, "s": 28571, "text": "double stod( const std::string& str, std::size_t* pos = 0 );\ndouble stod( const std::wstring& str, std::size_t* pos = 0 );\nReturn Value: return a value of type double\nParameters\nstr : the string to convert\npos : address of an integer to store the \nnumber of characters processed. This parameter can also be \na null pointer, in which case it is not used.\n" }, { "code": "// CPP program to illustrate// std::stod()#include <string>#include <iostream> int main(void) { std::string str = \"y=4.4786754x+5.6\"; double y, x, a, b; y = 0; x = 0; // offset will be set to the length of // characters of the \"value\" - 1. std::size_t offset = 0; a = std::stod(&str[2], &offset); b = std::stod(&str[offset + 3]); std::cout << b; return 0;}", "e": 29327, "s": 28926, "text": null }, { "code": null, "e": 29335, "s": 29327, "text": "Output:" }, { "code": null, "e": 29340, "s": 29335, "text": "5.6\n" }, { "code": null, "e": 29358, "s": 29340, "text": "Another Example :" }, { "code": "// CPP program to illustrate// std::stod()#include <iostream>#include <string>using namespace std;int main(){ string b = \"5\"; double a = stod(b); int c = stoi(b); cout << b << \" \" << a << \" \" << c << endl;}", "e": 29579, "s": 29358, "text": null }, { "code": null, "e": 29587, "s": 29579, "text": "Output:" }, { "code": null, "e": 29594, "s": 29587, "text": "5 5 5\n" }, { "code": null, "e": 29820, "s": 29594, "text": "If conversion is not performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a double an out_of_range exception is thrown. An invalid idx causes undefined behavior." }, { "code": null, "e": 30690, "s": 29820, "text": "std::stof : It convert string into float.Syntax:float stof( const string& str, size_t* pos = 0 );\nfloat stof( const wstring& str, size_t* pos = 0 );\nParameters\nstr : the string to convert\npos : address of an integer to store the number of characters processed\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value: it returns value of type float.Example 1:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = \"20\"; float y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:22.5\nExample 2:// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = \"5000.5\"; float x = std::stof(str); std::cout << x; return 0;}Output:5000.5\nIf no conversion could be performed, an invalid_argument exception is thrown." }, { "code": null, "e": 31021, "s": 30690, "text": "float stof( const string& str, size_t* pos = 0 );\nfloat stof( const wstring& str, size_t* pos = 0 );\nParameters\nstr : the string to convert\npos : address of an integer to store the number of characters processed\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value: it returns value of type float." }, { "code": null, "e": 31032, "s": 31021, "text": "Example 1:" }, { "code": "// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string x; x = \"20\"; float y = std::stof(x) + 2.5; std::cout << y; return 0;}", "e": 31219, "s": 31032, "text": null }, { "code": null, "e": 31227, "s": 31219, "text": "Output:" }, { "code": null, "e": 31233, "s": 31227, "text": "22.5\n" }, { "code": null, "e": 31244, "s": 31233, "text": "Example 2:" }, { "code": "// CPP program to illustrate// std::stof()#include <iostream>#include <string>int main(){ std::string str = \"5000.5\"; float x = std::stof(str); std::cout << x; return 0;}", "e": 31427, "s": 31244, "text": null }, { "code": null, "e": 31435, "s": 31427, "text": "Output:" }, { "code": null, "e": 31443, "s": 31435, "text": "5000.5\n" }, { "code": null, "e": 31521, "s": 31443, "text": "If no conversion could be performed, an invalid_argument exception is thrown." }, { "code": null, "e": 32373, "s": 31521, "text": "std::stold : It convert string into long double.Syntax:long double stold( const string& str, size_t *pos = 0 );\nlong double stold (const wstring& str, size_t* pos = 0);\nParameters : \nstr : the string to convert\npos : address of integer to store the index of the first unconverted character.\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value : it returns value of type long double.\nExamples 1:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = \"500087\"; long double x = std::stold(str); std::cout << x; return 0;}Output:500087\nExample 2:// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = \"2075\"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;}Output:2077.5\n" }, { "code": null, "e": 32736, "s": 32373, "text": "long double stold( const string& str, size_t *pos = 0 );\nlong double stold (const wstring& str, size_t* pos = 0);\nParameters : \nstr : the string to convert\npos : address of integer to store the index of the first unconverted character.\nThis parameter can also be a null pointer, in which case it is not used.\nReturn value : it returns value of type long double.\n" }, { "code": null, "e": 32748, "s": 32736, "text": "Examples 1:" }, { "code": "// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string str = \"500087\"; long double x = std::stold(str); std::cout << x; return 0;}", "e": 32939, "s": 32748, "text": null }, { "code": null, "e": 32947, "s": 32939, "text": "Output:" }, { "code": null, "e": 32955, "s": 32947, "text": "500087\n" }, { "code": null, "e": 32966, "s": 32955, "text": "Example 2:" }, { "code": "// CPP program to illustrate// std::stold()#include <iostream>#include <string>int main(){ std::string x; x = \"2075\"; long double y = std::stof(x) + 2.5; std::cout << y; return 0;}", "e": 33162, "s": 32966, "text": null }, { "code": null, "e": 33170, "s": 33162, "text": "Output:" }, { "code": null, "e": 33178, "s": 33170, "text": "2077.5\n" }, { "code": null, "e": 33483, "s": 33178, "text": "This article is contributed by Shivani Ghughtyal. 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": 33608, "s": 33483, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33617, "s": 33608, "text": "papun007" }, { "code": null, "e": 33629, "s": 33617, "text": "CPP-Library" }, { "code": null, "e": 33633, "s": 33629, "text": "STL" }, { "code": null, "e": 33637, "s": 33633, "text": "C++" }, { "code": null, "e": 33641, "s": 33637, "text": "STL" }, { "code": null, "e": 33645, "s": 33641, "text": "CPP" }, { "code": null, "e": 33743, "s": 33645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33752, "s": 33743, "text": "Comments" }, { "code": null, "e": 33765, "s": 33752, "text": "Old Comments" }, { "code": null, "e": 33808, "s": 33765, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 33827, "s": 33808, "text": "Inheritance in C++" }, { "code": null, "e": 33847, "s": 33827, "text": "Constructors in C++" }, { "code": null, "e": 33871, "s": 33847, "text": "C++ Classes and Objects" }, { "code": null, "e": 33899, "s": 33871, "text": "Socket Programming in C/C++" }, { "code": null, "e": 33926, "s": 33899, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33954, "s": 33926, "text": "Operator Overloading in C++" }, { "code": null, "e": 33978, "s": 33954, "text": "Copy Constructor in C++" }, { "code": null, "e": 34002, "s": 33978, "text": "Virtual Function in C++" } ]
Digit sum upto a number of digits of a number in JavaScript
We are required to write a JavaScript function that takes in two numbers, let’s say m and n as arguments. n will always be smaller than or equal to the number of digits present in m. The function should calculate and return the sum of first n digits of m. For example − If the input numbers are − const m = 5465767; const n = 4; Then the output should be − const output = 20; because 5 + 4 + 6 + 5 = 20 Following is the code − const m = 5465767; const n = 4; const digitSumUpto = (m, n) => { if(n > String(m).length){ return 0; }; let sum = 0; for(let i = 0; i < n; i++){ const el = +String(m)[i]; sum += el; }; return sum; }; console.log(digitSumUpto(m, n)); Following is the console output − 20
[ { "code": null, "e": 1168, "s": 1062, "text": "We are required to write a JavaScript function that takes in two numbers, let’s say m and n as arguments." }, { "code": null, "e": 1318, "s": 1168, "text": "n will always be smaller than or equal to the number of digits present in m. The function should calculate and return the sum of first n digits of m." }, { "code": null, "e": 1332, "s": 1318, "text": "For example −" }, { "code": null, "e": 1359, "s": 1332, "text": "If the input numbers are −" }, { "code": null, "e": 1391, "s": 1359, "text": "const m = 5465767;\nconst n = 4;" }, { "code": null, "e": 1419, "s": 1391, "text": "Then the output should be −" }, { "code": null, "e": 1438, "s": 1419, "text": "const output = 20;" }, { "code": null, "e": 1465, "s": 1438, "text": "because 5 + 4 + 6 + 5 = 20" }, { "code": null, "e": 1489, "s": 1465, "text": "Following is the code −" }, { "code": null, "e": 1758, "s": 1489, "text": "const m = 5465767;\nconst n = 4;\nconst digitSumUpto = (m, n) => {\n if(n > String(m).length){\n return 0;\n };\n let sum = 0;\n for(let i = 0; i < n; i++){\n const el = +String(m)[i];\n sum += el;\n };\n return sum;\n};\nconsole.log(digitSumUpto(m, n));" }, { "code": null, "e": 1792, "s": 1758, "text": "Following is the console output −" }, { "code": null, "e": 1795, "s": 1792, "text": "20" } ]
How to add and remove names on button click with JavaScript?
To create, use add() method, whereas to delete created and appended element, you can use remove(). Following is the code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css"> <style> </style> </head> <body> <div class=""> <ul id="listOfName"></ul> </div> <div class=""> <h1 class="">Add A New Name</h1> <div class=""> <input type="text" id="name" placeholder="Add Name......"> <button class="btn" id="addNameButton">AddName</button> </div> </div> </div> <script> var givenName = document.querySelector('#name') var btnClass = document.querySelector('#addNameButton') var listOfName = document.querySelector('#listOfName') btnClass.addEventListener('click', () => { var actualName = givenName.value if (actualName.length != 0) { var createAnHTMLList = `<li class=""><div>${actualName}</div><button onclick="removeNameFromTheList(this)">Remove Name</button>` listOfName.innerHTML += createAnHTMLList givenName.value = '' givenName.classList.remove('red') } else{ givenName.classList.add('red') } }) function removeNameFromTheList(e) { e.parentElement.remove() } </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − Here, I am adding two names, which are John, David. The snapshot is as follows. Let’s first add “John” and click “AddName” − Click the “AddName” button. You will get following output − Now you can do with David also. After adding both the names, you will get the following sample output. Now, I am going to remove the name ‘John’. This will produce the following output −
[ { "code": null, "e": 1185, "s": 1062, "text": "To create, use add() method, whereas to delete created and appended element, you can use\nremove(). Following is the code −" }, { "code": null, "e": 1196, "s": 1185, "text": " Live Demo" }, { "code": null, "e": 2704, "s": 1196, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/\n4.7.0/css/font-awesome.min.css\">\n<style>\n</style>\n</head>\n<body>\n<div class=\"\">\n<ul id=\"listOfName\"></ul>\n</div>\n<div class=\"\">\n<h1 class=\"\">Add A New Name</h1>\n<div class=\"\">\n<input type=\"text\" id=\"name\" placeholder=\"Add Name......\">\n<button class=\"btn\" id=\"addNameButton\">AddName</button>\n</div>\n</div>\n</div>\n<script>\n var givenName = document.querySelector('#name')\n var btnClass = document.querySelector('#addNameButton')\n var listOfName = document.querySelector('#listOfName')\n btnClass.addEventListener('click', () => {\n var actualName = givenName.value\n if (actualName.length != 0) {\n var createAnHTMLList = `<li class=\"\"><div>${actualName}</div><button\n onclick=\"removeNameFromTheList(this)\">Remove Name</button>`\n listOfName.innerHTML += createAnHTMLList\n givenName.value = ''\n givenName.classList.remove('red')\n } else{\n givenName.classList.add('red')\n }\n })\n function removeNameFromTheList(e) {\n e.parentElement.remove()\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2866, "s": 2704, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2907, "s": 2866, "text": "This will produce the following output −" }, { "code": null, "e": 3032, "s": 2907, "text": "Here, I am adding two names, which are John, David. The snapshot is as follows. Let’s first add\n“John” and click “AddName” −" }, { "code": null, "e": 3092, "s": 3032, "text": "Click the “AddName” button. You will get following output −" }, { "code": null, "e": 3195, "s": 3092, "text": "Now you can do with David also. After adding both the names, you will get the following sample\noutput." }, { "code": null, "e": 3279, "s": 3195, "text": "Now, I am going to remove the name ‘John’. This will produce the following output −" } ]
Intersection of two arrays in C#
To get intersection of two arrays, use the Intersect method. It is an extension method from the System.Linq namespace. The method returns the common elements between the two arrays. Set the two arrays first − int[] arr1 = { 44, 76, 98, 34 }; int[] arr2 = { 24, 98, 44, 55, 47, 86 }; Now use the Intersect on both the arrays − Arr1.Intersect(arr2); The following is the complete code − Live Demo using System; using System.Linq; class Program { static void Main() { int[] arr1 = { 44, 76, 98, 34 }; int[] arr2 = { 24, 98, 44, 55, 47, 86 }; var intersect = arr1.Intersect(arr2); foreach (int res in intersect) { Console.WriteLine(res); } } } 44 98
[ { "code": null, "e": 1181, "s": 1062, "text": "To get intersection of two arrays, use the Intersect method. It is an extension method from the System.Linq namespace." }, { "code": null, "e": 1244, "s": 1181, "text": "The method returns the common elements between the two arrays." }, { "code": null, "e": 1271, "s": 1244, "text": "Set the two arrays first −" }, { "code": null, "e": 1345, "s": 1271, "text": "int[] arr1 = { 44, 76, 98, 34 };\nint[] arr2 = { 24, 98, 44, 55, 47, 86 };" }, { "code": null, "e": 1388, "s": 1345, "text": "Now use the Intersect on both the arrays −" }, { "code": null, "e": 1410, "s": 1388, "text": "Arr1.Intersect(arr2);" }, { "code": null, "e": 1447, "s": 1410, "text": "The following is the complete code −" }, { "code": null, "e": 1458, "s": 1447, "text": " Live Demo" }, { "code": null, "e": 1749, "s": 1458, "text": "using System;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n int[] arr1 = { 44, 76, 98, 34 };\n int[] arr2 = { 24, 98, 44, 55, 47, 86 };\n var intersect = arr1.Intersect(arr2);\n foreach (int res in intersect) {\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1755, "s": 1749, "text": "44\n98" } ]
Nuts and Bolts Problem | Practice | GeeksforGeeks
Given a set of N nuts of different sizes and N bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller. The elements should follow the following order ! # $ % & * @ ^ ~ . Example 1: Input: N = 5 nuts[] = {@, %, $, #, ^} bolts[] = {%, @, #, $ ^} Output: # $ % @ ^ # $ % @ ^ Example 2: Input: N = 9 nuts[] = {^, &, %, @, #, *, $, ~, !} bolts[] = {~, #, @, %, &, *, $ ,^, !} Output: ! # $ % & * @ ^ ~ ! # $ % & * @ ^ ~ Your Task: You don't need to read input or print anything. Your task is to complete the function matchPairs() which takes an array of characters nuts[], bolts[] and n as parameters and returns void. You need to change the array itself. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 9 Array of Nuts/Bolts can only consist of the following elements:{'@', '#', '$', '%', '^', '&', '~', '*', '!'}. 0 jrm6lrcrp3lcpybdms0n4rk0xpecvc73ulg3nna31 month ago python code 0.0/1.6 time taken: def matchPairs(self,nuts, bolts, n): # code here s=['!','#', '$','%', '&', '*' ,'@' ,'^' ,'~'] d=0 for i in s: if i in nuts: nuts.remove(i) bolts.remove(i) nuts.insert(d,i) bolts.insert(d,i) d+=1 0 artistdarkangel1 month ago Java code : O(N) time complexity O(1) Space complexity. All test cases pass. class Solution { void matchPairs(char nuts[], char bolts[], int n) { HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); hm.put('!',0); hm.put('#',1); hm.put('$',2); hm.put('%',3); hm.put('&',4); hm.put('*',5); hm.put('@',6); hm.put('^',7); hm.put('~',8); HashMap<Integer, Character> hm2 = new HashMap<Integer, Character>(); hm2.put(0,'!'); hm2.put(1,'#'); hm2.put(2,'$'); hm2.put(3,'%'); hm2.put(4,'&'); hm2.put(5,'*'); hm2.put(6,'@'); hm2.put(7,'^'); hm2.put(8,'~'); int temp[] = new int[9]; for(int i=0; i<n; i++) { temp[hm.get(nuts[i])]=1; } int k=0; for(int i=0; i<9; i++) { if(temp[i]==1) { nuts[k]=hm2.get(i); bolts[k]=nuts[k]; k++; } } }} 0 ayazmrz981 month ago def matchPairs(self,nuts, bolts, n): nuts.sort() bolts.sort() 0 satyapani9991 month ago Simple Hashset approach... 0.2/1.5 class Solution { void matchPairs(char nuts[], char bolts[], int n) { // code here HashSet<Character> set = new LinkedHashSet<>(); set.add('!'); set.add('#'); set.add('$'); set.add('%'); set.add('&'); set.add('*'); set.add('@'); set.add('^'); set.add('~'); HashSet<Character> hs= new HashSet<>(); for(int i=0;i<n;i++) { hs.add(nuts[i]); } int j=0; for(char i:set) { if(j<n && hs.contains(i)) { nuts[j] = i; bolts[j] = i; j++; } } }} 0 yashkotalwar101 month ago //JAVA // 1 HashMap<Character, Integer> rule = new HashMap<>(); rule.put('!',0); rule.put('#',1); rule.put('$',2); rule.put('%',3); rule.put('&',4); rule.put('*',5); rule.put('@',6); rule.put('^',7); rule.put('~',8); char ch; for(int i=0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if(rule.get(nuts[i])>rule.get(nuts[j])){ ch = nuts[i]; nuts[i] = nuts[j]; nuts[j] = ch; } if(rule.get(bolts[i])>rule.get(bolts[j])){ ch = bolts[i]; bolts[i] = bolts[j]; bolts[j] = ch; } } } // 2 Arrays.sort(nuts); Arrays.sort(bolts); 0 narendranathmaddikeri20072 months ago #JAVA CODE class Solution { void matchPairs(char nuts[], char bolts[], int n) { Arrays.sort(nuts); Arrays.sort(bolts); }} 0 mohammadtanveer75402 months ago class Solution{ public: void matchPairs(char nuts[], char bolts[], int n) { sort(nuts, nuts+n); sort(bolts, bolts+n); } }; -1 mdsaif04052 months ago class Solution{ public: void matchPairs(char nuts[], char bolts[], int n) { vector<char>v1; vector<char>v2; sort(nuts,nuts+n); sort(bolts,bolts+n); } }; +1 shineinsa2 months ago #include<vector>class Solution{public: void matchPairs(char nuts[], char bolts[], int n) { // code here// int m=nuts.length();// int n=bolts.length();vector<char>v1;vector<char>v2;sort(nuts,nuts+n);sort(bolts,bolts+n);for(int i=0;i<n;i++){ if(nuts[i]==bolts[i]){ v1.push_back(nuts[i]); v2.push_back(bolts[i]); }} } }; 0 sharmasheli222 months ago //JAVASCRIPT //const nuts = [ '@','%','$','#','^']; //const bolts = ['%','@','#','$','^']; //let a = ['!#$%&*@^~']; let nut = nuts.sort(); let bolt = bolts.sort(); console.log(nut); console.log(bolt); 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": 396, "s": 238, "text": "Given a set of N nuts of different sizes and N bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently." }, { "code": null, "e": 659, "s": 396, "text": "Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller.\nThe elements should follow the following order ! # $ % & * @ ^ ~ ." }, { "code": null, "e": 670, "s": 659, "text": "Example 1:" }, { "code": null, "e": 764, "s": 670, "text": "Input: \nN = 5\nnuts[] = {@, %, $, #, ^}\nbolts[] = {%, @, #, $ ^}\nOutput: \n# $ % @ ^\n# $ % @ ^\n" }, { "code": null, "e": 775, "s": 764, "text": "Example 2:" }, { "code": null, "e": 910, "s": 775, "text": "Input: \nN = 9\nnuts[] = {^, &, %, @, #, *, $, ~, !}\nbolts[] = {~, #, @, %, &, *, $ ,^, !}\nOutput: \n! # $ % & * @ ^ ~\n! # $ % & * @ ^ ~\n" }, { "code": null, "e": 1148, "s": 910, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function matchPairs() which takes an array of characters nuts[], bolts[] and n as parameters and returns void. You need to change the array itself." }, { "code": null, "e": 1214, "s": 1148, "text": "Expected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1351, "s": 1214, "text": "Constraints:\n1 <= N <= 9\nArray of Nuts/Bolts can only consist of the following elements:{'@', '#', '$', '%', '^', '&', '~', '*', '!'}.\n " }, { "code": null, "e": 1353, "s": 1351, "text": "0" }, { "code": null, "e": 1405, "s": 1353, "text": "jrm6lrcrp3lcpybdms0n4rk0xpecvc73ulg3nna31 month ago" }, { "code": null, "e": 1438, "s": 1405, "text": "python code 0.0/1.6 time taken:" }, { "code": null, "e": 1680, "s": 1440, "text": "def matchPairs(self,nuts, bolts, n): # code here s=['!','#', '$','%', '&', '*' ,'@' ,'^' ,'~'] d=0 for i in s: if i in nuts: nuts.remove(i) bolts.remove(i) nuts.insert(d,i) bolts.insert(d,i) d+=1" }, { "code": null, "e": 1686, "s": 1684, "text": "0" }, { "code": null, "e": 1713, "s": 1686, "text": "artistdarkangel1 month ago" }, { "code": null, "e": 1790, "s": 1713, "text": "Java code : O(N) time complexity O(1) Space complexity. All test cases pass." }, { "code": null, "e": 1861, "s": 1790, "text": "class Solution { void matchPairs(char nuts[], char bolts[], int n) {" }, { "code": null, "e": 2750, "s": 1861, "text": " HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); hm.put('!',0); hm.put('#',1); hm.put('$',2); hm.put('%',3); hm.put('&',4); hm.put('*',5); hm.put('@',6); hm.put('^',7); hm.put('~',8); HashMap<Integer, Character> hm2 = new HashMap<Integer, Character>(); hm2.put(0,'!'); hm2.put(1,'#'); hm2.put(2,'$'); hm2.put(3,'%'); hm2.put(4,'&'); hm2.put(5,'*'); hm2.put(6,'@'); hm2.put(7,'^'); hm2.put(8,'~'); int temp[] = new int[9]; for(int i=0; i<n; i++) { temp[hm.get(nuts[i])]=1; } int k=0; for(int i=0; i<9; i++) { if(temp[i]==1) { nuts[k]=hm2.get(i); bolts[k]=nuts[k]; k++; } } }}" }, { "code": null, "e": 2752, "s": 2750, "text": "0" }, { "code": null, "e": 2773, "s": 2752, "text": "ayazmrz981 month ago" }, { "code": null, "e": 2837, "s": 2773, "text": "def matchPairs(self,nuts, bolts, n):\n nuts.sort()\n bolts.sort()" }, { "code": null, "e": 2839, "s": 2837, "text": "0" }, { "code": null, "e": 2863, "s": 2839, "text": "satyapani9991 month ago" }, { "code": null, "e": 2898, "s": 2863, "text": "Simple Hashset approach... 0.2/1.5" }, { "code": null, "e": 3432, "s": 2900, "text": "class Solution { void matchPairs(char nuts[], char bolts[], int n) { // code here HashSet<Character> set = new LinkedHashSet<>(); set.add('!'); set.add('#'); set.add('$'); set.add('%'); set.add('&'); set.add('*'); set.add('@'); set.add('^'); set.add('~'); HashSet<Character> hs= new HashSet<>(); for(int i=0;i<n;i++) { hs.add(nuts[i]); } int j=0; for(char i:set) { if(j<n && hs.contains(i)) { nuts[j] = i; bolts[j] = i; j++; } } }}" }, { "code": null, "e": 3434, "s": 3432, "text": "0" }, { "code": null, "e": 3460, "s": 3434, "text": "yashkotalwar101 month ago" }, { "code": null, "e": 3467, "s": 3460, "text": "//JAVA" }, { "code": null, "e": 3472, "s": 3467, "text": "// 1" }, { "code": null, "e": 4204, "s": 3472, "text": "HashMap<Character, Integer> rule = new HashMap<>(); rule.put('!',0); rule.put('#',1); rule.put('$',2); rule.put('%',3); rule.put('&',4); rule.put('*',5); rule.put('@',6); rule.put('^',7); rule.put('~',8); char ch; for(int i=0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if(rule.get(nuts[i])>rule.get(nuts[j])){ ch = nuts[i]; nuts[i] = nuts[j]; nuts[j] = ch; } if(rule.get(bolts[i])>rule.get(bolts[j])){ ch = bolts[i]; bolts[i] = bolts[j]; bolts[j] = ch; } } }" }, { "code": null, "e": 4211, "s": 4206, "text": "// 2" }, { "code": null, "e": 4230, "s": 4211, "text": "Arrays.sort(nuts);" }, { "code": null, "e": 4250, "s": 4230, "text": "Arrays.sort(bolts);" }, { "code": null, "e": 4252, "s": 4250, "text": "0" }, { "code": null, "e": 4290, "s": 4252, "text": "narendranathmaddikeri20072 months ago" }, { "code": null, "e": 4301, "s": 4290, "text": "#JAVA CODE" }, { "code": null, "e": 4431, "s": 4301, "text": "class Solution { void matchPairs(char nuts[], char bolts[], int n) { Arrays.sort(nuts); Arrays.sort(bolts); }}" }, { "code": null, "e": 4433, "s": 4431, "text": "0" }, { "code": null, "e": 4465, "s": 4433, "text": "mohammadtanveer75402 months ago" }, { "code": null, "e": 4596, "s": 4465, "text": "class Solution{\npublic:\t\n\tvoid matchPairs(char nuts[], char bolts[], int n) {\n\t sort(nuts, nuts+n); sort(bolts, bolts+n);\n\t}\n};" }, { "code": null, "e": 4599, "s": 4596, "text": "-1" }, { "code": null, "e": 4622, "s": 4599, "text": "mdsaif04052 months ago" }, { "code": null, "e": 4815, "s": 4622, "text": "class Solution{\npublic:\t\n void matchPairs(char nuts[], char bolts[], int n) \n {\n vector<char>v1;\n vector<char>v2;\n sort(nuts,nuts+n);\n sort(bolts,bolts+n);\n }\n};" }, { "code": null, "e": 4818, "s": 4815, "text": "+1" }, { "code": null, "e": 4840, "s": 4818, "text": "shineinsa2 months ago" }, { "code": null, "e": 4879, "s": 4840, "text": "#include<vector>class Solution{public:" }, { "code": null, "e": 5176, "s": 4879, "text": "void matchPairs(char nuts[], char bolts[], int n) { // code here// int m=nuts.length();// int n=bolts.length();vector<char>v1;vector<char>v2;sort(nuts,nuts+n);sort(bolts,bolts+n);for(int i=0;i<n;i++){ if(nuts[i]==bolts[i]){ v1.push_back(nuts[i]); v2.push_back(bolts[i]); }}" }, { "code": null, "e": 5178, "s": 5176, "text": "}" }, { "code": null, "e": 5181, "s": 5178, "text": "};" }, { "code": null, "e": 5183, "s": 5181, "text": "0" }, { "code": null, "e": 5209, "s": 5183, "text": "sharmasheli222 months ago" }, { "code": null, "e": 5223, "s": 5209, "text": "//JAVASCRIPT " }, { "code": null, "e": 5264, "s": 5225, "text": "//const nuts = [ '@','%','$','#','^'];" }, { "code": null, "e": 5303, "s": 5264, "text": "//const bolts = ['%','@','#','$','^'];" }, { "code": null, "e": 5328, "s": 5303, "text": "//let a = ['!#$%&*@^~'];" }, { "code": null, "e": 5351, "s": 5328, "text": "let nut = nuts.sort();" }, { "code": null, "e": 5376, "s": 5351, "text": "let bolt = bolts.sort();" }, { "code": null, "e": 5394, "s": 5376, "text": "console.log(nut);" }, { "code": null, "e": 5413, "s": 5394, "text": "console.log(bolt);" }, { "code": null, "e": 5559, "s": 5413, "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": 5595, "s": 5559, "text": " Login to access your submissions. " }, { "code": null, "e": 5605, "s": 5595, "text": "\nProblem\n" }, { "code": null, "e": 5615, "s": 5605, "text": "\nContest\n" }, { "code": null, "e": 5678, "s": 5615, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5826, "s": 5678, "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": 6034, "s": 5826, "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": 6140, "s": 6034, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Gradle - Installation
Gradle is a build tool based on java. There are some prerequisites that are required to be installed before installing the Gradle frame work. JDK and Groovy are the prerequisites for Gradle installation. Gradle requires JDK version 6 or later to be installed in the system. It uses the JDK libraries which are installed, and sets to the JAVA_HOME environmental variable. Gradle carries its own Groovy library, therefore, we need not install Groovy explicitly. If it is installed, that is ignored by Gradle. The steps to install Gradle in your system are explained below. First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute Java –version command in any of the platform you are working on. Execute the following command to verify Java installation. I have installed JDK 1.8 in my system. C:\> java - version Output The output is as follows − java version "1.8.0_66" Java(TM) SE Runtime Environment (build 1.8.0_66-b18) Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode) Execute the following command to verify Java installation.We have installed JDK 1.8 in the system. $ java - version Output java version "1.8.0_66" Java(TM) SE Runtime Environment (build 1.8.0_66-b18) Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode) We assume the readers of this tutorial have Java SDK version 1.8.0_66 installed on their system. Download the latest version of Gradle from the link available at https://gradle.org/install/. In the reference page, click on the Complete Distribution link. This step is common for any platform. For this you will get the complete distribution file into your Downloads folder. Setting up environment means, we have to extract the distribution file and copy the library files into proper location. Set up GRADLE_HOME and PATH environmental variables. This step is platform dependent. Extract the downloaded zip file named gradle-2.11-all.zip and copy the distribution files from Downloads\gradle-2.11\ to C:\gradle\ location. After that, add the C:\gradle and C:\gradle\bin directories to the GRADLE_HOME and PATH system variables. Follow the given instructions − Right Click On My Computers -> Click On Properties -> Advanced System Settings -> Click On Environmental Variables. There you will find a dialog box for creating and editing system variables. Click on new button for creating GRADLE_HOME variable (follow the left side screenshot). Click on Edit for editing the existing Path system variable (follow the right side screenshot). Follow the below given screenshots. Extract the downloaded zip file named gradle-2.11-all.zip then you will find an extracted file named gradle-2.11. You can use the following to move the distribution files from Downloads/gradle-2.11/ to /opt/gradle/ location. Execute this operation from the Downloads directory. $ sudo mv gradle-2.11 /opt/gradle Edit the ~/.bashrc file and paste the following content to it and save it. export ORIENT_HOME = /opt/gradle export PATH = $PATH: Execute the following command to execute ~/.bashrc file. $ source ~/.bashrc You can execute the following command in command prompt. C:\> gradle –v Output Here you will find the Gradle version. ------------------------------------------------------------ Gradle 2.11 ------------------------------------------------------------ Build time: 2016-02-08 07:59:16 UTC Build number: none Revision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978 Groovy: 2.4.4 Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013 JVM: 1.7.0_60 (Oracle Corporation 24.60-b09) OS: Windows 8.1 6.3 amd64 You can execute the following command in terminal. $ gradle –v Output Here you will find the Gradle version. ------------------------------------------------------------ Gradle 2.11 ------------------------------------------------------------ Build time: 2016-02-08 07:59:16 UTC Build number: none Revision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978 Groovy: 2.4.4 Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013 JVM: 1.7.0_60 (Oracle Corporation 24.60-b09) OS: Windows 8.1 6.3 amd64 You can execute the following command in terminal. $ gradle –v Output You will find the Gradle version. ------------------------------------------------------------ Gradle 2.11 ------------------------------------------------------------ Build time: 2016-02-08 07:59:16 UTC Build number: none Revision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978 Groovy: 2.4.4 Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013 JVM: 1.7.0_60 (Oracle Corporation 24.60-b09) OS: Linux 3.13.0-74-generic amd64 Print Add Notes Bookmark this page
[ { "code": null, "e": 2024, "s": 1882, "text": "Gradle is a build tool based on java. There are some prerequisites that are required to be installed before installing the Gradle frame work." }, { "code": null, "e": 2087, "s": 2024, "text": "JDK and Groovy are the prerequisites for Gradle installation. " }, { "code": null, "e": 2254, "s": 2087, "text": "Gradle requires JDK version 6 or later to be installed in the system. It uses the JDK libraries which are installed, and sets to the JAVA_HOME environmental variable." }, { "code": null, "e": 2390, "s": 2254, "text": "Gradle carries its own Groovy library, therefore, we need not install Groovy explicitly. If it is installed, that is ignored by Gradle." }, { "code": null, "e": 2454, "s": 2390, "text": "The steps to install Gradle in your system are explained below." }, { "code": null, "e": 2636, "s": 2454, "text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute Java –version command in any of the platform you are working on." }, { "code": null, "e": 2734, "s": 2636, "text": "Execute the following command to verify Java installation. I have installed JDK 1.8 in my system." }, { "code": null, "e": 2755, "s": 2734, "text": "C:\\> java - version\n" }, { "code": null, "e": 2762, "s": 2755, "text": "Output" }, { "code": null, "e": 2789, "s": 2762, "text": "The output is as follows −" }, { "code": null, "e": 2931, "s": 2789, "text": "java version \"1.8.0_66\"\nJava(TM) SE Runtime Environment (build 1.8.0_66-b18)\nJava HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode)\n" }, { "code": null, "e": 3030, "s": 2931, "text": "Execute the following command to verify Java installation.We have installed JDK 1.8 in the system." }, { "code": null, "e": 3047, "s": 3030, "text": "$ java - version" }, { "code": null, "e": 3054, "s": 3047, "text": "Output" }, { "code": null, "e": 3196, "s": 3054, "text": "java version \"1.8.0_66\"\nJava(TM) SE Runtime Environment (build 1.8.0_66-b18)\nJava HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode)\n" }, { "code": null, "e": 3293, "s": 3196, "text": "We assume the readers of this tutorial have Java SDK version 1.8.0_66 installed on their system." }, { "code": null, "e": 3570, "s": 3293, "text": "Download the latest version of Gradle from the link available at https://gradle.org/install/. In the reference page, click on the Complete Distribution link. This step is common for any platform. For this you will get the complete distribution file into your Downloads folder." }, { "code": null, "e": 3776, "s": 3570, "text": "Setting up environment means, we have to extract the distribution file and copy the library files into proper location. Set up GRADLE_HOME and PATH environmental variables. This step is platform dependent." }, { "code": null, "e": 3918, "s": 3776, "text": "Extract the downloaded zip file named gradle-2.11-all.zip and copy the distribution files from Downloads\\gradle-2.11\\ to C:\\gradle\\ location." }, { "code": null, "e": 4024, "s": 3918, "text": "After that, add the C:\\gradle and C:\\gradle\\bin directories to the GRADLE_HOME and PATH system variables." }, { "code": null, "e": 4172, "s": 4024, "text": "Follow the given instructions −\nRight Click On My Computers -> Click On Properties -> Advanced System Settings -> Click On Environmental Variables." }, { "code": null, "e": 4248, "s": 4172, "text": "There you will find a dialog box for creating and editing system variables." }, { "code": null, "e": 4337, "s": 4248, "text": "Click on new button for creating GRADLE_HOME variable (follow the left side screenshot)." }, { "code": null, "e": 4433, "s": 4337, "text": "Click on Edit for editing the existing Path system variable (follow the right side screenshot)." }, { "code": null, "e": 4469, "s": 4433, "text": "Follow the below given screenshots." }, { "code": null, "e": 4583, "s": 4469, "text": "Extract the downloaded zip file named gradle-2.11-all.zip then you will find an extracted file named gradle-2.11." }, { "code": null, "e": 4747, "s": 4583, "text": "You can use the following to move the distribution files from Downloads/gradle-2.11/ to /opt/gradle/ location. Execute this operation from the Downloads directory." }, { "code": null, "e": 4782, "s": 4747, "text": "$ sudo mv gradle-2.11 /opt/gradle\n" }, { "code": null, "e": 4857, "s": 4782, "text": "Edit the ~/.bashrc file and paste the following content to it and save it." }, { "code": null, "e": 4912, "s": 4857, "text": "export ORIENT_HOME = /opt/gradle\nexport PATH = $PATH:\n" }, { "code": null, "e": 4969, "s": 4912, "text": "Execute the following command to execute ~/.bashrc file." }, { "code": null, "e": 4989, "s": 4969, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 5046, "s": 4989, "text": "You can execute the following command in command prompt." }, { "code": null, "e": 5062, "s": 5046, "text": "C:\\> gradle –v\n" }, { "code": null, "e": 5069, "s": 5062, "text": "Output" }, { "code": null, "e": 5108, "s": 5069, "text": "Here you will find the Gradle version." }, { "code": null, "e": 5499, "s": 5108, "text": "------------------------------------------------------------\nGradle 2.11\n------------------------------------------------------------\n\nBuild time: 2016-02-08 07:59:16 UTC\nBuild number: none\nRevision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978\nGroovy: 2.4.4\n\nAnt: Apache Ant(TM) version 1.9.3 compiled on December 23 2013\nJVM: 1.7.0_60 (Oracle Corporation 24.60-b09)\nOS: Windows 8.1 6.3 amd64\n" }, { "code": null, "e": 5550, "s": 5499, "text": "You can execute the following command in terminal." }, { "code": null, "e": 5563, "s": 5550, "text": "$ gradle –v\n" }, { "code": null, "e": 5570, "s": 5563, "text": "Output" }, { "code": null, "e": 5609, "s": 5570, "text": "Here you will find the Gradle version." }, { "code": null, "e": 6001, "s": 5609, "text": "------------------------------------------------------------\nGradle 2.11\n------------------------------------------------------------\n\nBuild time: 2016-02-08 07:59:16 UTC\nBuild number: none\nRevision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978\n\nGroovy: 2.4.4\nAnt: Apache Ant(TM) version 1.9.3 compiled on December 23 2013\nJVM: 1.7.0_60 (Oracle Corporation 24.60-b09)\nOS: Windows 8.1 6.3 amd64 \n" }, { "code": null, "e": 6052, "s": 6001, "text": "You can execute the following command in terminal." }, { "code": null, "e": 6065, "s": 6052, "text": "$ gradle –v\n" }, { "code": null, "e": 6072, "s": 6065, "text": "Output" }, { "code": null, "e": 6106, "s": 6072, "text": "You will find the Gradle version." }, { "code": null, "e": 6503, "s": 6106, "text": "------------------------------------------------------------\nGradle 2.11\n------------------------------------------------------------\nBuild time: 2016-02-08 07:59:16 UTC\nBuild number: none\nRevision: 584db1c7c90bdd1de1d1c4c51271c665bfcba978\nGroovy: 2.4.4\nAnt: Apache Ant(TM) version 1.9.3 compiled on December 23 2013\nJVM: 1.7.0_60 (Oracle Corporation 24.60-b09)\nOS: Linux 3.13.0-74-generic amd64\n" }, { "code": null, "e": 6510, "s": 6503, "text": " Print" }, { "code": null, "e": 6521, "s": 6510, "text": " Add Notes" } ]
How to create a two dimensional array in JavaScript?
A two-dimensional array has more than one dimension, such as myarray[0][0] for element one, myarray[0][1] for element two, etc. To create a two-dimensional array in JavaScript, you can try to run the following code − Live Demo <html> <body> <script> var myarray=new Array(3); for (i=0; i <3; i++) myarray[i]=new Array(3) myarray[0][0]="One" myarray[0][1]="Two" myarray[0][2]="Three" myarray[1][0]="Four" myarray[1][1]="Five" myarray[1][2]="Six" myarray[2][0]="Seven" myarray[2][1]="Eight" myarray[2][2]="Nine" document.write(myarray[2][0]); </script> </body> </html> Seven
[ { "code": null, "e": 1279, "s": 1062, "text": "A two-dimensional array has more than one dimension, such as myarray[0][0] for element one, myarray[0][1] for element two, etc. To create a two-dimensional array in JavaScript, you can try to run the following code −" }, { "code": null, "e": 1289, "s": 1279, "text": "Live Demo" }, { "code": null, "e": 1900, "s": 1289, "text": "<html> \n <body> \n <script> \n var myarray=new Array(3); \n for (i=0; i <3; i++) \n myarray[i]=new Array(3) \n myarray[0][0]=\"One\" \n myarray[0][1]=\"Two\" \n myarray[0][2]=\"Three\" \n myarray[1][0]=\"Four\" \n myarray[1][1]=\"Five\" \n myarray[1][2]=\"Six\" \n myarray[2][0]=\"Seven\" \n myarray[2][1]=\"Eight\" \n myarray[2][2]=\"Nine\" \n document.write(myarray[2][0]); \n </script> \n </body>\n</html>" }, { "code": null, "e": 1906, "s": 1900, "text": "Seven" } ]
GridLayouts in Kivy | Python
21 Oct, 2021 Kivy is a platform independent as it can be run on Android, IOS, Linux and Windows, etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Use this command To install kivy: pip install kivy Kivy Tutorial – Learn Kivy with Examples. Gridlayout is the function which creates the children and arrange them in a matrix format. It takes the available space(square) and divides that space into rows and columns then add the widgets accordingly to the resulting cells or grids. We can not explicitly place the widgets in a particular column/row. Each child is assigned a particular position automatically determined by the layout configuration and the child index in children list. A gridlayout must contain at least on input constraints i.e. cols and rows. If we do not specify the cols or rows to it, the layout gives you an exception. Now the Columns represent the width and the rows represents the height just like matrix. Initial the size is given by the col_default_width and row_default_height properties. We can force the default size by setting the col_force_default or row_force_default property. This will force the layout to ignore the width and size_hint properties of children and use the default size. To customize the size of a single column or row, use cols_minimum or rows_minimum. It is not necessary to give both rows and columns, it depends on the requirement. We can provide either both or anyone accordingly. In the given below example, all the widgets will have the same or equal size. By default, the size is (1, 1) so the child will take full size of the parent. Python3 # main.py# import the kivy moduleimport kivy # It’s required that the base Class# of your App inherits from the App class.from kivy.app import Appfrom kivy.uix.gridlayout import GridLayout # This class stores the info of .kv file# when it is called goes to my.kv fileclass MainWidget(GridLayout): pass # we are defining the Base Class of our Kivy Appclass myApp(App): def build(self): # return a MainWidget() as a root widget return MainWidget() if __name__ == '__main__': # Here the class MyApp is initialized # and its run() method called. myApp().run() Note : For understanding how to use .kv files, just visit this. Code #1: Python3 # my.kv file code here<MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' Button: text: 'World 1' Button: text: 'Hello 2' Button: text: 'World 2' Output: Note: To run this code you have to make the main.py python file for the above python code and another file my.kv file. Code #2: Now let’s fix the size of the buttons to 100px instead of the default size_hint_x = 1. Python3 # just do change in the above my.kv# (code #1) file else all are same.<MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' Output : Code #3: We can also fix the row height to a specific size. Python3 # just do change in the above my.kv# (code #1)file else all are same. <MainWidget>: cols: 2 rows: 2 row_force_default: True row_default_height: 40 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' Output: anikakapoor anikaseth98 gabaa406 Python-gui 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Oct, 2021" }, { "code": null, "e": 366, "s": 52, "text": "Kivy is a platform independent as it can be run on Android, IOS, Linux and Windows, etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 401, "s": 366, "text": "Use this command To install kivy: " }, { "code": null, "e": 418, "s": 401, "text": "pip install kivy" }, { "code": null, "e": 460, "s": 418, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 1060, "s": 460, "text": "Gridlayout is the function which creates the children and arrange them in a matrix format. It takes the available space(square) and divides that space into rows and columns then add the widgets accordingly to the resulting cells or grids. We can not explicitly place the widgets in a particular column/row. Each child is assigned a particular position automatically determined by the layout configuration and the child index in children list. A gridlayout must contain at least on input constraints i.e. cols and rows. If we do not specify the cols or rows to it, the layout gives you an exception. " }, { "code": null, "e": 1150, "s": 1060, "text": "Now the Columns represent the width and the rows represents the height just like matrix. " }, { "code": null, "e": 1440, "s": 1150, "text": "Initial the size is given by the col_default_width and row_default_height properties. We can force the default size by setting the col_force_default or row_force_default property. This will force the layout to ignore the width and size_hint properties of children and use the default size." }, { "code": null, "e": 1523, "s": 1440, "text": "To customize the size of a single column or row, use cols_minimum or rows_minimum." }, { "code": null, "e": 1655, "s": 1523, "text": "It is not necessary to give both rows and columns, it depends on the requirement. We can provide either both or anyone accordingly." }, { "code": null, "e": 1812, "s": 1655, "text": "In the given below example, all the widgets will have the same or equal size. By default, the size is (1, 1) so the child will take full size of the parent." }, { "code": null, "e": 1820, "s": 1812, "text": "Python3" }, { "code": "# main.py# import the kivy moduleimport kivy # It’s required that the base Class# of your App inherits from the App class.from kivy.app import Appfrom kivy.uix.gridlayout import GridLayout # This class stores the info of .kv file# when it is called goes to my.kv fileclass MainWidget(GridLayout): pass # we are defining the Base Class of our Kivy Appclass myApp(App): def build(self): # return a MainWidget() as a root widget return MainWidget() if __name__ == '__main__': # Here the class MyApp is initialized # and its run() method called. myApp().run()", "e": 2410, "s": 1820, "text": null }, { "code": null, "e": 2474, "s": 2410, "text": "Note : For understanding how to use .kv files, just visit this." }, { "code": null, "e": 2484, "s": 2474, "text": "Code #1: " }, { "code": null, "e": 2492, "s": 2484, "text": "Python3" }, { "code": "# my.kv file code here<MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' Button: text: 'World 1' Button: text: 'Hello 2' Button: text: 'World 2' ", "e": 2712, "s": 2492, "text": null }, { "code": null, "e": 2722, "s": 2712, "text": "Output: " }, { "code": null, "e": 2938, "s": 2722, "text": "Note: To run this code you have to make the main.py python file for the above python code and another file my.kv file. Code #2: Now let’s fix the size of the buttons to 100px instead of the default size_hint_x = 1." }, { "code": null, "e": 2946, "s": 2938, "text": "Python3" }, { "code": "# just do change in the above my.kv# (code #1) file else all are same.<MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' ", "e": 3299, "s": 2946, "text": null }, { "code": null, "e": 3310, "s": 3299, "text": "Output : " }, { "code": null, "e": 3370, "s": 3310, "text": "Code #3: We can also fix the row height to a specific size." }, { "code": null, "e": 3378, "s": 3370, "text": "Python3" }, { "code": "# just do change in the above my.kv# (code #1)file else all are same. <MainWidget>: cols: 2 rows: 2 row_force_default: True row_default_height: 40 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' ", "e": 3779, "s": 3378, "text": null }, { "code": null, "e": 3789, "s": 3779, "text": "Output: " }, { "code": null, "e": 3803, "s": 3791, "text": "anikakapoor" }, { "code": null, "e": 3815, "s": 3803, "text": "anikaseth98" }, { "code": null, "e": 3824, "s": 3815, "text": "gabaa406" }, { "code": null, "e": 3835, "s": 3824, "text": "Python-gui" }, { "code": null, "e": 3842, "s": 3835, "text": "Python" }, { "code": null, "e": 3940, "s": 3842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3968, "s": 3940, "text": "Read JSON file using Python" }, { "code": null, "e": 4018, "s": 3968, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4040, "s": 4018, "text": "Python map() function" }, { "code": null, "e": 4084, "s": 4040, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4126, "s": 4084, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4148, "s": 4126, "text": "Enumerate() in Python" }, { "code": null, "e": 4183, "s": 4148, "text": "Read a file line by line in Python" }, { "code": null, "e": 4209, "s": 4183, "text": "Python String | replace()" }, { "code": null, "e": 4241, "s": 4209, "text": "How to Install PIP on Windows ?" } ]
How to plot a subset of a dataframe in R ?
30 Jun, 2021 In this article, we will learn multiple approaches to plotting a subset of a Dataframe in R Programming Language. Here we will be using, R language’s inbuilt “USArrests” dataset. In this method, first a subset of the data is created base don some condition, and then it is plotted using plot function. Let us first create the subset of the data. Syntax: plot(subset( data, condition, select)) Parameters: data: dataframe condition: indicates the logical expression on the basis of which subsetting has to be done select: indicates columns to select Example: R subset(USArrests, Assault > 100 & UrbanPop > 25, select = c( Rape, Assault)) Output: Rape Assault Alabama 21.2 236 Alaska 44.5 263 . . . Washington 26.2 145 Wyoming 15.6 161 Now let’s create the plot for the subset so obtained. The above command can be directly passed to the plot() function. Example: R plot(subset(USArrests,Assault > 100 & UrbanPop > 25, select = c(Rape, Assault))) Output: Using the ‘[ ]’ operator, elements of vectors and observations from dataframes can be accessed and subsetted based on some condition. Syntax: plot( df$col1[condition], df$col2[condition] ) Parameters: df: dataframe condition: indicates the logical expression on the basis of which subsetting has to be done Again the data will be first subsetted out and then will be provided to the plot() function. Example: R plot(USArrests$Rape[USArrests$Assault > 100] , USArrests$Assault[USArrests$Assault > 100] ) Output: In this we pass the row and column name to be plotted, and the condition based on which sub setting should be done to the plot function. Syntax: plot( x ~ y, data=subset(df, condition ) ) Parameters: x: data for x axis y: data for y axis data: subset of our dataframe which we want to plot. df: dataframe object condition: indicates the logical expression on the basis of which subsetting has to be done Example: R plot(Murder ~ UrbanPop, data=subset(USArrests, Rape < 25)) Output: Picked R DataFrame-Programs R-Charts R-DataFrame R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 207, "s": 28, "text": "In this article, we will learn multiple approaches to plotting a subset of a Dataframe in R Programming Language. Here we will be using, R language’s inbuilt “USArrests” dataset." }, { "code": null, "e": 374, "s": 207, "text": "In this method, first a subset of the data is created base don some condition, and then it is plotted using plot function. Let us first create the subset of the data." }, { "code": null, "e": 423, "s": 374, "text": "Syntax: plot(subset( data, condition, select)) " }, { "code": null, "e": 435, "s": 423, "text": "Parameters:" }, { "code": null, "e": 451, "s": 435, "text": "data: dataframe" }, { "code": null, "e": 543, "s": 451, "text": "condition: indicates the logical expression on the basis of which subsetting has to be done" }, { "code": null, "e": 579, "s": 543, "text": "select: indicates columns to select" }, { "code": null, "e": 588, "s": 579, "text": "Example:" }, { "code": null, "e": 590, "s": 588, "text": "R" }, { "code": "subset(USArrests, Assault > 100 & UrbanPop > 25, select = c( Rape, Assault))", "e": 673, "s": 590, "text": null }, { "code": null, "e": 681, "s": 673, "text": "Output:" }, { "code": null, "e": 697, "s": 681, "text": " Rape Assault" }, { "code": null, "e": 725, "s": 697, "text": "Alabama 21.2 236" }, { "code": null, "e": 753, "s": 725, "text": "Alaska 44.5 263" }, { "code": null, "e": 755, "s": 753, "text": "." }, { "code": null, "e": 757, "s": 755, "text": "." }, { "code": null, "e": 759, "s": 757, "text": "." }, { "code": null, "e": 787, "s": 759, "text": "Washington 26.2 145" }, { "code": null, "e": 815, "s": 787, "text": "Wyoming 15.6 161" }, { "code": null, "e": 934, "s": 815, "text": "Now let’s create the plot for the subset so obtained. The above command can be directly passed to the plot() function." }, { "code": null, "e": 943, "s": 934, "text": "Example:" }, { "code": null, "e": 945, "s": 943, "text": "R" }, { "code": "plot(subset(USArrests,Assault > 100 & UrbanPop > 25, select = c(Rape, Assault)))", "e": 1038, "s": 945, "text": null }, { "code": null, "e": 1046, "s": 1038, "text": "Output:" }, { "code": null, "e": 1180, "s": 1046, "text": "Using the ‘[ ]’ operator, elements of vectors and observations from dataframes can be accessed and subsetted based on some condition." }, { "code": null, "e": 1235, "s": 1180, "text": "Syntax: plot( df$col1[condition], df$col2[condition] )" }, { "code": null, "e": 1248, "s": 1235, "text": "Parameters: " }, { "code": null, "e": 1263, "s": 1248, "text": "df: dataframe " }, { "code": null, "e": 1356, "s": 1263, "text": "condition: indicates the logical expression on the basis of which subsetting has to be done" }, { "code": null, "e": 1449, "s": 1356, "text": "Again the data will be first subsetted out and then will be provided to the plot() function." }, { "code": null, "e": 1458, "s": 1449, "text": "Example:" }, { "code": null, "e": 1460, "s": 1458, "text": "R" }, { "code": "plot(USArrests$Rape[USArrests$Assault > 100] , USArrests$Assault[USArrests$Assault > 100] )", "e": 1556, "s": 1460, "text": null }, { "code": null, "e": 1564, "s": 1556, "text": "Output:" }, { "code": null, "e": 1701, "s": 1564, "text": "In this we pass the row and column name to be plotted, and the condition based on which sub setting should be done to the plot function." }, { "code": null, "e": 1752, "s": 1701, "text": "Syntax: plot( x ~ y, data=subset(df, condition ) )" }, { "code": null, "e": 1764, "s": 1752, "text": "Parameters:" }, { "code": null, "e": 1783, "s": 1764, "text": "x: data for x axis" }, { "code": null, "e": 1802, "s": 1783, "text": "y: data for y axis" }, { "code": null, "e": 1855, "s": 1802, "text": "data: subset of our dataframe which we want to plot." }, { "code": null, "e": 1876, "s": 1855, "text": "df: dataframe object" }, { "code": null, "e": 1968, "s": 1876, "text": "condition: indicates the logical expression on the basis of which subsetting has to be done" }, { "code": null, "e": 1977, "s": 1968, "text": "Example:" }, { "code": null, "e": 1979, "s": 1977, "text": "R" }, { "code": "plot(Murder ~ UrbanPop, data=subset(USArrests, Rape < 25))", "e": 2038, "s": 1979, "text": null }, { "code": null, "e": 2046, "s": 2038, "text": "Output:" }, { "code": null, "e": 2053, "s": 2046, "text": "Picked" }, { "code": null, "e": 2074, "s": 2053, "text": "R DataFrame-Programs" }, { "code": null, "e": 2083, "s": 2074, "text": "R-Charts" }, { "code": null, "e": 2095, "s": 2083, "text": "R-DataFrame" }, { "code": null, "e": 2104, "s": 2095, "text": "R-Graphs" }, { "code": null, "e": 2112, "s": 2104, "text": "R-plots" }, { "code": null, "e": 2123, "s": 2112, "text": "R Language" }, { "code": null, "e": 2221, "s": 2123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2273, "s": 2221, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2331, "s": 2273, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2383, "s": 2331, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2441, "s": 2383, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2473, "s": 2441, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2508, "s": 2473, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2552, "s": 2508, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2584, "s": 2552, "text": "Printing Output of an R Program" }, { "code": null, "e": 2622, "s": 2584, "text": "How to Change Axis Scales in R Plots?" } ]
OpenCV C++ Program for coin detection
09 Feb, 2018 The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV. Things to know: The code will only compile in Linux environment.To run in windows, please use the file: ‘coin.o’ and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious changes to the code like: Use in place of .Compile command: g++ -w coin.cpp -o coin.exe `pkg-config –libs opencv`Run command: ./coinThe image containing coin/coins has to be in the same directory as the code.Before you run the code, please make sure that you have OpenCV installed on your // system. The code will only compile in Linux environment. To run in windows, please use the file: ‘coin.o’ and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious changes to the code like: Use in place of . Compile command: g++ -w coin.cpp -o coin.exe `pkg-config –libs opencv` Run command: ./coin The image containing coin/coins has to be in the same directory as the code.Before you run the code, please make sure that you have OpenCV installed on your // system. Code Snippets Explained: #include "opencv2/highgui/highgui.hpp" // highgui - an interface to video and image capturing. #include "opencv2/imgproc/imgproc.hpp" // imgproc - An image processing module that for linear and non-linear image filtering, geometrical image transformations, color space conversion and so on. #include <iostream> #include <stdio.h> // The header files for performing input and output. using namespace cv; // Namespace where all the C++ OpenCV functionality resides. using namespace std; // For input output operations. int main() { Mat image; // Mat object is a basic image container. image is an object of Mat. image=imread("coin-detection.jpg",CV_LOAD_IMAGE_GRAYSCALE); // Take any image but make sure its in the same folder. // first argument denotes the image to be loaded. // second argument specifies the image format as follows: // CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as it is. // CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image in Gray scale. // CV_LOAD_IMAGE_COLOR (>0) loads the image in the BGR format. // If the second argument is not there, it is implied CV_LOAD_IMAGE_COLOR. vector coin; // A vector data type to store the details of coins. HoughCircles(image,coin,CV_HOUGH_GRADIENT,2,20,450,60,0,0 ); // Argument 1: Input image mode // Argument 2: A vector that stores 3 values: x,y and r for each circle. // Argument 3: CV_HOUGH_GRADIENT: Detection method. // Argument 4: The inverse ratio of resolution. // Argument 5: Minimum distance between centers. // Argument 6: Upper threshold for Canny edge detector. // Argument 7: Threshold for center detection. // Argument 8: Minimum radius to be detected. Put zero as default // Argument 9: Maximum radius to be detected. Put zero as default int l=coin.size(); // Get the number of coins. cout<<"\n The number of coins is: "<<l<<"\n\n"; // To draw the detected circles. for( size_t i = 0; i < coin.size(); i++ ) { Point center(cvRound(coin[i][0]),cvRound(coin[i][1])); // Detect center // cvRound: Rounds floating point number to nearest integer. int radius=cvRound(coin[i][2]); // To get the radius from the second argument of vector coin. circle(image,center,3,Scalar(0,255,0),-1,8,0); // circle center // To get the circle outline. circle(image,center,radius,Scalar(0,0,255),3,8,0); // circle outline cout<< " Center location for circle "<<i+1<<" : "<<center<<"\n Diameter : "<<2*radius<<"\n"; } cout<<"\n"; namedWindow("Coin Counter",CV_WINDOW_AUTOSIZE); // Create a window called //"A_good_name". // first argument: name of the window. // second argument: flag- types: // WINDOW_NORMAL : The user can resize the window. // WINDOW_AUTOSIZE : The window size is automatically adjusted to fit the // displayed image() ), and you cannot change the window size manually. // WINDOW_OPENGL : The window will be created with OpenGL support. imshow("Coin Counter",image); // first argument: name of the window // second argument: image to be shown(Mat object) waitKey(0); // Wait for infinite time for a key press. Return 0; // Return from main function. } End of explanation. About the Author: Aditya Prakash is an undergraduate student at Indian Institute of Information Technology, Vadodara. He primarily codes in C++. The motto for him is: So far so good. He plays cricket, watches superhero movies, football and is a big fan of answering questions. If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. Image-Processing OpenCV C++ Project 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++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Feb, 2018" }, { "code": null, "e": 152, "s": 54, "text": "The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV." }, { "code": null, "e": 168, "s": 152, "text": "Things to know:" }, { "code": null, "e": 701, "s": 168, "text": "The code will only compile in Linux environment.To run in windows, please use the file: ‘coin.o’ and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious changes to the code like: Use in place of .Compile command: g++ -w coin.cpp -o coin.exe `pkg-config –libs opencv`Run command: ./coinThe image containing coin/coins has to be in the same directory as the code.Before you run the code, please make sure that you have OpenCV installed on your // system." }, { "code": null, "e": 750, "s": 701, "text": "The code will only compile in Linux environment." }, { "code": null, "e": 979, "s": 750, "text": "To run in windows, please use the file: ‘coin.o’ and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious changes to the code like: Use in place of ." }, { "code": null, "e": 1050, "s": 979, "text": "Compile command: g++ -w coin.cpp -o coin.exe `pkg-config –libs opencv`" }, { "code": null, "e": 1070, "s": 1050, "text": "Run command: ./coin" }, { "code": null, "e": 1238, "s": 1070, "text": "The image containing coin/coins has to be in the same directory as the code.Before you run the code, please make sure that you have OpenCV installed on your // system." }, { "code": null, "e": 1263, "s": 1238, "text": "Code Snippets Explained:" }, { "code": null, "e": 4612, "s": 1263, "text": "#include \"opencv2/highgui/highgui.hpp\"\n// highgui - an interface to video and image capturing.\n\n#include \"opencv2/imgproc/imgproc.hpp\"\n// imgproc - An image processing module that for linear and non-linear\n image filtering, geometrical image transformations, color space conversion and so on.\n#include <iostream>\n#include <stdio.h>\n// The header files for performing input and output.\n \nusing namespace cv;\n// Namespace where all the C++ OpenCV functionality resides.\n\nusing namespace std;\n// For input output operations.\n \nint main()\n{\n Mat image;\n // Mat object is a basic image container. image is an object of Mat.\n\n image=imread(\"coin-detection.jpg\",CV_LOAD_IMAGE_GRAYSCALE);\n // Take any image but make sure its in the same folder.\n // first argument denotes the image to be loaded. \n // second argument specifies the image format as follows: \n // CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as it is. \n // CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image in Gray scale. \n // CV_LOAD_IMAGE_COLOR (>0) loads the image in the BGR format. \n // If the second argument is not there, it is implied CV_LOAD_IMAGE_COLOR.\n\n vector coin;\n // A vector data type to store the details of coins.\n\n HoughCircles(image,coin,CV_HOUGH_GRADIENT,2,20,450,60,0,0 );\n // Argument 1: Input image mode\n // Argument 2: A vector that stores 3 values: x,y and r for each circle.\n // Argument 3: CV_HOUGH_GRADIENT: Detection method.\n // Argument 4: The inverse ratio of resolution.\n // Argument 5: Minimum distance between centers.\n // Argument 6: Upper threshold for Canny edge detector.\n // Argument 7: Threshold for center detection.\n // Argument 8: Minimum radius to be detected. Put zero as default\n // Argument 9: Maximum radius to be detected. Put zero as default\n\n int l=coin.size();\n // Get the number of coins.\n\n cout<<\"\\n The number of coins is: \"<<l<<\"\\n\\n\";\n \n // To draw the detected circles.\n for( size_t i = 0; i < coin.size(); i++ )\n {\n Point center(cvRound(coin[i][0]),cvRound(coin[i][1]));\n // Detect center\n // cvRound: Rounds floating point number to nearest integer.\n int radius=cvRound(coin[i][2]);\n // To get the radius from the second argument of vector coin. \n circle(image,center,3,Scalar(0,255,0),-1,8,0);\n // circle center\n // To get the circle outline. \n circle(image,center,radius,Scalar(0,0,255),3,8,0);\n // circle outline\n cout<< \" Center location for circle \"<<i+1<<\" :\n \"<<center<<\"\\n Diameter : \"<<2*radius<<\"\\n\";\n }\n cout<<\"\\n\";\n \n namedWindow(\"Coin Counter\",CV_WINDOW_AUTOSIZE);\n // Create a window called \n //\"A_good_name\". \n // first argument: name of the window. \n // second argument: flag- types: \n // WINDOW_NORMAL : The user can resize the window. \n // WINDOW_AUTOSIZE : The window size is automatically adjusted to fit the\n // displayed image() ), and you cannot change the window size manually. \n // WINDOW_OPENGL : The window will be created with OpenGL support.\n \n imshow(\"Coin Counter\",image);\n // first argument: name of the window \n // second argument: image to be shown(Mat object)\n\n waitKey(0); // Wait for infinite time for a key press.\n\n Return 0; // Return from main function.\n}\n\nEnd of explanation." }, { "code": null, "e": 4630, "s": 4612, "text": "About the Author:" }, { "code": null, "e": 4889, "s": 4630, "text": "Aditya Prakash is an undergraduate student at Indian Institute of Information Technology, Vadodara. He primarily codes in C++. The motto for him is: So far so good. He plays cricket, watches superhero movies, football and is a big fan of answering questions." }, { "code": null, "e": 4992, "s": 4889, "text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks." }, { "code": null, "e": 5009, "s": 4992, "text": "Image-Processing" }, { "code": null, "e": 5016, "s": 5009, "text": "OpenCV" }, { "code": null, "e": 5020, "s": 5016, "text": "C++" }, { "code": null, "e": 5028, "s": 5020, "text": "Project" }, { "code": null, "e": 5032, "s": 5028, "text": "CPP" }, { "code": null, "e": 5130, "s": 5032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5154, "s": 5130, "text": "Sorting a vector in C++" }, { "code": null, "e": 5174, "s": 5154, "text": "Polymorphism in C++" }, { "code": null, "e": 5218, "s": 5174, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 5251, "s": 5218, "text": "Friend class and function in C++" }, { "code": null, "e": 5276, "s": 5251, "text": "std::string class in C++" }, { "code": null, "e": 5325, "s": 5276, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 5380, "s": 5325, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 5413, "s": 5380, "text": "Working with zip files in Python" }, { "code": null, "e": 5435, "s": 5413, "text": "XML parsing in Python" } ]
Octagonal number
16 Jul, 2021 You are given a number n, the task is to find nth octagonal number. Also, find the Octagonal series till n.An octagonal number is the figure number that represent octagonal. Octagonal numbers can be formed by placing triangular numbers on the four sides of a square. Octagonal number is calculated by using the formula (3n2 – 2n). Examples : Input : 5 Output : 65 Input : 10 Output : 280 Input : 15 Output : 645 C++ Java Python C# PHP Javascript // C++ program to find// nth octagonal number#include <bits/stdc++.h>using namespace std; // Function to calculate//octagonal numberint octagonal(int n){ // Formula for finding // nth octagonal number return 3 * n * n - 2 * n;} // Driver functionint main(){ int n = 10; cout << n << "th octagonal number :" << octagonal(n); return 0;} // Java program to find// nth octagonal numberimport java.util.*;import java.lang.*; public class GfG { // Function to calculate //octagonal number public static int octagonal(int n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver function public static void main(String argc[]) { int n = 10; System.out.println(n + "th octagonal" + " number :" + octagonal(n)); }} /* This code is contributed by Sagar Shukla */ # Python program to find# nth octagonal numberdef octagonal(n): return 3 * n * n - 2 * n # Driver coden = 10print(n, "th octagonal number :", octagonal(n)) // C# program to find nth octagonal numberusing System; public class GfG { // Function to calculate //octagonal number public static int octagonal(int n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver function public static void Main() { int n = 10; Console.WriteLine(n + "th octagonal" + " number :" + octagonal(n)); }} /* This code is contributed by Vt_m */ <?php// PHP program to find// nth octagonal number // Function to calculate//octagonal numberfunction octagonal($n){ // Formula for finding // nth octagonal number return 3 * $n * $n - 2 * $n;} // Driver Code $n = 10; echo $n , "th octagonal number :" , octagonal($n); // This code is contributed by Vt_m .?> <script> // JavaScript program to convert// Binary code to Gray code // Function to calculate //octagonal number function octagonal(n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver code let n = 10; document.write(n + "th octagonal" + " number :" + octagonal(n)); // This code is contributed by code_hunt.</script> Output : 10th octagonal number : 280 Time Complexity: O(1)Auxiliary Space: O(1) We can also find the octagonal series. Octagonal series contains the points on octagonal. Octagonal series 1, 8, 21, 40, 65, 96, 133, 176, 225, 280, . . . C++ Java Python C# PHP Javascript // C++ program to display the// octagonal series#include <bits/stdc++.h>using namespace std; // Function to display// octagonal seriesvoid octagonalSeries(int n){ // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number cout << (3 * i * i - 2 * i); } // Driver functionint main(){ int n = 10; octagonalSeries(n); return 0;} // Java program to find// nth octagonal numberimport java.util.*;import java.lang.*; public class GfG { // Function to display octagonal series public static void octagonalSeries(int n) { // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number System.out.print(3 * i * i - 2 * i); } // Driver function public static void main(String argc[]) { int n = 10; octagonalSeries(n); } /* This code is contributed by Sagar Shukla */} # Python program to find# nth octagonal numberdef octagonalSeries(n): for i in range(1, n + 1): print(3 * i * i - 2 * i, end = ", ") # Driver coden = 10octagonalSeries(n) // C# program to find// nth octagonal numberusing System; public class GfG { // Function to display octagonal series public static void octagonalSeries(int n) { // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number Console.Write(3 * i * i - 2 * i + ", "); } // Driver function public static void Main() { int n = 10; octagonalSeries(n); }} /* This code is contributed by Vt_m */ <?php// PHP program to display the// octagonal series // Function to display// octagonal seriesfunction octagonalSeries($n){ // Formula for finding // nth octagonal number for ($i = 1; $i <= $n; $i++) // Formula for computing // octagonal number echo (3 * $i * $i - 2 * $i),",";} // Driver Code $n = 10; octagonalSeries($n); // This code is contributed by Vt_m .?> <script>// Javascript program to display the// octagonal series // Function to display// octagonal seriesfunction octagonalSeries(n){ // Formula for finding // nth octagonal number for (let i = 1; i <= n; i++) // Formula for computing // octagonal number document.write(3 * i * i - 2 * i + ", ");} // Driver Code let n = 10; octagonalSeries(n); // This code is contributed by _saurabh_jaiswal </script> Output : 1, 8, 21, 40, 65, 96, 133, 176, 225, 280 Time Complexity: O(n)Auxiliary Space: O(1) vt_m code_hunt _saurabh_jaiswal manikarora059 Numbers series Mathematical School Programming Mathematical series Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jul, 2021" }, { "code": null, "e": 397, "s": 53, "text": "You are given a number n, the task is to find nth octagonal number. Also, find the Octagonal series till n.An octagonal number is the figure number that represent octagonal. Octagonal numbers can be formed by placing triangular numbers on the four sides of a square. Octagonal number is calculated by using the formula (3n2 – 2n). Examples : " }, { "code": null, "e": 469, "s": 397, "text": "Input : 5\nOutput : 65\n\nInput : 10\nOutput : 280\n\nInput : 15\nOutput : 645" }, { "code": null, "e": 477, "s": 473, "text": "C++" }, { "code": null, "e": 482, "s": 477, "text": "Java" }, { "code": null, "e": 489, "s": 482, "text": "Python" }, { "code": null, "e": 492, "s": 489, "text": "C#" }, { "code": null, "e": 496, "s": 492, "text": "PHP" }, { "code": null, "e": 507, "s": 496, "text": "Javascript" }, { "code": "// C++ program to find// nth octagonal number#include <bits/stdc++.h>using namespace std; // Function to calculate//octagonal numberint octagonal(int n){ // Formula for finding // nth octagonal number return 3 * n * n - 2 * n;} // Driver functionint main(){ int n = 10; cout << n << \"th octagonal number :\" << octagonal(n); return 0;}", "e": 868, "s": 507, "text": null }, { "code": "// Java program to find// nth octagonal numberimport java.util.*;import java.lang.*; public class GfG { // Function to calculate //octagonal number public static int octagonal(int n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver function public static void main(String argc[]) { int n = 10; System.out.println(n + \"th octagonal\" + \" number :\" + octagonal(n)); }} /* This code is contributed by Sagar Shukla */", "e": 1403, "s": 868, "text": null }, { "code": "# Python program to find# nth octagonal numberdef octagonal(n): return 3 * n * n - 2 * n # Driver coden = 10print(n, \"th octagonal number :\", octagonal(n))", "e": 1568, "s": 1403, "text": null }, { "code": "// C# program to find nth octagonal numberusing System; public class GfG { // Function to calculate //octagonal number public static int octagonal(int n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver function public static void Main() { int n = 10; Console.WriteLine(n + \"th octagonal\" + \" number :\" + octagonal(n)); }} /* This code is contributed by Vt_m */", "e": 2063, "s": 1568, "text": null }, { "code": "<?php// PHP program to find// nth octagonal number // Function to calculate//octagonal numberfunction octagonal($n){ // Formula for finding // nth octagonal number return 3 * $n * $n - 2 * $n;} // Driver Code $n = 10; echo $n , \"th octagonal number :\" , octagonal($n); // This code is contributed by Vt_m .?>", "e": 2438, "s": 2063, "text": null }, { "code": "<script> // JavaScript program to convert// Binary code to Gray code // Function to calculate //octagonal number function octagonal(n) { // Formula for finding // nth octagonal number return 3 * n * n - 2 * n; } // Driver code let n = 10; document.write(n + \"th octagonal\" + \" number :\" + octagonal(n)); // This code is contributed by code_hunt.</script>", "e": 2889, "s": 2438, "text": null }, { "code": null, "e": 2900, "s": 2889, "text": "Output : " }, { "code": null, "e": 2928, "s": 2900, "text": "10th octagonal number : 280" }, { "code": null, "e": 2972, "s": 2928, "text": "Time Complexity: O(1)Auxiliary Space: O(1) " }, { "code": null, "e": 3064, "s": 2972, "text": "We can also find the octagonal series. Octagonal series contains the points on octagonal. " }, { "code": null, "e": 3129, "s": 3064, "text": "Octagonal series 1, 8, 21, 40, 65, 96, 133, 176, 225, 280, . . ." }, { "code": null, "e": 3135, "s": 3131, "text": "C++" }, { "code": null, "e": 3140, "s": 3135, "text": "Java" }, { "code": null, "e": 3147, "s": 3140, "text": "Python" }, { "code": null, "e": 3150, "s": 3147, "text": "C#" }, { "code": null, "e": 3154, "s": 3150, "text": "PHP" }, { "code": null, "e": 3165, "s": 3154, "text": "Javascript" }, { "code": "// C++ program to display the// octagonal series#include <bits/stdc++.h>using namespace std; // Function to display// octagonal seriesvoid octagonalSeries(int n){ // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number cout << (3 * i * i - 2 * i); } // Driver functionint main(){ int n = 10; octagonalSeries(n); return 0;}", "e": 3594, "s": 3165, "text": null }, { "code": "// Java program to find// nth octagonal numberimport java.util.*;import java.lang.*; public class GfG { // Function to display octagonal series public static void octagonalSeries(int n) { // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number System.out.print(3 * i * i - 2 * i); } // Driver function public static void main(String argc[]) { int n = 10; octagonalSeries(n); } /* This code is contributed by Sagar Shukla */}", "e": 4187, "s": 3594, "text": null }, { "code": "# Python program to find# nth octagonal numberdef octagonalSeries(n): for i in range(1, n + 1): print(3 * i * i - 2 * i, end = \", \") # Driver coden = 10octagonalSeries(n)", "e": 4386, "s": 4187, "text": null }, { "code": "// C# program to find// nth octagonal numberusing System; public class GfG { // Function to display octagonal series public static void octagonalSeries(int n) { // Formula for finding //nth octagonal number for (int i = 1; i <= n; i++) // Formula for computing // octagonal number Console.Write(3 * i * i - 2 * i + \", \"); } // Driver function public static void Main() { int n = 10; octagonalSeries(n); }} /* This code is contributed by Vt_m */", "e": 4944, "s": 4386, "text": null }, { "code": "<?php// PHP program to display the// octagonal series // Function to display// octagonal seriesfunction octagonalSeries($n){ // Formula for finding // nth octagonal number for ($i = 1; $i <= $n; $i++) // Formula for computing // octagonal number echo (3 * $i * $i - 2 * $i),\",\";} // Driver Code $n = 10; octagonalSeries($n); // This code is contributed by Vt_m .?>", "e": 5356, "s": 4944, "text": null }, { "code": "<script>// Javascript program to display the// octagonal series // Function to display// octagonal seriesfunction octagonalSeries(n){ // Formula for finding // nth octagonal number for (let i = 1; i <= n; i++) // Formula for computing // octagonal number document.write(3 * i * i - 2 * i + \", \");} // Driver Code let n = 10; octagonalSeries(n); // This code is contributed by _saurabh_jaiswal </script>", "e": 5806, "s": 5356, "text": null }, { "code": null, "e": 5817, "s": 5806, "text": "Output : " }, { "code": null, "e": 5858, "s": 5817, "text": "1, 8, 21, 40, 65, 96, 133, 176, 225, 280" }, { "code": null, "e": 5902, "s": 5858, "text": "Time Complexity: O(n)Auxiliary Space: O(1) " }, { "code": null, "e": 5907, "s": 5902, "text": "vt_m" }, { "code": null, "e": 5917, "s": 5907, "text": "code_hunt" }, { "code": null, "e": 5934, "s": 5917, "text": "_saurabh_jaiswal" }, { "code": null, "e": 5948, "s": 5934, "text": "manikarora059" }, { "code": null, "e": 5956, "s": 5948, "text": "Numbers" }, { "code": null, "e": 5963, "s": 5956, "text": "series" }, { "code": null, "e": 5976, "s": 5963, "text": "Mathematical" }, { "code": null, "e": 5995, "s": 5976, "text": "School Programming" }, { "code": null, "e": 6008, "s": 5995, "text": "Mathematical" }, { "code": null, "e": 6015, "s": 6008, "text": "series" }, { "code": null, "e": 6023, "s": 6015, "text": "Numbers" }, { "code": null, "e": 6121, "s": 6023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6145, "s": 6121, "text": "Merge two sorted arrays" }, { "code": null, "e": 6166, "s": 6145, "text": "Operators in C / C++" }, { "code": null, "e": 6180, "s": 6166, "text": "Prime Numbers" }, { "code": null, "e": 6233, "s": 6180, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6270, "s": 6233, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6288, "s": 6270, "text": "Python Dictionary" }, { "code": null, "e": 6313, "s": 6288, "text": "Reverse a string in Java" }, { "code": null, "e": 6329, "s": 6313, "text": "Arrays in C/C++" }, { "code": null, "e": 6352, "s": 6329, "text": "Introduction To PYTHON" } ]
How to Select an Image from Gallery in Android?
17 May, 2022 Selecting an image from a gallery in Android is required when the user has to upload or set their image as a profile picture or the user wants to send a pic to the other. So in this article, it’s been discussed step by step how to select an image from the gallery and preview the selected image. Have a look at the following image what’s been discussed further in this article. Step 1: Create an empty activity project Create an empty activity Android Studio Project. And select Java as the programming language. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio Project. Step 2: Working with the activity_main.xml The main layout of the application includes one button to open the image selector, and one Image View to preview the selected image from the gallery. To implement the layout of the application, invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Button to open the image selector--> <Button android:id="@+id/BSelectImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:backgroundTint="@color/colorPrimary" android:text="SELECT IMAGE" android:textColor="@android:color/white" android:textSize="18sp" /> <!--ImageView to preview the selected image--> <ImageView android:id="@+id/IVPreviewImage" android:layout_width="match_parent" android:layout_height="300dp" android:layout_below="@id/BSelectImage" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" /> </RelativeLayout> Output UI: Step 3: Working with the MainActivity.java file In this case, the imageChooser is triggered with the intent of the type “image” and action as ACTION_GET_CONTENT. Invoke the following code to implement the same. Comments are added for better understanding. Example Java import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { // One Button Button BSelectImage; // One Preview Image ImageView IVPreviewImage; // constant to compare // the activity result code int SELECT_PICTURE = 200; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the UI widgets with their appropriate IDs BSelectImage = findViewById(R.id.BSelectImage); IVPreviewImage = findViewById(R.id.IVPreviewImage); // handle the Choose Image button to trigger // the image chooser function BSelectImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageChooser(); } }); } // this function is triggered when // the Select Image Button is clicked void imageChooser() { // create an instance of the // intent of the type image Intent i = new Intent(); i.setType("image/*"); i.setAction(Intent.ACTION_GET_CONTENT); // pass the constant to compare it // with the returned requestCode startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE); } // this function is triggered when user // selects the image from the imageChooser public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { // compare the resultCode with the // SELECT_PICTURE constant if (requestCode == SELECT_PICTURE) { // Get the url of the image from data Uri selectedImageUri = data.getData(); if (null != selectedImageUri) { // update the preview image in the layout IVPreviewImage.setImageURI(selectedImageUri); } } } }} Output: Run on Emulator Alternative Code: In case: startActivityForResult is deprecated Java private void imageChooser(){ Intent i = new Intent(); i.setType("image/*"); i.setAction(Intent.ACTION_GET_CONTENT); launchSomeActivity.launch(i);} ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult( new ActivityResultContracts .StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent data = result.getData(); // do your operation from here.... if (data != null && data.getData() != null) { Uri selectedImageUri = data.getData(); Bitmap selectedImageBitmap; try { selectedImageBitmap = MediaStore.Images.Media.getBitmap( this.getContentResolver(), selectedImageUri); } catch (IOException e) { e.printStackTrace(); } imageView.setImageBitmap( selectedImageBitmap); } } }); namitg677 android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2022" }, { "code": null, "e": 430, "s": 52, "text": "Selecting an image from a gallery in Android is required when the user has to upload or set their image as a profile picture or the user wants to send a pic to the other. So in this article, it’s been discussed step by step how to select an image from the gallery and preview the selected image. Have a look at the following image what’s been discussed further in this article." }, { "code": null, "e": 471, "s": 430, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 565, "s": 471, "text": "Create an empty activity Android Studio Project. And select Java as the programming language." }, { "code": null, "e": 701, "s": 565, "text": "Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio Project." }, { "code": null, "e": 744, "s": 701, "text": "Step 2: Working with the activity_main.xml" }, { "code": null, "e": 894, "s": 744, "text": "The main layout of the application includes one button to open the image selector, and one Image View to preview the selected image from the gallery." }, { "code": null, "e": 999, "s": 894, "text": "To implement the layout of the application, invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 1003, "s": 999, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Button to open the image selector--> <Button android:id=\"@+id/BSelectImage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"32dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"SELECT IMAGE\" android:textColor=\"@android:color/white\" android:textSize=\"18sp\" /> <!--ImageView to preview the selected image--> <ImageView android:id=\"@+id/IVPreviewImage\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_below=\"@id/BSelectImage\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" /> </RelativeLayout>", "e": 2121, "s": 1003, "text": null }, { "code": null, "e": 2133, "s": 2121, "text": " Output UI:" }, { "code": null, "e": 2182, "s": 2133, "text": "Step 3: Working with the MainActivity.java file " }, { "code": null, "e": 2296, "s": 2182, "text": "In this case, the imageChooser is triggered with the intent of the type “image” and action as ACTION_GET_CONTENT." }, { "code": null, "e": 2390, "s": 2296, "text": "Invoke the following code to implement the same. Comments are added for better understanding." }, { "code": null, "e": 2398, "s": 2390, "text": "Example" }, { "code": null, "e": 2403, "s": 2398, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { // One Button Button BSelectImage; // One Preview Image ImageView IVPreviewImage; // constant to compare // the activity result code int SELECT_PICTURE = 200; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the UI widgets with their appropriate IDs BSelectImage = findViewById(R.id.BSelectImage); IVPreviewImage = findViewById(R.id.IVPreviewImage); // handle the Choose Image button to trigger // the image chooser function BSelectImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageChooser(); } }); } // this function is triggered when // the Select Image Button is clicked void imageChooser() { // create an instance of the // intent of the type image Intent i = new Intent(); i.setType(\"image/*\"); i.setAction(Intent.ACTION_GET_CONTENT); // pass the constant to compare it // with the returned requestCode startActivityForResult(Intent.createChooser(i, \"Select Picture\"), SELECT_PICTURE); } // this function is triggered when user // selects the image from the imageChooser public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { // compare the resultCode with the // SELECT_PICTURE constant if (requestCode == SELECT_PICTURE) { // Get the url of the image from data Uri selectedImageUri = data.getData(); if (null != selectedImageUri) { // update the preview image in the layout IVPreviewImage.setImageURI(selectedImageUri); } } } }}", "e": 4675, "s": 2403, "text": null }, { "code": null, "e": 4700, "s": 4675, "text": " Output: Run on Emulator" }, { "code": null, "e": 4764, "s": 4700, "text": "Alternative Code: In case: startActivityForResult is deprecated" }, { "code": null, "e": 4769, "s": 4764, "text": "Java" }, { "code": "private void imageChooser(){ Intent i = new Intent(); i.setType(\"image/*\"); i.setAction(Intent.ACTION_GET_CONTENT); launchSomeActivity.launch(i);} ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult( new ActivityResultContracts .StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent data = result.getData(); // do your operation from here.... if (data != null && data.getData() != null) { Uri selectedImageUri = data.getData(); Bitmap selectedImageBitmap; try { selectedImageBitmap = MediaStore.Images.Media.getBitmap( this.getContentResolver(), selectedImageUri); } catch (IOException e) { e.printStackTrace(); } imageView.setImageBitmap( selectedImageBitmap); } } });", "e": 5963, "s": 4769, "text": null }, { "code": null, "e": 5975, "s": 5965, "text": "namitg677" }, { "code": null, "e": 5983, "s": 5975, "text": "android" }, { "code": null, "e": 6007, "s": 5983, "text": "Technical Scripter 2020" }, { "code": null, "e": 6015, "s": 6007, "text": "Android" }, { "code": null, "e": 6020, "s": 6015, "text": "Java" }, { "code": null, "e": 6039, "s": 6020, "text": "Technical Scripter" }, { "code": null, "e": 6044, "s": 6039, "text": "Java" }, { "code": null, "e": 6052, "s": 6044, "text": "Android" } ]
Python | Adding image in Kivy using .kv file
31 Jan, 2022 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. The Image widget is used to display an image. To use the image widget you must have to import : from kivy.uix.image import Image, AsyncImage (not necessary while working with .kv file) because the module kivy.uix.image have all the functionality related to images.Images can be loaded to the Application via two types: 1) Synchronous Loading: Loading image from the system (must be from the folder in which .py and .kv file is saved) 2) Asynchronous Loading: To load an image asynchronously (for example from an external webserver) Note: By default, the image is centered and fits inside the widget bounding box. If you don’t want that, you can set allow_stretch to True and keep_ratio to False. Basic Approach to create multiple layout in one file: 1) import kivy 2) import kivyApp 3) import image 4) import BoxLayout 5) set minimum version(optional) 6) Create the Layout class 7) Create App class 8) Create .kv file: 1) Add BoxLayout 2) Add Label 3) Add Image 4) Resizing, Positioning etc of Image 9) return instance of the layout class 10) Run an instance of the class So in the below code, we will explain How to load Synchronous and Asynchronous images. Also How to resize, Positioning, Label, etc the image with some more stuff..py file – Python3 ## Sample Python application demonstrating the ## working with images in Kivy using .kv file ################################################### import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # BoxLayout arranges children in a vertical or horizontal box.# or help to put the children at the desired location.from kivy.uix.boxlayout import BoxLayout # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the root widget used in .kv fileclass Imagekv(BoxLayout): ''' no need to do anything here as we are building things in .kv file ''' pass # class in which name .kv file must be named My.kv.class MyApp(App): # define build() function def build(self): # returning the instance of Imagekv class return Imagekv() # run the Appif __name__ == '__main__': MyApp().run() .kv file implementation – Python3 # How to use images in kivy using .kv # root widget od Imagekv Class<Imagekv>: # Giving orientation to Box Layout orientation:'vertical' ############################################### # Adding Box Layout BoxLayout: padding:5 # Adding image from the system Image: source: 'download.jpg' # Giving the size of image size_hint_x: 0.4 # allow stretching of image allow_stretch: True # Giving Label to images Label: text:"Python" font_size:11 bold:True Label: text:"Programing Language" font_size:10 ############################################### # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ################################################ # Another Box Layout BoxLayout: padding:5 Image: source:"downloading.jpg" size_hint_x: 0.4 allow_stretch: True Label: text:"Image" font_size:11 bold:True Label: text:"Python Image" font_size:10 ############################################# # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ############################################### # Adding next Box Layout BoxLayout: padding:5 # To load an image asynchronously # (for example from an external webserver) AsyncImage: source: 'http://kivy.org/logos/kivy-logo-black-64.png' width: 100 allow_stretch: True Label: text:" Asynchronous Image " font_size:11 bold:True Label: text:"Kivy Logo" font_size:10 #################################################### # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ##################################################### # LAst Box Layout BoxLayout: padding:5 AsyncImage: size_hint_y: None source: 'http://kivy.org/slides/kivypictures-thumb.jpg' width: 100 allow_stretch: True Label: text:"Asynchronous Image " font_size:11 bold:True Label: text:" Webserver image " font_size:10 Output: arorakashish0911 ruhelaa48 germanshephered48 varshagumber28 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2022" }, { "code": null, "e": 266, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 308, "s": 266, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 405, "s": 308, "text": "The Image widget is used to display an image. To use the image widget you must have to import : " }, { "code": null, "e": 494, "s": 405, "text": "from kivy.uix.image import Image, AsyncImage (not necessary while working with .kv file)" }, { "code": null, "e": 628, "s": 494, "text": "because the module kivy.uix.image have all the functionality related to images.Images can be loaded to the Application via two types:" }, { "code": null, "e": 842, "s": 628, "text": "1) Synchronous Loading: Loading image from the system (must be from the folder in which .py and .kv file is saved) 2) Asynchronous Loading: To load an image asynchronously (for example from an external webserver) " }, { "code": null, "e": 1007, "s": 842, "text": "Note: By default, the image is centered and fits inside the widget bounding box. If you don’t want that, you can set allow_stretch to True and keep_ratio to False. " }, { "code": null, "e": 1424, "s": 1007, "text": "Basic Approach to create multiple layout in one file:\n1) import kivy\n2) import kivyApp\n3) import image\n4) import BoxLayout\n5) set minimum version(optional)\n6) Create the Layout class\n7) Create App class\n8) Create .kv file:\n 1) Add BoxLayout\n 2) Add Label\n 3) Add Image\n 4) Resizing, Positioning etc of Image \n9) return instance of the layout class\n10) Run an instance of the class" }, { "code": null, "e": 1598, "s": 1424, "text": "So in the below code, we will explain How to load Synchronous and Asynchronous images. Also How to resize, Positioning, Label, etc the image with some more stuff..py file – " }, { "code": null, "e": 1606, "s": 1598, "text": "Python3" }, { "code": "## Sample Python application demonstrating the ## working with images in Kivy using .kv file ################################################### import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # BoxLayout arranges children in a vertical or horizontal box.# or help to put the children at the desired location.from kivy.uix.boxlayout import BoxLayout # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the root widget used in .kv fileclass Imagekv(BoxLayout): ''' no need to do anything here as we are building things in .kv file ''' pass # class in which name .kv file must be named My.kv.class MyApp(App): # define build() function def build(self): # returning the instance of Imagekv class return Imagekv() # run the Appif __name__ == '__main__': MyApp().run()", "e": 2848, "s": 1606, "text": null }, { "code": null, "e": 2877, "s": 2848, "text": " .kv file implementation – " }, { "code": null, "e": 2885, "s": 2877, "text": "Python3" }, { "code": "# How to use images in kivy using .kv # root widget od Imagekv Class<Imagekv>: # Giving orientation to Box Layout orientation:'vertical' ############################################### # Adding Box Layout BoxLayout: padding:5 # Adding image from the system Image: source: 'download.jpg' # Giving the size of image size_hint_x: 0.4 # allow stretching of image allow_stretch: True # Giving Label to images Label: text:\"Python\" font_size:11 bold:True Label: text:\"Programing Language\" font_size:10 ############################################### # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ################################################ # Another Box Layout BoxLayout: padding:5 Image: source:\"downloading.jpg\" size_hint_x: 0.4 allow_stretch: True Label: text:\"Image\" font_size:11 bold:True Label: text:\"Python Image\" font_size:10 ############################################# # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ############################################### # Adding next Box Layout BoxLayout: padding:5 # To load an image asynchronously # (for example from an external webserver) AsyncImage: source: 'http://kivy.org/logos/kivy-logo-black-64.png' width: 100 allow_stretch: True Label: text:\" Asynchronous Image \" font_size:11 bold:True Label: text:\"Kivy Logo\" font_size:10 #################################################### # Drawing the line between the multiples Label: canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: size: self.size pos: self.pos size_hint_y: None height: 1 ##################################################### # LAst Box Layout BoxLayout: padding:5 AsyncImage: size_hint_y: None source: 'http://kivy.org/slides/kivypictures-thumb.jpg' width: 100 allow_stretch: True Label: text:\"Asynchronous Image \" font_size:11 bold:True Label: text:\" Webserver image \" font_size:10", "e": 5856, "s": 2885, "text": null }, { "code": null, "e": 5865, "s": 5856, "text": "Output: " }, { "code": null, "e": 5884, "s": 5867, "text": "arorakashish0911" }, { "code": null, "e": 5894, "s": 5884, "text": "ruhelaa48" }, { "code": null, "e": 5912, "s": 5894, "text": "germanshephered48" }, { "code": null, "e": 5927, "s": 5912, "text": "varshagumber28" }, { "code": null, "e": 5938, "s": 5927, "text": "Python-gui" }, { "code": null, "e": 5950, "s": 5938, "text": "Python-kivy" }, { "code": null, "e": 5957, "s": 5950, "text": "Python" }, { "code": null, "e": 6055, "s": 5957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6073, "s": 6055, "text": "Python Dictionary" }, { "code": null, "e": 6115, "s": 6073, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6137, "s": 6115, "text": "Enumerate() in Python" }, { "code": null, "e": 6163, "s": 6137, "text": "Python String | replace()" }, { "code": null, "e": 6195, "s": 6163, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6224, "s": 6195, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6251, "s": 6224, "text": "Python Classes and Objects" }, { "code": null, "e": 6287, "s": 6251, "text": "Convert integer to string in Python" }, { "code": null, "e": 6308, "s": 6287, "text": "Python OOPs Concepts" } ]
Print all paths from a given source to a destination
19 Jan, 2022 Given a directed graph, a source vertex ‘s’ and a destination vertex ‘d’, print all paths from given ‘s’ to ‘d’. Consider the following directed graph. Let the s be 2 and d be 3. There are 3 different paths from 2 to 3. Approach: The idea is to do Depth First Traversal of given directed graph.Start the DFS traversal from source.Keep storing the visited vertices in an array or HashMap say ‘path[]’.If the destination vertex is reached, print contents of path[].The important thing is to mark current vertices in the path[] as visited also so that the traversal doesn’t go in a cycle. The idea is to do Depth First Traversal of given directed graph. Start the DFS traversal from source. Keep storing the visited vertices in an array or HashMap say ‘path[]’. If the destination vertex is reached, print contents of path[]. The important thing is to mark current vertices in the path[] as visited also so that the traversal doesn’t go in a cycle. Following is implementation of above idea. C++14 Java Python3 C# Javascript // C++ program to print all paths// from a source to destination.#include <iostream>#include <list>using namespace std; // A directed graph using// adjacency list representationclass Graph { int V; // No. of vertices in graph list<int>* adj; // Pointer to an array containing adjacency lists // A recursive function used by printAllPaths() void printAllPathsUtil(int, int, bool[], int[], int&); public: Graph(int V); // Constructor void addEdge(int u, int v); void printAllPaths(int s, int d);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); // Add v to u’s list.} // Prints all paths from 's' to 'd'void Graph::printAllPaths(int s, int d){ // Mark all the vertices as not visited bool* visited = new bool[V]; // Create an array to store paths int* path = new int[V]; int path_index = 0; // Initialize path[] as empty // Initialize all vertices as not visited for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to print all paths printAllPathsUtil(s, d, visited, path, path_index);} // A recursive function to print all paths from 'u' to 'd'.// visited[] keeps track of vertices in current path.// path[] stores actual vertices and path_index is current// index in path[]void Graph::printAllPathsUtil(int u, int d, bool visited[], int path[], int& path_index){ // Mark the current node and store it in path[] visited[u] = true; path[path_index] = u; path_index++; // If current vertex is same as destination, then print // current path[] if (u == d) { for (int i = 0; i < path_index; i++) cout << path[i] << " "; cout << endl; } else // If current vertex is not destination { // Recur for all the vertices adjacent to current vertex list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (!visited[*i]) printAllPathsUtil(*i, d, visited, path, path_index); } // Remove current vertex from path[] and mark it as unvisited path_index--; visited[u] = false;} // Driver programint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); int s = 2, d = 3; cout << "Following are all different paths from " << s << " to " << d << endl; g.printAllPaths(s, d); return 0;} // JAVA program to print all// paths from a source to// destination.import java.util.ArrayList;import java.util.List; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int v; // adjacency list private ArrayList<Integer>[] adjList; // Constructor public Graph(int vertices) { // initialise vertex count this.v = vertices; // initialise adjacency list initAdjList(); } // utility method to initialise // adjacency list @SuppressWarnings("unchecked") private void initAdjList() { adjList = new ArrayList[v]; for (int i = 0; i < v; i++) { adjList[i] = new ArrayList<>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } // Prints all paths from // 's' to 'd' public void printAllPaths(int s, int d) { boolean[] isVisited = new boolean[v]; ArrayList<Integer> pathList = new ArrayList<>(); // add source to path[] pathList.add(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList); } // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current path private void printAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) { if (u.equals(d)) { System.out.println(localPathList); // if match found then no need to traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex for (Integer i : adjList[u]) { if (!isVisited[i]) { // store current node // in path[] localPathList.add(i); printAllPathsUtil(i, d, isVisited, localPathList); // remove current node // in path[] localPathList.remove(i); } } // Mark the current node isVisited[u] = false; } // Driver program public static void main(String[] args) { // Create a sample graph Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); // arbitrary source int s = 2; // arbitrary destination int d = 3; System.out.println( "Following are all different paths from " + s + " to " + d); g.printAllPaths(s, d); }} // This code is contributed by Himanshu Shekhar. # Python program to print all paths from a source to destination. from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) '''A recursive function to print all paths from 'u' to 'd'. visited[] keeps track of vertices in current path. path[] stores actual vertices and path_index is current index in path[]''' def printAllPathsUtil(self, u, d, visited, path): # Mark the current node as visited and store in path visited[u]= True path.append(u) # If current vertex is same as destination, then print # current path[] if u == d: print (path) else: # If current vertex is not destination # Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]== False: self.printAllPathsUtil(i, d, visited, path) # Remove current vertex from path[] and mark it as unvisited path.pop() visited[u]= False # Prints all paths from 's' to 'd' def printAllPaths(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create an array to store paths path = [] # Call the recursive helper function to print all paths self.printAllPathsUtil(s, d, visited, path) # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(0, 3)g.addEdge(2, 0)g.addEdge(2, 1)g.addEdge(1, 3) s = 2 ; d = 3print ("Following are all different paths from % d to % d :" %(s, d))g.printAllPaths(s, d)# This code is contributed by Neelam Yadav // C# program to print all// paths from a source to// destination.using System;using System.Collections.Generic; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int v; // adjacency list private List<int>[] adjList; // Constructor public Graph(int vertices) { // initialise vertex count this.v = vertices; // initialise adjacency list initAdjList(); } // utility method to initialise // adjacency list private void initAdjList() { adjList = new List<int>[v]; for (int i = 0; i < v; i++) { adjList[i] = new List<int>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].Add(v); } // Prints all paths from // 's' to 'd' public void printAllPaths(int s, int d) { bool[] isVisited = new bool[v]; List<int> pathList = new List<int>(); // add source to path[] pathList.Add(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList); } // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current path private void printAllPathsUtil(int u, int d, bool[] isVisited, List<int> localPathList) { if (u.Equals(d)) { Console.WriteLine(string.Join(" ", localPathList)); // if match found then no need // to traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex foreach(int i in adjList[u]) { if (!isVisited[i]) { // store current node // in path[] localPathList.Add(i); printAllPathsUtil(i, d, isVisited, localPathList); // remove current node // in path[] localPathList.Remove(i); } } // Mark the current node isVisited[u] = false; } // Driver code public static void Main(String[] args) { // Create a sample graph Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); // arbitrary source int s = 2; // arbitrary destination int d = 3; Console.WriteLine("Following are all different" + " paths from " + s + " to " + d); g.printAllPaths(s, d); }} // This code contributed by Rajput-Ji <script> // JavaScript program to print all// paths from a source to// destination. let v; let adjList; // A directed graph using// adjacency list representationfunction Graph(vertices){ // initialise vertex count v = vertices; // initialise adjacency list initAdjList();} // utility method to initialise // adjacency listfunction initAdjList(){ adjList = new Array(v); for (let i = 0; i < v; i++) { adjList[i] = []; }} // add edge from u to vfunction addEdge(u,v){ // Add v to u's list. adjList[u].push(v);} // Prints all paths from // 's' to 'd'function printAllPaths(s,d){ let isVisited = new Array(v); for(let i=0;i<v;i++) isVisited[i]=false; let pathList = []; // add source to path[] pathList.push(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList);} // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current pathfunction printAllPathsUtil(u,d,isVisited,localPathList){ if (u == (d)) { document.write(localPathList+"<br>"); // if match found then no need to // traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex for (let i=0;i< adjList[u].length;i++) { if (!isVisited[adjList[u][i]]) { // store current node // in path[] localPathList.push(adjList[u][i]); printAllPathsUtil(adjList[u][i], d, isVisited, localPathList); // remove current node // in path[] localPathList.splice(localPathList.indexOf (adjList[u][i]),1); } } // Mark the current node isVisited[u] = false;} // Driver program// Create a sample graphGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(0, 3);addEdge(2, 0);addEdge(2, 1);addEdge(1, 3); // arbitrary sourcelet s = 2; // arbitrary destinationlet d = 3; document.write("Following are all different paths from "+ s + " to " + d+"<Br>");printAllPaths(s, d); // This code is contributed by avanitrachhadiya2155 </script> Output: Following are all different paths from 2 to 3 2 0 1 3 2 0 3 2 1 3 Complexity Analysis: Time Complexity: O(V^V). The time complexity is polynomial. From each vertex there are v vertices that can be visited from current vertex. Auxiliary space: O(V^V). To store the paths V^V space is needed. This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sparsh singhal Rajput-Ji andrew1234 azatdzhanybekov rskrish avanitrachhadiya2155 amartyaghoshgfg DFS Backtracking Graph DFS Graph Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction m Coloring Problem | Backtracking-5 Generate all the binary strings of N bits Hamiltonian Cycle | Backtracking-6 Backtracking to find all subsets Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jan, 2022" }, { "code": null, "e": 275, "s": 54, "text": "Given a directed graph, a source vertex ‘s’ and a destination vertex ‘d’, print all paths from given ‘s’ to ‘d’. Consider the following directed graph. Let the s be 2 and d be 3. There are 3 different paths from 2 to 3. " }, { "code": null, "e": 288, "s": 277, "text": "Approach: " }, { "code": null, "e": 644, "s": 288, "text": "The idea is to do Depth First Traversal of given directed graph.Start the DFS traversal from source.Keep storing the visited vertices in an array or HashMap say ‘path[]’.If the destination vertex is reached, print contents of path[].The important thing is to mark current vertices in the path[] as visited also so that the traversal doesn’t go in a cycle." }, { "code": null, "e": 709, "s": 644, "text": "The idea is to do Depth First Traversal of given directed graph." }, { "code": null, "e": 746, "s": 709, "text": "Start the DFS traversal from source." }, { "code": null, "e": 817, "s": 746, "text": "Keep storing the visited vertices in an array or HashMap say ‘path[]’." }, { "code": null, "e": 881, "s": 817, "text": "If the destination vertex is reached, print contents of path[]." }, { "code": null, "e": 1004, "s": 881, "text": "The important thing is to mark current vertices in the path[] as visited also so that the traversal doesn’t go in a cycle." }, { "code": null, "e": 1049, "s": 1004, "text": "Following is implementation of above idea. " }, { "code": null, "e": 1055, "s": 1049, "text": "C++14" }, { "code": null, "e": 1060, "s": 1055, "text": "Java" }, { "code": null, "e": 1068, "s": 1060, "text": "Python3" }, { "code": null, "e": 1071, "s": 1068, "text": "C#" }, { "code": null, "e": 1082, "s": 1071, "text": "Javascript" }, { "code": "// C++ program to print all paths// from a source to destination.#include <iostream>#include <list>using namespace std; // A directed graph using// adjacency list representationclass Graph { int V; // No. of vertices in graph list<int>* adj; // Pointer to an array containing adjacency lists // A recursive function used by printAllPaths() void printAllPathsUtil(int, int, bool[], int[], int&); public: Graph(int V); // Constructor void addEdge(int u, int v); void printAllPaths(int s, int d);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); // Add v to u’s list.} // Prints all paths from 's' to 'd'void Graph::printAllPaths(int s, int d){ // Mark all the vertices as not visited bool* visited = new bool[V]; // Create an array to store paths int* path = new int[V]; int path_index = 0; // Initialize path[] as empty // Initialize all vertices as not visited for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to print all paths printAllPathsUtil(s, d, visited, path, path_index);} // A recursive function to print all paths from 'u' to 'd'.// visited[] keeps track of vertices in current path.// path[] stores actual vertices and path_index is current// index in path[]void Graph::printAllPathsUtil(int u, int d, bool visited[], int path[], int& path_index){ // Mark the current node and store it in path[] visited[u] = true; path[path_index] = u; path_index++; // If current vertex is same as destination, then print // current path[] if (u == d) { for (int i = 0; i < path_index; i++) cout << path[i] << \" \"; cout << endl; } else // If current vertex is not destination { // Recur for all the vertices adjacent to current vertex list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (!visited[*i]) printAllPathsUtil(*i, d, visited, path, path_index); } // Remove current vertex from path[] and mark it as unvisited path_index--; visited[u] = false;} // Driver programint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); int s = 2, d = 3; cout << \"Following are all different paths from \" << s << \" to \" << d << endl; g.printAllPaths(s, d); return 0;}", "e": 3631, "s": 1082, "text": null }, { "code": "// JAVA program to print all// paths from a source to// destination.import java.util.ArrayList;import java.util.List; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int v; // adjacency list private ArrayList<Integer>[] adjList; // Constructor public Graph(int vertices) { // initialise vertex count this.v = vertices; // initialise adjacency list initAdjList(); } // utility method to initialise // adjacency list @SuppressWarnings(\"unchecked\") private void initAdjList() { adjList = new ArrayList[v]; for (int i = 0; i < v; i++) { adjList[i] = new ArrayList<>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } // Prints all paths from // 's' to 'd' public void printAllPaths(int s, int d) { boolean[] isVisited = new boolean[v]; ArrayList<Integer> pathList = new ArrayList<>(); // add source to path[] pathList.add(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList); } // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current path private void printAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) { if (u.equals(d)) { System.out.println(localPathList); // if match found then no need to traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex for (Integer i : adjList[u]) { if (!isVisited[i]) { // store current node // in path[] localPathList.add(i); printAllPathsUtil(i, d, isVisited, localPathList); // remove current node // in path[] localPathList.remove(i); } } // Mark the current node isVisited[u] = false; } // Driver program public static void main(String[] args) { // Create a sample graph Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); // arbitrary source int s = 2; // arbitrary destination int d = 3; System.out.println( \"Following are all different paths from \" + s + \" to \" + d); g.printAllPaths(s, d); }} // This code is contributed by Himanshu Shekhar.", "e": 6543, "s": 3631, "text": null }, { "code": "# Python program to print all paths from a source to destination. from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) '''A recursive function to print all paths from 'u' to 'd'. visited[] keeps track of vertices in current path. path[] stores actual vertices and path_index is current index in path[]''' def printAllPathsUtil(self, u, d, visited, path): # Mark the current node as visited and store in path visited[u]= True path.append(u) # If current vertex is same as destination, then print # current path[] if u == d: print (path) else: # If current vertex is not destination # Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]== False: self.printAllPathsUtil(i, d, visited, path) # Remove current vertex from path[] and mark it as unvisited path.pop() visited[u]= False # Prints all paths from 's' to 'd' def printAllPaths(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create an array to store paths path = [] # Call the recursive helper function to print all paths self.printAllPathsUtil(s, d, visited, path) # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(0, 3)g.addEdge(2, 0)g.addEdge(2, 1)g.addEdge(1, 3) s = 2 ; d = 3print (\"Following are all different paths from % d to % d :\" %(s, d))g.printAllPaths(s, d)# This code is contributed by Neelam Yadav", "e": 8522, "s": 6543, "text": null }, { "code": "// C# program to print all// paths from a source to// destination.using System;using System.Collections.Generic; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int v; // adjacency list private List<int>[] adjList; // Constructor public Graph(int vertices) { // initialise vertex count this.v = vertices; // initialise adjacency list initAdjList(); } // utility method to initialise // adjacency list private void initAdjList() { adjList = new List<int>[v]; for (int i = 0; i < v; i++) { adjList[i] = new List<int>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].Add(v); } // Prints all paths from // 's' to 'd' public void printAllPaths(int s, int d) { bool[] isVisited = new bool[v]; List<int> pathList = new List<int>(); // add source to path[] pathList.Add(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList); } // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current path private void printAllPathsUtil(int u, int d, bool[] isVisited, List<int> localPathList) { if (u.Equals(d)) { Console.WriteLine(string.Join(\" \", localPathList)); // if match found then no need // to traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex foreach(int i in adjList[u]) { if (!isVisited[i]) { // store current node // in path[] localPathList.Add(i); printAllPathsUtil(i, d, isVisited, localPathList); // remove current node // in path[] localPathList.Remove(i); } } // Mark the current node isVisited[u] = false; } // Driver code public static void Main(String[] args) { // Create a sample graph Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); // arbitrary source int s = 2; // arbitrary destination int d = 3; Console.WriteLine(\"Following are all different\" + \" paths from \" + s + \" to \" + d); g.printAllPaths(s, d); }} // This code contributed by Rajput-Ji", "e": 11415, "s": 8522, "text": null }, { "code": "<script> // JavaScript program to print all// paths from a source to// destination. let v; let adjList; // A directed graph using// adjacency list representationfunction Graph(vertices){ // initialise vertex count v = vertices; // initialise adjacency list initAdjList();} // utility method to initialise // adjacency listfunction initAdjList(){ adjList = new Array(v); for (let i = 0; i < v; i++) { adjList[i] = []; }} // add edge from u to vfunction addEdge(u,v){ // Add v to u's list. adjList[u].push(v);} // Prints all paths from // 's' to 'd'function printAllPaths(s,d){ let isVisited = new Array(v); for(let i=0;i<v;i++) isVisited[i]=false; let pathList = []; // add source to path[] pathList.push(s); // Call recursive utility printAllPathsUtil(s, d, isVisited, pathList);} // A recursive function to print // all paths from 'u' to 'd'. // isVisited[] keeps track of // vertices in current path. // localPathList<> stores actual // vertices in the current pathfunction printAllPathsUtil(u,d,isVisited,localPathList){ if (u == (d)) { document.write(localPathList+\"<br>\"); // if match found then no need to // traverse more till depth return; } // Mark the current node isVisited[u] = true; // Recur for all the vertices // adjacent to current vertex for (let i=0;i< adjList[u].length;i++) { if (!isVisited[adjList[u][i]]) { // store current node // in path[] localPathList.push(adjList[u][i]); printAllPathsUtil(adjList[u][i], d, isVisited, localPathList); // remove current node // in path[] localPathList.splice(localPathList.indexOf (adjList[u][i]),1); } } // Mark the current node isVisited[u] = false;} // Driver program// Create a sample graphGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(0, 3);addEdge(2, 0);addEdge(2, 1);addEdge(1, 3); // arbitrary sourcelet s = 2; // arbitrary destinationlet d = 3; document.write(\"Following are all different paths from \"+ s + \" to \" + d+\"<Br>\");printAllPaths(s, d); // This code is contributed by avanitrachhadiya2155 </script>", "e": 13818, "s": 11415, "text": null }, { "code": null, "e": 13828, "s": 13818, "text": "Output: " }, { "code": null, "e": 13895, "s": 13828, "text": "Following are all different paths from 2 to 3\n2 0 1 3\n2 0 3\n2 1 3 " }, { "code": null, "e": 13918, "s": 13895, "text": "Complexity Analysis: " }, { "code": null, "e": 14057, "s": 13918, "text": "Time Complexity: O(V^V). The time complexity is polynomial. From each vertex there are v vertices that can be visited from current vertex." }, { "code": null, "e": 14122, "s": 14057, "text": "Auxiliary space: O(V^V). To store the paths V^V space is needed." }, { "code": null, "e": 14293, "s": 14122, "text": "This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14308, "s": 14293, "text": "sparsh singhal" }, { "code": null, "e": 14318, "s": 14308, "text": "Rajput-Ji" }, { "code": null, "e": 14329, "s": 14318, "text": "andrew1234" }, { "code": null, "e": 14345, "s": 14329, "text": "azatdzhanybekov" }, { "code": null, "e": 14353, "s": 14345, "text": "rskrish" }, { "code": null, "e": 14374, "s": 14353, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14390, "s": 14374, "text": "amartyaghoshgfg" }, { "code": null, "e": 14394, "s": 14390, "text": "DFS" }, { "code": null, "e": 14407, "s": 14394, "text": "Backtracking" }, { "code": null, "e": 14413, "s": 14407, "text": "Graph" }, { "code": null, "e": 14417, "s": 14413, "text": "DFS" }, { "code": null, "e": 14423, "s": 14417, "text": "Graph" }, { "code": null, "e": 14436, "s": 14423, "text": "Backtracking" }, { "code": null, "e": 14534, "s": 14436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14562, "s": 14534, "text": "Backtracking | Introduction" }, { "code": null, "e": 14598, "s": 14562, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 14640, "s": 14598, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 14675, "s": 14640, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 14708, "s": 14675, "text": "Backtracking to find all subsets" }, { "code": null, "e": 14759, "s": 14708, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 14824, "s": 14759, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 14875, "s": 14824, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Count Number of Occurrences of Certain Character in String in R
16 May, 2021 In this article, we will discuss how to count the number of occurrences of a certain character in String in R Programming Language. The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines. install.packages("stringr") The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching to the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned. Syntax: str_count(str, pattern = “”) Parameters : str – The string to count the occurrences of pattern – the pattern to match to Example 1: R library(stringr) # declaring stringstr1 = "$geeks%for!geeks%" # declaring character to findch1 = "a"print("Count for character a")str_count(str1,ch1) ch2 = "%"print("Count for character %")str_count(str1,ch2) Output [1] "Count for character a" [1] 0 [1] "Count for character %" [1] 2 Example 2: R library(stringr) # declaring stringstr = c("$geeks%for!geeks%","cs^e%portal", "le%..e3oten","joinnow3")print ("Original vector")print (str) # declaring character to findch2 = "%"print("Count for character %")str_count(str,ch2) Output [1] "Original vector" [1] "$geeks%for!geeks%" "cs^e%portal" "le%..e3oten" "joinnow3" [1] "Count for character %" [1] 2 1 1 0 This approach uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case. Syntax: gregexpr(pattern, text) This is followed by the application of the regmatches() method in R which is used to extract and then replace the list of matched substrings returned by gregexpr() method. The first argument is the original vector and the second argument is the object returned as a result of the previous method. The lengths() method is then applied in order to return the individual lengths of all the elements of the argument vector. Syntax: lengths(x) Example 1: R # declaring stringstr1 = "$geeks%for!geeks%" # declaring character to findch1 = "a"print("Count for character a")lengths(regmatches(str1, gregexpr(ch1, str1))) ch2 = "%"print("Count for character %")lengths(regmatches(str1, gregexpr(ch2, str1))) Output [1] "Count for character a" [1] 0 [1] "Count for character %" [1] 2 Example 2: R # declaring stringstr = c("$geeks%for!geeks%","cs^e%portal","le%..e3oten","joinnow3")print ("Original vector")print (str) # declaring character to findch2 = "%"print("Count for character %")lengths(regmatches(str, gregexpr(ch2, str))) Output [1] "Original vector" [1] "$geeks%for!geeks%" "cs^e%portal" "le%..e3oten" "joinnow3" [1] "Count for character %" [1] 2 1 1 0 Picked R String-Programs R-strings R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 160, "s": 28, "text": "In this article, we will discuss how to count the number of occurrences of a certain character in String in R Programming Language." }, { "code": null, "e": 320, "s": 160, "text": "The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines. " }, { "code": null, "e": 348, "s": 320, "text": "install.packages(\"stringr\")" }, { "code": null, "e": 940, "s": 348, "text": "The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching to the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned. " }, { "code": null, "e": 977, "s": 940, "text": "Syntax: str_count(str, pattern = “”)" }, { "code": null, "e": 991, "s": 977, "text": "Parameters : " }, { "code": null, "e": 1036, "s": 991, "text": "str – The string to count the occurrences of" }, { "code": null, "e": 1070, "s": 1036, "text": "pattern – the pattern to match to" }, { "code": null, "e": 1081, "s": 1070, "text": "Example 1:" }, { "code": null, "e": 1083, "s": 1081, "text": "R" }, { "code": "library(stringr) # declaring stringstr1 = \"$geeks%for!geeks%\" # declaring character to findch1 = \"a\"print(\"Count for character a\")str_count(str1,ch1) ch2 = \"%\"print(\"Count for character %\")str_count(str1,ch2)", "e": 1295, "s": 1083, "text": null }, { "code": null, "e": 1302, "s": 1295, "text": "Output" }, { "code": null, "e": 1373, "s": 1302, "text": "[1] \"Count for character a\" \n[1] 0 \n[1] \"Count for character %\" \n[1] 2" }, { "code": null, "e": 1384, "s": 1373, "text": "Example 2:" }, { "code": null, "e": 1386, "s": 1384, "text": "R" }, { "code": "library(stringr) # declaring stringstr = c(\"$geeks%for!geeks%\",\"cs^e%portal\", \"le%..e3oten\",\"joinnow3\")print (\"Original vector\")print (str) # declaring character to findch2 = \"%\"print(\"Count for character %\")str_count(str,ch2)", "e": 1622, "s": 1386, "text": null }, { "code": null, "e": 1629, "s": 1622, "text": "Output" }, { "code": null, "e": 1754, "s": 1629, "text": "[1] \"Original vector\"\n[1] \"$geeks%for!geeks%\" \"cs^e%portal\" \"le%..e3oten\" \"joinnow3\"\n[1] \"Count for character %\"\n[1] 2 1 1 0" }, { "code": null, "e": 2067, "s": 1754, "text": "This approach uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case. " }, { "code": null, "e": 2075, "s": 2067, "text": "Syntax:" }, { "code": null, "e": 2099, "s": 2075, "text": "gregexpr(pattern, text)" }, { "code": null, "e": 2520, "s": 2099, "text": "This is followed by the application of the regmatches() method in R which is used to extract and then replace the list of matched substrings returned by gregexpr() method. The first argument is the original vector and the second argument is the object returned as a result of the previous method. The lengths() method is then applied in order to return the individual lengths of all the elements of the argument vector. " }, { "code": null, "e": 2528, "s": 2520, "text": "Syntax:" }, { "code": null, "e": 2539, "s": 2528, "text": "lengths(x)" }, { "code": null, "e": 2550, "s": 2539, "text": "Example 1:" }, { "code": null, "e": 2552, "s": 2550, "text": "R" }, { "code": "# declaring stringstr1 = \"$geeks%for!geeks%\" # declaring character to findch1 = \"a\"print(\"Count for character a\")lengths(regmatches(str1, gregexpr(ch1, str1))) ch2 = \"%\"print(\"Count for character %\")lengths(regmatches(str1, gregexpr(ch2, str1)))", "e": 2800, "s": 2552, "text": null }, { "code": null, "e": 2807, "s": 2800, "text": "Output" }, { "code": null, "e": 2875, "s": 2807, "text": "[1] \"Count for character a\"\n[1] 0\n[1] \"Count for character %\"\n[1] 2" }, { "code": null, "e": 2886, "s": 2875, "text": "Example 2:" }, { "code": null, "e": 2888, "s": 2886, "text": "R" }, { "code": "# declaring stringstr = c(\"$geeks%for!geeks%\",\"cs^e%portal\",\"le%..e3oten\",\"joinnow3\")print (\"Original vector\")print (str) # declaring character to findch2 = \"%\"print(\"Count for character %\")lengths(regmatches(str, gregexpr(ch2, str)))", "e": 3124, "s": 2888, "text": null }, { "code": null, "e": 3131, "s": 3124, "text": "Output" }, { "code": null, "e": 3256, "s": 3131, "text": "[1] \"Original vector\"\n[1] \"$geeks%for!geeks%\" \"cs^e%portal\" \"le%..e3oten\" \"joinnow3\"\n[1] \"Count for character %\"\n[1] 2 1 1 0" }, { "code": null, "e": 3263, "s": 3256, "text": "Picked" }, { "code": null, "e": 3281, "s": 3263, "text": "R String-Programs" }, { "code": null, "e": 3291, "s": 3281, "text": "R-strings" }, { "code": null, "e": 3302, "s": 3291, "text": "R Language" }, { "code": null, "e": 3313, "s": 3302, "text": "R Programs" } ]
Python | Maximum Sum Sublist
11 May, 2020 We can have an application for finding the lists with the maximum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambdaThe above two functions can help us achieve this particular task. The lambda function does the task of logic and iteration and reduce function does the task of returning the required result. Works in Python 2 only. # Python code to demonstrate# maximum sum sublist # using reduce() + lambda # importing functools for reduce()import functools # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]] # printing the original matrixprint ("The original matrix is : " + str(test_matrix)) # using reduce() + lambda# maximum sum sublist res = functools.reduce(lambda i, j: i if sum(i) > sum(j) else j, test_matrix) # printing resultprint ("Maximum sum sublist is : " + str(res)) The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]] Maximum sum sublist is : [4, 5, 3] Method #2 : Using max() + keyThe max function can get the maximum of all the list and key is used to specify on what the max condition has to be applied that is summation in this case. # Python3 code to demonstrate# maximum sum sublist # using max() + key # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]] # printing the original matrixprint ("The original matrix is : " + str(test_matrix)) # using max() + key# maximum sum sublist res = max(test_matrix, key = sum) # printing resultprint ("Maximum sum sublist is : " + str(res)) The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]] Maximum sum sublist is : [4, 5, 3] epskvv Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 288, "s": 28, "text": "We can have an application for finding the lists with the maximum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development." }, { "code": null, "e": 538, "s": 288, "text": "Method #1 : Using reduce() + lambdaThe above two functions can help us achieve this particular task. The lambda function does the task of logic and iteration and reduce function does the task of returning the required result. Works in Python 2 only." }, { "code": "# Python code to demonstrate# maximum sum sublist # using reduce() + lambda # importing functools for reduce()import functools # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]] # printing the original matrixprint (\"The original matrix is : \" + str(test_matrix)) # using reduce() + lambda# maximum sum sublist res = functools.reduce(lambda i, j: i if sum(i) > sum(j) else j, test_matrix) # printing resultprint (\"Maximum sum sublist is : \" + str(res))", "e": 1020, "s": 538, "text": null }, { "code": null, "e": 1115, "s": 1020, "text": "The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]\nMaximum sum sublist is : [4, 5, 3]\n" }, { "code": null, "e": 1302, "s": 1117, "text": "Method #2 : Using max() + keyThe max function can get the maximum of all the list and key is used to specify on what the max condition has to be applied that is summation in this case." }, { "code": "# Python3 code to demonstrate# maximum sum sublist # using max() + key # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]] # printing the original matrixprint (\"The original matrix is : \" + str(test_matrix)) # using max() + key# maximum sum sublist res = max(test_matrix, key = sum) # printing resultprint (\"Maximum sum sublist is : \" + str(res))", "e": 1671, "s": 1302, "text": null }, { "code": null, "e": 1766, "s": 1671, "text": "The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]\nMaximum sum sublist is : [4, 5, 3]\n" }, { "code": null, "e": 1773, "s": 1766, "text": "epskvv" }, { "code": null, "e": 1794, "s": 1773, "text": "Python list-programs" }, { "code": null, "e": 1806, "s": 1794, "text": "python-list" }, { "code": null, "e": 1813, "s": 1806, "text": "Python" }, { "code": null, "e": 1829, "s": 1813, "text": "Python Programs" }, { "code": null, "e": 1841, "s": 1829, "text": "python-list" } ]
RTL (Register Transfer Level) design vs Sequential logic design
21 Dec, 2018 In this article we try to explain the fundamental differences between Register Transfer Level (RTL) Design and Sequential Logic Design. In the RTL Design methodology different types of registers such as Counters, Shift Register, SIPO (Serial In Parallel Out), PISO (Parallel In Serial Out) are used as the basic building blocks for any Sequential Logic Circuits. On the other hand Synchronous Sequential Logic Design methodology different logic gates and different memory elements such as flip flops (to store the state of circuit at any time) is used as the basic building blocks for sequential logic circuits. The Synchronous Sequential Logic Design Process using state diagram and its shortcomings are explained in the following example: Lets say, we are to design a 2-bit synchronous Binary Up Counter whose count sequence is: 00 -> 01 -> 10 -> 11 -> 00 -> 01 -> ..... so on. Step-1: In the 1st step we draw a State Diagram representing the above sequential circuit.The State Diagram representing the above counter is shown below:Figure – State Diagram for 2-bit UP CounterStep-2: In the next step we derive the State Table from the above given State DiagramThe State Table is as given below:Present State Q(n)Next State Q(n+1)Output000101011010101111110000Step-3: In the third step we need to choose the type of flip flop we will be using to store the state of the circuit, for simplicity, we will be considering the Positive Edge Triggered D-type Flip-Flop.We also need to determine the number of Flip-Flops required to represent the internal state of the circuit. The general formula for the number of Flip-Flops required:Total Number of Flip-Flops = Where, N = Total Number of States in State Table Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below:Present State Q(n)Next State Q(n+1)DX00X11Step-4: In this step we combine the State Table from the 2nd step with the excitation table of the previous step as follows:000101011010101111110000Step-5: Next, from the above table we try to express as boolean functions of .In this case the expression for both are trivial.The Final Sequential Circuit is shown below:Figure – The Final Circuit Step-1: In the 1st step we draw a State Diagram representing the above sequential circuit.The State Diagram representing the above counter is shown below:Figure – State Diagram for 2-bit UP Counter Step-2: In the next step we derive the State Table from the above given State DiagramThe State Table is as given below:Present State Q(n)Next State Q(n+1)Output000101011010101111110000 The State Table is as given below: Step-3: In the third step we need to choose the type of flip flop we will be using to store the state of the circuit, for simplicity, we will be considering the Positive Edge Triggered D-type Flip-Flop.We also need to determine the number of Flip-Flops required to represent the internal state of the circuit. The general formula for the number of Flip-Flops required:Total Number of Flip-Flops = Where, N = Total Number of States in State Table Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below:Present State Q(n)Next State Q(n+1)DX00X11 Total Number of Flip-Flops = Where, N = Total Number of States in State Table Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below: Step-4: In this step we combine the State Table from the 2nd step with the excitation table of the previous step as follows:000101011010101111110000 Step-5: Next, from the above table we try to express as boolean functions of .In this case the expression for both are trivial. In this case the expression for both are trivial. The Final Sequential Circuit is shown below: Shortcomings of the above process: From the above example we observe that the Synchronous Sequential Logic Design process is a fairly involved process and requires us to go through a sequence of well defined steps even for simple circuits like the one above. Secondly, if the number of states become large then this process becomes cumbersome and time-consuming, and sometimes even impossible. To Address the above drawbacks of the Sequential Logic Design process and to enable Digital Designers to design circuits of higher complexity with ease, the RTL design methodology was introduced. The most popular example of RTL Design is that of a Processor, which is nothing but a very sophisticated Finite State Machine with a very large number of states. The main differences between RTL Design and Sequential Logic Design are summarized below: Technical Scripter 2018 Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Latches in Digital Logic Digital to Analog Conversion Half Subtractor in Digital Logic Introduction of Sequential Circuits Difference between Multiplexer and Demultiplexer Ring Counter in Digital Logic Representation of Negative Binary Numbers Shift Micro-Operations in Computer Architecture
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2018" }, { "code": null, "e": 164, "s": 28, "text": "In this article we try to explain the fundamental differences between Register Transfer Level (RTL) Design and Sequential Logic Design." }, { "code": null, "e": 391, "s": 164, "text": "In the RTL Design methodology different types of registers such as Counters, Shift Register, SIPO (Serial In Parallel Out), PISO (Parallel In Serial Out) are used as the basic building blocks for any Sequential Logic Circuits." }, { "code": null, "e": 640, "s": 391, "text": "On the other hand Synchronous Sequential Logic Design methodology different logic gates and different memory elements such as flip flops (to store the state of circuit at any time) is used as the basic building blocks for sequential logic circuits." }, { "code": null, "e": 769, "s": 640, "text": "The Synchronous Sequential Logic Design Process using state diagram and its shortcomings are explained in the following example:" }, { "code": null, "e": 859, "s": 769, "text": "Lets say, we are to design a 2-bit synchronous Binary Up Counter whose count sequence is:" }, { "code": null, "e": 908, "s": 859, "text": "00 -> 01 -> 10 -> 11 -> 00 -> 01 -> ..... so on." }, { "code": null, "e": 2275, "s": 908, "text": "Step-1: In the 1st step we draw a State Diagram representing the above sequential circuit.The State Diagram representing the above counter is shown below:Figure – State Diagram for 2-bit UP CounterStep-2: In the next step we derive the State Table from the above given State DiagramThe State Table is as given below:Present State Q(n)Next State Q(n+1)Output000101011010101111110000Step-3: In the third step we need to choose the type of flip flop we will be using to store the state of the circuit, for simplicity, we will be considering the Positive Edge Triggered D-type Flip-Flop.We also need to determine the number of Flip-Flops required to represent the internal state of the circuit. The general formula for the number of Flip-Flops required:Total Number of Flip-Flops = \n Where,\n N = Total Number of States in State Table Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below:Present State Q(n)Next State Q(n+1)DX00X11Step-4: In this step we combine the State Table from the 2nd step with the excitation table of the previous step as follows:000101011010101111110000Step-5: Next, from the above table we try to express as boolean functions of .In this case the expression for both are trivial.The Final Sequential Circuit is shown below:Figure – The Final Circuit" }, { "code": null, "e": 2473, "s": 2275, "text": "Step-1: In the 1st step we draw a State Diagram representing the above sequential circuit.The State Diagram representing the above counter is shown below:Figure – State Diagram for 2-bit UP Counter" }, { "code": null, "e": 2658, "s": 2473, "text": "Step-2: In the next step we derive the State Table from the above given State DiagramThe State Table is as given below:Present State Q(n)Next State Q(n+1)Output000101011010101111110000" }, { "code": null, "e": 2693, "s": 2658, "text": "The State Table is as given below:" }, { "code": null, "e": 3332, "s": 2693, "text": "Step-3: In the third step we need to choose the type of flip flop we will be using to store the state of the circuit, for simplicity, we will be considering the Positive Edge Triggered D-type Flip-Flop.We also need to determine the number of Flip-Flops required to represent the internal state of the circuit. The general formula for the number of Flip-Flops required:Total Number of Flip-Flops = \n Where,\n N = Total Number of States in State Table Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below:Present State Q(n)Next State Q(n+1)DX00X11" }, { "code": null, "e": 3431, "s": 3332, "text": "Total Number of Flip-Flops = \n Where,\n N = Total Number of States in State Table " }, { "code": null, "e": 3562, "s": 3431, "text": "Then we need to note down the Excitation Table for chosen Flip-Flop. The Excitation Table for the D-type Flip-Flop is shown below:" }, { "code": null, "e": 3711, "s": 3562, "text": "Step-4: In this step we combine the State Table from the 2nd step with the excitation table of the previous step as follows:000101011010101111110000" }, { "code": null, "e": 3841, "s": 3711, "text": "Step-5: Next, from the above table we try to express as boolean functions of .In this case the expression for both are trivial." }, { "code": null, "e": 3892, "s": 3841, "text": "In this case the expression for both are trivial." }, { "code": null, "e": 3937, "s": 3892, "text": "The Final Sequential Circuit is shown below:" }, { "code": null, "e": 3972, "s": 3937, "text": "Shortcomings of the above process:" }, { "code": null, "e": 4196, "s": 3972, "text": "From the above example we observe that the Synchronous Sequential Logic Design process is a fairly involved process and requires us to go through a sequence of well defined steps even for simple circuits like the one above." }, { "code": null, "e": 4331, "s": 4196, "text": "Secondly, if the number of states become large then this process becomes cumbersome and time-consuming, and sometimes even impossible." }, { "code": null, "e": 4689, "s": 4331, "text": "To Address the above drawbacks of the Sequential Logic Design process and to enable Digital Designers to design circuits of higher complexity with ease, the RTL design methodology was introduced. The most popular example of RTL Design is that of a Processor, which is nothing but a very sophisticated Finite State Machine with a very large number of states." }, { "code": null, "e": 4779, "s": 4689, "text": "The main differences between RTL Design and Sequential Logic Design are summarized below:" }, { "code": null, "e": 4803, "s": 4779, "text": "Technical Scripter 2018" }, { "code": null, "e": 4838, "s": 4803, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 4936, "s": 4838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4976, "s": 4936, "text": "Introduction to memory and memory units" }, { "code": null, "e": 5005, "s": 4976, "text": "Analog to Digital Conversion" }, { "code": null, "e": 5030, "s": 5005, "text": "Latches in Digital Logic" }, { "code": null, "e": 5059, "s": 5030, "text": "Digital to Analog Conversion" }, { "code": null, "e": 5092, "s": 5059, "text": "Half Subtractor in Digital Logic" }, { "code": null, "e": 5128, "s": 5092, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 5177, "s": 5128, "text": "Difference between Multiplexer and Demultiplexer" }, { "code": null, "e": 5207, "s": 5177, "text": "Ring Counter in Digital Logic" }, { "code": null, "e": 5249, "s": 5207, "text": "Representation of Negative Binary Numbers" } ]
Different ways to sort an array in descending order in C#
15 Feb, 2019 An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Arranging the array’s elements from largest to smallest is termed as sorting the array in descending order. Examples: Input : array = {5, 9, 1, 4, 6, 8}; Output : 9, 8, 6, 5, 4, 1 Input : array = {1, 9, 6, 7, 5, 9}; Output : 9 9 7 6 5 1 Input : array = {-8, 9, 7, 7, 0, 9, -9}; Output : 9 9 7 7 0 -8 -9 Method 1: Using Array.Sort() and Array.Reverse() MethodFirst, sort the array using Array.Sort() method which sorts an array ascending order then, reverse it using Array.Reverse() method. // C# program sort an array in decreasing order// using Array.Sort() and Array.Reverse() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort array in ascending order. Array.Sort(arr); // reverse array Array.Reverse(arr); // print all element of array foreach(int value in arr) { Console.Write(value + " "); } }} 9 9 7 6 5 1 Method 2: Using CompareTo() MethodYou can also sort an array in decreasing order by using CompareTo() method. // C# program sort an array in // decreasing order using // CompareTo() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr from last to first. // compare every element to each other Array.Sort<int>(arr, new Comparison<int>( (i1, i2) => i2.CompareTo(i1))); // print all element of array foreach(int value in arr) { Console.Write(value + " "); } }} 9 9 7 6 5 1 Method 3: Using delegateHere, first Sort() the delegate using an anonymous method. // C# program sort an array // in decreasing orderusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr from last to first // Normal compare is m-n Array.Sort<int>(arr, delegate(int m, int n) { return n - m; }); // print all element of array foreach(int value in arr) { Console.Write(value + " "); } }} 9 9 7 6 5 1 Method 4: Using Iterative way Sort an array without using any inbuilt function by iterative way. // C# program sort an array // in decreasing order using // iterative wayusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; int temp; // traverse 0 to array length for (int i = 0; i < arr.Length - 1; i++) // traverse i+1 to array length for (int j = i + 1; j < arr.Length; j++) // compare array element with // all next element if (arr[i] < arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // print all element of array foreach(int value in arr) { Console.Write(value + " "); } }} 9 9 7 6 5 1 Method 5: Using LINQ descendingLINQ stands for Language Integrated Query. It is a uniform query syntax which is used to retrieve and save the data from the different sources. Here, OrderByDescending sorting method is used for descending order sorting. The LINQ returns IOrderedIEnumerable, which is converted to Array using ToArray() method. // C# program sort an array in decreasing // order by using LINQ OrderByDescending // methodusing System;using System.Linq; class GFG { // Main Method public static void Main() { // declaring and initializing the // array with 6 positive number int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr in decreasing order // and return a array arr = arr.OrderByDescending(c => c).ToArray(); // print all element of array foreach(int value in arr) { Console.Write(value + " "); } }} 9 9 7 6 5 1 CSharp-Arrays Technical Scripter 2018 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Feb, 2019" }, { "code": null, "e": 299, "s": 54, "text": "An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Arranging the array’s elements from largest to smallest is termed as sorting the array in descending order." }, { "code": null, "e": 309, "s": 299, "text": "Examples:" }, { "code": null, "e": 497, "s": 309, "text": "Input : array = {5, 9, 1, 4, 6, 8};\nOutput : 9, 8, 6, 5, 4, 1\n\nInput : array = {1, 9, 6, 7, 5, 9};\nOutput : 9 9 7 6 5 1\n\nInput : array = {-8, 9, 7, 7, 0, 9, -9};\nOutput : 9 9 7 7 0 -8 -9\n" }, { "code": null, "e": 684, "s": 497, "text": "Method 1: Using Array.Sort() and Array.Reverse() MethodFirst, sort the array using Array.Sort() method which sorts an array ascending order then, reverse it using Array.Reverse() method." }, { "code": "// C# program sort an array in decreasing order// using Array.Sort() and Array.Reverse() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort array in ascending order. Array.Sort(arr); // reverse array Array.Reverse(arr); // print all element of array foreach(int value in arr) { Console.Write(value + \" \"); } }}", "e": 1213, "s": 684, "text": null }, { "code": null, "e": 1226, "s": 1213, "text": "9 9 7 6 5 1\n" }, { "code": null, "e": 1336, "s": 1226, "text": "Method 2: Using CompareTo() MethodYou can also sort an array in decreasing order by using CompareTo() method." }, { "code": "// C# program sort an array in // decreasing order using // CompareTo() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr from last to first. // compare every element to each other Array.Sort<int>(arr, new Comparison<int>( (i1, i2) => i2.CompareTo(i1))); // print all element of array foreach(int value in arr) { Console.Write(value + \" \"); } }}", "e": 1917, "s": 1336, "text": null }, { "code": null, "e": 1930, "s": 1917, "text": "9 9 7 6 5 1\n" }, { "code": null, "e": 2013, "s": 1930, "text": "Method 3: Using delegateHere, first Sort() the delegate using an anonymous method." }, { "code": "// C# program sort an array // in decreasing orderusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr from last to first // Normal compare is m-n Array.Sort<int>(arr, delegate(int m, int n) { return n - m; }); // print all element of array foreach(int value in arr) { Console.Write(value + \" \"); } }}", "e": 2556, "s": 2013, "text": null }, { "code": null, "e": 2569, "s": 2556, "text": "9 9 7 6 5 1\n" }, { "code": null, "e": 2599, "s": 2569, "text": "Method 4: Using Iterative way" }, { "code": null, "e": 2666, "s": 2599, "text": "Sort an array without using any inbuilt function by iterative way." }, { "code": "// C# program sort an array // in decreasing order using // iterative wayusing System; class GFG { // Main Method public static void Main() { // declaring and initializing the array int[] arr = new int[] {1, 9, 6, 7, 5, 9}; int temp; // traverse 0 to array length for (int i = 0; i < arr.Length - 1; i++) // traverse i+1 to array length for (int j = i + 1; j < arr.Length; j++) // compare array element with // all next element if (arr[i] < arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // print all element of array foreach(int value in arr) { Console.Write(value + \" \"); } }}", "e": 3498, "s": 2666, "text": null }, { "code": null, "e": 3511, "s": 3498, "text": "9 9 7 6 5 1\n" }, { "code": null, "e": 3853, "s": 3511, "text": "Method 5: Using LINQ descendingLINQ stands for Language Integrated Query. It is a uniform query syntax which is used to retrieve and save the data from the different sources. Here, OrderByDescending sorting method is used for descending order sorting. The LINQ returns IOrderedIEnumerable, which is converted to Array using ToArray() method." }, { "code": "// C# program sort an array in decreasing // order by using LINQ OrderByDescending // methodusing System;using System.Linq; class GFG { // Main Method public static void Main() { // declaring and initializing the // array with 6 positive number int[] arr = new int[] {1, 9, 6, 7, 5, 9}; // Sort the arr in decreasing order // and return a array arr = arr.OrderByDescending(c => c).ToArray(); // print all element of array foreach(int value in arr) { Console.Write(value + \" \"); } }}", "e": 4439, "s": 3853, "text": null }, { "code": null, "e": 4452, "s": 4439, "text": "9 9 7 6 5 1\n" }, { "code": null, "e": 4466, "s": 4452, "text": "CSharp-Arrays" }, { "code": null, "e": 4490, "s": 4466, "text": "Technical Scripter 2018" }, { "code": null, "e": 4493, "s": 4490, "text": "C#" }, { "code": null, "e": 4512, "s": 4493, "text": "Technical Scripter" }, { "code": null, "e": 4610, "s": 4512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4638, "s": 4610, "text": "C# Dictionary with examples" }, { "code": null, "e": 4669, "s": 4638, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4684, "s": 4669, "text": "C# | Delegates" }, { "code": null, "e": 4727, "s": 4684, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4776, "s": 4727, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4792, "s": 4776, "text": "C# | Data Types" }, { "code": null, "e": 4815, "s": 4792, "text": "C# | Method Overriding" }, { "code": null, "e": 4855, "s": 4815, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 4873, "s": 4855, "text": "C# | Constructors" } ]
C# | How to check current state of a thread
01 Feb, 2019 A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ThreadState to check the current state of the thread. The initial state of a thread is Unstarted state. Syntax: public ThreadState ThreadState{ get; } Return Value: This property returns the value that indicates the state of the current thread. Below programs illustrate the use of ThreadState property: Example 1: // C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the current state // of the main thread Console.WriteLine("The name of the current state of the Main " + "thread is: {0}", thr.ThreadState); }} Output: The name of the current state of the main thread is: Running Example 2: // C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread TR1 = new Thread(new ThreadStart(job)); Thread TR2 = new Thread(new ThreadStart(job)); Console.WriteLine("ThreadState of TR1 thread"+ " is: {0}", TR1.ThreadState); Console.WriteLine("ThreadState of TR2 thread"+ " is: {0}", TR2.ThreadState); // Running state TR1.Start(); Console.WriteLine("ThreadState of TR1 thread "+ "is: {0}", TR1.ThreadState); TR2.Start(); Console.WriteLine("ThreadState of TR2 thread"+ " is: {0}", TR2.ThreadState); } // Static method public static void job() { Thread.Sleep(2000); }} Output: ThreadState of TR1 thread is: Unstarted ThreadState of TR2 thread is: Unstarted ThreadState of TR1 thread is: Running ThreadState of TR2 thread is: WaitSleepJoin Reference: https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.threadstate?view=netframework-4.7.2 CSharp Multithreading CSharp Thread Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 258, "s": 28, "text": "A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ThreadState to check the current state of the thread. The initial state of a thread is Unstarted state." }, { "code": null, "e": 266, "s": 258, "text": "Syntax:" }, { "code": null, "e": 305, "s": 266, "text": "public ThreadState ThreadState{ get; }" }, { "code": null, "e": 399, "s": 305, "text": "Return Value: This property returns the value that indicates the state of the current thread." }, { "code": null, "e": 458, "s": 399, "text": "Below programs illustrate the use of ThreadState property:" }, { "code": null, "e": 469, "s": 458, "text": "Example 1:" }, { "code": "// C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the current state // of the main thread Console.WriteLine(\"The name of the current state of the Main \" + \"thread is: {0}\", thr.ThreadState); }}", "e": 994, "s": 469, "text": null }, { "code": null, "e": 1002, "s": 994, "text": "Output:" }, { "code": null, "e": 1064, "s": 1002, "text": "The name of the current state of the main thread is: Running\n" }, { "code": null, "e": 1075, "s": 1064, "text": "Example 2:" }, { "code": "// C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread TR1 = new Thread(new ThreadStart(job)); Thread TR2 = new Thread(new ThreadStart(job)); Console.WriteLine(\"ThreadState of TR1 thread\"+ \" is: {0}\", TR1.ThreadState); Console.WriteLine(\"ThreadState of TR2 thread\"+ \" is: {0}\", TR2.ThreadState); // Running state TR1.Start(); Console.WriteLine(\"ThreadState of TR1 thread \"+ \"is: {0}\", TR1.ThreadState); TR2.Start(); Console.WriteLine(\"ThreadState of TR2 thread\"+ \" is: {0}\", TR2.ThreadState); } // Static method public static void job() { Thread.Sleep(2000); }}", "e": 1999, "s": 1075, "text": null }, { "code": null, "e": 2007, "s": 1999, "text": "Output:" }, { "code": null, "e": 2170, "s": 2007, "text": "ThreadState of TR1 thread is: Unstarted\nThreadState of TR2 thread is: Unstarted\nThreadState of TR1 thread is: Running\nThreadState of TR2 thread is: WaitSleepJoin\n" }, { "code": null, "e": 2181, "s": 2170, "text": "Reference:" }, { "code": null, "e": 2285, "s": 2181, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.threadstate?view=netframework-4.7.2" }, { "code": null, "e": 2307, "s": 2285, "text": "CSharp Multithreading" }, { "code": null, "e": 2327, "s": 2307, "text": "CSharp Thread Class" }, { "code": null, "e": 2330, "s": 2327, "text": "C#" } ]
Remove leading zeros from an array
01 Nov, 2021 Given an array of N numbers, the task is to remove all leading zeros from the array. Examples: Input : arr[] = {0, 0, 0, 1, 2, 3} Output : 1 2 3 Input : arr[] = {0, 0, 0, 1, 0, 2, 3} Output : 1 0 2 3 Approach: Mark the first non-zero number’s index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the array// removing the leading zeros#include <bits/stdc++.h>using namespace std; // Function to print the array by// removing leading zerosvoid removeZeros(int a[], int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { cout << "Array has leading zeros only"; return; } // Create an array to store // numbers apart from leading zeros int b[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) cout << b[i] << " ";} // Driver Codeint main(){ int a[] = { 0, 0, 0, 1, 2, 0, 3 }; int n = sizeof(a) / sizeof(a[0]); removeZeros(a, n); return 0;} // Java program to print the array// removing the leading zerosimport java.util.*; class solution{ // Function to print the array by// removing leading zerosstatic void removeZeros(int[] a, int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { System.out.print("Array has leading zeros only"); return; } // Create an array to store // numbers apart from leading zeros int[] b = new int[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) System.out.print(b[i]+" ");} // Driver Codepublic static void main(String args[]){ int[] a = { 0, 0, 0, 1, 2, 0, 3 }; int n = a.length; removeZeros(a, n); }} # Python3 program to print# the array removing# the leading zeros # Function to print the# array by removing# leading zerosdef removeZeros(a, n): # index to store the # first non-zero number ind = -1; # traverse in the array # and find the first # non-zero number for i in range(n): if (a[i] != 0): ind = i; break; # if no non-zero # number is there if (ind == -1): print("Array has leading zeros only"); return; # Create an array to store # numbers apart from leading # zeros b[n - ind]; b=[0]*(n - ind); # store the numbers # removing leading zeros for i in range(n - ind): b[i] = a[ind + i]; # print the array for i in range(n - ind): print( b[i] , end=" "); # Driver Codea = [0, 0, 0, 1, 2, 0, 3];n = len(a);removeZeros(a, n); # This code is contributed by mits // C# program to print the array// removing the leading zerosusing System; class solution{ // Function to print the array by// removing leading zerosstatic void removeZeros(int[] a, int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { Console.Write("Array has leading zeros only"); return; } // Create an array to store // numbers apart from leading zeros int[] b = new int[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) Console.Write(b[i]+" ");} // Driver Codepublic static void Main(String []args){ int[] a = { 0, 0, 0, 1, 2, 0, 3 }; int n = a.Length; removeZeros(a, n);}} // This code contributed by Rajput-Ji <?php// PHP program to print// the array removing// the leading zeros // Function to print the// array by removing// leading zerosfunction removeZeros($a, $n){ // index to store the // first non-zero number $ind = -1; // traverse in the array // and find the first // non-zero number for ($i = 0; $i < $n; $i++) { if ($a[$i] != 0) { $ind = $i; break; } } // if no non-zero // number is there if ($ind == -1) { echo "Array has leading " . "zeros only"; return; } // Create an array to store // numbers apart from leading // zeros b[n - ind]; // store the numbers // removing leading zeros for ($i = 0; $i < $n - $ind; $i++) $b[$i] = $a[$ind + $i]; // print the array for ($i = 0; $i < $n - $ind; $i++) echo $b[$i] , " ";} // Driver Code$a = array(0, 0, 0, 1, 2, 0, 3);$n = sizeof($a);removeZeros($a, $n); // This code is contributed by ajit?> <script> // Javascript program to print the array// removing the leading zeros // Function to print the array by // removing leading zeros function removeZeros(a , n) { // index to store the first // non-zero number var ind = -1; // traverse in the array and // find the first // non-zero number for (i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { document.write("Array has leading zeros only"); return; } // Create an array to store // numbers apart from leading zeros var b = Array(n - ind).fill(0); // store the numbers removing leading zeros for (i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (i = 0; i < n - ind; i++) document.write(b[i] + " "); } // Driver Code var a = [ 0, 0, 0, 1, 2, 0, 3 ]; var n = a.length; removeZeros(a, n); // This code is contributed by todaysgaurav </script> 1 2 0 3 jit_t sahilshelangia Rajput-Ji Mithun Kumar todaysgaurav Kirti_Mangal school-programming Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Nov, 2021" }, { "code": null, "e": 149, "s": 52, "text": "Given an array of N numbers, the task is to remove all leading zeros from the array. Examples: " }, { "code": null, "e": 259, "s": 149, "text": "Input : arr[] = {0, 0, 0, 1, 2, 3} \nOutput : 1 2 3 \n\nInput : arr[] = {0, 0, 0, 1, 0, 2, 3} \nOutput : 1 0 2 3 " }, { "code": null, "e": 526, "s": 261, "text": "Approach: Mark the first non-zero number’s index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container. Below is the implementation of the above approach: " }, { "code": null, "e": 530, "s": 526, "text": "C++" }, { "code": null, "e": 535, "s": 530, "text": "Java" }, { "code": null, "e": 543, "s": 535, "text": "Python3" }, { "code": null, "e": 546, "s": 543, "text": "C#" }, { "code": null, "e": 550, "s": 546, "text": "PHP" }, { "code": null, "e": 561, "s": 550, "text": "Javascript" }, { "code": "// C++ program to print the array// removing the leading zeros#include <bits/stdc++.h>using namespace std; // Function to print the array by// removing leading zerosvoid removeZeros(int a[], int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { cout << \"Array has leading zeros only\"; return; } // Create an array to store // numbers apart from leading zeros int b[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) cout << b[i] << \" \";} // Driver Codeint main(){ int a[] = { 0, 0, 0, 1, 2, 0, 3 }; int n = sizeof(a) / sizeof(a[0]); removeZeros(a, n); return 0;}", "e": 1562, "s": 561, "text": null }, { "code": "// Java program to print the array// removing the leading zerosimport java.util.*; class solution{ // Function to print the array by// removing leading zerosstatic void removeZeros(int[] a, int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { System.out.print(\"Array has leading zeros only\"); return; } // Create an array to store // numbers apart from leading zeros int[] b = new int[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) System.out.print(b[i]+\" \");} // Driver Codepublic static void main(String args[]){ int[] a = { 0, 0, 0, 1, 2, 0, 3 }; int n = a.length; removeZeros(a, n); }}", "e": 2596, "s": 1562, "text": null }, { "code": "# Python3 program to print# the array removing# the leading zeros # Function to print the# array by removing# leading zerosdef removeZeros(a, n): # index to store the # first non-zero number ind = -1; # traverse in the array # and find the first # non-zero number for i in range(n): if (a[i] != 0): ind = i; break; # if no non-zero # number is there if (ind == -1): print(\"Array has leading zeros only\"); return; # Create an array to store # numbers apart from leading # zeros b[n - ind]; b=[0]*(n - ind); # store the numbers # removing leading zeros for i in range(n - ind): b[i] = a[ind + i]; # print the array for i in range(n - ind): print( b[i] , end=\" \"); # Driver Codea = [0, 0, 0, 1, 2, 0, 3];n = len(a);removeZeros(a, n); # This code is contributed by mits", "e": 3482, "s": 2596, "text": null }, { "code": "// C# program to print the array// removing the leading zerosusing System; class solution{ // Function to print the array by// removing leading zerosstatic void removeZeros(int[] a, int n){ // index to store the first // non-zero number int ind = -1; // traverse in the array and find the first // non-zero number for (int i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { Console.Write(\"Array has leading zeros only\"); return; } // Create an array to store // numbers apart from leading zeros int[] b = new int[n - ind]; // store the numbers removing leading zeros for (int i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (int i = 0; i < n - ind; i++) Console.Write(b[i]+\" \");} // Driver Codepublic static void Main(String []args){ int[] a = { 0, 0, 0, 1, 2, 0, 3 }; int n = a.Length; removeZeros(a, n);}} // This code contributed by Rajput-Ji", "e": 4548, "s": 3482, "text": null }, { "code": "<?php// PHP program to print// the array removing// the leading zeros // Function to print the// array by removing// leading zerosfunction removeZeros($a, $n){ // index to store the // first non-zero number $ind = -1; // traverse in the array // and find the first // non-zero number for ($i = 0; $i < $n; $i++) { if ($a[$i] != 0) { $ind = $i; break; } } // if no non-zero // number is there if ($ind == -1) { echo \"Array has leading \" . \"zeros only\"; return; } // Create an array to store // numbers apart from leading // zeros b[n - ind]; // store the numbers // removing leading zeros for ($i = 0; $i < $n - $ind; $i++) $b[$i] = $a[$ind + $i]; // print the array for ($i = 0; $i < $n - $ind; $i++) echo $b[$i] , \" \";} // Driver Code$a = array(0, 0, 0, 1, 2, 0, 3);$n = sizeof($a);removeZeros($a, $n); // This code is contributed by ajit?>", "e": 5554, "s": 4548, "text": null }, { "code": "<script> // Javascript program to print the array// removing the leading zeros // Function to print the array by // removing leading zeros function removeZeros(a , n) { // index to store the first // non-zero number var ind = -1; // traverse in the array and // find the first // non-zero number for (i = 0; i < n; i++) { if (a[i] != 0) { ind = i; break; } } // if no non-zero number is there if (ind == -1) { document.write(\"Array has leading zeros only\"); return; } // Create an array to store // numbers apart from leading zeros var b = Array(n - ind).fill(0); // store the numbers removing leading zeros for (i = 0; i < n - ind; i++) b[i] = a[ind + i]; // print the array for (i = 0; i < n - ind; i++) document.write(b[i] + \" \"); } // Driver Code var a = [ 0, 0, 0, 1, 2, 0, 3 ]; var n = a.length; removeZeros(a, n); // This code is contributed by todaysgaurav </script>", "e": 6701, "s": 5554, "text": null }, { "code": null, "e": 6709, "s": 6701, "text": "1 2 0 3" }, { "code": null, "e": 6717, "s": 6711, "text": "jit_t" }, { "code": null, "e": 6732, "s": 6717, "text": "sahilshelangia" }, { "code": null, "e": 6742, "s": 6732, "text": "Rajput-Ji" }, { "code": null, "e": 6755, "s": 6742, "text": "Mithun Kumar" }, { "code": null, "e": 6768, "s": 6755, "text": "todaysgaurav" }, { "code": null, "e": 6781, "s": 6768, "text": "Kirti_Mangal" }, { "code": null, "e": 6800, "s": 6781, "text": "school-programming" }, { "code": null, "e": 6807, "s": 6800, "text": "Arrays" }, { "code": null, "e": 6826, "s": 6807, "text": "School Programming" }, { "code": null, "e": 6833, "s": 6826, "text": "Arrays" }, { "code": null, "e": 6931, "s": 6833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6963, "s": 6931, "text": "Introduction to Data Structures" }, { "code": null, "e": 6988, "s": 6963, "text": "Window Sliding Technique" }, { "code": null, "e": 7035, "s": 6988, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7099, "s": 7035, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7130, "s": 7099, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7148, "s": 7130, "text": "Python Dictionary" }, { "code": null, "e": 7173, "s": 7148, "text": "Reverse a string in Java" }, { "code": null, "e": 7196, "s": 7173, "text": "Introduction To PYTHON" }, { "code": null, "e": 7215, "s": 7196, "text": "Interfaces in Java" } ]
sleep command in Linux with Examples
27 May, 2019 sleep command is used to create a dummy job. A dummy job helps in delaying the execution. It takes time in seconds by default but a small suffix(s, m, h, d) can be added at the end to convert it into any other format. This command pauses the execution for an amount of time which is defined by NUMBER. Syntax: sleep NUMBER[SUFFIX]... Example: Note: If you will define more than one NUMBER with sleep command then this command will delay for the sum of the values. Options provided by sleep command: –help : It displays help information. –version : It displays version information. linux-command Linux-Shell-Commands Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples 'crontab' in Linux with Examples Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction UDP Server-Client implementation in C diff command in Linux with examples echo command in Linux with Examples Cat command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2019" }, { "code": null, "e": 330, "s": 28, "text": "sleep command is used to create a dummy job. A dummy job helps in delaying the execution. It takes time in seconds by default but a small suffix(s, m, h, d) can be added at the end to convert it into any other format. This command pauses the execution for an amount of time which is defined by NUMBER." }, { "code": null, "e": 338, "s": 330, "text": "Syntax:" }, { "code": null, "e": 363, "s": 338, "text": "sleep NUMBER[SUFFIX]...\n" }, { "code": null, "e": 372, "s": 363, "text": "Example:" }, { "code": null, "e": 493, "s": 372, "text": "Note: If you will define more than one NUMBER with sleep command then this command will delay for the sum of the values." }, { "code": null, "e": 528, "s": 493, "text": "Options provided by sleep command:" }, { "code": null, "e": 566, "s": 528, "text": "–help : It displays help information." }, { "code": null, "e": 610, "s": 566, "text": "–version : It displays version information." }, { "code": null, "e": 624, "s": 610, "text": "linux-command" }, { "code": null, "e": 645, "s": 624, "text": "Linux-Shell-Commands" }, { "code": null, "e": 656, "s": 645, "text": "Linux-Unix" }, { "code": null, "e": 675, "s": 656, "text": "Technical Scripter" }, { "code": null, "e": 773, "s": 675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 808, "s": 773, "text": "tar command in Linux with examples" }, { "code": null, "e": 844, "s": 808, "text": "curl command in Linux with Examples" }, { "code": null, "e": 877, "s": 844, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 913, "s": 877, "text": "Tail command in Linux with examples" }, { "code": null, "e": 951, "s": 913, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 977, "s": 951, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1015, "s": 977, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 1051, "s": 1015, "text": "diff command in Linux with examples" }, { "code": null, "e": 1087, "s": 1051, "text": "echo command in Linux with Examples" } ]
Different ways to sum n using numbers greater than or equal to m
05 May, 2021 Given two natural number n and m. The task is to find the number of ways in which the numbers that are greater than or equal to m can be added to get the sum n.Examples: Input : n = 3, m = 1 Output : 3 Following are three different ways to get sum n such that each term is greater than or equal to m 1 + 1 + 1, 1 + 2, 3 Input : n = 2, m = 1 Output : 2 Two ways are 1 + 1 and 2 The idea is to use Dynamic Programming by define 2D matrix, say dp[][]. dp[i][j] define the number of ways to get sum i using the numbers greater than or equal to j. So dp[i][j] can be defined as: If i < j, dp[i][j] = 0, because we cannot achieve smaller sum of i using numbers greater than or equal to j.If i = j, dp[i][j] = 1, because there is only one way to show sum i using number i which is equal to j.Else dp[i][j] = dp[i][j+1] + dp[i-j][j], because obtaining a sum i using numbers greater than or equal to j is equal to the sum of obtaining a sum of i using numbers greater than or equal to j+1 and obtaining the sum of i-j using numbers greater than or equal to j. Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to find number of ways to// which numbers that are greater than// given number can be added to get sum.#include <bits/stdc++.h>#define MAX 100using namespace std; // Return number of ways to which numbers// that are greater than given number can// be added to get sum.int numberofways(int n, int m){ int dp[n+2][n+2]; memset(dp, 0, sizeof(dp)); dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m];} // Driver Programint main(){ int n = 3, m = 1; cout << numberofways(n, m) << endl; return 0;} // Java Program to find number of ways to// which numbers that are greater than// given number can be added to get sum.import java.io.*; class GFG { // Return number of ways to which numbers // that are greater than given number can // be added to get sum. static int numberofways(int n, int m) { int dp[][]=new int[n+2][n+2]; dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m]; } // Driver Program public static void main(String args[]) { int n = 3, m = 1; System.out.println(numberofways(n, m)); }} /*This code is contributed by Nikita tiwari.*/ # Python3 Program to find number of ways to# which numbers that are greater than# given number can be added to get sum.MAX = 100import numpy as np # Return number of ways to which numbers# that are greater than given number can# be added to get sum. def numberofways(n, m) : dp = np.zeros((n + 2, n + 2)) dp[0][n + 1] = 1 # Filling the table. k is for numbers # greater than or equal that are allowed. for k in range(n, m - 1, -1) : # i is for sum for i in range(n + 1) : # initializing dp[i][k] to number # ways to get sum using numbers # greater than or equal k+1 dp[i][k] = dp[i][k + 1] # if i > k if (i - k >= 0) : dp[i][k] = (dp[i][k] + dp[i - k][k]) return dp[n][m] # Driver Codeif __name__ == "__main__" : n, m = 3, 1 print(numberofways(n, m)) # This code is contributed by Ryuga // C# program to find number of ways to// which numbers that are greater than// given number can be added to get sum.using System; class GFG { // Return number of ways to which numbers // that are greater than given number can // be added to get sum. static int numberofways(int n, int m) { int[, ] dp = new int[n + 2, n + 2]; dp[0, n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i, k] = dp[i, k + 1]; // if i > k if (i - k >= 0) dp[i, k] = (dp[i, k] + dp[i - k, k]); } } return dp[n, m]; } // Driver Program public static void Main() { int n = 3, m = 1; Console.WriteLine(numberofways(n, m)); }} /*This code is contributed by vt_m.*/ <?php // PHP Program to find number of ways to// which numbers that are greater than// given number can be added to get sum. $MAX = 100; // Return number of ways to which numbers// that are greater than given number can// be added to get sum.function numberofways($n, $m){ global $MAX; $dp = array_fill(0, $n + 2, array_fill(0, $n+2, NULL)); $dp[0][$n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for ($k = $n; $k >= $m; $k--) { // i is for sum for ($i = 0; $i <= $n; $i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 $dp[$i][$k] = $dp[$i][$k + 1]; // if i > k if ($i - $k >= 0) $dp[$i][$k] = ($dp[$i][$k] + $dp[$i - $k][$k]); } } return $dp[$n][$m];} // Driver Program $n = 3; $m = 1; echo numberofways($n, $m) ; return 0; // This code is contributed by ChitraNayal?> <script>// Javascript Program to find number of ways to// which numbers that are greater than// given number can be added to get sum. // Return number of ways to which numbers // that are greater than given number can // be added to get sum. function numberofways(n,m) { let dp=new Array(n+2); for(let i=0;i<dp.length;i++) { dp[i]=new Array(n+2); for(let j=0;j<dp[i].length;j++) { dp[i][j]=0; } } dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (let k = n; k >= m; k--) { // i is for sum for (let i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m]; } // Driver Program let n = 3, m = 1; document.write(numberofways(n, m)); // This code is contributed by avanitrachhadiya2155</script> Output: 3 ankthon ukasp avanitrachhadiya2155 Combinatorial Dynamic Programming Dynamic Programming Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find the K-th Permutation Sequence of first N natural numbers Count Derangements (Permutation such that no element appears in its original position) Permutations of a given string using STL Stack Permutations (Check if an array is stack permutation of other) Find the Number of Permutations that satisfy the given condition in an array Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25
[ { "code": null, "e": 54, "s": 26, "text": "\n05 May, 2021" }, { "code": null, "e": 226, "s": 54, "text": "Given two natural number n and m. The task is to find the number of ways in which the numbers that are greater than or equal to m can be added to get the sum n.Examples: " }, { "code": null, "e": 435, "s": 226, "text": "Input : n = 3, m = 1\nOutput : 3\nFollowing are three different ways\nto get sum n such that each term is\ngreater than or equal to m\n1 + 1 + 1, 1 + 2, 3 \n\nInput : n = 2, m = 1\nOutput : 2\nTwo ways are 1 + 1 and 2" }, { "code": null, "e": 635, "s": 437, "text": "The idea is to use Dynamic Programming by define 2D matrix, say dp[][]. dp[i][j] define the number of ways to get sum i using the numbers greater than or equal to j. So dp[i][j] can be defined as: " }, { "code": null, "e": 1112, "s": 635, "text": "If i < j, dp[i][j] = 0, because we cannot achieve smaller sum of i using numbers greater than or equal to j.If i = j, dp[i][j] = 1, because there is only one way to show sum i using number i which is equal to j.Else dp[i][j] = dp[i][j+1] + dp[i-j][j], because obtaining a sum i using numbers greater than or equal to j is equal to the sum of obtaining a sum of i using numbers greater than or equal to j+1 and obtaining the sum of i-j using numbers greater than or equal to j." }, { "code": null, "e": 1160, "s": 1112, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 1164, "s": 1160, "text": "C++" }, { "code": null, "e": 1169, "s": 1164, "text": "Java" }, { "code": null, "e": 1177, "s": 1169, "text": "Python3" }, { "code": null, "e": 1180, "s": 1177, "text": "C#" }, { "code": null, "e": 1184, "s": 1180, "text": "PHP" }, { "code": null, "e": 1195, "s": 1184, "text": "Javascript" }, { "code": "// CPP Program to find number of ways to// which numbers that are greater than// given number can be added to get sum.#include <bits/stdc++.h>#define MAX 100using namespace std; // Return number of ways to which numbers// that are greater than given number can// be added to get sum.int numberofways(int n, int m){ int dp[n+2][n+2]; memset(dp, 0, sizeof(dp)); dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m];} // Driver Programint main(){ int n = 3, m = 1; cout << numberofways(n, m) << endl; return 0;}", "e": 2178, "s": 1195, "text": null }, { "code": "// Java Program to find number of ways to// which numbers that are greater than// given number can be added to get sum.import java.io.*; class GFG { // Return number of ways to which numbers // that are greater than given number can // be added to get sum. static int numberofways(int n, int m) { int dp[][]=new int[n+2][n+2]; dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m]; } // Driver Program public static void main(String args[]) { int n = 3, m = 1; System.out.println(numberofways(n, m)); }} /*This code is contributed by Nikita tiwari.*/", "e": 3346, "s": 2178, "text": null }, { "code": "# Python3 Program to find number of ways to# which numbers that are greater than# given number can be added to get sum.MAX = 100import numpy as np # Return number of ways to which numbers# that are greater than given number can# be added to get sum. def numberofways(n, m) : dp = np.zeros((n + 2, n + 2)) dp[0][n + 1] = 1 # Filling the table. k is for numbers # greater than or equal that are allowed. for k in range(n, m - 1, -1) : # i is for sum for i in range(n + 1) : # initializing dp[i][k] to number # ways to get sum using numbers # greater than or equal k+1 dp[i][k] = dp[i][k + 1] # if i > k if (i - k >= 0) : dp[i][k] = (dp[i][k] + dp[i - k][k]) return dp[n][m] # Driver Codeif __name__ == \"__main__\" : n, m = 3, 1 print(numberofways(n, m)) # This code is contributed by Ryuga", "e": 4272, "s": 3346, "text": null }, { "code": "// C# program to find number of ways to// which numbers that are greater than// given number can be added to get sum.using System; class GFG { // Return number of ways to which numbers // that are greater than given number can // be added to get sum. static int numberofways(int n, int m) { int[, ] dp = new int[n + 2, n + 2]; dp[0, n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (int k = n; k >= m; k--) { // i is for sum for (int i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i, k] = dp[i, k + 1]; // if i > k if (i - k >= 0) dp[i, k] = (dp[i, k] + dp[i - k, k]); } } return dp[n, m]; } // Driver Program public static void Main() { int n = 3, m = 1; Console.WriteLine(numberofways(n, m)); }} /*This code is contributed by vt_m.*/", "e": 5375, "s": 4272, "text": null }, { "code": "<?php // PHP Program to find number of ways to// which numbers that are greater than// given number can be added to get sum. $MAX = 100; // Return number of ways to which numbers// that are greater than given number can// be added to get sum.function numberofways($n, $m){ global $MAX; $dp = array_fill(0, $n + 2, array_fill(0, $n+2, NULL)); $dp[0][$n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for ($k = $n; $k >= $m; $k--) { // i is for sum for ($i = 0; $i <= $n; $i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 $dp[$i][$k] = $dp[$i][$k + 1]; // if i > k if ($i - $k >= 0) $dp[$i][$k] = ($dp[$i][$k] + $dp[$i - $k][$k]); } } return $dp[$n][$m];} // Driver Program $n = 3; $m = 1; echo numberofways($n, $m) ; return 0; // This code is contributed by ChitraNayal?>", "e": 6412, "s": 5375, "text": null }, { "code": "<script>// Javascript Program to find number of ways to// which numbers that are greater than// given number can be added to get sum. // Return number of ways to which numbers // that are greater than given number can // be added to get sum. function numberofways(n,m) { let dp=new Array(n+2); for(let i=0;i<dp.length;i++) { dp[i]=new Array(n+2); for(let j=0;j<dp[i].length;j++) { dp[i][j]=0; } } dp[0][n + 1] = 1; // Filling the table. k is for numbers // greater than or equal that are allowed. for (let k = n; k >= m; k--) { // i is for sum for (let i = 0; i <= n; i++) { // initializing dp[i][k] to number // ways to get sum using numbers // greater than or equal k+1 dp[i][k] = dp[i][k + 1]; // if i > k if (i - k >= 0) dp[i][k] = (dp[i][k] + dp[i - k][k]); } } return dp[n][m]; } // Driver Program let n = 3, m = 1; document.write(numberofways(n, m)); // This code is contributed by avanitrachhadiya2155</script>", "e": 7698, "s": 6412, "text": null }, { "code": null, "e": 7708, "s": 7698, "text": "Output: " }, { "code": null, "e": 7710, "s": 7708, "text": "3" }, { "code": null, "e": 7720, "s": 7712, "text": "ankthon" }, { "code": null, "e": 7726, "s": 7720, "text": "ukasp" }, { "code": null, "e": 7747, "s": 7726, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7761, "s": 7747, "text": "Combinatorial" }, { "code": null, "e": 7781, "s": 7761, "text": "Dynamic Programming" }, { "code": null, "e": 7801, "s": 7781, "text": "Dynamic Programming" }, { "code": null, "e": 7815, "s": 7801, "text": "Combinatorial" }, { "code": null, "e": 7913, "s": 7815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7975, "s": 7913, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 8062, "s": 7975, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 8103, "s": 8062, "text": "Permutations of a given string using STL" }, { "code": null, "e": 8172, "s": 8103, "text": "Stack Permutations (Check if an array is stack permutation of other)" }, { "code": null, "e": 8249, "s": 8172, "text": "Find the Number of Permutations that satisfy the given condition in an array" }, { "code": null, "e": 8281, "s": 8249, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 8311, "s": 8281, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8340, "s": 8311, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 8374, "s": 8340, "text": "Longest Common Subsequence | DP-4" } ]
How to force a clean build of a Docker Image?
When you execute the Docker pull command or Docker run command, the daemon first checks for a similar image in the local machine by comparing the digests of the image. If it finds a match, then it’s not required to search the registry for the image and the daemon can simply create a copy of the already existing image. However, if a copy is not found, it starts pulling it from the registry. The same is the case when you try to build images using a Dockerfile. We all know that Docker images are multi-layered files containing multiple image layers on top of each other. Each instruction mentioned inside a Dockerfile is responsible for creating a new layer. A layer only consists of the differences between the previous layer and the current layer. If you have previously built the same image, the daemon will look for a cache containing the same image layer. If a subsequent cache is found, it will simply use this cache and not build a new layer. However, there might be situations where you want to force a clean build of the image even if the build cache of subsequent layers exists. Here too, Docker has got your back. Let’s see how you can force clean build a Docker image. Consider the Dockerfile below. RUN apt-get update RUN apt-get -y install vim In the above Dockerfile, we have used two different RUN instructions in separate lines. This results in the build of separate image layers and build caches. When the Docker daemon processes an update command such as RUN apt-get -y update, those packages inside the container on which the update commands work are not compared to determine if a cache hit takes place or not. In such a case, only the command string is compared to find the match. Instead of using two separate lines for two consecutive RUN instructions, you can chain them to reduce the number of image layers and hence, reducing the possibility of a cache hit. RUN apt-get update && apt-get -y install vim If you don’t want to allow the daemon to perform checks for cache at all, you can use the --no-cache option to do so. When you use the Docker build command to build a Docker image, you can simply use the --no-cache option which will allow you to instruct daemon to not look for already existing image layers and simply force clean build of an image. For example, if you want to build an image from the following Dockerfile - FROM ubuntu:latest WORKDIR /app COPY . . MAINTAINER [email protected] RUN apt-get -y update RUN apt-get install -y openjdk-7-jdk RUN apt-get install -y git-core RUN apt-get install -y build-essential RUN apt-get install -y lsb-release CMD ["javac", "sample.java"] Suppose you have already built this image previously and you have now made some changes in the build context. Hence, the COPY instruction cache breaks and so does the cache of all the subsequent instructions. If you have not made any changes and have built the image once again, there is no cache break and the daemon simply uses the existing cache of the image layers to build the image. This is the default behavior and if you want to override this default behavior, you can use the --no-cache option along with the Docker build command. $ docker build --no-cache -t sample-image:sample-tag . When you execute this command, the daemon will not look for cache builds of existing image layers and will force a clean build of the Docker image from the Dockerfile. If you use Docker compose, you can use the following command. $ docker-compose build --no-cache You can also chain this with the up command to recreate all containers. $ docker-compose build --no-cache && docker-compose up -d --force-recreate Please note that these ways do not use the cache but the builder and the base images are referenced using the FROM instruction. You can clean the builder cache using - $ docker builder prune -af You can also clear the parent images if you don’t want to use it’s cache. $ docker image rm -f parent-image These were the most common approaches that you can adopt to force clean an image build and to avoid using the image layer caches. The best and probably the easiest option is to use the --no-cache option.
[ { "code": null, "e": 1355, "s": 1187, "text": "When you execute the Docker pull command or Docker run command, the daemon first checks for a similar image in the local machine by comparing the digests of the image." }, { "code": null, "e": 1650, "s": 1355, "text": "If it finds a match, then it’s not required to search the registry for the image and the daemon can simply create a copy of the already existing image. However, if a copy is not found, it starts pulling it from the registry. The same is the case when you try to build images using a Dockerfile." }, { "code": null, "e": 1848, "s": 1650, "text": "We all know that Docker images are multi-layered files containing multiple image layers on top of each other. Each instruction mentioned inside a Dockerfile is responsible for creating a new layer." }, { "code": null, "e": 2139, "s": 1848, "text": "A layer only consists of the differences between the previous layer and the current layer. If you have previously built the same image, the daemon will look for a cache containing the same image layer. If a subsequent cache is found, it will simply use this cache and not build a new layer." }, { "code": null, "e": 2370, "s": 2139, "text": "However, there might be situations where you want to force a clean build of the image even if the build cache of subsequent layers exists. Here too, Docker has got your back. Let’s see how you can force clean build a Docker image." }, { "code": null, "e": 2401, "s": 2370, "text": "Consider the Dockerfile below." }, { "code": null, "e": 2447, "s": 2401, "text": "RUN apt-get update\nRUN apt-get -y install vim" }, { "code": null, "e": 2892, "s": 2447, "text": "In the above Dockerfile, we have used two different RUN instructions in separate lines. This results in the build of separate image layers and build caches. When the Docker daemon processes an update command such as RUN apt-get -y update, those packages inside the container on which the update commands work are not compared to determine if a cache hit takes place or not. In such a case, only the command string is compared to find the match." }, { "code": null, "e": 3074, "s": 2892, "text": "Instead of using two separate lines for two consecutive RUN instructions, you can chain them to reduce the number of image layers and hence, reducing the possibility of a cache hit." }, { "code": null, "e": 3119, "s": 3074, "text": "RUN apt-get update && apt-get -y install vim" }, { "code": null, "e": 3469, "s": 3119, "text": "If you don’t want to allow the daemon to perform checks for cache at all, you can use the --no-cache option to do so. When you use the Docker build command to build a Docker image, you can simply use the --no-cache option which will allow you to instruct daemon to not look for already existing image layers and simply force clean build of an image." }, { "code": null, "e": 3544, "s": 3469, "text": "For example, if you want to build an image from the following Dockerfile -" }, { "code": null, "e": 4250, "s": 3544, "text": "FROM ubuntu:latest\nWORKDIR /app\nCOPY . .\nMAINTAINER [email protected]\nRUN apt-get -y update\nRUN apt-get install -y openjdk-7-jdk\nRUN apt-get install -y git-core\nRUN apt-get install -y build-essential\nRUN apt-get install -y lsb-release\nCMD [\"javac\", \"sample.java\"]" }, { "code": null, "e": 4639, "s": 4250, "text": "Suppose you have already built this image previously and you have now made some changes in the build context. Hence, the COPY instruction cache breaks and so does the cache of all the subsequent instructions. If you have not made any changes and have built the image once again, there is no cache break and the daemon simply uses the existing cache of the image layers to build the image." }, { "code": null, "e": 4790, "s": 4639, "text": "This is the default behavior and if you want to override this default behavior, you can use the --no-cache option along with the Docker build command." }, { "code": null, "e": 4845, "s": 4790, "text": "$ docker build --no-cache -t sample-image:sample-tag ." }, { "code": null, "e": 5013, "s": 4845, "text": "When you execute this command, the daemon will not look for cache builds of existing image layers and will force a clean build of the Docker image from the Dockerfile." }, { "code": null, "e": 5075, "s": 5013, "text": "If you use Docker compose, you can use the following command." }, { "code": null, "e": 5109, "s": 5075, "text": "$ docker-compose build --no-cache" }, { "code": null, "e": 5181, "s": 5109, "text": "You can also chain this with the up command to recreate all containers." }, { "code": null, "e": 5257, "s": 5181, "text": "$ docker-compose build --no-cache && docker-compose up -d --force-recreate\n" }, { "code": null, "e": 5425, "s": 5257, "text": "Please note that these ways do not use the cache but the builder and the base images are referenced using the FROM instruction. You can clean the builder cache using -" }, { "code": null, "e": 5452, "s": 5425, "text": "$ docker builder prune -af" }, { "code": null, "e": 5526, "s": 5452, "text": "You can also clear the parent images if you don’t want to use it’s cache." }, { "code": null, "e": 5560, "s": 5526, "text": "$ docker image rm -f parent-image" }, { "code": null, "e": 5764, "s": 5560, "text": "These were the most common approaches that you can adopt to force clean an image build and to avoid using the image layer caches. The best and probably the easiest option is to use the --no-cache option." } ]
Scala - Sets
Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Set. If you want to use the mutable Set, you'll have to import scala.collection.mutable.Set class explicitly. If you want to use both mutable and immutable sets in the same collection, then you can continue to refer to the immutable Set as Set but you can refer to the mutable Set as mutable.Set. Here is how you can declare immutable Sets − // Empty set of integer type var s : Set[Int] = Set() // Set of integer type var s : Set[Int] = Set(1,3,5,7) or var s = Set(1,3,5,7) While defining an empty set, the type annotation is necessary as the system needs to assign a concrete type to variable. All operations on sets can be expressed in terms of the following three methods − head This method returns the first element of a set. tail This method returns a set consisting of all elements except the first. isEmpty This method returns true if the set is empty otherwise false. Try the following example showing usage of the basic operational methods − object Demo { def main(args: Array[String]) { val fruit = Set("apples", "oranges", "pears") val nums: Set[Int] = Set() println( "Head of fruit : " + fruit.head ) println( "Tail of fruit : " + fruit.tail ) println( "Check if fruit is empty : " + fruit.isEmpty ) println( "Check if nums is empty : " + nums.isEmpty ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Head of fruit : apples Tail of fruit : Set(oranges, pears) Check if fruit is empty : false Check if nums is empty : true You can use either ++ operator or Set.++() method to concatenate two or more sets, but while adding sets it will remove duplicate elements. The Following is the example to concatenate two sets. object Demo { def main(args: Array[String]) { val fruit1 = Set("apples", "oranges", "pears") val fruit2 = Set("mangoes", "banana") // use two or more sets with ++ as operator var fruit = fruit1 ++ fruit2 println( "fruit1 ++ fruit2 : " + fruit ) // use two sets with ++ as method fruit = fruit1.++(fruit2) println( "fruit1.++(fruit2) : " + fruit ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo fruit1 ++ fruit2 : Set(banana, apples, mangoes, pears, oranges) fruit1.++(fruit2) : Set(banana, apples, mangoes, pears, oranges) You can use Set.min method to find out the minimum and Set.max method to find out the maximum of the elements available in a set. Following is the example to show the program. object Demo { def main(args: Array[String]) { val num = Set(5,6,9,20,30,45) // find min and max of the elements println( "Min element in Set(5,6,9,20,30,45) : " + num.min ) println( "Max element in Set(5,6,9,20,30,45) : " + num.max ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Min element in Set(5,6,9,20,30,45) : 5 Max element in Set(5,6,9,20,30,45) : 45 You can use either Set.& method or Set.intersect method to find out the common values between two sets. Try the following example to show the usage. object Demo { def main(args: Array[String]) { val num1 = Set(5,6,9,20,30,45) val num2 = Set(50,60,9,20,35,55) // find common elements between two sets println( "num1.&(num2) : " + num1.&(num2) ) println( "num1.intersect(num2) : " + num1.intersect(num2) ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo num1.&(num2) : Set(20, 9) num1.intersect(num2) : Set(20, 9) Following are the important methods which you can use while playing with Sets. For a complete list of methods available, please check official documentation of Scala. def +(elem: A): Set[A] Creates a new set with an additional element, unless the element is already present. def -(elem: A): Set[A] Creates a new set with a given element removed from this set. def contains(elem: A): Boolean Returns true if elem is contained in this set, false otherwise. def &(that: Set[A]): Set[A] Returns a new set consisting of all elements that are both in this set and in the given set. def &~(that: Set[A]): Set[A] Returns the difference of this set and another set. def +(elem1: A, elem2: A, elems: A*): Set[A] Creates a new immutable set with additional elements from the passed sets def ++(elems: A): Set[A] Concatenates this immutable set with the elements of another collection to this immutable set. def -(elem1: A, elem2: A, elems: A*): Set[A] Returns a new immutable set that contains all elements of the current immutable set except one less occurrence of each of the given argument elements. def addString(b: StringBuilder): StringBuilder Appends all elements of this immutable set to a string builder. def addString(b: StringBuilder, sep: String): StringBuilder Appends all elements of this immutable set to a string builder using a separator string. def apply(elem: A) Tests if some element is contained in this set. def count(p: (A) => Boolean): Int Counts the number of elements in the immutable set which satisfy a predicate. def copyToArray(xs: Array[A], start: Int, len: Int): Unit Copies elements of this immutable set to an array. def diff(that: Set[A]): Set[A] Computes the difference of this set and another set. def drop(n: Int): Set[A]] Returns all elements except first n ones. def dropRight(n: Int): Set[A] Returns all elements except last n ones. def dropWhile(p: (A) => Boolean): Set[A] Drops longest prefix of elements that satisfy a predicate. def equals(that: Any): Boolean The equals method for arbitrary sequences. Compares this sequence to some other object. def exists(p: (A) => Boolean): Boolean Tests whether a predicate holds for some of the elements of this immutable set. def filter(p: (A) => Boolean): Set[A] Returns all elements of this immutable set which satisfy a predicate. def find(p: (A) => Boolean): Option[A] Finds the first element of the immutable set satisfying a predicate, if any. def forall(p: (A) => Boolean): Boolean Tests whether a predicate holds for all elements of this immutable set. def foreach(f: (A) => Unit): Unit Applies a function f to all elements of this immutable set. def head: A Returns the first element of this immutable set. def init: Set[A] Returns all elements except the last. def intersect(that: Set[A]): Set[A] Computes the intersection between this set and another set. def isEmpty: Boolean Tests if this set is empty. def iterator: Iterator[A] Creates a new iterator over all elements contained in the iterable object. def last: A Returns the last element. def map[B](f: (A) => B): immutable.Set[B] Builds a new collection by applying a function to all elements of this immutable set. def max: A Finds the largest element. def min: A Finds the smallest element. def mkString: String Displays all elements of this immutable set in a string. def mkString(sep: String): String Displays all elements of this immutable set in a string using a separator string. def product: A Returns the product of all elements of this immutable set with respect to the * operator in num. def size: Int Returns the number of elements in this immutable set. def splitAt(n: Int): (Set[A], Set[A]) Returns a pair of immutable sets consisting of the first n elements of this immutable set, and the other elements. def subsetOf(that: Set[A]): Boolean Returns true if this set is a subset of that, i.e. if every element of this set is also an element of that. def sum: A Returns the sum of all elements of this immutable set with respect to the + operator in num. def tail: Set[A] Returns a immutable set consisting of all elements of this immutable set except the first one. def take(n: Int): Set[A] Returns first n elements. def takeRight(n: Int):Set[A] Returns last n elements. def toArray: Array[A] Returns an array containing all elements of this immutable set. def toBuffer[B >: A]: Buffer[B] Returns a buffer containing all elements of this immutable set. def toList: List[A] Returns a list containing all elements of this immutable set. def toMap[T, U]: Map[T, U] Converts this immutable set to a map def toSeq: Seq[A] Returns a seq containing all elements of this immutable set. def toString(): String Returns a String representation of the object.
[ { "code": null, "e": 2468, "s": 2132, "text": "Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed." }, { "code": null, "e": 2802, "s": 2468, "text": "By default, Scala uses the immutable Set. If you want to use the mutable Set, you'll have to import scala.collection.mutable.Set class explicitly. If you want to use both mutable and immutable sets in the same collection, then you can continue to refer to the immutable Set as Set but you can refer to the mutable Set as mutable.Set." }, { "code": null, "e": 2847, "s": 2802, "text": "Here is how you can declare immutable Sets −" }, { "code": null, "e": 2985, "s": 2847, "text": "// Empty set of integer type\nvar s : Set[Int] = Set()\n\n// Set of integer type\nvar s : Set[Int] = Set(1,3,5,7)\n\nor \n\nvar s = Set(1,3,5,7)\n" }, { "code": null, "e": 3106, "s": 2985, "text": "While defining an empty set, the type annotation is necessary as the system needs to assign a concrete type to variable." }, { "code": null, "e": 3188, "s": 3106, "text": "All operations on sets can be expressed in terms of the following three methods −" }, { "code": null, "e": 3193, "s": 3188, "text": "head" }, { "code": null, "e": 3241, "s": 3193, "text": "This method returns the first element of a set." }, { "code": null, "e": 3246, "s": 3241, "text": "tail" }, { "code": null, "e": 3317, "s": 3246, "text": "This method returns a set consisting of all elements except the first." }, { "code": null, "e": 3325, "s": 3317, "text": "isEmpty" }, { "code": null, "e": 3387, "s": 3325, "text": "This method returns true if the set is empty otherwise false." }, { "code": null, "e": 3462, "s": 3387, "text": "Try the following example showing usage of the basic operational methods −" }, { "code": null, "e": 3824, "s": 3462, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit = Set(\"apples\", \"oranges\", \"pears\")\n val nums: Set[Int] = Set()\n\n println( \"Head of fruit : \" + fruit.head )\n println( \"Tail of fruit : \" + fruit.tail )\n println( \"Check if fruit is empty : \" + fruit.isEmpty )\n println( \"Check if nums is empty : \" + nums.isEmpty )\n }\n}" }, { "code": null, "e": 3931, "s": 3824, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3965, "s": 3931, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4087, "s": 3965, "text": "Head of fruit : apples\nTail of fruit : Set(oranges, pears)\nCheck if fruit is empty : false\nCheck if nums is empty : true\n" }, { "code": null, "e": 4227, "s": 4087, "text": "You can use either ++ operator or Set.++() method to concatenate two or more sets, but while adding sets it will remove duplicate elements." }, { "code": null, "e": 4281, "s": 4227, "text": "The Following is the example to concatenate two sets." }, { "code": null, "e": 4688, "s": 4281, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit1 = Set(\"apples\", \"oranges\", \"pears\")\n val fruit2 = Set(\"mangoes\", \"banana\")\n\n // use two or more sets with ++ as operator\n var fruit = fruit1 ++ fruit2\n println( \"fruit1 ++ fruit2 : \" + fruit )\n\n // use two sets with ++ as method\n fruit = fruit1.++(fruit2)\n println( \"fruit1.++(fruit2) : \" + fruit )\n }\n}" }, { "code": null, "e": 4795, "s": 4688, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4829, "s": 4795, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4959, "s": 4829, "text": "fruit1 ++ fruit2 : Set(banana, apples, mangoes, pears, oranges)\nfruit1.++(fruit2) : Set(banana, apples, mangoes, pears, oranges)\n" }, { "code": null, "e": 5135, "s": 4959, "text": "You can use Set.min method to find out the minimum and Set.max method to find out the maximum of the elements available in a set. Following is the example to show the program." }, { "code": null, "e": 5404, "s": 5135, "text": "object Demo {\n def main(args: Array[String]) {\n val num = Set(5,6,9,20,30,45)\n\n // find min and max of the elements\n println( \"Min element in Set(5,6,9,20,30,45) : \" + num.min )\n println( \"Max element in Set(5,6,9,20,30,45) : \" + num.max )\n }\n}" }, { "code": null, "e": 5511, "s": 5404, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 5545, "s": 5511, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 5625, "s": 5545, "text": "Min element in Set(5,6,9,20,30,45) : 5\nMax element in Set(5,6,9,20,30,45) : 45\n" }, { "code": null, "e": 5774, "s": 5625, "text": "You can use either Set.& method or Set.intersect method to find out the common values between two sets. Try the following example to show the usage." }, { "code": null, "e": 6070, "s": 5774, "text": "object Demo {\n def main(args: Array[String]) {\n val num1 = Set(5,6,9,20,30,45)\n val num2 = Set(50,60,9,20,35,55)\n\n // find common elements between two sets\n println( \"num1.&(num2) : \" + num1.&(num2) )\n println( \"num1.intersect(num2) : \" + num1.intersect(num2) )\n }\n}" }, { "code": null, "e": 6177, "s": 6070, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 6211, "s": 6177, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 6272, "s": 6211, "text": "num1.&(num2) : Set(20, 9)\nnum1.intersect(num2) : Set(20, 9)\n" }, { "code": null, "e": 6439, "s": 6272, "text": "Following are the important methods which you can use while playing with Sets. For a complete list of methods available, please check official documentation of Scala." }, { "code": null, "e": 6462, "s": 6439, "text": "def +(elem: A): Set[A]" }, { "code": null, "e": 6547, "s": 6462, "text": "Creates a new set with an additional element, unless the element is already present." }, { "code": null, "e": 6570, "s": 6547, "text": "def -(elem: A): Set[A]" }, { "code": null, "e": 6632, "s": 6570, "text": "Creates a new set with a given element removed from this set." }, { "code": null, "e": 6663, "s": 6632, "text": "def contains(elem: A): Boolean" }, { "code": null, "e": 6727, "s": 6663, "text": "Returns true if elem is contained in this set, false otherwise." }, { "code": null, "e": 6755, "s": 6727, "text": "def &(that: Set[A]): Set[A]" }, { "code": null, "e": 6848, "s": 6755, "text": "Returns a new set consisting of all elements that are both in this set and in the given set." }, { "code": null, "e": 6877, "s": 6848, "text": "def &~(that: Set[A]): Set[A]" }, { "code": null, "e": 6929, "s": 6877, "text": "Returns the difference of this set and another set." }, { "code": null, "e": 6974, "s": 6929, "text": "def +(elem1: A, elem2: A, elems: A*): Set[A]" }, { "code": null, "e": 7048, "s": 6974, "text": "Creates a new immutable set with additional elements from the passed sets" }, { "code": null, "e": 7073, "s": 7048, "text": "def ++(elems: A): Set[A]" }, { "code": null, "e": 7168, "s": 7073, "text": "Concatenates this immutable set with the elements of another collection to this immutable set." }, { "code": null, "e": 7213, "s": 7168, "text": "def -(elem1: A, elem2: A, elems: A*): Set[A]" }, { "code": null, "e": 7364, "s": 7213, "text": "Returns a new immutable set that contains all elements of the current immutable set except one less occurrence of each of the given argument elements." }, { "code": null, "e": 7411, "s": 7364, "text": "def addString(b: StringBuilder): StringBuilder" }, { "code": null, "e": 7475, "s": 7411, "text": "Appends all elements of this immutable set to a string builder." }, { "code": null, "e": 7535, "s": 7475, "text": "def addString(b: StringBuilder, sep: String): StringBuilder" }, { "code": null, "e": 7624, "s": 7535, "text": "Appends all elements of this immutable set to a string builder using a separator string." }, { "code": null, "e": 7643, "s": 7624, "text": "def apply(elem: A)" }, { "code": null, "e": 7691, "s": 7643, "text": "Tests if some element is contained in this set." }, { "code": null, "e": 7725, "s": 7691, "text": "def count(p: (A) => Boolean): Int" }, { "code": null, "e": 7803, "s": 7725, "text": "Counts the number of elements in the immutable set which satisfy a predicate." }, { "code": null, "e": 7861, "s": 7803, "text": "def copyToArray(xs: Array[A], start: Int, len: Int): Unit" }, { "code": null, "e": 7912, "s": 7861, "text": "Copies elements of this immutable set to an array." }, { "code": null, "e": 7943, "s": 7912, "text": "def diff(that: Set[A]): Set[A]" }, { "code": null, "e": 7996, "s": 7943, "text": "Computes the difference of this set and another set." }, { "code": null, "e": 8022, "s": 7996, "text": "def drop(n: Int): Set[A]]" }, { "code": null, "e": 8064, "s": 8022, "text": "Returns all elements except first n ones." }, { "code": null, "e": 8094, "s": 8064, "text": "def dropRight(n: Int): Set[A]" }, { "code": null, "e": 8135, "s": 8094, "text": "Returns all elements except last n ones." }, { "code": null, "e": 8176, "s": 8135, "text": "def dropWhile(p: (A) => Boolean): Set[A]" }, { "code": null, "e": 8235, "s": 8176, "text": "Drops longest prefix of elements that satisfy a predicate." }, { "code": null, "e": 8266, "s": 8235, "text": "def equals(that: Any): Boolean" }, { "code": null, "e": 8354, "s": 8266, "text": "The equals method for arbitrary sequences. Compares this sequence to some other object." }, { "code": null, "e": 8393, "s": 8354, "text": "def exists(p: (A) => Boolean): Boolean" }, { "code": null, "e": 8473, "s": 8393, "text": "Tests whether a predicate holds for some of the elements of this immutable set." }, { "code": null, "e": 8511, "s": 8473, "text": "def filter(p: (A) => Boolean): Set[A]" }, { "code": null, "e": 8581, "s": 8511, "text": "Returns all elements of this immutable set which satisfy a predicate." }, { "code": null, "e": 8620, "s": 8581, "text": "def find(p: (A) => Boolean): Option[A]" }, { "code": null, "e": 8697, "s": 8620, "text": "Finds the first element of the immutable set satisfying a predicate, if any." }, { "code": null, "e": 8736, "s": 8697, "text": "def forall(p: (A) => Boolean): Boolean" }, { "code": null, "e": 8808, "s": 8736, "text": "Tests whether a predicate holds for all elements of this immutable set." }, { "code": null, "e": 8842, "s": 8808, "text": "def foreach(f: (A) => Unit): Unit" }, { "code": null, "e": 8902, "s": 8842, "text": "Applies a function f to all elements of this immutable set." }, { "code": null, "e": 8914, "s": 8902, "text": "def head: A" }, { "code": null, "e": 8963, "s": 8914, "text": "Returns the first element of this immutable set." }, { "code": null, "e": 8980, "s": 8963, "text": "def init: Set[A]" }, { "code": null, "e": 9018, "s": 8980, "text": "Returns all elements except the last." }, { "code": null, "e": 9054, "s": 9018, "text": "def intersect(that: Set[A]): Set[A]" }, { "code": null, "e": 9114, "s": 9054, "text": "Computes the intersection between this set and another set." }, { "code": null, "e": 9135, "s": 9114, "text": "def isEmpty: Boolean" }, { "code": null, "e": 9163, "s": 9135, "text": "Tests if this set is empty." }, { "code": null, "e": 9189, "s": 9163, "text": "def iterator: Iterator[A]" }, { "code": null, "e": 9264, "s": 9189, "text": "Creates a new iterator over all elements contained in the iterable object." }, { "code": null, "e": 9276, "s": 9264, "text": "def last: A" }, { "code": null, "e": 9302, "s": 9276, "text": "Returns the last element." }, { "code": null, "e": 9344, "s": 9302, "text": "def map[B](f: (A) => B): immutable.Set[B]" }, { "code": null, "e": 9430, "s": 9344, "text": "Builds a new collection by applying a function to all elements of this immutable set." }, { "code": null, "e": 9441, "s": 9430, "text": "def max: A" }, { "code": null, "e": 9468, "s": 9441, "text": "Finds the largest element." }, { "code": null, "e": 9479, "s": 9468, "text": "def min: A" }, { "code": null, "e": 9507, "s": 9479, "text": "Finds the smallest element." }, { "code": null, "e": 9528, "s": 9507, "text": "def mkString: String" }, { "code": null, "e": 9585, "s": 9528, "text": "Displays all elements of this immutable set in a string." }, { "code": null, "e": 9619, "s": 9585, "text": "def mkString(sep: String): String" }, { "code": null, "e": 9701, "s": 9619, "text": "Displays all elements of this immutable set in a string using a separator string." }, { "code": null, "e": 9716, "s": 9701, "text": "def product: A" }, { "code": null, "e": 9813, "s": 9716, "text": "Returns the product of all elements of this immutable set with respect to the * operator in num." }, { "code": null, "e": 9827, "s": 9813, "text": "def size: Int" }, { "code": null, "e": 9881, "s": 9827, "text": "Returns the number of elements in this immutable set." }, { "code": null, "e": 9919, "s": 9881, "text": "def splitAt(n: Int): (Set[A], Set[A])" }, { "code": null, "e": 10034, "s": 9919, "text": "Returns a pair of immutable sets consisting of the first n elements of this immutable set, and the other elements." }, { "code": null, "e": 10070, "s": 10034, "text": "def subsetOf(that: Set[A]): Boolean" }, { "code": null, "e": 10178, "s": 10070, "text": "Returns true if this set is a subset of that, i.e. if every element of this set is also an element of that." }, { "code": null, "e": 10189, "s": 10178, "text": "def sum: A" }, { "code": null, "e": 10282, "s": 10189, "text": "Returns the sum of all elements of this immutable set with respect to the + operator in num." }, { "code": null, "e": 10299, "s": 10282, "text": "def tail: Set[A]" }, { "code": null, "e": 10394, "s": 10299, "text": "Returns a immutable set consisting of all elements of this immutable set except the first one." }, { "code": null, "e": 10419, "s": 10394, "text": "def take(n: Int): Set[A]" }, { "code": null, "e": 10445, "s": 10419, "text": "Returns first n elements." }, { "code": null, "e": 10474, "s": 10445, "text": "def takeRight(n: Int):Set[A]" }, { "code": null, "e": 10499, "s": 10474, "text": "Returns last n elements." }, { "code": null, "e": 10521, "s": 10499, "text": "def toArray: Array[A]" }, { "code": null, "e": 10585, "s": 10521, "text": "Returns an array containing all elements of this immutable set." }, { "code": null, "e": 10617, "s": 10585, "text": "def toBuffer[B >: A]: Buffer[B]" }, { "code": null, "e": 10681, "s": 10617, "text": "Returns a buffer containing all elements of this immutable set." }, { "code": null, "e": 10701, "s": 10681, "text": "def toList: List[A]" }, { "code": null, "e": 10763, "s": 10701, "text": "Returns a list containing all elements of this immutable set." }, { "code": null, "e": 10790, "s": 10763, "text": "def toMap[T, U]: Map[T, U]" }, { "code": null, "e": 10827, "s": 10790, "text": "Converts this immutable set to a map" }, { "code": null, "e": 10845, "s": 10827, "text": "def toSeq: Seq[A]" }, { "code": null, "e": 10906, "s": 10845, "text": "Returns a seq containing all elements of this immutable set." }, { "code": null, "e": 10929, "s": 10906, "text": "def toString(): String" } ]
Information Classification in Information Security
19 Feb, 2021 In today’s world, Information is one of the essential parts of our life. In this, we will discuss the categorization of information on the basis of different organizations and different parameters. Information in an organization should be categorized and must be kept confidential and that’s why information security comes into the picture, and it plays a vital role for any organization. The main reason for classifying information is that not all data/information has the same level of importance or the same level of relevance/critical to an organization. Some data are more valuable to people who make strategic decisions (senior management) because they aid them in making long-run or short-range business direction decisions. Some data such as trade secrets, formulas (used by scientific and/or research organizations), and new product information (such as the use by marketing staff and sales force) are so valuable that their loss could create significant problems for the enterprise in the market. Thus, it is obvious that information is used to prevent unauthorized disclosure and the resultant failure of confidentiality. Schemes for Information Classifications as follows. Government OrganizationPrivate Organizations Government Organization Private Organizations Levels in Government organization for Information Classification : Unclassified –Information that is neither sensitive nor classified. The public release of this information does not violate confidentiality.Sensitive but Unclassified –Information that has been designed as a major secret but may not create serious damage if disclosed.Confidential –The unauthorized disclosure of confidential information could cause some damage to the country’s national securitySecret –The unauthorized disclosure of this information could cause serious damage to the countries national security.Top Secret –his is the highest level of information classification. Any unauthorized disclosure of top-secret information will cause grave damage to the country’s national security. Unclassified –Information that is neither sensitive nor classified. The public release of this information does not violate confidentiality. Sensitive but Unclassified –Information that has been designed as a major secret but may not create serious damage if disclosed. Confidential –The unauthorized disclosure of confidential information could cause some damage to the country’s national security Secret –The unauthorized disclosure of this information could cause serious damage to the countries national security. Top Secret –his is the highest level of information classification. Any unauthorized disclosure of top-secret information will cause grave damage to the country’s national security. Levels in Private Organizations for Information Classification : Public –Information that is similar to unclassified information. However, if it is disclosed, it is not expected to seriously impact the company.Sensitive –Information that required a higher level of classification than normal data. This information is protected from a loss of confidentiality as well as from loss of integrity owing to an unauthorized alteration.Private –Typically, this is the information i.e. considered of a personal nature and is intended for company use only, its disclosure could adversely affect the company or its employee salary levels and medical information could be considered as examples of “private information”. Public –Information that is similar to unclassified information. However, if it is disclosed, it is not expected to seriously impact the company. Sensitive –Information that required a higher level of classification than normal data. This information is protected from a loss of confidentiality as well as from loss of integrity owing to an unauthorized alteration. Private –Typically, this is the information i.e. considered of a personal nature and is intended for company use only, its disclosure could adversely affect the company or its employee salary levels and medical information could be considered as examples of “private information”. Criteria for Information Classification : Value –It is the most commonly used criteria for classifying data in the private sector. If the information is valuable to an organization it needs to be classified.Age –The classification of the information may be lowered if the information value decreases over time.Useful Life –Information will be more useful if it will be available to make the changes as per requirements than, it will be more useful.Personal association –If the information is personally associated with a specific individual or is addressed by a privacy law then it may need to be classified. Value –It is the most commonly used criteria for classifying data in the private sector. If the information is valuable to an organization it needs to be classified. Age –The classification of the information may be lowered if the information value decreases over time. Useful Life –Information will be more useful if it will be available to make the changes as per requirements than, it will be more useful. Personal association –If the information is personally associated with a specific individual or is addressed by a privacy law then it may need to be classified. Information-Security Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2021" }, { "code": null, "e": 443, "s": 54, "text": "In today’s world, Information is one of the essential parts of our life. In this, we will discuss the categorization of information on the basis of different organizations and different parameters. Information in an organization should be categorized and must be kept confidential and that’s why information security comes into the picture, and it plays a vital role for any organization." }, { "code": null, "e": 1187, "s": 443, "text": "The main reason for classifying information is that not all data/information has the same level of importance or the same level of relevance/critical to an organization. Some data are more valuable to people who make strategic decisions (senior management) because they aid them in making long-run or short-range business direction decisions. Some data such as trade secrets, formulas (used by scientific and/or research organizations), and new product information (such as the use by marketing staff and sales force) are so valuable that their loss could create significant problems for the enterprise in the market. Thus, it is obvious that information is used to prevent unauthorized disclosure and the resultant failure of confidentiality." }, { "code": null, "e": 1239, "s": 1187, "text": "Schemes for Information Classifications as follows." }, { "code": null, "e": 1284, "s": 1239, "text": "Government OrganizationPrivate Organizations" }, { "code": null, "e": 1308, "s": 1284, "text": "Government Organization" }, { "code": null, "e": 1330, "s": 1308, "text": "Private Organizations" }, { "code": null, "e": 1397, "s": 1330, "text": "Levels in Government organization for Information Classification :" }, { "code": null, "e": 2093, "s": 1397, "text": "Unclassified –Information that is neither sensitive nor classified. The public release of this information does not violate confidentiality.Sensitive but Unclassified –Information that has been designed as a major secret but may not create serious damage if disclosed.Confidential –The unauthorized disclosure of confidential information could cause some damage to the country’s national securitySecret –The unauthorized disclosure of this information could cause serious damage to the countries national security.Top Secret –his is the highest level of information classification. Any unauthorized disclosure of top-secret information will cause grave damage to the country’s national security." }, { "code": null, "e": 2234, "s": 2093, "text": "Unclassified –Information that is neither sensitive nor classified. The public release of this information does not violate confidentiality." }, { "code": null, "e": 2363, "s": 2234, "text": "Sensitive but Unclassified –Information that has been designed as a major secret but may not create serious damage if disclosed." }, { "code": null, "e": 2492, "s": 2363, "text": "Confidential –The unauthorized disclosure of confidential information could cause some damage to the country’s national security" }, { "code": null, "e": 2611, "s": 2492, "text": "Secret –The unauthorized disclosure of this information could cause serious damage to the countries national security." }, { "code": null, "e": 2793, "s": 2611, "text": "Top Secret –his is the highest level of information classification. Any unauthorized disclosure of top-secret information will cause grave damage to the country’s national security." }, { "code": null, "e": 2858, "s": 2793, "text": "Levels in Private Organizations for Information Classification :" }, { "code": null, "e": 3503, "s": 2858, "text": "Public –Information that is similar to unclassified information. However, if it is disclosed, it is not expected to seriously impact the company.Sensitive –Information that required a higher level of classification than normal data. This information is protected from a loss of confidentiality as well as from loss of integrity owing to an unauthorized alteration.Private –Typically, this is the information i.e. considered of a personal nature and is intended for company use only, its disclosure could adversely affect the company or its employee salary levels and medical information could be considered as examples of “private information”." }, { "code": null, "e": 3649, "s": 3503, "text": "Public –Information that is similar to unclassified information. However, if it is disclosed, it is not expected to seriously impact the company." }, { "code": null, "e": 3869, "s": 3649, "text": "Sensitive –Information that required a higher level of classification than normal data. This information is protected from a loss of confidentiality as well as from loss of integrity owing to an unauthorized alteration." }, { "code": null, "e": 4150, "s": 3869, "text": "Private –Typically, this is the information i.e. considered of a personal nature and is intended for company use only, its disclosure could adversely affect the company or its employee salary levels and medical information could be considered as examples of “private information”." }, { "code": null, "e": 4192, "s": 4150, "text": "Criteria for Information Classification :" }, { "code": null, "e": 4759, "s": 4192, "text": "Value –It is the most commonly used criteria for classifying data in the private sector. If the information is valuable to an organization it needs to be classified.Age –The classification of the information may be lowered if the information value decreases over time.Useful Life –Information will be more useful if it will be available to make the changes as per requirements than, it will be more useful.Personal association –If the information is personally associated with a specific individual or is addressed by a privacy law then it may need to be classified." }, { "code": null, "e": 4925, "s": 4759, "text": "Value –It is the most commonly used criteria for classifying data in the private sector. If the information is valuable to an organization it needs to be classified." }, { "code": null, "e": 5029, "s": 4925, "text": "Age –The classification of the information may be lowered if the information value decreases over time." }, { "code": null, "e": 5168, "s": 5029, "text": "Useful Life –Information will be more useful if it will be available to make the changes as per requirements than, it will be more useful." }, { "code": null, "e": 5329, "s": 5168, "text": "Personal association –If the information is personally associated with a specific individual or is addressed by a privacy law then it may need to be classified." }, { "code": null, "e": 5350, "s": 5329, "text": "Information-Security" }, { "code": null, "e": 5355, "s": 5350, "text": "Misc" }, { "code": null, "e": 5360, "s": 5355, "text": "Misc" }, { "code": null, "e": 5365, "s": 5360, "text": "Misc" } ]
How to Create a Histogram from Pandas DataFrame?
19 Dec, 2021 A histogram is a graph that displays the frequency of values in a metric variable’s intervals. These intervals are referred to as “bins,” and they are all the same width. We can create a histogram from the panda’s data frame using the df.hist() function. Syntax: DataFrame.hist(column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False, **kwargs) We use df.hist() and plot.show() to display the Histogram. CSV file used: gene_expression.csv Python3 # import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # reading the CSV filedf = pd.read_csv('gene_expression.csv') # displaying the DataFrameprint(df) # creating a basic histogramdf.hist()plt.show() Output: In this example, we add extra parameters to the hist method. We have changed the fig size, no of bins is specified as 15, and by parameter is given which ensures histograms for each cancer group are created. Python3 # import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # reading the CSV filedf = pd.read_csv('gene_expression.csv') # displaying the DataFrameprint(df) # creating a basic histogramdf.hist(by='Cancer Present', figsize=[12, 8], bins=15)plt.show() Output: Picked Python pandas-plotting 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": "\n19 Dec, 2021" }, { "code": null, "e": 199, "s": 28, "text": "A histogram is a graph that displays the frequency of values in a metric variable’s intervals. These intervals are referred to as “bins,” and they are all the same width." }, { "code": null, "e": 283, "s": 199, "text": "We can create a histogram from the panda’s data frame using the df.hist() function." }, { "code": null, "e": 291, "s": 283, "text": "Syntax:" }, { "code": null, "e": 506, "s": 291, "text": "DataFrame.hist(column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False, **kwargs)" }, { "code": null, "e": 565, "s": 506, "text": "We use df.hist() and plot.show() to display the Histogram." }, { "code": null, "e": 600, "s": 565, "text": "CSV file used: gene_expression.csv" }, { "code": null, "e": 608, "s": 600, "text": "Python3" }, { "code": "# import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # reading the CSV filedf = pd.read_csv('gene_expression.csv') # displaying the DataFrameprint(df) # creating a basic histogramdf.hist()plt.show()", "e": 878, "s": 608, "text": null }, { "code": null, "e": 886, "s": 878, "text": "Output:" }, { "code": null, "e": 1094, "s": 886, "text": "In this example, we add extra parameters to the hist method. We have changed the fig size, no of bins is specified as 15, and by parameter is given which ensures histograms for each cancer group are created." }, { "code": null, "e": 1102, "s": 1094, "text": "Python3" }, { "code": "# import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # reading the CSV filedf = pd.read_csv('gene_expression.csv') # displaying the DataFrameprint(df) # creating a basic histogramdf.hist(by='Cancer Present', figsize=[12, 8], bins=15)plt.show()", "e": 1417, "s": 1102, "text": null }, { "code": null, "e": 1425, "s": 1417, "text": "Output:" }, { "code": null, "e": 1432, "s": 1425, "text": "Picked" }, { "code": null, "e": 1455, "s": 1432, "text": "Python pandas-plotting" }, { "code": null, "e": 1469, "s": 1455, "text": "Python-pandas" }, { "code": null, "e": 1476, "s": 1469, "text": "Python" } ]
Python | Count keys with particular value in dictionary
22 Jun, 2022 Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it’s occurrence. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased. Python3 # Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using loop # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize valueK = 2 # Using loop# Selective key values in dictionaryres = 0for key in test_dict: if test_dict[key] == K: res = res + 1 # printing resultprint("Frequency of K is : " + str(res)) The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3 Method #2 : Using sum() + values() This can also be solved using the combination of sum() and value(). In this, sum is used to perform the summation of values filtered and values of dictionary are extracted using values() Python3 # Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using sum() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize valueK = 2 # Using sum() + values()# Selective key values in dictionaryres = sum(x == K for x in test_dict.values()) # printing resultprint("Frequency of K is : " + str(res)) The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3 Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value. Python3 # Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using count() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize valueK = 2 # Using count() + values()list1=list(test_dict.values()) # Selective key values in dictionaryres = list1.count(K) # printing resultprint("Frequency of K is : " + str(res)) The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3 In all the solutions time and space complexity are the same: Time Complexity: O(n) Space Complexity: O(n) kogantibhavya harshmaster07705 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 470, "s": 52, "text": "Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it’s occurrence. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased. " }, { "code": null, "e": 478, "s": 470, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using loop # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize valueK = 2 # Using loop# Selective key values in dictionaryres = 0for key in test_dict: if test_dict[key] == K: res = res + 1 # printing resultprint(\"Frequency of K is : \" + str(res))", "e": 964, "s": 478, "text": null }, { "code": null, "e": 1062, "s": 964, "text": "The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}\nFrequency of K is : 3" }, { "code": null, "e": 1287, "s": 1062, "text": " Method #2 : Using sum() + values() This can also be solved using the combination of sum() and value(). In this, sum is used to perform the summation of values filtered and values of dictionary are extracted using values() " }, { "code": null, "e": 1295, "s": 1287, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using sum() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize valueK = 2 # Using sum() + values()# Selective key values in dictionaryres = sum(x == K for x in test_dict.values()) # printing resultprint(\"Frequency of K is : \" + str(res))", "e": 1774, "s": 1295, "text": null }, { "code": null, "e": 1872, "s": 1774, "text": "The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}\nFrequency of K is : 3" }, { "code": null, "e": 1992, "s": 1872, "text": "Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value." }, { "code": null, "e": 2000, "s": 1992, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using count() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize valueK = 2 # Using count() + values()list1=list(test_dict.values()) # Selective key values in dictionaryres = list1.count(K) # printing resultprint(\"Frequency of K is : \" + str(res))", "e": 2488, "s": 2000, "text": null }, { "code": null, "e": 2586, "s": 2488, "text": "The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}\nFrequency of K is : 3" }, { "code": null, "e": 2647, "s": 2586, "text": "In all the solutions time and space complexity are the same:" }, { "code": null, "e": 2669, "s": 2647, "text": "Time Complexity: O(n)" }, { "code": null, "e": 2692, "s": 2669, "text": "Space Complexity: O(n)" }, { "code": null, "e": 2706, "s": 2692, "text": "kogantibhavya" }, { "code": null, "e": 2723, "s": 2706, "text": "harshmaster07705" }, { "code": null, "e": 2750, "s": 2723, "text": "Python dictionary-programs" }, { "code": null, "e": 2757, "s": 2750, "text": "Python" }, { "code": null, "e": 2773, "s": 2757, "text": "Python Programs" } ]
MS Project - Create a New Plan
When working with MS Project you either specify a start date or a finish date. Because once you enter one of the two, and other project tasks, constraints and dependencies, MS Project will calculate the other date. It is always a good practice to use a start date even if you know the deadline for the project. Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013. Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013. Windows 8 − On the Start screen, tap or click Project 2013. Windows 8 − On the Start screen, tap or click Project 2013. Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013. Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013. MS Project 2013 will display a list of options. In the list of available templates, click Blank Project. Project sets the plan’s start date to current date, a thin green vertical line in the chart portion of the Gantt Chart View indicates this current date. Let us change the project start date and add some more information. Click Project tab → Properties Group → Project Information. A dialog box appears. In the start date box, type 11/5/15, or click the down arrow to display the calendar, select November 5, 2015 (or any date of your choice). Click OK to accept the start date. Click Project tab → Properties Group → Project Information. Click the arrow on the Current Date dropdown box. A list appears containing three base calendars. 24 Hour − A calendar with no non-working time. 24 Hour − A calendar with no non-working time. Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks. Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks. Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks. Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks. Select a Standard Calendar as your project Calendar. Click “Cancel” or “OK” to close the dialog box. Now let us add exceptions. Exceptions are used to modify a Project calendar to have a non-standard workday or a non-working day. You can also allot unique working hours for a particular resource as well. Here is an example to create a non-working day, which could be because of a holiday or office celebrations or events other than the standard office work effort. Click Project tab → Properties Group → Change Working Time. Change Working Time dialog box appears. Under Exceptions Tab click on the Name Field, enter event as “Office Anniversary”. In the Start field enter 11/22/15, and then enter the same date in the Finish field. This date is now scheduled as a non-working day for the project. You can also verify the changed color indicated in the calendar within the dialog box as below. Click Ok to close. Just like you can change a Standard Base Calendar, you can change the work and non-working time for each resource. You can modify the resource calendar to accommodate flex-time, vacation time, training time, etc. Also remember, Resource Calendar can only be applied to work resources and not to material and cost resources. By default when we create the resources in a plan, the resource calendar matches the Standard base calendar. And any changes you make to the Project Calendar, gets reflected automatically in resource calendars, except when you create an exception in the resource calendar. In that case even if you update the project calendar, the exception in resource calendar is not affected. Click Project tab → Properties group → Click Change Working Time Change Working Time dialog box appears. Click the down arrow for the “For Calendar” drop-down box. Select the resource for whom you want to create an exception. In example below I have chosen John. Under Exceptions Tab click on the Name Field, enter event as “Personal holiday”. In the Start field enter the date (example 9/15/2015), and then enter the same date in the Finish field. Click Project tab → Properties group → Click Change Working Time. The Change Working Time dialog box appears. Click the down arrow for the “For Calendar” dropdown box. Select the resource for whom you want to change work schedule. In the following screen you can see we have chosen John. Click “Work Weeks” tab. Double-click the [default] cell below the Name column heading. Under “Selected Day(s)” choose any day you want to change the work schedule. We have chosen Tuesday and Wednesday. Click Set day(s) to these specific working times. Change the time. Click Project tab → Properties group → Click Change Working Time. The Change Working Time dialog box appears. Click the down arrow for the “For Calendar” dropdown box. Select the resource for whom you want to change work schedule. We have chosen John again. Click “Work Weeks” tab. Double-click the [default] cell below the Name column heading. Under “Selected Day(s)” choose any day you want to change the work schedule. Click any day (we have chosen Friday) and use the radio button “Set days to nonworking time”. Click OK to close the Dialog box. You will now see all Fridays are greyed out in the calendar. With Microsoft Windows Operating system, right clicking a file and selecting “Properties” brings up the file properties dialog box that contains version, security and other file details. You can record some top level information for your .mpp project file as well. This can be done as follows − Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013. Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013. Windows 8 − On the Start screen, tap or click Project 2013. Windows 8 − On the Start screen, tap or click Project 2013. Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013. Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013. Click File Tab. Under Info Tab go to Project Information. Click arrow near Project Information to click Advanced Properties. A dialog box opens, you can type in the changes as required. Click OK and don’t forget to save by clicking on Save. Before we start, let us assume you already have a Work Breakdown Structure (WBS). In context of WBS, “Work” refers to “Deliverables” and not effort. WBS identifies the deliverable at the lowest level as work package. This work package is decomposed into smaller tasks/activities, which is the effort necessary to complete the work package. So a task is action-oriented, and the work package is the deliverable or a result of one or more tasks being performed. There is a significant amount of confusion between what constitutes an activity and what constitutes a task within the project management community. But for MS Project, a task is the effort and action required to produce a particular project deliverable. MS Project does not use the term “activity”. This is simple. In Gantt Chart View, just click a cell directly below the Task Name column. Enter the task name. In the following screen, we have entered 5 different tasks. A duration of the task is the estimated amount of time it will take to complete a task. As a project manager you can estimate a task duration using expert judgment, historical information, analogous estimates or parametric estimates. You can enter task duration in terms of different dimensional units of time, namely minutes, hours, days, weeks, and months. You can use abbreviations for simplicity and ease as shown in the following table. Remember, Project default values depend on your work hours. So 1 day is not equivalent to 24 hours but has 8 hours of work for the day. Of course, you can change these defaults anytime you want. Click Project tab → Properties Group → Click Change Working Time → Click Options. You can apply this to all projects or a specific project that you are working on currently. One of the neat tricks MS Project possesses is, it considers duration of the task in workday sense. So if you have a non-working day in between, it accommodates this and ensures a task that takes 16 hours to complete to end on the 3rd day. In other words, if you have a task that needs 16 hours to complete starting on Monday 8:00 AM (if this is the time your work day starts, and 8 hours being total work hours in a day), and Tuesday being a holiday, the task will logically end on the evening of Wednesday. Tip − With manually scheduled tasks, if you are not sure about a task duration, you can just enter text such as “Check with Manager/Engineer” to come back to this later. This is simple in Gantt Chart View, click the cell below Duration column heading. Enter the duration. (Task 1 in the following screenshot) You can also enter Start and Finish date and MS Project will calculate the duration on its own. (Task 2 in the following screenshot) You can enter text as well when you don’t have a duration metric currently. (Task 3 and Task 4 in the following screenshot) Note − In the above screenshot, Task 6 is scheduled to start on Sunday, which is a nonworking day and ends on Wednesday. So essentially, one would believe that with these 3 days Monday, Tuesday, Wednesday, the duration calculated would be 3 days. But MS Project 2013 calculates it as 4 days. So one needs to be careful when choosing the start date of the task. Because for any successive operation, MS Project 2013 considers that Task 6 will take 4 days. The next time, you change the start date, the Finish date changes to reflect this 4-day duration. Elapsed Duration is the time that elapses while some event is occurring which does not require any resources. Elapsed duration for a task can be used in instances where a task will go on round-the-clock without any stoppage. A normal workday has 8 hours, and an elapsed day duration will have 24 hours. The task also continues over non-working (holidays and vacations) and working days. You can enter elapsed duration by preceding any duration abbreviation with an “e”. So 1ew is seven 24-hour days. For example, when you are ‘Waiting for the paint to dry’. And it takes 4 days for this to happen. It does not need a resource or a work effort, and all you are doing is waiting for it to dry. You can use 4ed as the time duration, which signifies 4 elapsed days, the paint can dry regardless of whether it is a weekend or if it falls on a holiday. Here in this example, the drying occurs over 24 hours over the weekend. In Project Management, Milestones are specific points in a project timeline. They are used as major progress points to manage project success and stakeholder expectations. They are primarily used for review, inputs and budgets. Mathematically, a milestone is a task of zero duration. And they can be put where there is a logical conclusion of a phase of work, or at deadlines imposed by the project plan. There are two ways you can insert a milestone. Click name of the Task which you want to insert a Milestone Click Task tab → Insert group → Click Milestone. MS Project names the new task as <New Milestone> with zero-day duration. Click on <New Milestone> to change its name. You can see the milestone appear with a rhombus symbol in the Gantt Chart View on the right. Click on any particular task or type in a new task under the Task Name Heading. Under Duration heading type in “0 days “. MS Project converts it to a Milestone. In Method 2, a task was converted to a Milestone of Zero duration. But one can also convert a task of non-zero duration into a Milestone. This is rarely used and causes confusion. Double-click a particular Task name. Task Information dialog box opens. Click Advanced tab → select option “Mark Task as Milestone”. The project summary task summarizes your whole project. In Gantt Chart View → Format Tab → Show/Hide → click to check Project Summary Task on. There can be a huge number of tasks in a project schedule, it is therefore a good idea to have a bunch of related tasks rolled up into a Summary Task to help you organize the plan in a better way. It helps you organize your plan into phases. In MS Project 2013, you can have several number of sub-tasks under any higher level task. These higher level tasks are called Summary Task. At an even higher level, they are called Phases. The highest level of a plan’s outline structure is called the Project Summary Task, which encompasses the entire project schedule. Remember because summary task is not a separate task entity but a phase of the project with several sub-tasks in it, the duration of the summary task is from the start of the first sub-task to the finish of the last sub-task. This will be automatically calculated by MS Project. Of course, you can enter a manual duration of the summary task as well which could be different from the automatically calculated duration. MS Project will keep track of both but this can cause significant confusion. In most cases, you should ensure that there is no manually entered duration for any task you will be using as a Summary Task. Let us use the following screenshot as an example. If you would like to group Task 4 and Task 5 into a Summary Task 1. You can do it in two ways. Select the names of Task 4 and Task 5. Click Task Tab → group Insert → Click Summary MS Project creates a <New Summary Task>. Rename it to Summary Task 1. You can click Task 4 row. Select “Insert Task”. A <New Task> is created. You can rename the Task. Here it is renamed as Summary Task 1. Don’t enter any duration for this task. Now select Task 4 and Task 5. Click Task tab → Schedule group → Click Indent Task Once you have a list of tasks ready to accomplish your project objectives, you need to link them with their task relationships called dependencies. For example, Task 2 can start once Task 1 has finished. These dependencies are called Links. A Guide to the Project Management Body of Knowledge (PMBOK Guide) does not define the term dependency, but refers to it as a logical relationship, which in turn is defined as a dependency between two activities, or between an activity and a milestone. In MS Project, the first task is called a predecessor because it precedes tasks that depend on it. The following task is called the successor because it succeeds, or follows tasks on which it is dependent. Any task can be a predecessor for one or more successor tasks. Likewise, any task can be a successor to one or more predecessor tasks. There are only four types of task dependencies, here we present them with examples. Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used. Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used. Finish to Finish (FF) − Cooking all dishes for dinner to finish on time. Finish to Finish (FF) − Cooking all dishes for dinner to finish on time. Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation. Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation. Start to Finish (SF) − Exam preparation will end when exam begins. Least used. Start to Finish (SF) − Exam preparation will end when exam begins. Least used. In MS Project you can identify the Task Links − Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks. Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks. Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks. Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks. Select the two tasks you want to link. In the following screenshot taken as an example, we have selected names, Task 1 and Task 2. Click Task tab → Schedule group → Link the Selected Tasks. Task 1 and Task 2 are linked with a Finish-to-Start relationship. Note − Task 2 will have a Start date of the Next working day from Finish date of Task 1. Double click a successor task you would like to link. Here I have clicked Task 4 The Task information dialog box opens Click Predecessors tab In the Table, click the empty cell below Task Name column. A drop down box appears with all Tasks defined in the project. Choose the predecessor task. Click OK. Here I have chosen Task 3. In this method, you will select a group of task, and link them all with Finish-to-Start relationship. Select multiple tasks with the help of the mouse → Task tab → Schedule group → Link the Selected Tasks. All tasks get linked. To select non-adjacent tasks, hold down Ctrl key and select each task separately. If you are in Manually Scheduled mode, any change in duration of the predecessor task will not reflect on Start date of Task 4. For example, Task 4 starts on 9/3/15 which is the next day of Finish date of Task 3. Now when we change the Duration of Task 3 from 5 to 7 days, the start date is not automatically updated for Task 4 in Manual Scheduling. You can force MS Project to respect the link (dependency) by doing the following − Select Task 4. Click Task tab → Schedule group → Respect Links. MS Project by default sets new tasks to be manually scheduled. Scheduling is controlled in two ways. Manual Scheduling − This is done to quickly capture some details without actually scheduling the tasks. You can leave out details for some of the tasks with respect to duration, start and finish dates, if you don’t know them yet. Automatic Scheduling − This uses the Scheduling engine in MS Project. It calculates values such as task durations, start dates, and finish dates automatically. It takes into accounts all constraints, links and calendars. For example, at Lucerne Publishing, the new book launch plan has been reviewed by the resources who will carry out the work and by other project stakeholders. Although you expect the plan to change somewhat as you learn more about the book launch, you now have enough confidence in the overall plan to switch from manual to automatic task scheduling. We have three different methods to convert a task to automatic schedule. If you want to change the mode for a particular task, say Task 5 in the following example. Click on Task Mode cell in the same row. Then, click the down arrow to open a dropdown box, you can select Auto Scheduled. Click Task → Tasks group → Auto Schedule. To switch completely to Auto Schedule mode − Toggle the scheduling mode of the plan by clicking the New Tasks status bar (at the bottom-left) and then selecting Auto scheduling mode. You can also change the default scheduling mode that Project applies to all new plans. Go to File tab and click Options. Then click Schedule tab and under scheduling options for this project select “All New Projects” from the dropdown box. Under new tasks created, select “Auto Scheduled” from the dropdown box.
[ { "code": null, "e": 2326, "s": 2015, "text": "When working with MS Project you either specify a start date or a finish date. Because once you enter one of the two, and other project tasks, constraints and dependencies, MS Project will calculate the other date. It is always a good practice to use a start date even if you know the deadline for the project." }, { "code": null, "e": 2435, "s": 2326, "text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013." }, { "code": null, "e": 2544, "s": 2435, "text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013." }, { "code": null, "e": 2604, "s": 2544, "text": "Windows 8 − On the Start screen, tap or click Project 2013." }, { "code": null, "e": 2664, "s": 2604, "text": "Windows 8 − On the Start screen, tap or click Project 2013." }, { "code": null, "e": 2743, "s": 2664, "text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013." }, { "code": null, "e": 2822, "s": 2743, "text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013." }, { "code": null, "e": 2927, "s": 2822, "text": "MS Project 2013 will display a list of options. In the list of available templates, click Blank Project." }, { "code": null, "e": 3080, "s": 2927, "text": "Project sets the plan’s start date to current date, a thin green vertical line in the chart portion of the Gantt Chart View indicates this current date." }, { "code": null, "e": 3148, "s": 3080, "text": "Let us change the project start date and add some more information." }, { "code": null, "e": 3208, "s": 3148, "text": "Click Project tab → Properties Group → Project Information." }, { "code": null, "e": 3370, "s": 3208, "text": "A dialog box appears. In the start date box, type 11/5/15, or click the down arrow to display the calendar, select November 5, 2015 (or any date of your choice)." }, { "code": null, "e": 3405, "s": 3370, "text": "Click OK to accept the start date." }, { "code": null, "e": 3465, "s": 3405, "text": "Click Project tab → Properties Group → Project Information." }, { "code": null, "e": 3563, "s": 3465, "text": "Click the arrow on the Current Date dropdown box. A list appears containing three base calendars." }, { "code": null, "e": 3610, "s": 3563, "text": "24 Hour − A calendar with no non-working time." }, { "code": null, "e": 3657, "s": 3610, "text": "24 Hour − A calendar with no non-working time." }, { "code": null, "e": 3771, "s": 3657, "text": "Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks." }, { "code": null, "e": 3885, "s": 3771, "text": "Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks." }, { "code": null, "e": 3980, "s": 3885, "text": "Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks." }, { "code": null, "e": 4075, "s": 3980, "text": "Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks." }, { "code": null, "e": 4176, "s": 4075, "text": "Select a Standard Calendar as your project Calendar. Click “Cancel” or “OK” to close the dialog box." }, { "code": null, "e": 4203, "s": 4176, "text": "Now let us add exceptions." }, { "code": null, "e": 4380, "s": 4203, "text": "Exceptions are used to modify a Project calendar to have a non-standard workday or a non-working day. You can also allot unique working hours for a particular resource as well." }, { "code": null, "e": 4541, "s": 4380, "text": "Here is an example to create a non-working day, which could be because of a holiday or office celebrations or events other than the standard office work effort." }, { "code": null, "e": 4602, "s": 4541, "text": "Click Project tab → Properties Group → Change Working Time.\n" }, { "code": null, "e": 4990, "s": 4602, "text": "Change Working Time dialog box appears. Under Exceptions Tab click on the Name Field, enter event as “Office Anniversary”. In the Start field enter 11/22/15, and then enter the same date in the Finish field. This date is now scheduled as a non-working day for the project. You can also verify the changed color indicated in the calendar within the dialog box as below. Click Ok to close." }, { "code": null, "e": 5203, "s": 4990, "text": "Just like you can change a Standard Base Calendar, you can change the work and non-working time for each resource. You can modify the resource calendar to accommodate flex-time, vacation time, training time, etc." }, { "code": null, "e": 5314, "s": 5203, "text": "Also remember, Resource Calendar can only be applied to work resources and not to material and cost resources." }, { "code": null, "e": 5693, "s": 5314, "text": "By default when we create the resources in a plan, the resource calendar matches the Standard base calendar. And any changes you make to the Project Calendar, gets reflected automatically in resource calendars, except when you create an exception in the resource calendar. In that case even if you update the project calendar, the exception in resource calendar is not affected." }, { "code": null, "e": 5960, "s": 5693, "text": "Click Project tab → Properties group → Click Change Working Time\n\nChange Working Time dialog box appears. \n\nClick the down arrow for the “For Calendar” drop-down box.\n\nSelect the resource for whom you want to create an exception. In example below I have chosen John." }, { "code": null, "e": 6146, "s": 5960, "text": "Under Exceptions Tab click on the Name Field, enter event as “Personal holiday”. In the Start field enter the date (example 9/15/2015), and then enter the same date in the Finish field." }, { "code": null, "e": 6715, "s": 6146, "text": "Click Project tab → Properties group → Click Change Working Time.\n\nThe Change Working Time dialog box appears. \n\nClick the down arrow for the “For Calendar” dropdown box.\n\nSelect the resource for whom you want to change work schedule. \nIn the following screen you can see we have chosen John.\n\nClick “Work Weeks” tab.\n\nDouble-click the [default] cell below the Name column heading.\n\nUnder “Selected Day(s)” choose any day you want to change the work schedule. \nWe have chosen Tuesday and Wednesday.\n\t\nClick Set day(s) to these specific working times. Change the time." }, { "code": null, "e": 7334, "s": 6715, "text": "Click Project tab → Properties group → Click Change Working Time.\n\nThe Change Working Time dialog box appears.\n\nClick the down arrow for the “For Calendar” dropdown box.\n\nSelect the resource for whom you want to change work schedule. We have chosen John again.\n\nClick “Work Weeks” tab.\n\nDouble-click the [default] cell below the Name column heading.\n\nUnder “Selected Day(s)” choose any day you want to change the work schedule.\n\nClick any day (we have chosen Friday) and use the radio button “Set days to nonworking time”.\n\nClick OK to close the Dialog box. You will now see all Fridays are greyed out in the calendar." }, { "code": null, "e": 7629, "s": 7334, "text": "With Microsoft Windows Operating system, right clicking a file and selecting “Properties” brings up the file properties dialog box that contains version, security and other file details. You can record some top level information for your .mpp project file as well. This can be done as follows −" }, { "code": null, "e": 7738, "s": 7629, "text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013." }, { "code": null, "e": 7847, "s": 7738, "text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013." }, { "code": null, "e": 7907, "s": 7847, "text": "Windows 8 − On the Start screen, tap or click Project 2013." }, { "code": null, "e": 7967, "s": 7907, "text": "Windows 8 − On the Start screen, tap or click Project 2013." }, { "code": null, "e": 8046, "s": 7967, "text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013." }, { "code": null, "e": 8125, "s": 8046, "text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013." }, { "code": null, "e": 8366, "s": 8125, "text": "Click File Tab. Under Info Tab go to Project Information. Click arrow near Project Information to click Advanced Properties. A dialog box opens, you can type in the changes as required. Click OK and don’t forget to save by clicking on Save." }, { "code": null, "e": 8515, "s": 8366, "text": "Before we start, let us assume you already have a Work Breakdown Structure (WBS). In context of WBS, “Work” refers to “Deliverables” and not effort." }, { "code": null, "e": 8826, "s": 8515, "text": "WBS identifies the deliverable at the lowest level as work package. This work package is decomposed into smaller tasks/activities, which is the effort necessary to complete the work package. So a task is action-oriented, and the work package is the deliverable or a result of one or more tasks being performed." }, { "code": null, "e": 9126, "s": 8826, "text": "There is a significant amount of confusion between what constitutes an activity and what constitutes a task within the project management community. But for MS Project, a task is the effort and action required to produce a particular project deliverable. MS Project does not use the term “activity”." }, { "code": null, "e": 9299, "s": 9126, "text": "This is simple. In Gantt Chart View, just click a cell directly below the Task Name column. Enter the task name. In the following screen, we have entered 5 different tasks." }, { "code": null, "e": 9533, "s": 9299, "text": "A duration of the task is the estimated amount of time it will take to complete a task. As a project manager you can estimate a task duration using expert judgment, historical information, analogous estimates or parametric estimates." }, { "code": null, "e": 9741, "s": 9533, "text": "You can enter task duration in terms of different dimensional units of time, namely minutes, hours, days, weeks, and months. You can use abbreviations for simplicity and ease as shown in the following table." }, { "code": null, "e": 9936, "s": 9741, "text": "Remember, Project default values depend on your work hours. So 1 day is not equivalent to 24 hours but has 8 hours of work for the day. Of course, you can change these defaults anytime you want." }, { "code": null, "e": 10018, "s": 9936, "text": "Click Project tab → Properties Group → Click Change Working Time → Click Options." }, { "code": null, "e": 10110, "s": 10018, "text": "You can apply this to all projects or a specific project that you are working on currently." }, { "code": null, "e": 10619, "s": 10110, "text": "One of the neat tricks MS Project possesses is, it considers duration of the task in workday sense. So if you have a non-working day in between, it accommodates this and ensures a task that takes 16 hours to complete to end on the 3rd day. In other words, if you have a task that needs 16 hours to complete starting on Monday 8:00 AM (if this is the time your work day starts, and 8 hours being total work hours in a day), and Tuesday being a holiday, the task will logically end on the evening of Wednesday." }, { "code": null, "e": 10789, "s": 10619, "text": "Tip − With manually scheduled tasks, if you are not sure about a task duration, you can just enter text such as “Check with Manager/Engineer” to come back to this later." }, { "code": null, "e": 10928, "s": 10789, "text": "This is simple in Gantt Chart View, click the cell below Duration column heading. Enter the duration. (Task 1 in the following screenshot)" }, { "code": null, "e": 11061, "s": 10928, "text": "You can also enter Start and Finish date and MS Project will calculate the duration on its own. (Task 2 in the following screenshot)" }, { "code": null, "e": 11185, "s": 11061, "text": "You can enter text as well when you don’t have a duration metric currently. (Task 3 and Task 4 in the following screenshot)" }, { "code": null, "e": 11738, "s": 11185, "text": "Note − In the above screenshot, Task 6 is scheduled to start on Sunday, which is a nonworking day and ends on Wednesday. So essentially, one would believe that with these 3 days Monday, Tuesday, Wednesday, the duration calculated would be 3 days. But MS Project 2013 calculates it as 4 days. So one needs to be careful when choosing the start date of the task. Because for any successive operation, MS Project 2013 considers that Task 6 will take 4 days. The next time, you change the start date, the Finish date changes to reflect this 4-day duration." }, { "code": null, "e": 12125, "s": 11738, "text": "Elapsed Duration is the time that elapses while some event is occurring which does not require any resources. Elapsed duration for a task can be used in instances where a task will go on round-the-clock without any stoppage. A normal workday has 8 hours, and an elapsed day duration will have 24 hours. The task also continues over non-working (holidays and vacations) and working days." }, { "code": null, "e": 12238, "s": 12125, "text": "You can enter elapsed duration by preceding any duration abbreviation with an “e”. So 1ew is seven 24-hour days." }, { "code": null, "e": 12657, "s": 12238, "text": "For example, when you are ‘Waiting for the paint to dry’. And it takes 4 days for this to happen. It does not need a resource or a work effort, and all you are doing is waiting for it to dry. You can use 4ed as the time duration, which signifies 4 elapsed days, the paint can dry regardless of whether it is a weekend or if it falls on a holiday. Here in this example, the drying occurs over 24 hours over the weekend." }, { "code": null, "e": 12885, "s": 12657, "text": "In Project Management, Milestones are specific points in a project timeline. They are used as major progress points to manage project success and stakeholder expectations. They are primarily used for review, inputs and budgets." }, { "code": null, "e": 13062, "s": 12885, "text": "Mathematically, a milestone is a task of zero duration. And they can be put where there is a logical conclusion of a phase of work, or at deadlines imposed by the project plan." }, { "code": null, "e": 13109, "s": 13062, "text": "There are two ways you can insert a milestone." }, { "code": null, "e": 13169, "s": 13109, "text": "Click name of the Task which you want to insert a Milestone" }, { "code": null, "e": 13219, "s": 13169, "text": "Click Task tab → Insert group → Click Milestone.\n" }, { "code": null, "e": 13292, "s": 13219, "text": "MS Project names the new task as <New Milestone> with zero-day duration." }, { "code": null, "e": 13338, "s": 13292, "text": "Click on <New Milestone> to change its name.\n" }, { "code": null, "e": 13431, "s": 13338, "text": "You can see the milestone appear with a rhombus symbol in the Gantt Chart View on the right." }, { "code": null, "e": 13555, "s": 13431, "text": "Click on any particular task or type in a new task under the Task Name Heading.\n\nUnder Duration heading type in “0 days “.\n" }, { "code": null, "e": 13594, "s": 13555, "text": "MS Project converts it to a Milestone." }, { "code": null, "e": 13774, "s": 13594, "text": "In Method 2, a task was converted to a Milestone of Zero duration. But one can also convert a task of non-zero duration into a Milestone. This is rarely used and causes confusion." }, { "code": null, "e": 13910, "s": 13774, "text": "Double-click a particular Task name.\n\nTask Information dialog box opens.\n\nClick Advanced tab → select option “Mark Task as Milestone”.\n" }, { "code": null, "e": 13966, "s": 13910, "text": "The project summary task summarizes your whole project." }, { "code": null, "e": 14054, "s": 13966, "text": "In Gantt Chart View → Format Tab → Show/Hide → click to check Project Summary Task on.\n" }, { "code": null, "e": 14296, "s": 14054, "text": "There can be a huge number of tasks in a project schedule, it is therefore a good idea to have a bunch of related tasks rolled up into a Summary Task to help you organize the plan in a better way. It helps you organize your plan into phases." }, { "code": null, "e": 14616, "s": 14296, "text": "In MS Project 2013, you can have several number of sub-tasks under any higher level task. These higher level tasks are called Summary Task. At an even higher level, they are called Phases. The highest level of a plan’s outline structure is called the Project Summary Task, which encompasses the entire project schedule." }, { "code": null, "e": 14895, "s": 14616, "text": "Remember because summary task is not a separate task entity but a phase of the project with several sub-tasks in it, the duration of the summary task is from the start of the first sub-task to the finish of the last sub-task. This will be automatically calculated by MS Project." }, { "code": null, "e": 15112, "s": 14895, "text": "Of course, you can enter a manual duration of the summary task as well which could be different from the automatically calculated duration. MS Project will keep track of both but this can cause significant confusion." }, { "code": null, "e": 15238, "s": 15112, "text": "In most cases, you should ensure that there is no manually entered duration for any task you will be using as a Summary Task." }, { "code": null, "e": 15384, "s": 15238, "text": "Let us use the following screenshot as an example. If you would like to group Task 4 and Task 5 into a Summary Task 1. You can do it in two ways." }, { "code": null, "e": 15423, "s": 15384, "text": "Select the names of Task 4 and Task 5." }, { "code": null, "e": 15470, "s": 15423, "text": "Click Task Tab → group Insert → Click Summary\n" }, { "code": null, "e": 15511, "s": 15470, "text": "MS Project creates a <New Summary Task>." }, { "code": null, "e": 15541, "s": 15511, "text": "Rename it to Summary Task 1.\n" }, { "code": null, "e": 15567, "s": 15541, "text": "You can click Task 4 row." }, { "code": null, "e": 15615, "s": 15567, "text": "Select “Insert Task”. A <New Task> is created.\n" }, { "code": null, "e": 15718, "s": 15615, "text": "You can rename the Task. Here it is renamed as Summary Task 1. Don’t enter any duration for this task." }, { "code": null, "e": 15802, "s": 15718, "text": "Now select Task 4 and Task 5.\n\nClick Task tab → Schedule group → Click Indent Task\n" }, { "code": null, "e": 16295, "s": 15802, "text": "Once you have a list of tasks ready to accomplish your project objectives, you need to link them with their task relationships called dependencies. For example, Task 2 can start once Task 1 has finished. These dependencies are called Links. A Guide to the Project Management Body of Knowledge (PMBOK Guide) does not define the term dependency, but refers to it as a logical relationship, which in turn is defined as a dependency between two activities, or between an activity and a milestone." }, { "code": null, "e": 16636, "s": 16295, "text": "In MS Project, the first task is called a predecessor because it precedes tasks that depend on it. The following task is called the successor because it succeeds, or follows tasks on which it is dependent. Any task can be a predecessor for one or more successor tasks. Likewise, any task can be a successor to one or more predecessor tasks." }, { "code": null, "e": 16720, "s": 16636, "text": "There are only four types of task dependencies, here we present them with examples." }, { "code": null, "e": 16820, "s": 16720, "text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used." }, { "code": null, "e": 16920, "s": 16820, "text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used." }, { "code": null, "e": 16993, "s": 16920, "text": "Finish to Finish (FF) − Cooking all dishes for dinner to finish on time." }, { "code": null, "e": 17066, "s": 16993, "text": "Finish to Finish (FF) − Cooking all dishes for dinner to finish on time." }, { "code": null, "e": 17273, "s": 17066, "text": "Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation." }, { "code": null, "e": 17480, "s": 17273, "text": "Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation." }, { "code": null, "e": 17559, "s": 17480, "text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used." }, { "code": null, "e": 17638, "s": 17559, "text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used." }, { "code": null, "e": 17686, "s": 17638, "text": "In MS Project you can identify the Task Links −" }, { "code": null, "e": 17799, "s": 17686, "text": "Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks." }, { "code": null, "e": 17912, "s": 17799, "text": "Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks." }, { "code": null, "e": 18021, "s": 17912, "text": "Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks." }, { "code": null, "e": 18130, "s": 18021, "text": "Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks." }, { "code": null, "e": 18261, "s": 18130, "text": "Select the two tasks you want to link. In the following screenshot taken as an example, we have selected names, Task 1 and Task 2." }, { "code": null, "e": 18321, "s": 18261, "text": "Click Task tab → Schedule group → Link the Selected Tasks.\n" }, { "code": null, "e": 18387, "s": 18321, "text": "Task 1 and Task 2 are linked with a Finish-to-Start relationship." }, { "code": null, "e": 18476, "s": 18387, "text": "Note − Task 2 will have a Start date of the Next working day from Finish date of Task 1." }, { "code": null, "e": 18531, "s": 18476, "text": "Double click a successor task you would like to link.\n" }, { "code": null, "e": 18558, "s": 18531, "text": "Here I have clicked Task 4" }, { "code": null, "e": 18596, "s": 18558, "text": "The Task information dialog box opens" }, { "code": null, "e": 18680, "s": 18596, "text": "Click Predecessors tab\n\nIn the Table, click the empty cell below Task Name column.\n" }, { "code": null, "e": 18743, "s": 18680, "text": "A drop down box appears with all Tasks defined in the project." }, { "code": null, "e": 18783, "s": 18743, "text": "Choose the predecessor task. Click OK.\n" }, { "code": null, "e": 18810, "s": 18783, "text": "Here I have chosen Task 3." }, { "code": null, "e": 18912, "s": 18810, "text": "In this method, you will select a group of task, and link them all with Finish-to-Start relationship." }, { "code": null, "e": 19017, "s": 18912, "text": "Select multiple tasks with the help of the mouse → Task tab → Schedule group → Link the Selected Tasks.\n" }, { "code": null, "e": 19121, "s": 19017, "text": "All tasks get linked. To select non-adjacent tasks, hold down Ctrl key and select each task separately." }, { "code": null, "e": 19334, "s": 19121, "text": "If you are in Manually Scheduled mode, any change in duration of the predecessor task will not reflect on Start date of Task 4. For example, Task 4 starts on 9/3/15 which is the next day of Finish date of Task 3." }, { "code": null, "e": 19471, "s": 19334, "text": "Now when we change the Duration of Task 3 from 5 to 7 days, the start date is not automatically updated for Task 4 in Manual Scheduling." }, { "code": null, "e": 19554, "s": 19471, "text": "You can force MS Project to respect the link (dependency) by doing the following −" }, { "code": null, "e": 19569, "s": 19554, "text": "Select Task 4." }, { "code": null, "e": 19618, "s": 19569, "text": "Click Task tab → Schedule group → Respect Links." }, { "code": null, "e": 19719, "s": 19618, "text": "MS Project by default sets new tasks to be manually scheduled. Scheduling is controlled in two ways." }, { "code": null, "e": 19949, "s": 19719, "text": "Manual Scheduling − This is done to quickly capture some details without actually scheduling the tasks. You can leave out details for some of the tasks with respect to duration, start and finish dates, if you don’t know them yet." }, { "code": null, "e": 20170, "s": 19949, "text": "Automatic Scheduling − This uses the Scheduling engine in MS Project. It calculates values such as task durations, start dates, and finish dates automatically. It takes into accounts all constraints, links and calendars." }, { "code": null, "e": 20521, "s": 20170, "text": "For example, at Lucerne Publishing, the new book launch plan has been reviewed by the resources who will carry out the work and by other project stakeholders. Although you expect the plan to change somewhat as you learn more about the book launch, you now have enough confidence in the overall plan to switch from manual to automatic task scheduling." }, { "code": null, "e": 20594, "s": 20521, "text": "We have three different methods to convert a task to automatic schedule." }, { "code": null, "e": 20808, "s": 20594, "text": "If you want to change the mode for a particular task, say Task 5 in the following example. Click on Task Mode cell in the same row. Then, click the down arrow to open a dropdown box, you can select Auto Scheduled." }, { "code": null, "e": 20850, "s": 20808, "text": "Click Task → Tasks group → Auto Schedule." }, { "code": null, "e": 20895, "s": 20850, "text": "To switch completely to Auto Schedule mode −" }, { "code": null, "e": 21033, "s": 20895, "text": "Toggle the scheduling mode of the plan by clicking the New Tasks status bar (at the bottom-left) and then selecting Auto scheduling mode." }, { "code": null, "e": 21120, "s": 21033, "text": "You can also change the default scheduling mode that Project applies to all new plans." } ]
Python – Key Value list pairings in Dictionary
22 Apr, 2020 Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionThis task can be performed using this method. In this we manually extract each key and then iterate with all the values of them to form new dictionary list. This has drawbacks of only available for certain keys. # Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using list comprehension # initializing dictionarytest_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Key Value list pairings in Dictionary# Using list comprehensionres = [{'gfg': i, 'best': j} for i in test_dict['gfg'] for j in test_dict['best']] # printing result print("All key value paired List : " + str(res)) The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}] Method #2 : Using dict() + zip() + product()The combination of above methods can also be used to perform this task. In this, the formation of combinations is done using product(), and linking of values is done using zip(). # Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using dict() + zip() + product()from itertools import product # initializing dictionarytest_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Key Value list pairings in Dictionary# Using dict() + zip() + product()res = [dict(zip(test_dict, sub)) for sub in product(*test_dict.values())] # printing result print("All key value paired List : " + str(res)) The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 587, "s": 339, "text": "Method #1 : Using list comprehensionThis task can be performed using this method. In this we manually extract each key and then iterate with all the values of them to form new dictionary list. This has drawbacks of only available for certain keys." }, { "code": "# Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using list comprehension # initializing dictionarytest_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Key Value list pairings in Dictionary# Using list comprehensionres = [{'gfg': i, 'best': j} for i in test_dict['gfg'] for j in test_dict['best']] # printing result print(\"All key value paired List : \" + str(res)) ", "e": 1114, "s": 587, "text": null }, { "code": null, "e": 1350, "s": 1114, "text": "The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]" }, { "code": null, "e": 1575, "s": 1352, "text": "Method #2 : Using dict() + zip() + product()The combination of above methods can also be used to perform this task. In this, the formation of combinations is done using product(), and linking of values is done using zip()." }, { "code": "# Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using dict() + zip() + product()from itertools import product # initializing dictionarytest_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Key Value list pairings in Dictionary# Using dict() + zip() + product()res = [dict(zip(test_dict, sub)) for sub in product(*test_dict.values())] # printing result print(\"All key value paired List : \" + str(res)) ", "e": 2112, "s": 1575, "text": null }, { "code": null, "e": 2348, "s": 2112, "text": "The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]" }, { "code": null, "e": 2375, "s": 2348, "text": "Python dictionary-programs" }, { "code": null, "e": 2382, "s": 2375, "text": "Python" }, { "code": null, "e": 2398, "s": 2382, "text": "Python Programs" } ]
dir() function in Python
21 Jun, 2021 dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, strings, lists, dictionaries etc.)Syntax : dir({object}) Parameters : object [optional] : Takes object name Returns :dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. For Class Objects, it returns a list of names of all the valid attributes and base attributes as well. For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module. If no parameters are passed it returns a list of names in the current local scope. Code #1 : With and Without importing external libraries. Python3 # Python3 code to demonstrate dir()# when no parameters are passed # Note that we have not imported any modulesprint(dir()) # Now let's import two modulesimport randomimport math # return the module names added to# the local namespace including all# the existing ones as beforeprint(dir()) Output : ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'random'] Code #2 : Python3 # Python3 code to demonstrate dir() function# when a module Object is passed as parameter. # import the random moduleimport random # Prints list which contains names of# attributes in random functionprint("The contents of the random library are::") # module Object is passed as parameterprint(dir(random)) Output : The contents of the random library are :: ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate'] Code #3 : Object is passed as parameters. Python3 # When a list object is passed as# parameters for the dir() function # A list, which contains# a few random valuesgeeks = ["geeksforgeeks", "gfg", "Computer Science", "Data Structures", "Algorithms" ] # dir() will also list out common# attributes of the dictionaryd = {} # empty dictionary # dir() will return all the available# list methods in current local scopeprint(dir(geeks)) # Call dir() with the dictionary# name "d" as parameter. Return all# the available dict methods in the# current local scopeprint(dir(d)) Output : ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] Code #4 : User Defined – Class Object with an available __dir()__ method is passed as parameter. Python3 # Python3 program to demonstrate working# of dir(), when user defined objects are# passed are parameters. # Creation of a simple class with __dir()__# method to demonstrate it's workingclass Supermarket: # Function __dir()___ which list all # the base attributes to be used. def __dir__(self): return['customer_name', 'product', 'quantity', 'price', 'date'] # user-defined object of class supermarketmy_cart = Supermarket() # listing out the dir() methodprint(dir(my_cart)) Output : ['customer_name', 'date', 'price', 'product', 'quantity'] Applications : The dir() has it’s own set of uses. It is usually used for debugging purposes in simple day to day programs, and even in large projects taken up by a team of developers. The capability of dir() to list out all the attributes of the parameter passed, is really useful when handling a lot of classes and functions, separately. The dir() function can also list out all the available attributes for a module/list/dictionary. So, it also gives us information on the operations we can perform with the available list or module, which can be very useful when having little to no information about the module. It also helps to know new modules faster. shubham_singh gabaa406 Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2021" }, { "code": null, "e": 235, "s": 52, "text": "dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, strings, lists, dictionaries etc.)Syntax : " }, { "code": null, "e": 249, "s": 235, "text": "dir({object})" }, { "code": null, "e": 264, "s": 249, "text": "Parameters : " }, { "code": null, "e": 302, "s": 264, "text": "object [optional] : Takes object name" }, { "code": null, "e": 560, "s": 304, "text": "Returns :dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. " }, { "code": null, "e": 665, "s": 560, "text": "For Class Objects, it returns a list of names of all the valid attributes and base attributes as well. " }, { "code": null, "e": 780, "s": 665, "text": "For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module. " }, { "code": null, "e": 863, "s": 780, "text": "If no parameters are passed it returns a list of names in the current local scope." }, { "code": null, "e": 923, "s": 863, "text": " Code #1 : With and Without importing external libraries. " }, { "code": null, "e": 931, "s": 923, "text": "Python3" }, { "code": "# Python3 code to demonstrate dir()# when no parameters are passed # Note that we have not imported any modulesprint(dir()) # Now let's import two modulesimport randomimport math # return the module names added to# the local namespace including all# the existing ones as beforeprint(dir())", "e": 1222, "s": 931, "text": null }, { "code": null, "e": 1233, "s": 1222, "text": "Output : " }, { "code": null, "e": 1535, "s": 1233, "text": "['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',\n '__name__', '__package__', '__spec__']\n\n\n\n['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',\n '__name__', '__package__', '__spec__', 'math', 'random']" }, { "code": null, "e": 1549, "s": 1535, "text": " Code #2 : " }, { "code": null, "e": 1557, "s": 1549, "text": "Python3" }, { "code": "# Python3 code to demonstrate dir() function# when a module Object is passed as parameter. # import the random moduleimport random # Prints list which contains names of# attributes in random functionprint(\"The contents of the random library are::\") # module Object is passed as parameterprint(dir(random))", "e": 1864, "s": 1557, "text": null }, { "code": null, "e": 1875, "s": 1864, "text": "Output : " }, { "code": null, "e": 2624, "s": 1875, "text": "The contents of the random library are ::\n\n['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',\n'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',\n'_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',\n'__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp',\n'_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',\n'_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',\n'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint',\n'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform',\n'vonmisesvariate', 'weibullvariate']" }, { "code": null, "e": 2669, "s": 2624, "text": " Code #3 : Object is passed as parameters. " }, { "code": null, "e": 2677, "s": 2669, "text": "Python3" }, { "code": "# When a list object is passed as# parameters for the dir() function # A list, which contains# a few random valuesgeeks = [\"geeksforgeeks\", \"gfg\", \"Computer Science\", \"Data Structures\", \"Algorithms\" ] # dir() will also list out common# attributes of the dictionaryd = {} # empty dictionary # dir() will return all the available# list methods in current local scopeprint(dir(geeks)) # Call dir() with the dictionary# name \"d\" as parameter. Return all# the available dict methods in the# current local scopeprint(dir(d))", "e": 3219, "s": 2677, "text": null }, { "code": null, "e": 3230, "s": 3219, "text": "Output : " }, { "code": null, "e": 4256, "s": 3230, "text": "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',\n'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', \n'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', \n'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', \n'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', \n'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', \n'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n\n\n['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', \n'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', \n'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', \n'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', \n'__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', \n'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']" }, { "code": null, "e": 4357, "s": 4256, "text": " Code #4 : User Defined – Class Object with an available __dir()__ method is passed as parameter. " }, { "code": null, "e": 4365, "s": 4357, "text": "Python3" }, { "code": "# Python3 program to demonstrate working# of dir(), when user defined objects are# passed are parameters. # Creation of a simple class with __dir()__# method to demonstrate it's workingclass Supermarket: # Function __dir()___ which list all # the base attributes to be used. def __dir__(self): return['customer_name', 'product', 'quantity', 'price', 'date'] # user-defined object of class supermarketmy_cart = Supermarket() # listing out the dir() methodprint(dir(my_cart))", "e": 4872, "s": 4365, "text": null }, { "code": null, "e": 4883, "s": 4872, "text": "Output : " }, { "code": null, "e": 4941, "s": 4883, "text": "['customer_name', 'date', 'price', 'product', 'quantity']" }, { "code": null, "e": 4960, "s": 4941, "text": " Applications : " }, { "code": null, "e": 5287, "s": 4960, "text": "The dir() has it’s own set of uses. It is usually used for debugging purposes in simple day to day programs, and even in large projects taken up by a team of developers. The capability of dir() to list out all the attributes of the parameter passed, is really useful when handling a lot of classes and functions, separately. " }, { "code": null, "e": 5608, "s": 5287, "text": "The dir() function can also list out all the available attributes for a module/list/dictionary. So, it also gives us information on the operations we can perform with the available list or module, which can be very useful when having little to no information about the module. It also helps to know new modules faster. " }, { "code": null, "e": 5624, "s": 5610, "text": "shubham_singh" }, { "code": null, "e": 5633, "s": 5624, "text": "gabaa406" }, { "code": null, "e": 5659, "s": 5633, "text": "Python-Built-in-functions" }, { "code": null, "e": 5666, "s": 5659, "text": "Python" } ]
Program for Rank of Matrix
30 Jun, 2022 What is rank of a matrix? Rank of a matrix A of size M x N is defined as Maximum number of linearly independent column vectors in the matrix or Maximum number of linearly independent row vectors in the matrix. Maximum number of linearly independent column vectors in the matrix or Maximum number of linearly independent row vectors in the matrix. Example: Input: mat[][] = {{10, 20, 10}, {20, 40, 20}, {30, 50, 0}} Output: Rank is 2 Explanation: Ist and IInd rows are linearly dependent. But Ist and 3rd or IInd and IIIrd are independent. Input: mat[][] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}} Output: Rank is 2 Explanation: Ist and IInd rows are linearly independent. So rank must be atleast 2. But all three rows are linearly dependent (the first is equal to the sum of the second and third) so the rank must be less than 3. In other words rank of A is the largest order of any non-zero minor in A where order of a minor is the side-length of the square sub-matrix of which it is determinant.So if M < N then maximum rank of A can be M else it can be N, in general rank of matrix can’t be greater than min(M, N).The rank of a matrix would be zero only if the matrix had no non-zero elements. If a matrix had even one non-zero element, its minimum rank would be one. How to find Rank? The idea is based on conversion to Row echelon form. 1) Let the input matrix be mat[][]. Initialize rank equals to number of columns // Before we visit row 'row', traversal of previous // rows make sure that mat[row][0],....mat[row][row-1] // are 0. 2) Do following for row = 0 to rank-1. a) If mat[row][row] is not zero, make all elements of current column as 0 except the element mat[row][row] by finding appropriate multiplier and adding a the multiple of row 'row' b) Else (mat[row][row] is zero). Two cases arise: (i) If there is a row below it with non-zero entry in same column, then swap current 'row' and that row. (ii) If all elements in current column below mat[r][row] are 0, then remove this column by swapping it with last column and reducing number of rank by 1. Reduce row by 1 so that this row is processed again. 3) Number of remaining columns is rank of matrix. Example: Input: mat[][] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}} row = 0: Since mat[0][0] is not 0, we are in case 2.a of above algorithm. We set all entries of 0'th column as 0 (except entry mat[0][0]). To do this, we subtract R1*(-2) from R2, i.e., R2 --> R2 - R1*(-2) mat[][] = {{10, 20, 10}, { 0, 10, 30}, {30, 50, 0}} And subtract R1*3 from R3, i.e., R3 --> R3 - R1*3 mat[][] = {{10, 20, 10}, { 0, 10, 30}, { 0, -10, -30}} row = 1: Since mat[1][1] is not 0, we are in case 2.a of above algorithm. We set all entries of 1st column as 0 (except entry mat[1][1]). To do this, we subtract R2*2 from R1, i.e., R1 --> R1 - R2*2 mat[][] = {{10, 0, -50}, { 0, 10, 30}, { 0, -10, -30}} And subtract R2*(-1) from R3, i.e., R3 --> R3 - R2*(-1) mat[][] = {{10, 0, -50}, { 0, 10, 30}, { 0, 0, 0}} row = 2: Since Since mat[2][2] is 0, we are in case 2.b of above algorithm. Since there is no row below it swap. We reduce the rank by 1 and keep row as 2. The loop doesn't iterate next time because loop termination condition row <= rank-1 returns false. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find rank of a matrix#include <bits/stdc++.h>using namespace std;#define R 3#define C 3 /* function for exchanging two rows of a matrix */void swap(int mat[R][C], int row1, int row2, int col){ for (int i = 0; i < col; i++) { int temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; }} // Function to display a matrixvoid display(int mat[R][C], int row, int col); /* function for finding rank of matrix */int rankOfMatrix(int mat[R][C]){ int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row 'row', we make // sure that mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row]) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries of current // column as 0 except entry 'mat[row][row]' double mult = (double)mat[col][row] / mat[row][row]; for (int i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. Two cases // arise: // 1) If there is a row below it with non-zero // entry, then swap this row with that row // and process that row // 2) If all elements in current column below // mat[r][row] are 0, then remove this column // by swapping it with last column and // reducing number of columns by 1. else { bool reduce = true; /* Find the non-zero element in current column */ for (int i = row + 1; i < R; i++) { // Swap the row with non-zero element // with this row. if (mat[i][row]) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with non-zero // element in current column, then all // values in this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see intermediate results // display(mat, R, C); // printf("\n"); } return rank;} /* function for displaying the matrix */void display(int mat[R][C], int row, int col){ for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) printf(" %d", mat[i][j]); printf("\n"); }} // Driver program to test above functionsint main(){ int mat[][3] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; printf("Rank of the matrix is : %d", rankOfMatrix(mat)); return 0;} // Java program to find rank of a matrixclass GFG { static final int R = 3; static final int C = 3; // function for exchanging two rows // of a matrix static void swap(int mat[][], int row1, int row2, int col) { for (int i = 0; i < col; i++) { int temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; } } // Function to display a matrix static void display(int mat[][], int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) System.out.print(" " + mat[i][j]); System.out.print("\n"); } } // function for finding rank of matrix static int rankOfMatrix(int mat[][]) { int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row] != 0) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' double mult = (double)mat[col][row] / mat[row][row]; for (int i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { boolean reduce = true; // Find the non-zero element // in current column for (int i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i][row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf("\n"); } return rank; } // Driver code public static void main (String[] args) { int mat[][] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; System.out.print("Rank of the matrix is : " + rankOfMatrix(mat)); }} // This code is contributed by Anant Agarwal. # Python 3 program to find rank of a matrixclass rankMatrix(object): def __init__(self, Matrix): self.R = len(Matrix) self.C = len(Matrix[0]) # Function for exchanging two rows of a matrix def swap(self, Matrix, row1, row2, col): for i in range(col): temp = Matrix[row1][i] Matrix[row1][i] = Matrix[row2][i] Matrix[row2][i] = temp # Function to Display a matrix def Display(self, Matrix, row, col): for i in range(row): for j in range(col): print (" " + str(Matrix[i][j])) print ('\n') # Find rank of a matrix def rankOfMatrix(self, Matrix): rank = self.C for row in range(0, rank, 1): # Before we visit current row # 'row', we make sure that # mat[row][0],....mat[row][row-1] # are 0. # Diagonal element is not zero if Matrix[row][row] != 0: for col in range(0, self.R, 1): if col != row: # This makes all entries of current # column as 0 except entry 'mat[row][row]' multiplier = (Matrix[col][row] / Matrix[row][row]) for i in range(rank): Matrix[col][i] -= (multiplier * Matrix[row][i]) # Diagonal element is already zero. # Two cases arise: # 1) If there is a row below it # with non-zero entry, then swap # this row with that row and process # that row # 2) If all elements in current # column below mat[r][row] are 0, # then remove this column by # swapping it with last column and # reducing number of columns by 1. else: reduce = True # Find the non-zero element # in current column for i in range(row + 1, self.R, 1): # Swap the row with non-zero # element with this row. if Matrix[i][row] != 0: self.swap(Matrix, row, i, rank) reduce = False break # If we did not find any row with # non-zero element in current # column, then all values in # this column are 0. if reduce: # Reduce number of columns rank -= 1 # copy the last column here for i in range(0, self.R, 1): Matrix[i][row] = Matrix[i][rank] # process this row again row -= 1 # self.Display(Matrix, self.R,self.C) return (rank) # Driver Codeif __name__ == '__main__': Matrix = [[10, 20, 10], [-20, -30, 10], [30, 50, 0]] RankMatrix = rankMatrix(Matrix) print ("Rank of the Matrix is:", (RankMatrix.rankOfMatrix(Matrix))) # This code is contributed by Vikas Chitturi // C# program to find rank of a matrixusing System;class GFG { static int R = 3; static int C = 3; // function for exchanging two rows // of a matrix static void swap(int [,]mat, int row1, int row2, int col) { for (int i = 0; i < col; i++) { int temp = mat[row1,i]; mat[row1,i] = mat[row2,i]; mat[row2,i] = temp; } } // Function to display a matrix static void display(int [,]mat, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) Console.Write(" " + mat[i,j]); Console.Write("\n"); } } // function for finding rank of matrix static int rankOfMatrix(int [,]mat) { int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row,row] != 0) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' double mult = (double)mat[col,row] / mat[row,row]; for (int i = 0; i < rank; i++) mat[col,i] -= (int) mult * mat[row,i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { bool reduce = true; // Find the non-zero element // in current column for (int i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i,row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i,row] = mat[i,rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf("\n"); } return rank; } // Driver code public static void Main () { int [,]mat = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; Console.Write("Rank of the matrix is : " + rankOfMatrix(mat)); }} // This code is contributed by nitin mittal <?php// PHP program to find rank of a matrix $R = 3;$C = 3; /* function for exchanging two rows ofa matrix */function swap(&$mat, $row1, $row2, $col){ for ($i = 0; $i < $col; $i++) { $temp = $mat[$row1][$i]; $mat[$row1][$i] = $mat[$row2][$i]; $mat[$row2][$i] = $temp; }} /* function for finding rank of matrix */function rankOfMatrix($mat){ global $R, $C; $rank = $C; for ($row = 0; $row < $rank; $row++) { // Before we visit current row 'row', we make // sure that mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if ($mat[$row][$row]) { for ($col = 0; $col < $R; $col++) { if ($col != $row) { // This makes all entries of current // column as 0 except entry 'mat[row][row]' $mult = $mat[$col][$row] / $mat[$row][$row]; for ($i = 0; $i < $rank; $i++) $mat[$col][$i] -= $mult * $mat[$row][$i]; } } } // Diagonal element is already zero. Two cases // arise: // 1) If there is a row below it with non-zero // entry, then swap this row with that row // and process that row // 2) If all elements in current column below // mat[r][row] are 0, then remove this column // by swapping it with last column and // reducing number of columns by 1. else { $reduce = true; /* Find the non-zero element in current column */ for ($i = $row + 1; $i < $R; $i++) { // Swap the row with non-zero element // with this row. if ($mat[$i][$row]) { swap($mat, $row, $i, $rank); $reduce = false; break ; } } // If we did not find any row with non-zero // element in current column, then all // values in this column are 0. if ($reduce) { // Reduce number of columns $rank--; // Copy the last column here for ($i = 0; $i < $R; $i++) $mat[$i][$row] = $mat[$i][$rank]; } // Process this row again $row--; } // Uncomment these lines to see intermediate results // display(mat, R, C); // printf("\n"); } return $rank;} /* function for displaying the matrix */function display($mat, $row, $col){ for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $col; $j++) print(" $mat[$i][$j]"); print("\n"); }} // Driver code$mat = array(array(10, 20, 10), array(-20, -30, 10), array(30, 50, 0));print("Rank of the matrix is : ".rankOfMatrix($mat)); // This code is contributed by mits?> <script> // javascript program to find rank of a matrix var R = 3; var C = 3; // function for exchanging two rows // of a matrix function swap(mat, row1 , row2 , col) { for (i = 0; i < col; i++) { var temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; } } // Function to display a matrix function display(mat,row , col) { for (i = 0; i < row; i++) { for (j = 0; j < col; j++) document.write(" " + mat[i][j]); document.write('<br>'); } } // function for finding rank of matrix function rankOfMatrix(mat) { var rank = C; for (row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row] != 0) { for (col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' var mult = mat[col][row] / mat[row][row]; for (i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { reduce = true; // Find the non-zero element // in current column for (var i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i][row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf(<br>); } return rank; } // Driver code var mat = [[10, 20, 10], [-20, -30, 10], [30, 50, 0]]; document.write("Rank of the matrix is : " + rankOfMatrix(mat)); // This code is contributed by Amit Katiyar</script> Rank of the matrix is : 2 Time complexity: O(row x col x rank).Auxiliary Space: O(1) Since above rank calculation method involves floating point arithmetic, it may produce incorrect results if the division goes beyond precision. There are other methods to handle. nitin mittal Mithun Kumar Vikas Chitturi amit143katiyar varshagumber28 sweetyty codewithshinchan hardikkoriintern Mathematical Matrix Mathematical Matrix 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 Program to find largest element in an array Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 126, "s": 52, "text": "What is rank of a matrix? Rank of a matrix A of size M x N is defined as " }, { "code": null, "e": 264, "s": 126, "text": "Maximum number of linearly independent column vectors in the matrix or Maximum number of linearly independent row vectors in the matrix. " }, { "code": null, "e": 336, "s": 264, "text": "Maximum number of linearly independent column vectors in the matrix or " }, { "code": null, "e": 403, "s": 336, "text": "Maximum number of linearly independent row vectors in the matrix. " }, { "code": null, "e": 412, "s": 403, "text": "Example:" }, { "code": null, "e": 1076, "s": 412, "text": "Input: mat[][] = {{10, 20, 10},\n {20, 40, 20},\n {30, 50, 0}}\nOutput: Rank is 2\nExplanation: Ist and IInd rows are linearly dependent.\n But Ist and 3rd or IInd and IIIrd are\n independent. \n\n\nInput: mat[][] = {{10, 20, 10},\n {-20, -30, 10},\n {30, 50, 0}}\nOutput: Rank is 2\nExplanation: Ist and IInd rows are linearly independent.\n So rank must be atleast 2. But all three rows\n are linearly dependent (the first is equal to\n the sum of the second and third) so the rank \n must be less than 3. " }, { "code": null, "e": 1518, "s": 1076, "text": "In other words rank of A is the largest order of any non-zero minor in A where order of a minor is the side-length of the square sub-matrix of which it is determinant.So if M < N then maximum rank of A can be M else it can be N, in general rank of matrix can’t be greater than min(M, N).The rank of a matrix would be zero only if the matrix had no non-zero elements. If a matrix had even one non-zero element, its minimum rank would be one. " }, { "code": null, "e": 1590, "s": 1518, "text": "How to find Rank? The idea is based on conversion to Row echelon form. " }, { "code": null, "e": 2513, "s": 1590, "text": "1) Let the input matrix be mat[][]. Initialize rank equals\n to number of columns\n\n// Before we visit row 'row', traversal of previous \n// rows make sure that mat[row][0],....mat[row][row-1]\n// are 0.\n2) Do following for row = 0 to rank-1.\n\n a) If mat[row][row] is not zero, make all elements of\n current column as 0 except the element mat[row][row]\n by finding appropriate multiplier and adding a the \n multiple of row 'row'\n \n b) Else (mat[row][row] is zero). Two cases arise:\n (i) If there is a row below it with non-zero entry in \n same column, then swap current 'row' and that row.\n (ii) If all elements in current column below mat[r][row] \n are 0, then remove this column by swapping it with\n last column and reducing number of rank by 1.\n Reduce row by 1 so that this row is processed again.\n\n3) Number of remaining columns is rank of matrix." }, { "code": null, "e": 2523, "s": 2513, "text": "Example: " }, { "code": null, "e": 3889, "s": 2523, "text": "Input: mat[][] = {{10, 20, 10},\n {-20, -30, 10},\n {30, 50, 0}}\n\nrow = 0:\nSince mat[0][0] is not 0, we are in case 2.a of above algorithm.\nWe set all entries of 0'th column as 0 (except entry mat[0][0]).\nTo do this, we subtract R1*(-2) from R2, i.e., R2 --> R2 - R1*(-2)\n mat[][] = {{10, 20, 10},\n { 0, 10, 30},\n {30, 50, 0}}\n And subtract R1*3 from R3, i.e., R3 --> R3 - R1*3 \n mat[][] = {{10, 20, 10},\n { 0, 10, 30},\n { 0, -10, -30}}\n\nrow = 1:\nSince mat[1][1] is not 0, we are in case 2.a of above algorithm.\nWe set all entries of 1st column as 0 (except entry mat[1][1]).\nTo do this, we subtract R2*2 from R1, i.e., R1 --> R1 - R2*2\n mat[][] = {{10, 0, -50},\n { 0, 10, 30},\n { 0, -10, -30}}\n And subtract R2*(-1) from R3, i.e., R3 --> R3 - R2*(-1)\n mat[][] = {{10, 0, -50},\n { 0, 10, 30},\n { 0, 0, 0}}\n\nrow = 2:\nSince Since mat[2][2] is 0, we are in case 2.b of above algorithm.\nSince there is no row below it swap. We reduce the rank by 1 and \nkeep row as 2. \n\nThe loop doesn't iterate next time because loop termination condition\nrow <= rank-1 returns false." }, { "code": null, "e": 3932, "s": 3889, "text": "Below is the implementation of above idea." }, { "code": null, "e": 3936, "s": 3932, "text": "C++" }, { "code": null, "e": 3941, "s": 3936, "text": "Java" }, { "code": null, "e": 3949, "s": 3941, "text": "Python3" }, { "code": null, "e": 3952, "s": 3949, "text": "C#" }, { "code": null, "e": 3956, "s": 3952, "text": "PHP" }, { "code": null, "e": 3967, "s": 3956, "text": "Javascript" }, { "code": "// C++ program to find rank of a matrix#include <bits/stdc++.h>using namespace std;#define R 3#define C 3 /* function for exchanging two rows of a matrix */void swap(int mat[R][C], int row1, int row2, int col){ for (int i = 0; i < col; i++) { int temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; }} // Function to display a matrixvoid display(int mat[R][C], int row, int col); /* function for finding rank of matrix */int rankOfMatrix(int mat[R][C]){ int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row 'row', we make // sure that mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row]) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries of current // column as 0 except entry 'mat[row][row]' double mult = (double)mat[col][row] / mat[row][row]; for (int i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. Two cases // arise: // 1) If there is a row below it with non-zero // entry, then swap this row with that row // and process that row // 2) If all elements in current column below // mat[r][row] are 0, then remove this column // by swapping it with last column and // reducing number of columns by 1. else { bool reduce = true; /* Find the non-zero element in current column */ for (int i = row + 1; i < R; i++) { // Swap the row with non-zero element // with this row. if (mat[i][row]) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with non-zero // element in current column, then all // values in this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see intermediate results // display(mat, R, C); // printf(\"\\n\"); } return rank;} /* function for displaying the matrix */void display(int mat[R][C], int row, int col){ for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) printf(\" %d\", mat[i][j]); printf(\"\\n\"); }} // Driver program to test above functionsint main(){ int mat[][3] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; printf(\"Rank of the matrix is : %d\", rankOfMatrix(mat)); return 0;}", "e": 7145, "s": 3967, "text": null }, { "code": "// Java program to find rank of a matrixclass GFG { static final int R = 3; static final int C = 3; // function for exchanging two rows // of a matrix static void swap(int mat[][], int row1, int row2, int col) { for (int i = 0; i < col; i++) { int temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; } } // Function to display a matrix static void display(int mat[][], int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) System.out.print(\" \" + mat[i][j]); System.out.print(\"\\n\"); } } // function for finding rank of matrix static int rankOfMatrix(int mat[][]) { int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row] != 0) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' double mult = (double)mat[col][row] / mat[row][row]; for (int i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { boolean reduce = true; // Find the non-zero element // in current column for (int i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i][row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf(\"\\n\"); } return rank; } // Driver code public static void main (String[] args) { int mat[][] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; System.out.print(\"Rank of the matrix is : \" + rankOfMatrix(mat)); }} // This code is contributed by Anant Agarwal.", "e": 11160, "s": 7145, "text": null }, { "code": "# Python 3 program to find rank of a matrixclass rankMatrix(object): def __init__(self, Matrix): self.R = len(Matrix) self.C = len(Matrix[0]) # Function for exchanging two rows of a matrix def swap(self, Matrix, row1, row2, col): for i in range(col): temp = Matrix[row1][i] Matrix[row1][i] = Matrix[row2][i] Matrix[row2][i] = temp # Function to Display a matrix def Display(self, Matrix, row, col): for i in range(row): for j in range(col): print (\" \" + str(Matrix[i][j])) print ('\\n') # Find rank of a matrix def rankOfMatrix(self, Matrix): rank = self.C for row in range(0, rank, 1): # Before we visit current row # 'row', we make sure that # mat[row][0],....mat[row][row-1] # are 0. # Diagonal element is not zero if Matrix[row][row] != 0: for col in range(0, self.R, 1): if col != row: # This makes all entries of current # column as 0 except entry 'mat[row][row]' multiplier = (Matrix[col][row] / Matrix[row][row]) for i in range(rank): Matrix[col][i] -= (multiplier * Matrix[row][i]) # Diagonal element is already zero. # Two cases arise: # 1) If there is a row below it # with non-zero entry, then swap # this row with that row and process # that row # 2) If all elements in current # column below mat[r][row] are 0, # then remove this column by # swapping it with last column and # reducing number of columns by 1. else: reduce = True # Find the non-zero element # in current column for i in range(row + 1, self.R, 1): # Swap the row with non-zero # element with this row. if Matrix[i][row] != 0: self.swap(Matrix, row, i, rank) reduce = False break # If we did not find any row with # non-zero element in current # column, then all values in # this column are 0. if reduce: # Reduce number of columns rank -= 1 # copy the last column here for i in range(0, self.R, 1): Matrix[i][row] = Matrix[i][rank] # process this row again row -= 1 # self.Display(Matrix, self.R,self.C) return (rank) # Driver Codeif __name__ == '__main__': Matrix = [[10, 20, 10], [-20, -30, 10], [30, 50, 0]] RankMatrix = rankMatrix(Matrix) print (\"Rank of the Matrix is:\", (RankMatrix.rankOfMatrix(Matrix))) # This code is contributed by Vikas Chitturi", "e": 14585, "s": 11160, "text": null }, { "code": "// C# program to find rank of a matrixusing System;class GFG { static int R = 3; static int C = 3; // function for exchanging two rows // of a matrix static void swap(int [,]mat, int row1, int row2, int col) { for (int i = 0; i < col; i++) { int temp = mat[row1,i]; mat[row1,i] = mat[row2,i]; mat[row2,i] = temp; } } // Function to display a matrix static void display(int [,]mat, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) Console.Write(\" \" + mat[i,j]); Console.Write(\"\\n\"); } } // function for finding rank of matrix static int rankOfMatrix(int [,]mat) { int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row,row] != 0) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' double mult = (double)mat[col,row] / mat[row,row]; for (int i = 0; i < rank; i++) mat[col,i] -= (int) mult * mat[row,i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { bool reduce = true; // Find the non-zero element // in current column for (int i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i,row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i,row] = mat[i,rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf(\"\\n\"); } return rank; } // Driver code public static void Main () { int [,]mat = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; Console.Write(\"Rank of the matrix is : \" + rankOfMatrix(mat)); }} // This code is contributed by nitin mittal", "e": 18579, "s": 14585, "text": null }, { "code": "<?php// PHP program to find rank of a matrix $R = 3;$C = 3; /* function for exchanging two rows ofa matrix */function swap(&$mat, $row1, $row2, $col){ for ($i = 0; $i < $col; $i++) { $temp = $mat[$row1][$i]; $mat[$row1][$i] = $mat[$row2][$i]; $mat[$row2][$i] = $temp; }} /* function for finding rank of matrix */function rankOfMatrix($mat){ global $R, $C; $rank = $C; for ($row = 0; $row < $rank; $row++) { // Before we visit current row 'row', we make // sure that mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if ($mat[$row][$row]) { for ($col = 0; $col < $R; $col++) { if ($col != $row) { // This makes all entries of current // column as 0 except entry 'mat[row][row]' $mult = $mat[$col][$row] / $mat[$row][$row]; for ($i = 0; $i < $rank; $i++) $mat[$col][$i] -= $mult * $mat[$row][$i]; } } } // Diagonal element is already zero. Two cases // arise: // 1) If there is a row below it with non-zero // entry, then swap this row with that row // and process that row // 2) If all elements in current column below // mat[r][row] are 0, then remove this column // by swapping it with last column and // reducing number of columns by 1. else { $reduce = true; /* Find the non-zero element in current column */ for ($i = $row + 1; $i < $R; $i++) { // Swap the row with non-zero element // with this row. if ($mat[$i][$row]) { swap($mat, $row, $i, $rank); $reduce = false; break ; } } // If we did not find any row with non-zero // element in current column, then all // values in this column are 0. if ($reduce) { // Reduce number of columns $rank--; // Copy the last column here for ($i = 0; $i < $R; $i++) $mat[$i][$row] = $mat[$i][$rank]; } // Process this row again $row--; } // Uncomment these lines to see intermediate results // display(mat, R, C); // printf(\"\\n\"); } return $rank;} /* function for displaying the matrix */function display($mat, $row, $col){ for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $col; $j++) print(\" $mat[$i][$j]\"); print(\"\\n\"); }} // Driver code$mat = array(array(10, 20, 10), array(-20, -30, 10), array(30, 50, 0));print(\"Rank of the matrix is : \".rankOfMatrix($mat)); // This code is contributed by mits?>", "e": 21558, "s": 18579, "text": null }, { "code": "<script> // javascript program to find rank of a matrix var R = 3; var C = 3; // function for exchanging two rows // of a matrix function swap(mat, row1 , row2 , col) { for (i = 0; i < col; i++) { var temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; } } // Function to display a matrix function display(mat,row , col) { for (i = 0; i < row; i++) { for (j = 0; j < col; j++) document.write(\" \" + mat[i][j]); document.write('<br>'); } } // function for finding rank of matrix function rankOfMatrix(mat) { var rank = C; for (row = 0; row < rank; row++) { // Before we visit current row // 'row', we make sure that // mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row] != 0) { for (col = 0; col < R; col++) { if (col != row) { // This makes all entries // of current column // as 0 except entry // 'mat[row][row]' var mult = mat[col][row] / mat[row][row]; for (i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. // Two cases arise: // 1) If there is a row below it // with non-zero entry, then swap // this row with that row and process // that row // 2) If all elements in current // column below mat[r][row] are 0, // then remove this column by // swapping it with last column and // reducing number of columns by 1. else { reduce = true; // Find the non-zero element // in current column for (var i = row + 1; i < R; i++) { // Swap the row with non-zero // element with this row. if (mat[i][row] != 0) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with // non-zero element in current // column, then all values in // this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see // intermediate results display(mat, R, C); // printf(<br>); } return rank; } // Driver code var mat = [[10, 20, 10], [-20, -30, 10], [30, 50, 0]]; document.write(\"Rank of the matrix is : \" + rankOfMatrix(mat)); // This code is contributed by Amit Katiyar</script>", "e": 25327, "s": 21558, "text": null }, { "code": null, "e": 25353, "s": 25327, "text": "Rank of the matrix is : 2" }, { "code": null, "e": 25412, "s": 25353, "text": "Time complexity: O(row x col x rank).Auxiliary Space: O(1)" }, { "code": null, "e": 25591, "s": 25412, "text": "Since above rank calculation method involves floating point arithmetic, it may produce incorrect results if the division goes beyond precision. There are other methods to handle." }, { "code": null, "e": 25604, "s": 25591, "text": "nitin mittal" }, { "code": null, "e": 25617, "s": 25604, "text": "Mithun Kumar" }, { "code": null, "e": 25632, "s": 25617, "text": "Vikas Chitturi" }, { "code": null, "e": 25647, "s": 25632, "text": "amit143katiyar" }, { "code": null, "e": 25662, "s": 25647, "text": "varshagumber28" }, { "code": null, "e": 25671, "s": 25662, "text": "sweetyty" }, { "code": null, "e": 25688, "s": 25671, "text": "codewithshinchan" }, { "code": null, "e": 25705, "s": 25688, "text": "hardikkoriintern" }, { "code": null, "e": 25718, "s": 25705, "text": "Mathematical" }, { "code": null, "e": 25725, "s": 25718, "text": "Matrix" }, { "code": null, "e": 25738, "s": 25725, "text": "Mathematical" }, { "code": null, "e": 25745, "s": 25738, "text": "Matrix" }, { "code": null, "e": 25843, "s": 25745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25873, "s": 25843, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 25916, "s": 25873, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 25976, "s": 25916, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 25991, "s": 25976, "text": "C++ Data Types" }, { "code": null, "e": 26015, "s": 25991, "text": "Merge two sorted arrays" }, { "code": null, "e": 26059, "s": 26015, "text": "Program to find largest element in an array" }, { "code": null, "e": 26094, "s": 26059, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 26125, "s": 26094, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 26149, "s": 26125, "text": "Sudoku | Backtracking-7" } ]
Face Detection using Python and OpenCV with webcam
22 Sep, 2021 OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Python 2.7 OpenCV Numpy Haar Cascade Frontal face classifiers Approach/Algorithms used: This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number.LBPH uses 4 parameters : (i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the central pixel. (ii) Neighbors : the number of sample points to build the circular local binary pattern. (iii) Grid X : the number of cells in the horizontal direction. (iv) Grid Y : the number of cells in the vertical direction.The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it. This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number. LBPH uses 4 parameters : (i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the central pixel. (ii) Neighbors : the number of sample points to build the circular local binary pattern. (iii) Grid X : the number of cells in the horizontal direction. (iv) Grid Y : the number of cells in the vertical direction. The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it. How to use : Create a directory in your pc and name it (say project)Create two python files named create_data.py and face_recognize.py, copy the first source code and second source code in it respectively.Copy haarcascade_frontalface_default.xml to the project directory, you can get it in opencv or from here.You are ready to now run the following codes. Create a directory in your pc and name it (say project) Create two python files named create_data.py and face_recognize.py, copy the first source code and second source code in it respectively. Copy haarcascade_frontalface_default.xml to the project directory, you can get it in opencv or from here. You are ready to now run the following codes. Python # Creating database# It captures images and stores them in datasets# folder under the folder name of sub_dataimport cv2, sys, numpy, oshaar_file = 'haarcascade_frontalface_default.xml' # All the faces data will be# present this folderdatasets = 'datasets' # These are sub data sets of folder,# for my faces I've used my name you can# change the label heresub_data = 'vivek' path = os.path.join(datasets, sub_data)if not os.path.isdir(path): os.mkdir(path) # defining the size of images(width, height) = (130, 100) #'0' is used for my webcam,# if you've any other camera# attached use '1' like thisface_cascade = cv2.CascadeClassifier(haar_file)webcam = cv2.VideoCapture(0) # The program loops until it has 30 images of the face.count = 1while count < 30: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 4) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) cv2.imwrite('% s/% s.png' % (path, count), face_resize) count += 1 cv2.imshow('OpenCV', im) key = cv2.waitKey(10) if key == 27: break Following code should be run after the model has been trained for the faces : Python # It helps in identifying the facesimport cv2, sys, numpy, ossize = 4haar_file = 'haarcascade_frontalface_default.xml'datasets = 'datasets' # Part 1: Create fisherRecognizerprint('Recognizing Face Please Be in sufficient Lights...') # Create a list of images and a list of corresponding names(images, labels, names, id) = ([], [], {}, 0)for (subdirs, dirs, files) in os.walk(datasets): for subdir in dirs: names[id] = subdir subjectpath = os.path.join(datasets, subdir) for filename in os.listdir(subjectpath): path = subjectpath + '/' + filename label = id images.append(cv2.imread(path, 0)) labels.append(int(label)) id += 1(width, height) = (130, 100) # Create a Numpy array from the two lists above(images, labels) = [numpy.array(lis) for lis in [images, labels]] # OpenCV trains a model from the images# NOTE FOR OpenCV2: remove '.face'model = cv2.face.LBPHFaceRecognizer_create()model.train(images, labels) # Part 2: Use fisherRecognizer on camera streamface_cascade = cv2.CascadeClassifier(haar_file)webcam = cv2.VideoCapture(0)while True: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) # Try to recognize the face prediction = model.predict(face_resize) cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3) if prediction[1]<500: cv2.putText(im, '% s - %.0f' %(names[prediction[0]], prediction[1]), (x-10, y-10),cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0)) else: cv2.putText(im, 'not recognized',(x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0)) cv2.imshow('OpenCV', im) key = cv2.waitKey(10) if key == 27: break Note : Above programs will not run on online IDE. Screenshots of the Program It may look something different because I had integrated the above program on flask frameworkRunning of second program yields results similar to the below image : face detection Datasets Storage : data_sets sagartomar9927 Image-Processing OpenCV Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Sep, 2021" }, { "code": null, "e": 309, "s": 52, "text": "OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- " }, { "code": null, "e": 368, "s": 309, "text": "Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers" }, { "code": null, "e": 379, "s": 368, "text": "Python 2.7" }, { "code": null, "e": 386, "s": 379, "text": "OpenCV" }, { "code": null, "e": 392, "s": 386, "text": "Numpy" }, { "code": null, "e": 430, "s": 392, "text": "Haar Cascade Frontal face classifiers" }, { "code": null, "e": 458, "s": 430, "text": "Approach/Algorithms used: " }, { "code": null, "e": 1190, "s": 458, "text": "This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number.LBPH uses 4 parameters : (i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the central pixel. (ii) Neighbors : the number of sample points to build the circular local binary pattern. (iii) Grid X : the number of cells in the horizontal direction. (iv) Grid Y : the number of cells in the vertical direction.The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it." }, { "code": null, "e": 1400, "s": 1190, "text": "This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number." }, { "code": null, "e": 1765, "s": 1400, "text": "LBPH uses 4 parameters : (i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the central pixel. (ii) Neighbors : the number of sample points to build the circular local binary pattern. (iii) Grid X : the number of cells in the horizontal direction. (iv) Grid Y : the number of cells in the vertical direction." }, { "code": null, "e": 1924, "s": 1765, "text": "The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it." }, { "code": null, "e": 1939, "s": 1924, "text": "How to use : " }, { "code": null, "e": 2282, "s": 1939, "text": "Create a directory in your pc and name it (say project)Create two python files named create_data.py and face_recognize.py, copy the first source code and second source code in it respectively.Copy haarcascade_frontalface_default.xml to the project directory, you can get it in opencv or from here.You are ready to now run the following codes." }, { "code": null, "e": 2338, "s": 2282, "text": "Create a directory in your pc and name it (say project)" }, { "code": null, "e": 2476, "s": 2338, "text": "Create two python files named create_data.py and face_recognize.py, copy the first source code and second source code in it respectively." }, { "code": null, "e": 2582, "s": 2476, "text": "Copy haarcascade_frontalface_default.xml to the project directory, you can get it in opencv or from here." }, { "code": null, "e": 2628, "s": 2582, "text": "You are ready to now run the following codes." }, { "code": null, "e": 2637, "s": 2630, "text": "Python" }, { "code": "# Creating database# It captures images and stores them in datasets# folder under the folder name of sub_dataimport cv2, sys, numpy, oshaar_file = 'haarcascade_frontalface_default.xml' # All the faces data will be# present this folderdatasets = 'datasets' # These are sub data sets of folder,# for my faces I've used my name you can# change the label heresub_data = 'vivek' path = os.path.join(datasets, sub_data)if not os.path.isdir(path): os.mkdir(path) # defining the size of images(width, height) = (130, 100) #'0' is used for my webcam,# if you've any other camera# attached use '1' like thisface_cascade = cv2.CascadeClassifier(haar_file)webcam = cv2.VideoCapture(0) # The program loops until it has 30 images of the face.count = 1while count < 30: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 4) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) cv2.imwrite('% s/% s.png' % (path, count), face_resize) count += 1 cv2.imshow('OpenCV', im) key = cv2.waitKey(10) if key == 27: break", "e": 3887, "s": 2637, "text": null }, { "code": null, "e": 3966, "s": 3887, "text": "Following code should be run after the model has been trained for the faces : " }, { "code": null, "e": 3973, "s": 3966, "text": "Python" }, { "code": "# It helps in identifying the facesimport cv2, sys, numpy, ossize = 4haar_file = 'haarcascade_frontalface_default.xml'datasets = 'datasets' # Part 1: Create fisherRecognizerprint('Recognizing Face Please Be in sufficient Lights...') # Create a list of images and a list of corresponding names(images, labels, names, id) = ([], [], {}, 0)for (subdirs, dirs, files) in os.walk(datasets): for subdir in dirs: names[id] = subdir subjectpath = os.path.join(datasets, subdir) for filename in os.listdir(subjectpath): path = subjectpath + '/' + filename label = id images.append(cv2.imread(path, 0)) labels.append(int(label)) id += 1(width, height) = (130, 100) # Create a Numpy array from the two lists above(images, labels) = [numpy.array(lis) for lis in [images, labels]] # OpenCV trains a model from the images# NOTE FOR OpenCV2: remove '.face'model = cv2.face.LBPHFaceRecognizer_create()model.train(images, labels) # Part 2: Use fisherRecognizer on camera streamface_cascade = cv2.CascadeClassifier(haar_file)webcam = cv2.VideoCapture(0)while True: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) # Try to recognize the face prediction = model.predict(face_resize) cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3) if prediction[1]<500: cv2.putText(im, '% s - %.0f' %(names[prediction[0]], prediction[1]), (x-10, y-10),cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0)) else: cv2.putText(im, 'not recognized',(x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0)) cv2.imshow('OpenCV', im) key = cv2.waitKey(10) if key == 27: break", "e": 5919, "s": 3973, "text": null }, { "code": null, "e": 5971, "s": 5919, "text": "Note : Above programs will not run on online IDE. " }, { "code": null, "e": 5998, "s": 5971, "text": "Screenshots of the Program" }, { "code": null, "e": 6163, "s": 5998, "text": "It may look something different because I had integrated the above program on flask frameworkRunning of second program yields results similar to the below image : " }, { "code": null, "e": 6178, "s": 6163, "text": "face detection" }, { "code": null, "e": 6199, "s": 6178, "text": "Datasets Storage : " }, { "code": null, "e": 6209, "s": 6199, "text": "data_sets" }, { "code": null, "e": 6226, "s": 6211, "text": "sagartomar9927" }, { "code": null, "e": 6243, "s": 6226, "text": "Image-Processing" }, { "code": null, "e": 6250, "s": 6243, "text": "OpenCV" }, { "code": null, "e": 6258, "s": 6250, "text": "Project" }, { "code": null, "e": 6265, "s": 6258, "text": "Python" } ]
Maximum index a pointer can reach in N steps by avoiding a given index B
09 Apr, 2021 Given two integers N and B, the task is to print the maximum index a pointer, starting from 0th index can reach in an array of natural numbers(i.e., 0, 1, 2, 3, 4, 5...), say arr[], in N steps without placing itself at index B at any point. In each step, the pointer can move from the Current Index to a Jumping Index or can remain at the Current Index. Jumping Index = Current Index + Step Number Examples: Input: N = 3, B = 2Output: 6Explanation: Step 1:Current Index = 0Step Number = 1Jumping Index = 0 + 1 = 1Step 2:Current Index = 1Step Number = 2Jumping Index = 1 + 2 = 3Step 3:Current Index = 3Step Number = 3Jumping Index = 3 + 3 = 6Therefore, the maximum index that can be reached is 6. Input: N = 3, B = 1Output: 5Explanation: Step 1:Current Index = 0Step Number = 1Jumping Index = 0 + 1 = 1But this is bad index. So pointer remains at the Current Index.Step 2:Current Index = 0Step Number = 2Jumping Index = 0 + 2 = 2Step 3:Current Index = 2Step Number = 3Jumping Index = 2 + 3 = 5Therefore, the maximum index that can be reached is 5. Naive Approach: The simplest approach to solve the problem is to calculate the maximum index by considering two possibilities for every Current Index, either to move the pointer by Step Number or by remaining at the Current Index, and generate all possible combinations. Finally, print the maximum index obtained. Time Complexity: O(N3)Auxiliary Space: O(1) Efficient Approach:Calculate the maximum index that can be reached within the given steps. If the 0th Index can be reached from the maximum index by avoiding the bad index, print the result. Otherwise, repeat the procedure by decrementing the maximum index by 1.Below are the steps: Calculate the maximum index that can be reached in N steps by calculating the sum of the first N natural numbers.Assign the value of the calculated maximum index to the Current Index.Keep decrementing Current Index by Step Number and Step Number by 1 until one of them becomes negative.After every decrement, check if the Current Index is equal to B or not. If found to be true, revert the changes made on the Current Index.If the Current Index reaches 0 successfully, print the current value of the maximum index as the answer.Otherwise, decrement the value of the maximum index by 1 and repeat from step 2. Calculate the maximum index that can be reached in N steps by calculating the sum of the first N natural numbers. Assign the value of the calculated maximum index to the Current Index. Keep decrementing Current Index by Step Number and Step Number by 1 until one of them becomes negative. After every decrement, check if the Current Index is equal to B or not. If found to be true, revert the changes made on the Current Index. If the Current Index reaches 0 successfully, print the current value of the maximum index as the answer. Otherwise, decrement the value of the maximum index by 1 and repeat from step 2. 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; // Function to find the maximum// index the pointer can reachvoid maximumIndex(int N, int B){ int max_index = 0; // Calculate maximum possible // index that can be reached for (int i = 1; i <= N; i++) { max_index += i; } int current_index = max_index, step = N; while (1) { // Check if current index and step // both are greater than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index by step current_index -= N; // Check if current index is // equal to B or not if (current_index == B) { // Restore to previous index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result cout << max_index << endl; break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver Codeint main(){ int N = 3, B = 2; maximumIndex(N, B); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to find the maximum// index the pointer can reachstatic void maximumIndex(int N, int B){int max_index = 0; // Calculate maximum possible// index that can be reachedfor (int i = 1; i <= N; i++){ max_index += i;} int current_index = max_index, step = N; while (true){ // Check if current index // and step both are greater // than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index // by step current_index -= N; // Check if current index // is equal to B or not if (current_index == B) { // Restore to previous // index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result System.out.print(max_index + "\n"); break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in // current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is // equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } }}} // Driver Codepublic static void main(String[] args){int N = 3, B = 2;maximumIndex(N, B);}} // This code is contributed by gauravrajput1 # Python3 program for the above approach # Function to find the maximum# index the pointer can reachdef maximumIndex(N, B): max_index = 0 # Calculate maximum possible # index that can be reached for i in range(1, N + 1): max_index += i current_index = max_index step = N while (1): # Check if current index and step # both are greater than 0 or not while (current_index > 0 and N > 0): # Decrement current_index by step current_index -= N # Check if current index is # equal to B or not if (current_index == B): # Restore to previous index current_index += N # Decrement step by one N -= 1 # If it reaches the 0th index if (current_index <= 0): # Print result print(max_index) break # If max index fails to # reach the 0th index else: N = step # Store max_index - 1 in current index current_index = max_index - 1 # Decrement max index max_index -= 1 # If current index is equal to B if (current_index == B): current_index = max_index - 1 # Decrement current index max_index -= 1 # Driver Codeif __name__ == '__main__': N = 3 B = 2 maximumIndex(N, B) # This code is contributed by mohit kumar 29 // C# program for the// above approachusing System; class GFG{ // Function to find the maximum// index the pointer can reachstatic void maximumIndex(int N, int B){ int max_index = 0; // Calculate maximum possible // index that can be reached for(int i = 1; i <= N; i++) { max_index += i; } int current_index = max_index, step = N; while (true) { // Check if current index // and step both are greater // than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index // by step current_index -= N; // Check if current index // is equal to B or not if (current_index == B) { // Restore to previous // index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result Console.Write(max_index + " "); break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in // current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is // equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver codepublic static void Main (String[] args){ int N = 3, B = 2; maximumIndex(N, B);}} // This code is contributed by offbeat <script> // Javascript program for the above approach // Function to find the maximum// index the pointer can reachfunction maximumIndex( N, B){ var max_index = 0; // Calculate maximum possible // index that can be reached for (var i = 1; i <= N; i++) { max_index += i; } var current_index = max_index, step = N; while (1) { // Check if current index and step // both are greater than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index by step current_index -= N; // Check if current index is // equal to B or not if (current_index == B) { // Restore to previous index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result document.write(max_index + "<br>");; break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver Codevar N = 3, B = 2;maximumIndex(N, B); // This code is contributed by rrrtnx.</script> 6 Time Complexity: O(N2)Auxiliary Space: O(1) mohit kumar 29 GauravRajput1 offbeat rrrtnx interview-preparation Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Apr, 2021" }, { "code": null, "e": 295, "s": 54, "text": "Given two integers N and B, the task is to print the maximum index a pointer, starting from 0th index can reach in an array of natural numbers(i.e., 0, 1, 2, 3, 4, 5...), say arr[], in N steps without placing itself at index B at any point." }, { "code": null, "e": 452, "s": 295, "text": "In each step, the pointer can move from the Current Index to a Jumping Index or can remain at the Current Index. Jumping Index = Current Index + Step Number" }, { "code": null, "e": 462, "s": 452, "text": "Examples:" }, { "code": null, "e": 505, "s": 462, "text": "Input: N = 3, B = 2Output: 6Explanation: " }, { "code": null, "e": 752, "s": 505, "text": "Step 1:Current Index = 0Step Number = 1Jumping Index = 0 + 1 = 1Step 2:Current Index = 1Step Number = 2Jumping Index = 1 + 2 = 3Step 3:Current Index = 3Step Number = 3Jumping Index = 3 + 3 = 6Therefore, the maximum index that can be reached is 6." }, { "code": null, "e": 794, "s": 752, "text": "Input: N = 3, B = 1Output: 5Explanation: " }, { "code": null, "e": 1104, "s": 794, "text": "Step 1:Current Index = 0Step Number = 1Jumping Index = 0 + 1 = 1But this is bad index. So pointer remains at the Current Index.Step 2:Current Index = 0Step Number = 2Jumping Index = 0 + 2 = 2Step 3:Current Index = 2Step Number = 3Jumping Index = 2 + 3 = 5Therefore, the maximum index that can be reached is 5." }, { "code": null, "e": 1419, "s": 1104, "text": "Naive Approach: The simplest approach to solve the problem is to calculate the maximum index by considering two possibilities for every Current Index, either to move the pointer by Step Number or by remaining at the Current Index, and generate all possible combinations. Finally, print the maximum index obtained. " }, { "code": null, "e": 1463, "s": 1419, "text": "Time Complexity: O(N3)Auxiliary Space: O(1)" }, { "code": null, "e": 1746, "s": 1463, "text": "Efficient Approach:Calculate the maximum index that can be reached within the given steps. If the 0th Index can be reached from the maximum index by avoiding the bad index, print the result. Otherwise, repeat the procedure by decrementing the maximum index by 1.Below are the steps:" }, { "code": null, "e": 2355, "s": 1746, "text": "Calculate the maximum index that can be reached in N steps by calculating the sum of the first N natural numbers.Assign the value of the calculated maximum index to the Current Index.Keep decrementing Current Index by Step Number and Step Number by 1 until one of them becomes negative.After every decrement, check if the Current Index is equal to B or not. If found to be true, revert the changes made on the Current Index.If the Current Index reaches 0 successfully, print the current value of the maximum index as the answer.Otherwise, decrement the value of the maximum index by 1 and repeat from step 2." }, { "code": null, "e": 2469, "s": 2355, "text": "Calculate the maximum index that can be reached in N steps by calculating the sum of the first N natural numbers." }, { "code": null, "e": 2540, "s": 2469, "text": "Assign the value of the calculated maximum index to the Current Index." }, { "code": null, "e": 2644, "s": 2540, "text": "Keep decrementing Current Index by Step Number and Step Number by 1 until one of them becomes negative." }, { "code": null, "e": 2783, "s": 2644, "text": "After every decrement, check if the Current Index is equal to B or not. If found to be true, revert the changes made on the Current Index." }, { "code": null, "e": 2888, "s": 2783, "text": "If the Current Index reaches 0 successfully, print the current value of the maximum index as the answer." }, { "code": null, "e": 2969, "s": 2888, "text": "Otherwise, decrement the value of the maximum index by 1 and repeat from step 2." }, { "code": null, "e": 3020, "s": 2969, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3024, "s": 3020, "text": "C++" }, { "code": null, "e": 3029, "s": 3024, "text": "Java" }, { "code": null, "e": 3037, "s": 3029, "text": "Python3" }, { "code": null, "e": 3040, "s": 3037, "text": "C#" }, { "code": null, "e": 3051, "s": 3040, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// index the pointer can reachvoid maximumIndex(int N, int B){ int max_index = 0; // Calculate maximum possible // index that can be reached for (int i = 1; i <= N; i++) { max_index += i; } int current_index = max_index, step = N; while (1) { // Check if current index and step // both are greater than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index by step current_index -= N; // Check if current index is // equal to B or not if (current_index == B) { // Restore to previous index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result cout << max_index << endl; break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver Codeint main(){ int N = 3, B = 2; maximumIndex(N, B); return 0;}", "e": 4648, "s": 3051, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to find the maximum// index the pointer can reachstatic void maximumIndex(int N, int B){int max_index = 0; // Calculate maximum possible// index that can be reachedfor (int i = 1; i <= N; i++){ max_index += i;} int current_index = max_index, step = N; while (true){ // Check if current index // and step both are greater // than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index // by step current_index -= N; // Check if current index // is equal to B or not if (current_index == B) { // Restore to previous // index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result System.out.print(max_index + \"\\n\"); break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in // current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is // equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } }}} // Driver Codepublic static void main(String[] args){int N = 3, B = 2;maximumIndex(N, B);}} // This code is contributed by gauravrajput1", "e": 6114, "s": 4648, "text": null }, { "code": "# Python3 program for the above approach # Function to find the maximum# index the pointer can reachdef maximumIndex(N, B): max_index = 0 # Calculate maximum possible # index that can be reached for i in range(1, N + 1): max_index += i current_index = max_index step = N while (1): # Check if current index and step # both are greater than 0 or not while (current_index > 0 and N > 0): # Decrement current_index by step current_index -= N # Check if current index is # equal to B or not if (current_index == B): # Restore to previous index current_index += N # Decrement step by one N -= 1 # If it reaches the 0th index if (current_index <= 0): # Print result print(max_index) break # If max index fails to # reach the 0th index else: N = step # Store max_index - 1 in current index current_index = max_index - 1 # Decrement max index max_index -= 1 # If current index is equal to B if (current_index == B): current_index = max_index - 1 # Decrement current index max_index -= 1 # Driver Codeif __name__ == '__main__': N = 3 B = 2 maximumIndex(N, B) # This code is contributed by mohit kumar 29", "e": 7606, "s": 6114, "text": null }, { "code": "// C# program for the// above approachusing System; class GFG{ // Function to find the maximum// index the pointer can reachstatic void maximumIndex(int N, int B){ int max_index = 0; // Calculate maximum possible // index that can be reached for(int i = 1; i <= N; i++) { max_index += i; } int current_index = max_index, step = N; while (true) { // Check if current index // and step both are greater // than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index // by step current_index -= N; // Check if current index // is equal to B or not if (current_index == B) { // Restore to previous // index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result Console.Write(max_index + \" \"); break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in // current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is // equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver codepublic static void Main (String[] args){ int N = 3, B = 2; maximumIndex(N, B);}} // This code is contributed by offbeat", "e": 9209, "s": 7606, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the maximum// index the pointer can reachfunction maximumIndex( N, B){ var max_index = 0; // Calculate maximum possible // index that can be reached for (var i = 1; i <= N; i++) { max_index += i; } var current_index = max_index, step = N; while (1) { // Check if current index and step // both are greater than 0 or not while (current_index > 0 && N > 0) { // Decrement current_index by step current_index -= N; // Check if current index is // equal to B or not if (current_index == B) { // Restore to previous index current_index += N; } // Decrement step by one N--; } // If it reaches the 0th index if (current_index <= 0) { // Print result document.write(max_index + \"<br>\");; break; } // If max index fails to // reach the 0th index else { N = step; // Store max_index - 1 in current index current_index = max_index - 1; // Decrement max index max_index--; // If current index is equal to B if (current_index == B) { current_index = max_index - 1; // Decrement current index max_index--; } } }} // Driver Codevar N = 3, B = 2;maximumIndex(N, B); // This code is contributed by rrrtnx.</script>", "e": 10800, "s": 9209, "text": null }, { "code": null, "e": 10802, "s": 10800, "text": "6" }, { "code": null, "e": 10849, "s": 10804, "text": "Time Complexity: O(N2)Auxiliary Space: O(1) " }, { "code": null, "e": 10866, "s": 10851, "text": "mohit kumar 29" }, { "code": null, "e": 10880, "s": 10866, "text": "GauravRajput1" }, { "code": null, "e": 10888, "s": 10880, "text": "offbeat" }, { "code": null, "e": 10895, "s": 10888, "text": "rrrtnx" }, { "code": null, "e": 10917, "s": 10895, "text": "interview-preparation" }, { "code": null, "e": 10931, "s": 10917, "text": "Combinatorial" }, { "code": null, "e": 10944, "s": 10931, "text": "Mathematical" }, { "code": null, "e": 10957, "s": 10944, "text": "Mathematical" }, { "code": null, "e": 10971, "s": 10957, "text": "Combinatorial" } ]
SQL Query to Check If a Name Begins and Ends With a Vowel
08 Oct, 2021 In this article, we will see an SQL query to check if a name begins and ends with a vowel and we will implement it with the help of an example for better understanding, first of all, we will create a database Name of the Database will GeeksforGeeks. and inside the database, we will create a table name As “Student”. Here we use two different methods for this. Syntax: FOR LEFT(): LEFT ( expression, no_of_chars needed to the left) FOR RIGHT(): RIGHT ( expression, no_of_chars needed to the right) In this article let us see how to Check If a Name Begins and Ends With a Vowel and display them using MSSQL as a server. Creating a database GeeksforGeeks by using the following SQL query as follows. Query: CREATE DATABASE GeeksforGeeks; Using the database GeeksforGeeks using the following SQL query as follows. Query: USE GeeksforGeeks; Creating a table student with 3 columns using the following SQL query as follows. Query: CREATE TABLE student( stu_id VARCHAR(8), stu_name VARCHAR(30), stu_branch VARCHAR(30) ) To view the description of the table using the following SQL query as follows. Query: EXEC sp_columns student Inserting rows into student tables using the following SQL query as follows. Query: INSERT INTO student VALUES ('191401', 'ABHI','E.C.E'), ('191402', 'OLIVIA','E.C.E'), ('191403', 'SAMARTH','E.C.E'), ('191404', 'ANNABELLE','E.C.E'), ('191405', 'ARIA','E.C.E'), ('191406', 'RAMESH','E.C.E') Viewing the table student after inserting rows by using the following SQL query as follows. Query: SELECT * FROM student Step 7: Query to Check If a Name Begins and Ends With a Vowel using string functions and IN operator To check if a name begins ends with a vowel we use the string functions to pick the first and last characters and check if they were matching with vowels using in where the condition of the query. We use the LEFT() and RIGHT() functions of the string in SQL to check the first and last characters. Query: SELECT stu_name FROM student WHERE LEFT(stu_name , 1) IN ('a','e','i','o','u') AND RIGHT(stu_name,1) IN ('a','e','i','o','u') Output: Method 2: Using Regular Expressions and LIKE operator to check if first and last characters are vowels. Query to Check If a Name Begins and Ends With a Vowel using REGEX Query: SELECT stu_name FROM student WHERE stu_name LIKE '[aeiouAEIOU]%[aeiouAEIOU]' Here % is used for multiple occurrences of any character and [] is used for anyone occurrence of a given set of characters in the brackets. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Oct, 2021" }, { "code": null, "e": 371, "s": 53, "text": "In this article, we will see an SQL query to check if a name begins and ends with a vowel and we will implement it with the help of an example for better understanding, first of all, we will create a database Name of the Database will GeeksforGeeks. and inside the database, we will create a table name As “Student”. " }, { "code": null, "e": 415, "s": 371, "text": "Here we use two different methods for this." }, { "code": null, "e": 423, "s": 415, "text": "Syntax:" }, { "code": null, "e": 553, "s": 423, "text": "FOR LEFT():\nLEFT ( expression, no_of_chars needed to the left)\n\nFOR RIGHT():\nRIGHT ( expression, no_of_chars needed to the right)" }, { "code": null, "e": 674, "s": 553, "text": "In this article let us see how to Check If a Name Begins and Ends With a Vowel and display them using MSSQL as a server." }, { "code": null, "e": 753, "s": 674, "text": "Creating a database GeeksforGeeks by using the following SQL query as follows." }, { "code": null, "e": 760, "s": 753, "text": "Query:" }, { "code": null, "e": 791, "s": 760, "text": "CREATE DATABASE GeeksforGeeks;" }, { "code": null, "e": 866, "s": 791, "text": "Using the database GeeksforGeeks using the following SQL query as follows." }, { "code": null, "e": 873, "s": 866, "text": "Query:" }, { "code": null, "e": 892, "s": 873, "text": "USE GeeksforGeeks;" }, { "code": null, "e": 974, "s": 892, "text": "Creating a table student with 3 columns using the following SQL query as follows." }, { "code": null, "e": 981, "s": 974, "text": "Query:" }, { "code": null, "e": 1069, "s": 981, "text": "CREATE TABLE student(\nstu_id VARCHAR(8),\nstu_name VARCHAR(30),\nstu_branch VARCHAR(30)\n)" }, { "code": null, "e": 1148, "s": 1069, "text": "To view the description of the table using the following SQL query as follows." }, { "code": null, "e": 1155, "s": 1148, "text": "Query:" }, { "code": null, "e": 1180, "s": 1155, "text": "EXEC sp_columns student " }, { "code": null, "e": 1257, "s": 1180, "text": "Inserting rows into student tables using the following SQL query as follows." }, { "code": null, "e": 1264, "s": 1257, "text": "Query:" }, { "code": null, "e": 1470, "s": 1264, "text": "INSERT INTO student VALUES\n('191401', 'ABHI','E.C.E'),\n('191402', 'OLIVIA','E.C.E'),\n('191403', 'SAMARTH','E.C.E'),\n('191404', 'ANNABELLE','E.C.E'),\n('191405', 'ARIA','E.C.E'),\n('191406', 'RAMESH','E.C.E')" }, { "code": null, "e": 1562, "s": 1470, "text": "Viewing the table student after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 1569, "s": 1562, "text": "Query:" }, { "code": null, "e": 1592, "s": 1569, "text": "SELECT * FROM student " }, { "code": null, "e": 1694, "s": 1592, "text": "Step 7: Query to Check If a Name Begins and Ends With a Vowel using string functions and IN operator" }, { "code": null, "e": 1992, "s": 1694, "text": "To check if a name begins ends with a vowel we use the string functions to pick the first and last characters and check if they were matching with vowels using in where the condition of the query. We use the LEFT() and RIGHT() functions of the string in SQL to check the first and last characters." }, { "code": null, "e": 1999, "s": 1992, "text": "Query:" }, { "code": null, "e": 2127, "s": 1999, "text": "SELECT stu_name\nFROM student \nWHERE LEFT(stu_name , 1) IN ('a','e','i','o','u')\nAND RIGHT(stu_name,1) IN ('a','e','i','o','u')" }, { "code": null, "e": 2135, "s": 2127, "text": "Output:" }, { "code": null, "e": 2146, "s": 2135, "text": "Method 2: " }, { "code": null, "e": 2307, "s": 2146, "text": "Using Regular Expressions and LIKE operator to check if first and last characters are vowels. Query to Check If a Name Begins and Ends With a Vowel using REGEX" }, { "code": null, "e": 2314, "s": 2307, "text": "Query:" }, { "code": null, "e": 2393, "s": 2314, "text": "SELECT stu_name \nFROM student \nWHERE stu_name LIKE '[aeiouAEIOU]%[aeiouAEIOU]'" }, { "code": null, "e": 2533, "s": 2393, "text": "Here % is used for multiple occurrences of any character and [] is used for anyone occurrence of a given set of characters in the brackets." }, { "code": null, "e": 2541, "s": 2533, "text": "Output:" }, { "code": null, "e": 2548, "s": 2541, "text": "Picked" }, { "code": null, "e": 2558, "s": 2548, "text": "SQL-Query" }, { "code": null, "e": 2569, "s": 2558, "text": "SQL-Server" }, { "code": null, "e": 2573, "s": 2569, "text": "SQL" }, { "code": null, "e": 2577, "s": 2573, "text": "SQL" } ]
Shell Script to Delete Zero Sized Files From a Directory
30 Apr, 2021 A zero-sized file is a file that contains no data and has a length of 0. It is also called a zero-byte file. Incomplete transfers can be responsible for the zero-sized file. You can create a zero-sized file intentionally by running the following command in the terminal : touch zero_sized_file_name Output: zero-sized file Approaches: Input directory name and check if the directory exists in the current folder/directory. Use for loop to traverse each file and check their size. Steps included: Firstly we are taking the directory name as input from the user using the read command.To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists.If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, if the file is zero-sized then we enter the loop and remove the file using the rm command. rm (remove) is used to delete the files/folder.After that, we are displaying that the files have been successfully deleted using the echo command. echo is just like a print statement it is used to display things on the screen.If the directory doesn’t exist we are going to display the directory that doesn’t exist. Firstly we are taking the directory name as input from the user using the read command. To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists. If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, if the file is zero-sized then we enter the loop and remove the file using the rm command. rm (remove) is used to delete the files/folder. After that, we are displaying that the files have been successfully deleted using the echo command. echo is just like a print statement it is used to display things on the screen. If the directory doesn’t exist we are going to display the directory that doesn’t exist. #! /bin/bash # Taking directory name as input from user echo -n "Enter name of the directory : " read directory_name # If directory exists it will print # Directory exits # and remove the zero-sized files. # Or if directory doesn't exists it will print # Directory does not exists. if [ -d "$directory_name" ]; then echo "Directory exist" for i in `find $directory_name -size 0` do rm $i echo "Zero-sized files are Successfully deleted" done else echo "Directory does not exist" fi Steps included: First, we have to take the directory name as input from the user using the read command and store it in variable directory_name.To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists.If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, as soon as we found a file that meets our requirements (i.e. file with zero-sized), using -delete argument we will delete that particular file from that directory. We do the same until there is no file with zero sizes.After that, we are displaying that the files have been successfully deleted using the echo command. echo is used to display things on the screen.If the directory doesn’t exist we simply return that the directory that doesn’t exist using the echo command. First, we have to take the directory name as input from the user using the read command and store it in variable directory_name. To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists. If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, as soon as we found a file that meets our requirements (i.e. file with zero-sized), using -delete argument we will delete that particular file from that directory. We do the same until there is no file with zero sizes. After that, we are displaying that the files have been successfully deleted using the echo command. echo is used to display things on the screen. If the directory doesn’t exist we simply return that the directory that doesn’t exist using the echo command. #! /bin/bash # Taking directory name as input from user echo -n "Enter name of the directory : " read directory_name # If directory exist it will print # Directory exits # and remove the zero-sized files. # Or if directory doesn't exist it will print # Directory does not exist. if [ -d "$directory_name" ]; then echo "$directory_name Directory exist" for i in `find $directory_name -size 0 -delete` do echo "" done echo "Zero-sized files are Successfully deleted" else echo "$directory_name does not exist" fi Output : Before After using script Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2021" }, { "code": null, "e": 300, "s": 28, "text": "A zero-sized file is a file that contains no data and has a length of 0. It is also called a zero-byte file. Incomplete transfers can be responsible for the zero-sized file. You can create a zero-sized file intentionally by running the following command in the terminal :" }, { "code": null, "e": 327, "s": 300, "text": "touch zero_sized_file_name" }, { "code": null, "e": 335, "s": 327, "text": "Output:" }, { "code": null, "e": 351, "s": 335, "text": "zero-sized file" }, { "code": null, "e": 363, "s": 351, "text": "Approaches:" }, { "code": null, "e": 451, "s": 363, "text": "Input directory name and check if the directory exists in the current folder/directory." }, { "code": null, "e": 508, "s": 451, "text": "Use for loop to traverse each file and check their size." }, { "code": null, "e": 524, "s": 508, "text": "Steps included:" }, { "code": null, "e": 1370, "s": 524, "text": "Firstly we are taking the directory name as input from the user using the read command.To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists.If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, if the file is zero-sized then we enter the loop and remove the file using the rm command. rm (remove) is used to delete the files/folder.After that, we are displaying that the files have been successfully deleted using the echo command. echo is just like a print statement it is used to display things on the screen.If the directory doesn’t exist we are going to display the directory that doesn’t exist." }, { "code": null, "e": 1458, "s": 1370, "text": "Firstly we are taking the directory name as input from the user using the read command." }, { "code": null, "e": 1671, "s": 1458, "text": "To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists." }, { "code": null, "e": 1951, "s": 1671, "text": "If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, if the file is zero-sized then we enter the loop and remove the file using the rm command. rm (remove) is used to delete the files/folder." }, { "code": null, "e": 2131, "s": 1951, "text": "After that, we are displaying that the files have been successfully deleted using the echo command. echo is just like a print statement it is used to display things on the screen." }, { "code": null, "e": 2220, "s": 2131, "text": "If the directory doesn’t exist we are going to display the directory that doesn’t exist." }, { "code": null, "e": 2772, "s": 2220, "text": "#! /bin/bash\n\n# Taking directory name as input from user\necho -n \"Enter name of the directory : \"\nread directory_name\n\n# If directory exists it will print \n# Directory exits \n# and remove the zero-sized files.\n# Or if directory doesn't exists it will print \n# Directory does not exists.\nif [ -d \"$directory_name\" ];\nthen\n echo \"Directory exist\"\n for i in `find $directory_name -size 0`\n do\n rm $i \n echo \"Zero-sized files are Successfully deleted\" \n done\nelse\n echo \"Directory does not exist\"\n\nfi" }, { "code": null, "e": 2788, "s": 2772, "text": "Steps included:" }, { "code": null, "e": 3742, "s": 2788, "text": "First, we have to take the directory name as input from the user using the read command and store it in variable directory_name.To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists.If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, as soon as we found a file that meets our requirements (i.e. file with zero-sized), using -delete argument we will delete that particular file from that directory. We do the same until there is no file with zero sizes.After that, we are displaying that the files have been successfully deleted using the echo command. echo is used to display things on the screen.If the directory doesn’t exist we simply return that the directory that doesn’t exist using the echo command." }, { "code": null, "e": 3871, "s": 3742, "text": "First, we have to take the directory name as input from the user using the read command and store it in variable directory_name." }, { "code": null, "e": 4084, "s": 3871, "text": "To check if the directory name entered by the user really exists, we are using the if [-d “$directory_name”] statement. Here we are using if statement with the -d flag it will return true if the directory exists." }, { "code": null, "e": 4444, "s": 4084, "text": "If the directory exists then we are going to use the looping statement (for loop) to iterate over files and check their size using -size 0, as soon as we found a file that meets our requirements (i.e. file with zero-sized), using -delete argument we will delete that particular file from that directory. We do the same until there is no file with zero sizes." }, { "code": null, "e": 4590, "s": 4444, "text": "After that, we are displaying that the files have been successfully deleted using the echo command. echo is used to display things on the screen." }, { "code": null, "e": 4700, "s": 4590, "text": "If the directory doesn’t exist we simply return that the directory that doesn’t exist using the echo command." }, { "code": null, "e": 5271, "s": 4700, "text": "#! /bin/bash\n\n# Taking directory name as input from user\necho -n \"Enter name of the directory : \"\nread directory_name\n\n# If directory exist it will print \n# Directory exits \n# and remove the zero-sized files.\n# Or if directory doesn't exist it will print \n# Directory does not exist.\nif [ -d \"$directory_name\" ];\nthen\n echo \"$directory_name Directory exist\"\n for i in `find $directory_name -size 0 -delete`\n do\n echo \"\"\n done\n echo \"Zero-sized files are Successfully deleted\" \nelse\n echo \"$directory_name does not exist\"\n\nfi\n " }, { "code": null, "e": 5280, "s": 5271, "text": "Output :" }, { "code": null, "e": 5288, "s": 5280, "text": "Before " }, { "code": null, "e": 5307, "s": 5288, "text": "After using script" }, { "code": null, "e": 5314, "s": 5307, "text": "Picked" }, { "code": null, "e": 5327, "s": 5314, "text": "Shell Script" }, { "code": null, "e": 5338, "s": 5327, "text": "Linux-Unix" } ]
Recursive sum of digits of a number formed by repeated appends
25 Aug, 2021 Given two positive number N and X. The task is to find the sum of digits of a number formed by N repeating X number of times until sum become single digit. Examples : Input : N = 24, X = 3 Output : 9 Number formed after repeating 24 three time = 242424 Sum = 2 + 4 + 2 + 4 + 2 + 4 = 18 Sum is not the single digit, so finding the sum of digits of 18, 1 + 8 = 9 Input : N = 4, X = 4 Output : 7 As discussed in this post, recursive sum of digits is 9 if number is multiple of 9, else n % 9. Since divisibility and modular arithmetic are compatible with multiplication, we simply find result for single occurrence, multiply result with x and again find the result. How does this work? Lets N = 24 and X = 3. So, sumUntilSingle(N) = 2 + 4 = 6. Multiplying 6 by 3 = 18 sumUntilSingle(18) = 9. Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find Sum of digits of a// number formed by repeating a number X number of// times until sum become single digit.#include <bits/stdc++.h>using namespace std; // return single digit sum of a number.int digSum(int n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Returns recursive sum of digits of a number// formed by repeating a number X number of// times until sum become single digit.int repeatedNumberSum(int n, int x){ int sum = x*digSum(n); return digSum(sum);} // Driver programint main(){ int n = 24, x = 3; cout << repeatedNumberSum(n, x) << endl; return 0;} // Java program to find Sum of digits of a// number formed by repeating a number X number of// times until sum become single digit. class GFG { // return single digit sum of a number. static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Returns recursive sum of digits of a number // formed by repeating a number X number of // times until sum become single digit. static int repeatedNumberSum(int n, int x) { int sum = x * digSum(n); return digSum(sum); } // Driver program public static void main (String[] args) { int n = 24, x = 3; System.out.println(repeatedNumberSum(n, x)); }} // This code is contributed by Ajit. # Python program to find Sum of digits of a# number formed by repeating a number X number# of times until sum become single digit. # Return single digit sum of a numberdef digSum(n): if n == 0: return 0 return (n % 9 == 0) and 9 or (n % 9) # Returns recursive sum of digits of a number# formed by repeating a number X number of# times until sum become single digit.def repeatedNumberSum(n, x): sum = x * digSum(n) return digSum(sum) # Driver Coden = 24; x = 3print(repeatedNumberSum(n, x)) # This code is contributed by Ajit. // C# program to find Sum of digits of a// number formed by repeating a number X// number of times until sum becomes// single digit.using System; public class GFG{ // return single digit sum of a number. static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Returns recursive sum of digits of a // number formed by repeating a number X // number of times until sum become // single digit. static int repeatedNumberSum(int n, int x) { int sum = x * digSum(n); return digSum(sum); } // driver program public static void Main () { int n = 24, x = 3; Console.Write( repeatedNumberSum(n, x)); }} // This code is contributed by Sam007 <?php// PHP program to find Sum// of digits of a number// formed by repeating a number// X number of times until// sum becomes single digit. // return single digit// sum of a number.function digSum($n){ if ($n == 0) return 0; return ($n % 9 == 0) ? 9 : ($n % 9);} // Returns recursive sum of// digits of a number formed// by repeating a number X// number of times until sum// become single digit.function repeatedNumberSum( $n, $x){ $sum = $x * digSum($n); return digSum($sum);} // Driver Code$n = 24; $x = 3;echo repeatedNumberSum($n, $x); // This code is contributed by anuj_67.?> <script> // Javascript program to find Sum// of digits of a number formed by// repeating a number X number of// times until sum becomes single digit. // Return single digit// sum of a number.function digSum(n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Returns recursive sum of// digits of a number formed// by repeating a number X// number of times until sum// become single digit.function repeatedNumberSum(n, x){ sum = x * digSum(n); return digSum(sum);} // Driver Codelet n = 24;let x = 3; document.write(repeatedNumberSum(n, x)); // This code is contributed by _saurabh_jaiswal. </script> Output : 9 vt_m _saurabh_jaiswal saurabh1990aror Modular Arithmetic number-digits Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Aug, 2021" }, { "code": null, "e": 209, "s": 53, "text": "Given two positive number N and X. The task is to find the sum of digits of a number formed by N repeating X number of times until sum become single digit." }, { "code": null, "e": 222, "s": 209, "text": "Examples : " }, { "code": null, "e": 454, "s": 222, "text": "Input : N = 24, X = 3\nOutput : 9\nNumber formed after repeating 24 three time = 242424\nSum = 2 + 4 + 2 + 4 + 2 + 4\n = 18\nSum is not the single digit, so finding \nthe sum of digits of 18,\n1 + 8 = 9\n\nInput : N = 4, X = 4\nOutput : 7" }, { "code": null, "e": 724, "s": 454, "text": "As discussed in this post, recursive sum of digits is 9 if number is multiple of 9, else n % 9. Since divisibility and modular arithmetic are compatible with multiplication, we simply find result for single occurrence, multiply result with x and again find the result. " }, { "code": null, "e": 850, "s": 724, "text": "How does this work? Lets N = 24 and X = 3. So, sumUntilSingle(N) = 2 + 4 = 6. Multiplying 6 by 3 = 18 sumUntilSingle(18) = 9." }, { "code": null, "e": 898, "s": 850, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 902, "s": 898, "text": "C++" }, { "code": null, "e": 907, "s": 902, "text": "Java" }, { "code": null, "e": 915, "s": 907, "text": "Python3" }, { "code": null, "e": 918, "s": 915, "text": "C#" }, { "code": null, "e": 922, "s": 918, "text": "PHP" }, { "code": null, "e": 933, "s": 922, "text": "Javascript" }, { "code": "// C++ program to find Sum of digits of a// number formed by repeating a number X number of// times until sum become single digit.#include <bits/stdc++.h>using namespace std; // return single digit sum of a number.int digSum(int n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Returns recursive sum of digits of a number// formed by repeating a number X number of// times until sum become single digit.int repeatedNumberSum(int n, int x){ int sum = x*digSum(n); return digSum(sum);} // Driver programint main(){ int n = 24, x = 3; cout << repeatedNumberSum(n, x) << endl; return 0;}", "e": 1561, "s": 933, "text": null }, { "code": "// Java program to find Sum of digits of a// number formed by repeating a number X number of// times until sum become single digit. class GFG { // return single digit sum of a number. static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Returns recursive sum of digits of a number // formed by repeating a number X number of // times until sum become single digit. static int repeatedNumberSum(int n, int x) { int sum = x * digSum(n); return digSum(sum); } // Driver program public static void main (String[] args) { int n = 24, x = 3; System.out.println(repeatedNumberSum(n, x)); }} // This code is contributed by Ajit.", "e": 2332, "s": 1561, "text": null }, { "code": "# Python program to find Sum of digits of a# number formed by repeating a number X number# of times until sum become single digit. # Return single digit sum of a numberdef digSum(n): if n == 0: return 0 return (n % 9 == 0) and 9 or (n % 9) # Returns recursive sum of digits of a number# formed by repeating a number X number of# times until sum become single digit.def repeatedNumberSum(n, x): sum = x * digSum(n) return digSum(sum) # Driver Coden = 24; x = 3print(repeatedNumberSum(n, x)) # This code is contributed by Ajit.", "e": 2881, "s": 2332, "text": null }, { "code": "// C# program to find Sum of digits of a// number formed by repeating a number X// number of times until sum becomes// single digit.using System; public class GFG{ // return single digit sum of a number. static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Returns recursive sum of digits of a // number formed by repeating a number X // number of times until sum become // single digit. static int repeatedNumberSum(int n, int x) { int sum = x * digSum(n); return digSum(sum); } // driver program public static void Main () { int n = 24, x = 3; Console.Write( repeatedNumberSum(n, x)); }} // This code is contributed by Sam007", "e": 3670, "s": 2881, "text": null }, { "code": "<?php// PHP program to find Sum// of digits of a number// formed by repeating a number// X number of times until// sum becomes single digit. // return single digit// sum of a number.function digSum($n){ if ($n == 0) return 0; return ($n % 9 == 0) ? 9 : ($n % 9);} // Returns recursive sum of// digits of a number formed// by repeating a number X// number of times until sum// become single digit.function repeatedNumberSum( $n, $x){ $sum = $x * digSum($n); return digSum($sum);} // Driver Code$n = 24; $x = 3;echo repeatedNumberSum($n, $x); // This code is contributed by anuj_67.?>", "e": 4272, "s": 3670, "text": null }, { "code": "<script> // Javascript program to find Sum// of digits of a number formed by// repeating a number X number of// times until sum becomes single digit. // Return single digit// sum of a number.function digSum(n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Returns recursive sum of// digits of a number formed// by repeating a number X// number of times until sum// become single digit.function repeatedNumberSum(n, x){ sum = x * digSum(n); return digSum(sum);} // Driver Codelet n = 24;let x = 3; document.write(repeatedNumberSum(n, x)); // This code is contributed by _saurabh_jaiswal. </script>", "e": 4913, "s": 4272, "text": null }, { "code": null, "e": 4923, "s": 4913, "text": "Output : " }, { "code": null, "e": 4925, "s": 4923, "text": "9" }, { "code": null, "e": 4932, "s": 4927, "text": "vt_m" }, { "code": null, "e": 4949, "s": 4932, "text": "_saurabh_jaiswal" }, { "code": null, "e": 4965, "s": 4949, "text": "saurabh1990aror" }, { "code": null, "e": 4984, "s": 4965, "text": "Modular Arithmetic" }, { "code": null, "e": 4998, "s": 4984, "text": "number-digits" }, { "code": null, "e": 5011, "s": 4998, "text": "Mathematical" }, { "code": null, "e": 5024, "s": 5011, "text": "Mathematical" }, { "code": null, "e": 5043, "s": 5024, "text": "Modular Arithmetic" } ]
How to print a circular structure in a JSON like format using JavaScript ?
09 Feb, 2021 The circular structure is when you try to reference an object which directly or indirectly references itself. Example: A -> B -> A OR A -> A Circular structures are pretty common while developing an application. For Example, suppose you are developing a social media application where each user may have one or more images. Each image may be referencing its owner. Something like this: { User1: { Image1:{ URL: 'Image Url', Owner: User1 (object) }, Image2:{ URL: 'Image Url', Owner: User1 (object) } } } Here you can easily resolve this by passing the user id to Owner instead of the user object. Passing such objects to JSON.stringify() results in ‘Converting circular structure to JSON Error’. Let’s take an example and try to resolve this issue. Example: Javascript var object = {};object.array = {'first':1};object.array2 = object; console.log(object); The output should look something like this: If we pass the above object to JSON.stringify() then this will result in the following error: To resolve this we can pass another parameter to JSON.stringify() which is actually a function. And we can handle the object however we want inside the function. It takes two parameters, the key and the value that is being stringified. It gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string. Let’s create a function named circularReplacer. const circularReplacer = () => { // Creating new WeakSet to keep // track of previously seen objects const seen = new WeakSet(); return (key, value) => { // If type of value is an // object or value is null if (typeof(value) === "object" && value !== null) { // If it has been seen before if (seen.has(value)) { return; } // Add current value to the set seen.add(value); } // return the value return value; }; }; Explanation: The above function will first create a WeakSet to keep track of previously seen objects. WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. Read more above WeakSet here. Checks if the type of value is an object and the value is not null. Then checks if it has been seen before. If yes then just return. if not then add it to the set. Instead of just return nothing when an object has been seen. We can return even more useful information, for example, return ‘Object’, which will tell us that value of this will create a circular structure. If the type of value is not an object or the value is null. Then simply return the value. Example 1: Javascript var object = {};object.array = {'first':1};object.array2 = object; const circularReplacer = () => { // Creating new WeakSet to keep // track of previously seen objects const seen = new WeakSet(); return (key, value) => { // If type of value is an // object or value is null if (typeof(value) === "object" && value !== null) { // If it has been seen before if (seen.has(value)) { return; } // Add current value to the set seen.add(value); } // return the value return value; };}; var jsonString = JSON.stringify( object, circularReplacer());console.log(jsonString); Output: Note: If we just return when seeing a circular structure that key will not get added to the output string. Example 2: Let’s return a string instead of nothing. Javascript var object = {};object.array = {'first':1};object.array2 = object;object.array3 = object.array2; const circularReplacer = () => { // Creating new WeakSet to keep // track of previously seen objects const seen = new WeakSet(); return (key, value) => { // If type of value is an // object or value is null if (typeof(value) === "object" && value !== null) { // If it has been seen before if (seen.has(value)) { return 'Object'; } // Add current value to the set seen.add(value); } // return the value return value; };}; var jsonString = JSON.stringify( object, circularReplacer());console.log(jsonString); Output: JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2021" }, { "code": null, "e": 138, "s": 28, "text": "The circular structure is when you try to reference an object which directly or indirectly references itself." }, { "code": null, "e": 147, "s": 138, "text": "Example:" }, { "code": null, "e": 173, "s": 147, "text": "A -> B -> A OR A -> A" }, { "code": null, "e": 418, "s": 173, "text": "Circular structures are pretty common while developing an application. For Example, suppose you are developing a social media application where each user may have one or more images. Each image may be referencing its owner. Something like this:" }, { "code": null, "e": 624, "s": 418, "text": "{\n User1: {\n Image1:{\n URL: 'Image Url',\n Owner: User1 (object)\n },\n Image2:{\n URL: 'Image Url',\n Owner: User1 (object)\n }\n }\n}" }, { "code": null, "e": 717, "s": 624, "text": "Here you can easily resolve this by passing the user id to Owner instead of the user object." }, { "code": null, "e": 816, "s": 717, "text": "Passing such objects to JSON.stringify() results in ‘Converting circular structure to JSON Error’." }, { "code": null, "e": 869, "s": 816, "text": "Let’s take an example and try to resolve this issue." }, { "code": null, "e": 878, "s": 869, "text": "Example:" }, { "code": null, "e": 889, "s": 878, "text": "Javascript" }, { "code": "var object = {};object.array = {'first':1};object.array2 = object; console.log(object);", "e": 978, "s": 889, "text": null }, { "code": null, "e": 1022, "s": 978, "text": "The output should look something like this:" }, { "code": null, "e": 1116, "s": 1022, "text": "If we pass the above object to JSON.stringify() then this will result in the following error:" }, { "code": null, "e": 1495, "s": 1116, "text": "To resolve this we can pass another parameter to JSON.stringify() which is actually a function. And we can handle the object however we want inside the function. It takes two parameters, the key and the value that is being stringified. It gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string." }, { "code": null, "e": 1543, "s": 1495, "text": "Let’s create a function named circularReplacer." }, { "code": null, "e": 2144, "s": 1543, "text": "const circularReplacer = () => {\n\n // Creating new WeakSet to keep \n // track of previously seen objects\n const seen = new WeakSet();\n \n return (key, value) => {\n // If type of value is an \n // object or value is null\n if (typeof(value) === \"object\" \n && value !== null) {\n \n // If it has been seen before\n if (seen.has(value)) {\n return;\n }\n \n // Add current value to the set\n seen.add(value);\n }\n \n // return the value\n return value;\n };\n};" }, { "code": null, "e": 2157, "s": 2144, "text": "Explanation:" }, { "code": null, "e": 2419, "s": 2157, "text": "The above function will first create a WeakSet to keep track of previously seen objects. WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. Read more above WeakSet here." }, { "code": null, "e": 2583, "s": 2419, "text": "Checks if the type of value is an object and the value is not null. Then checks if it has been seen before. If yes then just return. if not then add it to the set." }, { "code": null, "e": 2790, "s": 2583, "text": "Instead of just return nothing when an object has been seen. We can return even more useful information, for example, return ‘Object’, which will tell us that value of this will create a circular structure." }, { "code": null, "e": 2880, "s": 2790, "text": "If the type of value is not an object or the value is null. Then simply return the value." }, { "code": null, "e": 2891, "s": 2880, "text": "Example 1:" }, { "code": null, "e": 2902, "s": 2891, "text": "Javascript" }, { "code": "var object = {};object.array = {'first':1};object.array2 = object; const circularReplacer = () => { // Creating new WeakSet to keep // track of previously seen objects const seen = new WeakSet(); return (key, value) => { // If type of value is an // object or value is null if (typeof(value) === \"object\" && value !== null) { // If it has been seen before if (seen.has(value)) { return; } // Add current value to the set seen.add(value); } // return the value return value; };}; var jsonString = JSON.stringify( object, circularReplacer());console.log(jsonString);", "e": 3661, "s": 2902, "text": null }, { "code": null, "e": 3669, "s": 3661, "text": "Output:" }, { "code": null, "e": 3776, "s": 3669, "text": "Note: If we just return when seeing a circular structure that key will not get added to the output string." }, { "code": null, "e": 3829, "s": 3776, "text": "Example 2: Let’s return a string instead of nothing." }, { "code": null, "e": 3840, "s": 3829, "text": "Javascript" }, { "code": "var object = {};object.array = {'first':1};object.array2 = object;object.array3 = object.array2; const circularReplacer = () => { // Creating new WeakSet to keep // track of previously seen objects const seen = new WeakSet(); return (key, value) => { // If type of value is an // object or value is null if (typeof(value) === \"object\" && value !== null) { // If it has been seen before if (seen.has(value)) { return 'Object'; } // Add current value to the set seen.add(value); } // return the value return value; };}; var jsonString = JSON.stringify( object, circularReplacer());console.log(jsonString);", "e": 4635, "s": 3840, "text": null }, { "code": null, "e": 4643, "s": 4635, "text": "Output:" }, { "code": null, "e": 4664, "s": 4643, "text": "JavaScript-Questions" }, { "code": null, "e": 4671, "s": 4664, "text": "Picked" }, { "code": null, "e": 4682, "s": 4671, "text": "JavaScript" }, { "code": null, "e": 4699, "s": 4682, "text": "Web Technologies" } ]
Python Tuples
16 Jun, 2022 Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. This helps in understanding the Python tuples more easily. In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping the data sequence. Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing. Python3 # Creating an empty TupleTuple1 = ()print("Initial empty Tuple: ")print(Tuple1) # Creating a Tuple# with the use of stringTuple1 = ('Geeks', 'For')print("\nTuple with the use of String: ")print(Tuple1) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print("\nTuple using List: ")print(tuple(list1)) # Creating a Tuple# with the use of built-in functionTuple1 = tuple('Geeks')print("\nTuple with the use of function: ")print(Tuple1) Output: Initial empty Tuple: () Tuple with the use of String: ('Geeks', 'For') Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('G', 'e', 'e', 'k', 's') Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple. Python3 # Creating a Tuple# with Mixed DatatypeTuple1 = (5, 'Welcome', 7, 'Geeks')print("\nTuple with Mixed Datatypes: ")print(Tuple1) # Creating a Tuple# with nested tuplesTuple1 = (0, 1, 2, 3)Tuple2 = ('python', 'geek')Tuple3 = (Tuple1, Tuple2)print("\nTuple with nested tuples: ")print(Tuple3) # Creating a Tuple# with repetitionTuple1 = ('Geeks',) * 3print("\nTuple with repetition: ")print(Tuple1) # Creating a Tuple# with the use of loopTuple1 = ('Geeks')n = 5print("\nTuple with a loop")for i in range(int(n)): Tuple1 = (Tuple1,) print(Tuple1) Output: Tuple with Mixed Datatypes: (5, 'Welcome', 7, 'Geeks') Tuple with nested tuples: ((0, 1, 2, 3), ('python', 'geek')) Tuple with repetition: ('Geeks', 'Geeks', 'Geeks') Tuple with a loop ('Geeks',) (('Geeks',),) ((('Geeks',),),) (((('Geeks',),),),) ((((('Geeks',),),),),) Time complexity: O(1) Auxiliary Space : O(n) Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list. Note: In unpacking of tuple number of variables on the left-hand side should be equal to a number of values in given tuple a. Python3 # Accessing Tuple# with IndexingTuple1 = tuple("Geeks")print("\nFirst element of Tuple: ")print(Tuple1[0]) # Tuple unpackingTuple1 = ("Geeks", "For", "Geeks") # This line unpack# values of Tuple1a, b, c = Tuple1print("\nValues after unpacking: ")print(a)print(b)print(c) Output: First element of Tuple: G Values after unpacking: Geeks For Geeks Time complexity: O(1) Space complexity: O(1) Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other arithmetic operations do not apply on Tuples. Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a tuple are combined. Python3 # Concatenation of tuplesTuple1 = (0, 1, 2, 3)Tuple2 = ('Geeks', 'For', 'Geeks') Tuple3 = Tuple1 + Tuple2 # Printing first Tupleprint("Tuple 1: ")print(Tuple1) # Printing Second Tupleprint("\nTuple2: ")print(Tuple2) # Printing Final Tupleprint("\nTuples after Concatenation: ")print(Tuple3) Output: Tuple 1: (0, 1, 2, 3) Tuple2: ('Geeks', 'For', 'Geeks') Tuples after Concatenation: (0, 1, 2, 3, 'Geeks', 'For', 'Geeks') Time Complexity: O(1) Auxiliary Space: O(1) Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to fetch a set of elements. Note- Negative Increment values can also be used to reverse the sequence of Tuples. Python3 # Slicing of a Tuple # Slicing of a Tuple# with NumbersTuple1 = tuple('GEEKSFORGEEKS') # Removing First elementprint("Removal of First Element: ")print(Tuple1[1:]) # Reversing the Tupleprint("\nTuple after sequence of Element is reversed: ")print(Tuple1[::-1]) # Printing elements of a Rangeprint("\nPrinting elements between Range 4-9: ")print(Tuple1[4:9]) Output: Removal of First Element: ('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S') Tuple after sequence of Element is reversed: ('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G') Printing elements between Range 4-9: ('S', 'F', 'O', 'R', 'G') Time complexity: O(1) Space complexity: O(1) Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets deleted by the use of del() method. Note- Printing of Tuple after deletion results in an Error. Python # Deleting a Tuple Tuple1 = (0, 1, 2, 3, 4)del Tuple1 print(Tuple1) Traceback (most recent call last): File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in print(Tuple1) NameError: name ‘Tuple1’ is not defined Functions that can be used for both lists and tuples: len(), max(), min(), sum(), any(), all(), sorted() Methods that cannot be used for tuples: append(), insert(), remove(), pop(), clear(), sort(), reverse() Methods that can be used for both lists and tuples: count(), Index() YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lv_Z6loukOs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Tuples Programs Print unique rows in a given boolean Strings Program to generate all possible valid IP addresses from given string Python Dictionary to find mirror characters in a string Generate two output strings depending upon occurrence of character in input string in Python Python groupby method to remove all consecutive duplicates Convert a list of characters into a string Remove empty tuples from a list Reversing a Tuple Python Set symmetric_difference() Convert a list of Tuples into Dictionary Sort a tuple by its float element Count occurrences of an element in a Tuple Count the elements in a list until an element is a Tuple Sort Tuples in Increasing Order by any key Namedtuple in Python Useful Links: Output of Python Programs Recent Articles on Python Tuples Multiple Choice Questions – Python All articles in Python Category nikhilaggarwal3 vishwajeet0524 sooda367 gabaa406 promitbodak santeswar python-tuple 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 206, "s": 52, "text": "Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. " }, { "code": null, "e": 440, "s": 206, "text": "Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. This helps in understanding the Python tuples more easily." }, { "code": null, "e": 594, "s": 440, "text": "In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping the data sequence." }, { "code": null, "e": 685, "s": 594, "text": "Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing. " }, { "code": null, "e": 693, "s": 685, "text": "Python3" }, { "code": "# Creating an empty TupleTuple1 = ()print(\"Initial empty Tuple: \")print(Tuple1) # Creating a Tuple# with the use of stringTuple1 = ('Geeks', 'For')print(\"\\nTuple with the use of String: \")print(Tuple1) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print(\"\\nTuple using List: \")print(tuple(list1)) # Creating a Tuple# with the use of built-in functionTuple1 = tuple('Geeks')print(\"\\nTuple with the use of function: \")print(Tuple1)", "e": 1140, "s": 693, "text": null }, { "code": null, "e": 1149, "s": 1140, "text": "Output: " }, { "code": null, "e": 1320, "s": 1149, "text": "Initial empty Tuple: \n()\n\nTuple with the use of String: \n('Geeks', 'For')\n\nTuple using List: \n(1, 2, 4, 5, 6)\n\nTuple with the use of function: \n('G', 'e', 'e', 'k', 's') " }, { "code": null, "e": 1605, "s": 1320, "text": "Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple. " }, { "code": null, "e": 1613, "s": 1605, "text": "Python3" }, { "code": "# Creating a Tuple# with Mixed DatatypeTuple1 = (5, 'Welcome', 7, 'Geeks')print(\"\\nTuple with Mixed Datatypes: \")print(Tuple1) # Creating a Tuple# with nested tuplesTuple1 = (0, 1, 2, 3)Tuple2 = ('python', 'geek')Tuple3 = (Tuple1, Tuple2)print(\"\\nTuple with nested tuples: \")print(Tuple3) # Creating a Tuple# with repetitionTuple1 = ('Geeks',) * 3print(\"\\nTuple with repetition: \")print(Tuple1) # Creating a Tuple# with the use of loopTuple1 = ('Geeks')n = 5print(\"\\nTuple with a loop\")for i in range(int(n)): Tuple1 = (Tuple1,) print(Tuple1)", "e": 2162, "s": 1613, "text": null }, { "code": null, "e": 2171, "s": 2162, "text": "Output: " }, { "code": null, "e": 2447, "s": 2171, "text": "Tuple with Mixed Datatypes: \n(5, 'Welcome', 7, 'Geeks')\n\nTuple with nested tuples: \n((0, 1, 2, 3), ('python', 'geek'))\n\nTuple with repetition: \n('Geeks', 'Geeks', 'Geeks')\n\nTuple with a loop\n('Geeks',)\n(('Geeks',),)\n((('Geeks',),),)\n(((('Geeks',),),),)\n((((('Geeks',),),),),)" }, { "code": null, "e": 2469, "s": 2447, "text": "Time complexity: O(1)" }, { "code": null, "e": 2492, "s": 2469, "text": "Auxiliary Space : O(n)" }, { "code": null, "e": 2780, "s": 2492, "text": "Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list." }, { "code": null, "e": 2907, "s": 2780, "text": "Note: In unpacking of tuple number of variables on the left-hand side should be equal to a number of values in given tuple a. " }, { "code": null, "e": 2915, "s": 2907, "text": "Python3" }, { "code": "# Accessing Tuple# with IndexingTuple1 = tuple(\"Geeks\")print(\"\\nFirst element of Tuple: \")print(Tuple1[0]) # Tuple unpackingTuple1 = (\"Geeks\", \"For\", \"Geeks\") # This line unpack# values of Tuple1a, b, c = Tuple1print(\"\\nValues after unpacking: \")print(a)print(b)print(c)", "e": 3187, "s": 2915, "text": null }, { "code": null, "e": 3196, "s": 3187, "text": "Output: " }, { "code": null, "e": 3265, "s": 3196, "text": "First element of Tuple: \nG\n\nValues after unpacking: \nGeeks\nFor\nGeeks" }, { "code": null, "e": 3287, "s": 3265, "text": "Time complexity: O(1)" }, { "code": null, "e": 3310, "s": 3287, "text": "Space complexity: O(1)" }, { "code": null, "e": 3557, "s": 3310, "text": "Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other arithmetic operations do not apply on Tuples. " }, { "code": null, "e": 3676, "s": 3557, "text": "Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a tuple are combined. " }, { "code": null, "e": 3684, "s": 3676, "text": "Python3" }, { "code": "# Concatenation of tuplesTuple1 = (0, 1, 2, 3)Tuple2 = ('Geeks', 'For', 'Geeks') Tuple3 = Tuple1 + Tuple2 # Printing first Tupleprint(\"Tuple 1: \")print(Tuple1) # Printing Second Tupleprint(\"\\nTuple2: \")print(Tuple2) # Printing Final Tupleprint(\"\\nTuples after Concatenation: \")print(Tuple3)", "e": 3975, "s": 3684, "text": null }, { "code": null, "e": 3984, "s": 3975, "text": "Output: " }, { "code": null, "e": 4111, "s": 3984, "text": "Tuple 1: \n(0, 1, 2, 3)\n\nTuple2: \n('Geeks', 'For', 'Geeks')\n\nTuples after Concatenation: \n(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')" }, { "code": null, "e": 4133, "s": 4111, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4155, "s": 4133, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4401, "s": 4155, "text": "Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to fetch a set of elements. " }, { "code": null, "e": 4486, "s": 4401, "text": "Note- Negative Increment values can also be used to reverse the sequence of Tuples. " }, { "code": null, "e": 4494, "s": 4486, "text": "Python3" }, { "code": "# Slicing of a Tuple # Slicing of a Tuple# with NumbersTuple1 = tuple('GEEKSFORGEEKS') # Removing First elementprint(\"Removal of First Element: \")print(Tuple1[1:]) # Reversing the Tupleprint(\"\\nTuple after sequence of Element is reversed: \")print(Tuple1[::-1]) # Printing elements of a Rangeprint(\"\\nPrinting elements between Range 4-9: \")print(Tuple1[4:9])", "e": 4852, "s": 4494, "text": null }, { "code": null, "e": 4861, "s": 4852, "text": "Output: " }, { "code": null, "e": 5127, "s": 4861, "text": "Removal of First Element: \n('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')\n\nTuple after sequence of Element is reversed: \n('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')\n\nPrinting elements between Range 4-9: \n('S', 'F', 'O', 'R', 'G')" }, { "code": null, "e": 5149, "s": 5127, "text": "Time complexity: O(1)" }, { "code": null, "e": 5172, "s": 5149, "text": "Space complexity: O(1)" }, { "code": null, "e": 5306, "s": 5172, "text": "Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets deleted by the use of del() method. " }, { "code": null, "e": 5367, "s": 5306, "text": "Note- Printing of Tuple after deletion results in an Error. " }, { "code": null, "e": 5374, "s": 5367, "text": "Python" }, { "code": "# Deleting a Tuple Tuple1 = (0, 1, 2, 3, 4)del Tuple1 print(Tuple1)", "e": 5442, "s": 5374, "text": null }, { "code": null, "e": 5592, "s": 5442, "text": "Traceback (most recent call last): File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in print(Tuple1) NameError: name ‘Tuple1’ is not defined" }, { "code": null, "e": 5646, "s": 5592, "text": "Functions that can be used for both lists and tuples:" }, { "code": null, "e": 5697, "s": 5646, "text": "len(), max(), min(), sum(), any(), all(), sorted()" }, { "code": null, "e": 5737, "s": 5697, "text": "Methods that cannot be used for tuples:" }, { "code": null, "e": 5801, "s": 5737, "text": "append(), insert(), remove(), pop(), clear(), sort(), reverse()" }, { "code": null, "e": 5853, "s": 5801, "text": "Methods that can be used for both lists and tuples:" }, { "code": null, "e": 5870, "s": 5853, "text": "count(), Index()" }, { "code": null, "e": 6162, "s": 5870, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=lv_Z6loukOs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 6178, "s": 6162, "text": "Tuples Programs" }, { "code": null, "e": 6223, "s": 6178, "text": "Print unique rows in a given boolean Strings" }, { "code": null, "e": 6293, "s": 6223, "text": "Program to generate all possible valid IP addresses from given string" }, { "code": null, "e": 6349, "s": 6293, "text": "Python Dictionary to find mirror characters in a string" }, { "code": null, "e": 6442, "s": 6349, "text": "Generate two output strings depending upon occurrence of character in input string in Python" }, { "code": null, "e": 6501, "s": 6442, "text": "Python groupby method to remove all consecutive duplicates" }, { "code": null, "e": 6544, "s": 6501, "text": "Convert a list of characters into a string" }, { "code": null, "e": 6576, "s": 6544, "text": "Remove empty tuples from a list" }, { "code": null, "e": 6594, "s": 6576, "text": "Reversing a Tuple" }, { "code": null, "e": 6628, "s": 6594, "text": "Python Set symmetric_difference()" }, { "code": null, "e": 6669, "s": 6628, "text": "Convert a list of Tuples into Dictionary" }, { "code": null, "e": 6703, "s": 6669, "text": "Sort a tuple by its float element" }, { "code": null, "e": 6746, "s": 6703, "text": "Count occurrences of an element in a Tuple" }, { "code": null, "e": 6803, "s": 6746, "text": "Count the elements in a list until an element is a Tuple" }, { "code": null, "e": 6846, "s": 6803, "text": "Sort Tuples in Increasing Order by any key" }, { "code": null, "e": 6868, "s": 6846, "text": "Namedtuple in Python " }, { "code": null, "e": 6882, "s": 6868, "text": "Useful Links:" }, { "code": null, "e": 6908, "s": 6882, "text": "Output of Python Programs" }, { "code": null, "e": 6941, "s": 6908, "text": "Recent Articles on Python Tuples" }, { "code": null, "e": 6976, "s": 6941, "text": "Multiple Choice Questions – Python" }, { "code": null, "e": 7008, "s": 6976, "text": "All articles in Python Category" }, { "code": null, "e": 7024, "s": 7008, "text": "nikhilaggarwal3" }, { "code": null, "e": 7039, "s": 7024, "text": "vishwajeet0524" }, { "code": null, "e": 7048, "s": 7039, "text": "sooda367" }, { "code": null, "e": 7057, "s": 7048, "text": "gabaa406" }, { "code": null, "e": 7069, "s": 7057, "text": "promitbodak" }, { "code": null, "e": 7079, "s": 7069, "text": "santeswar" }, { "code": null, "e": 7092, "s": 7079, "text": "python-tuple" }, { "code": null, "e": 7099, "s": 7092, "text": "Python" }, { "code": null, "e": 7197, "s": 7099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7225, "s": 7197, "text": "Read JSON file using Python" }, { "code": null, "e": 7275, "s": 7225, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7297, "s": 7275, "text": "Python map() function" }, { "code": null, "e": 7341, "s": 7297, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 7383, "s": 7341, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7405, "s": 7383, "text": "Enumerate() in Python" }, { "code": null, "e": 7440, "s": 7405, "text": "Read a file line by line in Python" }, { "code": null, "e": 7472, "s": 7440, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7498, "s": 7472, "text": "Python String | replace()" } ]
Pandas | Parsing JSON Dataset
27 Mar, 2019 Parsing of JSON Dataset using pandas is much more convenient. Pandas allow you to convert a list of lists into a Dataframe and specify the column names separately. A JSON parser transforms a JSON text into another representation must accept all texts that conform to the JSON grammar. It may accept non-JSON forms or extensions. An implementation may set the following: limits on the size of texts that it accepts, limits on the maximum depth of nesting, limits on the range and precision of numbers, set limits on the length and character contents of strings. Working with large JSON datasets can be deteriorating, particularly when they are too large to fit into memory. In cases like this, a combination of command line tools and Python can make for an efficient way to explore and analyze the data. Importing JSON Files: Manipulating the JSON is done using the Python Data Analysis Library, called pandas. import pandas as pd Now you can read the JSON and save it as a pandas data structure, using the command read_json. pandas.read_json (path_or_buf=None, orient = None, typ=’frame’, dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression=’infer’) import pandas as pd# Creating Dataframe df = pd.DataFrame([['a', 'b'], ['c', 'd']], index =['row 1', 'row 2'], columns =['col 1', 'col 2']) # Indication of expected JSON string formatprint(df.to_json(orient ='split')) print(df.to_json(orient ='index')) {"columns":["col 1", "col 2"], "index":["row 1", "row 2"], "data":[["a", "b"], ["c", "d"]]} {"row 1":{"col 1":"a", "col 2":"b"}, "row 2":{"col 1":"c", "col 2":"d"}} Convert the object to a JSON string using dataframe.to_json: DataFrame.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True) Read the JSON File directly from Dataset: import pandas as pd data = pd.read_json('http://api.population.io/1.0/population/India/today-and-tomorrow/?format = json')print(data) total_population 0 {'date': '2019-03-18', 'population': 1369169250} 1 {'date': '2019-03-19', 'population': 1369211502} Nested JSON Parsing with Pandas: Nested JSON files can be time consuming and difficult process to flatten and load into Pandas.We are using nested ”’raw_nyc_phil.json.”’ to create a flattened pandas data frame from one nested array then unpack a deeply nested array. Code #1:Let’s unpack the works column into a standalone dataframe. We’ll also grab the flat columns. import json import pandas as pd from pandas.io.json import json_normalize with open('https://github.com/a9k00r/python-test/blob/master/raw_nyc_phil.json') as f: d = json.load(f) # lets put the data into a pandas df# clicking on raw_nyc_phil.json under "Input Files"# tells us parent node is 'programs'nycphil = json_normalize(d['programs'])nycphil.head(3) Output: Code #2:Let’s unpack the works column into a standalone dataframe using json_normaliz. works_data = json_normalize(data = d['programs'], record_path ='works', meta =['id', 'orchestra', 'programID', 'season'])works_data.head(3) Output: Code #3: Let’s flatten the ‘soloists’ data here by passing a list. Since soloists is nested in work. soloist_data = json_normalize(data = d['programs'], record_path =['works', 'soloists'], meta =['id']) soloist_data.head(3) Output: Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Mar, 2019" }, { "code": null, "e": 216, "s": 52, "text": "Parsing of JSON Dataset using pandas is much more convenient. Pandas allow you to convert a list of lists into a Dataframe and specify the column names separately." }, { "code": null, "e": 422, "s": 216, "text": "A JSON parser transforms a JSON text into another representation must accept all texts that conform to the JSON grammar. It may accept non-JSON forms or extensions. An implementation may set the following:" }, { "code": null, "e": 467, "s": 422, "text": "limits on the size of texts that it accepts," }, { "code": null, "e": 507, "s": 467, "text": "limits on the maximum depth of nesting," }, { "code": null, "e": 553, "s": 507, "text": "limits on the range and precision of numbers," }, { "code": null, "e": 613, "s": 553, "text": "set limits on the length and character contents of strings." }, { "code": null, "e": 855, "s": 613, "text": "Working with large JSON datasets can be deteriorating, particularly when they are too large to fit into memory. In cases like this, a combination of command line tools and Python can make for an efficient way to explore and analyze the data." }, { "code": null, "e": 877, "s": 855, "text": "Importing JSON Files:" }, { "code": null, "e": 962, "s": 877, "text": "Manipulating the JSON is done using the Python Data Analysis Library, called pandas." }, { "code": null, "e": 982, "s": 962, "text": "import pandas as pd" }, { "code": null, "e": 1077, "s": 982, "text": "Now you can read the JSON and save it as a pandas data structure, using the command read_json." }, { "code": null, "e": 1332, "s": 1077, "text": "pandas.read_json (path_or_buf=None, orient = None, typ=’frame’, dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression=’infer’)" }, { "code": "import pandas as pd# Creating Dataframe df = pd.DataFrame([['a', 'b'], ['c', 'd']], index =['row 1', 'row 2'], columns =['col 1', 'col 2']) # Indication of expected JSON string formatprint(df.to_json(orient ='split')) print(df.to_json(orient ='index'))", "e": 1621, "s": 1332, "text": null }, { "code": null, "e": 1791, "s": 1621, "text": "{\"columns\":[\"col 1\", \"col 2\"],\n \"index\":[\"row 1\", \"row 2\"],\n \"data\":[[\"a\", \"b\"], [\"c\", \"d\"]]}\n\n{\"row 1\":{\"col 1\":\"a\", \"col 2\":\"b\"},\n \"row 2\":{\"col 1\":\"c\", \"col 2\":\"d\"}}\n" }, { "code": null, "e": 1853, "s": 1791, "text": " Convert the object to a JSON string using dataframe.to_json:" }, { "code": null, "e": 2043, "s": 1853, "text": "DataFrame.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)" }, { "code": null, "e": 2085, "s": 2043, "text": "Read the JSON File directly from Dataset:" }, { "code": "import pandas as pd data = pd.read_json('http://api.population.io/1.0/population/India/today-and-tomorrow/?format = json')print(data)", "e": 2220, "s": 2085, "text": null }, { "code": null, "e": 2342, "s": 2220, "text": "total_population\n0 {'date': '2019-03-18', 'population': 1369169250}\n1 {'date': '2019-03-19', 'population': 1369211502}\n" }, { "code": null, "e": 2375, "s": 2342, "text": "Nested JSON Parsing with Pandas:" }, { "code": null, "e": 2609, "s": 2375, "text": "Nested JSON files can be time consuming and difficult process to flatten and load into Pandas.We are using nested ”’raw_nyc_phil.json.”’ to create a flattened pandas data frame from one nested array then unpack a deeply nested array." }, { "code": null, "e": 2710, "s": 2609, "text": "Code #1:Let’s unpack the works column into a standalone dataframe. We’ll also grab the flat columns." }, { "code": "import json import pandas as pd from pandas.io.json import json_normalize with open('https://github.com/a9k00r/python-test/blob/master/raw_nyc_phil.json') as f: d = json.load(f) # lets put the data into a pandas df# clicking on raw_nyc_phil.json under \"Input Files\"# tells us parent node is 'programs'nycphil = json_normalize(d['programs'])nycphil.head(3)", "e": 3072, "s": 2710, "text": null }, { "code": null, "e": 3080, "s": 3072, "text": "Output:" }, { "code": null, "e": 3167, "s": 3080, "text": "Code #2:Let’s unpack the works column into a standalone dataframe using json_normaliz." }, { "code": "works_data = json_normalize(data = d['programs'], record_path ='works', meta =['id', 'orchestra', 'programID', 'season'])works_data.head(3)", "e": 3362, "s": 3167, "text": null }, { "code": null, "e": 3370, "s": 3362, "text": "Output:" }, { "code": null, "e": 3379, "s": 3370, "text": "Code #3:" }, { "code": null, "e": 3471, "s": 3379, "text": "Let’s flatten the ‘soloists’ data here by passing a list. Since soloists is nested in work." }, { "code": "soloist_data = json_normalize(data = d['programs'], record_path =['works', 'soloists'], meta =['id']) soloist_data.head(3)", "e": 3653, "s": 3471, "text": null }, { "code": null, "e": 3661, "s": 3653, "text": "Output:" }, { "code": null, "e": 3675, "s": 3661, "text": "Python-pandas" }, { "code": null, "e": 3682, "s": 3675, "text": "Python" } ]
Software Engineering | The Make-Buy Decision or Decision Table
02 Sep, 2021 A decision table is a brief visual representation for specifying which actions to perform depending on given conditions. The information represented in decision tables can also be represented as decision trees or in a programming language using if-then-else and switch-case statements. A decision table is a good way to settle with different combination inputs with their corresponding outputs and is also called a cause-effect table. The reason to call cause-effect table is a related logical diagramming technique called cause-effect graphing that is basically used to obtain the decision table. Importance of Decision Table: Decision tables are very much helpful in test design techniques. It helps testers to search the effects of combinations of different inputs and other software states that must correctly implement business rules. It provides a regular way of starting complex business rules, that is helpful for developers as well as for testers. It assists in the development process with the developer to do a better job. Testing with all combinations might be impractical. A decision table is basically an outstanding technique used in both testing and requirements management. It is a structured exercise to prepare requirements when dealing with complex business rules. It is also used in model complicated logic. CONDITIONS STEP 1 STEP 2 STEP 3 STEP 4 Condition 1 Condition 2 Condition 3 Condition 4 Decision Table: Combinations CONDITIONS STEP 1 STEP 2 STEP 3 STEP 4 Condition 1 Y Y N N Condition 2 Y N Y N Condition 3 Y N N Y Condition 4 N Y Y N Advantage of Decision Table: Any complex business flow can be easily converted into test scenarios & test cases using this technique. Decision tables work iteratively which means the table created at the first iteration is used as input tables for the next tables. The iteration is done only if the initial table is not satisfactory. Simple to understand and everyone can use this method to design the test scenarios & test cases. It provides complete coverage of test cases which helps to reduce the rework on writing test scenarios & test cases. These tables guarantee that we consider every possible combination of condition values. This is known as its completeness property. varshachoudhary rajeev0719singh Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2021" }, { "code": null, "e": 339, "s": 52, "text": "A decision table is a brief visual representation for specifying which actions to perform depending on given conditions. The information represented in decision tables can also be represented as decision trees or in a programming language using if-then-else and switch-case statements. " }, { "code": null, "e": 652, "s": 339, "text": "A decision table is a good way to settle with different combination inputs with their corresponding outputs and is also called a cause-effect table. The reason to call cause-effect table is a related logical diagramming technique called cause-effect graphing that is basically used to obtain the decision table. " }, { "code": null, "e": 682, "s": 652, "text": "Importance of Decision Table:" }, { "code": null, "e": 747, "s": 682, "text": "Decision tables are very much helpful in test design techniques." }, { "code": null, "e": 894, "s": 747, "text": "It helps testers to search the effects of combinations of different inputs and other software states that must correctly implement business rules." }, { "code": null, "e": 1011, "s": 894, "text": "It provides a regular way of starting complex business rules, that is helpful for developers as well as for testers." }, { "code": null, "e": 1140, "s": 1011, "text": "It assists in the development process with the developer to do a better job. Testing with all combinations might be impractical." }, { "code": null, "e": 1245, "s": 1140, "text": "A decision table is basically an outstanding technique used in both testing and requirements management." }, { "code": null, "e": 1339, "s": 1245, "text": "It is a structured exercise to prepare requirements when dealing with complex business rules." }, { "code": null, "e": 1383, "s": 1339, "text": "It is also used in model complicated logic." }, { "code": null, "e": 1546, "s": 1383, "text": "CONDITIONS STEP 1 STEP 2 STEP 3 STEP 4\nCondition 1 \nCondition 2 \nCondition 3 \nCondition 4 " }, { "code": null, "e": 1576, "s": 1546, "text": "Decision Table: Combinations " }, { "code": null, "e": 1823, "s": 1576, "text": "CONDITIONS STEP 1 STEP 2 STEP 3 STEP 4\nCondition 1 Y Y N N\nCondition 2 Y N Y N\nCondition 3 Y N N Y\nCondition 4 N Y Y N" }, { "code": null, "e": 1854, "s": 1823, "text": "Advantage of Decision Table: " }, { "code": null, "e": 1959, "s": 1854, "text": "Any complex business flow can be easily converted into test scenarios & test cases using this technique." }, { "code": null, "e": 2159, "s": 1959, "text": "Decision tables work iteratively which means the table created at the first iteration is used as input tables for the next tables. The iteration is done only if the initial table is not satisfactory." }, { "code": null, "e": 2256, "s": 2159, "text": "Simple to understand and everyone can use this method to design the test scenarios & test cases." }, { "code": null, "e": 2373, "s": 2256, "text": "It provides complete coverage of test cases which helps to reduce the rework on writing test scenarios & test cases." }, { "code": null, "e": 2505, "s": 2373, "text": "These tables guarantee that we consider every possible combination of condition values. This is known as its completeness property." }, { "code": null, "e": 2523, "s": 2507, "text": "varshachoudhary" }, { "code": null, "e": 2539, "s": 2523, "text": "rajeev0719singh" }, { "code": null, "e": 2560, "s": 2539, "text": "Software Engineering" } ]
Connection Between Eigenvectors and Nullspace
04 May, 2020 Prerequisites: Eigenvectors Nullspace Some important points about eigenvalues and eigenvectors: Eigenvalues can be complex numbers even for real matrices. When eigenvalues become complex, eigenvectors also become complex. If the matrix is symmetric (e.g A = AT), then the eigenvalues are always real. As a result, eigenvectors of symmetric matrices are also real. There will always be n linearly independent eigenvectors for symmetric matrices. Now, let’s discuss the connection between eigenvectors and nullspace. From this article we show that AX = λX Now let me ask you a question. What happens when lambda is 0? That is one of the eigenvalues becomes 0.So, when one of the eigenvalues becomes 0, then we have this equation which is given by AX = 0 —(equation 1) From this article we show that AB = 0 —(equation 2) So you notice that equation 1 and equation 2 form are the same. So, that basically means that X which is an eigenvector corresponding to eigenvalue, lambda equals to 0, is a null space vector, because it is just of the form that we have noticed here. So, we could say, the eigenvectors corresponding to zero eigenvalues are in the null space of the original matrix A. Conversely, if the eigenvalue corresponding to an eigenvector is not 0, then that eigenvector can not be in the null space of A. So, these are important results that we need to know.So, this is how eigenvectors are connected to nullspace. Example:Consider the following A matrixNotice that this is a symmetric matrix hence the eigenvalues are always real as I told before in the important points section.The eigenvalues for this matrix are λ = (0, 1, 2) The eigenvectors corresponding to these eigenvalues are Code: Python code to calculate eigenvalue and eigenvector # Python program to illustrate# connection between eigenvectors and nullspace # Importing required librariesimport numpy as npfrom numpy import linalg # Taking A matrixA = np.array([ [0.36, 0.48, 0], [0.48, 0.64, 0], [0, 0, 2]]) # Calculating eigenvalues and eigenvectorseigValues, eigVectors = linalg.eig(A) # Printing those valuesprint("Eigenvalue are :", eigValues)print("Eigenvectors are :", eigVectors) # Taking eigenvector 1eigVector1 = np.array([ [-0.8], [0.6], [0]]) # Matrix multiplication between A and eigenvector1result = np.dot(A, eigVector1)# Print the resultprint(result) # This code is contributed by Amiya Rout Output: Eigenvalue are : [0. 1. 2.] Eigenvectors are : [[-0.8 -0.6 0. ] [ 0.6 -0.8 0. ] [ 0. 0. 1. ]] [[0.] [0.] [0.]] So we have noticed from our discussion before that if X1 is an eigenvector corresponding to lambda equal to 0, then this is going to be in the null space of this matrix A. Let’s verify it by multiplying A with X1. We check thatYou can quite easily see that when you do this computation, you will get this (0, 0, 0), which basically shows that this is the eigenvector corresponding to zero eigenvalue. Engineering Mathematics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n04 May, 2020" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisites:" }, { "code": null, "e": 56, "s": 43, "text": "Eigenvectors" }, { "code": null, "e": 66, "s": 56, "text": "Nullspace" }, { "code": null, "e": 124, "s": 66, "text": "Some important points about eigenvalues and eigenvectors:" }, { "code": null, "e": 183, "s": 124, "text": "Eigenvalues can be complex numbers even for real matrices." }, { "code": null, "e": 250, "s": 183, "text": "When eigenvalues become complex, eigenvectors also become complex." }, { "code": null, "e": 329, "s": 250, "text": "If the matrix is symmetric (e.g A = AT), then the eigenvalues are always real." }, { "code": null, "e": 392, "s": 329, "text": "As a result, eigenvectors of symmetric matrices are also real." }, { "code": null, "e": 473, "s": 392, "text": "There will always be n linearly independent eigenvectors for symmetric matrices." }, { "code": null, "e": 543, "s": 473, "text": "Now, let’s discuss the connection between eigenvectors and nullspace." }, { "code": null, "e": 574, "s": 543, "text": "From this article we show that" }, { "code": null, "e": 582, "s": 574, "text": "AX = λX" }, { "code": null, "e": 773, "s": 582, "text": "Now let me ask you a question. What happens when lambda is 0? That is one of the eigenvalues becomes 0.So, when one of the eigenvalues becomes 0, then we have this equation which is given by" }, { "code": null, "e": 794, "s": 773, "text": "AX = 0 —(equation 1)" }, { "code": null, "e": 825, "s": 794, "text": "From this article we show that" }, { "code": null, "e": 846, "s": 825, "text": "AB = 0 —(equation 2)" }, { "code": null, "e": 910, "s": 846, "text": "So you notice that equation 1 and equation 2 form are the same." }, { "code": null, "e": 1453, "s": 910, "text": "So, that basically means that X which is an eigenvector corresponding to eigenvalue, lambda equals to 0, is a null space vector, because it is just of the form that we have noticed here. So, we could say, the eigenvectors corresponding to zero eigenvalues are in the null space of the original matrix A. Conversely, if the eigenvalue corresponding to an eigenvector is not 0, then that eigenvector can not be in the null space of A. So, these are important results that we need to know.So, this is how eigenvectors are connected to nullspace." }, { "code": null, "e": 1654, "s": 1453, "text": "Example:Consider the following A matrixNotice that this is a symmetric matrix hence the eigenvalues are always real as I told before in the important points section.The eigenvalues for this matrix are" }, { "code": null, "e": 1668, "s": 1654, "text": "λ = (0, 1, 2)" }, { "code": null, "e": 1724, "s": 1668, "text": "The eigenvectors corresponding to these eigenvalues are" }, { "code": null, "e": 1782, "s": 1724, "text": "Code: Python code to calculate eigenvalue and eigenvector" }, { "code": "# Python program to illustrate# connection between eigenvectors and nullspace # Importing required librariesimport numpy as npfrom numpy import linalg # Taking A matrixA = np.array([ [0.36, 0.48, 0], [0.48, 0.64, 0], [0, 0, 2]]) # Calculating eigenvalues and eigenvectorseigValues, eigVectors = linalg.eig(A) # Printing those valuesprint(\"Eigenvalue are :\", eigValues)print(\"Eigenvectors are :\", eigVectors) # Taking eigenvector 1eigVector1 = np.array([ [-0.8], [0.6], [0]]) # Matrix multiplication between A and eigenvector1result = np.dot(A, eigVector1)# Print the resultprint(result) # This code is contributed by Amiya Rout", "e": 2435, "s": 1782, "text": null }, { "code": null, "e": 2566, "s": 2435, "text": "Output:\nEigenvalue are : [0. 1. 2.]\nEigenvectors are : \n[[-0.8 -0.6 0. ]\n [ 0.6 -0.8 0. ]\n [ 0. 0. 1. ]]\n[[0.]\n [0.]\n [0.]]\n" }, { "code": null, "e": 2967, "s": 2566, "text": "So we have noticed from our discussion before that if X1 is an eigenvector corresponding to lambda equal to 0, then this is going to be in the null space of this matrix A. Let’s verify it by multiplying A with X1. We check thatYou can quite easily see that when you do this computation, you will get this (0, 0, 0), which basically shows that this is the eigenvector corresponding to zero eigenvalue." }, { "code": null, "e": 2991, "s": 2967, "text": "Engineering Mathematics" }, { "code": null, "e": 2998, "s": 2991, "text": "Python" }, { "code": null, "e": 3096, "s": 2998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3155, "s": 3096, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 3178, "s": 3155, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 3201, "s": 3178, "text": "Set Notations in LaTeX" }, { "code": null, "e": 3222, "s": 3201, "text": "Activation Functions" }, { "code": null, "e": 3287, "s": 3222, "text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph" }, { "code": null, "e": 3315, "s": 3287, "text": "Read JSON file using Python" }, { "code": null, "e": 3365, "s": 3315, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3387, "s": 3365, "text": "Python map() function" }, { "code": null, "e": 3405, "s": 3387, "text": "Python Dictionary" } ]
ReactJS Reactstrap Popover Component
22 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Popover component is a container-type element that hovers over the parent window. We can use the following approach in ReactJS to use the ReactJS Reactstrap Popover Component. Popover Props: children: It is used to pass the children element to this component. trigger: It is used to denote a space-separated list of triggers. isOpen: It is used to indicate whether to open popover or not. toggle: It is a callback function for toggling isOpen in the controlling component. boundariesElement: It is used to denote the boundaries for a popper. container: It is used to indicate where to inject the popper DOM node. className: It is used to denote the class name for styling. popperClassName: It is used to apply a class to the popper component. innerClassName: It is used to apply a class to the inner-popover. disabled: It is used to indicate whether the component is disabled or not. hideArrow: It is used to indicate whether to hide an arrow or not. placementPrefix: It is used to denote the placement prefix class like bs-popover, etc. delay: It is used to denote the delay value. placement: It is used for the placement of the popover. modifiers: It is used to denote a custom modifier that is passed to Popper.js positionFixed: It is used to indicate whether the popover pointing element has position: fixed styling or not. offset: It is used to denote offset element. fade: It is used to indicate whether to show/hide the popover with a fade effect. flip: It is used to indicate whether to flip the direction of the popover if too close to the container edge. 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 required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here we have shown Popover with a header component and the placement of popover is at the bottom position. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Popover, PopoverHeader, PopoverBody } from "reactstrap" function App() { // Popover open state const [popoverOpen, setPopoverOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Popover Component</h4> <Button id="Popover1" type="button"> Click me to Open Popover </Button> <br></br> <Popover placement="bottom" isOpen={popoverOpen} target="Popover1" toggle= {() => { setPopoverOpen(!popoverOpen) }}> <PopoverHeader>Sample Popover Title</PopoverHeader> <PopoverBody>Sample Body Text to display...</PopoverBody> </Popover> </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: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here we have shown Popover without a header component and the placement of popover is at the right position. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Popover, PopoverBody } from "reactstrap" function App() { // Popover open state const [popoverOpen, setPopoverOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Popover Component</h4> <Button id="Popover" color="primary"> Click to Open Popover </Button> <br></br> <Popover placement="right" isOpen={popoverOpen} target="Popover" toggle= {() => { setPopoverOpen(!popoverOpen) }}> <PopoverBody>Sample Body Text to display...</PopoverBody> </Popover> </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: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/popovers/ Reactstrap 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request 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": "\n22 Jul, 2021" }, { "code": null, "e": 370, "s": 28, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Popover component is a container-type element that hovers over the parent window. We can use the following approach in ReactJS to use the ReactJS Reactstrap Popover Component." }, { "code": null, "e": 385, "s": 370, "text": "Popover Props:" }, { "code": null, "e": 454, "s": 385, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 520, "s": 454, "text": "trigger: It is used to denote a space-separated list of triggers." }, { "code": null, "e": 583, "s": 520, "text": "isOpen: It is used to indicate whether to open popover or not." }, { "code": null, "e": 667, "s": 583, "text": "toggle: It is a callback function for toggling isOpen in the controlling component." }, { "code": null, "e": 736, "s": 667, "text": "boundariesElement: It is used to denote the boundaries for a popper." }, { "code": null, "e": 807, "s": 736, "text": "container: It is used to indicate where to inject the popper DOM node." }, { "code": null, "e": 867, "s": 807, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 937, "s": 867, "text": "popperClassName: It is used to apply a class to the popper component." }, { "code": null, "e": 1003, "s": 937, "text": "innerClassName: It is used to apply a class to the inner-popover." }, { "code": null, "e": 1078, "s": 1003, "text": "disabled: It is used to indicate whether the component is disabled or not." }, { "code": null, "e": 1147, "s": 1078, "text": "hideArrow: It is used to indicate whether to hide an arrow or not. " }, { "code": null, "e": 1234, "s": 1147, "text": "placementPrefix: It is used to denote the placement prefix class like bs-popover, etc." }, { "code": null, "e": 1279, "s": 1234, "text": "delay: It is used to denote the delay value." }, { "code": null, "e": 1335, "s": 1279, "text": "placement: It is used for the placement of the popover." }, { "code": null, "e": 1413, "s": 1335, "text": "modifiers: It is used to denote a custom modifier that is passed to Popper.js" }, { "code": null, "e": 1524, "s": 1413, "text": "positionFixed: It is used to indicate whether the popover pointing element has position: fixed styling or not." }, { "code": null, "e": 1569, "s": 1524, "text": "offset: It is used to denote offset element." }, { "code": null, "e": 1651, "s": 1569, "text": "fade: It is used to indicate whether to show/hide the popover with a fade effect." }, { "code": null, "e": 1761, "s": 1651, "text": "flip: It is used to indicate whether to flip the direction of the popover if too close to the container edge." }, { "code": null, "e": 1811, "s": 1761, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1875, "s": 1811, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1907, "s": 1875, "text": "npx create-react-app foldername" }, { "code": null, "e": 2009, "s": 1909, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 2023, "s": 2009, "text": "cd foldername" }, { "code": null, "e": 2128, "s": 2023, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 2161, "s": 2128, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 2213, "s": 2161, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2231, "s": 2213, "text": "Project Structure" }, { "code": null, "e": 2403, "s": 2231, "text": "Example 1: Now write down the following code in the App.js file. Here we have shown Popover with a header component and the placement of popover is at the bottom position." }, { "code": null, "e": 2414, "s": 2403, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Popover, PopoverHeader, PopoverBody } from \"reactstrap\" function App() { // Popover open state const [popoverOpen, setPopoverOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Popover Component</h4> <Button id=\"Popover1\" type=\"button\"> Click me to Open Popover </Button> <br></br> <Popover placement=\"bottom\" isOpen={popoverOpen} target=\"Popover1\" toggle= {() => { setPopoverOpen(!popoverOpen) }}> <PopoverHeader>Sample Popover Title</PopoverHeader> <PopoverBody>Sample Body Text to display...</PopoverBody> </Popover> </div > );} export default App;", "e": 3324, "s": 2414, "text": null }, { "code": null, "e": 3437, "s": 3324, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3447, "s": 3437, "text": "npm start" }, { "code": null, "e": 3546, "s": 3447, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3720, "s": 3546, "text": "Example 2: Now write down the following code in the App.js file. Here we have shown Popover without a header component and the placement of popover is at the right position." }, { "code": null, "e": 3731, "s": 3720, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Popover, PopoverBody } from \"reactstrap\" function App() { // Popover open state const [popoverOpen, setPopoverOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Popover Component</h4> <Button id=\"Popover\" color=\"primary\"> Click to Open Popover </Button> <br></br> <Popover placement=\"right\" isOpen={popoverOpen} target=\"Popover\" toggle= {() => { setPopoverOpen(!popoverOpen) }}> <PopoverBody>Sample Body Text to display...</PopoverBody> </Popover> </div > );} export default App;", "e": 4555, "s": 3731, "text": null }, { "code": null, "e": 4668, "s": 4555, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4678, "s": 4668, "text": "npm start" }, { "code": null, "e": 4777, "s": 4678, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4838, "s": 4777, "text": "Reference: https://reactstrap.github.io/components/popovers/" }, { "code": null, "e": 4849, "s": 4838, "text": "Reactstrap" }, { "code": null, "e": 4860, "s": 4849, "text": "JavaScript" }, { "code": null, "e": 4868, "s": 4860, "text": "ReactJS" }, { "code": null, "e": 4885, "s": 4868, "text": "Web Technologies" }, { "code": null, "e": 4983, "s": 4885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5044, "s": 4983, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5116, "s": 5044, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5156, "s": 5116, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5198, "s": 5156, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5239, "s": 5198, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5282, "s": 5239, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 5327, "s": 5282, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 5365, "s": 5327, "text": "Axios in React: A Guide for Beginners" } ]
How to animate a Progress Bar in Bootstrap ?
10 Aug, 2021 The Bootstrap Progress Bar is a component of the bootstrap framework used to display the progress of a process. We can customize the bootstrap progress bar, color, shape, and animation as per the requirements. Bootstrap also provides several types of progress bars. Using Progress Bar, users can easily know the status of work done for a particular process. For example, if a user is downloading a file, the progress bar can be used to show the progress of the ongoing download, the same is the case for uploading and etc. Step By Step Guide to Animate Progress Bar Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> Step 2: Add a HTML <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped. Inside the <div> add an empty <div> with a class of .progress-bar and .progress-bar-success. Using CSS attribute specify the width for progress bar. <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" style="width:0%"> </div> </div> Step 3: Add jQuery in <script> tag to animate progress bar to show progress. $(".progress-bar").animate({ width: "70%" }, 2500); Example: HTML <!DOCTYPE html><html> <head> <title>Bootstrap Progress Bar Animation Example</title> <!--Include Latest compiled and minified CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head> <body> <br><br> <!--Include bootstrap progress bar in div. Also specify width as 0% using CSS --> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 0%"> </div> </div> <script> // Set the width to animate the progress bar // Along with time duration in milliseconds $(".progress-bar").animate({ width: "70%", }, 2500); </script></body> </html> Output: Bootstrap-4 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? 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
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Aug, 2021" }, { "code": null, "e": 294, "s": 28, "text": "The Bootstrap Progress Bar is a component of the bootstrap framework used to display the progress of a process. We can customize the bootstrap progress bar, color, shape, and animation as per the requirements. Bootstrap also provides several types of progress bars." }, { "code": null, "e": 551, "s": 294, "text": "Using Progress Bar, users can easily know the status of work done for a particular process. For example, if a user is downloading a file, the progress bar can be used to show the progress of the ongoing download, the same is the case for uploading and etc." }, { "code": null, "e": 594, "s": 551, "text": "Step By Step Guide to Animate Progress Bar" }, { "code": null, "e": 701, "s": 594, "text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 1080, "s": 703, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>" }, { "code": null, "e": 1349, "s": 1080, "text": "Step 2: Add a HTML <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped. Inside the <div> add an empty <div> with a class of .progress-bar and .progress-bar-success. Using CSS attribute specify the width for progress bar. " }, { "code": null, "e": 1491, "s": 1349, "text": "<div class=\"progress progress-striped active\">\n <div class=\"progress-bar progress-bar-success\"\n style=\"width:0%\">\n </div>\n</div>" }, { "code": null, "e": 1568, "s": 1491, "text": "Step 3: Add jQuery in <script> tag to animate progress bar to show progress." }, { "code": null, "e": 1624, "s": 1568, "text": "$(\".progress-bar\").animate({\n width: \"70%\"\n}, 2500);" }, { "code": null, "e": 1633, "s": 1624, "text": "Example:" }, { "code": null, "e": 1638, "s": 1633, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Progress Bar Animation Example</title> <!--Include Latest compiled and minified CSS --> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" rel=\"stylesheet\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script></head> <body> <br><br> <!--Include bootstrap progress bar in div. Also specify width as 0% using CSS --> <div class=\"progress progress-striped active\"> <div class=\"progress-bar progress-bar-success\" style=\"width: 0%\"> </div> </div> <script> // Set the width to animate the progress bar // Along with time duration in milliseconds $(\".progress-bar\").animate({ width: \"70%\", }, 2500); </script></body> </html>", "e": 2705, "s": 1638, "text": null }, { "code": null, "e": 2713, "s": 2705, "text": "Output:" }, { "code": null, "e": 2725, "s": 2713, "text": "Bootstrap-4" }, { "code": null, "e": 2745, "s": 2725, "text": "Bootstrap-Questions" }, { "code": null, "e": 2752, "s": 2745, "text": "Picked" }, { "code": null, "e": 2762, "s": 2752, "text": "Bootstrap" }, { "code": null, "e": 2767, "s": 2762, "text": "HTML" }, { "code": null, "e": 2784, "s": 2767, "text": "Web Technologies" }, { "code": null, "e": 2789, "s": 2784, "text": "HTML" }, { "code": null, "e": 2887, "s": 2789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2928, "s": 2887, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 2961, "s": 2928, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 3006, "s": 2961, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 3032, "s": 3006, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 3099, "s": 3032, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 3147, "s": 3099, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3209, "s": 3147, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3259, "s": 3209, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3283, "s": 3259, "text": "REST API (Introduction)" } ]
Merge two sorted arrays in Python using heapq?
In this section we will see how two sorted lists can be merged using the heapq module in Python. As an example, if list1 = [10, 20, 30, 40] and list2 = [100, 200, 300, 400, 500], then after merging it will return list3 = [10, 20, 30, 40, 100, 200, 300, 400, 500] To perform this task, we will use the heapq module. This module comes with Python as Standard Library Module. So we need to import it before using it. import heapq The heapq module has some properties. These are like below − Method heapq.heapify(iterable) It is used to convert an iterable dataset to heap data structure. Method heapq.heappush(heap, element) This method is used to insert the element into the heap. After that re-heap the entire heap structure. Method heapq.heappop(heap) This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements. Method heapq.heappushpop(heap, element) This method is used to insert and pop element in one statement. Method heapq.heapreplace(heap, element) This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap. Method heapq.nlargest(n, iterable, key=None) This method is used to return n largest element from the heap. Method heapq.nsmallest(n, iterable, key=None) This method is used to return n smallest element from the heap. Live Demo import heapq first_list = [45, 12, 63, 95, 74, 21, 20, 15, 36] second_list = [42, 13, 69, 54, 15] first_list = sorted(first_list) second_list = sorted(second_list) print('First sorted list: ' + str(first_list)) print('Second sorted list: ' + str(second_list)) final_list = list(heapq.merge(first_list, second_list)) print('The final list: ' + str(final_list)) First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95] Second sorted list: [13, 15, 42, 54, 69] The final list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]
[ { "code": null, "e": 1450, "s": 1187, "text": "In this section we will see how two sorted lists can be merged using the heapq module in Python. As an example, if list1 = [10, 20, 30, 40] and list2 = [100, 200, 300, 400, 500], then after merging it will return list3 = [10, 20, 30, 40, 100, 200, 300, 400, 500]" }, { "code": null, "e": 1601, "s": 1450, "text": "To perform this task, we will use the heapq module. This module comes with Python as Standard Library Module. So we need to import it before using it." }, { "code": null, "e": 1614, "s": 1601, "text": "import heapq" }, { "code": null, "e": 1675, "s": 1614, "text": "The heapq module has some properties. These are like below −" }, { "code": null, "e": 1706, "s": 1675, "text": "Method heapq.heapify(iterable)" }, { "code": null, "e": 1772, "s": 1706, "text": "It is used to convert an iterable dataset to heap data structure." }, { "code": null, "e": 1809, "s": 1772, "text": "Method heapq.heappush(heap, element)" }, { "code": null, "e": 1912, "s": 1809, "text": "This method is used to insert the element into the heap. After that re-heap the entire heap structure." }, { "code": null, "e": 1939, "s": 1912, "text": "Method heapq.heappop(heap)" }, { "code": null, "e": 2066, "s": 1939, "text": "This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements." }, { "code": null, "e": 2106, "s": 2066, "text": "Method heapq.heappushpop(heap, element)" }, { "code": null, "e": 2170, "s": 2106, "text": "This method is used to insert and pop element in one statement." }, { "code": null, "e": 2210, "s": 2170, "text": "Method heapq.heapreplace(heap, element)" }, { "code": null, "e": 2355, "s": 2210, "text": "This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap." }, { "code": null, "e": 2400, "s": 2355, "text": "Method heapq.nlargest(n, iterable, key=None)" }, { "code": null, "e": 2463, "s": 2400, "text": "This method is used to return n largest element from the heap." }, { "code": null, "e": 2509, "s": 2463, "text": "Method heapq.nsmallest(n, iterable, key=None)" }, { "code": null, "e": 2573, "s": 2509, "text": "This method is used to return n smallest element from the heap." }, { "code": null, "e": 2584, "s": 2573, "text": " Live Demo" }, { "code": null, "e": 2947, "s": 2584, "text": "import heapq\nfirst_list = [45, 12, 63, 95, 74, 21, 20, 15, 36]\nsecond_list = [42, 13, 69, 54, 15]\n\nfirst_list = sorted(first_list)\nsecond_list = sorted(second_list)\n\nprint('First sorted list: ' + str(first_list))\nprint('Second sorted list: ' + str(second_list))\n\nfinal_list = list(heapq.merge(first_list, second_list))\nprint('The final list: ' + str(final_list))" }, { "code": null, "e": 3117, "s": 2947, "text": "First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95]\nSecond sorted list: [13, 15, 42, 54, 69]\nThe final list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]" } ]
Number of Integral Points between Two Points
24 May, 2022 Given two points p (x1, y1) and q (x2, y2), calculate the number of integral points lying on the line joining them.Example : If points are (0, 2) and (4, 0), then the number of integral points lying on it is only one and that is (2, 1). Similarly, if points are (1, 9) and (8, 16), the integral points lying on it are 6 and they are (2, 10), (3, 11), (4, 12), (5, 13), (6, 14) and (7, 15). Simple Approach Start from any of the given points, reach the other end point by using loops. For every point inside the loop, check if it lies on the line that joins given two points. If yes, then increment the count by 1. Time Complexity for this approach will be O(min(x2-x1, y2-y1)). Optimal Approach 1. If the edge formed by joining p and q is parallel to the X-axis, then the number of integral points between the vertices is : abs(p.y - q.y)-1 2. Similarly if edge is parallel to the Y-axis, then the number of integral points in between is : abs(p.x - q.x)-1 3. Else, we can find the integral points between the vertices using below formula: GCD(abs(p.x - q.x), abs(p.y - q.y)) - 1 How does the GCD formula work? The idea is to find the equation of the line in simplest form, i.e., in equation ax + by +c, coefficients a, b and c become co-prime. We can do this by calculating the GCD (greatest common divisor) of a, b and c and convert a, b and c in the simplest form. Then, the answer will be (difference of y coordinates) divided by (a) – 1. This is because after calculating ax + by + c = 0, for different y values, x will be number of y values which are exactly divisible by a.Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ code to find the number of integral points// lying on the line joining the two given points#include <iostream>#include <cmath>using namespace std; // Class to represent an Integral point on XY plane.class Point{public: int x, y; Point(int a=0, int b=0):x(a),y(b) {}}; // Utility function to find GCD of two numbers// GCD of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a%b);} // Finds the no. of Integral points between// two given points.int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x==q.x) return abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return abs(p.x-q.x) - 1; return gcd(abs(p.x-q.x), abs(p.y-q.y))-1;} // Driver program to test aboveint main(){ Point p(1, 9); Point q(8, 16); cout << "The number of integral points between " << "(" << p.x << ", " << p.y << ") and (" << q.x << ", " << q.y << ") is " << getCount(p, q); return 0;} // Java code to find the number of integral points// lying on the line joining the two given points class GFG{ // Class to represent an Integral point on XY plane.static class Point{ int x, y; Point(int a, int b) { this.x = a; this.y = b; }}; // Utility function to find GCD of two numbers// GCD of a and bstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between// two given points.static int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1;} // Driver program to test abovepublic static void main(String[] args){ Point p = new Point(1, 9); Point q = new Point(8, 16); System.out.println("The number of integral points between " + "(" + p.x + ", " + p.y + ") and (" + q.x + ", " + q.y + ") is " + getCount(p, q));}} // This code contributed by Rajput-Ji # Python3 code to find the number of# integral points lying on the line# joining the two given points # Class to represent an Integral point# on XY plane.class Point: def __init__(self, a, b): self.x = a self.y = b # Utility function to find GCD# of two numbers GCD of a and bdef gcd(a, b): if b == 0: return a return gcd(b, a % b) # Finds the no. of Integral points# between two given points.def getCount(p, q): # If line joining p and q is parallel # to x axis, then count is difference # of y values if p.x == q.x: return abs(p.y - q.y) - 1 # If line joining p and q is parallel # to y axis, then count is difference # of x values if p.y == q.y: return abs(p.x - q.x) - 1 return gcd(abs(p.x - q.x), abs(p.y - q.y)) - 1 # Driver Codeif __name__ == "__main__": p = Point(1, 9) q = Point(8, 16) print("The number of integral points", "between ({}, {}) and ({}, {}) is {}" . format(p.x, p.y, q.x, q.y, getCount(p, q))) # This code is contributed by Rituraj Jain // C# code to find the number of integral points// lying on the line joining the two given pointsusing System; class GFG{ // Class to represent an Integral point on XY plane.public class Point{ public int x, y; public Point(int a, int b) { this.x = a; this.y = b; }}; // Utility function to find GCD of two numbers// GCD of a and bstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between// two given points.static int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.Abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.Abs(p.x - q.x) - 1; return gcd(Math.Abs(p.x - q.x), Math.Abs(p.y - q.y)) - 1;} // Driver codepublic static void Main(String[] args){ Point p = new Point(1, 9); Point q = new Point(8, 16); Console.WriteLine("The number of integral points between " + "(" + p.x + ", " + p.y + ") and (" + q.x + ", " + q.y + ") is " + getCount(p, q));}} /* This code contributed by PrinciRaj1992 */ <script>// javascript code to find the number of integral points// lying on the line joining the two given points // Class to represent an Integral point on XY plane. class Point { constructor(a , b) { this.x = a; this.y = b; } } // Utility function to find GCD of two numbers // GCD of a and b function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. function getCount( p, q) { // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1; } // Driver program to test above p = new Point(1, 9); q = new Point(8, 16); document.write("The number of integral points between " + "(" + p.x + ", " + p.y + ") and (" + q.x + ", " + q.y + ") is " + getCount(p, q)); // This code is contributed by gauravrajput1</script> Output: The number of integral points between (1, 9) and (8, 16) is 6 Time Complexity: O(log(min(a,b))), as we are using recursion to find the GCD. Auxiliary Space: O(1), as we are not using any extra space.Reference : https://www.geeksforgeeks.org/count-integral-points-inside-a-triangle/This article has been contributed by Paridhi Johari. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 nikhil52 rituraj_jain Rajput-Ji princiraj1992 GauravRajput1 ankita_saini rohitsingh07052 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation 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
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2022" }, { "code": null, "e": 448, "s": 54, "text": "Given two points p (x1, y1) and q (x2, y2), calculate the number of integral points lying on the line joining them.Example : If points are (0, 2) and (4, 0), then the number of integral points lying on it is only one and that is (2, 1). Similarly, if points are (1, 9) and (8, 16), the integral points lying on it are 6 and they are (2, 10), (3, 11), (4, 12), (5, 13), (6, 14) and (7, 15). " }, { "code": null, "e": 756, "s": 448, "text": " Simple Approach Start from any of the given points, reach the other end point by using loops. For every point inside the loop, check if it lies on the line that joins given two points. If yes, then increment the count by 1. Time Complexity for this approach will be O(min(x2-x1, y2-y1)). Optimal Approach " }, { "code": null, "e": 1176, "s": 756, "text": "1. If the edge formed by joining p and q is parallel \n to the X-axis, then the number of integral points \n between the vertices is : \n abs(p.y - q.y)-1\n\n2. Similarly if edge is parallel to the Y-axis, then \n the number of integral points in between is :\n abs(p.x - q.x)-1\n\n3. Else, we can find the integral points between the\n vertices using below formula:\n GCD(abs(p.x - q.x), abs(p.y - q.y)) - 1" }, { "code": null, "e": 1720, "s": 1176, "text": "How does the GCD formula work? The idea is to find the equation of the line in simplest form, i.e., in equation ax + by +c, coefficients a, b and c become co-prime. We can do this by calculating the GCD (greatest common divisor) of a, b and c and convert a, b and c in the simplest form. Then, the answer will be (difference of y coordinates) divided by (a) – 1. This is because after calculating ax + by + c = 0, for different y values, x will be number of y values which are exactly divisible by a.Below is the implementation of above idea. " }, { "code": null, "e": 1724, "s": 1720, "text": "C++" }, { "code": null, "e": 1729, "s": 1724, "text": "Java" }, { "code": null, "e": 1737, "s": 1729, "text": "Python3" }, { "code": null, "e": 1740, "s": 1737, "text": "C#" }, { "code": null, "e": 1751, "s": 1740, "text": "Javascript" }, { "code": "// C++ code to find the number of integral points// lying on the line joining the two given points#include <iostream>#include <cmath>using namespace std; // Class to represent an Integral point on XY plane.class Point{public: int x, y; Point(int a=0, int b=0):x(a),y(b) {}}; // Utility function to find GCD of two numbers// GCD of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a%b);} // Finds the no. of Integral points between// two given points.int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x==q.x) return abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return abs(p.x-q.x) - 1; return gcd(abs(p.x-q.x), abs(p.y-q.y))-1;} // Driver program to test aboveint main(){ Point p(1, 9); Point q(8, 16); cout << \"The number of integral points between \" << \"(\" << p.x << \", \" << p.y << \") and (\" << q.x << \", \" << q.y << \") is \" << getCount(p, q); return 0;}", "e": 2888, "s": 1751, "text": null }, { "code": "// Java code to find the number of integral points// lying on the line joining the two given points class GFG{ // Class to represent an Integral point on XY plane.static class Point{ int x, y; Point(int a, int b) { this.x = a; this.y = b; }}; // Utility function to find GCD of two numbers// GCD of a and bstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between// two given points.static int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1;} // Driver program to test abovepublic static void main(String[] args){ Point p = new Point(1, 9); Point q = new Point(8, 16); System.out.println(\"The number of integral points between \" + \"(\" + p.x + \", \" + p.y + \") and (\" + q.x + \", \" + q.y + \") is \" + getCount(p, q));}} // This code contributed by Rajput-Ji", "e": 4132, "s": 2888, "text": null }, { "code": "# Python3 code to find the number of# integral points lying on the line# joining the two given points # Class to represent an Integral point# on XY plane.class Point: def __init__(self, a, b): self.x = a self.y = b # Utility function to find GCD# of two numbers GCD of a and bdef gcd(a, b): if b == 0: return a return gcd(b, a % b) # Finds the no. of Integral points# between two given points.def getCount(p, q): # If line joining p and q is parallel # to x axis, then count is difference # of y values if p.x == q.x: return abs(p.y - q.y) - 1 # If line joining p and q is parallel # to y axis, then count is difference # of x values if p.y == q.y: return abs(p.x - q.x) - 1 return gcd(abs(p.x - q.x), abs(p.y - q.y)) - 1 # Driver Codeif __name__ == \"__main__\": p = Point(1, 9) q = Point(8, 16) print(\"The number of integral points\", \"between ({}, {}) and ({}, {}) is {}\" . format(p.x, p.y, q.x, q.y, getCount(p, q))) # This code is contributed by Rituraj Jain", "e": 5217, "s": 4132, "text": null }, { "code": "// C# code to find the number of integral points// lying on the line joining the two given pointsusing System; class GFG{ // Class to represent an Integral point on XY plane.public class Point{ public int x, y; public Point(int a, int b) { this.x = a; this.y = b; }}; // Utility function to find GCD of two numbers// GCD of a and bstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between// two given points.static int getCount(Point p, Point q){ // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.Abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.Abs(p.x - q.x) - 1; return gcd(Math.Abs(p.x - q.x), Math.Abs(p.y - q.y)) - 1;} // Driver codepublic static void Main(String[] args){ Point p = new Point(1, 9); Point q = new Point(8, 16); Console.WriteLine(\"The number of integral points between \" + \"(\" + p.x + \", \" + p.y + \") and (\" + q.x + \", \" + q.y + \") is \" + getCount(p, q));}} /* This code contributed by PrinciRaj1992 */", "e": 6475, "s": 5217, "text": null }, { "code": "<script>// javascript code to find the number of integral points// lying on the line joining the two given points // Class to represent an Integral point on XY plane. class Point { constructor(a , b) { this.x = a; this.y = b; } } // Utility function to find GCD of two numbers // GCD of a and b function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. function getCount( p, q) { // If line joining p and q is parallel to // x axis, then count is difference of y // values if (p.x == q.x) return Math.abs(p.y - q.y) - 1; // If line joining p and q is parallel to // y axis, then count is difference of x // values if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1; } // Driver program to test above p = new Point(1, 9); q = new Point(8, 16); document.write(\"The number of integral points between \" + \"(\" + p.x + \", \" + p.y + \") and (\" + q.x + \", \" + q.y + \") is \" + getCount(p, q)); // This code is contributed by gauravrajput1</script>", "e": 7786, "s": 6475, "text": null }, { "code": null, "e": 7796, "s": 7786, "text": "Output: " }, { "code": null, "e": 7858, "s": 7796, "text": "The number of integral points between (1, 9) and (8, 16) is 6" }, { "code": null, "e": 7936, "s": 7858, "text": "Time Complexity: O(log(min(a,b))), as we are using recursion to find the GCD." }, { "code": null, "e": 8478, "s": 7936, "text": "Auxiliary Space: O(1), as we are not using any extra space.Reference : https://www.geeksforgeeks.org/count-integral-points-inside-a-triangle/This article has been contributed by Paridhi Johari. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 8487, "s": 8478, "text": "nikhil52" }, { "code": null, "e": 8500, "s": 8487, "text": "rituraj_jain" }, { "code": null, "e": 8510, "s": 8500, "text": "Rajput-Ji" }, { "code": null, "e": 8524, "s": 8510, "text": "princiraj1992" }, { "code": null, "e": 8538, "s": 8524, "text": "GauravRajput1" }, { "code": null, "e": 8551, "s": 8538, "text": "ankita_saini" }, { "code": null, "e": 8567, "s": 8551, "text": "rohitsingh07052" }, { "code": null, "e": 8577, "s": 8567, "text": "Geometric" }, { "code": null, "e": 8590, "s": 8577, "text": "Mathematical" }, { "code": null, "e": 8603, "s": 8590, "text": "Mathematical" }, { "code": null, "e": 8613, "s": 8603, "text": "Geometric" }, { "code": null, "e": 8711, "s": 8613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8760, "s": 8711, "text": "Program for distance between two points on earth" }, { "code": null, "e": 8813, "s": 8760, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 8864, "s": 8813, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 8911, "s": 8864, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 8986, "s": 8911, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 9016, "s": 8986, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9059, "s": 9016, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9119, "s": 9059, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9134, "s": 9119, "text": "C++ Data Types" } ]
Services provided by Data Link Layer
25 Aug, 2020 Prerequisite – Data Link Layer Data Link Layer is generally representing protocol layer in program that is simply used to handle and control the transmission of data between source and destination machines. It is simply responsible for exchange of frames among nodes or machines over physical network media. This layer is often closest and nearest to Physical Layer (Hardware). Data Link Layer is basically second layer of seven-layer Open System Interconnection (OSI) reference model of computer networking and lies just above Physical Layer. This layer usually provides and gives data reliability and provides various tools to establish, maintain, and also release data link connections between network nodes. It is responsible for receiving and getting data bits usually from Physical Layer and also then converting these bits into groups, known as data link frames so that it can be transmitted further. It is also responsible to handle errors that might arise due to transmission of bits. Service Provided to Network Layer :The important and essential function of Data Link Layer is to provide an interface to Network Layer. Network Layer is third layer of seven-layer OSI reference model and is present just above Data Link Layer. The main aim of Data Link Layer is to transmit data frames they have received to destination machine so that these data frames can be handed over to network layer of destination machine. At the network layer, these data frames are basically addressed and routed. This process is shown in diagram : 1. Actual Communication :In this communication, physical medium is present through which Data Link Layer simply transmits data frames. The actual path is Network Layer -> Data link layer -> Physical Layer on sending machine, then to physical media and after that to Physical Layer -> Data link layer -> Network Layer on receiving machine. 2. Virtual Communication :In this communication, no physical medium is present for Data Link Layer to transmit data. It can be only be visualized and imagined that two Data Link Layers are communicating with each other with the help of or using data link protocol. Types of Services provided by Data Link Layer :The Data link layer generally provides or offers three types of services as given below : 1. Unacknowledged Connectionless Service 2. Acknowledged Connectionless Service 3. Acknowledged Connection-Oriented Service Unacknowledged Connectionless Service :Unacknowledged connectionless service simply provides datagram styles delivery without any error, issue, or flow control. In this service, source machine generally transmits independent frames to destination machine without having destination machine to acknowledge these frames.This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer.In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet.Acknowledged Connectionless Service :This service simply provides acknowledged connectionless service i.e. packet delivery is simply acknowledged, with help of stop and wait for protocol.In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually.This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period.This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc.Acknowledged Connection-Oriented Service :In this type of service, connection is established first among sender and receiver or source and destination before data is transferred.Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence. Unacknowledged Connectionless Service :Unacknowledged connectionless service simply provides datagram styles delivery without any error, issue, or flow control. In this service, source machine generally transmits independent frames to destination machine without having destination machine to acknowledge these frames.This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer.In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet. This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer. In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet. Acknowledged Connectionless Service :This service simply provides acknowledged connectionless service i.e. packet delivery is simply acknowledged, with help of stop and wait for protocol.In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually.This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period.This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc. In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually. This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period. This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc. Acknowledged Connection-Oriented Service :In this type of service, connection is established first among sender and receiver or source and destination before data is transferred.Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence. Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography Socket Programming in Python Differences between IPv4 and IPv6 Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Data encryption standard (DES) | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Aug, 2020" }, { "code": null, "e": 83, "s": 52, "text": "Prerequisite – Data Link Layer" }, { "code": null, "e": 430, "s": 83, "text": "Data Link Layer is generally representing protocol layer in program that is simply used to handle and control the transmission of data between source and destination machines. It is simply responsible for exchange of frames among nodes or machines over physical network media. This layer is often closest and nearest to Physical Layer (Hardware)." }, { "code": null, "e": 596, "s": 430, "text": "Data Link Layer is basically second layer of seven-layer Open System Interconnection (OSI) reference model of computer networking and lies just above Physical Layer." }, { "code": null, "e": 1046, "s": 596, "text": "This layer usually provides and gives data reliability and provides various tools to establish, maintain, and also release data link connections between network nodes. It is responsible for receiving and getting data bits usually from Physical Layer and also then converting these bits into groups, known as data link frames so that it can be transmitted further. It is also responsible to handle errors that might arise due to transmission of bits." }, { "code": null, "e": 1289, "s": 1046, "text": "Service Provided to Network Layer :The important and essential function of Data Link Layer is to provide an interface to Network Layer. Network Layer is third layer of seven-layer OSI reference model and is present just above Data Link Layer." }, { "code": null, "e": 1552, "s": 1289, "text": "The main aim of Data Link Layer is to transmit data frames they have received to destination machine so that these data frames can be handed over to network layer of destination machine. At the network layer, these data frames are basically addressed and routed." }, { "code": null, "e": 1587, "s": 1552, "text": "This process is shown in diagram :" }, { "code": null, "e": 1926, "s": 1587, "text": "1. Actual Communication :In this communication, physical medium is present through which Data Link Layer simply transmits data frames. The actual path is Network Layer -> Data link layer -> Physical Layer on sending machine, then to physical media and after that to Physical Layer -> Data link layer -> Network Layer on receiving machine." }, { "code": null, "e": 2191, "s": 1926, "text": "2. Virtual Communication :In this communication, no physical medium is present for Data Link Layer to transmit data. It can be only be visualized and imagined that two Data Link Layers are communicating with each other with the help of or using data link protocol." }, { "code": null, "e": 2328, "s": 2191, "text": "Types of Services provided by Data Link Layer :The Data link layer generally provides or offers three types of services as given below :" }, { "code": null, "e": 2453, "s": 2328, "text": "1. Unacknowledged Connectionless Service\n2. Acknowledged Connectionless Service\n3. Acknowledged Connection-Oriented Service " }, { "code": null, "e": 4635, "s": 2453, "text": "Unacknowledged Connectionless Service :Unacknowledged connectionless service simply provides datagram styles delivery without any error, issue, or flow control. In this service, source machine generally transmits independent frames to destination machine without having destination machine to acknowledge these frames.This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer.In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet.Acknowledged Connectionless Service :This service simply provides acknowledged connectionless service i.e. packet delivery is simply acknowledged, with help of stop and wait for protocol.In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually.This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period.This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc.Acknowledged Connection-Oriented Service :In this type of service, connection is established first among sender and receiver or source and destination before data is transferred.Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence." }, { "code": null, "e": 5399, "s": 4635, "text": "Unacknowledged Connectionless Service :Unacknowledged connectionless service simply provides datagram styles delivery without any error, issue, or flow control. In this service, source machine generally transmits independent frames to destination machine without having destination machine to acknowledge these frames.This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer.In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet." }, { "code": null, "e": 5613, "s": 5399, "text": "This service is called as connectionless service because there is no connection established among sending or source machine and destination or receiving machine before data transfer or release after data transfer." }, { "code": null, "e": 5846, "s": 5613, "text": "In Data Link Layer, if anyhow frame is lost due to noise, there will be no attempt made just to detect or determine loss or recovery from it. This simply means that there will be no error or flow control. An example can be Ethernet." }, { "code": null, "e": 6797, "s": 5846, "text": "Acknowledged Connectionless Service :This service simply provides acknowledged connectionless service i.e. packet delivery is simply acknowledged, with help of stop and wait for protocol.In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually.This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period.This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc." }, { "code": null, "e": 7100, "s": 6797, "text": "In this service, each frame that is transmitted by Data Link Layer is simply acknowledged individually and then sender usually knows whether or not these transmitted data frames received safely. There is no logical connection established and each frame that is transmitted is acknowledged individually." }, { "code": null, "e": 7378, "s": 7100, "text": "This mode simply provides means by which user of data link can just send or transfer data and request return of data at the same time. It also uses particular time period that if it has passed frame without getting acknowledgment, then it will resend data frame on time period." }, { "code": null, "e": 7563, "s": 7378, "text": "This service is more reliable than unacknowledged connectionless service. This service is generally useful over several unreliable channels, like wireless systems, Wi-Fi services, etc." }, { "code": null, "e": 8032, "s": 7563, "text": "Acknowledged Connection-Oriented Service :In this type of service, connection is established first among sender and receiver or source and destination before data is transferred.Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence." }, { "code": null, "e": 8323, "s": 8032, "text": "Then data is transferred or transmitted along with this established connection. In this service, each of frames that are transmitted is provided individual numbers first, so as to confirm and guarantee that each of frames is received only once that too in an appropriate order and sequence." }, { "code": null, "e": 8341, "s": 8323, "text": "Computer Networks" }, { "code": null, "e": 8359, "s": 8341, "text": "Computer Networks" }, { "code": null, "e": 8457, "s": 8359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8489, "s": 8457, "text": "Differences between TCP and UDP" }, { "code": null, "e": 8515, "s": 8489, "text": "Types of Network Topology" }, { "code": null, "e": 8545, "s": 8515, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 8574, "s": 8545, "text": "Socket Programming in Python" }, { "code": null, "e": 8608, "s": 8574, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 8638, "s": 8608, "text": "Wireless Application Protocol" }, { "code": null, "e": 8668, "s": 8638, "text": "GSM in Wireless Communication" }, { "code": null, "e": 8694, "s": 8668, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 8734, "s": 8694, "text": "Mobile Internet Protocol (or Mobile IP)" } ]
TRIM() Function in SQL Server
18 Jan, 2021 TRIM() function : This function in SQL Server is used to omit the space character or additional stated characters from the beginning or the ending of a specified string. Features : This function is used to omit the space character or some additional given characters from the beginning or the ending of a string stated. This function accepts specific characters and string. This function can by default omit the front and endmost spaces from a string given. Syntax : TRIM([characters FROM ]string) Parameter : This method accepts two parameters characters FROM – Specific characters which are to be omitted. string – Specified string from which the stated characters or spaces are omitted. Returns : It returns the specified string after omitting the space character or some additional stated characters from the front or the endmost part of it. Example-1 : Getting the specified string after omitting the beginning and ending space of it. SELECT TRIM(' GFG '); Output : GFG Example-2 : Using TRIM() function with a variable and getting the specified string after modification as output. DECLARE @str VARCHAR(10); SET @str = ' Geeks '; SELECT TRIM(@str); Output : Geeks Example-3 : Getting the specified string after omitting the specific characters and the beginning and ending space of it. SELECT TRIM('@$ ' FROM ' @geeksforgeeks$ '); Output : geeksforgeeks Here, the specified character is also omitted. Example-4 : Using TRIM() function with two variables and getting the specified string after modification as output. DECLARE @str VARCHAR(10); DEclare @char VARCHAR(10); SET @str = ' &Geeks* '; SET @char = '&* '; SELECT TRIM(@char FROM @str); Output : Geeks Application : This function is used to return the modified string after omitting the space character or additional stated characters from the beginning or the ending of a given string. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Sub queries in From Clause Window functions in SQL What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT RANK() Function in SQL Server How to Import JSON Data into SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jan, 2021" }, { "code": null, "e": 72, "s": 54, "text": "TRIM() function :" }, { "code": null, "e": 224, "s": 72, "text": "This function in SQL Server is used to omit the space character or additional stated characters from the beginning or the ending of a specified string." }, { "code": null, "e": 235, "s": 224, "text": "Features :" }, { "code": null, "e": 374, "s": 235, "text": "This function is used to omit the space character or some additional given characters from the beginning or the ending of a string stated." }, { "code": null, "e": 428, "s": 374, "text": "This function accepts specific characters and string." }, { "code": null, "e": 512, "s": 428, "text": "This function can by default omit the front and endmost spaces from a string given." }, { "code": null, "e": 521, "s": 512, "text": "Syntax :" }, { "code": null, "e": 552, "s": 521, "text": "TRIM([characters FROM ]string)" }, { "code": null, "e": 564, "s": 552, "text": "Parameter :" }, { "code": null, "e": 599, "s": 564, "text": "This method accepts two parameters" }, { "code": null, "e": 662, "s": 599, "text": "characters FROM – Specific characters which are to be omitted." }, { "code": null, "e": 744, "s": 662, "text": "string – Specified string from which the stated characters or spaces are omitted." }, { "code": null, "e": 754, "s": 744, "text": "Returns :" }, { "code": null, "e": 900, "s": 754, "text": "It returns the specified string after omitting the space character or some additional stated characters from the front or the endmost part of it." }, { "code": null, "e": 912, "s": 900, "text": "Example-1 :" }, { "code": null, "e": 994, "s": 912, "text": "Getting the specified string after omitting the beginning and ending space of it." }, { "code": null, "e": 1024, "s": 994, "text": "SELECT TRIM(' GFG ');" }, { "code": null, "e": 1033, "s": 1024, "text": "Output :" }, { "code": null, "e": 1037, "s": 1033, "text": "GFG" }, { "code": null, "e": 1049, "s": 1037, "text": "Example-2 :" }, { "code": null, "e": 1150, "s": 1049, "text": "Using TRIM() function with a variable and getting the specified string after modification as output." }, { "code": null, "e": 1221, "s": 1150, "text": "DECLARE @str VARCHAR(10);\nSET @str = ' Geeks ';\nSELECT TRIM(@str);" }, { "code": null, "e": 1230, "s": 1221, "text": "Output :" }, { "code": null, "e": 1236, "s": 1230, "text": "Geeks" }, { "code": null, "e": 1248, "s": 1236, "text": "Example-3 :" }, { "code": null, "e": 1358, "s": 1248, "text": "Getting the specified string after omitting the specific characters and the beginning and ending space of it." }, { "code": null, "e": 1409, "s": 1358, "text": "SELECT TRIM('@$ ' FROM ' @geeksforgeeks$ ');" }, { "code": null, "e": 1418, "s": 1409, "text": "Output :" }, { "code": null, "e": 1432, "s": 1418, "text": "geeksforgeeks" }, { "code": null, "e": 1479, "s": 1432, "text": "Here, the specified character is also omitted." }, { "code": null, "e": 1491, "s": 1479, "text": "Example-4 :" }, { "code": null, "e": 1595, "s": 1491, "text": "Using TRIM() function with two variables and getting the specified string after modification as output." }, { "code": null, "e": 1724, "s": 1595, "text": "DECLARE @str VARCHAR(10);\nDEclare @char VARCHAR(10);\nSET @str = ' &Geeks* ';\nSET @char = '&* ';\nSELECT TRIM(@char FROM @str);" }, { "code": null, "e": 1733, "s": 1724, "text": "Output :" }, { "code": null, "e": 1739, "s": 1733, "text": "Geeks" }, { "code": null, "e": 1753, "s": 1739, "text": "Application :" }, { "code": null, "e": 1924, "s": 1753, "text": "This function is used to return the modified string after omitting the space character or additional stated characters from the beginning or the ending of a given string." }, { "code": null, "e": 1933, "s": 1924, "text": "DBMS-SQL" }, { "code": null, "e": 1944, "s": 1933, "text": "SQL-Server" }, { "code": null, "e": 1948, "s": 1944, "text": "SQL" }, { "code": null, "e": 1952, "s": 1948, "text": "SQL" }, { "code": null, "e": 2050, "s": 1952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2116, "s": 2050, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2149, "s": 2116, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2173, "s": 2149, "text": "Window functions in SQL" }, { "code": null, "e": 2205, "s": 2173, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2283, "s": 2205, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2300, "s": 2283, "text": "SQL using Python" }, { "code": null, "e": 2336, "s": 2300, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2366, "s": 2336, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2407, "s": 2366, "text": "How to Import JSON Data into SQL Server?" } ]
StringBuilder substring() method in Java with examples
19 Aug, 2019 In StringBuilder class, there are two types of substring method depending upon the parameters passed to it. The substring(int start) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence. Syntax: public String substring(int start) Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring. Return Value: This method returns the substring lie in the range start to end of old sequence. Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object. Below programs illustrate the StringBuilder substring() method: Example 1: // Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksForGeeks"); // print string System.out.println("String contains = " + str); // get substring start from index 5 // using substring() and print results System.out.println("SubSequence = " + str.substring(5)); }} String contains = GeeksForGeeks SubSequence = ForGeeks Example 2: To demonstrate StringIndexOutOfBoundsException // Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Indian Team Played Well"); try { // get substring starts from index -7 // using substring() and print str.substring(-7); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7 The substring(int start, int end) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence. Syntax: public String substring(int start) Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring. Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence. Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end. Below programs illustrate the StringBuilder.substring() method: Example 1: // Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksForGeeks"); // print string System.out.println("String contains = " + str); // get substring start from index 5 to index 8 // using substring() and print results System.out.println("SubSequence = " + str.substring(5, 8)); }} String contains = GeeksForGeeks SubSequence = For Example 2: To demonstrate StringIndexOutOfBoundsException // Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Indian Team Played Well"); try { // get substring starts from index 7 // and end at index 3 // using substring() and print str.substring(9, 3); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6 References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int, int)https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int) Akanksha_Rai java-basics Java-Functions Java-StringBuilder Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Aug, 2019" }, { "code": null, "e": 161, "s": 53, "text": "In StringBuilder class, there are two types of substring method depending upon the parameters passed to it." }, { "code": null, "e": 428, "s": 161, "text": "The substring(int start) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence." }, { "code": null, "e": 436, "s": 428, "text": "Syntax:" }, { "code": null, "e": 471, "s": 436, "text": "public String substring(int start)" }, { "code": null, "e": 596, "s": 471, "text": "Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring." }, { "code": null, "e": 691, "s": 596, "text": "Return Value: This method returns the substring lie in the range start to end of old sequence." }, { "code": null, "e": 824, "s": 691, "text": "Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object." }, { "code": null, "e": 888, "s": 824, "text": "Below programs illustrate the StringBuilder substring() method:" }, { "code": null, "e": 899, "s": 888, "text": "Example 1:" }, { "code": "// Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksForGeeks\"); // print string System.out.println(\"String contains = \" + str); // get substring start from index 5 // using substring() and print results System.out.println(\"SubSequence = \" + str.substring(5)); }}", "e": 1467, "s": 899, "text": null }, { "code": null, "e": 1523, "s": 1467, "text": "String contains = GeeksForGeeks\nSubSequence = ForGeeks\n" }, { "code": null, "e": 1581, "s": 1523, "text": "Example 2: To demonstrate StringIndexOutOfBoundsException" }, { "code": "// Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Indian Team Played Well\"); try { // get substring starts from index -7 // using substring() and print str.substring(-7); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 2127, "s": 1581, "text": null }, { "code": null, "e": 2212, "s": 2127, "text": "Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7\n" }, { "code": null, "e": 2508, "s": 2212, "text": "The substring(int start, int end) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence." }, { "code": null, "e": 2516, "s": 2508, "text": "Syntax:" }, { "code": null, "e": 2551, "s": 2516, "text": "public String substring(int start)" }, { "code": null, "e": 2751, "s": 2551, "text": "Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring." }, { "code": null, "e": 2860, "s": 2751, "text": "Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence." }, { "code": null, "e": 3007, "s": 2860, "text": "Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end." }, { "code": null, "e": 3071, "s": 3007, "text": "Below programs illustrate the StringBuilder.substring() method:" }, { "code": null, "e": 3082, "s": 3071, "text": "Example 1:" }, { "code": "// Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksForGeeks\"); // print string System.out.println(\"String contains = \" + str); // get substring start from index 5 to index 8 // using substring() and print results System.out.println(\"SubSequence = \" + str.substring(5, 8)); }}", "e": 3638, "s": 3082, "text": null }, { "code": null, "e": 3689, "s": 3638, "text": "String contains = GeeksForGeeks\nSubSequence = For\n" }, { "code": null, "e": 3747, "s": 3689, "text": "Example 2: To demonstrate StringIndexOutOfBoundsException" }, { "code": "// Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Indian Team Played Well\"); try { // get substring starts from index 7 // and end at index 3 // using substring() and print str.substring(9, 3); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 4329, "s": 3747, "text": null }, { "code": null, "e": 4414, "s": 4329, "text": "Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6\n" }, { "code": null, "e": 4603, "s": 4414, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int, int)https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int)" }, { "code": null, "e": 4616, "s": 4603, "text": "Akanksha_Rai" }, { "code": null, "e": 4628, "s": 4616, "text": "java-basics" }, { "code": null, "e": 4643, "s": 4628, "text": "Java-Functions" }, { "code": null, "e": 4662, "s": 4643, "text": "Java-StringBuilder" }, { "code": null, "e": 4667, "s": 4662, "text": "Java" }, { "code": null, "e": 4672, "s": 4667, "text": "Java" }, { "code": null, "e": 4770, "s": 4672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4821, "s": 4770, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4852, "s": 4821, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4871, "s": 4852, "text": "Interfaces in Java" }, { "code": null, "e": 4901, "s": 4871, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4919, "s": 4901, "text": "ArrayList in Java" }, { "code": null, "e": 4939, "s": 4919, "text": "Collections in Java" }, { "code": null, "e": 4971, "s": 4939, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4986, "s": 4971, "text": "Stream In Java" }, { "code": null, "e": 4998, "s": 4986, "text": "Set in Java" } ]
Introduction of Database Normalization
28 Jun, 2021 Database normalization is the process of organizing the attributes of the database to reduce or eliminate data redundancy (having the same data but at different places) . Problems because of data redundancy Data redundancy unnecessarily increases the size of the database as the same data is repeated in many places. Inconsistency problems also arise during insert, delete and update operations. Functional Dependency Functional Dependency is a constraint between two sets of attributes in relation to a database. A functional dependency is denoted by an arrow (→). If an attribute A functionally determines B, then it is written as A → B. For example, employee_id → name means employee_id functionally determines the name of the employee. As another example in a timetable database, {student_id, time} → {lecture_room}, student ID and time determine the lecture room where the student should be. What does functionally dependent mean? A function dependency A → B means for all instances of a particular value of A, there is the same value of B. For example in the below table A → B is true, but B → A is not true as there are different values of A for B = 3. A B ------ 1 3 2 3 4 0 1 3 4 0 Trivial Functional Dependency X → Y is trivial only when Y is subset of X. Examples ABC → AB ABC → A ABC → ABC Non Trivial Functional Dependencies X → Y is a non trivial functional dependency when Y is not a subset of X. X → Y is called completely non-trivial when X intersect Y is NULL. Example: Id → Name, Name → DOB Semi Non Trivial Functional Dependencies X → Y is called semi non-trivial when X intersect Y is not NULL. Examples: AB → BC, AD → DC Normal Forms Quiz on Normalization Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AmanSrivastava1 krishna_97 DBMS-Normalization DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? CTE in SQL Difference between Clustered and Non-clustered index SQL Trigger | Student Database SQL Interview Questions Data Preprocessing in Data Mining SQL | Views Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 224, "s": 52, "text": "Database normalization is the process of organizing the attributes of the database to reduce or eliminate data redundancy (having the same data but at different places) . " }, { "code": null, "e": 450, "s": 224, "text": "Problems because of data redundancy Data redundancy unnecessarily increases the size of the database as the same data is repeated in many places. Inconsistency problems also arise during insert, delete and update operations. " }, { "code": null, "e": 695, "s": 450, "text": "Functional Dependency Functional Dependency is a constraint between two sets of attributes in relation to a database. A functional dependency is denoted by an arrow (→). If an attribute A functionally determines B, then it is written as A → B. " }, { "code": null, "e": 953, "s": 695, "text": "For example, employee_id → name means employee_id functionally determines the name of the employee. As another example in a timetable database, {student_id, time} → {lecture_room}, student ID and time determine the lecture room where the student should be. " }, { "code": null, "e": 1103, "s": 953, "text": "What does functionally dependent mean? A function dependency A → B means for all instances of a particular value of A, there is the same value of B. " }, { "code": null, "e": 1218, "s": 1103, "text": "For example in the below table A → B is true, but B → A is not true as there are different values of A for B = 3. " }, { "code": null, "e": 1261, "s": 1218, "text": "A B\n------\n1 3\n2 3\n4 0\n1 3\n4 0" }, { "code": null, "e": 1347, "s": 1261, "text": "Trivial Functional Dependency X → Y is trivial only when Y is subset of X. Examples " }, { "code": null, "e": 1374, "s": 1347, "text": "ABC → AB\nABC → A\nABC → ABC" }, { "code": null, "e": 1485, "s": 1374, "text": "Non Trivial Functional Dependencies X → Y is a non trivial functional dependency when Y is not a subset of X. " }, { "code": null, "e": 1554, "s": 1485, "text": "X → Y is called completely non-trivial when X intersect Y is NULL. " }, { "code": null, "e": 1564, "s": 1554, "text": "Example: " }, { "code": null, "e": 1587, "s": 1564, "text": "Id → Name, \nName → DOB" }, { "code": null, "e": 1705, "s": 1587, "text": "Semi Non Trivial Functional Dependencies X → Y is called semi non-trivial when X intersect Y is not NULL. Examples: " }, { "code": null, "e": 1723, "s": 1705, "text": "AB → BC, \nAD → DC" }, { "code": null, "e": 1736, "s": 1723, "text": "Normal Forms" }, { "code": null, "e": 1758, "s": 1736, "text": "Quiz on Normalization" }, { "code": null, "e": 1883, "s": 1758, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1899, "s": 1883, "text": "AmanSrivastava1" }, { "code": null, "e": 1910, "s": 1899, "text": "krishna_97" }, { "code": null, "e": 1929, "s": 1910, "text": "DBMS-Normalization" }, { "code": null, "e": 1934, "s": 1929, "text": "DBMS" }, { "code": null, "e": 1939, "s": 1934, "text": "DBMS" }, { "code": null, "e": 2037, "s": 1939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2084, "s": 2037, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 2102, "s": 2084, "text": "SQL | WITH clause" }, { "code": null, "e": 2143, "s": 2102, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 2154, "s": 2143, "text": "CTE in SQL" }, { "code": null, "e": 2207, "s": 2154, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2238, "s": 2207, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2262, "s": 2238, "text": "SQL Interview Questions" }, { "code": null, "e": 2296, "s": 2262, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 2308, "s": 2296, "text": "SQL | Views" } ]
Matplotlib.axes.Axes.clear() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.clear() function in axes module of matplotlib library is used to clear the axes. Syntax: Axes.clear(self) Parameters: This method does not accept any parameters. Returns:This method does not returns any values. Below examples illustrate the matplotlib.axes.Axes.clear() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.plot([1, 2, 3])ax.grid(True)ax.clear()ax.set_title('matplotlib.axes.Axes.clear() \Example\n', fontsize = 12, fontweight ='bold')plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('matplotlib.axes.Axes.clear() Example\n\n Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True)ax1.clear()ax1.set_title('Above example with clear() \function', fontsize = 12, fontweight ='bold')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 418, "s": 328, "text": "The Axes.clear() function in axes module of matplotlib library is used to clear the axes." }, { "code": null, "e": 443, "s": 418, "text": "Syntax: Axes.clear(self)" }, { "code": null, "e": 499, "s": 443, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 548, "s": 499, "text": "Returns:This method does not returns any values." }, { "code": null, "e": 636, "s": 548, "text": "Below examples illustrate the matplotlib.axes.Axes.clear() function in matplotlib.axes:" }, { "code": null, "e": 647, "s": 636, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.plot([1, 2, 3])ax.grid(True)ax.clear()ax.set_title('matplotlib.axes.Axes.clear() \\Example\\n', fontsize = 12, fontweight ='bold')plt.show()", "e": 952, "s": 647, "text": null }, { "code": null, "e": 960, "s": 952, "text": "Output:" }, { "code": null, "e": 971, "s": 960, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('matplotlib.axes.Axes.clear() Example\\n\\n Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True)ax1.clear()ax1.set_title('Above example with clear() \\function', fontsize = 12, fontweight ='bold')plt.show()", "e": 1504, "s": 971, "text": null }, { "code": null, "e": 1512, "s": 1504, "text": "Output:" }, { "code": null, "e": 1530, "s": 1512, "text": "Python-matplotlib" }, { "code": null, "e": 1537, "s": 1530, "text": "Python" }, { "code": null, "e": 1635, "s": 1537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1653, "s": 1635, "text": "Python Dictionary" }, { "code": null, "e": 1695, "s": 1653, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1717, "s": 1695, "text": "Enumerate() in Python" }, { "code": null, "e": 1743, "s": 1717, "text": "Python String | replace()" }, { "code": null, "e": 1775, "s": 1743, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1804, "s": 1775, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1831, "s": 1804, "text": "Python Classes and Objects" }, { "code": null, "e": 1852, "s": 1831, "text": "Python OOPs Concepts" }, { "code": null, "e": 1888, "s": 1852, "text": "Convert integer to string in Python" } ]
pandas.array() function in Python
14 Aug, 2020 This method is used to create an array from a sequence in desired data type. Syntax : pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True) Parameters : data : Sequence of objects. The scalars inside `data` should be instances of the scalar type for `dtype`. It’s expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : tr, np.dtype, or ExtensionDtype, optional. The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas. copy : bool, default True. Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if “copy=False“. Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packagesimport pandas # create Pandas array with dtype stringpd_arr = pandas.array(data=[1,2,3,4,5],dtype=str) # print the formed arrayprint(pd_arr) Output : <PandasArray> ['1', '2', '3', '4', '5'] Length: 5, dtype: str32 Example 2 : Python3 # importing packagesimport pandasimport numpy # create Pandas array with dtype from numpypd_arr = pandas.array(data=['1', '2', '3', '4', '5'], dtype=numpy.int8) # print the formed arrayprint(pd_arr) Output : <PandasArray> [1, 2, 3, 4, 5] Length: 5, dtype: int8 Python pandas-datatypes Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Aug, 2020" }, { "code": null, "e": 105, "s": 28, "text": "This method is used to create an array from a sequence in desired data type." }, { "code": null, "e": 259, "s": 105, "text": "Syntax : pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True)" }, { "code": null, "e": 272, "s": 259, "text": "Parameters :" }, { "code": null, "e": 533, "s": 272, "text": "data : Sequence of objects. The scalars inside `data` should be instances of the scalar type for `dtype`. It’s expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`." }, { "code": null, "e": 687, "s": 533, "text": "dtype : tr, np.dtype, or ExtensionDtype, optional. The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas." }, { "code": null, "e": 867, "s": 687, "text": "copy : bool, default True. Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if “copy=False“." }, { "code": null, "e": 936, "s": 867, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 948, "s": 936, "text": "Example 1 :" }, { "code": null, "e": 956, "s": 948, "text": "Python3" }, { "code": "# importing packagesimport pandas # create Pandas array with dtype stringpd_arr = pandas.array(data=[1,2,3,4,5],dtype=str) # print the formed arrayprint(pd_arr)", "e": 1119, "s": 956, "text": null }, { "code": null, "e": 1128, "s": 1119, "text": "Output :" }, { "code": null, "e": 1193, "s": 1128, "text": "<PandasArray>\n['1', '2', '3', '4', '5']\nLength: 5, dtype: str32\n" }, { "code": null, "e": 1205, "s": 1193, "text": "Example 2 :" }, { "code": null, "e": 1213, "s": 1205, "text": "Python3" }, { "code": "# importing packagesimport pandasimport numpy # create Pandas array with dtype from numpypd_arr = pandas.array(data=['1', '2', '3', '4', '5'], dtype=numpy.int8) # print the formed arrayprint(pd_arr)", "e": 1435, "s": 1213, "text": null }, { "code": null, "e": 1444, "s": 1435, "text": "Output :" }, { "code": null, "e": 1498, "s": 1444, "text": "<PandasArray>\n[1, 2, 3, 4, 5]\nLength: 5, dtype: int8\n" }, { "code": null, "e": 1522, "s": 1498, "text": "Python pandas-datatypes" }, { "code": null, "e": 1536, "s": 1522, "text": "Python-pandas" }, { "code": null, "e": 1543, "s": 1536, "text": "Python" }, { "code": null, "e": 1641, "s": 1543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1673, "s": 1641, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1700, "s": 1673, "text": "Python Classes and Objects" }, { "code": null, "e": 1721, "s": 1700, "text": "Python OOPs Concepts" }, { "code": null, "e": 1744, "s": 1721, "text": "Introduction To PYTHON" }, { "code": null, "e": 1775, "s": 1744, "text": "Python | os.path.join() method" }, { "code": null, "e": 1831, "s": 1775, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1873, "s": 1831, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1915, "s": 1873, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1954, "s": 1915, "text": "Python | Get unique values from a list" } ]
Program to swap numbers using XOR operator in C#
08 Jun, 2020 C# Program to swap the two numbers using Bitwise XOR Operation. Given two variables, x and y, swap two variables with using a XOR statements. Example: Input: 300 400 Output: 400 300 Explanation: x = 300 y = 400 x = 400 y = 300 C# // C# Program to Swap the two Numbers// using Bitwise XOR Operationusing System;using System.Text; namespace Test {class GFG { static void Main(string[] args) { int x, y; Console.WriteLine("Enter two numbers \n"); x = int.Parse(Console.ReadLine()); y = int.Parse(Console.ReadLine()); // printing the numbers before swapping Console.WriteLine("Numbers before swapping"); Console.WriteLine("x = {0} \t b = {1}", x, y); // swapping x = x ^ y; y = x ^ y; x = x ^ y; // printing the numbers after swapping Console.WriteLine("Numbers after swapping"); Console.WriteLine("x = {0} \t b = {1}", x, y); Console.ReadLine(); }}} Output: Enter two numbers Numbers before swapping x = 300 b = 400 Numbers after swapping x = 400 b = 300 C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Convert String to Character Array in C# Program to Print a New Line in C# Socket Programming in C# Getting a Month Name Using Month Number in C# Program to find absolute value of a given number
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2020" }, { "code": null, "e": 197, "s": 54, "text": "C# Program to swap the two numbers using Bitwise XOR Operation. Given two variables, x and y, swap two variables with using a XOR statements. " }, { "code": null, "e": 207, "s": 197, "text": "Example: " }, { "code": null, "e": 289, "s": 207, "text": "Input: 300 400 \n\nOutput: 400 300 \n\nExplanation: \nx = 300 y = 400 \nx = 400 y = 300" }, { "code": null, "e": 292, "s": 289, "text": "C#" }, { "code": "// C# Program to Swap the two Numbers// using Bitwise XOR Operationusing System;using System.Text; namespace Test {class GFG { static void Main(string[] args) { int x, y; Console.WriteLine(\"Enter two numbers \\n\"); x = int.Parse(Console.ReadLine()); y = int.Parse(Console.ReadLine()); // printing the numbers before swapping Console.WriteLine(\"Numbers before swapping\"); Console.WriteLine(\"x = {0} \\t b = {1}\", x, y); // swapping x = x ^ y; y = x ^ y; x = x ^ y; // printing the numbers after swapping Console.WriteLine(\"Numbers after swapping\"); Console.WriteLine(\"x = {0} \\t b = {1}\", x, y); Console.ReadLine(); }}}", "e": 969, "s": 292, "text": null }, { "code": null, "e": 978, "s": 969, "text": "Output: " }, { "code": null, "e": 1088, "s": 978, "text": "Enter two numbers \n\nNumbers before swapping\nx = 300 b = 400\nNumbers after swapping\nx = 400 b = 300\n" }, { "code": null, "e": 1091, "s": 1088, "text": "C#" }, { "code": null, "e": 1103, "s": 1091, "text": "C# Programs" }, { "code": null, "e": 1201, "s": 1103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1229, "s": 1201, "text": "C# Dictionary with examples" }, { "code": null, "e": 1260, "s": 1229, "text": "Introduction to .NET Framework" }, { "code": null, "e": 1275, "s": 1260, "text": "C# | Delegates" }, { "code": null, "e": 1318, "s": 1275, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1367, "s": 1318, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1407, "s": 1367, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 1441, "s": 1407, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 1466, "s": 1441, "text": "Socket Programming in C#" }, { "code": null, "e": 1512, "s": 1466, "text": "Getting a Month Name Using Month Number in C#" } ]
Minimum absolute difference of adjacent elements in a circular array
08 Jun, 2022 Given n integers, which form a circle. Find the minimal absolute value of any adjacent pair. If there are many optimum solutions, output any of them. Note: they are in circle Examples: Input : arr[] = {10, 12, 13, 15, 10} Output : 0 Explanation: |10 - 10| = 0 which is the minimum possible. Input : arr[] = {10, 20, 30, 40} Output : 10 Explanation: |10 - 20| = 10 which is the minimum, 2 3 or 3 4 can be the answers also. Initially consider the minimum value to be of first and second elements. Traverse from second element to last. Check the difference of every adjacent pair and store the minimum value. When last element is reached, check its difference with first element.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C++ program to find maximum difference// between adjacent elements in a circular array.#include <bits/stdc++.h>using namespace std; void minAdjDifference(int arr[], int n){ if (n < 2) return; // Checking normal adjacent elements int res = abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = min(res, abs(arr[i] - arr[i - 1])); // Checking circular link res = min(res, abs(arr[n - 1] - arr[0])); cout << "Min Difference = " << res;} // driver program to check the above functionint main(){ int a[] = { 10, 12, 13, 15, 10 }; int n = sizeof(a) / sizeof(a[0]); minAdjDifference(a, n); return 0;} // Java program to find maximum difference// between adjacent elements in a circular// array.class GFG { static void minAdjDifference(int arr[], int n) { if (n < 2) return; // Checking normal adjacent elements int res = Math.abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = Math.min(res, Math.abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.min(res, Math.abs(arr[n - 1] - arr[0])); System.out.print("Min Difference = " + res); } // driver code public static void main(String arg[]) { int a[] = { 10, 12, 13, 15, 10 }; int n = a.length; minAdjDifference(a, n); }} // This code is contributed by Anant Agarwal// and improved by Anuj Sharma. # Python3 program to find maximum# difference between adjacent# elements in a circular array. def minAdjDifference(arr, n): if (n < 2): return # Checking normal adjacent elements res = abs(arr[1] - arr[0]) for i in range(2, n): res = min(res, abs(arr[i] - arr[i - 1])) # Checking circular link res = min(res, abs(arr[n - 1] - arr[0])) print("Min Difference = ", res) # Driver Codea = [10, 12, 13, 15, 10]n = len(a)minAdjDifference(a, n) # This code is contributed by Anant Agarwal# and improved by Anuj Sharma. // C# program to find maximum difference// between adjacent elements in a circular array.using System; class GFG { static void minAdjDifference(int[] arr, int n) { if (n < 2) return; // Checking normal adjacent elements int res = Math.Abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = Math.Min(res, Math.Abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.Min(res, Math.Abs(arr[n - 1] - arr[0])); Console.Write("Min Difference = " + res); } // driver code public static void Main() { int[] a = { 10, 12, 13, 15, 10 }; int n = a.Length; minAdjDifference(a, n); }} // This code is contributed by Anant Agarwal// and improved by Anuj Sharma. <?php// PHP program to find maximum// difference between adjacent// elements in a circular array. function minAdjDifference($arr, $n){ if ($n < 2) return; // Checking normal // adjacent elements $res = abs($arr[1] - $arr[0]); for ($i = 2; $i < $n; $i++) $res = min($res, abs($arr[$i] - $arr[$i - 1])); // Checking circular link $res = min($res, abs($arr[$n - 1] - $arr[0])); echo "Min Difference = ", $res;} // Driver Code$a = array(10, 12, 13, 15, 10);$n = count($a);minAdjDifference($a, $n); //This code is contributed by anuj_67//and improved by Anuj Sharma.?> <script> // Javascript program to find maximum difference// between adjacent elements in a circular array. function minAdjDifference( arr, n){ if (n < 2) return; // Checking normal adjacent elements let res = Math.abs(arr[1] - arr[0]); for (let i = 2; i < n; i++) res = Math.min(res, Math.abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.min(res, Math.abs(arr[n - 1] - arr[0])); document.write("Min Difference = " + res);} // driver code let a = [ 10, 12, 13, 15, 10 ]; let n = a.length; minAdjDifference(a, n); </script> Output: Min Difference = 0 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. https://youtu.be/G -vouVriEvY This article is contributed by striver. 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. vt_m Anuj_Sharma jana_sayantan rohan07 circular-array Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2022" }, { "code": null, "e": 240, "s": 53, "text": "Given n integers, which form a circle. Find the minimal absolute value of any adjacent pair. If there are many optimum solutions, output any of them. Note: they are in circle Examples: " }, { "code": null, "e": 483, "s": 240, "text": "Input : arr[] = {10, 12, 13, 15, 10} \nOutput : 0\nExplanation: |10 - 10| = 0 which is the \nminimum possible.\n\nInput : arr[] = {10, 20, 30, 40}\nOutput : 10\nExplanation: |10 - 20| = 10 which is the \nminimum, 2 3 or 3 4 can be the answers also. " }, { "code": null, "e": 791, "s": 485, "text": "Initially consider the minimum value to be of first and second elements. Traverse from second element to last. Check the difference of every adjacent pair and store the minimum value. When last element is reached, check its difference with first element.Below is the implementation of the above approach. " }, { "code": null, "e": 795, "s": 791, "text": "C++" }, { "code": null, "e": 800, "s": 795, "text": "Java" }, { "code": null, "e": 808, "s": 800, "text": "Python3" }, { "code": null, "e": 811, "s": 808, "text": "C#" }, { "code": null, "e": 815, "s": 811, "text": "PHP" }, { "code": null, "e": 826, "s": 815, "text": "Javascript" }, { "code": "// C++ program to find maximum difference// between adjacent elements in a circular array.#include <bits/stdc++.h>using namespace std; void minAdjDifference(int arr[], int n){ if (n < 2) return; // Checking normal adjacent elements int res = abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = min(res, abs(arr[i] - arr[i - 1])); // Checking circular link res = min(res, abs(arr[n - 1] - arr[0])); cout << \"Min Difference = \" << res;} // driver program to check the above functionint main(){ int a[] = { 10, 12, 13, 15, 10 }; int n = sizeof(a) / sizeof(a[0]); minAdjDifference(a, n); return 0;}", "e": 1475, "s": 826, "text": null }, { "code": "// Java program to find maximum difference// between adjacent elements in a circular// array.class GFG { static void minAdjDifference(int arr[], int n) { if (n < 2) return; // Checking normal adjacent elements int res = Math.abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = Math.min(res, Math.abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.min(res, Math.abs(arr[n - 1] - arr[0])); System.out.print(\"Min Difference = \" + res); } // driver code public static void main(String arg[]) { int a[] = { 10, 12, 13, 15, 10 }; int n = a.length; minAdjDifference(a, n); }} // This code is contributed by Anant Agarwal// and improved by Anuj Sharma.", "e": 2257, "s": 1475, "text": null }, { "code": "# Python3 program to find maximum# difference between adjacent# elements in a circular array. def minAdjDifference(arr, n): if (n < 2): return # Checking normal adjacent elements res = abs(arr[1] - arr[0]) for i in range(2, n): res = min(res, abs(arr[i] - arr[i - 1])) # Checking circular link res = min(res, abs(arr[n - 1] - arr[0])) print(\"Min Difference = \", res) # Driver Codea = [10, 12, 13, 15, 10]n = len(a)minAdjDifference(a, n) # This code is contributed by Anant Agarwal# and improved by Anuj Sharma.", "e": 2805, "s": 2257, "text": null }, { "code": "// C# program to find maximum difference// between adjacent elements in a circular array.using System; class GFG { static void minAdjDifference(int[] arr, int n) { if (n < 2) return; // Checking normal adjacent elements int res = Math.Abs(arr[1] - arr[0]); for (int i = 2; i < n; i++) res = Math.Min(res, Math.Abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.Min(res, Math.Abs(arr[n - 1] - arr[0])); Console.Write(\"Min Difference = \" + res); } // driver code public static void Main() { int[] a = { 10, 12, 13, 15, 10 }; int n = a.Length; minAdjDifference(a, n); }} // This code is contributed by Anant Agarwal// and improved by Anuj Sharma.", "e": 3580, "s": 2805, "text": null }, { "code": "<?php// PHP program to find maximum// difference between adjacent// elements in a circular array. function minAdjDifference($arr, $n){ if ($n < 2) return; // Checking normal // adjacent elements $res = abs($arr[1] - $arr[0]); for ($i = 2; $i < $n; $i++) $res = min($res, abs($arr[$i] - $arr[$i - 1])); // Checking circular link $res = min($res, abs($arr[$n - 1] - $arr[0])); echo \"Min Difference = \", $res;} // Driver Code$a = array(10, 12, 13, 15, 10);$n = count($a);minAdjDifference($a, $n); //This code is contributed by anuj_67//and improved by Anuj Sharma.?>", "e": 4245, "s": 3580, "text": null }, { "code": "<script> // Javascript program to find maximum difference// between adjacent elements in a circular array. function minAdjDifference( arr, n){ if (n < 2) return; // Checking normal adjacent elements let res = Math.abs(arr[1] - arr[0]); for (let i = 2; i < n; i++) res = Math.min(res, Math.abs(arr[i] - arr[i - 1])); // Checking circular link res = Math.min(res, Math.abs(arr[n - 1] - arr[0])); document.write(\"Min Difference = \" + res);} // driver code let a = [ 10, 12, 13, 15, 10 ]; let n = a.length; minAdjDifference(a, n); </script>", "e": 4830, "s": 4245, "text": null }, { "code": null, "e": 4839, "s": 4830, "text": "Output: " }, { "code": null, "e": 4859, "s": 4839, "text": "Min Difference = 0" }, { "code": null, "e": 4926, "s": 4859, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 4987, "s": 4926, "text": "Auxiliary Space: O(1), as we are not using any extra space. " }, { "code": null, "e": 5006, "s": 4987, "text": "https://youtu.be/G" }, { "code": null, "e": 5433, "s": 5006, "text": "-vouVriEvY This article is contributed by striver. 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": 5438, "s": 5433, "text": "vt_m" }, { "code": null, "e": 5450, "s": 5438, "text": "Anuj_Sharma" }, { "code": null, "e": 5464, "s": 5450, "text": "jana_sayantan" }, { "code": null, "e": 5472, "s": 5464, "text": "rohan07" }, { "code": null, "e": 5487, "s": 5472, "text": "circular-array" }, { "code": null, "e": 5494, "s": 5487, "text": "Arrays" }, { "code": null, "e": 5504, "s": 5494, "text": "Searching" }, { "code": null, "e": 5511, "s": 5504, "text": "Arrays" }, { "code": null, "e": 5521, "s": 5511, "text": "Searching" } ]
Searching Books with Python
19 Aug, 2021 In this article, we are going to write python scripts for searching books using isbntools modules. isbntools module able to search for books by there name or ISBN( International Standard Book Number) and return all the information about the book. Installation: Run the following pip command: pip install isbntools Importing the module: Python3 from isbntools.app import * 1. Use isbn_from_words() function to get the ISBN for a book. Syntax: isbn_from_words(str) Parameter: book name Returns: ISBN of the book. Python3 get_isbn = isbn_from_words("Half Girlfriend")print(get_isbn) Output: 9788129135728 2. Get the information of a book by its ISBN. Syntax: registry.bibformatters[identifiers](meta(isbn)) Parameter: ISB Number of the book Returns: the meta information of the book Notes: Identifiers can be used to print different types of format (bibtex, csl, opf, msword, endnote, refworks, json). Python3 print(registry.bibformatters['labels'](meta("9788129135728"))) Output: 3. If you want to print the object without identifiers then you will all object in a specific location. Python3 print(registry.bibformatters) Output: 4. Get information in JSON format: Python3 print(registry.bibformatters['json'](meta("9788129135728"))) Output: 5. Get information in MS Word format: Python3 print(registry.bibformatters['msword'](meta("9788129135728"))) Output: rajeev0719singh python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2021" }, { "code": null, "e": 275, "s": 28, "text": "In this article, we are going to write python scripts for searching books using isbntools modules. isbntools module able to search for books by there name or ISBN( International Standard Book Number) and return all the information about the book." }, { "code": null, "e": 320, "s": 275, "text": "Installation: Run the following pip command:" }, { "code": null, "e": 342, "s": 320, "text": "pip install isbntools" }, { "code": null, "e": 364, "s": 342, "text": "Importing the module:" }, { "code": null, "e": 372, "s": 364, "text": "Python3" }, { "code": "from isbntools.app import *", "e": 400, "s": 372, "text": null }, { "code": null, "e": 465, "s": 403, "text": "1. Use isbn_from_words() function to get the ISBN for a book." }, { "code": null, "e": 497, "s": 467, "text": "Syntax: isbn_from_words(str) " }, { "code": null, "e": 518, "s": 497, "text": "Parameter: book name" }, { "code": null, "e": 545, "s": 518, "text": "Returns: ISBN of the book." }, { "code": null, "e": 555, "s": 547, "text": "Python3" }, { "code": "get_isbn = isbn_from_words(\"Half Girlfriend\")print(get_isbn)", "e": 616, "s": 555, "text": null }, { "code": null, "e": 627, "s": 619, "text": "Output:" }, { "code": null, "e": 643, "s": 629, "text": "9788129135728" }, { "code": null, "e": 691, "s": 645, "text": "2. Get the information of a book by its ISBN." }, { "code": null, "e": 749, "s": 693, "text": "Syntax: registry.bibformatters[identifiers](meta(isbn))" }, { "code": null, "e": 783, "s": 749, "text": "Parameter: ISB Number of the book" }, { "code": null, "e": 825, "s": 783, "text": "Returns: the meta information of the book" }, { "code": null, "e": 946, "s": 827, "text": "Notes: Identifiers can be used to print different types of format (bibtex, csl, opf, msword, endnote, refworks, json)." }, { "code": null, "e": 956, "s": 948, "text": "Python3" }, { "code": "print(registry.bibformatters['labels'](meta(\"9788129135728\")))", "e": 1019, "s": 956, "text": null }, { "code": null, "e": 1030, "s": 1022, "text": "Output:" }, { "code": null, "e": 1138, "s": 1034, "text": "3. If you want to print the object without identifiers then you will all object in a specific location." }, { "code": null, "e": 1148, "s": 1140, "text": "Python3" }, { "code": "print(registry.bibformatters)", "e": 1178, "s": 1148, "text": null }, { "code": null, "e": 1189, "s": 1181, "text": "Output:" }, { "code": null, "e": 1228, "s": 1193, "text": "4. Get information in JSON format:" }, { "code": null, "e": 1238, "s": 1230, "text": "Python3" }, { "code": "print(registry.bibformatters['json'](meta(\"9788129135728\")))", "e": 1299, "s": 1238, "text": null }, { "code": null, "e": 1310, "s": 1302, "text": "Output:" }, { "code": null, "e": 1352, "s": 1314, "text": "5. Get information in MS Word format:" }, { "code": null, "e": 1362, "s": 1354, "text": "Python3" }, { "code": "print(registry.bibformatters['msword'](meta(\"9788129135728\")))", "e": 1425, "s": 1362, "text": null }, { "code": null, "e": 1436, "s": 1428, "text": "Output:" }, { "code": null, "e": 1456, "s": 1440, "text": "rajeev0719singh" }, { "code": null, "e": 1471, "s": 1456, "text": "python-utility" }, { "code": null, "e": 1478, "s": 1471, "text": "Python" } ]
Treemap in Pygal
28 Jul, 2020 Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. Treemap is a chart that is used for displaying echelons data using planted figures mainly rectangles. Each branch of the tree is in rectangular form and then which is macadamize with smaller rectangles to represent sub-branches. The color and the pattern are fixed in such a way in a treemap structure, that it won’t be difficult to understand the material. The second advantage of making treemap is they take less space in layout and can display thousands of items on a screen simultaneously. It can be created using Treemap() method. Syntax: treemap = pygal.Treemap() Example 1: # importing pygalimport pygalimport numpy # creating the chart objecttreemap = pygal.Treemap() # naming the titletreemap.title = 'Treemap' # Random datatreemap.add('A', numpy.random.rand(5))treemap.add('B', numpy.random.rand(5))treemap.add('C', numpy.random.rand(5))treemap.add('D', numpy.random.rand(5)) treemap Output: Example 2: # importing pygalimport pygalimport numpy # creating the chart objecttreemap = pygal.Treemap() # naming the titletreemap.title = 'Treemap' # Random datatreemap.add('A', [26, 22, 39, 39, 32, 30, 33, 24, 24, 30])treemap.add('B', [31, 40, None, None, None, None, 40, 32, 25, 31])treemap.add('C', [37, 27, 31, 20, None, 32, 24, 39, 29, 22])treemap.add('D', [38, None, 20, 29, 33, 23, 32, 33, 32, 23]) treemap Output: Data Visualization Python pygal-chart Python-pygal Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 306, "s": 28, "text": "Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write." }, { "code": null, "e": 842, "s": 306, "text": "Treemap is a chart that is used for displaying echelons data using planted figures mainly rectangles. Each branch of the tree is in rectangular form and then which is macadamize with smaller rectangles to represent sub-branches. The color and the pattern are fixed in such a way in a treemap structure, that it won’t be difficult to understand the material. The second advantage of making treemap is they take less space in layout and can display thousands of items on a screen simultaneously. It can be created using Treemap() method." }, { "code": null, "e": 850, "s": 842, "text": "Syntax:" }, { "code": null, "e": 876, "s": 850, "text": "treemap = pygal.Treemap()" }, { "code": null, "e": 887, "s": 876, "text": "Example 1:" }, { "code": "# importing pygalimport pygalimport numpy # creating the chart objecttreemap = pygal.Treemap() # naming the titletreemap.title = 'Treemap' # Random datatreemap.add('A', numpy.random.rand(5))treemap.add('B', numpy.random.rand(5))treemap.add('C', numpy.random.rand(5))treemap.add('D', numpy.random.rand(5)) treemap", "e": 1208, "s": 887, "text": null }, { "code": null, "e": 1216, "s": 1208, "text": "Output:" }, { "code": null, "e": 1227, "s": 1216, "text": "Example 2:" }, { "code": "# importing pygalimport pygalimport numpy # creating the chart objecttreemap = pygal.Treemap() # naming the titletreemap.title = 'Treemap' # Random datatreemap.add('A', [26, 22, 39, 39, 32, 30, 33, 24, 24, 30])treemap.add('B', [31, 40, None, None, None, None, 40, 32, 25, 31])treemap.add('C', [37, 27, 31, 20, None, 32, 24, 39, 29, 22])treemap.add('D', [38, None, 20, 29, 33, 23, 32, 33, 32, 23]) treemap", "e": 1646, "s": 1227, "text": null }, { "code": null, "e": 1654, "s": 1646, "text": "Output:" }, { "code": null, "e": 1673, "s": 1654, "text": "Data Visualization" }, { "code": null, "e": 1692, "s": 1673, "text": "Python pygal-chart" }, { "code": null, "e": 1705, "s": 1692, "text": "Python-pygal" }, { "code": null, "e": 1712, "s": 1705, "text": "Python" }, { "code": null, "e": 1810, "s": 1712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1842, "s": 1810, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1869, "s": 1842, "text": "Python Classes and Objects" }, { "code": null, "e": 1890, "s": 1869, "text": "Python OOPs Concepts" }, { "code": null, "e": 1913, "s": 1890, "text": "Introduction To PYTHON" }, { "code": null, "e": 1969, "s": 1913, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2000, "s": 1969, "text": "Python | os.path.join() method" }, { "code": null, "e": 2042, "s": 2000, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2084, "s": 2042, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2123, "s": 2084, "text": "Python | datetime.timedelta() function" } ]
Python – Row with Minimum difference in extreme values
11 Oct, 2020 Given a Matrix, extract the rows with a minimum difference in extreme values. Examples: Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]] Output : [[1, 4, 6], [5, 0]] Explanation : 6 – 1 = 5, 5 – 0 = 5, is minimum difference between extreme values. Input : test_list = [[4, 10, 18], [5, 0], [2, 4, 6], [19, 2]] Output : [[2, 4, 6]] Explanation : 6 – 2 = 4, is min diff. Method #1 : Using list comprehension + min() In this, we compute minimum difference between extreme values, and then use list comprehension to get particular row with that value difference between extreme values. Python3 # Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]] # printing original listprint("The original list is : " + str(test_list)) # getting min value min_val = min([max(sub) - min(sub) for sub in test_list]) # using list comprehension to filter res = [sub for sub in test_list if max(sub) - min(sub) == min_val] # printing result print("Rows with Minimum difference in extreme values : " + str(res)) Output: The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]] Method #2 : Using min() + list comprehension + filter() + lambda In this, we perform task of filtering comparing with minimum value using filter() + lambda. Python3 # Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension + filter() + lambda # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]] # printing original listprint("The original list is : " + str(test_list)) # getting min value min_val = min([max(sub) - min(sub) for sub in test_list]) # using filter() + lambda to filter res = list(filter(lambda sub : max(sub) - min(sub) == min_val, test_list)) # printing result print("Rows with Minimum difference in extreme values : " + str(res)) Output: The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 106, "s": 28, "text": "Given a Matrix, extract the rows with a minimum difference in extreme values." }, { "code": null, "e": 116, "s": 106, "text": "Examples:" }, { "code": null, "e": 290, "s": 116, "text": "Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]] Output : [[1, 4, 6], [5, 0]] Explanation : 6 – 1 = 5, 5 – 0 = 5, is minimum difference between extreme values. " }, { "code": null, "e": 412, "s": 290, "text": "Input : test_list = [[4, 10, 18], [5, 0], [2, 4, 6], [19, 2]] Output : [[2, 4, 6]] Explanation : 6 – 2 = 4, is min diff. " }, { "code": null, "e": 457, "s": 412, "text": "Method #1 : Using list comprehension + min()" }, { "code": null, "e": 625, "s": 457, "text": "In this, we compute minimum difference between extreme values, and then use list comprehension to get particular row with that value difference between extreme values." }, { "code": null, "e": 633, "s": 625, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # getting min value min_val = min([max(sub) - min(sub) for sub in test_list]) # using list comprehension to filter res = [sub for sub in test_list if max(sub) - min(sub) == min_val] # printing result print(\"Rows with Minimum difference in extreme values : \" + str(res))", "e": 1184, "s": 633, "text": null }, { "code": null, "e": 1192, "s": 1184, "text": "Output:" }, { "code": null, "e": 1321, "s": 1192, "text": "The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]]" }, { "code": null, "e": 1386, "s": 1321, "text": "Method #2 : Using min() + list comprehension + filter() + lambda" }, { "code": null, "e": 1478, "s": 1386, "text": "In this, we perform task of filtering comparing with minimum value using filter() + lambda." }, { "code": null, "e": 1486, "s": 1478, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension + filter() + lambda # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # getting min value min_val = min([max(sub) - min(sub) for sub in test_list]) # using filter() + lambda to filter res = list(filter(lambda sub : max(sub) - min(sub) == min_val, test_list)) # printing result print(\"Rows with Minimum difference in extreme values : \" + str(res))", "e": 2064, "s": 1486, "text": null }, { "code": null, "e": 2072, "s": 2064, "text": "Output:" }, { "code": null, "e": 2201, "s": 2072, "text": "The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]]" }, { "code": null, "e": 2222, "s": 2201, "text": "Python list-programs" }, { "code": null, "e": 2229, "s": 2222, "text": "Python" }, { "code": null, "e": 2245, "s": 2229, "text": "Python Programs" } ]
Simple sorting of a list of objects by a specific property using Python | by Gibson Tang | Towards Data Science
In my rudimentary experiments with Python and Data modeling where I have to import data into my Jupyter notebook. I thought of sorting and it occurred to me how do you sort a list of objects using a specific instance variable, such as name. For example, I have a list of car objects which consist of name and price. So I want to produce a list where the results are sorted in alphabetical order using the name of the car like so. And I didn’t want to use any libraries, so no import for me then. Googling didn’t return me much information as the results returned plenty of information on sorting of numbers, some results regarding sorting of words, and no satisfactory result of sorting of a word which is part of an instance variable. So I decided to have a crack at it. Python is not something that I am required to do in my day job. But I do use Python for the occasional scripting when there is a need for it. So I thought that I would have a crack at it. So this is how I would have approached the problem and my example code is shown below First, I would declare a class of cars and create a list to insert these objects class cars: def __init__(self, name, price): self.name = name self.price = price unsorted_cars = []unsorted_cars.append(cars('Ford', 20000))unsorted_cars.append(cars('Volvo', 50000))unsorted_cars.append(cars('BMW', 24000)) unsorted_cars.append(cars('Toyota', 15000)) unsorted_cars.append(cars('Kia', 12000)) unsorted_cars.append(cars('Audi', 40000)) unsorted_cars.append(cars('Tesla', 30000)) And since I want to sort the list by the name of the card, I created an empty list and put in the car names into that list and use the standard sort function to sort the list sorted_car_name = []for car in unsorted_cars: sorted_car_name.append(car.name)sorted_car_name.sort() This will then return a sorted list of car names in alphabetical order. Finally, now that I have the list of sorted names. I can use this as a reference to get the list of sort car objects using this double for loop to iterate through the unsorted_cars list and use the name instance variable in each car object to compare against each word in the sorted_car_name list and then insert it into a new empty list sorted_car_list if there is a match sorted_car = []for sort_car in sorted_car_name: for unsorted_car in unsorted_cars: if unsorted_car.name == sort_car: sorted_car.append(unsorted_car) break sorted_car_list now will then have the final list of cars sorted by the car name in alphabetical order as shown in table 2 above. Do note that this method is not very efficient due to the double for loop where we loop through the list of cart objects in unsorted_cars and then loop through each word in sorted_car_name and do a comparison to see if there is a match and then we insert that unsorted_car object into the sorted_car list. You can download the sample Python code here. To run the code, just go to your command line and type ‘python python_sort_sample.py’ and it will print out the list of unsorted cars and the final sorted cars. I hope this can be helpful to any Python folk out there. A friend of mind, Ruiwen, just pointed out to me that Python has a sorted() function that can be used. The sorted() function takes in a list of objects, the key to sort by and returns the sorted list. This function uses Lamba which creates an anonymous function. So to sort our unsorted list of car names, we use result_list = sorted(unsorted_cars, key=lambda cars: cars.name)for car in result_list: print(car.name + " and price is " + str(car.price)) So, by passing in the list of unsorted cars, and the anonymous function and the attribute to sort by, which is the name of the car. We will get the sorted list in result_list. This is a much better way of sorting, although the usage of the Lamba veers your Python code into the functional programming paradigm. I have updated my sample code and included the sorted() method here in this gist https://gist.github.com/gibtang/83f9681b525908900ec4b490992f032d Some related links to the sorted functionhttps://julien.danjou.info/python-functional-programming-lambda/https://docs.python.org/3/howto/sorting.htmlhttps://www.w3schools.com/python/ref_func_sorted.asp
[ { "code": null, "e": 487, "s": 171, "text": "In my rudimentary experiments with Python and Data modeling where I have to import data into my Jupyter notebook. I thought of sorting and it occurred to me how do you sort a list of objects using a specific instance variable, such as name. For example, I have a list of car objects which consist of name and price." }, { "code": null, "e": 667, "s": 487, "text": "So I want to produce a list where the results are sorted in alphabetical order using the name of the car like so. And I didn’t want to use any libraries, so no import for me then." }, { "code": null, "e": 1131, "s": 667, "text": "Googling didn’t return me much information as the results returned plenty of information on sorting of numbers, some results regarding sorting of words, and no satisfactory result of sorting of a word which is part of an instance variable. So I decided to have a crack at it. Python is not something that I am required to do in my day job. But I do use Python for the occasional scripting when there is a need for it. So I thought that I would have a crack at it." }, { "code": null, "e": 1217, "s": 1131, "text": "So this is how I would have approached the problem and my example code is shown below" }, { "code": null, "e": 1298, "s": 1217, "text": "First, I would declare a class of cars and create a list to insert these objects" }, { "code": null, "e": 1710, "s": 1298, "text": "class cars: def __init__(self, name, price): self.name = name self.price = price unsorted_cars = []unsorted_cars.append(cars('Ford', 20000))unsorted_cars.append(cars('Volvo', 50000))unsorted_cars.append(cars('BMW', 24000)) unsorted_cars.append(cars('Toyota', 15000)) unsorted_cars.append(cars('Kia', 12000)) unsorted_cars.append(cars('Audi', 40000)) unsorted_cars.append(cars('Tesla', 30000))" }, { "code": null, "e": 1885, "s": 1710, "text": "And since I want to sort the list by the name of the card, I created an empty list and put in the car names into that list and use the standard sort function to sort the list" }, { "code": null, "e": 1987, "s": 1885, "text": "sorted_car_name = []for car in unsorted_cars: \tsorted_car_name.append(car.name)sorted_car_name.sort()" }, { "code": null, "e": 2433, "s": 1987, "text": "This will then return a sorted list of car names in alphabetical order. Finally, now that I have the list of sorted names. I can use this as a reference to get the list of sort car objects using this double for loop to iterate through the unsorted_cars list and use the name instance variable in each car object to compare against each word in the sorted_car_name list and then insert it into a new empty list sorted_car_list if there is a match" }, { "code": null, "e": 2595, "s": 2433, "text": "sorted_car = []for sort_car in sorted_car_name: \tfor unsorted_car in unsorted_cars:\t\tif unsorted_car.name == sort_car:\t\t\tsorted_car.append(unsorted_car)\t\t\tbreak" }, { "code": null, "e": 3031, "s": 2595, "text": "sorted_car_list now will then have the final list of cars sorted by the car name in alphabetical order as shown in table 2 above. Do note that this method is not very efficient due to the double for loop where we loop through the list of cart objects in unsorted_cars and then loop through each word in sorted_car_name and do a comparison to see if there is a match and then we insert that unsorted_car object into the sorted_car list." }, { "code": null, "e": 3295, "s": 3031, "text": "You can download the sample Python code here. To run the code, just go to your command line and type ‘python python_sort_sample.py’ and it will print out the list of unsorted cars and the final sorted cars. I hope this can be helpful to any Python folk out there." }, { "code": null, "e": 3608, "s": 3295, "text": "A friend of mind, Ruiwen, just pointed out to me that Python has a sorted() function that can be used. The sorted() function takes in a list of objects, the key to sort by and returns the sorted list. This function uses Lamba which creates an anonymous function. So to sort our unsorted list of car names, we use" }, { "code": null, "e": 3754, "s": 3608, "text": "result_list = sorted(unsorted_cars, key=lambda cars: cars.name)for car in result_list: print(car.name + \" and price is \" + str(car.price))" }, { "code": null, "e": 4065, "s": 3754, "text": "So, by passing in the list of unsorted cars, and the anonymous function and the attribute to sort by, which is the name of the car. We will get the sorted list in result_list. This is a much better way of sorting, although the usage of the Lamba veers your Python code into the functional programming paradigm." }, { "code": null, "e": 4211, "s": 4065, "text": "I have updated my sample code and included the sorted() method here in this gist https://gist.github.com/gibtang/83f9681b525908900ec4b490992f032d" } ]
Bootstrap 5 | Card - GeeksforGeeks
29 Nov, 2021 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. The card is a component provided by Bootstrap 5 which provides a flexible and extensible content container with multiple variants and options. It includes options for headers and footers. Cards support a wide variety of content, including images, text, list groups, links, and more. Syntax: <div class="card"> Card Content ... <div> Basic Card: The basic building block of a card is the card-body and with card class as parent we can create a basic card. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <div class="card-body"> A computer science portal for geeks </div> </div> </div> </div> </body></html> Output: Header and Footer: The card-header provides header to the cards and card-footer provides footer to the cards as given below. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <div class="card-header">Header</div> <div class="card-body">Content</div> <div class="card-footer">Footer</div> </div> </div> </div> </body></html> Output: Title and Links: The card-title is used to give a title to the card and card-link is used to provide link to the card if required in it. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <div class="card-body"> <h4 class="card-title"> Card title</h4> <p class="card-text"> Some example text. Some example text.</p> <a href="#" class="card-link"> Card link</a> <a href="#" class="card-link"> Another link</a> </div> </div> </div> </div> </body></html> Output: Images: The images to the card are inserted with card-img-top and with card-img-bottom with the help of these two and img tag is used with it to add the image. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> <div class="card-body"> <h4 class="card-title">Developer Guy</h4> <p class="card-text">Developer Guy love to develope front-end and back-end</p> <a href="#" class="btn btn-primary"> See Profile</a> </div> </div> </div> </div> </body></html> Output: Example of image in the button: Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <div class="card-body"> <h4 class="card-title">Developer Guy</h4> <p class="card-text">Developer Guy love to develope front-end and back-end</p> <a href="#" class="btn btn-primary">See Profile</a> </div> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> </div> </div> </div> </body></html> Output: Image Overlays: In this we have to use an extra class called the card-img-overlay in the same line of code which you have used for card images. This turns an image into a card background and overlays the card’s text. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card" style="width: 400px;"> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> <div class="card-img-overlay"> <div class="card-body"> <h4 class="card-title"> Developer Guy </h4> <p class="card-text" style="color: red;"> Developer Guy love to develope front-end and back-end</p> <a href="#" class="btn btn-primary"> See Profile </a> </div> </div> </div> </div> </div> </body></html> Output: Card Groups: Use card groups to render cards as a single, attached element with equal width and height columns. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card-group"> <div class="card" style="width: 200px;"> <div class="card-body"> <h4 class="card-title"> Developer Guy I </h4> <p class="card-text"> Developer Guy love to develop front-end and back-end</p> <a href="#" class="btn btn-primary"> See Profile </a> </div> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> </div> <div class="card" style="width: 200px;"> <div class="card-body"> <h4 class="card-title"> Developer Guy II </h4> <p class="card-text"> Developer Guy love to develop android apps</p> <a href="#" class="btn btn-primary"> See Profile </a> </div> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> </div> <div class="card" style="width: 200px;"> <div class="card-body"> <h4 class="card-title"> Developer Guy III </h4> <p class="card-text"> Developer Guy love to develop machine learning models </p> <a href="#" class="btn btn-primary"> See Profile</a> </div> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png" alt="Card image" style="width: 100%;" /> </div> </div> </div> </div> </body></html> Output: List groups: It creates a list of content in a card. Example: HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <ul class="list-group list-group-flush"> <li class="list-group-item"> Bootstrap</li> <li class="list-group-item"> HTML</li> <li class="list-group-item"> JavaScript</li> </ul> </div> </div> </div> </body></html> OUTPUT: Kitchen sink: It is name given to the type of card which consist everything thing in it, it’s a mix and match of multiple content to make your desired card Example: HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card"> <ul class="list-group list-group-flush"> <li class="list-group-item"> Bootstrap</li> <li class="list-group-item"> HTML</li> <li class="list-group-item"> JavaScript</li> </ul> <div class="card-body"> <a href="" class="class-link"> Cart</a> <a href="" class="class-link"> Add Item</a> </div> </div> </div> </div> </body></html> Output: Navigation: It adds navigation bar to the cards. Example: HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card-text-center"> <div class="card-header"> <ul class= "nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link active" href="#">Active</a> </li> <li class="nav-item"> <a class="nav-link" href="#">link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> <div class="card-block"> <h4 class="card-title">Title</h4> <p class="card-text"> This the th test area</p> <a href="#" btn-btn-primary> Click me</a> </div> </div> </div> </div> </body></html> Output: Another example in pills form: Example: HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container mt-3" style="width: 600px;"> <div class="card-text-center"> <div class="card-header"> <ul class= "nav nav-pills card-header-tabs"> <li class="nav-item"> <a class="nav-link active" href="#">Active</a> </li> <li class="nav-item"> <a class="nav-link" href="#">link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> <div class="card-block"> <h4 class="card-title">Title</h4> <p class="card-text"> This the th test area</p> <a href="#" btn-btn-primary>Click me</a> </div> </div> </div> </div> </body></html> Output: We can easily change the text alignment of any card or a specific part of a card in Bootstrap using the Bootstrap text alignment classes of Bootstrap. Here is a code example displaying the examples in which we have change the alignment of a whole card or specific part of a card using the text align classes. and Using the grid class utility , we can create a card where the card image and card body is horizontally placed instead of being vertically placed using the grid utility classes. This feature is also mobile friendly and also is useful for responsive websites. Here is an code example in which we have created a sample card where the image and the card body text is horizontally placed. HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> </head> <body> <div class="container mt-3"> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> </div> <div class="card mb-2" style="max-width: 540px;"> <div class="row g-0"> <div class="col-md-6"> <img src="gfg.jpg" class="img-fluid rounded-start" alt="..."> </div> <div class="col-md-6"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">The card body and the card image is placed horizontally.</p> </div> </div> </div> </div> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script></body> </html> We can change the color of the card using the background utility classes and the text-color classes in Bootstrap. <div class="card text-white bg-primary"></div> HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> </head> <body> <div class="container mt-3"> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> </div> <div class="card text-white bg-primary mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-white bg-secondary mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-white bg-success mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-white bg-danger mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script></body> </html> We can add borders to the cards using the border-utilities classes present in the Bootstrap Framework like border-primary , border-success, border-danger and many more. <div class="card border-primary"></div> HTML <html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> </head> <body> <div class="container mt-3"> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> </div> <div class="card border-primary text-primary mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-success border-success mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-secondary border-secondary mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class="card text-danger border-danger mb-3" style="max-width: 18rem;"> <div class="card-header">This is the card header</div> <div class="card-body"> <h5 class="card-title">This is card title</h5> <p class="card-text">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script></body> </html> Google Chrome Mozilla Firefox Safari Brave Browsers Opera Code_Mech prachisoda1234 saikatmohanta43434 surinderdawra388 Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28049, "s": 28021, "text": "\n29 Nov, 2021" }, { "code": null, "e": 28446, "s": 28049, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. The card is a component provided by Bootstrap 5 which provides a flexible and extensible content container with multiple variants and options. It includes options for headers and footers. Cards support a wide variety of content, including images, text, list groups, links, and more." }, { "code": null, "e": 28455, "s": 28446, "text": "Syntax: " }, { "code": null, "e": 28497, "s": 28455, "text": "<div class=\"card\"> Card Content ... <div>" }, { "code": null, "e": 28628, "s": 28497, "text": "Basic Card: The basic building block of a card is the card-body and with card class as parent we can create a basic card. Example:" }, { "code": null, "e": 28633, "s": 28628, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <div class=\"card-body\"> A computer science portal for geeks </div> </div> </div> </div> </body></html>", "e": 30118, "s": 28633, "text": null }, { "code": null, "e": 30127, "s": 30118, "text": "Output: " }, { "code": null, "e": 30263, "s": 30129, "text": "Header and Footer: The card-header provides header to the cards and card-footer provides footer to the cards as given below. Example:" }, { "code": null, "e": 30268, "s": 30263, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <div class=\"card-header\">Header</div> <div class=\"card-body\">Content</div> <div class=\"card-footer\">Footer</div> </div> </div> </div> </body></html>", "e": 31783, "s": 30268, "text": null }, { "code": null, "e": 31792, "s": 31783, "text": "Output: " }, { "code": null, "e": 31938, "s": 31792, "text": "Title and Links: The card-title is used to give a title to the card and card-link is used to provide link to the card if required in it. Example:" }, { "code": null, "e": 31943, "s": 31938, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <div class=\"card-body\"> <h4 class=\"card-title\"> Card title</h4> <p class=\"card-text\"> Some example text. Some example text.</p> <a href=\"#\" class=\"card-link\"> Card link</a> <a href=\"#\" class=\"card-link\"> Another link</a> </div> </div> </div> </div> </body></html>", "e": 33791, "s": 31943, "text": null }, { "code": null, "e": 33800, "s": 33791, "text": "Output: " }, { "code": null, "e": 33969, "s": 33800, "text": "Images: The images to the card are inserted with card-img-top and with card-img-bottom with the help of these two and img tag is used with it to add the image. Example:" }, { "code": null, "e": 33974, "s": 33969, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> <div class=\"card-body\"> <h4 class=\"card-title\">Developer Guy</h4> <p class=\"card-text\">Developer Guy love to develope front-end and back-end</p> <a href=\"#\" class=\"btn btn-primary\"> See Profile</a> </div> </div> </div> </div> </body></html>", "e": 36004, "s": 33974, "text": null }, { "code": null, "e": 36013, "s": 36004, "text": "Output: " }, { "code": null, "e": 36054, "s": 36013, "text": "Example of image in the button: Example:" }, { "code": null, "e": 36059, "s": 36054, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <div class=\"card-body\"> <h4 class=\"card-title\">Developer Guy</h4> <p class=\"card-text\">Developer Guy love to develope front-end and back-end</p> <a href=\"#\" class=\"btn btn-primary\">See Profile</a> </div> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> </div> </div> </div> </body></html>", "e": 38050, "s": 36059, "text": null }, { "code": null, "e": 38059, "s": 38050, "text": "Output: " }, { "code": null, "e": 38285, "s": 38059, "text": "Image Overlays: In this we have to use an extra class called the card-img-overlay in the same line of code which you have used for card images. This turns an image into a card background and overlays the card’s text. Example:" }, { "code": null, "e": 38290, "s": 38285, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\" style=\"width: 400px;\"> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> <div class=\"card-img-overlay\"> <div class=\"card-body\"> <h4 class=\"card-title\"> Developer Guy </h4> <p class=\"card-text\" style=\"color: red;\"> Developer Guy love to develope front-end and back-end</p> <a href=\"#\" class=\"btn btn-primary\"> See Profile </a> </div> </div> </div> </div> </div> </body></html>", "e": 40635, "s": 38290, "text": null }, { "code": null, "e": 40644, "s": 40635, "text": "Output: " }, { "code": null, "e": 40765, "s": 40644, "text": "Card Groups: Use card groups to render cards as a single, attached element with equal width and height columns. Example:" }, { "code": null, "e": 40770, "s": 40765, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card-group\"> <div class=\"card\" style=\"width: 200px;\"> <div class=\"card-body\"> <h4 class=\"card-title\"> Developer Guy I </h4> <p class=\"card-text\"> Developer Guy love to develop front-end and back-end</p> <a href=\"#\" class=\"btn btn-primary\"> See Profile </a> </div> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> </div> <div class=\"card\" style=\"width: 200px;\"> <div class=\"card-body\"> <h4 class=\"card-title\"> Developer Guy II </h4> <p class=\"card-text\"> Developer Guy love to develop android apps</p> <a href=\"#\" class=\"btn btn-primary\"> See Profile </a> </div> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> </div> <div class=\"card\" style=\"width: 200px;\"> <div class=\"card-body\"> <h4 class=\"card-title\"> Developer Guy III </h4> <p class=\"card-text\"> Developer Guy love to develop machine learning models </p> <a href=\"#\" class=\"btn btn-primary\"> See Profile</a> </div> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190530183756/Good-Habits-for-developers-programmers.png\" alt=\"Card image\" style=\"width: 100%;\" /> </div> </div> </div> </div> </body></html>", "e": 44960, "s": 40770, "text": null }, { "code": null, "e": 44969, "s": 44960, "text": "Output: " }, { "code": null, "e": 45033, "s": 44971, "text": "List groups: It creates a list of content in a card. Example:" }, { "code": null, "e": 45038, "s": 45033, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <ul class=\"list-group list-group-flush\"> <li class=\"list-group-item\"> Bootstrap</li> <li class=\"list-group-item\"> HTML</li> <li class=\"list-group-item\"> JavaScript</li> </ul> </div> </div> </div> </body></html>", "e": 46741, "s": 45038, "text": null }, { "code": null, "e": 46750, "s": 46741, "text": "OUTPUT: " }, { "code": null, "e": 46915, "s": 46750, "text": "Kitchen sink: It is name given to the type of card which consist everything thing in it, it’s a mix and match of multiple content to make your desired card Example:" }, { "code": null, "e": 46920, "s": 46915, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card\"> <ul class=\"list-group list-group-flush\"> <li class=\"list-group-item\"> Bootstrap</li> <li class=\"list-group-item\"> HTML</li> <li class=\"list-group-item\"> JavaScript</li> </ul> <div class=\"card-body\"> <a href=\"\" class=\"class-link\"> Cart</a> <a href=\"\" class=\"class-link\"> Add Item</a> </div> </div> </div> </div> </body></html>", "e": 48872, "s": 46920, "text": null }, { "code": null, "e": 48881, "s": 48872, "text": "Output: " }, { "code": null, "e": 48939, "s": 48881, "text": "Navigation: It adds navigation bar to the cards. Example:" }, { "code": null, "e": 48944, "s": 48939, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card-text-center\"> <div class=\"card-header\"> <ul class= \"nav nav-tabs card-header-tabs\"> <li class=\"nav-item\"> <a class=\"nav-link active\" href=\"#\">Active</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">link</a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Disabled</a> </li> </ul> </div> <div class=\"card-block\"> <h4 class=\"card-title\">Title</h4> <p class=\"card-text\"> This the th test area</p> <a href=\"#\" btn-btn-primary> Click me</a> </div> </div> </div> </div> </body></html>", "e": 51390, "s": 48944, "text": null }, { "code": null, "e": 51399, "s": 51390, "text": "Output: " }, { "code": null, "e": 51439, "s": 51399, "text": "Another example in pills form: Example:" }, { "code": null, "e": 51444, "s": 51439, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container mt-3\" style=\"width: 600px;\"> <div class=\"card-text-center\"> <div class=\"card-header\"> <ul class= \"nav nav-pills card-header-tabs\"> <li class=\"nav-item\"> <a class=\"nav-link active\" href=\"#\">Active</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">link</a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Disabled</a> </li> </ul> </div> <div class=\"card-block\"> <h4 class=\"card-title\">Title</h4> <p class=\"card-text\"> This the th test area</p> <a href=\"#\" btn-btn-primary>Click me</a> </div> </div> </div> </div> </body></html>", "e": 53891, "s": 51444, "text": null }, { "code": null, "e": 53900, "s": 53891, "text": "Output: " }, { "code": null, "e": 54051, "s": 53900, "text": "We can easily change the text alignment of any card or a specific part of a card in Bootstrap using the Bootstrap text alignment classes of Bootstrap." }, { "code": null, "e": 54209, "s": 54051, "text": "Here is a code example displaying the examples in which we have change the alignment of a whole card or specific part of a card using the text align classes." }, { "code": null, "e": 54213, "s": 54209, "text": "and" }, { "code": null, "e": 54471, "s": 54213, "text": "Using the grid class utility , we can create a card where the card image and card body is horizontally placed instead of being vertically placed using the grid utility classes. This feature is also mobile friendly and also is useful for responsive websites." }, { "code": null, "e": 54597, "s": 54471, "text": "Here is an code example in which we have created a sample card where the image and the card body text is horizontally placed." }, { "code": null, "e": 54602, "s": 54597, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> </head> <body> <div class=\"container mt-3\"> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> </div> <div class=\"card mb-2\" style=\"max-width: 540px;\"> <div class=\"row g-0\"> <div class=\"col-md-6\"> <img src=\"gfg.jpg\" class=\"img-fluid rounded-start\" alt=\"...\"> </div> <div class=\"col-md-6\"> <div class=\"card-body\"> <h5 class=\"card-title\">Card title</h5> <p class=\"card-text\">The card body and the card image is placed horizontally.</p> </div> </div> </div> </div> <!-- Bootstrap JS --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script></body> </html>", "e": 56169, "s": 54602, "text": null }, { "code": null, "e": 56284, "s": 56169, "text": "We can change the color of the card using the background utility classes and the text-color classes in Bootstrap. " }, { "code": null, "e": 56331, "s": 56284, "text": "<div class=\"card text-white bg-primary\"></div>" }, { "code": null, "e": 56336, "s": 56331, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> </head> <body> <div class=\"container mt-3\"> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> </div> <div class=\"card text-white bg-primary mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-white bg-secondary mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-white bg-success mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-white bg-danger mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <!-- Bootstrap JS --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script></body> </html>", "e": 58807, "s": 56336, "text": null }, { "code": null, "e": 58977, "s": 58807, "text": "We can add borders to the cards using the border-utilities classes present in the Bootstrap Framework like border-primary , border-success, border-danger and many more. " }, { "code": null, "e": 59017, "s": 58977, "text": "<div class=\"card border-primary\"></div>" }, { "code": null, "e": 59022, "s": 59017, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> </head> <body> <div class=\"container mt-3\"> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> </div> <div class=\"card border-primary text-primary mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-success border-success mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-secondary border-secondary mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <div class=\"card text-danger border-danger mb-3\" style=\"max-width: 18rem;\"> <div class=\"card-header\">This is the card header</div> <div class=\"card-body\"> <h5 class=\"card-title\">This is card title</h5> <p class=\"card-text\">This is the body of the card made using Bootstrap Classes.</p> </div> </div> <!-- Bootstrap JS --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script></body> </html>", "e": 61512, "s": 59022, "text": null }, { "code": null, "e": 61526, "s": 61512, "text": "Google Chrome" }, { "code": null, "e": 61542, "s": 61526, "text": "Mozilla Firefox" }, { "code": null, "e": 61549, "s": 61542, "text": "Safari" }, { "code": null, "e": 61564, "s": 61549, "text": "Brave Browsers" }, { "code": null, "e": 61570, "s": 61564, "text": "Opera" }, { "code": null, "e": 61580, "s": 61570, "text": "Code_Mech" }, { "code": null, "e": 61595, "s": 61580, "text": "prachisoda1234" }, { "code": null, "e": 61614, "s": 61595, "text": "saikatmohanta43434" }, { "code": null, "e": 61631, "s": 61614, "text": "surinderdawra388" }, { "code": null, "e": 61646, "s": 61631, "text": "Bootstrap-Misc" }, { "code": null, "e": 61656, "s": 61646, "text": "Bootstrap" }, { "code": null, "e": 61673, "s": 61656, "text": "Web Technologies" }, { "code": null, "e": 61771, "s": 61673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 61780, "s": 61771, "text": "Comments" }, { "code": null, "e": 61793, "s": 61780, "text": "Old Comments" }, { "code": null, "e": 61843, "s": 61793, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 61872, "s": 61843, "text": "Form validation using jQuery" }, { "code": null, "e": 61928, "s": 61872, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 61969, "s": 61928, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 62010, "s": 61969, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 62066, "s": 62010, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 62099, "s": 62066, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 62161, "s": 62099, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 62204, "s": 62161, "text": "How to fetch data from an API in ReactJS ?" } ]
Return true or false in a MySQL select if another field contains a string?
To return TRUE or FALSE if another field contains a string, use IF(). Let us first create a table mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (1.28 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Chris','Brown'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('David','Miller'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Adam','Smith'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+----------+ | FirstName | LastName | +-----------+----------+ | Chris | Brown | | David | Miller | | Adam | Smith | +-----------+----------+ 3 rows in set (0.00 sec) Following is the query to return true or false in a MySQL select if another field contains a string. Here, we are checking for string “Miller” − Mysql> select if(LastName=’Miller’,’Yes','No') AS LastName,FirstName from DemoTable; This will produce the following output − +----------+-----------+ | LastName | FirstName | +----------+-----------+ | No | Chris | | Yes | David | | No | Adam | +----------+-----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "To return TRUE or FALSE if another field contains a string, use IF(). Let us first create a table" }, { "code": null, "e": 1284, "s": 1160, "text": "mysql> create table DemoTable\n(\n FirstName varchar(100),\n LastName varchar(100)\n);\nQuery OK, 0 rows affected (1.28 sec)" }, { "code": null, "e": 1340, "s": 1284, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1610, "s": 1340, "text": "mysql> insert into DemoTable values('Chris','Brown');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('David','Miller');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('Adam','Smith');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1670, "s": 1610, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1701, "s": 1670, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1742, "s": 1701, "text": "This will produce the following output −" }, { "code": null, "e": 1942, "s": 1742, "text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| Chris | Brown |\n| David | Miller |\n| Adam | Smith |\n+-----------+----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2087, "s": 1942, "text": "Following is the query to return true or false in a MySQL select if another field contains a string. Here, we are checking for string “Miller” −" }, { "code": null, "e": 2172, "s": 2087, "text": "Mysql> select if(LastName=’Miller’,’Yes','No') AS LastName,FirstName from DemoTable;" }, { "code": null, "e": 2213, "s": 2172, "text": "This will produce the following output −" }, { "code": null, "e": 2416, "s": 2213, "text": "+----------+-----------+\n| LastName | FirstName |\n+----------+-----------+\n| No | Chris |\n| Yes | David |\n| No | Adam | \n+----------+-----------+\n3 rows in set (0.00 sec)" } ]
Python | Pandas DataFrame.transform
21 Feb, 2019 Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.transform() function call func on self producing a DataFrame with transformed values and that has the same axis length as self. Syntax: DataFrame.transform(func, axis=0, *args, **kwargs) Parameter :func : Function to use for transforming the dataaxis : {0 or ‘index’, 1 or ‘columns’}, default 0*args : Positional arguments to pass to func.**kwargs : Keyword arguments to pass to func. Returns : DataFrame Example #1 : Use DataFrame.transform() function to add 10 to each element in the dataframe. # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output : Now we will use DataFrame.transform() function to add 10 to each element of the dataframe. # add 10 to each element of the dataframeresult = df.transform(func = lambda x : x + 10) # Print the resultprint(result) Output : As we can see in the output, the DataFrame.transform() function has successfully added 10 to each element of the given Dataframe. Example #2 : Use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe. # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output : Now we will use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe. # pass a list of functionsresult = df.transform(func = ['sqrt', 'exp']) # Print the resultprint(result) Output :As we can see in the output, the DataFrame.transform() function has successfully performed the desired operation on the given dataframe. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 342, "s": 28, "text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas." }, { "code": null, "e": 487, "s": 342, "text": "Pandas DataFrame.transform() function call func on self producing a DataFrame with transformed values and that has the same axis length as self." }, { "code": null, "e": 546, "s": 487, "text": "Syntax: DataFrame.transform(func, axis=0, *args, **kwargs)" }, { "code": null, "e": 744, "s": 546, "text": "Parameter :func : Function to use for transforming the dataaxis : {0 or ‘index’, 1 or ‘columns’}, default 0*args : Positional arguments to pass to func.**kwargs : Keyword arguments to pass to func." }, { "code": null, "e": 764, "s": 744, "text": "Returns : DataFrame" }, { "code": null, "e": 856, "s": 764, "text": "Example #1 : Use DataFrame.transform() function to add 10 to each element in the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 1242, "s": 856, "text": null }, { "code": null, "e": 1251, "s": 1242, "text": "Output :" }, { "code": null, "e": 1342, "s": 1251, "text": "Now we will use DataFrame.transform() function to add 10 to each element of the dataframe." }, { "code": "# add 10 to each element of the dataframeresult = df.transform(func = lambda x : x + 10) # Print the resultprint(result)", "e": 1464, "s": 1342, "text": null }, { "code": null, "e": 1473, "s": 1464, "text": "Output :" }, { "code": null, "e": 1749, "s": 1473, "text": "As we can see in the output, the DataFrame.transform() function has successfully added 10 to each element of the given Dataframe. Example #2 : Use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 2135, "s": 1749, "text": null }, { "code": null, "e": 2144, "s": 2135, "text": "Output :" }, { "code": null, "e": 2289, "s": 2144, "text": "Now we will use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe." }, { "code": "# pass a list of functionsresult = df.transform(func = ['sqrt', 'exp']) # Print the resultprint(result)", "e": 2394, "s": 2289, "text": null }, { "code": null, "e": 2539, "s": 2394, "text": "Output :As we can see in the output, the DataFrame.transform() function has successfully performed the desired operation on the given dataframe." }, { "code": null, "e": 2563, "s": 2539, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2595, "s": 2563, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2609, "s": 2595, "text": "Python-pandas" }, { "code": null, "e": 2616, "s": 2609, "text": "Python" } ]
How To Track ISS (International Space Station) Using Python?
13 Jul, 2021 In this article, we will discuss how to track the current location of ISS(International Space Station) and then maps the location. We will write a script that will display the current location of ISS along with onboarded crew names. It works on API, it takes the current location of ISS in the form of latitude and longitude and then locates that value onto the map. It takes the value from the website at very 5 sec and then updates the value of latitude and longitude and thus also moves the ISS icon on the world map. The movement visible is very little but you can notice that movement in the gif below. This is possible by using some of the modules of python like JSON, urllib.requests, Webbrowser, Geocoder etc. Numerous functions are used to create this script. JSON: It is JavaScript Object Notation, python supports JSON through a built-in package called JSON. It is just similar to the dictionary in python. To use the functions of this module, import the JSON module into the script. pip install jsonlib Turtle: The Python turtle library contains all of the necessary methods and functions for creating our designs and images. pip install turtle urllib: urllib.request is a python module for fetching URLs (Uniform Resource Locators). This module offers a very simple interface, in the form of the urlopen function. It combines several modules to preprocess the URLsThis is capable of fetching URLs using a variety of different protocols. pip install urllib3 Time: This module performs a variety of time-related functions. See also the datetime and calendar modules for related functionality. pip install times Webbrowser: Users can view Web-based documents using the webbrowser module, which provides a high-level interface. This module includes URL-opening functions for interactive browser applications. pip install pycopy-webbrowser Geocoder: This module transforms the various place name descriptions into a location on the earth’s surface. Because each geocoding provider has its own JSON schema, it can be difficult to parse them all at times. Here this module will help us to retrieve latitude and longitude using just simple functions. pip install geocoder So now there is a problem with tracking ISS because it travels at a speed of almost 28000km/h. Thus, it takes only 90 minutes to complete 1 rotation around the earth. At such a speed, it becomes quite difficult to lock the exact coordinates. So here comes the API to solve this issue. API acts as an intermediate between the website and the program, thus providing the current time data for the program. In our case, API will provide us with the current location of ISS in earth’s orbit, so visit the link below as an API link for astronaut info. url = "http://api.open-notify.org/astros.json" Use urllib.request.urlopen() function inorder to open the API url and json.loads(.read()) function to read the data from the url. Python3 import json import turtleimport urllib.request import time import webbrowser import geocoder url = "http://api.open-notify.org/astros.json" response = urllib.request.urlopen(url) result = json.loads(response.read())result Output: {'people': [{'name': 'Mark Vande Hei', 'craft': 'ISS'}, {'name': 'Oleg Novitskiy', 'craft': 'ISS'}, {'name': 'Pyotr Dubrov', 'craft': 'ISS'}, {'name': 'Thomas Pesquet', 'craft': 'ISS'}, {'name': 'Megan McArthur', 'craft': 'ISS'}, {'name': 'Shane Kimbrough', 'craft': 'ISS'}, {'name': 'Akihiko Hoshide', 'craft': 'ISS'}, {'name': 'Nie Haisheng', 'craft': 'Tiangong'}, {'name': 'Liu Boming', 'craft': 'Tiangong'}, {'name': 'Tang Hongbo', 'craft': 'Tiangong'}], 'number': 10, 'message': 'success'} Create.txt file for astronauts info: Create iss.text file using an open() function in write mode and write the result(names & numbers of astronauts) as data inside the file. Python3 file = open("iss.txt", "w") file.write( "There are currently " + str(result["number"]) + " astronauts on the ISS: \n\n") people = result["people"]for p in people: file.write(p['name'] + " - on board" + "\n") Use geocoder.ip(‘me’) to know your current location in terms of latitude and longitude and after that using write the data in the file and then close the file using the file.close() function. Python3 # print long and latg = geocoder.ip('me') file.write("\nYour current lat / long is: " + str(g.latlng))file.close()webbrowser.open("iss.txt") Use turtle.screen() function to get access to the screen, then use screen.setup() to set the size and position of the output window. Use screen.setworldcoordinates() function to set the coordinates of all 4 corners on x, y-axis so that when iss reach out from reaches they appear again from another edge. Python3 screen = turtle.Screen()screen.setup(1280, 720)screen.setworldcoordinates(-180, -90, 180, 90) Set map as background pic using screen.bgpic() function and set iss image as turtle shape using screen.register_shape() function. Use it as an object and assign it as a shape using iss.shape() function, then set the angle of shape using iss.setheading() function. iss.penup() function indicates that their drawings. Thus, the turtle stops. The file can be downloaded: map.gif iss.gif Code: Python3 # load the world map imagescreen.bgpic("images\map.gif")screen.register_shape("images\iss.gif")iss = turtle.Turtle()iss.shape("images\iss.gif")iss.setheading(45)iss.penup() Access the current status of ISS using the API below: url = "http://api.open-notify.org/iss-now.json" Extract the current location of ISS in terms of latitude and longitude from the above API. This script below runs inside the while loop so you can see the updated position and movement of the ISS until you stop the program. Python3 # load the current status of the ISS in real-timeurl = "http://api.open-notify.org/iss-now.json"response = urllib.request.urlopen(url)result = json.loads(response.read()) # Extract the ISS locationlocation = result["iss_position"]lat = location['latitude']lon = location['longitude'] # Output lon and lat to the terminal in the # float formatlat = float(lat)lon = float(lon)print("\nLatitude: " + str(lat))print("\nLongitude: " + str(lon)) Update the position of ISS every 5 seconds by refreshing the latitude and longitude value from API. Python3 # Update the ISS location on the mapiss.goto(lon, lat) # Refresh each 5 secondstime.sleep(5) Below is the full implementation. Python3 # json convert the python dictionary # above into a jsonimport json import turtle # urllib.request fetch URLs using# a variety of different protocolsimport urllib.request import time # webbrowser provides a high-level interface# to allow displaying Web-based documents # to usersimport webbrowser # geocoder takes the data and locate these# locations in the mapimport geocoder url = "http://api.open-notify.org/astros.json" response = urllib.request.urlopen(url) result = json.loads(response.read())file = open("iss.txt", "w") file.write("There are currently " + # prints number of astronauts str(result["number"]) + " astronauts on the ISS: \n\n")people = result["people"] # prints names of crew for p in people: file.write(p['name'] + " - on board" + "\n") # print long and latg = geocoder.ip('me') file.write("\nYour current lat / long is: " + str(g.latlng))file.close()webbrowser.open("iss.txt") # Setup the world map in turtle modulescreen = turtle.Screen()screen.setup(1280, 720)screen.setworldcoordinates(-180, -90, 180, 90) # load the world map imagescreen.bgpic("images/map.gif")screen.register_shape("images\iss.gif")iss = turtle.Turtle()iss.shape("images\iss.gif")iss.setheading(45)iss.penup() while True: # load the current status of the ISS in real-time url = "http://api.open-notify.org/iss-now.json" response = urllib.request.urlopen(url) result = json.loads(response.read()) # Extract the ISS location location = result["iss_position"] lat = location['latitude'] lon = location['longitude'] # Ouput lon and lat to the terminal lat = float(lat) lon = float(lon) print("\nLatitude: " + str(lat)) print("\nLongitude: " + str(lon)) # Update the ISS location on the map iss.goto(lon, lat) # Refresh each 5 seconds time.sleep(5) Output: Crew Information: Here is info on the onboarded crew members along with their names. ISS Location: Here is a screenshot of the moving ISS i.e orbiting around the earth. You can see it by zooming in on the screenshot. ISS Moving look: Here you can see the ISS moving every 5 seconds. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2021" }, { "code": null, "e": 822, "s": 52, "text": "In this article, we will discuss how to track the current location of ISS(International Space Station) and then maps the location. We will write a script that will display the current location of ISS along with onboarded crew names. It works on API, it takes the current location of ISS in the form of latitude and longitude and then locates that value onto the map. It takes the value from the website at very 5 sec and then updates the value of latitude and longitude and thus also moves the ISS icon on the world map. The movement visible is very little but you can notice that movement in the gif below. This is possible by using some of the modules of python like JSON, urllib.requests, Webbrowser, Geocoder etc. Numerous functions are used to create this script. " }, { "code": null, "e": 1048, "s": 822, "text": "JSON: It is JavaScript Object Notation, python supports JSON through a built-in package called JSON. It is just similar to the dictionary in python. To use the functions of this module, import the JSON module into the script." }, { "code": null, "e": 1068, "s": 1048, "text": "pip install jsonlib" }, { "code": null, "e": 1191, "s": 1068, "text": "Turtle: The Python turtle library contains all of the necessary methods and functions for creating our designs and images." }, { "code": null, "e": 1210, "s": 1191, "text": "pip install turtle" }, { "code": null, "e": 1503, "s": 1210, "text": "urllib: urllib.request is a python module for fetching URLs (Uniform Resource Locators). This module offers a very simple interface, in the form of the urlopen function. It combines several modules to preprocess the URLsThis is capable of fetching URLs using a variety of different protocols." }, { "code": null, "e": 1523, "s": 1503, "text": "pip install urllib3" }, { "code": null, "e": 1657, "s": 1523, "text": "Time: This module performs a variety of time-related functions. See also the datetime and calendar modules for related functionality." }, { "code": null, "e": 1675, "s": 1657, "text": "pip install times" }, { "code": null, "e": 1871, "s": 1675, "text": "Webbrowser: Users can view Web-based documents using the webbrowser module, which provides a high-level interface. This module includes URL-opening functions for interactive browser applications." }, { "code": null, "e": 1901, "s": 1871, "text": "pip install pycopy-webbrowser" }, { "code": null, "e": 2209, "s": 1901, "text": "Geocoder: This module transforms the various place name descriptions into a location on the earth’s surface. Because each geocoding provider has its own JSON schema, it can be difficult to parse them all at times. Here this module will help us to retrieve latitude and longitude using just simple functions." }, { "code": null, "e": 2230, "s": 2209, "text": "pip install geocoder" }, { "code": null, "e": 2634, "s": 2230, "text": "So now there is a problem with tracking ISS because it travels at a speed of almost 28000km/h. Thus, it takes only 90 minutes to complete 1 rotation around the earth. At such a speed, it becomes quite difficult to lock the exact coordinates. So here comes the API to solve this issue. API acts as an intermediate between the website and the program, thus providing the current time data for the program." }, { "code": null, "e": 2777, "s": 2634, "text": "In our case, API will provide us with the current location of ISS in earth’s orbit, so visit the link below as an API link for astronaut info." }, { "code": null, "e": 2825, "s": 2777, "text": "url = \"http://api.open-notify.org/astros.json\" " }, { "code": null, "e": 2955, "s": 2825, "text": "Use urllib.request.urlopen() function inorder to open the API url and json.loads(.read()) function to read the data from the url." }, { "code": null, "e": 2963, "s": 2955, "text": "Python3" }, { "code": "import json import turtleimport urllib.request import time import webbrowser import geocoder url = \"http://api.open-notify.org/astros.json\" response = urllib.request.urlopen(url) result = json.loads(response.read())result", "e": 3187, "s": 2963, "text": null }, { "code": null, "e": 3195, "s": 3187, "text": "Output:" }, { "code": null, "e": 3710, "s": 3195, "text": "{'people': [{'name': 'Mark Vande Hei', 'craft': 'ISS'},\n {'name': 'Oleg Novitskiy', 'craft': 'ISS'},\n {'name': 'Pyotr Dubrov', 'craft': 'ISS'},\n {'name': 'Thomas Pesquet', 'craft': 'ISS'},\n {'name': 'Megan McArthur', 'craft': 'ISS'},\n {'name': 'Shane Kimbrough', 'craft': 'ISS'},\n {'name': 'Akihiko Hoshide', 'craft': 'ISS'},\n {'name': 'Nie Haisheng', 'craft': 'Tiangong'},\n {'name': 'Liu Boming', 'craft': 'Tiangong'},\n {'name': 'Tang Hongbo', 'craft': 'Tiangong'}],\n 'number': 10,\n 'message': 'success'}" }, { "code": null, "e": 3884, "s": 3710, "text": "Create.txt file for astronauts info: Create iss.text file using an open() function in write mode and write the result(names & numbers of astronauts) as data inside the file." }, { "code": null, "e": 3892, "s": 3884, "text": "Python3" }, { "code": "file = open(\"iss.txt\", \"w\") file.write( \"There are currently \" + str(result[\"number\"]) + \" astronauts on the ISS: \\n\\n\") people = result[\"people\"]for p in people: file.write(p['name'] + \" - on board\" + \"\\n\")", "e": 4107, "s": 3892, "text": null }, { "code": null, "e": 4299, "s": 4107, "text": "Use geocoder.ip(‘me’) to know your current location in terms of latitude and longitude and after that using write the data in the file and then close the file using the file.close() function." }, { "code": null, "e": 4307, "s": 4299, "text": "Python3" }, { "code": "# print long and latg = geocoder.ip('me') file.write(\"\\nYour current lat / long is: \" + str(g.latlng))file.close()webbrowser.open(\"iss.txt\")", "e": 4448, "s": 4307, "text": null }, { "code": null, "e": 4753, "s": 4448, "text": "Use turtle.screen() function to get access to the screen, then use screen.setup() to set the size and position of the output window. Use screen.setworldcoordinates() function to set the coordinates of all 4 corners on x, y-axis so that when iss reach out from reaches they appear again from another edge." }, { "code": null, "e": 4761, "s": 4753, "text": "Python3" }, { "code": "screen = turtle.Screen()screen.setup(1280, 720)screen.setworldcoordinates(-180, -90, 180, 90)", "e": 4855, "s": 4761, "text": null }, { "code": null, "e": 5195, "s": 4855, "text": "Set map as background pic using screen.bgpic() function and set iss image as turtle shape using screen.register_shape() function. Use it as an object and assign it as a shape using iss.shape() function, then set the angle of shape using iss.setheading() function. iss.penup() function indicates that their drawings. Thus, the turtle stops." }, { "code": null, "e": 5223, "s": 5195, "text": "The file can be downloaded:" }, { "code": null, "e": 5231, "s": 5223, "text": "map.gif" }, { "code": null, "e": 5239, "s": 5231, "text": "iss.gif" }, { "code": null, "e": 5245, "s": 5239, "text": "Code:" }, { "code": null, "e": 5253, "s": 5245, "text": "Python3" }, { "code": "# load the world map imagescreen.bgpic(\"images\\map.gif\")screen.register_shape(\"images\\iss.gif\")iss = turtle.Turtle()iss.shape(\"images\\iss.gif\")iss.setheading(45)iss.penup()", "e": 5426, "s": 5253, "text": null }, { "code": null, "e": 5480, "s": 5426, "text": "Access the current status of ISS using the API below:" }, { "code": null, "e": 5529, "s": 5480, "text": " url = \"http://api.open-notify.org/iss-now.json\"" }, { "code": null, "e": 5753, "s": 5529, "text": "Extract the current location of ISS in terms of latitude and longitude from the above API. This script below runs inside the while loop so you can see the updated position and movement of the ISS until you stop the program." }, { "code": null, "e": 5761, "s": 5753, "text": "Python3" }, { "code": "# load the current status of the ISS in real-timeurl = \"http://api.open-notify.org/iss-now.json\"response = urllib.request.urlopen(url)result = json.loads(response.read()) # Extract the ISS locationlocation = result[\"iss_position\"]lat = location['latitude']lon = location['longitude'] # Output lon and lat to the terminal in the # float formatlat = float(lat)lon = float(lon)print(\"\\nLatitude: \" + str(lat))print(\"\\nLongitude: \" + str(lon))", "e": 6203, "s": 5761, "text": null }, { "code": null, "e": 6303, "s": 6203, "text": "Update the position of ISS every 5 seconds by refreshing the latitude and longitude value from API." }, { "code": null, "e": 6311, "s": 6303, "text": "Python3" }, { "code": "# Update the ISS location on the mapiss.goto(lon, lat) # Refresh each 5 secondstime.sleep(5)", "e": 6405, "s": 6311, "text": null }, { "code": null, "e": 6439, "s": 6405, "text": "Below is the full implementation." }, { "code": null, "e": 6447, "s": 6439, "text": "Python3" }, { "code": "# json convert the python dictionary # above into a jsonimport json import turtle # urllib.request fetch URLs using# a variety of different protocolsimport urllib.request import time # webbrowser provides a high-level interface# to allow displaying Web-based documents # to usersimport webbrowser # geocoder takes the data and locate these# locations in the mapimport geocoder url = \"http://api.open-notify.org/astros.json\" response = urllib.request.urlopen(url) result = json.loads(response.read())file = open(\"iss.txt\", \"w\") file.write(\"There are currently \" + # prints number of astronauts str(result[\"number\"]) + \" astronauts on the ISS: \\n\\n\")people = result[\"people\"] # prints names of crew for p in people: file.write(p['name'] + \" - on board\" + \"\\n\") # print long and latg = geocoder.ip('me') file.write(\"\\nYour current lat / long is: \" + str(g.latlng))file.close()webbrowser.open(\"iss.txt\") # Setup the world map in turtle modulescreen = turtle.Screen()screen.setup(1280, 720)screen.setworldcoordinates(-180, -90, 180, 90) # load the world map imagescreen.bgpic(\"images/map.gif\")screen.register_shape(\"images\\iss.gif\")iss = turtle.Turtle()iss.shape(\"images\\iss.gif\")iss.setheading(45)iss.penup() while True: # load the current status of the ISS in real-time url = \"http://api.open-notify.org/iss-now.json\" response = urllib.request.urlopen(url) result = json.loads(response.read()) # Extract the ISS location location = result[\"iss_position\"] lat = location['latitude'] lon = location['longitude'] # Ouput lon and lat to the terminal lat = float(lat) lon = float(lon) print(\"\\nLatitude: \" + str(lat)) print(\"\\nLongitude: \" + str(lon)) # Update the ISS location on the map iss.goto(lon, lat) # Refresh each 5 seconds time.sleep(5)", "e": 8284, "s": 6447, "text": null }, { "code": null, "e": 8292, "s": 8284, "text": "Output:" }, { "code": null, "e": 8377, "s": 8292, "text": "Crew Information: Here is info on the onboarded crew members along with their names." }, { "code": null, "e": 8509, "s": 8377, "text": "ISS Location: Here is a screenshot of the moving ISS i.e orbiting around the earth. You can see it by zooming in on the screenshot." }, { "code": null, "e": 8575, "s": 8509, "text": "ISS Moving look: Here you can see the ISS moving every 5 seconds." }, { "code": null, "e": 8590, "s": 8575, "text": "python-utility" }, { "code": null, "e": 8597, "s": 8590, "text": "Python" } ]
itertools.groupby() in Python
30 Jan, 2020 Prerequisites: Python Itertools Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items. Syntax: itertools.groupby(iterable, key_func) Parameters:iterable: Iterable can be of any kind (list, tuple, dictionary).key: A function that calculates keys for each element present in iterable. Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged. Example 1: # Python code to demonstrate # itertools.groupby() method import itertools L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)] # Key functionkey_func = lambda x: x[0] for key, group in itertools.groupby(L, key_func): print(key + " :", list(group)) Output: a : [('a', 1), ('a', 2)] b : [('b', 3), ('b', 4)] Example 2 : # Python code to demonstrate # itertools.groupby() method import itertools a_list = [("Animal", "cat"), ("Animal", "dog"), ("Bird", "peacock"), ("Bird", "pigeon")] an_iterator = itertools.groupby(a_list, lambda x : x[0]) for key, group in an_iterator: key_and_group = {key : list(group)} print(key_and_group) Output {'Animal': [('Animal', 'cat'), ('Animal', 'dog')]} {'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]} Python-itertools Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jan, 2020" }, { "code": null, "e": 84, "s": 52, "text": "Prerequisites: Python Itertools" }, { "code": null, "e": 328, "s": 84, "text": "Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra." }, { "code": null, "e": 444, "s": 328, "text": "This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items." }, { "code": null, "e": 490, "s": 444, "text": "Syntax: itertools.groupby(iterable, key_func)" }, { "code": null, "e": 640, "s": 490, "text": "Parameters:iterable: Iterable can be of any kind (list, tuple, dictionary).key: A function that calculates keys for each element present in iterable." }, { "code": null, "e": 832, "s": 640, "text": "Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged." }, { "code": null, "e": 843, "s": 832, "text": "Example 1:" }, { "code": "# Python code to demonstrate # itertools.groupby() method import itertools L = [(\"a\", 1), (\"a\", 2), (\"b\", 3), (\"b\", 4)] # Key functionkey_func = lambda x: x[0] for key, group in itertools.groupby(L, key_func): print(key + \" :\", list(group))", "e": 1096, "s": 843, "text": null }, { "code": null, "e": 1104, "s": 1096, "text": "Output:" }, { "code": null, "e": 1155, "s": 1104, "text": "a : [('a', 1), ('a', 2)]\nb : [('b', 3), ('b', 4)]\n" }, { "code": null, "e": 1167, "s": 1155, "text": "Example 2 :" }, { "code": "# Python code to demonstrate # itertools.groupby() method import itertools a_list = [(\"Animal\", \"cat\"), (\"Animal\", \"dog\"), (\"Bird\", \"peacock\"), (\"Bird\", \"pigeon\")] an_iterator = itertools.groupby(a_list, lambda x : x[0]) for key, group in an_iterator: key_and_group = {key : list(group)} print(key_and_group)", "e": 1523, "s": 1167, "text": null }, { "code": null, "e": 1530, "s": 1523, "text": "Output" }, { "code": null, "e": 1634, "s": 1530, "text": "{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}\n{'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}\n" }, { "code": null, "e": 1651, "s": 1634, "text": "Python-itertools" }, { "code": null, "e": 1675, "s": 1651, "text": "Technical Scripter 2019" }, { "code": null, "e": 1682, "s": 1675, "text": "Python" }, { "code": null, "e": 1701, "s": 1682, "text": "Technical Scripter" }, { "code": null, "e": 1799, "s": 1701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1817, "s": 1799, "text": "Python Dictionary" }, { "code": null, "e": 1859, "s": 1817, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1881, "s": 1859, "text": "Enumerate() in Python" }, { "code": null, "e": 1916, "s": 1881, "text": "Read a file line by line in Python" }, { "code": null, "e": 1942, "s": 1916, "text": "Python String | replace()" }, { "code": null, "e": 1974, "s": 1942, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2003, "s": 1974, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2030, "s": 2003, "text": "Python Classes and Objects" }, { "code": null, "e": 2060, "s": 2030, "text": "Iterate over a list in Python" } ]
Using JWT for user authentication in Flask
17 May, 2022 Pre-requisite: Basic knowledge about JSON Web Token (JWT)I will be assuming you have the basic knowledge of JWT and how JWT works. If not, then I suggest reading the linked Geeksforgeeks article. Let’s jump right into the setup. Ofcourse, you need python3 installed on your system. Now, follow along with me. I will be using a virtual environment where I will install the libraries which is undoubtedly the best way of doing any kind of development. First create a folder named flask project and change directory to it. If you are on linux then type the following in your terminal. mkdir "flask project" && cd "flask project" Now, create a virtual environment. If you are on linux then type the following in your terminal. python3 -m venv env Note: If you get any error then that means venv isn’t installed in your system. To install it, type sudo apt install python3-venv in your terminal and then you are good to go. If you are on windows then use something like virtualenv to make a virtual environment. This will create a folder named venv in the flask project which will contain the project specific libraries. Now create a file named requirements.txt and add the following lines in it. Flask-RESTful==0.3.8 PyJWT==1.7.1 Flask-SQLAlchemy==2.4.1 Now, lets install these libraries for this project. To do so, first we need to activate the virtual environment. To do so, type the following in your terminal. source env/bin/activate Note: If you are on windows then it would be Scripts instead of binNow, its time to install the libraries. To do so, again type the following in your terminal. pip install -r requirements.txt Now, we are done with the setup part. Lets now start writing the actual code. Before beginning with the code, I would like to make something clear. I would be writing the entire code in a single file, i.e. the database models and the routes all together, which is not a good practice and definitely not manageable for larger projects. Try keeping creating separate python files or modules for routes and database models.With that cleared out, lets directly jump into the writing the actual code. I will be adding inline comments explaining every part of the code. Create a python file called app.py and type the following code in it. Python3 # flask importsfrom flask import Flask, request, jsonify, make_responsefrom flask_sqlalchemy import SQLAlchemyimport uuid # for public idfrom werkzeug.security import generate_password_hash, check_password_hash# imports for PyJWT authenticationimport jwtfrom datetime import datetime, timedeltafrom functools import wraps # creates Flask objectapp = Flask(__name__)# configuration# NEVER HARDCODE YOUR CONFIGURATION IN YOUR CODE# INSTEAD CREATE A .env FILE AND STORE IN ITapp.config['SECRET_KEY'] = 'your secret key'# database nameapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Database.db'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True# creates SQLALCHEMY objectdb = SQLAlchemy(app) # Database ORMsclass User(db.Model): id = db.Column(db.Integer, primary_key = True) public_id = db.Column(db.String(50), unique = True) name = db.Column(db.String(100)) email = db.Column(db.String(70), unique = True) password = db.Column(db.String(80)) # decorator for verifying the JWTdef token_required(f): @wraps(f) def decorated(*args, **kwargs): token = None # jwt is passed in the request header if 'x-access-token' in request.headers: token = request.headers['x-access-token'] # return 401 if token is not passed if not token: return jsonify({'message' : 'Token is missing !!'}), 401 try: # decoding the payload to fetch the stored details data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.query\ .filter_by(public_id = data['public_id'])\ .first() except: return jsonify({ 'message' : 'Token is invalid !!' }), 401 # returns the current logged in users contex to the routes return f(current_user, *args, **kwargs) return decorated # User Database Route# this route sends back list of [email protected]('/user', methods =['GET'])@token_requireddef get_all_users(current_user): # querying the database # for all the entries in it users = User.query.all() # converting the query objects # to list of jsons output = [] for user in users: # appending the user data json # to the response list output.append({ 'public_id': user.public_id, 'name' : user.name, 'email' : user.email }) return jsonify({'users': output}) # route for logging user [email protected]('/login', methods =['POST'])def login(): # creates dictionary of form data auth = request.form if not auth or not auth.get('email') or not auth.get('password'): # returns 401 if any email or / and password is missing return make_response( 'Could not verify', 401, {'WWW-Authenticate' : 'Basic realm ="Login required !!"'} ) user = User.query\ .filter_by(email = auth.get('email'))\ .first() if not user: # returns 401 if user does not exist return make_response( 'Could not verify', 401, {'WWW-Authenticate' : 'Basic realm ="User does not exist !!"'} ) if check_password_hash(user.password, auth.get('password')): # generates the JWT Token token = jwt.encode({ 'public_id': user.public_id, 'exp' : datetime.utcnow() + timedelta(minutes = 30) }, app.config['SECRET_KEY']) return make_response(jsonify({'token' : token.decode('UTF-8')}), 201) # returns 403 if password is wrong return make_response( 'Could not verify', 403, {'WWW-Authenticate' : 'Basic realm ="Wrong Password !!"'} ) # signup [email protected]('/signup', methods =['POST'])def signup(): # creates a dictionary of the form data data = request.form # gets name, email and password name, email = data.get('name'), data.get('email') password = data.get('password') # checking for existing user user = User.query\ .filter_by(email = email)\ .first() if not user: # database ORM object user = User( public_id = str(uuid.uuid4()), name = name, email = email, password = generate_password_hash(password) ) # insert user db.session.add(user) db.session.commit() return make_response('Successfully registered.', 201) else: # returns 202 if user already exists return make_response('User already exists. Please Log in.', 202) if __name__ == "__main__": # setting debug to True enables hot reload # and also provides a debugger shell # if you hit an error while running the server app.run(debug = True) Now, our code is ready. We now need to create the database first and then the table User from the ORM (Object Relational Mapping). To do so, first start the python3 interpreter in your terminal. You can do that by typing python3 in your terminal and that should do the trick for you. Next you need to type the following in your python3 interpreter: from app import db db.create_all() So, what this does is first it imports the database object and then calls the create_all() function to create all the tables from the ORM. It should look something like this. Now that our actual code is ready, let’s test it out. I recommend using postman for testing out the APIs. You can use something like CURL but I will be using postman for this tutorial. To start testing our api, first we need to run our API. To do so, open up a terminal window and type the following in it. python app.py You should see an output like this If you get any error then make sure all your syntax and indentation are correct. You can see that our api is running on http://localhost:5000/. Copy this url. We will use this urlalong with the routes to test the api.Now, open up Postman. You should be greated with the following screen. Now, click on the + sign and enter the url localhost:5000/signup change request type to POST, then select Body and then form-data and enter the data as key-value pair and then click on Send and you should get a response. It should look something like this. So, we are registered. Now lets login. To do that just change the endpoint to /login and untick the Name field and click on Send. You should get a JWT as a response. Note down that JWT. That will be our token and we will need to send that token along with every subsequent requests. This token will identify us as logged in. The JSON contains the token. Note it down. Next try to fetch the list of users. To do that, change the endpoint to /user and then in the headers section, add a field as x-access-token and add the JWT token in the value and click on Send. You will get the list of users as JSON. So, this is how you can perform authentication with JWT in Flask. I recommend you to practice more with JWTs and user authentication to get your concepts more clear. gabaa406 sooda367 kapoorsagar226 surinderdawra388 simmytarika5 sagartomar9927 Python Flask Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2022" }, { "code": null, "e": 248, "s": 52, "text": "Pre-requisite: Basic knowledge about JSON Web Token (JWT)I will be assuming you have the basic knowledge of JWT and how JWT works. If not, then I suggest reading the linked Geeksforgeeks article." }, { "code": null, "e": 502, "s": 248, "text": "Let’s jump right into the setup. Ofcourse, you need python3 installed on your system. Now, follow along with me. I will be using a virtual environment where I will install the libraries which is undoubtedly the best way of doing any kind of development." }, { "code": null, "e": 634, "s": 502, "text": "First create a folder named flask project and change directory to it. If you are on linux then type the following in your terminal." }, { "code": null, "e": 678, "s": 634, "text": "mkdir \"flask project\" && cd \"flask project\"" }, { "code": null, "e": 775, "s": 678, "text": "Now, create a virtual environment. If you are on linux then type the following in your terminal." }, { "code": null, "e": 795, "s": 775, "text": "python3 -m venv env" }, { "code": null, "e": 1059, "s": 795, "text": "Note: If you get any error then that means venv isn’t installed in your system. To install it, type sudo apt install python3-venv in your terminal and then you are good to go. If you are on windows then use something like virtualenv to make a virtual environment." }, { "code": null, "e": 1169, "s": 1059, "text": "This will create a folder named venv in the flask project which will contain the project specific libraries. " }, { "code": null, "e": 1245, "s": 1169, "text": "Now create a file named requirements.txt and add the following lines in it." }, { "code": null, "e": 1303, "s": 1245, "text": "Flask-RESTful==0.3.8\nPyJWT==1.7.1\nFlask-SQLAlchemy==2.4.1" }, { "code": null, "e": 1463, "s": 1303, "text": "Now, lets install these libraries for this project. To do so, first we need to activate the virtual environment. To do so, type the following in your terminal." }, { "code": null, "e": 1487, "s": 1463, "text": "source env/bin/activate" }, { "code": null, "e": 1648, "s": 1487, "text": "Note: If you are on windows then it would be Scripts instead of binNow, its time to install the libraries. To do so, again type the following in your terminal. " }, { "code": null, "e": 1680, "s": 1648, "text": "pip install -r requirements.txt" }, { "code": null, "e": 2244, "s": 1680, "text": "Now, we are done with the setup part. Lets now start writing the actual code. Before beginning with the code, I would like to make something clear. I would be writing the entire code in a single file, i.e. the database models and the routes all together, which is not a good practice and definitely not manageable for larger projects. Try keeping creating separate python files or modules for routes and database models.With that cleared out, lets directly jump into the writing the actual code. I will be adding inline comments explaining every part of the code." }, { "code": null, "e": 2315, "s": 2244, "text": "Create a python file called app.py and type the following code in it. " }, { "code": null, "e": 2323, "s": 2315, "text": "Python3" }, { "code": "# flask importsfrom flask import Flask, request, jsonify, make_responsefrom flask_sqlalchemy import SQLAlchemyimport uuid # for public idfrom werkzeug.security import generate_password_hash, check_password_hash# imports for PyJWT authenticationimport jwtfrom datetime import datetime, timedeltafrom functools import wraps # creates Flask objectapp = Flask(__name__)# configuration# NEVER HARDCODE YOUR CONFIGURATION IN YOUR CODE# INSTEAD CREATE A .env FILE AND STORE IN ITapp.config['SECRET_KEY'] = 'your secret key'# database nameapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Database.db'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True# creates SQLALCHEMY objectdb = SQLAlchemy(app) # Database ORMsclass User(db.Model): id = db.Column(db.Integer, primary_key = True) public_id = db.Column(db.String(50), unique = True) name = db.Column(db.String(100)) email = db.Column(db.String(70), unique = True) password = db.Column(db.String(80)) # decorator for verifying the JWTdef token_required(f): @wraps(f) def decorated(*args, **kwargs): token = None # jwt is passed in the request header if 'x-access-token' in request.headers: token = request.headers['x-access-token'] # return 401 if token is not passed if not token: return jsonify({'message' : 'Token is missing !!'}), 401 try: # decoding the payload to fetch the stored details data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.query\\ .filter_by(public_id = data['public_id'])\\ .first() except: return jsonify({ 'message' : 'Token is invalid !!' }), 401 # returns the current logged in users contex to the routes return f(current_user, *args, **kwargs) return decorated # User Database Route# this route sends back list of [email protected]('/user', methods =['GET'])@token_requireddef get_all_users(current_user): # querying the database # for all the entries in it users = User.query.all() # converting the query objects # to list of jsons output = [] for user in users: # appending the user data json # to the response list output.append({ 'public_id': user.public_id, 'name' : user.name, 'email' : user.email }) return jsonify({'users': output}) # route for logging user [email protected]('/login', methods =['POST'])def login(): # creates dictionary of form data auth = request.form if not auth or not auth.get('email') or not auth.get('password'): # returns 401 if any email or / and password is missing return make_response( 'Could not verify', 401, {'WWW-Authenticate' : 'Basic realm =\"Login required !!\"'} ) user = User.query\\ .filter_by(email = auth.get('email'))\\ .first() if not user: # returns 401 if user does not exist return make_response( 'Could not verify', 401, {'WWW-Authenticate' : 'Basic realm =\"User does not exist !!\"'} ) if check_password_hash(user.password, auth.get('password')): # generates the JWT Token token = jwt.encode({ 'public_id': user.public_id, 'exp' : datetime.utcnow() + timedelta(minutes = 30) }, app.config['SECRET_KEY']) return make_response(jsonify({'token' : token.decode('UTF-8')}), 201) # returns 403 if password is wrong return make_response( 'Could not verify', 403, {'WWW-Authenticate' : 'Basic realm =\"Wrong Password !!\"'} ) # signup [email protected]('/signup', methods =['POST'])def signup(): # creates a dictionary of the form data data = request.form # gets name, email and password name, email = data.get('name'), data.get('email') password = data.get('password') # checking for existing user user = User.query\\ .filter_by(email = email)\\ .first() if not user: # database ORM object user = User( public_id = str(uuid.uuid4()), name = name, email = email, password = generate_password_hash(password) ) # insert user db.session.add(user) db.session.commit() return make_response('Successfully registered.', 201) else: # returns 202 if user already exists return make_response('User already exists. Please Log in.', 202) if __name__ == \"__main__\": # setting debug to True enables hot reload # and also provides a debugger shell # if you hit an error while running the server app.run(debug = True)", "e": 7052, "s": 2323, "text": null }, { "code": null, "e": 7336, "s": 7052, "text": "Now, our code is ready. We now need to create the database first and then the table User from the ORM (Object Relational Mapping). To do so, first start the python3 interpreter in your terminal. You can do that by typing python3 in your terminal and that should do the trick for you." }, { "code": null, "e": 7401, "s": 7336, "text": "Next you need to type the following in your python3 interpreter:" }, { "code": null, "e": 7436, "s": 7401, "text": "from app import db\ndb.create_all()" }, { "code": null, "e": 7611, "s": 7436, "text": "So, what this does is first it imports the database object and then calls the create_all() function to create all the tables from the ORM. It should look something like this." }, { "code": null, "e": 7796, "s": 7611, "text": "Now that our actual code is ready, let’s test it out. I recommend using postman for testing out the APIs. You can use something like CURL but I will be using postman for this tutorial." }, { "code": null, "e": 7919, "s": 7796, "text": "To start testing our api, first we need to run our API. To do so, open up a terminal window and type the following in it. " }, { "code": null, "e": 7933, "s": 7919, "text": "python app.py" }, { "code": null, "e": 7969, "s": 7933, "text": "You should see an output like this " }, { "code": null, "e": 8257, "s": 7969, "text": "If you get any error then make sure all your syntax and indentation are correct. You can see that our api is running on http://localhost:5000/. Copy this url. We will use this urlalong with the routes to test the api.Now, open up Postman. You should be greated with the following screen." }, { "code": null, "e": 8515, "s": 8257, "text": "Now, click on the + sign and enter the url localhost:5000/signup change request type to POST, then select Body and then form-data and enter the data as key-value pair and then click on Send and you should get a response. It should look something like this. " }, { "code": null, "e": 8840, "s": 8515, "text": "So, we are registered. Now lets login. To do that just change the endpoint to /login and untick the Name field and click on Send. You should get a JWT as a response. Note down that JWT. That will be our token and we will need to send that token along with every subsequent requests. This token will identify us as logged in." }, { "code": null, "e": 9118, "s": 8840, "text": "The JSON contains the token. Note it down. Next try to fetch the list of users. To do that, change the endpoint to /user and then in the headers section, add a field as x-access-token and add the JWT token in the value and click on Send. You will get the list of users as JSON." }, { "code": null, "e": 9285, "s": 9118, "text": "So, this is how you can perform authentication with JWT in Flask. I recommend you to practice more with JWTs and user authentication to get your concepts more clear. " }, { "code": null, "e": 9294, "s": 9285, "text": "gabaa406" }, { "code": null, "e": 9303, "s": 9294, "text": "sooda367" }, { "code": null, "e": 9318, "s": 9303, "text": "kapoorsagar226" }, { "code": null, "e": 9335, "s": 9318, "text": "surinderdawra388" }, { "code": null, "e": 9348, "s": 9335, "text": "simmytarika5" }, { "code": null, "e": 9363, "s": 9348, "text": "sagartomar9927" }, { "code": null, "e": 9376, "s": 9363, "text": "Python Flask" }, { "code": null, "e": 9383, "s": 9376, "text": "Python" }, { "code": null, "e": 9481, "s": 9383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9513, "s": 9481, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 9540, "s": 9513, "text": "Python Classes and Objects" }, { "code": null, "e": 9561, "s": 9540, "text": "Python OOPs Concepts" }, { "code": null, "e": 9584, "s": 9561, "text": "Introduction To PYTHON" }, { "code": null, "e": 9640, "s": 9584, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 9671, "s": 9640, "text": "Python | os.path.join() method" }, { "code": null, "e": 9713, "s": 9671, "text": "Check if element exists in list in Python" }, { "code": null, "e": 9755, "s": 9713, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 9794, "s": 9755, "text": "Python | Get unique values from a list" } ]
frozenset() in Python
12 Aug, 2021 The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable. In Python, frozenset is the same as set except the frozensets are immutable which means that elements from the frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved. Syntax : frozenset(iterable_object_name)Parameter : This function accepts iterable object as input parameter.Return Type: This function return an equivalent frozenset object. Below examples explains it clearly. Example #1: If no parameters are passed to frozenset() function then it returns a empty frozenset type object. Python3 # Python program to understand frozenset() function # tuple of numbersnu = (1, 2, 3, 4, 5, 6, 7, 8, 9) # converting tuple to frozensetfnum = frozenset(nu) # printing detailsprint("frozenset Object is : ", fnum) frozenset Object is : frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9}) Example #2: Uses of frozenset().Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets. Below example explains it clearly. Python3 # Python program to understand use# of frozenset function # creating a dictionaryStudent = {"name": "Ankit", "age": 21, "sex": "Male", "college": "MNNIT Allahabad", "address": "Allahabad"} # making keys of dictionary as frozensetkey = frozenset(Student) # printing keys detailsprint('The frozen set is:', key) The frozen set is: frozenset({'sex', 'age', 'address', 'name', 'college'}) Example #3: WarningIf by mistake we want to change the frozenset object then it throws an error “‘frozenset’ object does not support item assignment“. Python3 # Python program to understand# use of frozenset function # creating a listfavourite_subject = ["OS", "DBMS", "Algo"] # making it frozenset typef_subject = frozenset(favourite_subject) # below line will generate error f_subject[1] = "Networking" Output: Traceback (most recent call last): File "/home/0fbd773df8aa631590ed0f3f865c1437.py", line 12, in f_subject[1] = "Networking" TypeError: 'frozenset' object does not support item assignment 786meimran 122006025 Python-Functions python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Aug, 2021" }, { "code": null, "e": 236, "s": 53, "text": "The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable." }, { "code": null, "e": 548, "s": 236, "text": "In Python, frozenset is the same as set except the frozensets are immutable which means that elements from the frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved." }, { "code": null, "e": 723, "s": 548, "text": "Syntax : frozenset(iterable_object_name)Parameter : This function accepts iterable object as input parameter.Return Type: This function return an equivalent frozenset object." }, { "code": null, "e": 759, "s": 723, "text": "Below examples explains it clearly." }, { "code": null, "e": 872, "s": 759, "text": "Example #1: If no parameters are passed to frozenset() function then it returns a empty frozenset type object. " }, { "code": null, "e": 880, "s": 872, "text": "Python3" }, { "code": "# Python program to understand frozenset() function # tuple of numbersnu = (1, 2, 3, 4, 5, 6, 7, 8, 9) # converting tuple to frozensetfnum = frozenset(nu) # printing detailsprint(\"frozenset Object is : \", fnum)", "e": 1091, "s": 880, "text": null }, { "code": null, "e": 1153, "s": 1091, "text": "frozenset Object is : frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})" }, { "code": null, "e": 1330, "s": 1155, "text": " Example #2: Uses of frozenset().Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets. Below example explains it clearly. " }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": "# Python program to understand use# of frozenset function # creating a dictionaryStudent = {\"name\": \"Ankit\", \"age\": 21, \"sex\": \"Male\", \"college\": \"MNNIT Allahabad\", \"address\": \"Allahabad\"} # making keys of dictionary as frozensetkey = frozenset(Student) # printing keys detailsprint('The frozen set is:', key)", "e": 1658, "s": 1338, "text": null }, { "code": null, "e": 1733, "s": 1658, "text": "The frozen set is: frozenset({'sex', 'age', 'address', 'name', 'college'})" }, { "code": null, "e": 1887, "s": 1735, "text": "Example #3: WarningIf by mistake we want to change the frozenset object then it throws an error “‘frozenset’ object does not support item assignment“. " }, { "code": null, "e": 1895, "s": 1887, "text": "Python3" }, { "code": "# Python program to understand# use of frozenset function # creating a listfavourite_subject = [\"OS\", \"DBMS\", \"Algo\"] # making it frozenset typef_subject = frozenset(favourite_subject) # below line will generate error f_subject[1] = \"Networking\"", "e": 2141, "s": 1895, "text": null }, { "code": null, "e": 2150, "s": 2141, "text": "Output: " }, { "code": null, "e": 2345, "s": 2150, "text": "Traceback (most recent call last):\n File \"/home/0fbd773df8aa631590ed0f3f865c1437.py\", line 12, in \n f_subject[1] = \"Networking\"\nTypeError: 'frozenset' object does not support item assignment" }, { "code": null, "e": 2358, "s": 2347, "text": "786meimran" }, { "code": null, "e": 2368, "s": 2358, "text": "122006025" }, { "code": null, "e": 2385, "s": 2368, "text": "Python-Functions" }, { "code": null, "e": 2396, "s": 2385, "text": "python-set" }, { "code": null, "e": 2403, "s": 2396, "text": "Python" }, { "code": null, "e": 2414, "s": 2403, "text": "python-set" }, { "code": null, "e": 2512, "s": 2414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2540, "s": 2512, "text": "Read JSON file using Python" }, { "code": null, "e": 2562, "s": 2540, "text": "Python map() function" }, { "code": null, "e": 2612, "s": 2562, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2630, "s": 2612, "text": "Python Dictionary" }, { "code": null, "e": 2674, "s": 2630, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2716, "s": 2674, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2739, "s": 2716, "text": "Taking input in Python" }, { "code": null, "e": 2761, "s": 2739, "text": "Enumerate() in Python" }, { "code": null, "e": 2796, "s": 2761, "text": "Read a file line by line in Python" } ]
PyQt5 – How to access content of label ?
26 Mar, 2020 We can create label using QLabel() method, and set the content using setText() method. In this article, we will see how to access the content of the label, in order to do this we will use text() method. Syntax : label.text() Argument : It takes no argument. Return : It returns a string. Code : # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a label widget self.label_1 = QLabel("old label ", self) # setting up the border and background color self.label_1.setStyleSheet("border :3px solid black; background : pink") # getting the content of label content = self.label_1.text() # printing the content of label print(content) # moving the label self.label_1.move(10, 100) # creating a new label widget self.label_2 = QLabel("new Label ", self) # setting up the border and background color self.label_2.setStyleSheet("border :3px solid black; background : green") # moving the label self.label_2.move(110, 110) # printing the content of label print(self.label_2.text()) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : old label new Label Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 231, "s": 28, "text": "We can create label using QLabel() method, and set the content using setText() method. In this article, we will see how to access the content of the label, in order to do this we will use text() method." }, { "code": null, "e": 253, "s": 231, "text": "Syntax : label.text()" }, { "code": null, "e": 286, "s": 253, "text": "Argument : It takes no argument." }, { "code": null, "e": 316, "s": 286, "text": "Return : It returns a string." }, { "code": null, "e": 323, "s": 316, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a label widget self.label_1 = QLabel(\"old label \", self) # setting up the border and background color self.label_1.setStyleSheet(\"border :3px solid black; background : pink\") # getting the content of label content = self.label_1.text() # printing the content of label print(content) # moving the label self.label_1.move(10, 100) # creating a new label widget self.label_2 = QLabel(\"new Label \", self) # setting up the border and background color self.label_2.setStyleSheet(\"border :3px solid black; background : green\") # moving the label self.label_2.move(110, 110) # printing the content of label print(self.label_2.text()) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1729, "s": 323, "text": null }, { "code": null, "e": 1738, "s": 1729, "text": "Output :" }, { "code": null, "e": 1761, "s": 1738, "text": "old label \nnew Label \n" }, { "code": null, "e": 1772, "s": 1761, "text": "Python-gui" }, { "code": null, "e": 1784, "s": 1772, "text": "Python-PyQt" }, { "code": null, "e": 1791, "s": 1784, "text": "Python" }, { "code": null, "e": 1889, "s": 1791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1921, "s": 1889, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1948, "s": 1921, "text": "Python Classes and Objects" }, { "code": null, "e": 1969, "s": 1948, "text": "Python OOPs Concepts" }, { "code": null, "e": 1992, "s": 1969, "text": "Introduction To PYTHON" }, { "code": null, "e": 2048, "s": 1992, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2079, "s": 2048, "text": "Python | os.path.join() method" }, { "code": null, "e": 2121, "s": 2079, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2163, "s": 2121, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2202, "s": 2163, "text": "Python | Get unique values from a list" } ]
SQLite - AUTOINCREMENT
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only. The basic usage of AUTOINCREMENT keyword is as follows − CREATE TABLE table_name( column1 INTEGER AUTOINCREMENT, column2 datatype, column3 datatype, ..... columnN datatype, ); Consider COMPANY table to be created as follows − sqlite> CREATE TABLE COMPANY( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); Now, insert the following records into table COMPANY − INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'David', 27, 'Texas', 85000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Kim', 22, 'South-Hall', 45000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'James', 24, 'Houston', 10000.00 ); This will insert 7 tuples into the table COMPANY and COMPANY will have the following records − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
[ { "code": null, "e": 3000, "s": 2772, "text": "SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment." }, { "code": null, "e": 3063, "s": 3000, "text": "The keyword AUTOINCREMENT can be used with INTEGER field only." }, { "code": null, "e": 3120, "s": 3063, "text": "The basic usage of AUTOINCREMENT keyword is as follows −" }, { "code": null, "e": 3254, "s": 3120, "text": "CREATE TABLE table_name(\n column1 INTEGER AUTOINCREMENT,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);" }, { "code": null, "e": 3304, "s": 3254, "text": "Consider COMPANY table to be created as follows −" }, { "code": null, "e": 3505, "s": 3304, "text": "sqlite> CREATE TABLE COMPANY(\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 3560, "s": 3505, "text": "Now, insert the following records into table COMPANY −" }, { "code": null, "e": 4202, "s": 3560, "text": "INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Paul', 32, 'California', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Allen', 25, 'Texas', 15000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Teddy', 23, 'Norway', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'David', 27, 'Texas', 85000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Kim', 22, 'South-Hall', 45000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'James', 24, 'Houston', 10000.00 );\n" }, { "code": null, "e": 4297, "s": 4202, "text": "This will insert 7 tuples into the table COMPANY and COMPANY will have the following records −" } ]