title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Console.Read() Method in C#
28 Feb, 2019 Console.Read() Method is used to read the next character from the standard input stream. This method basically blocks its return when the user types some input characters. As soon as the user press ENTER key it terminates. Syntax: public static int Read (); Return Value: It returns the next character from the input stream, or a negative one (-1) if there are currently no more characters to be read. Exception: This method will give IOException if an I/O error occurred. Below programs illustrate the use of above-discussed method: Example 1: // C# program to illustrate the use// of Console.Read Methodusing System; namespace GFG { class Program { static void Main(string[] args) { int x; Console.WriteLine("Enter your Character to get Decimal number"); // using the method x = Console.Read(); Console.WriteLine(x); }}} Output: Example 2: // C# program to illustrate the use// of Console.Read Methodusing System; namespace GFG { class Program { static void Main(string[] args) { // Write to console window. int x; Console.WriteLine("Enter your Character to get Decimal number"); x = Console.Read(); Console.WriteLine(x); // Converting the decimal into character. Console.WriteLine(Convert.ToChar(x)); }}} Output: Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.read?view=netframework-4.7.2 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object Extension Method in C# Difference between Ref and Out keywords in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2019" }, { "code": null, "e": 251, "s": 28, "text": "Console.Read() Method is used to read the next character from the standard input stream. This method basically blocks its return when the user types some input characters. As soon as the user press ENTER key it terminates." }, { "code": null, "e": 286, "s": 251, "text": "Syntax: public static int Read ();" }, { "code": null, "e": 430, "s": 286, "text": "Return Value: It returns the next character from the input stream, or a negative one (-1) if there are currently no more characters to be read." }, { "code": null, "e": 501, "s": 430, "text": "Exception: This method will give IOException if an I/O error occurred." }, { "code": null, "e": 562, "s": 501, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 573, "s": 562, "text": "Example 1:" }, { "code": "// C# program to illustrate the use// of Console.Read Methodusing System; namespace GFG { class Program { static void Main(string[] args) { int x; Console.WriteLine(\"Enter your Character to get Decimal number\"); // using the method x = Console.Read(); Console.WriteLine(x); }}}", "e": 911, "s": 573, "text": null }, { "code": null, "e": 919, "s": 911, "text": "Output:" }, { "code": null, "e": 930, "s": 919, "text": "Example 2:" }, { "code": "// C# program to illustrate the use// of Console.Read Methodusing System; namespace GFG { class Program { static void Main(string[] args) { // Write to console window. int x; Console.WriteLine(\"Enter your Character to get Decimal number\"); x = Console.Read(); Console.WriteLine(x); // Converting the decimal into character. Console.WriteLine(Convert.ToChar(x)); }}}", "e": 1362, "s": 930, "text": null }, { "code": null, "e": 1370, "s": 1362, "text": "Output:" }, { "code": null, "e": 1381, "s": 1370, "text": "Reference:" }, { "code": null, "e": 1469, "s": 1381, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.read?view=netframework-4.7.2" }, { "code": null, "e": 1490, "s": 1469, "text": "CSharp-Console-Class" }, { "code": null, "e": 1504, "s": 1490, "text": "CSharp-method" }, { "code": null, "e": 1511, "s": 1504, "text": "Picked" }, { "code": null, "e": 1514, "s": 1511, "text": "C#" }, { "code": null, "e": 1612, "s": 1514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1643, "s": 1612, "text": "Introduction to .NET Framework" }, { "code": null, "e": 1658, "s": 1643, "text": "C# | Delegates" }, { "code": null, "e": 1701, "s": 1658, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1750, "s": 1701, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1766, "s": 1750, "text": "C# | Data Types" }, { "code": null, "e": 1784, "s": 1766, "text": "C# | Constructors" }, { "code": null, "e": 1824, "s": 1784, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 1846, "s": 1824, "text": "C# | Class and Object" }, { "code": null, "e": 1869, "s": 1846, "text": "Extension Method in C#" } ]
Internal Working of TreeMap in Java
05 Jul, 2021 TreeMap class is like HashMap. TreeMap stores key-value pairs. The main difference is that TreeMap sorts the key in ascending order. TreeMap is sorted as the ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Pre-requisite: Let’s go through pre-requisite that primarily includes constructors available in case of TreeMap before discussing further TreeMap() This default constructor constructs an empty TreeMapTreeMap(Map map) It creates a TreeMap with the entries from a map.TreeMap(Comparator compare) This is an argument constructor and it takes Comparator object to constructs an empty tree-based map. It will be sorted by using the Comparator compare.TreeMap(SortedMap sortedMap) It can be initialized as TreeMap with the entries from sortedMap. TreeMap() This default constructor constructs an empty TreeMap TreeMap(Map map) It creates a TreeMap with the entries from a map. TreeMap(Comparator compare) This is an argument constructor and it takes Comparator object to constructs an empty tree-based map. It will be sorted by using the Comparator compare. TreeMap(SortedMap sortedMap) It can be initialized as TreeMap with the entries from sortedMap. Illustration: Input : a = ["Alice", 1], b = ["Bob", 2] Output : TreeMap = {"Alice" = 1, "Bob" = 2} Input : a = [1, "First"], b = [2, "Second"], c = [3, "Third"] Output : TreeMap = {1 = "First", 2 = "Second", 3 = "Third"} Concept: Red-Black Trees A red-black tree is a self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the colour (red or black). These colours are used to ensure that the tree remains balanced during insertions and deletions. Although the balance of the tree is not perfect, it is good enough to reduce the searching time and maintain it around O(log n) time, where n is the total number of elements in the tree. It must be noted that as each node requires only 1 bit of space to store the colour information, these types of trees show identical memory footprint to the classic (uncoloured) binary search tree. As the name of the algorithm suggests colour of every node in the tree is either black or red.The root node must be Black in colour.The red node can not have a red colour neighbours node.All paths from the root node to the null should consist of the same number of black nodes. As the name of the algorithm suggests colour of every node in the tree is either black or red. The root node must be Black in colour. The red node can not have a red colour neighbours node. All paths from the root node to the null should consist of the same number of black nodes. The above characteristics lead to certain properties of a node to possess which results out as follows: The left elements are always less than the parent element.Natural ordering is computed in logical comparison of the objects.The right elements are always greater than or equal to the parent element. The left elements are always less than the parent element. Natural ordering is computed in logical comparison of the objects. The right elements are always greater than or equal to the parent element. Syntax: Declaring an object of TreeMap or simply creating a TreeMap Map<Key, Integer> treemap = new TreeMap<>(); Approach: Create a TreeMap.Create some entries to get entered in the TreeMap.Calculate hash code of Key {“key1”}. It will be generated as 118.Print the TreeMap using for loop traversal. Create a TreeMap. Create some entries to get entered in the TreeMap. Calculate hash code of Key {“key1”}. It will be generated as 118. Print the TreeMap using for loop traversal. Implementation: Implementing red-black trees to showcase internal working of TreeMap Example Java // Java Program to show Internal Working// of TreeMap in Java // Importing Map and TreeMap classes// from java.util packageimport java.util.Map;import java.util.TreeMap; // Standard Comparablepublic class Key implements Comparable<Key> { // Custom input final int data = 118; private String key; // Constructor of this class public Key(String key) { // Super keyword refers immediate parent class // object super(); // This keyword is a reference variable // referring to current object this.key = key; } // Print Key method public String printKey() { return this.key; } // Override compareTo method @Override public int compareTo(Key obj) { return key.compareTo(obj.key); }} // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Initialize TreeMap // Declaring object of String type Map<Key, String> treemap = new TreeMap<>(); // Adding the elements in object of TreeMap // Custom inputs treemap.put(new Key("Key1"), "Alice"); treemap.put(new Key("Key4"), "Zeya"); treemap.put(new Key("Key3"), "Geek"); treemap.put(new Key("Key2"), "Bob"); // Iterate over object elements using for-each loop for (Map.Entry<Key, String> entry : treemap.entrySet()) // Print elements in TreeMap object System.out.println( "[" + entry.getKey().printKey() + " = " + entry.getValue() + "]"); }} Java // Java Program to show Internal Working// of TreeMap in Java // Importing Map and TreeMap classes// from java.util packageimport java.util.Map;import java.util.TreeMap; // Standard Comparablepublic class Key implements Comparable<Key> { // Custom input final int data = 118; private String key; // Constructor of this class public Key(String key) { // Super keyword refers immediate parent class // object super(); // This keyword is a reference variable // referring to current object this.key = key; } // Print Key method public String printKey() { return this.key; } // Override compareTo method @Override public int compareTo(Key obj) { return key.compareTo(obj.key); }} // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Initialize TreeMap // Declaring object of String type Map<Key, String> treemap = new TreeMap<>(); // Adding the elements in object of TreeMap // Custom inputs treemap.put(new Key("Key1"), "Alice"); treemap.put(new Key("Key4"), "Zeya"); treemap.put(new Key("Key3"), "Geek"); treemap.put(new Key("Key2"), "Bob"); // Iterate over object elements using for-each loop for (Map.Entry<Key, String> entry : treemap.entrySet()) // Print elements in TreeMap object System.out.println( "[" + entry.getKey().printKey() + " = " + entry.getValue() + "]"); }} Output explanation is pictorially represented in order to get the internal working of TreeMap nodes how the above output is generated for better understanding. Note: Performance of TreeMap is slow in comparison with HashMap and LinkedHashMap. Tree implementation provides guaranteed log(n) time cost for the containsKey(), get(), put() and remove() operations. sooda367 varshagumber28 saurabh1990aror Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 322, "s": 52, "text": "TreeMap class is like HashMap. TreeMap stores key-value pairs. The main difference is that TreeMap sorts the key in ascending order. TreeMap is sorted as the ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used." }, { "code": null, "e": 337, "s": 322, "text": "Pre-requisite:" }, { "code": null, "e": 461, "s": 337, "text": "Let’s go through pre-requisite that primarily includes constructors available in case of TreeMap before discussing further " }, { "code": null, "e": 864, "s": 461, "text": "TreeMap() This default constructor constructs an empty TreeMapTreeMap(Map map) It creates a TreeMap with the entries from a map.TreeMap(Comparator compare) This is an argument constructor and it takes Comparator object to constructs an empty tree-based map. It will be sorted by using the Comparator compare.TreeMap(SortedMap sortedMap) It can be initialized as TreeMap with the entries from sortedMap." }, { "code": null, "e": 927, "s": 864, "text": "TreeMap() This default constructor constructs an empty TreeMap" }, { "code": null, "e": 994, "s": 927, "text": "TreeMap(Map map) It creates a TreeMap with the entries from a map." }, { "code": null, "e": 1175, "s": 994, "text": "TreeMap(Comparator compare) This is an argument constructor and it takes Comparator object to constructs an empty tree-based map. It will be sorted by using the Comparator compare." }, { "code": null, "e": 1270, "s": 1175, "text": "TreeMap(SortedMap sortedMap) It can be initialized as TreeMap with the entries from sortedMap." }, { "code": null, "e": 1284, "s": 1270, "text": "Illustration:" }, { "code": null, "e": 1494, "s": 1284, "text": "Input : a = [\"Alice\", 1], b = [\"Bob\", 2]\nOutput : TreeMap = {\"Alice\" = 1, \"Bob\" = 2}\n\nInput : a = [1, \"First\"], b = [2, \"Second\"], c = [3, \"Third\"]\nOutput : TreeMap = {1 = \"First\", 2 = \"Second\", 3 = \"Third\"}" }, { "code": null, "e": 1520, "s": 1494, "text": "Concept: Red-Black Trees " }, { "code": null, "e": 2157, "s": 1520, "text": "A red-black tree is a self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the colour (red or black). These colours are used to ensure that the tree remains balanced during insertions and deletions. Although the balance of the tree is not perfect, it is good enough to reduce the searching time and maintain it around O(log n) time, where n is the total number of elements in the tree. It must be noted that as each node requires only 1 bit of space to store the colour information, these types of trees show identical memory footprint to the classic (uncoloured) binary search tree. " }, { "code": null, "e": 2435, "s": 2157, "text": "As the name of the algorithm suggests colour of every node in the tree is either black or red.The root node must be Black in colour.The red node can not have a red colour neighbours node.All paths from the root node to the null should consist of the same number of black nodes." }, { "code": null, "e": 2530, "s": 2435, "text": "As the name of the algorithm suggests colour of every node in the tree is either black or red." }, { "code": null, "e": 2569, "s": 2530, "text": "The root node must be Black in colour." }, { "code": null, "e": 2625, "s": 2569, "text": "The red node can not have a red colour neighbours node." }, { "code": null, "e": 2716, "s": 2625, "text": "All paths from the root node to the null should consist of the same number of black nodes." }, { "code": null, "e": 2820, "s": 2716, "text": "The above characteristics lead to certain properties of a node to possess which results out as follows:" }, { "code": null, "e": 3019, "s": 2820, "text": "The left elements are always less than the parent element.Natural ordering is computed in logical comparison of the objects.The right elements are always greater than or equal to the parent element." }, { "code": null, "e": 3078, "s": 3019, "text": "The left elements are always less than the parent element." }, { "code": null, "e": 3145, "s": 3078, "text": "Natural ordering is computed in logical comparison of the objects." }, { "code": null, "e": 3220, "s": 3145, "text": "The right elements are always greater than or equal to the parent element." }, { "code": null, "e": 3288, "s": 3220, "text": "Syntax: Declaring an object of TreeMap or simply creating a TreeMap" }, { "code": null, "e": 3333, "s": 3288, "text": "Map<Key, Integer> treemap = new TreeMap<>();" }, { "code": null, "e": 3343, "s": 3333, "text": "Approach:" }, { "code": null, "e": 3519, "s": 3343, "text": "Create a TreeMap.Create some entries to get entered in the TreeMap.Calculate hash code of Key {“key1”}. It will be generated as 118.Print the TreeMap using for loop traversal." }, { "code": null, "e": 3537, "s": 3519, "text": "Create a TreeMap." }, { "code": null, "e": 3588, "s": 3537, "text": "Create some entries to get entered in the TreeMap." }, { "code": null, "e": 3654, "s": 3588, "text": "Calculate hash code of Key {“key1”}. It will be generated as 118." }, { "code": null, "e": 3698, "s": 3654, "text": "Print the TreeMap using for loop traversal." }, { "code": null, "e": 3783, "s": 3698, "text": "Implementation: Implementing red-black trees to showcase internal working of TreeMap" }, { "code": null, "e": 3791, "s": 3783, "text": "Example" }, { "code": null, "e": 3796, "s": 3791, "text": "Java" }, { "code": "// Java Program to show Internal Working// of TreeMap in Java // Importing Map and TreeMap classes// from java.util packageimport java.util.Map;import java.util.TreeMap; // Standard Comparablepublic class Key implements Comparable<Key> { // Custom input final int data = 118; private String key; // Constructor of this class public Key(String key) { // Super keyword refers immediate parent class // object super(); // This keyword is a reference variable // referring to current object this.key = key; } // Print Key method public String printKey() { return this.key; } // Override compareTo method @Override public int compareTo(Key obj) { return key.compareTo(obj.key); }} // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Initialize TreeMap // Declaring object of String type Map<Key, String> treemap = new TreeMap<>(); // Adding the elements in object of TreeMap // Custom inputs treemap.put(new Key(\"Key1\"), \"Alice\"); treemap.put(new Key(\"Key4\"), \"Zeya\"); treemap.put(new Key(\"Key3\"), \"Geek\"); treemap.put(new Key(\"Key2\"), \"Bob\"); // Iterate over object elements using for-each loop for (Map.Entry<Key, String> entry : treemap.entrySet()) // Print elements in TreeMap object System.out.println( \"[\" + entry.getKey().printKey() + \" = \" + entry.getValue() + \"]\"); }}", "e": 5358, "s": 3796, "text": null }, { "code": null, "e": 5363, "s": 5358, "text": "Java" }, { "code": "// Java Program to show Internal Working// of TreeMap in Java // Importing Map and TreeMap classes// from java.util packageimport java.util.Map;import java.util.TreeMap; // Standard Comparablepublic class Key implements Comparable<Key> { // Custom input final int data = 118; private String key; // Constructor of this class public Key(String key) { // Super keyword refers immediate parent class // object super(); // This keyword is a reference variable // referring to current object this.key = key; } // Print Key method public String printKey() { return this.key; } // Override compareTo method @Override public int compareTo(Key obj) { return key.compareTo(obj.key); }} // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Initialize TreeMap // Declaring object of String type Map<Key, String> treemap = new TreeMap<>(); // Adding the elements in object of TreeMap // Custom inputs treemap.put(new Key(\"Key1\"), \"Alice\"); treemap.put(new Key(\"Key4\"), \"Zeya\"); treemap.put(new Key(\"Key3\"), \"Geek\"); treemap.put(new Key(\"Key2\"), \"Bob\"); // Iterate over object elements using for-each loop for (Map.Entry<Key, String> entry : treemap.entrySet()) // Print elements in TreeMap object System.out.println( \"[\" + entry.getKey().printKey() + \" = \" + entry.getValue() + \"]\"); }}", "e": 6925, "s": 5363, "text": null }, { "code": null, "e": 7085, "s": 6925, "text": "Output explanation is pictorially represented in order to get the internal working of TreeMap nodes how the above output is generated for better understanding." }, { "code": null, "e": 7092, "s": 7085, "text": "Note: " }, { "code": null, "e": 7169, "s": 7092, "text": "Performance of TreeMap is slow in comparison with HashMap and LinkedHashMap." }, { "code": null, "e": 7287, "s": 7169, "text": "Tree implementation provides guaranteed log(n) time cost for the containsKey(), get(), put() and remove() operations." }, { "code": null, "e": 7298, "s": 7289, "text": "sooda367" }, { "code": null, "e": 7313, "s": 7298, "text": "varshagumber28" }, { "code": null, "e": 7329, "s": 7313, "text": "saurabh1990aror" }, { "code": null, "e": 7346, "s": 7329, "text": "Java-Collections" }, { "code": null, "e": 7359, "s": 7346, "text": "java-TreeMap" }, { "code": null, "e": 7364, "s": 7359, "text": "Java" }, { "code": null, "e": 7369, "s": 7364, "text": "Java" }, { "code": null, "e": 7386, "s": 7369, "text": "Java-Collections" }, { "code": null, "e": 7484, "s": 7386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7499, "s": 7484, "text": "Stream In Java" }, { "code": null, "e": 7520, "s": 7499, "text": "Introduction to Java" }, { "code": null, "e": 7541, "s": 7520, "text": "Constructors in Java" }, { "code": null, "e": 7560, "s": 7541, "text": "Exceptions in Java" }, { "code": null, "e": 7577, "s": 7560, "text": "Generics in Java" }, { "code": null, "e": 7607, "s": 7577, "text": "Functional Interfaces in Java" }, { "code": null, "e": 7633, "s": 7607, "text": "Java Programming Examples" }, { "code": null, "e": 7649, "s": 7633, "text": "Strings in Java" }, { "code": null, "e": 7686, "s": 7649, "text": "Differences between JDK, JRE and JVM" } ]
How to Use PRDownloader Library in Android App?
22 Feb, 2022 PRDownloader library is a file downloader library for android. It comes with pause and resumes support while downloading a file. This library is capable of downloading large files from the internet and can download any type of file like image, video, pdf, apk and etc. It provides many features that can help a user to download files from the internet easily and efficiently. With this library, you can also check the status of the downloading using the download id and can perform many other important operations using the download id. This library contains many important methods that give full control to the user to handle the downloading states of the file like pause, cancel, resume, etc. You can make the following Requests with this library: Pause a download request: PRDownloader.pause(downloadId); Cancel a download request: // Cancel with the download id PRDownloader.cancel(downloadId); // The tag can be set to any request and then can be used to cancel the request PRDownloader.cancel(TAG); // Cancel all the requests PRDownloader.cancelAll(); Resume a download request: PRDownloader.resume(downloadId); Get status of a download request: Status status = PRDownloader.getStatus(downloadId); A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Then Enter your App Name in the Name field and select Java from the Language drop-down menu. Step 2: Add dependency To add the dependency navigate to app > Gradle Scripts > gradle.build(Module: app) and add the below dependency in the dependencies section. After adding the dependency sync your project. implementation 'com.mindorks.android:prdownloader:0.6.0' Step 3: Add Internet Permission Navigate to app > manifest > AndroidManifest.xml and add the internet permission. <uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- EditText to take the url from the user --> <EditText android:id="@+id/url_etText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="@string/type_or_paste_your_url_here" /> <!-- Button to start downloading from file --> <Button android:id="@+id/btn_download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/url_etText" android:layout_centerHorizontal="true" android:text="@string/download" /> <!-- linear layout that contains widgets to show information --> <LinearLayout android:id="@+id/details_box" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/btn_download" android:layout_margin="10dp" android:layout_marginTop="20dp" android:background="@drawable/box_design_layout" android:orientation="vertical" android:padding="10dp" android:visibility="gone"> <!-- Textview to show the file name --> <TextView android:id="@+id/file_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/click_on_start_button_to_start_downloading" android:textSize="20sp" android:textStyle="bold" /> <!-- progress bar to show the progress of downloading --> <ProgressBar android:id="@+id/progress_horizontal" style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:progressTint="@color/purple_200" tools:ignore="UnusedAttribute" /> <!-- textview to show the downloading percentage --> <TextView android:id="@+id/downloading_percentage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textAlignment="center" android:textSize="12sp" android:textStyle="bold" /> <!-- this linear layout contains buttons --> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:orientation="horizontal" android:padding="10dp"> <!-- button to start the downloading --> <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/start" /> <!-- button to cancel or stop the downloading --> <Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" /> </LinearLayout> </LinearLayout> <!-- this textview will show the path where the downloaded file is stored --> <TextView android:id="@+id/txt_url" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/details_box" android:layout_marginTop="10dp" android:textSize="15sp" android:textStyle="bold" /> </RelativeLayout> Below is the code for the Strings.xml file XML <resources> <string name="app_name">GFG PRDownloader Library</string> <string name="download">DOWNLOAD</string> <string name="type_or_paste_your_url_here">Type or Paste Your URL Here</string> <string name="start">START</string> <string name="stop">STOP</string> <string name="click_on_start_button_to_start_downloading">Click on Start Button to Start Downloading</string></resources> Step 5: Designing the box layout Navigate to app > res > drawable > right-click > new > Drawable Resource File and name that file as box_design_layout and add the below code to that file. XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp" android:topLeftRadius="0dp" android:topRightRadius="0dp" /> <stroke android:width="1dp" android:color="@android:color/black" /> <solid android:color="@android:color/transparent" /> </shape> Step 6: Create Util class Navigate to app > java > package name > right-click > New >Java class and name that file as Utils.java. Add the below code into Utils.java. Below is the code for Utils.java. Java import android.content.Context;import android.os.Environment; import androidx.core.content.ContextCompat; import java.io.File;import java.util.Locale; public final class Utils { private Utils() { } public static String getRootDirPath(Context context) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null)[0]; return file.getAbsolutePath(); } else { return context.getApplicationContext().getFilesDir().getAbsolutePath(); } } public static String getProgressDisplayLine(long currentBytes, long totalBytes) { return getBytesToMBString(currentBytes) + "/" + getBytesToMBString(totalBytes); } private static String getBytesToMBString(long bytes) { return String.format(Locale.ENGLISH, "%.2fMb", bytes / (1024.00 * 1024.00)); }} Step 7: Working with the MainActivity.java Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.webkit.URLUtil;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.downloader.Error;import com.downloader.OnCancelListener;import com.downloader.OnDownloadListener;import com.downloader.OnPauseListener;import com.downloader.OnProgressListener;import com.downloader.OnStartOrResumeListener;import com.downloader.PRDownloader;import com.downloader.Progress;import com.downloader.Status; public class MainActivity extends AppCompatActivity { private EditText editTextUrl; private String path; private TextView file_downloaded_path, file_name, downloading_percent; private ProgressBar progressBar; private Button btnStart, btnCancel, buttonDownload; private LinearLayout details; int downloadID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing PRDownloader library PRDownloader.initialize(this); // finding edittext by its id editTextUrl = findViewById(R.id.url_etText); // finding button by its id buttonDownload = findViewById(R.id.btn_download); // finding textview by its id file_downloaded_path = findViewById(R.id.txt_url); // finding textview by its id file_name = findViewById(R.id.file_name); // finding progressbar by its id progressBar = findViewById(R.id.progress_horizontal); // finding textview by its id downloading_percent = findViewById(R.id.downloading_percentage); // finding button by its id btnStart = findViewById(R.id.btn_start); // finding button by its id btnCancel = findViewById(R.id.btn_stop); // finding linear layout by its id details = findViewById(R.id.details_box); //storing the path of the file path = Utils.getRootDirPath(this); // handling onclick event on button buttonDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // getting the text from edittext // and storing it to url variable String url = editTextUrl.getText().toString().trim(); // setting the visibility of linear layout to visible details.setVisibility(View.VISIBLE); // calling method downloadFile passing url as parameter downloadFile(url); } }); } @SuppressLint("SetTextI18n") private void downloadFile(final String url) { // handing click event on start button // which starts the downloading of the file btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // checks if the process is already running if (Status.RUNNING == PRDownloader.getStatus(downloadID)) { // pauses the download if // user click on pause button PRDownloader.pause(downloadID); return; } // enabling the start button btnStart.setEnabled(false); // checks if the status is paused if (Status.PAUSED == PRDownloader.getStatus(downloadID)) { // resume the download if download is paused PRDownloader.resume(downloadID); return; } // getting the filename String fileName = URLUtil.guessFileName(url, null, null); // setting the file name file_name.setText("Downloading " + fileName); // making the download request downloadID = PRDownloader.download(url, path, fileName) .build() .setOnStartOrResumeListener(new OnStartOrResumeListener() { @SuppressLint("SetTextI18n") @Override public void onStartOrResume() { progressBar.setIndeterminate(false); // enables the start button btnStart.setEnabled(true); // setting the text of start button to pause btnStart.setText("Pause"); // enabling the stop button btnCancel.setEnabled(true); Toast.makeText(MainActivity.this, "Downloading started", Toast.LENGTH_SHORT).show(); } }) .setOnPauseListener(new OnPauseListener() { @Override public void onPause() { // setting the text of start button to resume // when the download is in paused state btnStart.setText("Resume"); Toast.makeText(MainActivity.this, "Downloading Paused", Toast.LENGTH_SHORT).show(); } }) .setOnCancelListener(new OnCancelListener() { @Override public void onCancel() { // resetting the downloadId when // the download is cancelled downloadID = 0; // setting the text of start button to start btnStart.setText("Start"); // disabling the cancel button btnCancel.setEnabled(false); // resetting the progress bar progressBar.setProgress(0); // resetting the download percent downloading_percent.setText(""); progressBar.setIndeterminate(false); Toast.makeText(MainActivity.this, "Downloading Cancelled", Toast.LENGTH_SHORT).show(); } }) .setOnProgressListener(new OnProgressListener() { @Override public void onProgress(Progress progress) { // getting the progress of download long progressPer = progress.currentBytes * 100 / progress.totalBytes; // setting the progress to progressbar progressBar.setProgress((int) progressPer); // setting the download percent downloading_percent.setText(Utils.getProgressDisplayLine(progress.currentBytes, progress.totalBytes)); progressBar.setIndeterminate(false); } }) .start(new OnDownloadListener() { @Override public void onDownloadComplete() { // disabling the start button btnStart.setEnabled(false); // disabling the cancel button btnCancel.setEnabled(false); // setting the text completed to start button btnStart.setText("Completed"); // will show the path after the file is downloaded file_downloaded_path.setText("File stored at : " + path); Toast.makeText(MainActivity.this, "Downloading Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Error error) { // setting the text start btnStart.setText("Start"); // resetting the download percentage downloading_percent.setText("0"); // resetting the progressbar progressBar.setProgress(0); // resetting the downloadID downloadID = 0; // enabling the start button btnStart.setEnabled(true); // disabling the cancel button btnCancel.setEnabled(false); progressBar.setIndeterminate(false); Toast.makeText(MainActivity.this, "Error Occurred", Toast.LENGTH_SHORT).show(); } }); // handling click event on cancel button btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnStart.setText("Start"); // cancels the download PRDownloader.cancel(downloadID); } }); } }); }} Output: germanshephered48 kk9826225 Picked Android Java 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": "\n22 Feb, 2022" }, { "code": null, "e": 802, "s": 52, "text": "PRDownloader library is a file downloader library for android. It comes with pause and resumes support while downloading a file. This library is capable of downloading large files from the internet and can download any type of file like image, video, pdf, apk and etc. It provides many features that can help a user to download files from the internet easily and efficiently. With this library, you can also check the status of the downloading using the download id and can perform many other important operations using the download id. This library contains many important methods that give full control to the user to handle the downloading states of the file like pause, cancel, resume, etc. You can make the following Requests with this library:" }, { "code": null, "e": 828, "s": 802, "text": "Pause a download request:" }, { "code": null, "e": 860, "s": 828, "text": "PRDownloader.pause(downloadId);" }, { "code": null, "e": 887, "s": 860, "text": "Cancel a download request:" }, { "code": null, "e": 1110, "s": 887, "text": "// Cancel with the download id\nPRDownloader.cancel(downloadId);\n// The tag can be set to any request and then can be used to cancel the request\nPRDownloader.cancel(TAG);\n// Cancel all the requests\nPRDownloader.cancelAll();" }, { "code": null, "e": 1137, "s": 1110, "text": "Resume a download request:" }, { "code": null, "e": 1170, "s": 1137, "text": "PRDownloader.resume(downloadId);" }, { "code": null, "e": 1204, "s": 1170, "text": "Get status of a download request:" }, { "code": null, "e": 1256, "s": 1204, "text": "Status status = PRDownloader.getStatus(downloadId);" }, { "code": null, "e": 1423, "s": 1256, "text": "A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1452, "s": 1423, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1656, "s": 1452, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Then Enter your App Name in the Name field and select Java from the Language drop-down menu." }, { "code": null, "e": 1680, "s": 1656, "text": "Step 2: Add dependency" }, { "code": null, "e": 1868, "s": 1680, "text": "To add the dependency navigate to app > Gradle Scripts > gradle.build(Module: app) and add the below dependency in the dependencies section. After adding the dependency sync your project." }, { "code": null, "e": 1925, "s": 1868, "text": "implementation 'com.mindorks.android:prdownloader:0.6.0'" }, { "code": null, "e": 1957, "s": 1925, "text": "Step 3: Add Internet Permission" }, { "code": null, "e": 2039, "s": 1957, "text": "Navigate to app > manifest > AndroidManifest.xml and add the internet permission." }, { "code": null, "e": 2101, "s": 2039, "text": "<uses-permission android:name=\"android.permission.INTERNET\"/>" }, { "code": null, "e": 2149, "s": 2101, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2292, "s": 2149, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 2296, "s": 2292, "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\"> <!-- EditText to take the url from the user --> <EditText android:id=\"@+id/url_etText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"@string/type_or_paste_your_url_here\" /> <!-- Button to start downloading from file --> <Button android:id=\"@+id/btn_download\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/url_etText\" android:layout_centerHorizontal=\"true\" android:text=\"@string/download\" /> <!-- linear layout that contains widgets to show information --> <LinearLayout android:id=\"@+id/details_box\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/btn_download\" android:layout_margin=\"10dp\" android:layout_marginTop=\"20dp\" android:background=\"@drawable/box_design_layout\" android:orientation=\"vertical\" android:padding=\"10dp\" android:visibility=\"gone\"> <!-- Textview to show the file name --> <TextView android:id=\"@+id/file_name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/click_on_start_button_to_start_downloading\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- progress bar to show the progress of downloading --> <ProgressBar android:id=\"@+id/progress_horizontal\" style=\"@style/Widget.AppCompat.ProgressBar.Horizontal\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"4dp\" android:layout_marginRight=\"4dp\" android:progressTint=\"@color/purple_200\" tools:ignore=\"UnusedAttribute\" /> <!-- textview to show the downloading percentage --> <TextView android:id=\"@+id/downloading_percentage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:textAlignment=\"center\" android:textSize=\"12sp\" android:textStyle=\"bold\" /> <!-- this linear layout contains buttons --> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:orientation=\"horizontal\" android:padding=\"10dp\"> <!-- button to start the downloading --> <Button android:id=\"@+id/btn_start\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/start\" /> <!-- button to cancel or stop the downloading --> <Button android:id=\"@+id/btn_stop\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/stop\" /> </LinearLayout> </LinearLayout> <!-- this textview will show the path where the downloaded file is stored --> <TextView android:id=\"@+id/txt_url\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/details_box\" android:layout_marginTop=\"10dp\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 6181, "s": 2296, "text": null }, { "code": null, "e": 6227, "s": 6184, "text": "Below is the code for the Strings.xml file" }, { "code": null, "e": 6233, "s": 6229, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG PRDownloader Library</string> <string name=\"download\">DOWNLOAD</string> <string name=\"type_or_paste_your_url_here\">Type or Paste Your URL Here</string> <string name=\"start\">START</string> <string name=\"stop\">STOP</string> <string name=\"click_on_start_button_to_start_downloading\">Click on Start Button to Start Downloading</string></resources>", "e": 6635, "s": 6233, "text": null }, { "code": null, "e": 6671, "s": 6638, "text": "Step 5: Designing the box layout" }, { "code": null, "e": 6828, "s": 6673, "text": "Navigate to app > res > drawable > right-click > new > Drawable Resource File and name that file as box_design_layout and add the below code to that file." }, { "code": null, "e": 6834, "s": 6830, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:bottomLeftRadius=\"0dp\" android:bottomRightRadius=\"0dp\" android:topLeftRadius=\"0dp\" android:topRightRadius=\"0dp\" /> <stroke android:width=\"1dp\" android:color=\"@android:color/black\" /> <solid android:color=\"@android:color/transparent\" /> </shape>", "e": 7288, "s": 6834, "text": null }, { "code": null, "e": 7317, "s": 7291, "text": "Step 6: Create Util class" }, { "code": null, "e": 7493, "s": 7319, "text": "Navigate to app > java > package name > right-click > New >Java class and name that file as Utils.java. Add the below code into Utils.java. Below is the code for Utils.java." }, { "code": null, "e": 7500, "s": 7495, "text": "Java" }, { "code": "import android.content.Context;import android.os.Environment; import androidx.core.content.ContextCompat; import java.io.File;import java.util.Locale; public final class Utils { private Utils() { } public static String getRootDirPath(Context context) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null)[0]; return file.getAbsolutePath(); } else { return context.getApplicationContext().getFilesDir().getAbsolutePath(); } } public static String getProgressDisplayLine(long currentBytes, long totalBytes) { return getBytesToMBString(currentBytes) + \"/\" + getBytesToMBString(totalBytes); } private static String getBytesToMBString(long bytes) { return String.format(Locale.ENGLISH, \"%.2fMb\", bytes / (1024.00 * 1024.00)); }}", "e": 8434, "s": 7500, "text": null }, { "code": null, "e": 8480, "s": 8437, "text": "Step 7: Working with the MainActivity.java" }, { "code": null, "e": 8672, "s": 8482, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 8679, "s": 8674, "text": "Java" }, { "code": "import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.webkit.URLUtil;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.downloader.Error;import com.downloader.OnCancelListener;import com.downloader.OnDownloadListener;import com.downloader.OnPauseListener;import com.downloader.OnProgressListener;import com.downloader.OnStartOrResumeListener;import com.downloader.PRDownloader;import com.downloader.Progress;import com.downloader.Status; public class MainActivity extends AppCompatActivity { private EditText editTextUrl; private String path; private TextView file_downloaded_path, file_name, downloading_percent; private ProgressBar progressBar; private Button btnStart, btnCancel, buttonDownload; private LinearLayout details; int downloadID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing PRDownloader library PRDownloader.initialize(this); // finding edittext by its id editTextUrl = findViewById(R.id.url_etText); // finding button by its id buttonDownload = findViewById(R.id.btn_download); // finding textview by its id file_downloaded_path = findViewById(R.id.txt_url); // finding textview by its id file_name = findViewById(R.id.file_name); // finding progressbar by its id progressBar = findViewById(R.id.progress_horizontal); // finding textview by its id downloading_percent = findViewById(R.id.downloading_percentage); // finding button by its id btnStart = findViewById(R.id.btn_start); // finding button by its id btnCancel = findViewById(R.id.btn_stop); // finding linear layout by its id details = findViewById(R.id.details_box); //storing the path of the file path = Utils.getRootDirPath(this); // handling onclick event on button buttonDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // getting the text from edittext // and storing it to url variable String url = editTextUrl.getText().toString().trim(); // setting the visibility of linear layout to visible details.setVisibility(View.VISIBLE); // calling method downloadFile passing url as parameter downloadFile(url); } }); } @SuppressLint(\"SetTextI18n\") private void downloadFile(final String url) { // handing click event on start button // which starts the downloading of the file btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // checks if the process is already running if (Status.RUNNING == PRDownloader.getStatus(downloadID)) { // pauses the download if // user click on pause button PRDownloader.pause(downloadID); return; } // enabling the start button btnStart.setEnabled(false); // checks if the status is paused if (Status.PAUSED == PRDownloader.getStatus(downloadID)) { // resume the download if download is paused PRDownloader.resume(downloadID); return; } // getting the filename String fileName = URLUtil.guessFileName(url, null, null); // setting the file name file_name.setText(\"Downloading \" + fileName); // making the download request downloadID = PRDownloader.download(url, path, fileName) .build() .setOnStartOrResumeListener(new OnStartOrResumeListener() { @SuppressLint(\"SetTextI18n\") @Override public void onStartOrResume() { progressBar.setIndeterminate(false); // enables the start button btnStart.setEnabled(true); // setting the text of start button to pause btnStart.setText(\"Pause\"); // enabling the stop button btnCancel.setEnabled(true); Toast.makeText(MainActivity.this, \"Downloading started\", Toast.LENGTH_SHORT).show(); } }) .setOnPauseListener(new OnPauseListener() { @Override public void onPause() { // setting the text of start button to resume // when the download is in paused state btnStart.setText(\"Resume\"); Toast.makeText(MainActivity.this, \"Downloading Paused\", Toast.LENGTH_SHORT).show(); } }) .setOnCancelListener(new OnCancelListener() { @Override public void onCancel() { // resetting the downloadId when // the download is cancelled downloadID = 0; // setting the text of start button to start btnStart.setText(\"Start\"); // disabling the cancel button btnCancel.setEnabled(false); // resetting the progress bar progressBar.setProgress(0); // resetting the download percent downloading_percent.setText(\"\"); progressBar.setIndeterminate(false); Toast.makeText(MainActivity.this, \"Downloading Cancelled\", Toast.LENGTH_SHORT).show(); } }) .setOnProgressListener(new OnProgressListener() { @Override public void onProgress(Progress progress) { // getting the progress of download long progressPer = progress.currentBytes * 100 / progress.totalBytes; // setting the progress to progressbar progressBar.setProgress((int) progressPer); // setting the download percent downloading_percent.setText(Utils.getProgressDisplayLine(progress.currentBytes, progress.totalBytes)); progressBar.setIndeterminate(false); } }) .start(new OnDownloadListener() { @Override public void onDownloadComplete() { // disabling the start button btnStart.setEnabled(false); // disabling the cancel button btnCancel.setEnabled(false); // setting the text completed to start button btnStart.setText(\"Completed\"); // will show the path after the file is downloaded file_downloaded_path.setText(\"File stored at : \" + path); Toast.makeText(MainActivity.this, \"Downloading Completed\", Toast.LENGTH_SHORT).show(); } @Override public void onError(Error error) { // setting the text start btnStart.setText(\"Start\"); // resetting the download percentage downloading_percent.setText(\"0\"); // resetting the progressbar progressBar.setProgress(0); // resetting the downloadID downloadID = 0; // enabling the start button btnStart.setEnabled(true); // disabling the cancel button btnCancel.setEnabled(false); progressBar.setIndeterminate(false); Toast.makeText(MainActivity.this, \"Error Occurred\", Toast.LENGTH_SHORT).show(); } }); // handling click event on cancel button btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnStart.setText(\"Start\"); // cancels the download PRDownloader.cancel(downloadID); } }); } }); }}", "e": 18513, "s": 8679, "text": null }, { "code": null, "e": 18524, "s": 18516, "text": "Output:" }, { "code": null, "e": 18546, "s": 18528, "text": "germanshephered48" }, { "code": null, "e": 18556, "s": 18546, "text": "kk9826225" }, { "code": null, "e": 18563, "s": 18556, "text": "Picked" }, { "code": null, "e": 18571, "s": 18563, "text": "Android" }, { "code": null, "e": 18576, "s": 18571, "text": "Java" }, { "code": null, "e": 18581, "s": 18576, "text": "Java" }, { "code": null, "e": 18589, "s": 18581, "text": "Android" } ]
Inheritance in Java
25 May, 2022 Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology: Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class). Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. How to use inheritance in Java The keyword used for inheritance is extends. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Syntax : class derived-class extends base-class { //methods and fields } Example: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends Bicycle class and class Test is a driver class to run program. Java // Java program to illustrate the// concept of inheritance // base classclass Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } // toString() method to print info of Bicycle public String toString() { return ("No of gears are " + gear + "\n" + "speed of bicycle is " + speed); }} // derived classclass MountainBike extends Bicycle { // the MountainBike subclass adds one more field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int gear, int speed, int startHeight) { // invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the MountainBike subclass adds one more method public void setHeight(int newValue) { seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info @Override public String toString() { return (super.toString() + "\nseat height is " + seatHeight); }} // driver classpublic class Test { public static void main(String args[]) { MountainBike mb = new MountainBike(3, 100, 25); System.out.println(mb.toString()); }} No of gears are 3 speed of bicycle is 100 seat height is 25 In the above program, when an object of MountainBike class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass. Please note that during inheritance only the object of the subclass is created, not the superclass. For more, refer Java Object Creation of Inherited Class. Illustrative image of the program: In practice, inheritance and polymorphism are used together in java to achieve fast performance and readability of code. Types of Inheritance in Java Below are the different types of inheritance which are supported by Java. 1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B. Java // Java program to illustrate the// concept of single inheritanceimport java.io.*;import java.lang.*;import java.util.*; class one { public void print_geek() { System.out.println("Geeks"); }} class two extends one { public void print_for() { System.out.println("for"); }}// Driver classpublic class Main { public static void main(String[] args) { two g = new two(); g.print_geek(); g.print_for(); g.print_geek(); }} Geeks for Geeks 2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. Java // Java program to illustrate the// concept of Multilevel inheritanceimport java.io.*;import java.lang.*;import java.util.*; class one { public void print_geek() { System.out.println("Geeks"); }} class two extends one { public void print_for() { System.out.println("for"); }} class three extends two { public void print_geek() { System.out.println("Geeks"); }} // Drived classpublic class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); g.print_for(); g.print_geek(); }} Geeks for Geeks 3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D. Java // Java program to illustrate the// concept of Hierarchical inheritance class A { public void print_A() { System.out.println("Class A"); }} class B extends A { public void print_B() { System.out.println("Class B"); }} class C extends A { public void print_C() { System.out.println("Class C"); }} class D extends A { public void print_D() { System.out.println("Class D"); }} // Driver Classpublic class Test { public static void main(String[] args) { B obj_B = new B(); obj_B.print_A(); obj_B.print_B(); C obj_C = new C(); obj_C.print_A(); obj_C.print_C(); D obj_D = new D(); obj_D.print_A(); obj_D.print_D(); }} Class A Class B Class A Class C Class A Class D Hierarchical Inheritance 4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from interface A and B. Java // Java program to illustrate the// concept of Multiple inheritanceimport java.io.*;import java.lang.*;import java.util.*; interface one { public void print_geek();} interface two { public void print_for();} interface three extends one, two { public void print_geek();}class child implements three { @Override public void print_geek() { System.out.println("Geeks"); } public void print_for() { System.out.println("for"); }} // Drived classpublic class Main { public static void main(String[] args) { child c = new child(); c.print_geek(); c.print_for(); c.print_geek(); }} Geeks for Geeks 5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces. Important facts about inheritance in Java Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class. Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by java. Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass. Java IS-A type of Relationship. IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. Java public class SolarSystem {}public class Earth extends SolarSystem {}public class Mars extends SolarSystem {}public class Moon extends Earth {} Now, based on the above example, in Object-Oriented terms, the following are true:- SolarSystem the superclass of Earth class.SolarSystem the superclass of Mars class.Earth and Mars are subclasses of SolarSystem class.Moon is the subclass of both Earth and SolarSystem classes. SolarSystem the superclass of Earth class. SolarSystem the superclass of Mars class. Earth and Mars are subclasses of SolarSystem class. Moon is the subclass of both Earth and SolarSystem classes. Java class SolarSystem {}class Earth extends SolarSystem {}class Mars extends SolarSystem {}public class Moon extends Earth { public static void main(String args[]) { SolarSystem s = new SolarSystem(); Earth e = new Earth(); Mars m = new Mars(); System.out.println(s instanceof SolarSystem); System.out.println(e instanceof Earth); System.out.println(m instanceof SolarSystem); }} true true true What all can be done in a Subclass? In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members: The inherited fields can be used directly, just like any other fields. We can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in the example above, toString() method is overridden). We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. We can declare new methods in the subclass that are not in the superclass. We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. sai003 Jitender_1998 kshitijmotke asmitsirohi java-inheritance Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initialize an ArrayList in Java Initializing a List in Java Generics in Java Java Programming Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 245, "s": 52, "text": "Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. " }, { "code": null, "e": 269, "s": 245, "text": "Important terminology: " }, { "code": null, "e": 380, "s": 269, "text": "Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class)." }, { "code": null, "e": 605, "s": 380, "text": "Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods." }, { "code": null, "e": 912, "s": 605, "text": "Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class." }, { "code": null, "e": 943, "s": 912, "text": "How to use inheritance in Java" }, { "code": null, "e": 989, "s": 943, "text": "The keyword used for inheritance is extends. " }, { "code": null, "e": 998, "s": 989, "text": "Chapters" }, { "code": null, "e": 1025, "s": 998, "text": "descriptions off, selected" }, { "code": null, "e": 1075, "s": 1025, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1098, "s": 1075, "text": "captions off, selected" }, { "code": null, "e": 1106, "s": 1098, "text": "English" }, { "code": null, "e": 1130, "s": 1106, "text": "This is a modal window." }, { "code": null, "e": 1199, "s": 1130, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1221, "s": 1199, "text": "End of dialog window." }, { "code": null, "e": 1231, "s": 1221, "text": "Syntax : " }, { "code": null, "e": 1306, "s": 1231, "text": "class derived-class extends base-class \n{ \n //methods and fields \n} " }, { "code": null, "e": 1498, "s": 1306, "text": "Example: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends Bicycle class and class Test is a driver class to run program. " }, { "code": null, "e": 1503, "s": 1498, "text": "Java" }, { "code": "// Java program to illustrate the// concept of inheritance // base classclass Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } // toString() method to print info of Bicycle public String toString() { return (\"No of gears are \" + gear + \"\\n\" + \"speed of bicycle is \" + speed); }} // derived classclass MountainBike extends Bicycle { // the MountainBike subclass adds one more field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int gear, int speed, int startHeight) { // invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the MountainBike subclass adds one more method public void setHeight(int newValue) { seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info @Override public String toString() { return (super.toString() + \"\\nseat height is \" + seatHeight); }} // driver classpublic class Test { public static void main(String args[]) { MountainBike mb = new MountainBike(3, 100, 25); System.out.println(mb.toString()); }}", "e": 3127, "s": 1503, "text": null }, { "code": null, "e": 3188, "s": 3127, "text": "No of gears are 3\nspeed of bicycle is 100\nseat height is 25\n" }, { "code": null, "e": 3438, "s": 3188, "text": "In the above program, when an object of MountainBike class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass. " }, { "code": null, "e": 3596, "s": 3438, "text": "Please note that during inheritance only the object of the subclass is created, not the superclass. For more, refer Java Object Creation of Inherited Class. " }, { "code": null, "e": 3633, "s": 3596, "text": "Illustrative image of the program: " }, { "code": null, "e": 3754, "s": 3633, "text": "In practice, inheritance and polymorphism are used together in java to achieve fast performance and readability of code." }, { "code": null, "e": 3783, "s": 3754, "text": "Types of Inheritance in Java" }, { "code": null, "e": 3858, "s": 3783, "text": "Below are the different types of inheritance which are supported by Java. " }, { "code": null, "e": 4031, "s": 3858, "text": "1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B." }, { "code": null, "e": 4036, "s": 4031, "text": "Java" }, { "code": "// Java program to illustrate the// concept of single inheritanceimport java.io.*;import java.lang.*;import java.util.*; class one { public void print_geek() { System.out.println(\"Geeks\"); }} class two extends one { public void print_for() { System.out.println(\"for\"); }}// Driver classpublic class Main { public static void main(String[] args) { two g = new two(); g.print_geek(); g.print_for(); g.print_geek(); }}", "e": 4510, "s": 4036, "text": null }, { "code": null, "e": 4527, "s": 4510, "text": "Geeks\nfor\nGeeks\n" }, { "code": null, "e": 4910, "s": 4527, "text": "2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members." }, { "code": null, "e": 4915, "s": 4910, "text": "Java" }, { "code": "// Java program to illustrate the// concept of Multilevel inheritanceimport java.io.*;import java.lang.*;import java.util.*; class one { public void print_geek() { System.out.println(\"Geeks\"); }} class two extends one { public void print_for() { System.out.println(\"for\"); }} class three extends two { public void print_geek() { System.out.println(\"Geeks\"); }} // Drived classpublic class Main { public static void main(String[] args) { three g = new three(); g.print_geek(); g.print_for(); g.print_geek(); }}", "e": 5501, "s": 4915, "text": null }, { "code": null, "e": 5518, "s": 5501, "text": "Geeks\nfor\nGeeks\n" }, { "code": null, "e": 5735, "s": 5518, "text": "3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D." }, { "code": null, "e": 5740, "s": 5735, "text": "Java" }, { "code": "// Java program to illustrate the// concept of Hierarchical inheritance class A { public void print_A() { System.out.println(\"Class A\"); }} class B extends A { public void print_B() { System.out.println(\"Class B\"); }} class C extends A { public void print_C() { System.out.println(\"Class C\"); }} class D extends A { public void print_D() { System.out.println(\"Class D\"); }} // Driver Classpublic class Test { public static void main(String[] args) { B obj_B = new B(); obj_B.print_A(); obj_B.print_B(); C obj_C = new C(); obj_C.print_A(); obj_C.print_C(); D obj_D = new D(); obj_D.print_A(); obj_D.print_D(); }}", "e": 6446, "s": 5740, "text": null }, { "code": null, "e": 6495, "s": 6446, "text": "Class A\nClass B\nClass A\nClass C\nClass A\nClass D\n" }, { "code": null, "e": 6520, "s": 6495, "text": "Hierarchical Inheritance" }, { "code": null, "e": 6893, "s": 6522, "text": "4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from interface A and B." }, { "code": null, "e": 6898, "s": 6893, "text": "Java" }, { "code": "// Java program to illustrate the// concept of Multiple inheritanceimport java.io.*;import java.lang.*;import java.util.*; interface one { public void print_geek();} interface two { public void print_for();} interface three extends one, two { public void print_geek();}class child implements three { @Override public void print_geek() { System.out.println(\"Geeks\"); } public void print_for() { System.out.println(\"for\"); }} // Drived classpublic class Main { public static void main(String[] args) { child c = new child(); c.print_geek(); c.print_for(); c.print_geek(); }}", "e": 7542, "s": 6898, "text": null }, { "code": null, "e": 7559, "s": 7542, "text": "Geeks\nfor\nGeeks\n" }, { "code": null, "e": 7850, "s": 7559, "text": "5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces. " }, { "code": null, "e": 7893, "s": 7850, "text": "Important facts about inheritance in Java " }, { "code": null, "e": 8139, "s": 7893, "text": "Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class." }, { "code": null, "e": 8405, "s": 8139, "text": "Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by java." }, { "code": null, "e": 8668, "s": 8405, "text": "Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass." }, { "code": null, "e": 8924, "s": 8668, "text": "Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass." }, { "code": null, "e": 8956, "s": 8924, "text": "Java IS-A type of Relationship." }, { "code": null, "e": 9086, "s": 8956, "text": "IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance." }, { "code": null, "e": 9091, "s": 9086, "text": "Java" }, { "code": "public class SolarSystem {}public class Earth extends SolarSystem {}public class Mars extends SolarSystem {}public class Moon extends Earth {}", "e": 9234, "s": 9091, "text": null }, { "code": null, "e": 9318, "s": 9234, "text": "Now, based on the above example, in Object-Oriented terms, the following are true:-" }, { "code": null, "e": 9512, "s": 9318, "text": "SolarSystem the superclass of Earth class.SolarSystem the superclass of Mars class.Earth and Mars are subclasses of SolarSystem class.Moon is the subclass of both Earth and SolarSystem classes." }, { "code": null, "e": 9555, "s": 9512, "text": "SolarSystem the superclass of Earth class." }, { "code": null, "e": 9597, "s": 9555, "text": "SolarSystem the superclass of Mars class." }, { "code": null, "e": 9649, "s": 9597, "text": "Earth and Mars are subclasses of SolarSystem class." }, { "code": null, "e": 9709, "s": 9649, "text": "Moon is the subclass of both Earth and SolarSystem classes." }, { "code": null, "e": 9714, "s": 9709, "text": "Java" }, { "code": "class SolarSystem {}class Earth extends SolarSystem {}class Mars extends SolarSystem {}public class Moon extends Earth { public static void main(String args[]) { SolarSystem s = new SolarSystem(); Earth e = new Earth(); Mars m = new Mars(); System.out.println(s instanceof SolarSystem); System.out.println(e instanceof Earth); System.out.println(m instanceof SolarSystem); }}", "e": 10143, "s": 9714, "text": null }, { "code": null, "e": 10159, "s": 10143, "text": "true\ntrue\ntrue\n" }, { "code": null, "e": 10195, "s": 10159, "text": "What all can be done in a Subclass?" }, { "code": null, "e": 10303, "s": 10195, "text": "In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members: " }, { "code": null, "e": 10374, "s": 10303, "text": "The inherited fields can be used directly, just like any other fields." }, { "code": null, "e": 10448, "s": 10374, "text": "We can declare new fields in the subclass that are not in the superclass." }, { "code": null, "e": 10504, "s": 10448, "text": "The inherited methods can be used directly as they are." }, { "code": null, "e": 10692, "s": 10504, "text": "We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in the example above, toString() method is overridden)." }, { "code": null, "e": 10815, "s": 10692, "text": "We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it." }, { "code": null, "e": 10890, "s": 10815, "text": "We can declare new methods in the subclass that are not in the superclass." }, { "code": null, "e": 11023, "s": 10890, "text": "We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super." }, { "code": null, "e": 11030, "s": 11023, "text": "sai003" }, { "code": null, "e": 11044, "s": 11030, "text": "Jitender_1998" }, { "code": null, "e": 11057, "s": 11044, "text": "kshitijmotke" }, { "code": null, "e": 11069, "s": 11057, "text": "asmitsirohi" }, { "code": null, "e": 11086, "s": 11069, "text": "java-inheritance" }, { "code": null, "e": 11091, "s": 11086, "text": "Java" }, { "code": null, "e": 11096, "s": 11091, "text": "Java" }, { "code": null, "e": 11194, "s": 11096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11230, "s": 11194, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 11274, "s": 11230, "text": "Split() String method in Java with examples" }, { "code": null, "e": 11299, "s": 11274, "text": "Reverse a string in Java" }, { "code": null, "e": 11330, "s": 11299, "text": "How to iterate any Map in Java" }, { "code": null, "e": 11345, "s": 11330, "text": "Stream In Java" }, { "code": null, "e": 11369, "s": 11345, "text": "Singleton Class in Java" }, { "code": null, "e": 11401, "s": 11369, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 11429, "s": 11401, "text": "Initializing a List in Java" }, { "code": null, "e": 11446, "s": 11429, "text": "Generics in Java" } ]
Delete nodes which have a greater value on right side
14 Jan, 2022 Given a singly linked list, remove all the nodes which have a greater value on the right side. Examples: a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. When we examine 12, we see that after 12 there is one node with a value greater than 12 (i.e. 15), so we delete 12. When we examine 15, we find no node after 15 that has a value greater than 15, so we keep this node. When we go like this, we get 15->6->3b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that 10, 20, 30, 40, and 50 have been deleted because they all have a greater value on the right side.c) The list 60->50->40->30->20->10->NULL should not be changed. Method 1 (Simple) Use two loops. In the outer loop, pick nodes of the linked list one by one. In the inner loop, check if there exists a node whose value is greater than the picked node. If there exists a node whose value is greater, then delete the picked node. Time Complexity: O(n^2) Method 2 (Use Reverse) Thanks to Paras for providing the below algorithm. 1. Reverse the list. 2. Traverse the reversed list. Keep max till now. If the next node is less than max, then delete the next node, otherwise max = next node. 3. Reverse the list again to retain the original order. Time Complexity: O(n)Thanks to R.Srinivasan for providing the code below. C++ C Java C# Javascript // C++ program to delete nodes// which have a greater value on// right side#include <bits/stdc++.h>using namespace std; /* structure of a linked list node */struct Node{ int data; struct Node* next;}; /* prototype for utility functions */void reverseList(struct Node** headref);void _delLesserNodes(struct Node* head); /* Deletes nodes which have a node withgreater value node on left side */void delLesserNodes(struct Node** head_ref){ /* 1) Reverse the linked list */ reverseList(head_ref); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(*head_ref); /* 3) Reverse the linked list again to retain the original order */ reverseList(head_ref);} /* Deletes nodes which havegreater value node(s) on left side */void _delLesserNodes(struct Node* head){ struct Node* current = head; /* Initialize max */ struct Node* maxnode = head; struct Node* temp; while (current != NULL && current->next != NULL) { /* If current is smaller than max, then delete current */ if (current->next->data < maxnode->data) { temp = current->next; current->next = temp->next; free(temp); } /* If current is greater than max, then update max and move current */ else { current = current->next; maxnode = current; } }} /* Utility function to insert a nodeat the beginning */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to reverse a linked list */void reverseList(struct Node** headref){ struct Node* current = *headref; struct Node* prev = NULL; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *headref = prev;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { cout << " " << head->data ; head = head->next; } cout << "\n" ;} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); cout << "Given Linked List \n" ; printList(head); delLesserNodes(&head); cout << "Modified Linked List \n" ; printList(head); return 0;} // This code is contributed by shivanisinghss2110 // C program to delete nodes which have a greater value on// right side#include <stdio.h>#include <stdlib.h> /* structure of a linked list node */struct Node { int data; struct Node* next;}; /* prototype for utility functions */void reverseList(struct Node** headref);void _delLesserNodes(struct Node* head); /* Deletes nodes which have a node with greater value node on left side */void delLesserNodes(struct Node** head_ref){ /* 1) Reverse the linked list */ reverseList(head_ref); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(*head_ref); /* 3) Reverse the linked list again to retain the original order */ reverseList(head_ref);} /* Deletes nodes which have greater value node(s) on left side */void _delLesserNodes(struct Node* head){ struct Node* current = head; /* Initialize max */ struct Node* maxnode = head; struct Node* temp; while (current != NULL && current->next != NULL) { /* If current is smaller than max, then delete current */ if (current->next->data < maxnode->data) { temp = current->next; current->next = temp->next; free(temp); } /* If current is greater than max, then update max and move current */ else { current = current->next; maxnode = current; } }} /* Utility function to insert a node at the beginning */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to reverse a linked list */void reverseList(struct Node** headref){ struct Node* current = *headref; struct Node* prev = NULL; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *headref = prev;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n");} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); printf("Given Linked List \n"); printList(head); delLesserNodes(&head); printf("Modified Linked List \n"); printList(head); return 0;} // Java program to delete nodes which have a greater value on// right sideclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Deletes nodes which have a node with greater value node on left side */ void delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(); /* 3) Reverse the linked list again to retain the original order */ reverseList(); } /* Deletes nodes which have greater value node(s) on left side */ void _delLesserNodes() { Node current = head; /* Initialise max */ Node maxnode = head; Node temp; while (current != null && current.next != null) { /* If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ void reverseList() { Node current = head; Node prev = null; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ llist.push(3); llist.push(2); llist.push(6); llist.push(5); llist.push(11); llist.push(10); llist.push(15); llist.push(12); System.out.println("Given Linked List"); llist.printList(); llist.delLesserNodes(); System.out.println("Modified Linked List"); llist.printList(); }} /* This code is contributed by Rajat Mishra */ // C# program to delete nodes which have a greater value on// right sideusing System; class LinkedList{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Deletes nodes which have a node with greater value node on left side */ void delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(); /* 3) Reverse the linked list again to retain the original order */ reverseList(); } /* Deletes nodes which have greater value node(s) on left side */ void _delLesserNodes() { Node current = head; /* Initialise max */ Node maxnode = head; Node temp; while (current != null && current.next != null) { /* If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ void reverseList() { Node current = head; Node prev = null; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(string []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ llist.push(3); llist.push(2); llist.push(6); llist.push(5); llist.push(11); llist.push(10); llist.push(15); llist.push(12); Console.WriteLine("Given Linked List"); llist.printList(); llist.delLesserNodes(); Console.WriteLine("Modified Linked List"); llist.printList(); }} // This code is contributed by pratham76 <script>// javascript program to delete nodes which have a greater value on// right side var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Deletes nodes which have a node with greater value node on left side */ function delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* * 2) In the reversed list, delete nodes which have a node with greater value * node on left side. Note that head node is never deleted because it is the * leftmost node. */ _delLesserNodes(); /* * 3) Reverse the linked list again to retain the original order */ reverseList(); } /* * Deletes nodes which have greater value node(s) on left side */ function _delLesserNodes() { var current = head; /* Initialise max */ var maxnode = head; var temp; while (current != null && current.next != null) { /* * If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* * If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ function reverseList() { var current = head; var prev = null; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write(); } /* Driver program to test above functions */ /* * Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ push(3); push(2); push(6); push(5); push(11); push(10); push(15); push(12); document.write("Given Linked List<br/>"); printList(); delLesserNodes(); document.write("<br/>Modified Linked List<br/>"); printList(); // This code contributed by aashish1995</script> Given Linked List 12 15 10 11 5 6 2 3 Modified Linked List 15 11 6 3 Method 3: The other simpler method is to traverse the list from the start and delete the node when the current Node < next Node. To delete the current node, follow this approach. Let us assume you have to delete current node X 1. Copy next node’s data into X i.e X.data = X.next.data 2. Copy next node’s next address i.e X.next = X.next.next; Move forward in the List only when the current Node is > the next Node. Java C# Javascript // Java program for above approachimport java.io.*; // This class represents a single node// in a linked listclass Node { int data; Node next; public Node(int data){ this.data = data; this.next = null; }} //This is a utility class for linked listclass LLUtil{ // This function creates a linked list from a // given array and returns head public Node createLL(int[] arr){ Node head = new Node(arr[0]); Node temp = head; Node newNode = null; for(int i = 1; i < arr.length; i++){ newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } //This function prints given linked list public void printLL(Node head){ while(head != null){ System.out.print(head.data + " "); head = head.next; } System.out.println(); } } class GFG { public static void main (String[] args) { int[] arr = {12,15,10,11,5,6,2,3}; LLUtil llu = new LLUtil(); Node head = llu.createLL(arr); System.out.println("Given Linked List"); llu.printLL(head); head = deleteNodesOnRightSide(head); System.out.println("Modified Linked List"); llu.printLL(head); } //Main function public static Node deleteNodesOnRightSide(Node head){ if(head == null || head.next == null) return head; Node nextNode = deleteNodesOnRightSide(head.next); if(nextNode.data > head.data) return nextNode; head.next = nextNode; return head; }} // C# program for above approachusing System; // This class represents a single node// in a linked listclass Node{ public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }} // This is a utility class for linked listclass LLUtil{ // This function creates a linked list // from a given array and returns head public Node createLL(int[] arr) { Node head = new Node(arr[0]); Node temp = head; Node newNode = null; for(int i = 1; i < arr.Length; i++) { newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } // This function prints given linked list public void printLL(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine(); }} class GFG{ // Driver Codepublic static void Main(string[] args){ int[] arr = { 12, 15, 10, 11, 5, 6, 2, 3 }; LLUtil llu = new LLUtil(); Node head = llu.createLL(arr); Console.WriteLine("Given Linked List"); llu.printLL(head); deleteNodesOnRightSide(head); Console.WriteLine("Modified Linked List"); llu.printLL(head);} // Main functionpublic static void deleteNodesOnRightSide(Node head){ Node temp = head; while (temp != null && temp.next != null) { // Copying next node data into current node // i.e. we are indirectly deleting current node if (temp.data < temp.next.data) { temp.data = temp.next.data; temp.next = temp.next.next; } else { // Move to the next node temp = temp.next; } }}} // This code is contributed by rutvik_56 <script>// javascript program for above approach// This class represents a single node// in a linked listclass Node { constructor(val) { this.data = val; this.next = null; }} // This is a utility class for linked list // This function creates a linked list from a // given array and returns head function createLL(arr) { var head = new Node(arr[0]);var temp = head; var newNode = null; for (i = 1; i < arr.length; i++) { newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } // This function prints given linked list function printLL(head) { while (head != null) { document.write(head.data + " "); head = head.next; } document.write("<br/>"); } // Main function function deleteNodesOnRightSide(head) { if (head == null || head.next == null) return head;var nextNode = deleteNodesOnRightSide(head.next); if (nextNode.data > head.data) return nextNode; head.next = nextNode; return head;}var arr = [ 12, 15, 10, 11, 5, 6, 2, 3 ]; var head = createLL(arr); document.write("Given Linked List<br/>"); printLL(head); head = deleteNodesOnRightSide(head); document.write("<br/>Modified Linked List<br/>"); printLL(head); // This code contributed by aashish1995</script> Given Linked List 12 15 10 11 5 6 2 3 Modified Linked List 15 11 6 3 Source: https://www.geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists-6 Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. Akanksha_Rai shivanisinghss2110 abhilashpotharaju rutvik_56 pratham76 moinahmed9999 aashish1995 arorakashish0911 simmytarika5 Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jan, 2022" }, { "code": null, "e": 150, "s": 54, "text": "Given a singly linked list, remove all the nodes which have a greater value on the right side. " }, { "code": null, "e": 840, "s": 150, "text": "Examples: a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. When we examine 12, we see that after 12 there is one node with a value greater than 12 (i.e. 15), so we delete 12. When we examine 15, we find no node after 15 that has a value greater than 15, so we keep this node. When we go like this, we get 15->6->3b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that 10, 20, 30, 40, and 50 have been deleted because they all have a greater value on the right side.c) The list 60->50->40->30->20->10->NULL should not be changed. " }, { "code": null, "e": 1127, "s": 840, "text": "Method 1 (Simple) Use two loops. In the outer loop, pick nodes of the linked list one by one. In the inner loop, check if there exists a node whose value is greater than the picked node. If there exists a node whose value is greater, then delete the picked node. Time Complexity: O(n^2)" }, { "code": null, "e": 1492, "s": 1127, "text": "Method 2 (Use Reverse) Thanks to Paras for providing the below algorithm. 1. Reverse the list. 2. Traverse the reversed list. Keep max till now. If the next node is less than max, then delete the next node, otherwise max = next node. 3. Reverse the list again to retain the original order. Time Complexity: O(n)Thanks to R.Srinivasan for providing the code below. " }, { "code": null, "e": 1496, "s": 1492, "text": "C++" }, { "code": null, "e": 1498, "s": 1496, "text": "C" }, { "code": null, "e": 1503, "s": 1498, "text": "Java" }, { "code": null, "e": 1506, "s": 1503, "text": "C#" }, { "code": null, "e": 1517, "s": 1506, "text": "Javascript" }, { "code": "// C++ program to delete nodes// which have a greater value on// right side#include <bits/stdc++.h>using namespace std; /* structure of a linked list node */struct Node{ int data; struct Node* next;}; /* prototype for utility functions */void reverseList(struct Node** headref);void _delLesserNodes(struct Node* head); /* Deletes nodes which have a node withgreater value node on left side */void delLesserNodes(struct Node** head_ref){ /* 1) Reverse the linked list */ reverseList(head_ref); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(*head_ref); /* 3) Reverse the linked list again to retain the original order */ reverseList(head_ref);} /* Deletes nodes which havegreater value node(s) on left side */void _delLesserNodes(struct Node* head){ struct Node* current = head; /* Initialize max */ struct Node* maxnode = head; struct Node* temp; while (current != NULL && current->next != NULL) { /* If current is smaller than max, then delete current */ if (current->next->data < maxnode->data) { temp = current->next; current->next = temp->next; free(temp); } /* If current is greater than max, then update max and move current */ else { current = current->next; maxnode = current; } }} /* Utility function to insert a nodeat the beginning */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to reverse a linked list */void reverseList(struct Node** headref){ struct Node* current = *headref; struct Node* prev = NULL; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *headref = prev;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { cout << \" \" << head->data ; head = head->next; } cout << \"\\n\" ;} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); cout << \"Given Linked List \\n\" ; printList(head); delLesserNodes(&head); cout << \"Modified Linked List \\n\" ; printList(head); return 0;} // This code is contributed by shivanisinghss2110", "e": 4357, "s": 1517, "text": null }, { "code": "// C program to delete nodes which have a greater value on// right side#include <stdio.h>#include <stdlib.h> /* structure of a linked list node */struct Node { int data; struct Node* next;}; /* prototype for utility functions */void reverseList(struct Node** headref);void _delLesserNodes(struct Node* head); /* Deletes nodes which have a node with greater value node on left side */void delLesserNodes(struct Node** head_ref){ /* 1) Reverse the linked list */ reverseList(head_ref); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(*head_ref); /* 3) Reverse the linked list again to retain the original order */ reverseList(head_ref);} /* Deletes nodes which have greater value node(s) on left side */void _delLesserNodes(struct Node* head){ struct Node* current = head; /* Initialize max */ struct Node* maxnode = head; struct Node* temp; while (current != NULL && current->next != NULL) { /* If current is smaller than max, then delete current */ if (current->next->data < maxnode->data) { temp = current->next; current->next = temp->next; free(temp); } /* If current is greater than max, then update max and move current */ else { current = current->next; maxnode = current; } }} /* Utility function to insert a node at the beginning */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to reverse a linked list */void reverseList(struct Node** headref){ struct Node* current = *headref; struct Node* prev = NULL; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *headref = prev;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { printf(\"%d \", head->data); head = head->next; } printf(\"\\n\");} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); printf(\"Given Linked List \\n\"); printList(head); delLesserNodes(&head); printf(\"Modified Linked List \\n\"); printList(head); return 0;}", "e": 7105, "s": 4357, "text": null }, { "code": "// Java program to delete nodes which have a greater value on// right sideclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Deletes nodes which have a node with greater value node on left side */ void delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(); /* 3) Reverse the linked list again to retain the original order */ reverseList(); } /* Deletes nodes which have greater value node(s) on left side */ void _delLesserNodes() { Node current = head; /* Initialise max */ Node maxnode = head; Node temp; while (current != null && current.next != null) { /* If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ void reverseList() { Node current = head; Node prev = null; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ llist.push(3); llist.push(2); llist.push(6); llist.push(5); llist.push(11); llist.push(10); llist.push(15); llist.push(12); System.out.println(\"Given Linked List\"); llist.printList(); llist.delLesserNodes(); System.out.println(\"Modified Linked List\"); llist.printList(); }} /* This code is contributed by Rajat Mishra */", "e": 10236, "s": 7105, "text": null }, { "code": "// C# program to delete nodes which have a greater value on// right sideusing System; class LinkedList{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Deletes nodes which have a node with greater value node on left side */ void delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* 2) In the reversed list, delete nodes which have a node with greater value node on left side. Note that head node is never deleted because it is the leftmost node.*/ _delLesserNodes(); /* 3) Reverse the linked list again to retain the original order */ reverseList(); } /* Deletes nodes which have greater value node(s) on left side */ void _delLesserNodes() { Node current = head; /* Initialise max */ Node maxnode = head; Node temp; while (current != null && current.next != null) { /* If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ void reverseList() { Node current = head; Node prev = null; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(string []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ llist.push(3); llist.push(2); llist.push(6); llist.push(5); llist.push(11); llist.push(10); llist.push(15); llist.push(12); Console.WriteLine(\"Given Linked List\"); llist.printList(); llist.delLesserNodes(); Console.WriteLine(\"Modified Linked List\"); llist.printList(); }} // This code is contributed by pratham76", "e": 13470, "s": 10236, "text": null }, { "code": "<script>// javascript program to delete nodes which have a greater value on// right side var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Deletes nodes which have a node with greater value node on left side */ function delLesserNodes() { /* 1.Reverse the linked list */ reverseList(); /* * 2) In the reversed list, delete nodes which have a node with greater value * node on left side. Note that head node is never deleted because it is the * leftmost node. */ _delLesserNodes(); /* * 3) Reverse the linked list again to retain the original order */ reverseList(); } /* * Deletes nodes which have greater value node(s) on left side */ function _delLesserNodes() { var current = head; /* Initialise max */ var maxnode = head; var temp; while (current != null && current.next != null) { /* * If current is smaller than max, then delete current */ if (current.next.data < maxnode.data) { temp = current.next; current.next = temp.next; temp = null; } /* * If current is greater than max, then update max and move current */ else { current = current.next; maxnode = current; } } } /* Utility functions */ /* Inserts a new Node at front of the */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to reverse the linked list */ function reverseList() { var current = head; var prev = null; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(); } /* Driver program to test above functions */ /* * Constructed Linked List is 12->15->10->11-> 5->6->2->3 */ push(3); push(2); push(6); push(5); push(11); push(10); push(15); push(12); document.write(\"Given Linked List<br/>\"); printList(); delLesserNodes(); document.write(\"<br/>Modified Linked List<br/>\"); printList(); // This code contributed by aashish1995</script>", "e": 16466, "s": 13470, "text": null }, { "code": null, "e": 16539, "s": 16466, "text": "Given Linked List \n 12 15 10 11 5 6 2 3\nModified Linked List \n 15 11 6 3" }, { "code": null, "e": 16549, "s": 16539, "text": "Method 3:" }, { "code": null, "e": 16719, "s": 16549, "text": "The other simpler method is to traverse the list from the start and delete the node when the current Node < next Node. To delete the current node, follow this approach. " }, { "code": null, "e": 16768, "s": 16719, "text": "Let us assume you have to delete current node X " }, { "code": null, "e": 16825, "s": 16768, "text": "1. Copy next node’s data into X i.e X.data = X.next.data" }, { "code": null, "e": 16884, "s": 16825, "text": "2. Copy next node’s next address i.e X.next = X.next.next;" }, { "code": null, "e": 16956, "s": 16884, "text": "Move forward in the List only when the current Node is > the next Node." }, { "code": null, "e": 16961, "s": 16956, "text": "Java" }, { "code": null, "e": 16964, "s": 16961, "text": "C#" }, { "code": null, "e": 16975, "s": 16964, "text": "Javascript" }, { "code": "// Java program for above approachimport java.io.*; // This class represents a single node// in a linked listclass Node { int data; Node next; public Node(int data){ this.data = data; this.next = null; }} //This is a utility class for linked listclass LLUtil{ // This function creates a linked list from a // given array and returns head public Node createLL(int[] arr){ Node head = new Node(arr[0]); Node temp = head; Node newNode = null; for(int i = 1; i < arr.length; i++){ newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } //This function prints given linked list public void printLL(Node head){ while(head != null){ System.out.print(head.data + \" \"); head = head.next; } System.out.println(); } } class GFG { public static void main (String[] args) { int[] arr = {12,15,10,11,5,6,2,3}; LLUtil llu = new LLUtil(); Node head = llu.createLL(arr); System.out.println(\"Given Linked List\"); llu.printLL(head); head = deleteNodesOnRightSide(head); System.out.println(\"Modified Linked List\"); llu.printLL(head); } //Main function public static Node deleteNodesOnRightSide(Node head){ if(head == null || head.next == null) return head; Node nextNode = deleteNodesOnRightSide(head.next); if(nextNode.data > head.data) return nextNode; head.next = nextNode; return head; }}", "e": 18643, "s": 16975, "text": null }, { "code": "// C# program for above approachusing System; // This class represents a single node// in a linked listclass Node{ public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }} // This is a utility class for linked listclass LLUtil{ // This function creates a linked list // from a given array and returns head public Node createLL(int[] arr) { Node head = new Node(arr[0]); Node temp = head; Node newNode = null; for(int i = 1; i < arr.Length; i++) { newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } // This function prints given linked list public void printLL(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine(); }} class GFG{ // Driver Codepublic static void Main(string[] args){ int[] arr = { 12, 15, 10, 11, 5, 6, 2, 3 }; LLUtil llu = new LLUtil(); Node head = llu.createLL(arr); Console.WriteLine(\"Given Linked List\"); llu.printLL(head); deleteNodesOnRightSide(head); Console.WriteLine(\"Modified Linked List\"); llu.printLL(head);} // Main functionpublic static void deleteNodesOnRightSide(Node head){ Node temp = head; while (temp != null && temp.next != null) { // Copying next node data into current node // i.e. we are indirectly deleting current node if (temp.data < temp.next.data) { temp.data = temp.next.data; temp.next = temp.next.next; } else { // Move to the next node temp = temp.next; } }}} // This code is contributed by rutvik_56", "e": 20517, "s": 18643, "text": null }, { "code": "<script>// javascript program for above approach// This class represents a single node// in a linked listclass Node { constructor(val) { this.data = val; this.next = null; }} // This is a utility class for linked list // This function creates a linked list from a // given array and returns head function createLL(arr) { var head = new Node(arr[0]);var temp = head; var newNode = null; for (i = 1; i < arr.length; i++) { newNode = new Node(arr[i]); temp.next = newNode; temp = temp.next; } return head; } // This function prints given linked list function printLL(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } document.write(\"<br/>\"); } // Main function function deleteNodesOnRightSide(head) { if (head == null || head.next == null) return head;var nextNode = deleteNodesOnRightSide(head.next); if (nextNode.data > head.data) return nextNode; head.next = nextNode; return head;}var arr = [ 12, 15, 10, 11, 5, 6, 2, 3 ]; var head = createLL(arr); document.write(\"Given Linked List<br/>\"); printLL(head); head = deleteNodesOnRightSide(head); document.write(\"<br/>Modified Linked List<br/>\"); printLL(head); // This code contributed by aashish1995</script>", "e": 21968, "s": 20517, "text": null }, { "code": null, "e": 22038, "s": 21968, "text": "Given Linked List\n12 15 10 11 5 6 2 3 \nModified Linked List\n15 11 6 3" }, { "code": null, "e": 22047, "s": 22038, "text": "Source: " }, { "code": null, "e": 22167, "s": 22047, "text": "https://www.geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists-6" }, { "code": null, "e": 22283, "s": 22167, "text": "Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 22296, "s": 22283, "text": "Akanksha_Rai" }, { "code": null, "e": 22315, "s": 22296, "text": "shivanisinghss2110" }, { "code": null, "e": 22333, "s": 22315, "text": "abhilashpotharaju" }, { "code": null, "e": 22343, "s": 22333, "text": "rutvik_56" }, { "code": null, "e": 22353, "s": 22343, "text": "pratham76" }, { "code": null, "e": 22367, "s": 22353, "text": "moinahmed9999" }, { "code": null, "e": 22379, "s": 22367, "text": "aashish1995" }, { "code": null, "e": 22396, "s": 22379, "text": "arorakashish0911" }, { "code": null, "e": 22409, "s": 22396, "text": "simmytarika5" }, { "code": null, "e": 22421, "s": 22409, "text": "Linked List" }, { "code": null, "e": 22433, "s": 22421, "text": "Linked List" } ]
Ways to choose three points with distance between the most distant points <= L
06 May, 2021 Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to LNote: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points Examples: Input : x = {1, 2, 3, 4} L = 3 Output : 4Explanation: Ways to select three points such that the distance between the most distant points <= L are: 1) {1, 2, 3} Here distance between farthest points = 3 – 1 = 2 <= L 2) {1, 2, 4} Here distance between farthest points = 4 – 1 = 3 <= L 3) {1, 3, 4} Here distance between farthest points = 4 – 1 = 3 <= L 4) {2, 3, 4} Here distance between farthest points = 4 – 2 = 2 <= LThus, total number of ways = 4 Naive Approach: First of all, sort the array of points to generate triplets {a, b, c} such that a and c are the farthest points of the triplet and a < b < c, since all the points are distinct. We can generate all the possible triplets and check for the condition if the distance between the two most distant points in <= L. If it holds we count this way, else we don’t C++ Java Python3 C# PHP Javascript // C++ program to count ways to choose// triplets such that the distance// between the farthest points <= L#include<bits/stdc++.h>using namespace std; // Returns the number of triplets with// distance between farthest points <= Lint countTripletsLessThanL(int n, int L, int* arr){ // sort to get ordered triplets so that we can // find the distance between farthest points // belonging to a triplet sort(arr, arr + n); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways;} // Driver Codeint main(){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 3; int ans = countTripletsLessThanL(n, L, arr); cout << "Total Number of ways = " << ans << "\n"; return 0;} // Java program to count ways to choose// triplets such that the distance// between the farthest points <= Limport java .io.*;import java .util.Arrays;class GFG { // Returns the number of triplets with // distance between farthest points <= L static int countTripletsLessThanL(int n, int L, int []arr) { // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet Arrays.sort(arr); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways; } // Driver Code static public void main (String[] args) { // set of n points on the X axis int []arr = {1, 2, 3, 4}; int n =arr.length; int L = 3; int ans = countTripletsLessThanL(n, L, arr); System.out.println("Total Number of ways = " + ans); }} // This code is contributed by anuj_67. # Python3 program to count ways to choose# triplets such that the distance# between the farthest points <= L # Returns the number of triplets with# distance between farthest points <= Ldef countTripletsLessThanL(n, L, arr): # sort to get ordered triplets so that # we can find the distance between # farthest points belonging to a triplet arr.sort() ways = 0 # generate and check for all possible # triplets: {arr[i], arr[j], arr[k]} for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): # Since the array is sorted the # farthest points will be a[i] # and a[k]; mostDistantDistance = arr[k] - arr[i] if (mostDistantDistance <= L): ways += 1 return ways # Driver Codeif __name__ == "__main__": # set of n points on the X axis arr = [1, 2, 3, 4 ] n = len(arr) L = 3 ans = countTripletsLessThanL(n, L, arr) print ("Total Number of ways =", ans) # This code is contributed by ita_c // C# program to count ways to choose// triplets such that the distance// between the farthest points <= Lusing System;class GFG { // Returns the number of triplets with// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int []arr){ // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet Array.Sort(arr); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways;} // Driver Code static public void Main () { // set of n points on the X axis int []arr = {1, 2, 3, 4}; int n =arr.Length; int L = 3; int ans = countTripletsLessThanL(n, L, arr); Console.WriteLine("Total Number of ways = " + ans); }} // This code is contributed by anuj_67. <?php// PHP program to count ways to choose// triplets such that the distance// between the farthest points <= L // Returns the number of triplets with// distance between farthest points <= Lfunction countTripletsLessThanL($n, $L, $arr){ // sort to get ordered triplets so that // we can find the distance between // farthest points belonging to a triplet sort($arr); $ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { for ($k = $j + 1; $k < $n; $k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; $mostDistantDistance = $arr[$k] - $arr[$i]; if ($mostDistantDistance <= $L) { $ways++; } } } } return $ways;} // Driver Code // set of n points on the X axis$arr = array( 1, 2, 3, 4 ); $n = sizeof($arr);$L = 3;$ans = countTripletsLessThanL($n, $L, $arr);echo "Total Number of ways = " , $ans, "\n"; // This code is contributed by akt_mit?> <script> // javascript program to count ways to choose// triplets such that the distance// between the farthest points <= L // Returns the number of triplets with // distance between farthest points <= L function countTripletsLessThanL(n , L, arr) { // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet arr.sort(); var ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { for (k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; var mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways; } // Driver Code // set of n points on the X axis var arr = [ 1, 2, 3, 4 ]; var n = arr.length; var L = 3; var ans = countTripletsLessThanL(n, L, arr); document.write("Total Number of ways = " + ans); // This code contributed by Rajput-Ji </script> Output: Total Number of ways = 4 Time Complexity: O(n3) for generating all possible triplets. Efficient Approach: This problem can be solved by using Binary search. First of all, sort the array. Now, for each element of the array we find the number of elements which are greater than it(by maintaining a sorted order of points) and lie in the range (xi + 1, xi + L) both inclusive (Note that here all points are distinct so we need consider the elements equal to xi itself). Doing so we find all such points where the distance between the farthest points will always be less than or equal to L. Now let’s say for the ith point, we have M such points which are less than or equal to xi + L, then the number of ways we can select 2 points from M such points is simply M * (M – 1) / 2 C++ Java Python3 C# Javascript // C++ program to count ways to choose// triplets such that the distance between// the farthest points <= L */#include<bits/stdc++.h>using namespace std; // Returns the number of triplets with the// distance between farthest points <= Lint countTripletsLessThanL(int n, int L, int* arr){ // sort the array sort(arr, arr + n); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, arr + n, arr[i] + L) - arr; // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} // Driver Codeint main(){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 4; int ans = countTripletsLessThanL(n, L, arr); cout << "Total Number of ways = " << ans << "\n"; return 0;} // Java program to count ways to choose// triplets such that the distance between// the farthest points <= L */import java.util.*; class GFG{ // Returns the number of triplets with the// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int[] arr){ // sort the array Arrays.sort(arr); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, 0, n, arr[i] + L); // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} static int upper_bound(int[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low) / 2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver Codepublic static void main(String[] args){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = arr.length; int L = 4; int ans = countTripletsLessThanL(n, L, arr); System.out.println("Total Number of ways = " + ans);}} // This code is contributed by 29AjayKumar # Python program to count ways to choose# triplets such that the distance between# the farthest points <= L ''' # Returns the number of triplets with the# distance between farthest points <= Ldef countTripletsLessThanL(n, L, arr): # sort the array arr = sorted(arr); ways = 0; for i in range(n): # find index of element greater than arr[i] + L indexGreater = upper_bound(arr, 0, n, arr[i] + L); # find Number of elements between the ith # index and indexGreater since the Numbers # are sorted and the elements are distinct # from the points btw these indices represent # points within range (a[i] + 1 and a[i] + L) # both inclusive numberOfElements = indexGreater - (i + 1); # if there are at least two elements in between # i and indexGreater find the Number of ways # to select two points out of these if (numberOfElements >= 2): ways += (numberOfElements * (numberOfElements - 1) / 2); return ways; def upper_bound(a, low, high, element): while (low < high): middle = int(low + (high - low) / 2); if (a[middle] > element): high = middle; else: low = middle + 1; return low; # Driver Codeif __name__ == '__main__': # set of n points on the X axis arr = [1, 2, 3, 4]; n = len(arr); L = 4; ans = countTripletsLessThanL(n, L, arr); print("Total Number of ways = " , ans); # This code is contributed by 29AjayKumar // C# program to count ways to choose// triplets such that the distance between// the farthest points <= L */using System; class GFG{ // Returns the number of triplets with the// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int[] arr){ // sort the array Array.Sort(arr); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, 0, n, arr[i] + L); // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} static int upper_bound(int[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low) / 2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver Codepublic static void Main(String[] args){ // set of n points on the X axis int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int L = 4; int ans = countTripletsLessThanL(n, L, arr); Console.WriteLine("Total Number of ways = " + ans);}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to count ways to choose// triplets such that the distance between// the farthest points <= L // Returns the number of triplets with the// distance between farthest points <= Lfunction countTripletsLessThanL(n, L, arr){ // Sort the array arr.sort(function(a, b){return a - b}); let ways = 0; for(let i = 0; i < n; i++) { // Find index of element greater // than arr[i] + L let indexGreater = upper_bound(arr, 0, n, arr[i] + L); // Find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive let numberOfElements = indexGreater - (i + 1); // If there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} function upper_bound(a, low, high, element){ while(low < high) { let middle = low + parseInt((high - low) / 2, 10); if (a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver code // Set of n points on the X axislet arr = [ 1, 2, 3, 4 ];let n = arr.length;let L = 4; let ans = countTripletsLessThanL(n, L, arr); document.write("Total Number of ways = " + ans); // This code is contributed by suresh07 </script> Output Total Number of ways = 4 Time Complexity:O(NlogN) where N is the number of points. vt_m jit_t ukasp 29AjayKumar princiraj1992 Rajput-Ji suresh07 Arrays Geometric Searching Arrays Searching Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2021" }, { "code": null, "e": 397, "s": 52, "text": "Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to LNote: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points" }, { "code": null, "e": 408, "s": 397, "text": "Examples: " }, { "code": null, "e": 858, "s": 408, "text": "Input : x = {1, 2, 3, 4} L = 3 Output : 4Explanation: Ways to select three points such that the distance between the most distant points <= L are: 1) {1, 2, 3} Here distance between farthest points = 3 – 1 = 2 <= L 2) {1, 2, 4} Here distance between farthest points = 4 – 1 = 3 <= L 3) {1, 3, 4} Here distance between farthest points = 4 – 1 = 3 <= L 4) {2, 3, 4} Here distance between farthest points = 4 – 2 = 2 <= LThus, total number of ways = 4 " }, { "code": null, "e": 1228, "s": 858, "text": "Naive Approach: First of all, sort the array of points to generate triplets {a, b, c} such that a and c are the farthest points of the triplet and a < b < c, since all the points are distinct. We can generate all the possible triplets and check for the condition if the distance between the two most distant points in <= L. If it holds we count this way, else we don’t " }, { "code": null, "e": 1232, "s": 1228, "text": "C++" }, { "code": null, "e": 1237, "s": 1232, "text": "Java" }, { "code": null, "e": 1245, "s": 1237, "text": "Python3" }, { "code": null, "e": 1248, "s": 1245, "text": "C#" }, { "code": null, "e": 1252, "s": 1248, "text": "PHP" }, { "code": null, "e": 1263, "s": 1252, "text": "Javascript" }, { "code": "// C++ program to count ways to choose// triplets such that the distance// between the farthest points <= L#include<bits/stdc++.h>using namespace std; // Returns the number of triplets with// distance between farthest points <= Lint countTripletsLessThanL(int n, int L, int* arr){ // sort to get ordered triplets so that we can // find the distance between farthest points // belonging to a triplet sort(arr, arr + n); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways;} // Driver Codeint main(){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 3; int ans = countTripletsLessThanL(n, L, arr); cout << \"Total Number of ways = \" << ans << \"\\n\"; return 0;}", "e": 2497, "s": 1263, "text": null }, { "code": "// Java program to count ways to choose// triplets such that the distance// between the farthest points <= Limport java .io.*;import java .util.Arrays;class GFG { // Returns the number of triplets with // distance between farthest points <= L static int countTripletsLessThanL(int n, int L, int []arr) { // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet Arrays.sort(arr); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways; } // Driver Code static public void main (String[] args) { // set of n points on the X axis int []arr = {1, 2, 3, 4}; int n =arr.length; int L = 3; int ans = countTripletsLessThanL(n, L, arr); System.out.println(\"Total Number of ways = \" + ans); }} // This code is contributed by anuj_67.", "e": 4117, "s": 2497, "text": null }, { "code": "# Python3 program to count ways to choose# triplets such that the distance# between the farthest points <= L # Returns the number of triplets with# distance between farthest points <= Ldef countTripletsLessThanL(n, L, arr): # sort to get ordered triplets so that # we can find the distance between # farthest points belonging to a triplet arr.sort() ways = 0 # generate and check for all possible # triplets: {arr[i], arr[j], arr[k]} for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): # Since the array is sorted the # farthest points will be a[i] # and a[k]; mostDistantDistance = arr[k] - arr[i] if (mostDistantDistance <= L): ways += 1 return ways # Driver Codeif __name__ == \"__main__\": # set of n points on the X axis arr = [1, 2, 3, 4 ] n = len(arr) L = 3 ans = countTripletsLessThanL(n, L, arr) print (\"Total Number of ways =\", ans) # This code is contributed by ita_c", "e": 5181, "s": 4117, "text": null }, { "code": "// C# program to count ways to choose// triplets such that the distance// between the farthest points <= Lusing System;class GFG { // Returns the number of triplets with// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int []arr){ // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet Array.Sort(arr); int ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; int mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways;} // Driver Code static public void Main () { // set of n points on the X axis int []arr = {1, 2, 3, 4}; int n =arr.Length; int L = 3; int ans = countTripletsLessThanL(n, L, arr); Console.WriteLine(\"Total Number of ways = \" + ans); }} // This code is contributed by anuj_67.", "e": 6540, "s": 5181, "text": null }, { "code": "<?php// PHP program to count ways to choose// triplets such that the distance// between the farthest points <= L // Returns the number of triplets with// distance between farthest points <= Lfunction countTripletsLessThanL($n, $L, $arr){ // sort to get ordered triplets so that // we can find the distance between // farthest points belonging to a triplet sort($arr); $ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { for ($k = $j + 1; $k < $n; $k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; $mostDistantDistance = $arr[$k] - $arr[$i]; if ($mostDistantDistance <= $L) { $ways++; } } } } return $ways;} // Driver Code // set of n points on the X axis$arr = array( 1, 2, 3, 4 ); $n = sizeof($arr);$L = 3;$ans = countTripletsLessThanL($n, $L, $arr);echo \"Total Number of ways = \" , $ans, \"\\n\"; // This code is contributed by akt_mit?>", "e": 7767, "s": 6540, "text": null }, { "code": "<script> // javascript program to count ways to choose// triplets such that the distance// between the farthest points <= L // Returns the number of triplets with // distance between farthest points <= L function countTripletsLessThanL(n , L, arr) { // sort to get ordered triplets // so that we can find the // distance between farthest // points belonging to a triplet arr.sort(); var ways = 0; // generate and check for all possible // triplets: {arr[i], arr[j], arr[k]} for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { for (k = j + 1; k < n; k++) { // Since the array is sorted the // farthest points will be a[i] // and a[k]; var mostDistantDistance = arr[k] - arr[i]; if (mostDistantDistance <= L) { ways++; } } } } return ways; } // Driver Code // set of n points on the X axis var arr = [ 1, 2, 3, 4 ]; var n = arr.length; var L = 3; var ans = countTripletsLessThanL(n, L, arr); document.write(\"Total Number of ways = \" + ans); // This code contributed by Rajput-Ji </script>", "e": 9093, "s": 7767, "text": null }, { "code": null, "e": 9103, "s": 9093, "text": "Output: " }, { "code": null, "e": 9128, "s": 9103, "text": "Total Number of ways = 4" }, { "code": null, "e": 9189, "s": 9128, "text": "Time Complexity: O(n3) for generating all possible triplets." }, { "code": null, "e": 9210, "s": 9189, "text": "Efficient Approach: " }, { "code": null, "e": 9261, "s": 9210, "text": "This problem can be solved by using Binary search." }, { "code": null, "e": 9291, "s": 9261, "text": "First of all, sort the array." }, { "code": null, "e": 9571, "s": 9291, "text": "Now, for each element of the array we find the number of elements which are greater than it(by maintaining a sorted order of points) and lie in the range (xi + 1, xi + L) both inclusive (Note that here all points are distinct so we need consider the elements equal to xi itself)." }, { "code": null, "e": 9691, "s": 9571, "text": "Doing so we find all such points where the distance between the farthest points will always be less than or equal to L." }, { "code": null, "e": 9878, "s": 9691, "text": "Now let’s say for the ith point, we have M such points which are less than or equal to xi + L, then the number of ways we can select 2 points from M such points is simply M * (M – 1) / 2" }, { "code": null, "e": 9882, "s": 9878, "text": "C++" }, { "code": null, "e": 9887, "s": 9882, "text": "Java" }, { "code": null, "e": 9895, "s": 9887, "text": "Python3" }, { "code": null, "e": 9898, "s": 9895, "text": "C#" }, { "code": null, "e": 9909, "s": 9898, "text": "Javascript" }, { "code": "// C++ program to count ways to choose// triplets such that the distance between// the farthest points <= L */#include<bits/stdc++.h>using namespace std; // Returns the number of triplets with the// distance between farthest points <= Lint countTripletsLessThanL(int n, int L, int* arr){ // sort the array sort(arr, arr + n); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, arr + n, arr[i] + L) - arr; // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} // Driver Codeint main(){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 4; int ans = countTripletsLessThanL(n, L, arr); cout << \"Total Number of ways = \" << ans << \"\\n\"; return 0;}", "e": 11382, "s": 9909, "text": null }, { "code": "// Java program to count ways to choose// triplets such that the distance between// the farthest points <= L */import java.util.*; class GFG{ // Returns the number of triplets with the// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int[] arr){ // sort the array Arrays.sort(arr); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, 0, n, arr[i] + L); // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} static int upper_bound(int[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low) / 2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver Codepublic static void main(String[] args){ // set of n points on the X axis int arr[] = { 1, 2, 3, 4 }; int n = arr.length; int L = 4; int ans = countTripletsLessThanL(n, L, arr); System.out.println(\"Total Number of ways = \" + ans);}} // This code is contributed by 29AjayKumar", "e": 13194, "s": 11382, "text": null }, { "code": "# Python program to count ways to choose# triplets such that the distance between# the farthest points <= L ''' # Returns the number of triplets with the# distance between farthest points <= Ldef countTripletsLessThanL(n, L, arr): # sort the array arr = sorted(arr); ways = 0; for i in range(n): # find index of element greater than arr[i] + L indexGreater = upper_bound(arr, 0, n, arr[i] + L); # find Number of elements between the ith # index and indexGreater since the Numbers # are sorted and the elements are distinct # from the points btw these indices represent # points within range (a[i] + 1 and a[i] + L) # both inclusive numberOfElements = indexGreater - (i + 1); # if there are at least two elements in between # i and indexGreater find the Number of ways # to select two points out of these if (numberOfElements >= 2): ways += (numberOfElements * (numberOfElements - 1) / 2); return ways; def upper_bound(a, low, high, element): while (low < high): middle = int(low + (high - low) / 2); if (a[middle] > element): high = middle; else: low = middle + 1; return low; # Driver Codeif __name__ == '__main__': # set of n points on the X axis arr = [1, 2, 3, 4]; n = len(arr); L = 4; ans = countTripletsLessThanL(n, L, arr); print(\"Total Number of ways = \" , ans); # This code is contributed by 29AjayKumar", "e": 14708, "s": 13194, "text": null }, { "code": "// C# program to count ways to choose// triplets such that the distance between// the farthest points <= L */using System; class GFG{ // Returns the number of triplets with the// distance between farthest points <= Lstatic int countTripletsLessThanL(int n, int L, int[] arr){ // sort the array Array.Sort(arr); int ways = 0; for (int i = 0; i < n; i++) { // find index of element greater than arr[i] + L int indexGreater = upper_bound(arr, 0, n, arr[i] + L); // find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive int numberOfElements = indexGreater - (i + 1); // if there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} static int upper_bound(int[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low) / 2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver Codepublic static void Main(String[] args){ // set of n points on the X axis int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int L = 4; int ans = countTripletsLessThanL(n, L, arr); Console.WriteLine(\"Total Number of ways = \" + ans);}} // This code is contributed by PrinciRaj1992", "e": 16503, "s": 14708, "text": null }, { "code": "<script> // Javascript program to count ways to choose// triplets such that the distance between// the farthest points <= L // Returns the number of triplets with the// distance between farthest points <= Lfunction countTripletsLessThanL(n, L, arr){ // Sort the array arr.sort(function(a, b){return a - b}); let ways = 0; for(let i = 0; i < n; i++) { // Find index of element greater // than arr[i] + L let indexGreater = upper_bound(arr, 0, n, arr[i] + L); // Find Number of elements between the ith // index and indexGreater since the Numbers // are sorted and the elements are distinct // from the points btw these indices represent // points within range (a[i] + 1 and a[i] + L) // both inclusive let numberOfElements = indexGreater - (i + 1); // If there are at least two elements in between // i and indexGreater find the Number of ways // to select two points out of these if (numberOfElements >= 2) { ways += (numberOfElements * (numberOfElements - 1) / 2); } } return ways;} function upper_bound(a, low, high, element){ while(low < high) { let middle = low + parseInt((high - low) / 2, 10); if (a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver code // Set of n points on the X axislet arr = [ 1, 2, 3, 4 ];let n = arr.length;let L = 4; let ans = countTripletsLessThanL(n, L, arr); document.write(\"Total Number of ways = \" + ans); // This code is contributed by suresh07 </script>", "e": 18220, "s": 16503, "text": null }, { "code": null, "e": 18229, "s": 18220, "text": "Output " }, { "code": null, "e": 18254, "s": 18229, "text": "Total Number of ways = 4" }, { "code": null, "e": 18313, "s": 18254, "text": "Time Complexity:O(NlogN) where N is the number of points. " }, { "code": null, "e": 18318, "s": 18313, "text": "vt_m" }, { "code": null, "e": 18324, "s": 18318, "text": "jit_t" }, { "code": null, "e": 18330, "s": 18324, "text": "ukasp" }, { "code": null, "e": 18342, "s": 18330, "text": "29AjayKumar" }, { "code": null, "e": 18356, "s": 18342, "text": "princiraj1992" }, { "code": null, "e": 18366, "s": 18356, "text": "Rajput-Ji" }, { "code": null, "e": 18375, "s": 18366, "text": "suresh07" }, { "code": null, "e": 18382, "s": 18375, "text": "Arrays" }, { "code": null, "e": 18392, "s": 18382, "text": "Geometric" }, { "code": null, "e": 18402, "s": 18392, "text": "Searching" }, { "code": null, "e": 18409, "s": 18402, "text": "Arrays" }, { "code": null, "e": 18419, "s": 18409, "text": "Searching" }, { "code": null, "e": 18429, "s": 18419, "text": "Geometric" } ]
Machine Learning - Jupyter Notebook
Jupyter notebooks basically provides an interactive computational environment for developing Python based Data Science applications. They are formerly known as ipython notebooks. The following are some of the features of Jupyter notebooks that makes it one of the best components of Python ML ecosystem − Jupyter notebooks can illustrate the analysis process step by step by arranging the stuff like code, images, text, output etc. in a step by step manner. Jupyter notebooks can illustrate the analysis process step by step by arranging the stuff like code, images, text, output etc. in a step by step manner. It helps a data scientist to document the thought process while developing the analysis process. It helps a data scientist to document the thought process while developing the analysis process. One can also capture the result as the part of the notebook. One can also capture the result as the part of the notebook. With the help of jupyter notebooks, we can share our work with a peer also. With the help of jupyter notebooks, we can share our work with a peer also. If you are using Anaconda distribution, then you need not install jupyter notebook separately as it is already installed with it. You just need to go to Anaconda Prompt and type the following command − C:\>jupyter notebook After pressing enter, it will start a notebook server at localhost:8888 of your computer. It is shown in the following screen shot − Now, after clicking the New tab, you will get a list of options. Select Python 3 and it will take you to the new notebook for start working in it. You will get a glimpse of it in the following screenshots − On the other hand, if you are using standard Python distribution then jupyter notebook can be installed using popular python package installer, pip. pip install jupyter The following are the three types of cells in a jupyter notebook − Code cells − As the name suggests, we can use these cells to write code. After writing the code/content, it will send it to the kernel that is associated with the notebook. Markdown cells − We can use these cells for notating the computation process. They can contain the stuff like text, images, Latex equations, HTML tags etc. Raw cells − The text written in them is displayed as it is. These cells are basically used to add the text that we do not wish to be converted by the automatic conversion mechanism of jupyter notebook. For more detailed study of jupyter notebook, you can go to the link www.tutorialspoint.com/jupyter/index.htm. It is another useful component that makes Python as one of the favorite languages for Data Science. It basically stands for Numerical Python and consists of multidimensional array objects. By using NumPy, we can perform the following important operations − Mathematical and logical operations on arrays. Fourier transformation Operations associated with linear algebra. We can also see NumPy as the replacement of MatLab because NumPy is mostly used along with Scipy (Scientific Python) and Mat-plotlib (plotting library). Installation and Execution If you are using Anaconda distribution, then no need to install NumPy separately as it is already installed with it. You just need to import the package into your Python script with the help of following − import numpy as np On the other hand, if you are using standard Python distribution then NumPy can be installed using popular python package installer, pip. pip install NumPy After installing NumPy, you can import it into your Python script as you did above. For more detailed study of NumPy, you can go to the link www.tutorialspoint.com/numpy/index.htm. It is another useful Python library that makes Python one of the favorite languages for Data Science. Pandas is basically used for data manipulation, wrangling and analysis. It was developed by Wes McKinney in 2008. With the help of Pandas, in data processing we can accomplish the following five steps − Load Prepare Manipulate Model Analyze The entire representation of data in Pandas is done with the help of following three data structures − Series − It is basically a one-dimensional ndarray with an axis label which means it is like a simple array with homogeneous data. For example, the following series is a collection of integers 1,5,10,15,24,25... Data frame − It is the most useful data structure and used for almost all kind of data representation and manipulation in pandas. It is basically a two-dimensional data structure which can contain heterogeneous data. Generally, tabular data is represented by using data frames. For example, the following table shows the data of students having their names and roll numbers, age and gender. Panel − It is a 3-dimensional data structure containing heterogeneous data. It is very difficult to represent the panel in graphical representation, but it can be illustrated as a container of DataFrame. The following table gives us the dimension and description about above mentioned data structures used in Pandas − We can understand these data structures as the higher dimensional data structure is the container of lower dimensional data structure. If you are using Anaconda distribution, then no need to install Pandas separately as it is already installed with it. You just need to import the package into your Python script with the help of following − import pandas as pd On the other hand, if you are using standard Python distribution then Pandas can be installed using popular python package installer, pip. pip install Pandas After installing Pandas, you can import it into your Python script as did above. The following is an example of creating a series from ndarray by using Pandas − In [1]: import pandas as pd In [2]: import numpy as np In [3]: data = np.array(['g','a','u','r','a','v']) In [4]: s = pd.Series(data) In [5]: print (s) 0 g 1 a 2 u 3 r 4 a 5 v dtype: object For more detailed study of Pandas you can go to the link www.tutorialspoint.com/python_pandas/index.htm. Another useful and most important python library for Data Science and machine learning in Python is Scikit-learn. The following are some features of Scikit-learn that makes it so useful − It is built on NumPy, SciPy, and Matplotlib. It is built on NumPy, SciPy, and Matplotlib. It is an open source and can be reused under BSD license. It is an open source and can be reused under BSD license. It is accessible to everybody and can be reused in various contexts. It is accessible to everybody and can be reused in various contexts. Wide range of machine learning algorithms covering major areas of ML like classification, clustering, regression, dimensionality reduction, model selection etc. can be implemented with the help of it. Wide range of machine learning algorithms covering major areas of ML like classification, clustering, regression, dimensionality reduction, model selection etc. can be implemented with the help of it. If you are using Anaconda distribution, then no need to install Scikit-learn separately as it is already installed with it. You just need to use the package into your Python script. For example, with following line of script we are importing dataset of breast cancer patients from Scikit-learn − from sklearn.datasets import load_breast_cancer On the other hand, if you are using standard Python distribution and having NumPy and SciPy then Scikit-learn can be installed using popular python package installer, pip. pip install -U scikit-learn After installing Scikit-learn, you can use it into your Python script as you have done above. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2609, "s": 2304, "text": "Jupyter notebooks basically provides an interactive computational environment for developing Python based Data Science applications. They are formerly known as ipython notebooks. The following are some of the features of Jupyter notebooks that makes it one of the best components of Python ML ecosystem −" }, { "code": null, "e": 2762, "s": 2609, "text": "Jupyter notebooks can illustrate the analysis process step by step by arranging the stuff like code, images, text, output etc. in a step by step manner." }, { "code": null, "e": 2915, "s": 2762, "text": "Jupyter notebooks can illustrate the analysis process step by step by arranging the stuff like code, images, text, output etc. in a step by step manner." }, { "code": null, "e": 3012, "s": 2915, "text": "It helps a data scientist to document the thought process while developing the analysis process." }, { "code": null, "e": 3109, "s": 3012, "text": "It helps a data scientist to document the thought process while developing the analysis process." }, { "code": null, "e": 3170, "s": 3109, "text": "One can also capture the result as the part of the notebook." }, { "code": null, "e": 3231, "s": 3170, "text": "One can also capture the result as the part of the notebook." }, { "code": null, "e": 3307, "s": 3231, "text": "With the help of jupyter notebooks, we can share our work with a peer also." }, { "code": null, "e": 3383, "s": 3307, "text": "With the help of jupyter notebooks, we can share our work with a peer also." }, { "code": null, "e": 3585, "s": 3383, "text": "If you are using Anaconda distribution, then you need not install jupyter notebook separately as it is already installed with it. You just need to go to Anaconda Prompt and type the following command −" }, { "code": null, "e": 3607, "s": 3585, "text": "C:\\>jupyter notebook\n" }, { "code": null, "e": 3740, "s": 3607, "text": "After pressing enter, it will start a notebook server at localhost:8888 of your computer. It is shown in the following screen shot −" }, { "code": null, "e": 3947, "s": 3740, "text": "Now, after clicking the New tab, you will get a list of options. Select Python 3 and it will take you to the new notebook for start working in it. You will get a glimpse of it in the following screenshots −" }, { "code": null, "e": 4096, "s": 3947, "text": "On the other hand, if you are using standard Python distribution then jupyter notebook can be installed using popular python package installer, pip." }, { "code": null, "e": 4117, "s": 4096, "text": "pip install jupyter\n" }, { "code": null, "e": 4184, "s": 4117, "text": "The following are the three types of cells in a jupyter notebook −" }, { "code": null, "e": 4357, "s": 4184, "text": "Code cells − As the name suggests, we can use these cells to write code. After writing the code/content, it will send it to the kernel that is associated with the notebook." }, { "code": null, "e": 4513, "s": 4357, "text": "Markdown cells − We can use these cells for notating the computation process. They can contain the stuff like text, images, Latex equations, HTML tags etc." }, { "code": null, "e": 4715, "s": 4513, "text": "Raw cells − The text written in them is displayed as it is. These cells are basically used to add the text that we do not wish to be converted by the automatic conversion mechanism of jupyter notebook." }, { "code": null, "e": 4825, "s": 4715, "text": "For more detailed study of jupyter notebook, you can go to the link www.tutorialspoint.com/jupyter/index.htm." }, { "code": null, "e": 5082, "s": 4825, "text": "It is another useful component that makes Python as one of the favorite languages for Data Science. It basically stands for Numerical Python and consists of multidimensional array objects. By using NumPy, we can perform the following important operations −" }, { "code": null, "e": 5129, "s": 5082, "text": "Mathematical and logical operations on arrays." }, { "code": null, "e": 5152, "s": 5129, "text": "Fourier transformation" }, { "code": null, "e": 5195, "s": 5152, "text": "Operations associated with linear algebra." }, { "code": null, "e": 5348, "s": 5195, "text": "We can also see NumPy as the replacement of MatLab because NumPy is mostly used along with Scipy (Scientific Python) and Mat-plotlib (plotting library)." }, { "code": null, "e": 5375, "s": 5348, "text": "Installation and Execution" }, { "code": null, "e": 5581, "s": 5375, "text": "If you are using Anaconda distribution, then no need to install NumPy separately as it is already installed with it. You just need to import the package into your Python script with the help of following −" }, { "code": null, "e": 5601, "s": 5581, "text": "import numpy as np\n" }, { "code": null, "e": 5739, "s": 5601, "text": "On the other hand, if you are using standard Python distribution then NumPy can be installed using popular python package installer, pip." }, { "code": null, "e": 5758, "s": 5739, "text": "pip install NumPy\n" }, { "code": null, "e": 5842, "s": 5758, "text": "After installing NumPy, you can import it into your Python script as you did above." }, { "code": null, "e": 5940, "s": 5842, "text": "For more detailed study of NumPy, you can go to the link www.tutorialspoint.com/numpy/index.htm." }, { "code": null, "e": 6245, "s": 5940, "text": "It is another useful Python library that makes Python one of the favorite languages for Data Science. Pandas is basically used for data manipulation, wrangling and analysis. It was developed by Wes McKinney in 2008. With the help of Pandas, in data processing we can accomplish the following five steps −" }, { "code": null, "e": 6250, "s": 6245, "text": "Load" }, { "code": null, "e": 6258, "s": 6250, "text": "Prepare" }, { "code": null, "e": 6269, "s": 6258, "text": "Manipulate" }, { "code": null, "e": 6275, "s": 6269, "text": "Model" }, { "code": null, "e": 6283, "s": 6275, "text": "Analyze" }, { "code": null, "e": 6386, "s": 6283, "text": "The entire representation of data in Pandas is done with the help of following three data structures −" }, { "code": null, "e": 6598, "s": 6386, "text": "Series − It is basically a one-dimensional ndarray with an axis label which means it is like a simple array with homogeneous data. For example, the following series is a collection of integers 1,5,10,15,24,25..." }, { "code": null, "e": 6989, "s": 6598, "text": "Data frame − It is the most useful data structure and used for almost all kind of data representation and manipulation in pandas. It is basically a two-dimensional data structure which can contain heterogeneous data. Generally, tabular data is represented by using data frames. For example, the following table shows the data of students having their names and roll numbers, age and gender." }, { "code": null, "e": 7193, "s": 6989, "text": "Panel − It is a 3-dimensional data structure containing heterogeneous data. It is very difficult to represent the panel in graphical representation, but it can be illustrated as a container of DataFrame." }, { "code": null, "e": 7307, "s": 7193, "text": "The following table gives us the dimension and description about above mentioned data structures used in Pandas −" }, { "code": null, "e": 7442, "s": 7307, "text": "We can understand these data structures as the higher dimensional data structure is the container of lower dimensional data structure." }, { "code": null, "e": 7649, "s": 7442, "text": "If you are using Anaconda distribution, then no need to install Pandas separately as it is already installed with it. You just need to import the package into your Python script with the help of following −" }, { "code": null, "e": 7670, "s": 7649, "text": "import pandas as pd\n" }, { "code": null, "e": 7809, "s": 7670, "text": "On the other hand, if you are using standard Python distribution then Pandas can be installed using popular python package installer, pip." }, { "code": null, "e": 7829, "s": 7809, "text": "pip install Pandas\n" }, { "code": null, "e": 7910, "s": 7829, "text": "After installing Pandas, you can import it into your Python script as did above." }, { "code": null, "e": 7990, "s": 7910, "text": "The following is an example of creating a series from ndarray by using Pandas −" }, { "code": null, "e": 8180, "s": 7990, "text": "In [1]: import pandas as pd\nIn [2]: import numpy as np\nIn [3]: data = np.array(['g','a','u','r','a','v'])\nIn [4]: s = pd.Series(data)\nIn [5]: print (s)\n0 g\n1 a\n2 u\n3 r\n4 a\n5 v\ndtype: object" }, { "code": null, "e": 8285, "s": 8180, "text": "For more detailed study of Pandas you can go to the link www.tutorialspoint.com/python_pandas/index.htm." }, { "code": null, "e": 8473, "s": 8285, "text": "Another useful and most important python library for Data Science and machine learning in Python is Scikit-learn. The following are some features of Scikit-learn that makes it so useful −" }, { "code": null, "e": 8518, "s": 8473, "text": "It is built on NumPy, SciPy, and Matplotlib." }, { "code": null, "e": 8563, "s": 8518, "text": "It is built on NumPy, SciPy, and Matplotlib." }, { "code": null, "e": 8621, "s": 8563, "text": "It is an open source and can be reused under BSD license." }, { "code": null, "e": 8679, "s": 8621, "text": "It is an open source and can be reused under BSD license." }, { "code": null, "e": 8748, "s": 8679, "text": "It is accessible to everybody and can be reused in various contexts." }, { "code": null, "e": 8817, "s": 8748, "text": "It is accessible to everybody and can be reused in various contexts." }, { "code": null, "e": 9018, "s": 8817, "text": "Wide range of machine learning algorithms covering major areas of ML like classification, clustering, regression, dimensionality reduction, model selection etc. can be implemented with the help of it." }, { "code": null, "e": 9219, "s": 9018, "text": "Wide range of machine learning algorithms covering major areas of ML like classification, clustering, regression, dimensionality reduction, model selection etc. can be implemented with the help of it." }, { "code": null, "e": 9515, "s": 9219, "text": "If you are using Anaconda distribution, then no need to install Scikit-learn separately as it is already installed with it. You just need to use the package into your Python script. For example, with following line of script we are importing dataset of breast cancer patients from Scikit-learn −" }, { "code": null, "e": 9564, "s": 9515, "text": "from sklearn.datasets import load_breast_cancer\n" }, { "code": null, "e": 9736, "s": 9564, "text": "On the other hand, if you are using standard Python distribution and having NumPy and SciPy then Scikit-learn can be installed using popular python package installer, pip." }, { "code": null, "e": 9765, "s": 9736, "text": "pip install -U scikit-learn\n" }, { "code": null, "e": 9859, "s": 9765, "text": "After installing Scikit-learn, you can use it into your Python script as you have done above." }, { "code": null, "e": 9896, "s": 9859, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 9919, "s": 9896, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 9955, "s": 9919, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 9983, "s": 9955, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10017, "s": 9983, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 10034, "s": 10017, "text": " Abhilash Nelson" }, { "code": null, "e": 10067, "s": 10034, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 10089, "s": 10067, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10122, "s": 10089, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 10144, "s": 10122, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10177, "s": 10144, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 10199, "s": 10177, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10206, "s": 10199, "text": " Print" }, { "code": null, "e": 10217, "s": 10206, "text": " Add Notes" } ]
AWS IAM Introduction. An overview of AWS identity and access... | by Evan Kozliner | Towards Data Science
The first thing to both shock (and frustrate) many people moving into cloud-based environments is how complicated permissions can be. Typically, after years of becoming acclimated to being the God — sudo— of whatever code you have been writing prior, you are introduced to an environment where nearly everything is locked down by default. This post will focus on alleviating some of that pain by teaching you the most important parts of IAM, the identity and access management service for Amazon Web Services, as well as introducing some well known best practices. In future posts I plan to build off this one. Be sure to read this follow-up post, if you’re interested in seeing all the elements of IAM I discuss in this post in-action. The world of AWS starts with accounts and resources within those accounts. IAM exists primarily to protect the resources in your account from problems like: Malicious actors trying to do unwanted things to your AWS account (e.g. steal your data from your S3 buckets). Users/applications within your company accidentally deleting resources, or performing actions they otherwise should not be able to. The logical barrier between users of AWS. Pretty straightforward: 1–1 correspondence with a 12-digit account id e.g. 123456789012. As a best practice, an organization will have multiple AWS accounts [1]. IAM is often used to handle permissions between AWS accounts within an organization. Tied to an email address, credit card; accounts are how you are billed. Resources are persisted objects in your account that you want to use, like load balancers or EC2 instances. Resources always have an ARN — Amazon Resource Name — that uniquely identify them. E.g. for an IAM user, an ARN might look like the below: arn:aws:iam::123456789012:user/Development/product_1234/* Notice how the account id 123456789012is present in the ARN, as well as the type of resource (this resource is an IAM user). The core feature of IAM is identities, a type of AWS resource. AWS services always expose APIs you can call using some identity; this tells AWS who you are (authentication) and whether you’re allowed to do what you’re doing (authorization). There are two major forms of identities in IAM: users, and roles. The intention of a user in IAM is similar those in other websites like Facebook. When you first create an AWS account you are given a root user that has complete access to your account [2]. Then you’re given the — strongly suggested — option of creating further users and roles. Some notes on users: Users, unlike roles, have a username and password. These are long lived credentials that can be persisted for an extended period of time and used to log into the AWS console. Often intended to give individuals access to AWS console, or APIs. However, as a best practice, you should use roles instead of users whenever possible. This is to limit the risk of long-lived credentials being misplaced and giving an attacker access to your AWS account. Users are given access keys. Access keys can be used to call AWS services via the CLI or SDK. Like a username/password, access keys are long lived. They will look more randomized, and can be used together with the CLI by creating a file named ~/.aws/credentials with contents that look like the below: [personal]aws_access_key_id = AKIAIOSFODNN7EXAMPLEaws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY You can use a credentials profile with the CLI with the --profile option on the CLI: > aws s3 ls --profile personal2017-11-30 16:20:55 some-s3-bucket2017-10-31 20:05:17 some-other-s3-bucket... Like users, roles are an identity used for accessing an AWS APIs and resources. However, roles are generally used to grant temporary credentials to an AWS account. Further, these temporary credentials can be configured to trust third parties, or other AWS services. Roles are used ubiquitously in AWS: An EC2 instance that needs to access AWS resources will use an instance role to command other AWS services/resources based on your application logic. Other AWS accounts that need access to resources in your account will sometimes assume a role in your account to gain access via the STS assume role API. To allow them to do this, you can grant permissions on a role for some identity in another account via a trust policy (more on this later). A critical feature of AWS is its ability to take actions on your behalf. However, AWS services are typically implemented as AWS accounts; this means that they do not, by default, have access to the resources in your account. Accordingly, they will often require you create and grant them access to a “service role” in your account so that they can take actions on your behalf. Autoscaling on EC2, for example, will need permissions to spin up and down EC2 instances for you. Third parties, like JumpCloud, will use roles to grant users managed outside of AWS access to AWS resources. This process is known as federation. Finally, when you (running as some identity) call an AWS API, IAM will determine whether the call is valid by evaluating one or more policies. There are two major kinds of policies: identity policies and resource policies. Identity policies determine what a given identity (role/user) is allowed to do. Identity policies can be managed by either AWS — these managed policies will be pre-created in your account — or by you. Below is an example of a simpler identity policy: APIs that can be called are referred to as Actions in IAM. Multiple APIs can hit into a single action, but, more often than not, actions just correspond to a single API. The policy is a whitelist; this means that, by default, actions are not permitted. An explicit Allow is given for 2 actions: CreateRole and CreateUser. For a full breakdown of how policy logic is evaluated within an AWS account, see this doc. Most API calls in AWS can be scoped-down to only being allowed on specific resources, as the above has. You can tell this has happened because the Resources section is not a *. This means that a request using this identity will succeed only against resources with those specific ARNs. For example, you could only create a role with the ARN arn:aws:iam::123456789012:role/some-role using this policy. Scoping down to individual resources is a best practice that prevents many security holes. Take, for instance, the 2019 Capital One hack. Capital One gave their firewall excessive S3 permissions, which, once it was tricked via SSRF, allowed attackers to steal data from over 100 million individuals. Identity policies alone — without resource policies — will only work within the same AWS account. Wildcards are supported. The second statement in this policy is related to Cloudwatch logs, and gives full access to Cloudwatch logs (any API they open up, and for any resource). Any given identity can have multiple policies attached to it; when this is the case, the identity gets the logical OR of the policies applied to it, where an explicit Deny will overwrite an explicit Allow . I think the syntax is mostly straightforward, but, for a deeper dive into policy syntax, read the docs. There is also an EMR policy generator I recommend you use to build these faster here: https://awspolicygen.s3.amazonaws.com/policygen.html When a resource is acted on by some Principal, whether that resource is an S3 bucket getting objects pulled from it, or an IAM role that someone is trying to assume, its resource policy will take effect. These may seem redundant at first, as you can scope identity policies to specific resources, but oftentimes it can be useful to set a policy on your resource instead of the identities that call it. These resource policies also serve a critical role in enabling cross-account access to resources. Identity policies alone cannot enable cross account access, as the permissions boundary between AWS accounts is much tighter than within a single account. Let’s examine a resource policy for a role. Note that resource policies on roles are also known as trust policies, because they enable others to assume the role. Principals are a name for the caller attempting to access a resource. This policy whitelists the service, EC2, as well as two other roles in account 123456789012 to assume this role. Principals are a super-set of normal Identities, that can include things like AWS services, or users federated from other applications. You’ll notice that when you specify a principal for some rule, you need to specify what kind of principal it is. There are several types of principals, but two of the most common are Service and AWS . The former allows an AWS service, like EC2, to access this role, and the latter allows a specific AWS account’s identities to access the role. Depending on the service, resource policies vary widely. Some resource policies are stricter than others, or enable different features. In Key Management Service, for example, you must grant your account’s root user permissions in a key’s resource policy before identity policies will be able to grant access to that key. S3 buckets have additional security controls, like Access Control Lists. Always aim to understand how the resource you’re working with manages permissions individually: don’t assume two types of resources manage permissions the same way. On most resources, resource policies are optional. If they are not present, they are ignored, as you will see below. To close, I want to offer a simple diagram to visualize what order the policies we talked about are evaluated in. In the interests of simplicity, I’ve omitted the complete evaluation logic and only included common policies below. I recommend you read the public documentation for a more detailed view of policy evaluation, including more esoteric policies like Session policies and Permissions Boundaries. IAM is one of the major building blocks of AWS. I hope this has served to introduce you to the major topics you will encounter when using it. If you’d like understand IAM a little more in depth, be sure to read my follow up post too! If you have any more questions or just want to chat you can contact me through my, [email protected] or message me on Twitter. [1] Architecting a multi-account organization is beyond the scope of this post, but, if you’re interested, I would recommend this video below and this introduction. [2] The root user is actually distinct from IAM users. There are certain tasks that only a root user can execute.
[ { "code": null, "e": 511, "s": 172, "text": "The first thing to both shock (and frustrate) many people moving into cloud-based environments is how complicated permissions can be. Typically, after years of becoming acclimated to being the God — sudo— of whatever code you have been writing prior, you are introduced to an environment where nearly everything is locked down by default." }, { "code": null, "e": 783, "s": 511, "text": "This post will focus on alleviating some of that pain by teaching you the most important parts of IAM, the identity and access management service for Amazon Web Services, as well as introducing some well known best practices. In future posts I plan to build off this one." }, { "code": null, "e": 909, "s": 783, "text": "Be sure to read this follow-up post, if you’re interested in seeing all the elements of IAM I discuss in this post in-action." }, { "code": null, "e": 1066, "s": 909, "text": "The world of AWS starts with accounts and resources within those accounts. IAM exists primarily to protect the resources in your account from problems like:" }, { "code": null, "e": 1177, "s": 1066, "text": "Malicious actors trying to do unwanted things to your AWS account (e.g. steal your data from your S3 buckets)." }, { "code": null, "e": 1309, "s": 1177, "text": "Users/applications within your company accidentally deleting resources, or performing actions they otherwise should not be able to." }, { "code": null, "e": 1375, "s": 1309, "text": "The logical barrier between users of AWS. Pretty straightforward:" }, { "code": null, "e": 1440, "s": 1375, "text": "1–1 correspondence with a 12-digit account id e.g. 123456789012." }, { "code": null, "e": 1598, "s": 1440, "text": "As a best practice, an organization will have multiple AWS accounts [1]. IAM is often used to handle permissions between AWS accounts within an organization." }, { "code": null, "e": 1670, "s": 1598, "text": "Tied to an email address, credit card; accounts are how you are billed." }, { "code": null, "e": 1778, "s": 1670, "text": "Resources are persisted objects in your account that you want to use, like load balancers or EC2 instances." }, { "code": null, "e": 1917, "s": 1778, "text": "Resources always have an ARN — Amazon Resource Name — that uniquely identify them. E.g. for an IAM user, an ARN might look like the below:" }, { "code": null, "e": 1975, "s": 1917, "text": "arn:aws:iam::123456789012:user/Development/product_1234/*" }, { "code": null, "e": 2100, "s": 1975, "text": "Notice how the account id 123456789012is present in the ARN, as well as the type of resource (this resource is an IAM user)." }, { "code": null, "e": 2341, "s": 2100, "text": "The core feature of IAM is identities, a type of AWS resource. AWS services always expose APIs you can call using some identity; this tells AWS who you are (authentication) and whether you’re allowed to do what you’re doing (authorization)." }, { "code": null, "e": 2407, "s": 2341, "text": "There are two major forms of identities in IAM: users, and roles." }, { "code": null, "e": 2686, "s": 2407, "text": "The intention of a user in IAM is similar those in other websites like Facebook. When you first create an AWS account you are given a root user that has complete access to your account [2]. Then you’re given the — strongly suggested — option of creating further users and roles." }, { "code": null, "e": 2707, "s": 2686, "text": "Some notes on users:" }, { "code": null, "e": 2882, "s": 2707, "text": "Users, unlike roles, have a username and password. These are long lived credentials that can be persisted for an extended period of time and used to log into the AWS console." }, { "code": null, "e": 3154, "s": 2882, "text": "Often intended to give individuals access to AWS console, or APIs. However, as a best practice, you should use roles instead of users whenever possible. This is to limit the risk of long-lived credentials being misplaced and giving an attacker access to your AWS account." }, { "code": null, "e": 3456, "s": 3154, "text": "Users are given access keys. Access keys can be used to call AWS services via the CLI or SDK. Like a username/password, access keys are long lived. They will look more randomized, and can be used together with the CLI by creating a file named ~/.aws/credentials with contents that look like the below:" }, { "code": null, "e": 3575, "s": 3456, "text": "[personal]aws_access_key_id = AKIAIOSFODNN7EXAMPLEaws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" }, { "code": null, "e": 3660, "s": 3575, "text": "You can use a credentials profile with the CLI with the --profile option on the CLI:" }, { "code": null, "e": 3768, "s": 3660, "text": "> aws s3 ls --profile personal2017-11-30 16:20:55 some-s3-bucket2017-10-31 20:05:17 some-other-s3-bucket..." }, { "code": null, "e": 4034, "s": 3768, "text": "Like users, roles are an identity used for accessing an AWS APIs and resources. However, roles are generally used to grant temporary credentials to an AWS account. Further, these temporary credentials can be configured to trust third parties, or other AWS services." }, { "code": null, "e": 4070, "s": 4034, "text": "Roles are used ubiquitously in AWS:" }, { "code": null, "e": 4220, "s": 4070, "text": "An EC2 instance that needs to access AWS resources will use an instance role to command other AWS services/resources based on your application logic." }, { "code": null, "e": 4514, "s": 4220, "text": "Other AWS accounts that need access to resources in your account will sometimes assume a role in your account to gain access via the STS assume role API. To allow them to do this, you can grant permissions on a role for some identity in another account via a trust policy (more on this later)." }, { "code": null, "e": 4989, "s": 4514, "text": "A critical feature of AWS is its ability to take actions on your behalf. However, AWS services are typically implemented as AWS accounts; this means that they do not, by default, have access to the resources in your account. Accordingly, they will often require you create and grant them access to a “service role” in your account so that they can take actions on your behalf. Autoscaling on EC2, for example, will need permissions to spin up and down EC2 instances for you." }, { "code": null, "e": 5135, "s": 4989, "text": "Third parties, like JumpCloud, will use roles to grant users managed outside of AWS access to AWS resources. This process is known as federation." }, { "code": null, "e": 5358, "s": 5135, "text": "Finally, when you (running as some identity) call an AWS API, IAM will determine whether the call is valid by evaluating one or more policies. There are two major kinds of policies: identity policies and resource policies." }, { "code": null, "e": 5559, "s": 5358, "text": "Identity policies determine what a given identity (role/user) is allowed to do. Identity policies can be managed by either AWS — these managed policies will be pre-created in your account — or by you." }, { "code": null, "e": 5609, "s": 5559, "text": "Below is an example of a simpler identity policy:" }, { "code": null, "e": 5779, "s": 5609, "text": "APIs that can be called are referred to as Actions in IAM. Multiple APIs can hit into a single action, but, more often than not, actions just correspond to a single API." }, { "code": null, "e": 6022, "s": 5779, "text": "The policy is a whitelist; this means that, by default, actions are not permitted. An explicit Allow is given for 2 actions: CreateRole and CreateUser. For a full breakdown of how policy logic is evaluated within an AWS account, see this doc." }, { "code": null, "e": 6722, "s": 6022, "text": "Most API calls in AWS can be scoped-down to only being allowed on specific resources, as the above has. You can tell this has happened because the Resources section is not a *. This means that a request using this identity will succeed only against resources with those specific ARNs. For example, you could only create a role with the ARN arn:aws:iam::123456789012:role/some-role using this policy. Scoping down to individual resources is a best practice that prevents many security holes. Take, for instance, the 2019 Capital One hack. Capital One gave their firewall excessive S3 permissions, which, once it was tricked via SSRF, allowed attackers to steal data from over 100 million individuals." }, { "code": null, "e": 6820, "s": 6722, "text": "Identity policies alone — without resource policies — will only work within the same AWS account." }, { "code": null, "e": 6999, "s": 6820, "text": "Wildcards are supported. The second statement in this policy is related to Cloudwatch logs, and gives full access to Cloudwatch logs (any API they open up, and for any resource)." }, { "code": null, "e": 7206, "s": 6999, "text": "Any given identity can have multiple policies attached to it; when this is the case, the identity gets the logical OR of the policies applied to it, where an explicit Deny will overwrite an explicit Allow ." }, { "code": null, "e": 7310, "s": 7206, "text": "I think the syntax is mostly straightforward, but, for a deeper dive into policy syntax, read the docs." }, { "code": null, "e": 7449, "s": 7310, "text": "There is also an EMR policy generator I recommend you use to build these faster here: https://awspolicygen.s3.amazonaws.com/policygen.html" }, { "code": null, "e": 7851, "s": 7449, "text": "When a resource is acted on by some Principal, whether that resource is an S3 bucket getting objects pulled from it, or an IAM role that someone is trying to assume, its resource policy will take effect. These may seem redundant at first, as you can scope identity policies to specific resources, but oftentimes it can be useful to set a policy on your resource instead of the identities that call it." }, { "code": null, "e": 8104, "s": 7851, "text": "These resource policies also serve a critical role in enabling cross-account access to resources. Identity policies alone cannot enable cross account access, as the permissions boundary between AWS accounts is much tighter than within a single account." }, { "code": null, "e": 8266, "s": 8104, "text": "Let’s examine a resource policy for a role. Note that resource policies on roles are also known as trust policies, because they enable others to assume the role." }, { "code": null, "e": 8585, "s": 8266, "text": "Principals are a name for the caller attempting to access a resource. This policy whitelists the service, EC2, as well as two other roles in account 123456789012 to assume this role. Principals are a super-set of normal Identities, that can include things like AWS services, or users federated from other applications." }, { "code": null, "e": 8929, "s": 8585, "text": "You’ll notice that when you specify a principal for some rule, you need to specify what kind of principal it is. There are several types of principals, but two of the most common are Service and AWS . The former allows an AWS service, like EC2, to access this role, and the latter allows a specific AWS account’s identities to access the role." }, { "code": null, "e": 9489, "s": 8929, "text": "Depending on the service, resource policies vary widely. Some resource policies are stricter than others, or enable different features. In Key Management Service, for example, you must grant your account’s root user permissions in a key’s resource policy before identity policies will be able to grant access to that key. S3 buckets have additional security controls, like Access Control Lists. Always aim to understand how the resource you’re working with manages permissions individually: don’t assume two types of resources manage permissions the same way." }, { "code": null, "e": 9606, "s": 9489, "text": "On most resources, resource policies are optional. If they are not present, they are ignored, as you will see below." }, { "code": null, "e": 9720, "s": 9606, "text": "To close, I want to offer a simple diagram to visualize what order the policies we talked about are evaluated in." }, { "code": null, "e": 10012, "s": 9720, "text": "In the interests of simplicity, I’ve omitted the complete evaluation logic and only included common policies below. I recommend you read the public documentation for a more detailed view of policy evaluation, including more esoteric policies like Session policies and Permissions Boundaries." }, { "code": null, "e": 10154, "s": 10012, "text": "IAM is one of the major building blocks of AWS. I hope this has served to introduce you to the major topics you will encounter when using it." }, { "code": null, "e": 10246, "s": 10154, "text": "If you’d like understand IAM a little more in depth, be sure to read my follow up post too!" }, { "code": null, "e": 10378, "s": 10246, "text": "If you have any more questions or just want to chat you can contact me through my, [email protected] or message me on Twitter." }, { "code": null, "e": 10543, "s": 10378, "text": "[1] Architecting a multi-account organization is beyond the scope of this post, but, if you’re interested, I would recommend this video below and this introduction." } ]
Geospatial Operations at Scale with Dask and Geopandas | by Ravi Shekhar | Towards Data Science
In this post, I will give a motivating example of a spatial join, and then describe how to perform spatial joins at scale with GeoPandas and Dask. Note: To condense and simplify this post for Medium, I removed interactive graphics and most code. You can view the original Jupyter notebook on nbviewer. One problem I came across when analyzing the New York City Taxi Dataset, is that from 2009 to June 2016, both the starting and stopping locations of taxi trips were given as longitude and latitude points. After July 2016, to provide a degree of anonymity when releasing data to the public, the Taxi and Limousine Commission (TLC) only provides the starting and ending “taxi zones” of a trip, and a shapefile that specifies the boundaries, available here. To get a continuous dataset, I needed an efficient way to convert a latitude and longitude coordinate pair into a “taxi zone”. Let’s load the shapefile in Geopandas, and set the coordinate system to ‘epsg:4326’, which is latitude and longitude coordinates. Here are the first few rows. We see that the geometry column consists of polygons (from Shapely) that have vertices defined by longitude and latitude points. Let’s plot in order of ascending LocationID. This is a familiar map of New York, with 262 taxi districts shown, colored by the id of the taxi district. I see that LocationID is not in any particular geographic order. I have added a random point (-73.966 ̊E, 40.78 ̊N) in magenta, which happens to fall in the middle of Central Park. Assigning a point as within a taxi zone is something humans can do easily, but on a computer it requires solving the point in polygon problem. Luckily the Shapely library provides an easy interface to such geometric operations in Python. But, point in polygon is computationally expensive, and using the Shapely library on 2.4 billion (latitude, longitude) pairs to assign taxi zones as in the NYC Taxi Dataset would take a modern single core cpu about four years. To speed this up, we calculate the bounding boxes for each taxi zone, which looks like: Now, given a (longitude, latitude) coordinate pair, bounding boxes that contain that pair can be efficiently calculated with an R-tree. You can find an excellent introduction to R-trees here. Only the polygons (taxi zones) that have bounding boxes that contain the coordinate pair need to be examined, and then the point in Polygon is solved for those (hopefully) few taxi zones. This reduces computation by a factor of about 100–1000. This process, assigning coordinate pairs to taxi zones is one example of a spatial join. Geopandas provides a nice interface to efficient spatial joins in Python, and it takes care of calculating bounding boxes and R-trees for you, as this snippet which performs a left spatial join shows. import geopandas as gpdfrom shapely.geometry import Pointdf = gpd.read_file('taxi_zones.shp').to_crs({'init': 'epsg:4326'})df = df.drop(['Shape_Area', 'Shape_Leng', 'OBJECTID'], axis=1)gpd.sjoin(gpd.GeoDataFrame(crs={'init': 'epsg:4326'}, geometry=[Point(-73.966, 40.78)]), df, how='left', op='within') This code does the merge for a single point (drawn in magenta) on maps above, and correctly identifies it in Central Park In my NYC transit project, I download and process the entire 200GB Taxi dataset. Here I load up a single file from the taxi dataset (May 2016) into Dask, and show the first few rows and a few columns. The file is a bit large at 1.8GB, and Dask chooses to divide up the dataframe into 30 partitions for efficient calculations. Each partition is a pandas DataFrame, and dask takes care of all the logic to view the combination as a single DataFrame. Here are a few columns. So each trip has pickup and dropoff (longitude, latitude) coordinate pairs. Just to give you a feel for the data, I plot the start and end locations of the first trip, ending in the East Village. Driving directions come with a great deal of additional complexity, so here I just plot an arrow, as the crow flies. A spatial join identifies the taxi zones as Clinton East and East Village. So, Dask DataFrames are just collections of Pandas DataFrames, and I know how to perform a spatial join on a Pandas DataFrame. Let’s take advantage of Dask’s map_partitions function to do a spatial join with the taxi zones on every partition. Here is the function to do the spatial join, given a Pandas DataFrame, and the names of the longitude, latitude, and taxizone id columns. Code is directly linked here. Using the map_partitions function, I apply the spatial join to each of the Pandas DataFrames that make up the Dask DataFrame. For simplicity, I just call the function twice, once for pickup locations, and once for dropoff locations. To assist dask in determining schema of returned data, we specify it as a column of floats (allowing for NaN values). trips['pickup_taxizone_id'] = trips.map_partitions( assign_taxi_zones, "pickup_longitude", "pickup_latitude", "pickup_taxizone_id", meta=('pickup_taxizone_id', np.float64))trips['dropoff_taxizone_id'] = trips.map_partitions( assign_taxi_zones, "dropoff_longitude", "dropoff_latitude", "dropoff_taxizone_id", meta=('dropoff_taxizone_id', np.float64))trips[['pickup_taxizone_id', 'dropoff_taxizone_id']].head() At this point, the trips Dask DataFrame will have valid taxizone_id information. Lets save this data to Parquet, which is a columnar format that is well supported in Dask and Apache Spark. This prevents Dask from recalculating the spatial join (which is very expensive) every time an operation on the trips DataFrame is required. trips.to_parquet('trips_2016-05.parquet', has_nulls=True, object_encoding='json', compression="SNAPPY")trips = dd.read_parquet('trips_2016-05.parquet', columns=['pickup_taxizone_id', 'dropoff_taxizone_id']) To close this post out, I’ll produce a heatmap of taxi dropoff locations, aggregated by taxi zone using Dask. Unsurprisingly (for New Yorkers at least) the vast majority of taxi dropoffs tend to be in Downtown and Midtown Manhattan. I will analyze this dataset further in future posts. In this post I described the process of a Spatial Join, and doing the Spatial Join at scale on a cluster using Dask and Pandas. I glossed over some details that are important for the full New York Taxi Dataset, but my full code is available here on Github. In future posts, I will analyze this data more thoroughly, and possibly look into releasing the processed data as a parquet file for others to analyze. The spatial join as written above with GeoPandas, using the New York Taxi Dataset, can assign taxi zones to approxmately 40 million taxi trips per hour on a 4 GHz 4-core i5 system. A lot of the code that supports this join is some amalgamation of Python and wrapped C code. This is approxmately a factor of two slower than performing the same spatial join in highly optimized PostGIS C/C++ code. However, PostGIS does not efficiently use multiple cores (at least without multiple spatial joins running simultaneously), and more importantly, the network and serialization overhead of a round trip to the PostgreSQL database puts PostgreSQL/PostGIS at roughly the same speed as the GeoPandas implementation I describe in this post, with vastly more moving parts to break. Basically, Python is actually pretty fast for these kinds of data structure operations. Some rights reserved
[ { "code": null, "e": 318, "s": 171, "text": "In this post, I will give a motivating example of a spatial join, and then describe how to perform spatial joins at scale with GeoPandas and Dask." }, { "code": null, "e": 473, "s": 318, "text": "Note: To condense and simplify this post for Medium, I removed interactive graphics and most code. You can view the original Jupyter notebook on nbviewer." }, { "code": null, "e": 1214, "s": 473, "text": "One problem I came across when analyzing the New York City Taxi Dataset, is that from 2009 to June 2016, both the starting and stopping locations of taxi trips were given as longitude and latitude points. After July 2016, to provide a degree of anonymity when releasing data to the public, the Taxi and Limousine Commission (TLC) only provides the starting and ending “taxi zones” of a trip, and a shapefile that specifies the boundaries, available here. To get a continuous dataset, I needed an efficient way to convert a latitude and longitude coordinate pair into a “taxi zone”. Let’s load the shapefile in Geopandas, and set the coordinate system to ‘epsg:4326’, which is latitude and longitude coordinates. Here are the first few rows." }, { "code": null, "e": 1388, "s": 1214, "text": "We see that the geometry column consists of polygons (from Shapely) that have vertices defined by longitude and latitude points. Let’s plot in order of ascending LocationID." }, { "code": null, "e": 2229, "s": 1388, "text": "This is a familiar map of New York, with 262 taxi districts shown, colored by the id of the taxi district. I see that LocationID is not in any particular geographic order. I have added a random point (-73.966 ̊E, 40.78 ̊N) in magenta, which happens to fall in the middle of Central Park. Assigning a point as within a taxi zone is something humans can do easily, but on a computer it requires solving the point in polygon problem. Luckily the Shapely library provides an easy interface to such geometric operations in Python. But, point in polygon is computationally expensive, and using the Shapely library on 2.4 billion (latitude, longitude) pairs to assign taxi zones as in the NYC Taxi Dataset would take a modern single core cpu about four years. To speed this up, we calculate the bounding boxes for each taxi zone, which looks like:" }, { "code": null, "e": 2955, "s": 2229, "text": "Now, given a (longitude, latitude) coordinate pair, bounding boxes that contain that pair can be efficiently calculated with an R-tree. You can find an excellent introduction to R-trees here. Only the polygons (taxi zones) that have bounding boxes that contain the coordinate pair need to be examined, and then the point in Polygon is solved for those (hopefully) few taxi zones. This reduces computation by a factor of about 100–1000. This process, assigning coordinate pairs to taxi zones is one example of a spatial join. Geopandas provides a nice interface to efficient spatial joins in Python, and it takes care of calculating bounding boxes and R-trees for you, as this snippet which performs a left spatial join shows." }, { "code": null, "e": 3265, "s": 2955, "text": "import geopandas as gpdfrom shapely.geometry import Pointdf = gpd.read_file('taxi_zones.shp').to_crs({'init': 'epsg:4326'})df = df.drop(['Shape_Area', 'Shape_Leng', 'OBJECTID'], axis=1)gpd.sjoin(gpd.GeoDataFrame(crs={'init': 'epsg:4326'}, geometry=[Point(-73.966, 40.78)]), df, how='left', op='within')" }, { "code": null, "e": 3387, "s": 3265, "text": "This code does the merge for a single point (drawn in magenta) on maps above, and correctly identifies it in Central Park" }, { "code": null, "e": 3859, "s": 3387, "text": "In my NYC transit project, I download and process the entire 200GB Taxi dataset. Here I load up a single file from the taxi dataset (May 2016) into Dask, and show the first few rows and a few columns. The file is a bit large at 1.8GB, and Dask chooses to divide up the dataframe into 30 partitions for efficient calculations. Each partition is a pandas DataFrame, and dask takes care of all the logic to view the combination as a single DataFrame. Here are a few columns." }, { "code": null, "e": 4247, "s": 3859, "text": "So each trip has pickup and dropoff (longitude, latitude) coordinate pairs. Just to give you a feel for the data, I plot the start and end locations of the first trip, ending in the East Village. Driving directions come with a great deal of additional complexity, so here I just plot an arrow, as the crow flies. A spatial join identifies the taxi zones as Clinton East and East Village." }, { "code": null, "e": 4658, "s": 4247, "text": "So, Dask DataFrames are just collections of Pandas DataFrames, and I know how to perform a spatial join on a Pandas DataFrame. Let’s take advantage of Dask’s map_partitions function to do a spatial join with the taxi zones on every partition. Here is the function to do the spatial join, given a Pandas DataFrame, and the names of the longitude, latitude, and taxizone id columns. Code is directly linked here." }, { "code": null, "e": 5009, "s": 4658, "text": "Using the map_partitions function, I apply the spatial join to each of the Pandas DataFrames that make up the Dask DataFrame. For simplicity, I just call the function twice, once for pickup locations, and once for dropoff locations. To assist dask in determining schema of returned data, we specify it as a column of floats (allowing for NaN values)." }, { "code": null, "e": 5430, "s": 5009, "text": "trips['pickup_taxizone_id'] = trips.map_partitions( assign_taxi_zones, \"pickup_longitude\", \"pickup_latitude\", \"pickup_taxizone_id\", meta=('pickup_taxizone_id', np.float64))trips['dropoff_taxizone_id'] = trips.map_partitions( assign_taxi_zones, \"dropoff_longitude\", \"dropoff_latitude\", \"dropoff_taxizone_id\", meta=('dropoff_taxizone_id', np.float64))trips[['pickup_taxizone_id', 'dropoff_taxizone_id']].head()" }, { "code": null, "e": 5760, "s": 5430, "text": "At this point, the trips Dask DataFrame will have valid taxizone_id information. Lets save this data to Parquet, which is a columnar format that is well supported in Dask and Apache Spark. This prevents Dask from recalculating the spatial join (which is very expensive) every time an operation on the trips DataFrame is required." }, { "code": null, "e": 5974, "s": 5760, "text": "trips.to_parquet('trips_2016-05.parquet', has_nulls=True, object_encoding='json', compression=\"SNAPPY\")trips = dd.read_parquet('trips_2016-05.parquet', columns=['pickup_taxizone_id', 'dropoff_taxizone_id'])" }, { "code": null, "e": 6260, "s": 5974, "text": "To close this post out, I’ll produce a heatmap of taxi dropoff locations, aggregated by taxi zone using Dask. Unsurprisingly (for New Yorkers at least) the vast majority of taxi dropoffs tend to be in Downtown and Midtown Manhattan. I will analyze this dataset further in future posts." }, { "code": null, "e": 6669, "s": 6260, "text": "In this post I described the process of a Spatial Join, and doing the Spatial Join at scale on a cluster using Dask and Pandas. I glossed over some details that are important for the full New York Taxi Dataset, but my full code is available here on Github. In future posts, I will analyze this data more thoroughly, and possibly look into releasing the processed data as a parquet file for others to analyze." }, { "code": null, "e": 6943, "s": 6669, "text": "The spatial join as written above with GeoPandas, using the New York Taxi Dataset, can assign taxi zones to approxmately 40 million taxi trips per hour on a 4 GHz 4-core i5 system. A lot of the code that supports this join is some amalgamation of Python and wrapped C code." }, { "code": null, "e": 7439, "s": 6943, "text": "This is approxmately a factor of two slower than performing the same spatial join in highly optimized PostGIS C/C++ code. However, PostGIS does not efficiently use multiple cores (at least without multiple spatial joins running simultaneously), and more importantly, the network and serialization overhead of a round trip to the PostgreSQL database puts PostgreSQL/PostGIS at roughly the same speed as the GeoPandas implementation I describe in this post, with vastly more moving parts to break." }, { "code": null, "e": 7527, "s": 7439, "text": "Basically, Python is actually pretty fast for these kinds of data structure operations." } ]
Java JColorChooser Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this example, I am going to show you how to use apply different colors to swing components. Java JColorChooser is a class used to display the color pane to pick the colors in different formats. package com.onlinetutorialspoint.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JPanel; public class JColorChooserDemo extends JFrame { private JButton button; private Color color; private JPanel colorPanel; public JColorChooserDemo(){ super("JColorChooser Example"); colorPanel = new JPanel(); button = new JButton("Apply Color"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { color = JColorChooser.showDialog(JColorChooserDemo.this, "Pick Color", color); if(color == null) color = Color.WHITE; colorPanel.setBackground(color); } }); add(colorPanel,BorderLayout.CENTER); add(button,BorderLayout.SOUTH); setSize(400, 130); setVisible(true); } public static void main(String[] args) { JColorChooserDemo colorChooser = new JColorChooserDemo(); colorChooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Output : Color Chooser : After Applying Color : RGB Color Picker : After Applying RGB Picker : Happy Learning 🙂 How to create Java Rainbow using Swing How to use Java JSlider Example Java Swing JOptionPane Example Java Swing JSplitPane Example Java Swing JLabel Example Java Swing Login Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JOptionPane Html Content Example Java Swing JTree Example How to create Java Smiley Swing Java Swing BorderFactory Example How to create Java Rainbow using Swing How to use Java JSlider Example Java Swing JOptionPane Example Java Swing JSplitPane Example Java Swing JLabel Example Java Swing Login Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JOptionPane Html Content Example Java Swing JTree Example How to create Java Smiley Swing Java Swing BorderFactory Example Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 595, "s": 398, "text": "In this example, I am going to show you how to use apply different colors to swing components. Java JColorChooser is a class used to display the color pane to pick the colors in different formats." }, { "code": null, "e": 1927, "s": 595, "text": "package com.onlinetutorialspoint.swing;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JColorChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class JColorChooserDemo extends JFrame {\n\n private JButton button;\n private Color color;\n private JPanel colorPanel;\n \n public JColorChooserDemo(){\n super(\"JColorChooser Example\");\n \n colorPanel = new JPanel();\n \n button = new JButton(\"Apply Color\");\n \n button.addActionListener(new ActionListener() {\n \n @Override\n public void actionPerformed(ActionEvent e) {\n color = JColorChooser.showDialog(JColorChooserDemo.this, \"Pick Color\", color);\n if(color == null)\n color = Color.WHITE;\n colorPanel.setBackground(color);\n }\n });\n add(colorPanel,BorderLayout.CENTER);\n add(button,BorderLayout.SOUTH);\n setSize(400, 130);\n setVisible(true);\n }\n public static void main(String[] args) {\n JColorChooserDemo colorChooser = new JColorChooserDemo();\n colorChooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n\n}" }, { "code": null, "e": 1936, "s": 1927, "text": "Output :" }, { "code": null, "e": 1952, "s": 1936, "text": "Color Chooser :" }, { "code": null, "e": 1975, "s": 1952, "text": "After Applying Color :" }, { "code": null, "e": 1994, "s": 1975, "text": "RGB Color Picker :" }, { "code": null, "e": 2022, "s": 1994, "text": "After Applying RGB Picker :" }, { "code": null, "e": 2039, "s": 2022, "text": "Happy Learning 🙂" }, { "code": null, "e": 2506, "s": 2039, "text": "\nHow to create Java Rainbow using Swing\nHow to use Java JSlider Example\nJava Swing JOptionPane Example\nJava Swing JSplitPane Example\nJava Swing JLabel Example\nJava Swing Login Example\nJava Swing ProgressBar Example\nJava Swing JTable Example\nJava Swing Advanced JTable Example\nJava Swing JTabbedPane Example\nJava Swing JMenu Example\nJava Swing JOptionPane Html Content Example\nJava Swing JTree Example\nHow to create Java Smiley Swing\nJava Swing BorderFactory Example\n" }, { "code": null, "e": 2545, "s": 2506, "text": "How to create Java Rainbow using Swing" }, { "code": null, "e": 2577, "s": 2545, "text": "How to use Java JSlider Example" }, { "code": null, "e": 2608, "s": 2577, "text": "Java Swing JOptionPane Example" }, { "code": null, "e": 2638, "s": 2608, "text": "Java Swing JSplitPane Example" }, { "code": null, "e": 2664, "s": 2638, "text": "Java Swing JLabel Example" }, { "code": null, "e": 2689, "s": 2664, "text": "Java Swing Login Example" }, { "code": null, "e": 2720, "s": 2689, "text": "Java Swing ProgressBar Example" }, { "code": null, "e": 2746, "s": 2720, "text": "Java Swing JTable Example" }, { "code": null, "e": 2781, "s": 2746, "text": "Java Swing Advanced JTable Example" }, { "code": null, "e": 2812, "s": 2781, "text": "Java Swing JTabbedPane Example" }, { "code": null, "e": 2837, "s": 2812, "text": "Java Swing JMenu Example" }, { "code": null, "e": 2881, "s": 2837, "text": "Java Swing JOptionPane Html Content Example" }, { "code": null, "e": 2906, "s": 2881, "text": "Java Swing JTree Example" }, { "code": null, "e": 2938, "s": 2906, "text": "How to create Java Smiley Swing" }, { "code": null, "e": 2971, "s": 2938, "text": "Java Swing BorderFactory Example" }, { "code": null, "e": 2977, "s": 2975, "text": "Δ" }, { "code": null, "e": 3001, "s": 2977, "text": " Install Java on Mac OS" }, { "code": null, "e": 3029, "s": 3001, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3058, "s": 3029, "text": " Install Minikube on Windows" }, { "code": null, "e": 3093, "s": 3058, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3120, "s": 3093, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3147, "s": 3120, "text": " Install Gradle on Windows" }, { "code": null, "e": 3176, "s": 3147, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3202, "s": 3176, "text": " Install PuTTY on windows" }, { "code": null, "e": 3228, "s": 3202, "text": " Install Mysql on Windows" }, { "code": null, "e": 3264, "s": 3228, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 3298, "s": 3264, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 3324, "s": 3298, "text": " Install Maven on Windows" }, { "code": null, "e": 3349, "s": 3324, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 3383, "s": 3349, "text": " Install Maven on Windows Command" }, { "code": null, "e": 3418, "s": 3383, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 3442, "s": 3418, "text": " Install Ant on Windows" }, { "code": null, "e": 3471, "s": 3442, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3503, "s": 3471, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 3536, "s": 3503, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 3561, "s": 3536, "text": " Java8 – Install Windows" }, { "code": null, "e": 3578, "s": 3561, "text": " Java8 – foreach" }, { "code": null, "e": 3606, "s": 3578, "text": " Java8 – forEach with index" }, { "code": null, "e": 3637, "s": 3606, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 3669, "s": 3637, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 3689, "s": 3669, "text": " Java8 – GroupingBy" }, { "code": null, "e": 3709, "s": 3689, "text": " Java8 – SummingInt" }, { "code": null, "e": 3733, "s": 3709, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 3763, "s": 3733, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 3795, "s": 3763, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 3831, "s": 3795, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 3875, "s": 3831, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 3907, "s": 3875, "text": " Howto – Convert List to String" }, { "code": null, "e": 3948, "s": 3907, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 3985, "s": 3948, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4025, "s": 3985, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4054, "s": 4025, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4086, "s": 4054, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4106, "s": 4086, "text": " Howto – Sort a Map" }, { "code": null, "e": 4128, "s": 4106, "text": " Howto – Filter a Map" }, { "code": null, "e": 4158, "s": 4128, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4209, "s": 4158, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4245, "s": 4209, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 4277, "s": 4245, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 4312, "s": 4277, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 4335, "s": 4312, "text": " Howto – Merge Streams" }, { "code": null, "e": 4382, "s": 4335, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 4407, "s": 4382, "text": " Howto -Get Stream count" }, { "code": null, "e": 4451, "s": 4407, "text": " Howto – Get Min and Max values in a Stream" } ]
Median of BST | Practice | GeeksforGeeks
Given a Binary Search Tree of size N, find the Median of its Node values. Example 1: Input: 6 / \ 3 8 / \ / \ 1 4 7 9 Output: 6 Explanation: Inorder of Given BST will be: 1, 3, 4, 6, 7, 8, 9. So, here median will 6. Example 2: Input: 6 / \ 3 8 / \ / 1 4 7 Output: 5 Explanation:Inorder of Given BST will be: 1, 3, 4, 6, 7, 8. So, here median will (4 + 6)/2 = 10/2 = 5. Your Task: You don't need to read input or print anything. Your task is to complete the function findMedian() which takes the root of the Binary Search Tree as input and returns the Median of Node values in the given BST. Median of the BST is: If number of nodes are even: then median = (N/2 th node + (N/2)+1 th node)/2 If number of nodes are odd : then median = (N+1)/2th node. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1<=N<=1000 0 ankushkhatri3 days ago import math def inorder(root): global arr if not root: return inorder(root.left) arr.append(root.data) inorder(root.right) def findMedian(root): global arr arr = [] inorder(root) #print(arr) m = int(len(arr)/2) n = len(arr) if n%2 == 0: ans = (arr[m]+arr[m-1])/2 if math.floor(ans)==math.ceil(ans): return int(ans) else: return ans else: return arr[m] 0 ankushkhatri This comment was deleted. 0 uttarandas5012 weeks ago void inorder(Node *root, vector<int> &v){ if(!root){return;} inorder(root->left, v); v.push_back(root->data); inorder(root->right, v); } float findMedian(struct Node *root) { //Code here vector<int>v; inorder(root, v); return (v[v.size()/2] + v[(v.size()-1)/2])/2.00; } 0 neerajchatterjee23012 weeks ago void inorder(struct Node* root, int &n){ if(root == NULL) return; inorder(root->left, n); n++; inorder(root->right, n); } void calc(Node* root, int &k, int &ans){ if(root == NULL){ return; } calc(root->left, k, ans); k--; if(k == 0){ k = INT_MAX; ans = root->data; return; } calc(root->right, k, ans); } float findMedian(struct Node *root) { int n = 0; inorder(root, n); if(n&1){ int k = (n+1)/2; int fans; calc(root, k, fans); return fans; } else{ int k = n/2; int first; calc(root, k, first); int k2 = n/2 + 1; int second; calc(root, k2, second); float ans = (first + second) / 2.0 ; return ans; } } 0 amarrajsmart1972 weeks ago void inorder(struct Node* root,vector<int> &v){ if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v);}float findMedian(struct Node *root){ //Code here vector<int> v; inorder(root,v); int mid=v.size()/2; if(v.size()%2==0) return (v[mid]+v[mid-1])/(float)2; else return v[mid];} 0 himanshibaranwal051291 month ago I am not sure why is this not getting submitted. public static List<Integer> nodeValues = new ArrayList<Integer>(); public static float findMedian(Node root) { if(root==null){ return 0; } inOrderTraversal(root); int size = nodeValues.size(); if(size%2==0){ float sumMidValues = nodeValues.get(size/2)+nodeValues.get((size/2)-1); float median = sumMidValues/2; return median; }else{ return nodeValues.get(size/2); } } static void inOrderTraversal(Node root){ if(root==null){ return; } inOrderTraversal(root.left); nodeValues.add(root.data); inOrderTraversal(root.right); } 0 harrypotter01 month ago ans = []def solve(root, ans, count): if not root: return count[0]+=1 solve(root.left, ans,count ) ans.append(root.data) solve(root.right, ans, count) def findMedian(root): ans = [] count = [0] solve(root, ans, count ) n = count[0] # print(ans) if n%2: ## odd ind = n//2+1 return ans[ind-1] else: ind = (n//2+(n//2)+1)//2 if (ans[n//2-1]+ans[n//2])/2 == int((ans[n//2-1]+ans[n//2])/2): return int((ans[n//2-1]+ans[n//2])/2) else: return (ans[n//2-1]+ans[n//2])/2 0 cshubham4391 month ago java Solution static void inorder(Node root,ArrayList<Integer> list){ if(root!=null){ inorder(root.left,list); list.add(root.data); inorder(root.right,list); } } public static float findMedian(Node root) { // code here. ArrayList<Integer> list = new ArrayList<>(); inorder(root,list); int n = list.size(); if(n%2==0){ return (((float)list.get(n/2-1)+(float)list.get(n/2))/2); } else return list.get(n/2); +3 bruhmantri2 months ago Time Complexity: O(n) Space Complexity: O(1) (if recurive stack space not considered) Approach: First Calculate total numberof nodes in the tree If the nodes are even, we need to consider 2 numbers for median If the nodes are odd, only 1 number is needed. So we find middle element by countOfNodes/2 + 1 We also maintain a prev pointer whcih stores prev traversed node When our node is at position middleELement, we check if it had even, if yes then we would take prev and root (prev + root)/2 as answer, else we would have just just root as ans int findCountOfNodes(Node *root) { if(!root) { return 0; } int leftTree = findCountOfNodes(root->left); int rightTree = findCountOfNodes(root->right); return leftTree + rightTree + 1; } void solve(Node* root, int k, bool twoNums, float &ans, int &currentNode, Node* &prev) { if(!root) { return; } solve(root->left, k, twoNums, ans, currentNode, prev); if(currentNode == k) { if(twoNums) { ans = ((float)prev->data + (float)root->data)/2; } else { ans = root->data; } } prev = root; currentNode++; solve(root->right, k, twoNums, ans, currentNode, prev); } float findMedian(struct Node *root) { //Code here int countOfNodes = findCountOfNodes(root); int currentNode = 1; bool twoNums = true; int k = 0; if(countOfNodes%2 == 0) { twoNums = true; } else { twoNums = false; } k = (countOfNodes/2) + 1; float ans = 0; Node* prev = NULL; solve(root, k, twoNums, ans, currentNode, prev); return ans; } 0 yojobex113 This comment was deleted. 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": 312, "s": 238, "text": "Given a Binary Search Tree of size N, find the Median of its Node values." }, { "code": null, "e": 323, "s": 312, "text": "Example 1:" }, { "code": null, "e": 493, "s": 323, "text": "Input:\n 6\n / \\\n 3 8 \n / \\ / \\\n1 4 7 9\nOutput: 6\nExplanation: Inorder of Given BST will be:\n1, 3, 4, 6, 7, 8, 9. So, here median will 6.\n" }, { "code": null, "e": 505, "s": 493, "text": "\nExample 2:" }, { "code": null, "e": 689, "s": 505, "text": "Input:\n 6\n / \\\n 3 8 \n / \\ / \n1 4 7 \nOutput: 5\nExplanation:Inorder of Given BST will be:\n1, 3, 4, 6, 7, 8. So, here median will\n(4 + 6)/2 = 10/2 = 5." }, { "code": null, "e": 935, "s": 691, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findMedian() which takes the root of the Binary Search Tree as input and returns the Median of Node values in the given BST.\nMedian of the BST is:" }, { "code": null, "e": 1012, "s": 935, "text": "If number of nodes are even: then median = (N/2 th node + (N/2)+1 th node)/2" }, { "code": null, "e": 1071, "s": 1012, "text": "If number of nodes are odd : then median = (N+1)/2th node." }, { "code": null, "e": 1153, "s": 1071, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 1178, "s": 1153, "text": "\nConstraints:\n1<=N<=1000" }, { "code": null, "e": 1182, "s": 1180, "text": "0" }, { "code": null, "e": 1205, "s": 1182, "text": "ankushkhatri3 days ago" }, { "code": null, "e": 1681, "s": 1205, "text": "import math\n\ndef inorder(root):\n global arr\n if not root:\n return \n inorder(root.left)\n arr.append(root.data)\n inorder(root.right)\n \ndef findMedian(root):\n global arr\n arr = []\n inorder(root)\n #print(arr)\n\n m = int(len(arr)/2)\n n = len(arr)\n if n%2 == 0:\n ans = (arr[m]+arr[m-1])/2\n if math.floor(ans)==math.ceil(ans):\n return int(ans)\n else:\n return ans\n else:\n return arr[m]" }, { "code": null, "e": 1683, "s": 1681, "text": "0" }, { "code": null, "e": 1696, "s": 1683, "text": "ankushkhatri" }, { "code": null, "e": 1722, "s": 1696, "text": "This comment was deleted." }, { "code": null, "e": 1724, "s": 1722, "text": "0" }, { "code": null, "e": 1749, "s": 1724, "text": "uttarandas5012 weeks ago" }, { "code": null, "e": 2052, "s": 1749, "text": "void inorder(Node *root, vector<int> &v){\n if(!root){return;}\n inorder(root->left, v);\n v.push_back(root->data);\n inorder(root->right, v);\n}\n\nfloat findMedian(struct Node *root)\n{\n //Code here\n vector<int>v;\n inorder(root, v);\n return (v[v.size()/2] + v[(v.size()-1)/2])/2.00;\n}" }, { "code": null, "e": 2054, "s": 2052, "text": "0" }, { "code": null, "e": 2086, "s": 2054, "text": "neerajchatterjee23012 weeks ago" }, { "code": null, "e": 3033, "s": 2086, "text": "void inorder(struct Node* root, int &n){\n \n if(root == NULL) return;\n \n inorder(root->left, n);\n n++;\n inorder(root->right, n);\n \n}\n\nvoid calc(Node* root, int &k, int &ans){\n \n \n if(root == NULL){\n return;\n }\n \n calc(root->left, k, ans);\n k--;\n if(k == 0){\n \n k = INT_MAX;\n ans = root->data;\n return;\n \n }\n calc(root->right, k, ans);\n \n}\n\nfloat findMedian(struct Node *root)\n{\n int n = 0;\n inorder(root, n);\n \n if(n&1){\n int k = (n+1)/2;\n int fans;\n calc(root, k, fans);\n return fans;\n }\n else{\n int k = n/2;\n \n int first;\n calc(root, k, first);\n \n int k2 = n/2 + 1;\n \n int second;\n calc(root, k2, second);\n \n float ans = (first + second) / 2.0 ;\n return ans;\n }\n \n}\n" }, { "code": null, "e": 3035, "s": 3033, "text": "0" }, { "code": null, "e": 3062, "s": 3035, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 3430, "s": 3062, "text": "void inorder(struct Node* root,vector<int> &v){ if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v);}float findMedian(struct Node *root){ //Code here vector<int> v; inorder(root,v); int mid=v.size()/2; if(v.size()%2==0) return (v[mid]+v[mid-1])/(float)2; else return v[mid];}" }, { "code": null, "e": 3432, "s": 3430, "text": "0" }, { "code": null, "e": 3465, "s": 3432, "text": "himanshibaranwal051291 month ago" }, { "code": null, "e": 3514, "s": 3465, "text": "I am not sure why is this not getting submitted." }, { "code": null, "e": 4212, "s": 3516, "text": "public static List<Integer> nodeValues = new ArrayList<Integer>(); public static float findMedian(Node root) { if(root==null){ return 0; } inOrderTraversal(root); int size = nodeValues.size(); if(size%2==0){ float sumMidValues = nodeValues.get(size/2)+nodeValues.get((size/2)-1); float median = sumMidValues/2; return median; }else{ return nodeValues.get(size/2); } } static void inOrderTraversal(Node root){ if(root==null){ return; } inOrderTraversal(root.left); nodeValues.add(root.data); inOrderTraversal(root.right); }" }, { "code": null, "e": 4214, "s": 4212, "text": "0" }, { "code": null, "e": 4238, "s": 4214, "text": "harrypotter01 month ago" }, { "code": null, "e": 4405, "s": 4238, "text": "ans = []def solve(root, ans, count): if not root: return count[0]+=1 solve(root.left, ans,count ) ans.append(root.data) solve(root.right, ans, count)" }, { "code": null, "e": 4785, "s": 4405, "text": " def findMedian(root): ans = [] count = [0] solve(root, ans, count ) n = count[0] # print(ans) if n%2: ## odd ind = n//2+1 return ans[ind-1] else: ind = (n//2+(n//2)+1)//2 if (ans[n//2-1]+ans[n//2])/2 == int((ans[n//2-1]+ans[n//2])/2): return int((ans[n//2-1]+ans[n//2])/2) else: return (ans[n//2-1]+ans[n//2])/2 " }, { "code": null, "e": 4787, "s": 4785, "text": "0" }, { "code": null, "e": 4810, "s": 4787, "text": "cshubham4391 month ago" }, { "code": null, "e": 5348, "s": 4810, "text": "java Solution\nstatic void inorder(Node root,ArrayList<Integer> list){\n if(root!=null){\n inorder(root.left,list);\n list.add(root.data);\n inorder(root.right,list);\n }\n }\n public static float findMedian(Node root)\n {\n // code here.\n \n ArrayList<Integer> list = new ArrayList<>();\n inorder(root,list);\n int n = list.size();\n if(n%2==0){\n return (((float)list.get(n/2-1)+(float)list.get(n/2))/2);\n }\n else\n return list.get(n/2);" }, { "code": null, "e": 5351, "s": 5348, "text": "+3" }, { "code": null, "e": 5374, "s": 5351, "text": "bruhmantri2 months ago" }, { "code": null, "e": 5396, "s": 5374, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5461, "s": 5396, "text": "Space Complexity: O(1) (if recurive stack space not considered)" }, { "code": null, "e": 5473, "s": 5463, "text": "Approach:" }, { "code": null, "e": 5522, "s": 5473, "text": "First Calculate total numberof nodes in the tree" }, { "code": null, "e": 5586, "s": 5522, "text": "If the nodes are even, we need to consider 2 numbers for median" }, { "code": null, "e": 5633, "s": 5586, "text": "If the nodes are odd, only 1 number is needed." }, { "code": null, "e": 5681, "s": 5633, "text": "So we find middle element by countOfNodes/2 + 1" }, { "code": null, "e": 5746, "s": 5681, "text": "We also maintain a prev pointer whcih stores prev traversed node" }, { "code": null, "e": 5923, "s": 5746, "text": "When our node is at position middleELement, we check if it had even, if yes then we would take prev and root (prev + root)/2 as answer, else we would have just just root as ans" }, { "code": null, "e": 7136, "s": 5925, "text": "int findCountOfNodes(Node *root)\n{\n if(!root)\n {\n return 0;\n }\n int leftTree = findCountOfNodes(root->left);\n int rightTree = findCountOfNodes(root->right);\n \n return leftTree + rightTree + 1;\n}\n\nvoid solve(Node* root, int k, bool twoNums, float &ans, int &currentNode, Node* &prev)\n{\n if(!root)\n {\n return;\n }\n \n solve(root->left, k, twoNums, ans, currentNode, prev);\n if(currentNode == k)\n {\n if(twoNums)\n {\n ans = ((float)prev->data + (float)root->data)/2;\n }\n else\n {\n ans = root->data;\n }\n \n }\n prev = root;\n currentNode++;\n solve(root->right, k, twoNums, ans, currentNode, prev);\n}\n\nfloat findMedian(struct Node *root)\n{\n //Code here\n int countOfNodes = findCountOfNodes(root);\n int currentNode = 1;\n \n bool twoNums = true;\n int k = 0;\n \n if(countOfNodes%2 == 0)\n {\n twoNums = true;\n }\n else\n {\n twoNums = false;\n }\n k = (countOfNodes/2) + 1;\n \n float ans = 0;\n Node* prev = NULL;\n solve(root, k, twoNums, ans, currentNode, prev);\n \n return ans;\n}" }, { "code": null, "e": 7138, "s": 7136, "text": "0" }, { "code": null, "e": 7149, "s": 7138, "text": "yojobex113" }, { "code": null, "e": 7175, "s": 7149, "text": "This comment was deleted." }, { "code": null, "e": 7321, "s": 7175, "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": 7357, "s": 7321, "text": " Login to access your submissions. " }, { "code": null, "e": 7367, "s": 7357, "text": "\nProblem\n" }, { "code": null, "e": 7377, "s": 7367, "text": "\nContest\n" }, { "code": null, "e": 7440, "s": 7377, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7588, "s": 7440, "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": 7796, "s": 7588, "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": 7902, "s": 7796, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert JSON Array to normal Java Array?
The get method of the JSONArray class returns the element at a particular index. Using this method, you can get the elements of the JSONArray object and populate the array with them. import java.util.Arrays; import org.json.JSONArray; public class JsonToArray { public static void main(String args[]) throws Exception { String [] myArray = {"JavaFX", "HBase", "JOGL", "WebGL"}; JSONArray jsArray = new JSONArray(); for (int i = 0; i < myArray.length; i++) { jsArray.put(myArray[i]); } System.out.println(jsArray); String[] array = new String[myArray.length]; for (int i = 0; i < myArray.length; i++) { array[i] = (String)jsArray.get(i); } System.out.println("Contents of the array :: "+Arrays.toString(array)); } } ["JavaFX","HBase","JOGL","WebGL"] Contents of the array :: [JavaFX, HBase, JOGL, WebGL]
[ { "code": null, "e": 1245, "s": 1062, "text": "The get method of the JSONArray class returns the element at a particular index. Using this method, you can get the elements of the JSONArray object and populate the array with them." }, { "code": null, "e": 1849, "s": 1245, "text": "import java.util.Arrays;\nimport org.json.JSONArray;\n\npublic class JsonToArray {\n public static void main(String args[]) throws Exception {\n String [] myArray = {\"JavaFX\", \"HBase\", \"JOGL\", \"WebGL\"};\n JSONArray jsArray = new JSONArray();\n for (int i = 0; i < myArray.length; i++) {\n jsArray.put(myArray[i]);\n }\n System.out.println(jsArray);\n String[] array = new String[myArray.length];\n for (int i = 0; i < myArray.length; i++) {\n array[i] = (String)jsArray.get(i);\n }\n System.out.println(\"Contents of the array :: \"+Arrays.toString(array));\n }\n}" }, { "code": null, "e": 1937, "s": 1849, "text": "[\"JavaFX\",\"HBase\",\"JOGL\",\"WebGL\"]\nContents of the array :: [JavaFX, HBase, JOGL, WebGL]" } ]
C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined − #include <stdio.h> int main () { int var1; char var2[10]; printf("Address of var1 variable: %x\n", &var1 ); printf("Address of var2 variable: %x\n", &var2 ); return 0; } When the above code is compiled and executed, it produces the following result − Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations − #include <stdio.h> int main () { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("Address of var variable: %x\n", &var ); /* address stored in pointer variable */ printf("Address stored in ip variable: %x\n", ip ); /* access the value using the pointer */ printf("Value of *ip variable: %d\n", *ip ); return 0; } When the above code is compiled and executed, it produces the following result − Address of var variable: bffd8b3c Address stored in ip variable: bffd8b3c Value of *ip variable: 20 It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − #include <stdio.h> int main () { int *ptr = NULL; printf("The value of ptr is : %x\n", ptr ); return 0; } When the above code is compiled and executed, it produces the following result − The value of ptr is 0 In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer, you can use an 'if' statement as follows − if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */ Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer − There are four arithmetic operators that can be used in pointers: ++, --, +, - You can define arrays to hold a number of pointers. C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function. C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well. Print Add Notes Bookmark this page
[ { "code": null, "e": 2415, "s": 2084, "text": "Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps." }, { "code": null, "e": 2686, "s": 2415, "text": "As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined −" }, { "code": null, "e": 2878, "s": 2686, "text": "#include <stdio.h>\n\nint main () {\n\n int var1;\n char var2[10];\n\n printf(\"Address of var1 variable: %x\\n\", &var1 );\n printf(\"Address of var2 variable: %x\\n\", &var2 );\n\n return 0;\n}" }, { "code": null, "e": 2959, "s": 2878, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3030, "s": 2959, "text": "Address of var1 variable: bff5a400\nAddress of var2 variable: bff5a3f6\n" }, { "code": null, "e": 3308, "s": 3030, "text": "A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −" }, { "code": null, "e": 3325, "s": 3308, "text": "type *var-name;\n" }, { "code": null, "e": 3680, "s": 3325, "text": "Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations −" }, { "code": null, "e": 3849, "s": 3680, "text": "int *ip; /* pointer to an integer */\ndouble *dp; /* pointer to a double */\nfloat *fp; /* pointer to a float */\nchar *ch /* pointer to a character */\n" }, { "code": null, "e": 4156, "s": 3849, "text": "The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to." }, { "code": null, "e": 4602, "s": 4156, "text": "There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations −" }, { "code": null, "e": 5070, "s": 4602, "text": "#include <stdio.h>\n\nint main () {\n\n int var = 20; /* actual variable declaration */\n int *ip; /* pointer variable declaration */\n\n ip = &var; /* store address of var in pointer variable*/\n\n printf(\"Address of var variable: %x\\n\", &var );\n\n /* address stored in pointer variable */\n printf(\"Address stored in ip variable: %x\\n\", ip );\n\n /* access the value using the pointer */\n printf(\"Value of *ip variable: %d\\n\", *ip );\n\n return 0;\n}" }, { "code": null, "e": 5151, "s": 5070, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5252, "s": 5151, "text": "Address of var variable: bffd8b3c\nAddress stored in ip variable: bffd8b3c\nValue of *ip variable: 20\n" }, { "code": null, "e": 5491, "s": 5252, "text": "It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer." }, { "code": null, "e": 5615, "s": 5491, "text": "The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −" }, { "code": null, "e": 5737, "s": 5615, "text": "#include <stdio.h>\n\nint main () {\n\n int *ptr = NULL;\n\n printf(\"The value of ptr is : %x\\n\", ptr );\n \n return 0;\n}" }, { "code": null, "e": 5818, "s": 5737, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5841, "s": 5818, "text": "The value of ptr is 0\n" }, { "code": null, "e": 6231, "s": 5841, "text": "In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing." }, { "code": null, "e": 6303, "s": 6231, "text": "To check for a null pointer, you can use an 'if' statement as follows −" }, { "code": null, "e": 6388, "s": 6303, "text": "if(ptr) /* succeeds if p is not null */\nif(!ptr) /* succeeds if p is null */\n" }, { "code": null, "e": 6550, "s": 6388, "text": "Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer −" }, { "code": null, "e": 6629, "s": 6550, "text": "There are four arithmetic operators that can be used in pointers: ++, --, +, -" }, { "code": null, "e": 6681, "s": 6629, "text": "You can define arrays to hold a number of pointers." }, { "code": null, "e": 6734, "s": 6681, "text": "C allows you to have pointer on a pointer and so on." }, { "code": null, "e": 6870, "s": 6734, "text": "Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function." }, { "code": null, "e": 6992, "s": 6870, "text": "C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well." }, { "code": null, "e": 6999, "s": 6992, "text": " Print" }, { "code": null, "e": 7010, "s": 6999, "text": " Add Notes" } ]
How to find the sum of squared values of an R data frame column?
To find the sum of squared values of an R data frame column, we can simply square the column with ^ sign and take the sum using sum function. For example, if we have a data frame called df that contains a column say V then the sum of squared values of V can be found by using the command sum(df$V^2). Consider the below data frame − Live Demo ID<-1:20 x<-rpois(20,5) df1<-data.frame(ID,x) df1 ID x 1 1 3 2 2 9 3 3 7 4 4 4 5 5 6 6 6 4 7 7 7 8 8 4 9 9 8 10 10 5 11 11 6 12 12 7 13 13 7 14 14 7 15 15 5 16 16 4 17 17 4 18 18 5 19 19 4 20 20 5 Finding the sum of squared values in column x of df1 − sum(df1$x^2) [1] 667 Live Demo S.No<-LETTERS[1:20] y<-rnorm(20,5,1) df2<-data.frame(S.No,y) df2 S.No y 1 A 4.398238 2 B 5.543076 3 C 3.089420 4 D 7.313162 5 E 6.389394 6 F 5.718104 7 G 4.999203 8 H 5.835729 9 I 5.078716 10 J 3.507107 11 K 5.712762 12 L 2.778876 13 M 4.379454 14 N 5.487530 15 O 6.192156 16 P 5.065865 17 Q 4.984204 18 R 4.925256 19 S 4.522911 20 T 4.957369 Finding the sum of squared values in column y of df2 − sum(df2$y^2) [1] 531.5479
[ { "code": null, "e": 1363, "s": 1062, "text": "To find the sum of squared values of an R data frame column, we can simply square the column with ^ sign and take the sum using sum function. For example, if we have a data frame called df that contains a column say V then the sum of squared values of V can be found by using the command sum(df$V^2)." }, { "code": null, "e": 1395, "s": 1363, "text": "Consider the below data frame −" }, { "code": null, "e": 1406, "s": 1395, "text": " Live Demo" }, { "code": null, "e": 1456, "s": 1406, "text": "ID<-1:20\nx<-rpois(20,5)\ndf1<-data.frame(ID,x)\ndf1" }, { "code": null, "e": 1624, "s": 1456, "text": " ID x\n1 1 3\n2 2 9\n3 3 7\n4 4 4\n5 5 6\n6 6 4\n7 7 7\n8 8 4\n9 9 8\n10 10 5\n11 11 6\n12 12 7\n13 13 7\n14 14 7\n15 15 5\n16 16 4\n17 17 4\n18 18 5\n19 19 4\n20 20 5" }, { "code": null, "e": 1679, "s": 1624, "text": "Finding the sum of squared values in column x of df1 −" }, { "code": null, "e": 1692, "s": 1679, "text": "sum(df1$x^2)" }, { "code": null, "e": 1700, "s": 1692, "text": "[1] 667" }, { "code": null, "e": 1711, "s": 1700, "text": " Live Demo" }, { "code": null, "e": 1776, "s": 1711, "text": "S.No<-LETTERS[1:20]\ny<-rnorm(20,5,1)\ndf2<-data.frame(S.No,y)\ndf2" }, { "code": null, "e": 2126, "s": 1776, "text": " S.No y\n1 A 4.398238\n2 B 5.543076\n3 C 3.089420\n4 D 7.313162\n5 E 6.389394\n6 F 5.718104\n7 G 4.999203\n8 H 5.835729\n9 I 5.078716\n10 J 3.507107\n11 K 5.712762\n12 L 2.778876\n13 M 4.379454\n14 N 5.487530\n15 O 6.192156\n16 P 5.065865\n17 Q 4.984204\n18 R 4.925256\n19 S 4.522911\n20 T 4.957369" }, { "code": null, "e": 2181, "s": 2126, "text": "Finding the sum of squared values in column y of df2 −" }, { "code": null, "e": 2194, "s": 2181, "text": "sum(df2$y^2)" }, { "code": null, "e": 2207, "s": 2194, "text": "[1] 531.5479" } ]
SymPy - Function class
Sympy package has Function class, which is defined in sympy.core.function module. It is a base class for all applied mathematical functions, as also a constructor for undefined function classes. Following categories of functions are inherited from Function class − Functions for complex number Trigonometric functions Functions for integer number Combinatorial functions Other miscellaneous functions This set of functions is defined in sympy.functions.elementary.complexes module. re This function returns real part of an expression − >>> from sympy import * >>> re(5+3*I) The output for the above code snippet is given below − 5 >>> re(I) The output for the above code snippet is − 0 Im This function returns imaginary part of an expression − >>> im(5+3*I) The output for the above code snippet is given below − 3 >>> im(I) The output for the above code snippet is given below − 1 sign This function returns the complex sign of an expression. For real expression, the sign will be − 1 if expression is positive 0 if expression is equal to zero -1 if expression is negative If expression is imaginary the sign returned is − I if im(expression) is positive -I if im(expression) is negative >>> sign(1.55), sign(-1), sign(S.Zero) The output for the above code snippet is given below − (1, -1, 0) >>> sign (-3*I), sign(I*2) The output for the above code snippet is given below − (-I, I) Abs This function return absolute value of a complex number. It is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. This function is an extension of the built-in function abs() to accept symbolic values. >>> Abs(2+3*I) The output for the above code snippet is given below − 13 conjugate This function returns conjugate of a complex number. To find the complex conjugate we change the sign of the imaginary part. >>> conjugate(4+7*I) You get the following output after executing the above code snippet − 4 - 7i SymPy has defintions for all trigonometric ratios - sin cos, tan etc as well as well as its inverse counterparts such as asin, acos, atan etc. These functions compute respective value for given angle expressed in radians. >>> sin(pi/2), cos(pi/4), tan(pi/6) The output for the above code snippet is given below − (1, sqrt(2)/2, sqrt(3)/3) >>> asin(1), acos(sqrt(2)/2), atan(sqrt(3)/3) The output for the above code snippet is given below − (pi/2, pi/4, pi/6) This is a set of functions to perform various operations on integer number. ceiling This is a univariate function which returns the smallest integer value not less than its argument. In case of complex numbers, ceiling of the real and imaginary parts separately. >>> ceiling(pi), ceiling(Rational(20,3)), ceiling(2.6+3.3*I) The output for the above code snippet is given below − (4, 7, 3 + 4*I) floor This function returns the largest integer value not greater than its argument. In case of complex numbers, this function too takes the floor of the real and imaginary parts separately. >>> floor(pi), floor(Rational(100,6)), floor(6.3-5.9*I) The output for the above code snippet is given below − (3, 16, 6 - 6*I) frac This function represents the fractional part of x. >>> frac(3.99), frac(Rational(10,3)), frac(10) The output for the above code snippet is given below − (0.990000000000000, 1/3, 0) Combinatorics is a field of mathematics concerned with problems of selection, arrangement, and operation within a finite or discrete system. factorial The factorial is very important in combinatorics where it gives the number of ways in which n objects can be permuted. It is symbolically represented as x! This function is implementation of factorial function over nonnegative integers, factorial of a negative integer is complex infinity. >>> x=Symbol('x') >>> factorial(x) The output for the above code snippet is given below − x! >>> factorial(5) The output for the above code snippet is given below − 120 >>> factorial(-1) The output for the above code snippet is given below − ∞∽ This function the number of ways we can choose k elements from a set of n elements. >>> x,y=symbols('x y') >>> binomial(x,y) The output for the above code snippet is given below − (xy) >>> binomial(4,2) The output for the above code snippet is given below − 6 Rows of Pascal's triangle can be generated with the binomial function. >>> for i in range(5): print ([binomial(i,j) for j in range(i+1)]) You get the following output after executing the above code snippet − [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] fibonacci The Fibonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1 and the two-term recurrence relation Fn=Fn−1+Fn−2. >>> [fibonacci(x) for x in range(10)] The following output is obtained after executing the above code snippet − [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] tribonacci The Tribonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1, F2=1 and the three-term recurrence relation Fn=Fn-1+Fn-2+Fn-3. >>> tribonacci(5, Symbol('x')) The above code snippet gives an output equivalent to the below expression − x8+3x5+3x2 >>> [tribonacci(x) for x in range(10)] The following output is obtained after executing the above code snippet − [0, 1, 1, 2, 4, 7, 13, 24, 44, 81] Following is a list of some frequently used functions − Min − Returns minimum value of the list. It is named Min to avoid conflicts with the built-in function min. Max − Returns maximum value of the list. It is named Max to avoid conflicts with the built-in function max. root − Returns nth root of x. sqrt − Returns the principal square root of x. cbrt − This function computes the principal cube root of x, (shortcut for x++Rational(1,3)). The following are the examples of the above miscellaneous functions and their respective outputs − >>> Min(pi,E) e >>> Max(5, Rational(11,2)) 112 >>> root(7,Rational(1,2)) 49 >>> sqrt(2) 2 >>> cbrt(1000) 10 Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 2019, "text": "Sympy package has Function class, which is defined in sympy.core.function module. It is a base class for all applied mathematical functions, as also a constructor for undefined function classes." }, { "code": null, "e": 2284, "s": 2214, "text": "Following categories of functions are inherited from Function class −" }, { "code": null, "e": 2313, "s": 2284, "text": "Functions for complex number" }, { "code": null, "e": 2337, "s": 2313, "text": "Trigonometric functions" }, { "code": null, "e": 2366, "s": 2337, "text": "Functions for integer number" }, { "code": null, "e": 2390, "s": 2366, "text": "Combinatorial functions" }, { "code": null, "e": 2420, "s": 2390, "text": "Other miscellaneous functions" }, { "code": null, "e": 2501, "s": 2420, "text": "This set of functions is defined in sympy.functions.elementary.complexes module." }, { "code": null, "e": 2504, "s": 2501, "text": "re" }, { "code": null, "e": 2555, "s": 2504, "text": "This function returns real part of an expression −" }, { "code": null, "e": 2595, "s": 2555, "text": ">>> from sympy import * \n>>> re(5+3*I)\n" }, { "code": null, "e": 2650, "s": 2595, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 2652, "s": 2650, "text": "5" }, { "code": null, "e": 2663, "s": 2652, "text": ">>> re(I)\n" }, { "code": null, "e": 2706, "s": 2663, "text": "The output for the above code snippet is −" }, { "code": null, "e": 2708, "s": 2706, "text": "0" }, { "code": null, "e": 2711, "s": 2708, "text": "Im" }, { "code": null, "e": 2767, "s": 2711, "text": "This function returns imaginary part of an expression −" }, { "code": null, "e": 2782, "s": 2767, "text": ">>> im(5+3*I)\n" }, { "code": null, "e": 2837, "s": 2782, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 2839, "s": 2837, "text": "3" }, { "code": null, "e": 2850, "s": 2839, "text": ">>> im(I)\n" }, { "code": null, "e": 2905, "s": 2850, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 2907, "s": 2905, "text": "1" }, { "code": null, "e": 2912, "s": 2907, "text": "sign" }, { "code": null, "e": 2969, "s": 2912, "text": "This function returns the complex sign of an expression." }, { "code": null, "e": 3009, "s": 2969, "text": "For real expression, the sign will be −" }, { "code": null, "e": 3037, "s": 3009, "text": "1 if expression is positive" }, { "code": null, "e": 3070, "s": 3037, "text": "0 if expression is equal to zero" }, { "code": null, "e": 3099, "s": 3070, "text": "-1 if expression is negative" }, { "code": null, "e": 3149, "s": 3099, "text": "If expression is imaginary the sign returned is −" }, { "code": null, "e": 3181, "s": 3149, "text": "I if im(expression) is positive" }, { "code": null, "e": 3214, "s": 3181, "text": "-I if im(expression) is negative" }, { "code": null, "e": 3254, "s": 3214, "text": ">>> sign(1.55), sign(-1), sign(S.Zero)\n" }, { "code": null, "e": 3309, "s": 3254, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 3320, "s": 3309, "text": "(1, -1, 0)" }, { "code": null, "e": 3348, "s": 3320, "text": ">>> sign (-3*I), sign(I*2)\n" }, { "code": null, "e": 3403, "s": 3348, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 3411, "s": 3403, "text": "(-I, I)" }, { "code": null, "e": 3415, "s": 3411, "text": "Abs" }, { "code": null, "e": 3657, "s": 3415, "text": "This function return absolute value of a complex number. It is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. This function is an extension of the built-in function abs() to accept symbolic values." }, { "code": null, "e": 3673, "s": 3657, "text": ">>> Abs(2+3*I)\n" }, { "code": null, "e": 3728, "s": 3673, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 3731, "s": 3728, "text": "13" }, { "code": null, "e": 3741, "s": 3731, "text": "conjugate" }, { "code": null, "e": 3866, "s": 3741, "text": "This function returns conjugate of a complex number. To find the complex conjugate we change the sign of the imaginary part." }, { "code": null, "e": 3888, "s": 3866, "text": ">>> conjugate(4+7*I)\n" }, { "code": null, "e": 3958, "s": 3888, "text": "You get the following output after executing the above code snippet −" }, { "code": null, "e": 3965, "s": 3958, "text": "4 - 7i" }, { "code": null, "e": 4187, "s": 3965, "text": "SymPy has defintions for all trigonometric ratios - sin cos, tan etc as well as well as its inverse counterparts such as asin, acos, atan etc. These functions compute respective value for given angle expressed in radians." }, { "code": null, "e": 4224, "s": 4187, "text": ">>> sin(pi/2), cos(pi/4), tan(pi/6)\n" }, { "code": null, "e": 4279, "s": 4224, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 4305, "s": 4279, "text": "(1, sqrt(2)/2, sqrt(3)/3)" }, { "code": null, "e": 4352, "s": 4305, "text": ">>> asin(1), acos(sqrt(2)/2), atan(sqrt(3)/3)\n" }, { "code": null, "e": 4407, "s": 4352, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 4426, "s": 4407, "text": "(pi/2, pi/4, pi/6)" }, { "code": null, "e": 4502, "s": 4426, "text": "This is a set of functions to perform various operations on integer number." }, { "code": null, "e": 4510, "s": 4502, "text": "ceiling" }, { "code": null, "e": 4689, "s": 4510, "text": "This is a univariate function which returns the smallest integer value not less than its argument. In case of complex numbers, ceiling of the real and imaginary parts separately." }, { "code": null, "e": 4751, "s": 4689, "text": ">>> ceiling(pi), ceiling(Rational(20,3)), ceiling(2.6+3.3*I)\n" }, { "code": null, "e": 4806, "s": 4751, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 4822, "s": 4806, "text": "(4, 7, 3 + 4*I)" }, { "code": null, "e": 4828, "s": 4822, "text": "floor" }, { "code": null, "e": 5013, "s": 4828, "text": "This function returns the largest integer value not greater than its argument. In case of complex numbers, this function too takes the floor of the real and imaginary parts separately." }, { "code": null, "e": 5070, "s": 5013, "text": ">>> floor(pi), floor(Rational(100,6)), floor(6.3-5.9*I)\n" }, { "code": null, "e": 5125, "s": 5070, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 5142, "s": 5125, "text": "(3, 16, 6 - 6*I)" }, { "code": null, "e": 5147, "s": 5142, "text": "frac" }, { "code": null, "e": 5198, "s": 5147, "text": "This function represents the fractional part of x." }, { "code": null, "e": 5246, "s": 5198, "text": ">>> frac(3.99), frac(Rational(10,3)), frac(10)\n" }, { "code": null, "e": 5301, "s": 5246, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 5329, "s": 5301, "text": "(0.990000000000000, 1/3, 0)" }, { "code": null, "e": 5470, "s": 5329, "text": "Combinatorics is a field of mathematics concerned with problems of selection, arrangement, and operation within a finite or discrete system." }, { "code": null, "e": 5480, "s": 5470, "text": "factorial" }, { "code": null, "e": 5770, "s": 5480, "text": "The factorial is very important in combinatorics where it gives the number of ways in which n objects can be permuted. It is symbolically represented as x! This function is implementation of factorial function over nonnegative integers, factorial of a negative integer is complex infinity." }, { "code": null, "e": 5807, "s": 5770, "text": ">>> x=Symbol('x') \n>>> factorial(x)\n" }, { "code": null, "e": 5862, "s": 5807, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 5865, "s": 5862, "text": "x!" }, { "code": null, "e": 5883, "s": 5865, "text": ">>> factorial(5)\n" }, { "code": null, "e": 5938, "s": 5883, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 5942, "s": 5938, "text": "120" }, { "code": null, "e": 5961, "s": 5942, "text": ">>> factorial(-1)\n" }, { "code": null, "e": 6016, "s": 5961, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 6019, "s": 6016, "text": "∞∽" }, { "code": null, "e": 6103, "s": 6019, "text": "This function the number of ways we can choose k elements from a set of n elements." }, { "code": null, "e": 6146, "s": 6103, "text": ">>> x,y=symbols('x y') \n>>> binomial(x,y)\n" }, { "code": null, "e": 6201, "s": 6146, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 6206, "s": 6201, "text": "(xy)" }, { "code": null, "e": 6225, "s": 6206, "text": ">>> binomial(4,2)\n" }, { "code": null, "e": 6280, "s": 6225, "text": "The output for the above code snippet is given below −" }, { "code": null, "e": 6282, "s": 6280, "text": "6" }, { "code": null, "e": 6353, "s": 6282, "text": "Rows of Pascal's triangle can be generated with the binomial function." }, { "code": null, "e": 6421, "s": 6353, "text": ">>> for i in range(5): print ([binomial(i,j) for j in range(i+1)])\n" }, { "code": null, "e": 6491, "s": 6421, "text": "You get the following output after executing the above code snippet −" }, { "code": null, "e": 6495, "s": 6491, "text": "[1]" }, { "code": null, "e": 6502, "s": 6495, "text": "[1, 1]" }, { "code": null, "e": 6512, "s": 6502, "text": "[1, 2, 1]" }, { "code": null, "e": 6525, "s": 6512, "text": "[1, 3, 3, 1]" }, { "code": null, "e": 6541, "s": 6525, "text": "[1, 4, 6, 4, 1]" }, { "code": null, "e": 6551, "s": 6541, "text": "fibonacci" }, { "code": null, "e": 6689, "s": 6551, "text": "The Fibonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1 and the two-term recurrence relation Fn=Fn−1+Fn−2." }, { "code": null, "e": 6728, "s": 6689, "text": ">>> [fibonacci(x) for x in range(10)]\n" }, { "code": null, "e": 6802, "s": 6728, "text": "The following output is obtained after executing the above code snippet −" }, { "code": null, "e": 6836, "s": 6802, "text": "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" }, { "code": null, "e": 6847, "s": 6836, "text": "tribonacci" }, { "code": null, "e": 6999, "s": 6847, "text": "The Tribonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1, F2=1 and the three-term recurrence relation Fn=Fn-1+Fn-2+Fn-3." }, { "code": null, "e": 7031, "s": 6999, "text": ">>> tribonacci(5, Symbol('x'))\n" }, { "code": null, "e": 7107, "s": 7031, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 7118, "s": 7107, "text": "x8+3x5+3x2" }, { "code": null, "e": 7158, "s": 7118, "text": ">>> [tribonacci(x) for x in range(10)]\n" }, { "code": null, "e": 7232, "s": 7158, "text": "The following output is obtained after executing the above code snippet −" }, { "code": null, "e": 7267, "s": 7232, "text": "[0, 1, 1, 2, 4, 7, 13, 24, 44, 81]" }, { "code": null, "e": 7323, "s": 7267, "text": "Following is a list of some frequently used functions −" }, { "code": null, "e": 7431, "s": 7323, "text": "Min − Returns minimum value of the list. It is named Min to avoid conflicts with the built-in function min." }, { "code": null, "e": 7539, "s": 7431, "text": "Max − Returns maximum value of the list. It is named Max to avoid conflicts with the built-in function max." }, { "code": null, "e": 7569, "s": 7539, "text": "root − Returns nth root of x." }, { "code": null, "e": 7616, "s": 7569, "text": "sqrt − Returns the principal square root of x." }, { "code": null, "e": 7709, "s": 7616, "text": "cbrt − This function computes the principal cube root of x, (shortcut for x++Rational(1,3))." }, { "code": null, "e": 7808, "s": 7709, "text": "The following are the examples of the above miscellaneous functions and their respective outputs −" }, { "code": null, "e": 7823, "s": 7808, "text": ">>> Min(pi,E)\n" }, { "code": null, "e": 7825, "s": 7823, "text": "e" }, { "code": null, "e": 7853, "s": 7825, "text": ">>> Max(5, Rational(11,2))\n" }, { "code": null, "e": 7857, "s": 7853, "text": "112" }, { "code": null, "e": 7884, "s": 7857, "text": ">>> root(7,Rational(1,2))\n" }, { "code": null, "e": 7887, "s": 7884, "text": "49" }, { "code": null, "e": 7900, "s": 7887, "text": ">>> sqrt(2)\n" }, { "code": null, "e": 7902, "s": 7900, "text": "2" }, { "code": null, "e": 7918, "s": 7902, "text": ">>> cbrt(1000)\n" }, { "code": null, "e": 7921, "s": 7918, "text": "10" }, { "code": null, "e": 7928, "s": 7921, "text": " Print" }, { "code": null, "e": 7939, "s": 7928, "text": " Add Notes" } ]
How to Optimize a Deep Learning Model | by Zachary Warnes | Towards Data Science
Hyperparameter optimization is a critical part of any machine learning pipeline. Just selecting a model is not enough to achieve exceptional performance. You also need to tune your model to better perform on the problem. This post will discuss hyperparameter tuning for deep learning architectures. There are code chunks to recreate the example shown. Feel free to bookmark this post to copy code to optimize your deep learning models quickly. If you are developing different deep learning models, replace code in the function ‘create_model’ with your specific model and update the relevant hyperparameters for each function. The rest of the optimization code is model-independent. When developing models using scikit-learn, hyperparameter tuning is a relatively straightforward procedure. Both random and grid searches have their advantages and disadvantages. However, a third option known as Bayesian optimization provides a practical, balanced approach to hyperparameter optimization that can lead to more robust models. Optimization in machine learning generally follows the same format. First, define a function that represents a loss. Then, by minimizing this loss, the model is forced to produce increasingly improved performance. Loss functions are chosen for two main reasons. The first is that they represent the problem well. The second aspect of the standard loss functions is that the gradient is well defined. By having a well-defined gradient, many different optimization techniques become available. The most common of which is gradient descent which relies on the gradient of the function. But what happens when the function does not have a gradient? This scenario is precisely the case when you have a black-box model. A black-box model takes in an input and has an output. But what happens within the box is unknown. This property makes the model a black-box model. The problem of optimization is more difficult when the model is a black-box. Unfortunately, black boxes are the standard when building deep learning models, so standard optimization methods don’t perform well. Briefly consider why optimization methods like gradient descent would not work to optimize hyperparameters. If you wanted to optimize for a hyperparameter, you would need to determine the derivative with respect to that hyperparameter. For example, imagine taking the derivative of the number of estimators for a random forest. It’s impossible. However, black-box optimization does not care about determining the derivative of a function. Instead, the goal is to select a function based on multiple samples from the hyperparameter space. Then once this function closely represents hyperparameter space, you can optimize this function. The results of this optimization produce an optimal hyperparameter configuration that should perform well on the original black-box function. In a previous post, I discussed different hyperparameter tuning methods and introduced Bayesian optimization. For the details regarding the other tuning methods available, their pitfalls, and benefits, refer to my previous post here: towardsdatascience.com Bayesian optimization is the process of sampling from the possible hyperparameter spaces, modeling a function based on these samples, and then optimizing that model Bayesian optimization is the process of repeatedly sampling from the possible hyperparameter spaces, modeling a function based on these samples, and then optimizing that model In contrast to gradient descent which requires optimization using the derivative, Bayesian optimization creates a representative function generated by sampling from the hyperparameter space multiple times. This process of multiple sampling and generating an approximation of the space is why the method is Bayesian. Finally, the representative function is adjusted using prior information from the repeated sampling. The process requires two things, a method to sample from the hyperparameter space and a method to optimize the function produced. The method for sampling from a black-box will require sampling the hyperparameter space, creating a representative function based on multiple samples, then optimizing that function. Thus, the input becomes the hyperparameters, and the output is the performance of the model. A good approximation of this function is generated with a sufficient number of samples from the hyperparameter space. From this, the model is then optimized for an optimal configuration of hyperparameters. Deep learning models require a lot of tuning. When you manually tune your deep learning models, it is incredibly time-consuming. The number of hyperparameters used to define deep learning models is numerous. By repeatedly changing the parameters in a network manually, you are effectively performing a hands-on grid search. Instead of manually checking different network configurations, you can define the distributions of each hyperparameter that you want to analyze. Then with many samples, you can find a more optimal model, and you can clearly understand how each hyperparameter affects your model overall. This method of architecture tuning requires at least two functions. First, a process to evaluate the function and store the best result and the function to generate the deep learning model based on a set of hyperparameters. For this post, I will focus on optimizing the architecture of a neural network with dropout layers. I’ll be using Keras within TensorFlow as it is straightforward to generate different models quickly. A quick pause here to say thank you to those responsible for Keras and TensorFlow. If you’ve ever created a neural network, CNN, or LSTM from scratch, you know it is incredibly tedious and complicated. So I’m am extremely grateful that these libraries exist and that they are open to the public. The model is generated using the hyperparameters sampled from each distribution defined. These values control the number of layers, the number of nodes across each of these layers, the dropout layer probability, the learning rate, optimizer, the learning decay for the optimization method, and the activation function. This model is set up for classification. It is possible to apply these functions to different networks, such as a convolutional neural network. However, due to the nature of convolutional layers, each subsequent layer depends on the previous layer. This aspect increases the complexity of the model creation function. CNN optimization will likely be the focus of a future post. However, a simple workaround for CNNs is fixing the number of layers and optimizing the remaining parameters. The first step is to import some packages and initialize some parameters. Here I also initialize the distributions of different hyperparameters that I was to test. You’ll notice that I don’t set up all of my hyperparameters as distributions, so I won’t be testing every combination possible. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow.keras import backend as Kfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Dropoutfrom tensorflow.keras.callbacks import TensorBoardfrom tensorflow.keras.optimizers import Adam, SGDfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.callbacks import EarlyStoppingfrom tensorflow.keras.optimizers.schedules import ExponentialDecayimport skoptfrom skopt.space import Real, Categorical, Integerfrom skopt import gp_minimize, forest_minimizefrom skopt.plots import plot_convergence, plot_objective, plot_evaluationsfrom skopt.utils import use_named_argsprint( "Tensorflow version: ", tf.__version__)data = load_breast_cancer()y = data.target.astype(float)X = data.dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=2)X_validation, X_test, y_validation, y_test = train_test_split(X_test, y_test, test_size=0.4, random_state=2) Next, distributions for the hyperparameters are defined. These distributions can be real continuous values, integer values, or categorical values. Moreover, the type of distribution is added for continuous distributions. For example, a log-uniform distribution may work better for a learning rate decay when most of the values that you want to test fall in a subset of the distribution. The hyperparameters also require default values. These defaults are used in the first model built in the optimization process. dim_optimization = Categorical(categories=['adam', 'SGD'],name='optimization')dim_learning_rate = Real(low=1e-3, high=1e-1, prior='log-uniform',name='learning_rate')dim_learning_decay = Real(low=0.9, high=0.999, prior='uniform',name='learning_decay')dim_num_layers = Integer(low=1, high=5, name='num_layers')dim_num_dense_nodes = Integer(low=5, high=50, name='num_dense_nodes')dim_dropout_prob = Real(low=0.5, high=0.99, prior='uniform',name='dropout_prob')dim_activation = Categorical(categories=['sigmoid', 'softmax', 'relu'],name='activation')dimensions = [ dim_optimization, dim_learning_rate, dim_learning_decay, dim_num_layers, dim_num_dense_nodes, dim_dropout_prob, dim_activation]NUM_LAYERS = 1BATCH_SIZE = 128LEARNING_RATE = 0.001DECAY_STEPS = 1000DENSE_UNITS = 20DROPOUT_PROB = 0.8ACTIVATION_FUNC = 'relu'LOSS_FUNC = 'binary_crossentropy'METRIC = 'accuracy'LEARNING_DECAY = 0.9OTIMIZATION_FUNC = 'adam'ACQ_FUNC = 'EI' # Expected Improvementbest_score = 0EPOCHS = 50BATCH_SIZE = 256N_CALLS = 1000default_parameters = [OTIMIZATION_FUNC, LEARNING_RATE, LEARNING_DECAY, NUM_LAYERS, DENSE_UNITS, DROPOUT_PROB, ACTIVATION_FUNC] If you want to change the underlying model, this function will need to be changed. Depending on the hyperparameter input, some of the model parameters may be conditioned on other parameters. For example, in a CNN the filter dimensions affect the output shape into the next layer. Currently skopt does not support conditional features. For this example, I control the number of units in each of the dense layers and then add a dropout layer. This structure is a fairly simple network, but this code is easily modified to include different models of your choice. The next code chunk generates a deep neural net based on the hyperparameters from the sample. def create_model(optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation): model = Sequential() name = 'layer_{0}_dense_units'.format(0) model.add( Dense( num_dense_nodes, input_dim=X_train.shape[1], activation=activation, name=name)) for i in range(num_layers-1): name = 'layer_{0}_dense_units'.format(i+1) model.add( Dense( num_dense_nodes, activation=activation, name=name)) model.add( Dropout(dropout_prob)) model.add( Dense(1, activation=activation)) lr_schedule = ExponentialDecay( initial_learning_rate=learning_rate, decay_steps=DECAY_STEPS, decay_rate=learning_decay) if optimization == 'adam': optimizer = Adam(learning_rate=lr_schedule) if optimization == 'SGD': optimizer = SGD(learning_rate=lr_schedule) model.compile( optimizer=optimizer, loss=LOSS_FUNC, metrics=[METRIC]) return model Fitness is the function that skopt will optimize with ‘gp_minimize’, which minimizes the Gaussian process generated to model the hyperparameter space. This function is minimization by construction. Hence the score that is being maximized becomes a minimization of the negative scores. @use_named_args(dimensions=dimensions)def fitness(optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation): # Create the neural network model = create_model( optimization=optimization, learning_rate=learning_rate, learning_decay=learning_decay, num_layers=num_layers, num_dense_nodes=num_dense_nodes, dropout_prob=dropout_prob, activation=activation) # Save log for tensorboard callback_log = TensorBoard( log_dir ="./21_logs/opt_{0}_lr_{1:.0e}_lr_decay_{2:.0e}_layers_{3}_nodes_{4}_dropout_{5}_activation_{5}/".format( optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation), histogram_freq=0, write_graph=True, write_grads=False, write_images=False) # Train the model. history = model.fit( x= X_train,y= y_train, epochs=EPOCHS,batch_size=BATCH_SIZE, validation_data=(X_validation, y_validation), callbacks=[callback_log],verbose=0) # Get the final model performance. col = [x for x in list(history.history.keys()) if 'val_'+METRIC in x] score = history.history[col[0]][-1] print("--> Validation {0}: {1:.2%}".format(METRIC, score)) global best_score # Track scores and save best model if score > best_score: model.save('Optimal-NN') best_score = score # Clear model to save space del model K.clear_session() # Skopt minimizes black-box functions, return the negative return -score The skopt function ‘gp_minimize’ runs Bayesian optimization on the black-box model to determine the optimal hyperparameter configuration. The ‘acq_func’, which is used to optimized the Gaussian process, is one of several options for optimization. search_result = gp_minimize(func=fitness, dimensions=dimensions, acq_func=ACQ_FUNC, n_calls=N_CALLS, x0=default_parameters) Once the search is completed the best model found is saved locally. This model can be loaded in and used from this point and trained further if necessary. The search results contain the hyperparameters at each evaluation as well as the performance of each model tested. To see how the search improved the model performance over time, run the following code chunk: plot_convergence(search_result) However, just seeing the improvement over the different models tested is not the largest benefit of Bayesian optimization. The behavior of each of the hyperparameters is analyzed independently, and how they interact with other hyperparameters. _ = plot_objective(result=search_result) You can see from the image above that there still is some uncertainty around some of the parameters. The results from changing the number of dense nodes vary a fair amount. However, the learning rate appears to be modeled effectively. You can see the optimization has selected a learning rate around 10e-2. Similarly, sigmoid activation and adam optimization appear to perform the best across all models generated. Bayesian optimization is useful when trying to fine-tune and optimize a computationally expensive model. In addition, Bayesian optimization requires few samples and rapidly closes in on a more optimal hyperparameter configuration, so it is ideal for deep learning models. For deep learning models such as neural networks and network variants, fine-tuning architecture is crucial. However, don’t waste your time manually tuning your model. Instead, use Bayesian optimization to determine what the role of each hyperparameter is for your model. If you’re interested in reading articles about novel data science tools and understanding machine learning algorithms, consider following me on Medium. If you’re interested in my writing and want to support me directly, please subscribe through the following link. This link ensures that I will receive a portion of your membership fees.
[ { "code": null, "e": 393, "s": 172, "text": "Hyperparameter optimization is a critical part of any machine learning pipeline. Just selecting a model is not enough to achieve exceptional performance. You also need to tune your model to better perform on the problem." }, { "code": null, "e": 524, "s": 393, "text": "This post will discuss hyperparameter tuning for deep learning architectures. There are code chunks to recreate the example shown." }, { "code": null, "e": 616, "s": 524, "text": "Feel free to bookmark this post to copy code to optimize your deep learning models quickly." }, { "code": null, "e": 854, "s": 616, "text": "If you are developing different deep learning models, replace code in the function ‘create_model’ with your specific model and update the relevant hyperparameters for each function. The rest of the optimization code is model-independent." }, { "code": null, "e": 1196, "s": 854, "text": "When developing models using scikit-learn, hyperparameter tuning is a relatively straightforward procedure. Both random and grid searches have their advantages and disadvantages. However, a third option known as Bayesian optimization provides a practical, balanced approach to hyperparameter optimization that can lead to more robust models." }, { "code": null, "e": 1509, "s": 1196, "text": "Optimization in machine learning generally follows the same format. First, define a function that represents a loss. Then, by minimizing this loss, the model is forced to produce increasingly improved performance. Loss functions are chosen for two main reasons. The first is that they represent the problem well." }, { "code": null, "e": 1779, "s": 1509, "text": "The second aspect of the standard loss functions is that the gradient is well defined. By having a well-defined gradient, many different optimization techniques become available. The most common of which is gradient descent which relies on the gradient of the function." }, { "code": null, "e": 1909, "s": 1779, "text": "But what happens when the function does not have a gradient? This scenario is precisely the case when you have a black-box model." }, { "code": null, "e": 2057, "s": 1909, "text": "A black-box model takes in an input and has an output. But what happens within the box is unknown. This property makes the model a black-box model." }, { "code": null, "e": 2134, "s": 2057, "text": "The problem of optimization is more difficult when the model is a black-box." }, { "code": null, "e": 2267, "s": 2134, "text": "Unfortunately, black boxes are the standard when building deep learning models, so standard optimization methods don’t perform well." }, { "code": null, "e": 2612, "s": 2267, "text": "Briefly consider why optimization methods like gradient descent would not work to optimize hyperparameters. If you wanted to optimize for a hyperparameter, you would need to determine the derivative with respect to that hyperparameter. For example, imagine taking the derivative of the number of estimators for a random forest. It’s impossible." }, { "code": null, "e": 3044, "s": 2612, "text": "However, black-box optimization does not care about determining the derivative of a function. Instead, the goal is to select a function based on multiple samples from the hyperparameter space. Then once this function closely represents hyperparameter space, you can optimize this function. The results of this optimization produce an optimal hyperparameter configuration that should perform well on the original black-box function." }, { "code": null, "e": 3278, "s": 3044, "text": "In a previous post, I discussed different hyperparameter tuning methods and introduced Bayesian optimization. For the details regarding the other tuning methods available, their pitfalls, and benefits, refer to my previous post here:" }, { "code": null, "e": 3301, "s": 3278, "text": "towardsdatascience.com" }, { "code": null, "e": 3466, "s": 3301, "text": "Bayesian optimization is the process of sampling from the possible hyperparameter spaces, modeling a function based on these samples, and then optimizing that model" }, { "code": null, "e": 3642, "s": 3466, "text": "Bayesian optimization is the process of repeatedly sampling from the possible hyperparameter spaces, modeling a function based on these samples, and then optimizing that model" }, { "code": null, "e": 3848, "s": 3642, "text": "In contrast to gradient descent which requires optimization using the derivative, Bayesian optimization creates a representative function generated by sampling from the hyperparameter space multiple times." }, { "code": null, "e": 4059, "s": 3848, "text": "This process of multiple sampling and generating an approximation of the space is why the method is Bayesian. Finally, the representative function is adjusted using prior information from the repeated sampling." }, { "code": null, "e": 4189, "s": 4059, "text": "The process requires two things, a method to sample from the hyperparameter space and a method to optimize the function produced." }, { "code": null, "e": 4464, "s": 4189, "text": "The method for sampling from a black-box will require sampling the hyperparameter space, creating a representative function based on multiple samples, then optimizing that function. Thus, the input becomes the hyperparameters, and the output is the performance of the model." }, { "code": null, "e": 4670, "s": 4464, "text": "A good approximation of this function is generated with a sufficient number of samples from the hyperparameter space. From this, the model is then optimized for an optimal configuration of hyperparameters." }, { "code": null, "e": 4799, "s": 4670, "text": "Deep learning models require a lot of tuning. When you manually tune your deep learning models, it is incredibly time-consuming." }, { "code": null, "e": 4878, "s": 4799, "text": "The number of hyperparameters used to define deep learning models is numerous." }, { "code": null, "e": 4994, "s": 4878, "text": "By repeatedly changing the parameters in a network manually, you are effectively performing a hands-on grid search." }, { "code": null, "e": 5281, "s": 4994, "text": "Instead of manually checking different network configurations, you can define the distributions of each hyperparameter that you want to analyze. Then with many samples, you can find a more optimal model, and you can clearly understand how each hyperparameter affects your model overall." }, { "code": null, "e": 5505, "s": 5281, "text": "This method of architecture tuning requires at least two functions. First, a process to evaluate the function and store the best result and the function to generate the deep learning model based on a set of hyperparameters." }, { "code": null, "e": 5706, "s": 5505, "text": "For this post, I will focus on optimizing the architecture of a neural network with dropout layers. I’ll be using Keras within TensorFlow as it is straightforward to generate different models quickly." }, { "code": null, "e": 6002, "s": 5706, "text": "A quick pause here to say thank you to those responsible for Keras and TensorFlow. If you’ve ever created a neural network, CNN, or LSTM from scratch, you know it is incredibly tedious and complicated. So I’m am extremely grateful that these libraries exist and that they are open to the public." }, { "code": null, "e": 6362, "s": 6002, "text": "The model is generated using the hyperparameters sampled from each distribution defined. These values control the number of layers, the number of nodes across each of these layers, the dropout layer probability, the learning rate, optimizer, the learning decay for the optimization method, and the activation function. This model is set up for classification." }, { "code": null, "e": 6809, "s": 6362, "text": "It is possible to apply these functions to different networks, such as a convolutional neural network. However, due to the nature of convolutional layers, each subsequent layer depends on the previous layer. This aspect increases the complexity of the model creation function. CNN optimization will likely be the focus of a future post. However, a simple workaround for CNNs is fixing the number of layers and optimizing the remaining parameters." }, { "code": null, "e": 7101, "s": 6809, "text": "The first step is to import some packages and initialize some parameters. Here I also initialize the distributions of different hyperparameters that I was to test. You’ll notice that I don’t set up all of my hyperparameters as distributions, so I won’t be testing every combination possible." }, { "code": null, "e": 8223, "s": 7101, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow.keras import backend as Kfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Dropoutfrom tensorflow.keras.callbacks import TensorBoardfrom tensorflow.keras.optimizers import Adam, SGDfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.callbacks import EarlyStoppingfrom tensorflow.keras.optimizers.schedules import ExponentialDecayimport skoptfrom skopt.space import Real, Categorical, Integerfrom skopt import gp_minimize, forest_minimizefrom skopt.plots import plot_convergence, plot_objective, plot_evaluationsfrom skopt.utils import use_named_argsprint( \"Tensorflow version: \", tf.__version__)data = load_breast_cancer()y = data.target.astype(float)X = data.dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=2)X_validation, X_test, y_validation, y_test = train_test_split(X_test, y_test, test_size=0.4, random_state=2)" }, { "code": null, "e": 8444, "s": 8223, "text": "Next, distributions for the hyperparameters are defined. These distributions can be real continuous values, integer values, or categorical values. Moreover, the type of distribution is added for continuous distributions." }, { "code": null, "e": 8737, "s": 8444, "text": "For example, a log-uniform distribution may work better for a learning rate decay when most of the values that you want to test fall in a subset of the distribution. The hyperparameters also require default values. These defaults are used in the first model built in the optimization process." }, { "code": null, "e": 9875, "s": 8737, "text": "dim_optimization = Categorical(categories=['adam', 'SGD'],name='optimization')dim_learning_rate = Real(low=1e-3, high=1e-1, prior='log-uniform',name='learning_rate')dim_learning_decay = Real(low=0.9, high=0.999, prior='uniform',name='learning_decay')dim_num_layers = Integer(low=1, high=5, name='num_layers')dim_num_dense_nodes = Integer(low=5, high=50, name='num_dense_nodes')dim_dropout_prob = Real(low=0.5, high=0.99, prior='uniform',name='dropout_prob')dim_activation = Categorical(categories=['sigmoid', 'softmax', 'relu'],name='activation')dimensions = [ dim_optimization, dim_learning_rate, dim_learning_decay, dim_num_layers, dim_num_dense_nodes, dim_dropout_prob, dim_activation]NUM_LAYERS = 1BATCH_SIZE = 128LEARNING_RATE = 0.001DECAY_STEPS = 1000DENSE_UNITS = 20DROPOUT_PROB = 0.8ACTIVATION_FUNC = 'relu'LOSS_FUNC = 'binary_crossentropy'METRIC = 'accuracy'LEARNING_DECAY = 0.9OTIMIZATION_FUNC = 'adam'ACQ_FUNC = 'EI' # Expected Improvementbest_score = 0EPOCHS = 50BATCH_SIZE = 256N_CALLS = 1000default_parameters = [OTIMIZATION_FUNC, LEARNING_RATE, LEARNING_DECAY, NUM_LAYERS, DENSE_UNITS, DROPOUT_PROB, ACTIVATION_FUNC]" }, { "code": null, "e": 10210, "s": 9875, "text": "If you want to change the underlying model, this function will need to be changed. Depending on the hyperparameter input, some of the model parameters may be conditioned on other parameters. For example, in a CNN the filter dimensions affect the output shape into the next layer. Currently skopt does not support conditional features." }, { "code": null, "e": 10436, "s": 10210, "text": "For this example, I control the number of units in each of the dense layers and then add a dropout layer. This structure is a fairly simple network, but this code is easily modified to include different models of your choice." }, { "code": null, "e": 10530, "s": 10436, "text": "The next code chunk generates a deep neural net based on the hyperparameters from the sample." }, { "code": null, "e": 11464, "s": 10530, "text": "def create_model(optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation): model = Sequential() name = 'layer_{0}_dense_units'.format(0) model.add( Dense( num_dense_nodes, input_dim=X_train.shape[1], activation=activation, name=name)) for i in range(num_layers-1): name = 'layer_{0}_dense_units'.format(i+1) model.add( Dense( num_dense_nodes, activation=activation, name=name)) model.add( Dropout(dropout_prob)) model.add( Dense(1, activation=activation)) lr_schedule = ExponentialDecay( initial_learning_rate=learning_rate, decay_steps=DECAY_STEPS, decay_rate=learning_decay) if optimization == 'adam': optimizer = Adam(learning_rate=lr_schedule) if optimization == 'SGD': optimizer = SGD(learning_rate=lr_schedule) model.compile( optimizer=optimizer, loss=LOSS_FUNC, metrics=[METRIC]) return model" }, { "code": null, "e": 11749, "s": 11464, "text": "Fitness is the function that skopt will optimize with ‘gp_minimize’, which minimizes the Gaussian process generated to model the hyperparameter space. This function is minimization by construction. Hence the score that is being maximized becomes a minimization of the negative scores." }, { "code": null, "e": 13265, "s": 11749, "text": "@use_named_args(dimensions=dimensions)def fitness(optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation): # Create the neural network model = create_model( optimization=optimization, learning_rate=learning_rate, learning_decay=learning_decay, num_layers=num_layers, num_dense_nodes=num_dense_nodes, dropout_prob=dropout_prob, activation=activation) # Save log for tensorboard callback_log = TensorBoard( log_dir =\"./21_logs/opt_{0}_lr_{1:.0e}_lr_decay_{2:.0e}_layers_{3}_nodes_{4}_dropout_{5}_activation_{5}/\".format( optimization, learning_rate, learning_decay, num_layers, num_dense_nodes, dropout_prob, activation), histogram_freq=0, write_graph=True, write_grads=False, write_images=False) # Train the model. history = model.fit( x= X_train,y= y_train, epochs=EPOCHS,batch_size=BATCH_SIZE, validation_data=(X_validation, y_validation), callbacks=[callback_log],verbose=0) # Get the final model performance. col = [x for x in list(history.history.keys()) if 'val_'+METRIC in x] score = history.history[col[0]][-1] print(\"--> Validation {0}: {1:.2%}\".format(METRIC, score)) global best_score # Track scores and save best model if score > best_score: model.save('Optimal-NN') best_score = score # Clear model to save space del model K.clear_session() # Skopt minimizes black-box functions, return the negative return -score" }, { "code": null, "e": 13512, "s": 13265, "text": "The skopt function ‘gp_minimize’ runs Bayesian optimization on the black-box model to determine the optimal hyperparameter configuration. The ‘acq_func’, which is used to optimized the Gaussian process, is one of several options for optimization." }, { "code": null, "e": 13648, "s": 13512, "text": "search_result = gp_minimize(func=fitness, dimensions=dimensions, acq_func=ACQ_FUNC, n_calls=N_CALLS, x0=default_parameters)" }, { "code": null, "e": 13803, "s": 13648, "text": "Once the search is completed the best model found is saved locally. This model can be loaded in and used from this point and trained further if necessary." }, { "code": null, "e": 13918, "s": 13803, "text": "The search results contain the hyperparameters at each evaluation as well as the performance of each model tested." }, { "code": null, "e": 14012, "s": 13918, "text": "To see how the search improved the model performance over time, run the following code chunk:" }, { "code": null, "e": 14044, "s": 14012, "text": "plot_convergence(search_result)" }, { "code": null, "e": 14288, "s": 14044, "text": "However, just seeing the improvement over the different models tested is not the largest benefit of Bayesian optimization. The behavior of each of the hyperparameters is analyzed independently, and how they interact with other hyperparameters." }, { "code": null, "e": 14329, "s": 14288, "text": "_ = plot_objective(result=search_result)" }, { "code": null, "e": 14744, "s": 14329, "text": "You can see from the image above that there still is some uncertainty around some of the parameters. The results from changing the number of dense nodes vary a fair amount. However, the learning rate appears to be modeled effectively. You can see the optimization has selected a learning rate around 10e-2. Similarly, sigmoid activation and adam optimization appear to perform the best across all models generated." }, { "code": null, "e": 15016, "s": 14744, "text": "Bayesian optimization is useful when trying to fine-tune and optimize a computationally expensive model. In addition, Bayesian optimization requires few samples and rapidly closes in on a more optimal hyperparameter configuration, so it is ideal for deep learning models." }, { "code": null, "e": 15287, "s": 15016, "text": "For deep learning models such as neural networks and network variants, fine-tuning architecture is crucial. However, don’t waste your time manually tuning your model. Instead, use Bayesian optimization to determine what the role of each hyperparameter is for your model." }, { "code": null, "e": 15439, "s": 15287, "text": "If you’re interested in reading articles about novel data science tools and understanding machine learning algorithms, consider following me on Medium." } ]
Max Odd Sum | Practice | GeeksforGeeks
Given an array of integers, check whether there is a subsequence with odd sum and if yes, then finding the maximum odd sum. If no subsequence contains odd sum, print -1. Example 1: Input: N=4 arr[] = {4, -3, 3, -5} Output: 7 Explanation: The subsequence with maximum odd sum is 4 + 3 = 7 Example 2: Input: N=5 arr[] = {2, 5, -4, 3, -1} Output: 9 Explanation: The subsequence with maximum odd sum is 2 + 5 + 3 + -1 = 9 Your Task: Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function findMaxOddSubarraySum() that takes array arr and integer N as parameters and returns the desired value. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 2 ≤ N ≤ 107 -103 <= arr[i] <= 103 0 hasnainraza1998hr1 month ago C++, 0.5 long long int findMaxOddSubarraySum(long long int arr[], long long int n) { bool flag = true; long long int maxSum = 0; int minAbsValue = INT_MAX; for(int i=0;i<n;i++){ if(arr[i]>0) maxSum += arr[i]; if(arr[i]%2!=0){ flag = false; if(abs(arr[i])<minAbsValue) minAbsValue = abs(arr[i]); } } if(flag == true) return -1; if(maxSum%2==0) maxSum -= minAbsValue; return maxSum; } -1 Ramdeo Yadav1 year ago Ramdeo Yadav https://uploads.disquscdn.c... 0 363-AISHWARYA THORAT1 year ago 363-AISHWARYA THORAT Correct Answer.Execution Time:1.36 JAVA SOLUTION.: class Solution{ long findMaxOddSubarraySum(long arr[], long n) { boolean isOdd = false; long sum = 0; for (int i = 0 ; i < n ; i++) { if (arr[i] > 0) sum = sum + arr[i]; if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } } if (isOdd == false) return -1; if (sum % 2 == 0) sum = sum - min_odd; return sum; }} 0 TayfunYirdem2 years ago TayfunYirdem Two-lines solution with LINQhttps://ide.geeksforgeeks.o... +1 rahul495 years ago rahul49 how to deal with LTE issue in my code 0 ||||| | R A T H O R E | |||||5 years ago ||||| | R A T H O R E | ||||| few test cases you guys can use to check your algorithm..... 552 5 -4 3 -144 -3 3 -532 4 6384136 27 165 43 85 136 242 -101 171 112 -223 -60 -191 13 176 -210 176 -78 -14 -39 118 -183 179 32 -220 112 -127 -183 -115 179 52 -228 -192 -181 -83 143 206 -239 -208 -21 123 171 169 34 -213 -52 74 65 120 163 -224 -159 230 206 123 112 -80 246 31 55 175 -166 77 86 -245 96 -21 63 107 -126 145 -168 -205 64 117 184 114 -207 0 -163 58 26 -72 38 -166 153 -99 4 149 182 -190 -74 118 -11 -238 -24 -164 -156 -211 45 -180 184 128 217 -149 -153 152 67 242 -98 6 51 30 36 191 115 -61 194 -131 190 -21 -219 -133 -153 21 231 -75 -41 177 -183 106 247 103 -164 215 56 -67 -31 -126 -222 121 -18 79 -247 -231 20 118 -42 -35 90 -101 46 -27 -132 -5 96 201 171 -195 129 238 14 -22 91 100 -57 -250 -216 14 -126 164 237 106 -7 241 -23 115 109 186 182 -199 187 -22 25 157 224 -129 108 145 -221 -13 -15 43 68 178 -107 -239 178 -221 26 154 193 13 -137 -212 -144 90 154 68 -122 -62 119 167 167 246 74 -7 220 -67 240 249 22 -25 -106 -160 -245 -111 204 36 -81 -168 -208 214 -53 -243 105 54 98 -139 -128 78 49 93 -4 -182 90 172 61 60 -145 51 -89 -20 128 55 70 -14 194 -124 -228 215 -42 166 32 8 174 -113 -188 -126 -150 -214 202 149 129 -200 218 -179 223 -119 131 180 183 144 -90 -87 -51 231 149 246 209 23 63 -82 -60 -155 176 216 -166 90 -160 -66 126 -208 186 -143 195 6 -71 168 137 162 98 -78 -91 -241 86 -40 92 -163 -44 51 -37 122 71 5 69 -151 -29 154 189 61 190 -83 -45 -22 -123 -100 234 -92 170 -26 172 19 146 -169 -120 -166 42 222 -78 100 -125 135 -28 49 -110 -208 148 -37 48 -60 -226 -160 -41 -169 69 86 -18 -95 244 -246 129 19 23 26 100 5 110 -108 -171 134 243 -45 -129 260107 -6 249 161 -123 200 -14 -190 68 -145 -187 -201 -6 -39 55 184 41 125 205 -136 -161 18 243 168 55 132 72 232 -33 -220 -157 -176 -124 -157 236 3 -207 -176 64 -37 -71 127 12 25 -162 169 -40 -18 44 -233 96 -15 -113 -59 -97 193 -177 78 175 41 -40 -232 -33 86 213 -195 -160 108 -120 154 -179 -89 -117 -65 39 -177 -146 101 55 0 118 -247 235 -244 -55 -111 199 -130 217 -24 13 -73 -154 231 115 -190 -214 205 20 -232 -39 92 -218 -54 129 71 20 234 -78 177 -16 -210 33 -178 148 80 -187 97 200 -220 -177 -36 -191 -228 -203 174 -168 185 -18 -46 204 193 148 236 -110 28 -91 12 12 -67 -209 98 -27 74 22 -128 -96 85 71 207 115 -3 -79 26 19 -32 -49 -47 -97 183 157 209 -22 56 47 -30 -166 58 84 -52 241 126 148 -35 -198 -79 -61 -191 -244 -240 -234 -26 -141 -211 -250 128 -141 -197 -169 -136 88 239 176 -183 -103 -27 37 -19 -218 -128 31 125 100 -71 -160 4 100 -119 63 107 244 -69 -169 -147 -30 183 232 -69 237 165 46 75 154 -28 142 -199 47 -218 -116 -69 -244 165 -193 -42 -155 249 212 47 233 26 -96 227 59 -163 182 132 -229 16 -187 110 -68 -39 -65 -164 35 180 240 -167 64 226 and its correct answer97-12597315309 ACCEPTED code for further help time complexity O(N) and space O(1)http://ide.geeksforgeeks.or... 0 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 408, "s": 238, "text": "Given an array of integers, check whether there is a subsequence with odd sum and if yes, then finding the maximum odd sum. If no subsequence contains odd sum, print -1." }, { "code": null, "e": 420, "s": 408, "text": "\nExample 1:" }, { "code": null, "e": 527, "s": 420, "text": "Input:\nN=4\narr[] = {4, -3, 3, -5}\nOutput: 7\nExplanation:\nThe subsequence with maximum odd\nsum is 4 + 3 = 7" }, { "code": null, "e": 539, "s": 527, "text": "\nExample 2:" }, { "code": null, "e": 659, "s": 539, "text": "Input:\nN=5\narr[] = {2, 5, -4, 3, -1}\nOutput: 9\nExplanation:\nThe subsequence with maximum odd \nsum is 2 + 5 + 3 + -1 = 9" }, { "code": null, "e": 935, "s": 659, "text": "\nYour Task:\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function findMaxOddSubarraySum() that takes array arr and integer N as parameters and returns the desired value.\n " }, { "code": null, "e": 999, "s": 935, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1047, "s": 999, "text": "\nConstraints:\n2 ≤ N ≤ 107\n-103 <= arr[i] <= 103" }, { "code": null, "e": 1051, "s": 1049, "text": "0" }, { "code": null, "e": 1080, "s": 1051, "text": "hasnainraza1998hr1 month ago" }, { "code": null, "e": 1089, "s": 1080, "text": "C++, 0.5" }, { "code": null, "e": 1625, "s": 1089, "text": "long long int findMaxOddSubarraySum(long long int arr[], long long int n) { bool flag = true; long long int maxSum = 0; int minAbsValue = INT_MAX; for(int i=0;i<n;i++){ if(arr[i]>0) maxSum += arr[i]; if(arr[i]%2!=0){ flag = false; if(abs(arr[i])<minAbsValue) minAbsValue = abs(arr[i]); } } if(flag == true) return -1; if(maxSum%2==0) maxSum -= minAbsValue; return maxSum; }" }, { "code": null, "e": 1628, "s": 1625, "text": "-1" }, { "code": null, "e": 1651, "s": 1628, "text": "Ramdeo Yadav1 year ago" }, { "code": null, "e": 1664, "s": 1651, "text": "Ramdeo Yadav" }, { "code": null, "e": 1695, "s": 1664, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 1697, "s": 1695, "text": "0" }, { "code": null, "e": 1728, "s": 1697, "text": "363-AISHWARYA THORAT1 year ago" }, { "code": null, "e": 1749, "s": 1728, "text": "363-AISHWARYA THORAT" }, { "code": null, "e": 1784, "s": 1749, "text": "Correct Answer.Execution Time:1.36" }, { "code": null, "e": 1800, "s": 1784, "text": "JAVA SOLUTION.:" }, { "code": null, "e": 1869, "s": 1800, "text": "class Solution{ long findMaxOddSubarraySum(long arr[], long n) {" }, { "code": null, "e": 1896, "s": 1869, "text": " boolean isOdd = false;" }, { "code": null, "e": 1955, "s": 1896, "text": " long sum = 0; for (int i = 0 ; i < n ; i++) {" }, { "code": null, "e": 2011, "s": 1955, "text": " if (arr[i] > 0) sum = sum + arr[i];" }, { "code": null, "e": 2180, "s": 2011, "text": " if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } }" }, { "code": null, "e": 2219, "s": 2180, "text": " if (isOdd == false) return -1;" }, { "code": null, "e": 2270, "s": 2219, "text": " if (sum % 2 == 0) sum = sum - min_odd;" }, { "code": null, "e": 2289, "s": 2270, "text": " return sum; }}" }, { "code": null, "e": 2291, "s": 2289, "text": "0" }, { "code": null, "e": 2315, "s": 2291, "text": "TayfunYirdem2 years ago" }, { "code": null, "e": 2328, "s": 2315, "text": "TayfunYirdem" }, { "code": null, "e": 2387, "s": 2328, "text": "Two-lines solution with LINQhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 2390, "s": 2387, "text": "+1" }, { "code": null, "e": 2409, "s": 2390, "text": "rahul495 years ago" }, { "code": null, "e": 2417, "s": 2409, "text": "rahul49" }, { "code": null, "e": 2455, "s": 2417, "text": "how to deal with LTE issue in my code" }, { "code": null, "e": 2457, "s": 2455, "text": "0" }, { "code": null, "e": 2498, "s": 2457, "text": "||||| | R A T H O R E | |||||5 years ago" }, { "code": null, "e": 2528, "s": 2498, "text": "||||| | R A T H O R E | |||||" }, { "code": null, "e": 2589, "s": 2528, "text": "few test cases you guys can use to check your algorithm....." }, { "code": null, "e": 5229, "s": 2589, "text": "552 5 -4 3 -144 -3 3 -532 4 6384136 27 165 43 85 136 242 -101 171 112 -223 -60 -191 13 176 -210 176 -78 -14 -39 118 -183 179 32 -220 112 -127 -183 -115 179 52 -228 -192 -181 -83 143 206 -239 -208 -21 123 171 169 34 -213 -52 74 65 120 163 -224 -159 230 206 123 112 -80 246 31 55 175 -166 77 86 -245 96 -21 63 107 -126 145 -168 -205 64 117 184 114 -207 0 -163 58 26 -72 38 -166 153 -99 4 149 182 -190 -74 118 -11 -238 -24 -164 -156 -211 45 -180 184 128 217 -149 -153 152 67 242 -98 6 51 30 36 191 115 -61 194 -131 190 -21 -219 -133 -153 21 231 -75 -41 177 -183 106 247 103 -164 215 56 -67 -31 -126 -222 121 -18 79 -247 -231 20 118 -42 -35 90 -101 46 -27 -132 -5 96 201 171 -195 129 238 14 -22 91 100 -57 -250 -216 14 -126 164 237 106 -7 241 -23 115 109 186 182 -199 187 -22 25 157 224 -129 108 145 -221 -13 -15 43 68 178 -107 -239 178 -221 26 154 193 13 -137 -212 -144 90 154 68 -122 -62 119 167 167 246 74 -7 220 -67 240 249 22 -25 -106 -160 -245 -111 204 36 -81 -168 -208 214 -53 -243 105 54 98 -139 -128 78 49 93 -4 -182 90 172 61 60 -145 51 -89 -20 128 55 70 -14 194 -124 -228 215 -42 166 32 8 174 -113 -188 -126 -150 -214 202 149 129 -200 218 -179 223 -119 131 180 183 144 -90 -87 -51 231 149 246 209 23 63 -82 -60 -155 176 216 -166 90 -160 -66 126 -208 186 -143 195 6 -71 168 137 162 98 -78 -91 -241 86 -40 92 -163 -44 51 -37 122 71 5 69 -151 -29 154 189 61 190 -83 -45 -22 -123 -100 234 -92 170 -26 172 19 146 -169 -120 -166 42 222 -78 100 -125 135 -28 49 -110 -208 148 -37 48 -60 -226 -160 -41 -169 69 86 -18 -95 244 -246 129 19 23 26 100 5 110 -108 -171 134 243 -45 -129 260107 -6 249 161 -123 200 -14 -190 68 -145 -187 -201 -6 -39 55 184 41 125 205 -136 -161 18 243 168 55 132 72 232 -33 -220 -157 -176 -124 -157 236 3 -207 -176 64 -37 -71 127 12 25 -162 169 -40 -18 44 -233 96 -15 -113 -59 -97 193 -177 78 175 41 -40 -232 -33 86 213 -195 -160 108 -120 154 -179 -89 -117 -65 39 -177 -146 101 55 0 118 -247 235 -244 -55 -111 199 -130 217 -24 13 -73 -154 231 115 -190 -214 205 20 -232 -39 92 -218 -54 129 71 20 234 -78 177 -16 -210 33 -178 148 80 -187 97 200 -220 -177 -36 -191 -228 -203 174 -168 185 -18 -46 204 193 148 236 -110 28 -91 12 12 -67 -209 98 -27 74 22 -128 -96 85 71 207 115 -3 -79 26 19 -32 -49 -47 -97 183 157 209 -22 56 47 -30 -166 58 84 -52 241 126 148 -35 -198 -79 -61 -191 -244 -240 -234 -26 -141 -211 -250 128 -141 -197 -169 -136 88 239 176 -183 -103 -27 37 -19 -218 -128 31 125 100 -71 -160 4 100 -119 63 107 244 -69 -169 -147 -30 183 232 -69 237 165 46 75 154 -28 142 -199 47 -218 -116 -69 -244 165 -193 -42 -155 249 212 47 233 26 -96 227 59 -163 182 132 -229 16 -187 110 -68 -39 -65 -164 35 180 240 -167 64 226" }, { "code": null, "e": 5266, "s": 5229, "text": "and its correct answer97-12597315309" }, { "code": null, "e": 5363, "s": 5266, "text": "ACCEPTED code for further help time complexity O(N) and space O(1)http://ide.geeksforgeeks.or..." }, { "code": null, "e": 5365, "s": 5363, "text": "0" }, { "code": null, "e": 5391, "s": 5365, "text": "This comment was deleted." }, { "code": null, "e": 5537, "s": 5391, "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": 5573, "s": 5537, "text": " Login to access your submissions. " }, { "code": null, "e": 5583, "s": 5573, "text": "\nProblem\n" }, { "code": null, "e": 5593, "s": 5583, "text": "\nContest\n" }, { "code": null, "e": 5656, "s": 5593, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5804, "s": 5656, "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": 6012, "s": 5804, "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": 6118, "s": 6012, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
break command in Linux with examples - GeeksforGeeks
15 May, 2019 break command is used to terminate the execution of for loop, while loop and until loop. It can also take one parameter i.e.[N]. Here n is the number of nested loops to break. The default number is 1. Syntax: break [n] Example 1: Using break statement in for loop Example 2: Using break statement in while loop Example 3: Using break statement in until loop break –help : It displays help information. linux-command Linux-Shell-Commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization echo command in Linux with Examples tee command in Linux with examples
[ { "code": null, "e": 24039, "s": 24011, "text": "\n15 May, 2019" }, { "code": null, "e": 24240, "s": 24039, "text": "break command is used to terminate the execution of for loop, while loop and until loop. It can also take one parameter i.e.[N]. Here n is the number of nested loops to break. The default number is 1." }, { "code": null, "e": 24248, "s": 24240, "text": "Syntax:" }, { "code": null, "e": 24259, "s": 24248, "text": "break [n]\n" }, { "code": null, "e": 24304, "s": 24259, "text": "Example 1: Using break statement in for loop" }, { "code": null, "e": 24351, "s": 24304, "text": "Example 2: Using break statement in while loop" }, { "code": null, "e": 24398, "s": 24351, "text": "Example 3: Using break statement in until loop" }, { "code": null, "e": 24442, "s": 24398, "text": "break –help : It displays help information." }, { "code": null, "e": 24456, "s": 24442, "text": "linux-command" }, { "code": null, "e": 24477, "s": 24456, "text": "Linux-Shell-Commands" }, { "code": null, "e": 24484, "s": 24477, "text": "Picked" }, { "code": null, "e": 24508, "s": 24484, "text": "Technical Scripter 2018" }, { "code": null, "e": 24519, "s": 24508, "text": "Linux-Unix" }, { "code": null, "e": 24538, "s": 24519, "text": "Technical Scripter" }, { "code": null, "e": 24636, "s": 24538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24671, "s": 24636, "text": "tar command in Linux with examples" }, { "code": null, "e": 24707, "s": 24671, "text": "curl command in Linux with Examples" }, { "code": null, "e": 24745, "s": 24707, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 24783, "s": 24745, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 24818, "s": 24783, "text": "Cat command in Linux with examples" }, { "code": null, "e": 24854, "s": 24818, "text": "Tail command in Linux with examples" }, { "code": null, "e": 24891, "s": 24854, "text": "touch command in Linux with Examples" }, { "code": null, "e": 24935, "s": 24891, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 24971, "s": 24935, "text": "echo command in Linux with Examples" } ]
Higher-Order Functions with Spark 3.1 | by David Vrba | Towards Data Science
Complex data structures, such as arrays, structs, and maps are very common in big data processing, especially in Spark. The situation occurs each time we want to represent in one column more than a single value on each row, this can be a list of values in the case of array data type or a list of key-value pairs in the case of the map. The support for processing these complex data types increased since Spark 2.4 by releasing higher-order functions (HOFs). In this article, we will take a look at what higher-order functions are, how they can be efficiently used and what related features were released in the last few Spark releases 3.0 and 3.1.1. For the code, we will use Python API. After aggregations and window functions that we covered in the last article, HOFs are another group of more advanced transformations in Spark SQL. Let’s first see the difference between the three complex data types that Spark offers. l = [(1, ['the', 'quick', 'braun', 'fox'])]df = spark.createDataFrame(l, schema=['id', 'words'])df.printSchema()root |-- id: long (nullable = true) |-- words: array (nullable = true) | |-- element: string (containsNull = true) In the example above, we have a DataFrame with two columns, where the column words is of the array type, which means that on each row in the DataFrame we can represent a list of values and the list can have different size on each row. Also, the elements of the array have an order. The important property is that the arrays are homogeneous in terms of the element type, which means that all elements must have the same type. To access the elements of the arrays we can use indices as follows: df.withColumn('first_element', col('words')[0]) StructType is used to group together some sub-fields that may have a different type (unlike arrays). Each sub-field has a type and also a name and this must be the same for all rows in the DataFrame. What might be unexpected is that the sub-fields inside a struct have an order, so comparing two structs s1==s2 that have the same fields but in different order leads to False. Notice the fundamental differences between array and struct: array: homogeneous in types, a different size on each row is allowed struct: heterogeneous in types, the same schema on each row is required You can think of the map type as a mixture of the two previous types: array and struct. Imagine a situation where the schema for each row is not given, you need to support a different number of sub-fields on each row. In such a case you can not use struct. But using an array is not a good option for you either because each element has a name and a value (it is actually a key-value pair) or because the elements have a different type — that would be a good use-case for the map type. With a map type, you can store on each row a different number of key-value pairs, but each key must have the same type and also all values need to be of the same type (which can be different from the type of the keys). The order of the pairs matters. Before we start talking about transforming arrays, let’s first see how we can create an array. The first way we have seen above, where we created the DataFrame from a local list of values. On the other hand, if we already have a DataFrame and we want to group some columns to an array we can use a function array() for this purpose. It allows you to create an array from other existing columns, so if you have columns a, b, c and you want to have the values inside an array instead of having it in individual columns you can do it as follows: df.withColumn('my_arr', array('a', 'b', 'c')) Apart from that, there are also some functions that produce an array as a result of a transformation. This is for example the function split() that will split a string into an array of words. Another example is collect_list() or collect_set() which are aggregation functions that will also produce an array. And in practice, the most common way how to get an array to a DataFrame is by reading the data from a source that supports complex data structures such as Parquet. In this file format, some columns can be stored as arrays, so Spark will naturally read them also as arrays. Now when we know how to create an array, let’s see how arrays can be transformed. Since Spark 2.4 there are plenty of functions for array transformation. For the complete list of them, check the PySpark documentation. For example, all the functions starting with array_ can be used for array processing, you can find min-max values, deduplicate the arrays, sort them, join them, and so on. Next, there is also concat(), flatten(), shuffle(), size(), slice(), sort_array(). As you can see, the API is quite mature in this regard and there are lots of operations that you can do with arrays in Spark. Apart from these aforementioned functions, there is also a group of functions that take as an argument another function that is then applied to each element of the array — these are called Higher-Order Functions (HOFs). The important thing to know about them is that in the Python API, they are supported since 3.1.1 and in Scala API they were released in 3.0. On the other hand, with SQL expressions, you can use them since 2.4. To see some specific examples, consider the following simple DataFrame: l = [(1, ['prague', 'london', 'tokyo', None, 'sydney'])]df = spark.createDataFrame(l, ['id', 'cities'])df.show(truncate=False)+---+-------------------------------------+|id |cities |+---+-------------------------------------+|1 |[prague, london, tokyo, null, sydney]|+---+-------------------------------------+ Let’s say we want to do these five independent tasks: Convert starting letter of each city to upper-case.Get rid of null values in the array.Check if there is an element that starts with the letter t.Check if there is a null value in the array.Sum the number of characters (the length) of each city in the array. Convert starting letter of each city to upper-case. Get rid of null values in the array. Check if there is an element that starts with the letter t. Check if there is a null value in the array. Sum the number of characters (the length) of each city in the array. These are some typical examples of problems that can be solved with HOFs. So let's see them one by one: For the first problem, we can use the transform HOF, which simply takes an anonymous function, applies it to each element of the original array, and returns another transformed array. The syntax is as follows: df \.withColumn('cities', transform('cities', lambda x: initcap(x))) \.show(truncate=False)+---+-------------------------------------+|id |cities |+---+-------------------------------------+|1 |[Prague, London, Tokyo, null, Sydney]|+---+-------------------------------------+ As you can see, the transform() takes two arguments, the first one is the array that should be transformed and the second one is an anonymous function. Here, to achieve our transformation, we used initcap() inside the anonymous function and it was applied on each element of the array — this is exactly what the transform HOF allows us to do. With SQL expressions it can be used as follows: df.selectExpr("id", "TRANSFORM(cities, x -> INITCAP(x)) AS cities") Notice that the anonymous function in SQL is expressed with the arrow (->) notation. In the second problem, we want to filter out null values from the array. This (and any other filtering for that matter) can be handled using the filter HOF. It allows us to apply an anonymous function that returns boolean (True/False) on each element and it will return a new array that contains only elements for which the function returned True: df \.withColumn('cities', filter('cities', lambda x: x.isNotNull())) \.show(truncate=False)+---+-------------------------------+|id |cities |+---+-------------------------------+|1 |[prague, london, tokyo, sydney]|+---+-------------------------------+ Here, in the anonymous function we call PySpark function isNotNull(). The SQL syntax goes as follows: df.selectExpr("id", "FILTER(cities, x -> x IS NOT NULL) AS cities") In the next problem, we want to check if the array contains elements that satisfy some specific condition. Notice, that this is a more general example of a situation in which we want to check for the presence of some particular element. For example, if we want to check whether the array contains the city prague, we could just call the array_contains function: df.withColumn('has_prague', array_contains('cities', 'prague')) On the other hand, the exists HOF allows us to apply a more general condition to each element. The result is no longer an array as it was with the two previous HOFs, but it is just True/False: df \.withColumn('has_t_city', exists('cities', lambda x: x.startswith('t'))) \.show(truncate=False)+---+-------------------------------------+----------+|id |cities |has_t_city|+---+-------------------------------------+----------+|1 |[prague, london, tokyo, null, sydney]|true |+---+-------------------------------------+----------+ Here in the anonymous function, we used the PySpark function startswith(). In the fourth question, we want to verify if all elements in the array satisfy some condition, in our example, we want to check if they are all not null: df \.withColumn('nulls_free',forall('cities', lambda x: x.isNotNull()))\.show(truncate=False)+---+-------------------------------------+----------+|id |cities |nulls_free|+---+-------------------------------------+----------+|1 |[prague, london, tokyo, null, sydney]|false |+---+-------------------------------------+----------+ As you can see, forall is quite similar to exists, but now we are checking if the condition holds for all elements, before we were looking for at least one. In the last problem, we want to sum the lengths of each word in the array. It is an example of a situation in which we want to reduce the entire array to a single value and for this kind of problem we can use the HOF aggregate. df \.withColumn('cities', filter('cities', lambda x: x.isNotNull())) \.withColumn('cities_len', aggregate('cities', lit(0), lambda x, y: x + length(y))) \.show(truncate=False)+---+-------------------------------+----------+|id |cities |cities_len|+---+-------------------------------+----------+|1 |[prague, london, tokyo, sydney]|23 |+---+-------------------------------+----------+ And with SQL: df \.withColumn("cities", filter("cities", lambda x: x.isNotNull())) \.selectExpr( "cities", "AGGREGATE(cities, 0,(x, y) -> x + length(y)) AS cities_len") As you can see the syntax is slightly more complex as compared to the previous HOFs. The aggregate takes more arguments, the first one is still the array that we want to transform, the second argument is the initial value that we want to start with. In our case, the initial value is zero (lit(0)) and we will be adding to it the length of each city. The third argument is the anonymous function and now this function itself takes two arguments — the first one (in our example x) is the running buffer to which we are adding the length of the next element that is represented with the second argument (in our example y). Optionally, there can be a fourth argument provided which is another anonymous function that transforms the final result. This is useful if we want to do a more complex aggregation, for example, if we want to compute the average length, we need to keep around two values, the sum and also the count and we would divide them in the last transformation as follows: ( df .withColumn('cities', filter('cities', lambda x: x.isNotNull())) .withColumn('cities_avg_len', aggregate( 'cities', struct(lit(0).alias('sum'), lit(0).alias('count')), lambda x, y: struct( (x.sum + length(y)).alias('sum'), (x.count + 1).alias('count') ), lambda x: x.sum / x.count ) )).show(truncate=False)+---+-------------------------------+--------------+|id |cities |cities_avg_len|+---+-------------------------------+--------------+|1 |[prague, london, tokyo, sydney]|5.75 |+---+-------------------------------+--------------+ As you can see, this is a more advanced example in which we need to keep around two values during the aggregation and we represent them using struct() that has two subfields sum and count. Using the first anonymous function we compute the final sum of all lengths and also the count which is the number of summed elements. In the second anonymous function, we just divide these two values to get the final average. Also notice, that before using aggregate we first filtered out null values because if we keep the null value in the array, the sum (and also the average) will become null. To see another example of the aggregate HOF where it is used with SQL expressions, check this Stack Overflow question. Apart from these five aforementioned HOFs, there is also zip_with that can be used to merge two arrays into a single one. Besides that, there are also other HOFs such as map_filter, map_zip_with, transform_keys, and transform_values that are used with maps and we will take a look at them in a future article. In this article, we covered higher-order functions (HOFs) which is a feature that was released in Spark 2.4. First, it was supported only with SQL expressions, but since 3.1.1 it is supported also in the Python API. We have seen examples of five HOFs, that allow us to transform, filter, check for existence, and aggregate elements in the Spark arrays. Before HOFs were released, most of these problems had to be solved using User-Defined functions. The HOF approach is however more efficient in terms of performance and to see some performance benchmarks, see my other recent article that shows some concrete numbers.
[ { "code": null, "e": 509, "s": 172, "text": "Complex data structures, such as arrays, structs, and maps are very common in big data processing, especially in Spark. The situation occurs each time we want to represent in one column more than a single value on each row, this can be a list of values in the case of array data type or a list of key-value pairs in the case of the map." }, { "code": null, "e": 861, "s": 509, "text": "The support for processing these complex data types increased since Spark 2.4 by releasing higher-order functions (HOFs). In this article, we will take a look at what higher-order functions are, how they can be efficiently used and what related features were released in the last few Spark releases 3.0 and 3.1.1. For the code, we will use Python API." }, { "code": null, "e": 1008, "s": 861, "text": "After aggregations and window functions that we covered in the last article, HOFs are another group of more advanced transformations in Spark SQL." }, { "code": null, "e": 1095, "s": 1008, "text": "Let’s first see the difference between the three complex data types that Spark offers." }, { "code": null, "e": 1325, "s": 1095, "text": "l = [(1, ['the', 'quick', 'braun', 'fox'])]df = spark.createDataFrame(l, schema=['id', 'words'])df.printSchema()root |-- id: long (nullable = true) |-- words: array (nullable = true) | |-- element: string (containsNull = true)" }, { "code": null, "e": 1818, "s": 1325, "text": "In the example above, we have a DataFrame with two columns, where the column words is of the array type, which means that on each row in the DataFrame we can represent a list of values and the list can have different size on each row. Also, the elements of the array have an order. The important property is that the arrays are homogeneous in terms of the element type, which means that all elements must have the same type. To access the elements of the arrays we can use indices as follows:" }, { "code": null, "e": 1866, "s": 1818, "text": "df.withColumn('first_element', col('words')[0])" }, { "code": null, "e": 2242, "s": 1866, "text": "StructType is used to group together some sub-fields that may have a different type (unlike arrays). Each sub-field has a type and also a name and this must be the same for all rows in the DataFrame. What might be unexpected is that the sub-fields inside a struct have an order, so comparing two structs s1==s2 that have the same fields but in different order leads to False." }, { "code": null, "e": 2303, "s": 2242, "text": "Notice the fundamental differences between array and struct:" }, { "code": null, "e": 2372, "s": 2303, "text": "array: homogeneous in types, a different size on each row is allowed" }, { "code": null, "e": 2444, "s": 2372, "text": "struct: heterogeneous in types, the same schema on each row is required" }, { "code": null, "e": 3181, "s": 2444, "text": "You can think of the map type as a mixture of the two previous types: array and struct. Imagine a situation where the schema for each row is not given, you need to support a different number of sub-fields on each row. In such a case you can not use struct. But using an array is not a good option for you either because each element has a name and a value (it is actually a key-value pair) or because the elements have a different type — that would be a good use-case for the map type. With a map type, you can store on each row a different number of key-value pairs, but each key must have the same type and also all values need to be of the same type (which can be different from the type of the keys). The order of the pairs matters." }, { "code": null, "e": 3724, "s": 3181, "text": "Before we start talking about transforming arrays, let’s first see how we can create an array. The first way we have seen above, where we created the DataFrame from a local list of values. On the other hand, if we already have a DataFrame and we want to group some columns to an array we can use a function array() for this purpose. It allows you to create an array from other existing columns, so if you have columns a, b, c and you want to have the values inside an array instead of having it in individual columns you can do it as follows:" }, { "code": null, "e": 3770, "s": 3724, "text": "df.withColumn('my_arr', array('a', 'b', 'c'))" }, { "code": null, "e": 4078, "s": 3770, "text": "Apart from that, there are also some functions that produce an array as a result of a transformation. This is for example the function split() that will split a string into an array of words. Another example is collect_list() or collect_set() which are aggregation functions that will also produce an array." }, { "code": null, "e": 4351, "s": 4078, "text": "And in practice, the most common way how to get an array to a DataFrame is by reading the data from a source that supports complex data structures such as Parquet. In this file format, some columns can be stored as arrays, so Spark will naturally read them also as arrays." }, { "code": null, "e": 4433, "s": 4351, "text": "Now when we know how to create an array, let’s see how arrays can be transformed." }, { "code": null, "e": 4950, "s": 4433, "text": "Since Spark 2.4 there are plenty of functions for array transformation. For the complete list of them, check the PySpark documentation. For example, all the functions starting with array_ can be used for array processing, you can find min-max values, deduplicate the arrays, sort them, join them, and so on. Next, there is also concat(), flatten(), shuffle(), size(), slice(), sort_array(). As you can see, the API is quite mature in this regard and there are lots of operations that you can do with arrays in Spark." }, { "code": null, "e": 5380, "s": 4950, "text": "Apart from these aforementioned functions, there is also a group of functions that take as an argument another function that is then applied to each element of the array — these are called Higher-Order Functions (HOFs). The important thing to know about them is that in the Python API, they are supported since 3.1.1 and in Scala API they were released in 3.0. On the other hand, with SQL expressions, you can use them since 2.4." }, { "code": null, "e": 5452, "s": 5380, "text": "To see some specific examples, consider the following simple DataFrame:" }, { "code": null, "e": 5794, "s": 5452, "text": "l = [(1, ['prague', 'london', 'tokyo', None, 'sydney'])]df = spark.createDataFrame(l, ['id', 'cities'])df.show(truncate=False)+---+-------------------------------------+|id |cities |+---+-------------------------------------+|1 |[prague, london, tokyo, null, sydney]|+---+-------------------------------------+" }, { "code": null, "e": 5848, "s": 5794, "text": "Let’s say we want to do these five independent tasks:" }, { "code": null, "e": 6107, "s": 5848, "text": "Convert starting letter of each city to upper-case.Get rid of null values in the array.Check if there is an element that starts with the letter t.Check if there is a null value in the array.Sum the number of characters (the length) of each city in the array." }, { "code": null, "e": 6159, "s": 6107, "text": "Convert starting letter of each city to upper-case." }, { "code": null, "e": 6196, "s": 6159, "text": "Get rid of null values in the array." }, { "code": null, "e": 6256, "s": 6196, "text": "Check if there is an element that starts with the letter t." }, { "code": null, "e": 6301, "s": 6256, "text": "Check if there is a null value in the array." }, { "code": null, "e": 6370, "s": 6301, "text": "Sum the number of characters (the length) of each city in the array." }, { "code": null, "e": 6474, "s": 6370, "text": "These are some typical examples of problems that can be solved with HOFs. So let's see them one by one:" }, { "code": null, "e": 6684, "s": 6474, "text": "For the first problem, we can use the transform HOF, which simply takes an anonymous function, applies it to each element of the original array, and returns another transformed array. The syntax is as follows:" }, { "code": null, "e": 6991, "s": 6684, "text": "df \\.withColumn('cities', transform('cities', lambda x: initcap(x))) \\.show(truncate=False)+---+-------------------------------------+|id |cities |+---+-------------------------------------+|1 |[Prague, London, Tokyo, null, Sydney]|+---+-------------------------------------+" }, { "code": null, "e": 7382, "s": 6991, "text": "As you can see, the transform() takes two arguments, the first one is the array that should be transformed and the second one is an anonymous function. Here, to achieve our transformation, we used initcap() inside the anonymous function and it was applied on each element of the array — this is exactly what the transform HOF allows us to do. With SQL expressions it can be used as follows:" }, { "code": null, "e": 7450, "s": 7382, "text": "df.selectExpr(\"id\", \"TRANSFORM(cities, x -> INITCAP(x)) AS cities\")" }, { "code": null, "e": 7535, "s": 7450, "text": "Notice that the anonymous function in SQL is expressed with the arrow (->) notation." }, { "code": null, "e": 7883, "s": 7535, "text": "In the second problem, we want to filter out null values from the array. This (and any other filtering for that matter) can be handled using the filter HOF. It allows us to apply an anonymous function that returns boolean (True/False) on each element and it will return a new array that contains only elements for which the function returned True:" }, { "code": null, "e": 8160, "s": 7883, "text": "df \\.withColumn('cities', filter('cities', lambda x: x.isNotNull())) \\.show(truncate=False)+---+-------------------------------+|id |cities |+---+-------------------------------+|1 |[prague, london, tokyo, sydney]|+---+-------------------------------+" }, { "code": null, "e": 8262, "s": 8160, "text": "Here, in the anonymous function we call PySpark function isNotNull(). The SQL syntax goes as follows:" }, { "code": null, "e": 8330, "s": 8262, "text": "df.selectExpr(\"id\", \"FILTER(cities, x -> x IS NOT NULL) AS cities\")" }, { "code": null, "e": 8692, "s": 8330, "text": "In the next problem, we want to check if the array contains elements that satisfy some specific condition. Notice, that this is a more general example of a situation in which we want to check for the presence of some particular element. For example, if we want to check whether the array contains the city prague, we could just call the array_contains function:" }, { "code": null, "e": 8756, "s": 8692, "text": "df.withColumn('has_prague', array_contains('cities', 'prague'))" }, { "code": null, "e": 8949, "s": 8756, "text": "On the other hand, the exists HOF allows us to apply a more general condition to each element. The result is no longer an array as it was with the two previous HOFs, but it is just True/False:" }, { "code": null, "e": 9321, "s": 8949, "text": "df \\.withColumn('has_t_city', exists('cities', lambda x: x.startswith('t'))) \\.show(truncate=False)+---+-------------------------------------+----------+|id |cities |has_t_city|+---+-------------------------------------+----------+|1 |[prague, london, tokyo, null, sydney]|true |+---+-------------------------------------+----------+" }, { "code": null, "e": 9396, "s": 9321, "text": "Here in the anonymous function, we used the PySpark function startswith()." }, { "code": null, "e": 9550, "s": 9396, "text": "In the fourth question, we want to verify if all elements in the array satisfy some condition, in our example, we want to check if they are all not null:" }, { "code": null, "e": 9914, "s": 9550, "text": "df \\.withColumn('nulls_free',forall('cities', lambda x: x.isNotNull()))\\.show(truncate=False)+---+-------------------------------------+----------+|id |cities |nulls_free|+---+-------------------------------------+----------+|1 |[prague, london, tokyo, null, sydney]|false |+---+-------------------------------------+----------+" }, { "code": null, "e": 10071, "s": 9914, "text": "As you can see, forall is quite similar to exists, but now we are checking if the condition holds for all elements, before we were looking for at least one." }, { "code": null, "e": 10299, "s": 10071, "text": "In the last problem, we want to sum the lengths of each word in the array. It is an example of a situation in which we want to reduce the entire array to a single value and for this kind of problem we can use the HOF aggregate." }, { "code": null, "e": 10717, "s": 10299, "text": "df \\.withColumn('cities', filter('cities', lambda x: x.isNotNull())) \\.withColumn('cities_len', aggregate('cities', lit(0), lambda x, y: x + length(y))) \\.show(truncate=False)+---+-------------------------------+----------+|id |cities |cities_len|+---+-------------------------------+----------+|1 |[prague, london, tokyo, sydney]|23 |+---+-------------------------------+----------+" }, { "code": null, "e": 10731, "s": 10717, "text": "And with SQL:" }, { "code": null, "e": 10893, "s": 10731, "text": "df \\.withColumn(\"cities\", filter(\"cities\", lambda x: x.isNotNull())) \\.selectExpr( \"cities\", \"AGGREGATE(cities, 0,(x, y) -> x + length(y)) AS cities_len\")" }, { "code": null, "e": 11514, "s": 10893, "text": "As you can see the syntax is slightly more complex as compared to the previous HOFs. The aggregate takes more arguments, the first one is still the array that we want to transform, the second argument is the initial value that we want to start with. In our case, the initial value is zero (lit(0)) and we will be adding to it the length of each city. The third argument is the anonymous function and now this function itself takes two arguments — the first one (in our example x) is the running buffer to which we are adding the length of the next element that is represented with the second argument (in our example y)." }, { "code": null, "e": 11877, "s": 11514, "text": "Optionally, there can be a fourth argument provided which is another anonymous function that transforms the final result. This is useful if we want to do a more complex aggregation, for example, if we want to compute the average length, we need to keep around two values, the sum and also the count and we would divide them in the last transformation as follows:" }, { "code": null, "e": 12564, "s": 11877, "text": "( df .withColumn('cities', filter('cities', lambda x: x.isNotNull())) .withColumn('cities_avg_len', aggregate( 'cities', struct(lit(0).alias('sum'), lit(0).alias('count')), lambda x, y: struct( (x.sum + length(y)).alias('sum'), (x.count + 1).alias('count') ), lambda x: x.sum / x.count ) )).show(truncate=False)+---+-------------------------------+--------------+|id |cities |cities_avg_len|+---+-------------------------------+--------------+|1 |[prague, london, tokyo, sydney]|5.75 |+---+-------------------------------+--------------+" }, { "code": null, "e": 13151, "s": 12564, "text": "As you can see, this is a more advanced example in which we need to keep around two values during the aggregation and we represent them using struct() that has two subfields sum and count. Using the first anonymous function we compute the final sum of all lengths and also the count which is the number of summed elements. In the second anonymous function, we just divide these two values to get the final average. Also notice, that before using aggregate we first filtered out null values because if we keep the null value in the array, the sum (and also the average) will become null." }, { "code": null, "e": 13270, "s": 13151, "text": "To see another example of the aggregate HOF where it is used with SQL expressions, check this Stack Overflow question." }, { "code": null, "e": 13580, "s": 13270, "text": "Apart from these five aforementioned HOFs, there is also zip_with that can be used to merge two arrays into a single one. Besides that, there are also other HOFs such as map_filter, map_zip_with, transform_keys, and transform_values that are used with maps and we will take a look at them in a future article." } ]
Count of subarrays for each Array element in which arr[i] is first and least - GeeksforGeeks
04 Apr, 2022 Given an array arr[], the task is to find the count of subarrays starting from the current element that has a minimum element as the current element itself. Examples: Input: arr[] = {2, 4, 2, 1, 3} Output: {3, 1, 1, 2, 1}Explanation: For the first element we can form 3 valid subarrays with the given condition 2 -> {2} , {2,4} , {2,4,2} = 3 subarrays and so on 4 -> {4} = 1 subarray 2 -> {2} = 1 subarray 1 -> {1} , {1, 3} = 2 subarrays 3 -> {3} = 1 subarray Input: arr[] = {1, 4, 2, 5, 3}Output: {5, 1, 3, 1, 1} Naive Solution: The naive approach revolves around the idea that: If smaller element is not found then count of subarrays = length of array – current index If element is found then count of subarrays = index of smaller element – current index The task can be solved using 2 loops. The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by the outer loop. If a smaller element is found then the index of that element – current index is stored as next, otherwise, the length – current index is stored. 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 count of subarraysvector<int> countOfSubArray(vector<int> arr){ int next, i, j; int n = arr.size(); vector<int> ans; for (i = 0; i < n; i++) { bool flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.push_back(next); flag = true; break; } } if (flag == false) { ans.push_back(next); } } return ans;} // Driver Codeint main(){ vector<int> arr{ 1, 4, 2, 5, 3 }; vector<int> ans = countOfSubArray(arr); for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; } return 0;} // Java program for the above approachimport java.util.ArrayList; class GFG { // Function to find the count of subarrays static ArrayList<Integer> countOfSubArray(int[] arr) { int next, i, j; int n = arr.length; ArrayList<Integer> ans = new ArrayList<Integer>(); for (i = 0; i < n; i++) { boolean flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.add(next); flag = true; break; } } if (flag == false) { ans.add(next); } } return ans; } // Driver Code public static void main(String args[]) { int[] arr = { 1, 4, 2, 5, 3 }; ArrayList<Integer> ans = countOfSubArray(arr); for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + " "); } }} // This code is contributed by gfgking. # Python code for the above approach # Function to find the count of subarraysdef countOfSubArray(arr): n = len(arr) ans = [] for i in range(n): flag = 0 # If the next smaller element # is not found then # length - current index # would be the answer next = n - i for j in range(i + 1, n): if arr[i] > arr[j]: # If the next smaller # element is found then # the difference of indices # will be the count next = j - i ans.append(next) flag = 1 break if flag == 0: ans.append(next) return ans # Driver Codearr = [1, 4, 2, 5, 3]ans = countOfSubArray(arr) for i in range(len(ans)): print(ans[i], end = " ") # This code is contributed by Potta Lokesh // C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the count of subarrays static List<int> countOfSubArray(int[] arr) { int next, i, j; int n = arr.Length; List<int> ans = new List<int>(); for (i = 0; i < n; i++) { bool flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.Add(next); flag = true; break; } } if (flag == false) { ans.Add(next); } } return ans; } // Driver Code public static void Main() { int[] arr = { 1, 4, 2, 5, 3 }; List<int> ans = countOfSubArray(arr); for (int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + " "); } }} // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to find the count of subarrays const countOfSubArray = (arr) => { let next, i, j; let n = arr.length; let ans = []; for (i = 0; i < n; i++) { let flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.push(next); flag = true; break; } } if (flag == false) { ans.push(next); } } return ans; } // Driver Code let arr = [1, 4, 2, 5, 3]; let ans = countOfSubArray(arr); for (let i = 0; i < ans.length; i++) { document.write(`${ans[i]} `); } // This code is contributed by rakeshsahni </script> 5 1 3 1 1 Time Complexity: O(N2) Auxiliary Space: O(1) Efficient Solution: This problem basically asks to find how far is the current index from the index of the next smaller number to the number at the current index. The most optimal way to solve this problem is by making use of a stack.Follow the below steps to solve the problem: Iterate over each number of the given array arr[] using the current index. If the stack is empty, push the current index to the stack. If the stack is not empty then do the following:If the number at the current index is lesser than the number of the index at top of the stack, push the current index.If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index If the number at the current index is lesser than the number of the index at top of the stack, push the current index. If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index Pop the stack once the number of days has been updated in the output list. Repeat the above steps for all the indices in the stack that are greater than the number at the current index. 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 determine how many count// of subarrays are possible// with each numbervector<int> countOfSubArray(vector<int> arr){ stack<int> st; // To store the answer vector<int> v; int n = arr.size(); // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.size() > 0 && arr[st.top()] >= arr[i]) { // Pop the element st.pop(); } if (st.size() == 0) { v.push_back(n - i); } else { v.push_back(st.top() - i); } // Push the current index st.push(i); } // reverse the output reverse(v.begin(), v.end()); return v;} // Driver Codeint main(){ // Given numbers vector<int> arr{ 1, 4, 2, 5, 3 }; // Function Call vector<int> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; } return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to determine how many count// of subarrays are possible// with each numberstatic Vector<Integer> countOfSubArray(int[] arr){ Stack<Integer> st = new Stack<Integer>(); // To store the answer Vector<Integer> v = new Vector<Integer>(); int n = arr.length; // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.size() > 0 && arr[st.peek()] >= arr[i]) { // Pop the element st.pop(); } if (st.size() == 0) { v.add(n - i); } else { v.add(st.peek() - i); } // Push the current index st.add(i); } // reverse the output Collections.reverse(v); return v;} // Driver Codepublic static void main(String[] args){ // Given numbers int []arr ={ 1, 4, 2, 5, 3 }; // Function Call Vector<Integer> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i)+ " "); } }} // This code is contributed by shikhasingrajput # Python program for the above approach # Function to determine how many count# of subarrays are possible# with each numberdef countOfSubArray(arr): st = [] # To store the answer v = [] n = len(arr) # Traverse all the numbers for i in range(n - 1,-1,-1): # Check if current index is the # next smaller element of # any previous indices while len(st) > 0 and arr[st[len(st)-1]] >= arr[i] : # Pop the element st.pop() if (len(st) == 0): v.append(n - i) else: v.append(st[len(st) - 1]- i) # Push the current index st.append(i) # reverse the output v = v[::-1] return v # Driver Code # Given numbersarr = [ 1, 4, 2, 5, 3 ] # Function Callans = countOfSubArray(arr) # Printing the resultfor i in range(len(ans)): print(ans[i],end = " ") # This code is contributed by shinjanpatra // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to determine how many count // of subarrays are possible // with each number static List<int> countOfSubArray(int[] arr) { Stack<int> st = new Stack<int>(); // To store the answer List<int> v = new List<int>(); int n = arr.Length; // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.Count > 0 && arr[st.Peek()] >= arr[i]) { // Pop the element st.Pop(); } if (st.Count == 0) { v.Add(n - i); } else { v.Add(st.Peek() - i); } // Push the current index st.Push(i); } // reverse the output v.Reverse(); return v; } // Driver Code public static void Main(String[] args) { // Given numbers int []arr ={ 1, 4, 2, 5, 3 }; // Function Call List<int> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.Count; i++) { Console.Write(ans[i]+ " "); } }} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // Function to determine how many count// of subarrays are possible// with each numberfunction countOfSubArray(arr){ let st = []; // To store the answer let v = []; let n = arr.length; // Traverse all the numbers for (let i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.length > 0 && arr[st[st.length-1]] >= arr[i]) { // Pop the element st.pop(); } if (st.length == 0) { v.push(n - i); } else { v.push(st[st.length - 1]- i); } // Push the current index st.push(i); } // reverse the output v.reverse(); return v;} // Driver Code // Given numberslet arr = [ 1, 4, 2, 5, 3 ]; // Function Calllet ans = countOfSubArray(arr); // Printing the resultfor (let i = 0; i < ans.length; i++) { document.write(ans[i]," ");} // This code is contributed by shinjanpatra </script> 5 1 3 1 1 Time Complexity: O(N) Auxiliary Space: O(N) rakeshsahni lokeshpotta20 gfgking ukasp shikhasingrajput 29AjayKumar sagartomar9927 shinjanpatra Algo-Geek 2021 subarray Algo Geek Arrays Stack Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if given matrix is Zero Division matrix Check if all duplicate elements in the Array are adjacent or not Find Characteristic Polynomial of a Square Matrix Find all substrings containing exactly K unique vowels Calculate the sum of sum of numbers in range L to R Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 25937, "s": 25909, "text": "\n04 Apr, 2022" }, { "code": null, "e": 26094, "s": 25937, "text": "Given an array arr[], the task is to find the count of subarrays starting from the current element that has a minimum element as the current element itself." }, { "code": null, "e": 26105, "s": 26094, "text": "Examples: " }, { "code": null, "e": 26250, "s": 26105, "text": "Input: arr[] = {2, 4, 2, 1, 3} Output: {3, 1, 1, 2, 1}Explanation: For the first element we can form 3 valid subarrays with the given condition " }, { "code": null, "e": 26301, "s": 26250, "text": "2 -> {2} , {2,4} , {2,4,2} = 3 subarrays and so on" }, { "code": null, "e": 26341, "s": 26301, "text": "4 -> {4} = 1 subarray" }, { "code": null, "e": 26381, "s": 26341, "text": "2 -> {2} = 1 subarray" }, { "code": null, "e": 26422, "s": 26381, "text": "1 -> {1} , {1, 3} = 2 subarrays" }, { "code": null, "e": 26462, "s": 26422, "text": "3 -> {3} = 1 subarray" }, { "code": null, "e": 26516, "s": 26462, "text": "Input: arr[] = {1, 4, 2, 5, 3}Output: {5, 1, 3, 1, 1}" }, { "code": null, "e": 26582, "s": 26516, "text": "Naive Solution: The naive approach revolves around the idea that:" }, { "code": null, "e": 26672, "s": 26582, "text": "If smaller element is not found then count of subarrays = length of array – current index" }, { "code": null, "e": 26759, "s": 26672, "text": "If element is found then count of subarrays = index of smaller element – current index" }, { "code": null, "e": 27086, "s": 26759, "text": "The task can be solved using 2 loops. The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by the outer loop. If a smaller element is found then the index of that element – current index is stored as next, otherwise, the length – current index is stored." }, { "code": null, "e": 27137, "s": 27086, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27141, "s": 27137, "text": "C++" }, { "code": null, "e": 27146, "s": 27141, "text": "Java" }, { "code": null, "e": 27154, "s": 27146, "text": "Python3" }, { "code": null, "e": 27157, "s": 27154, "text": "C#" }, { "code": null, "e": 27168, "s": 27157, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of subarraysvector<int> countOfSubArray(vector<int> arr){ int next, i, j; int n = arr.size(); vector<int> ans; for (i = 0; i < n; i++) { bool flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.push_back(next); flag = true; break; } } if (flag == false) { ans.push_back(next); } } return ans;} // Driver Codeint main(){ vector<int> arr{ 1, 4, 2, 5, 3 }; vector<int> ans = countOfSubArray(arr); for (int i = 0; i < ans.size(); i++) { cout << ans[i] << \" \"; } return 0;}", "e": 28265, "s": 27168, "text": null }, { "code": "// Java program for the above approachimport java.util.ArrayList; class GFG { // Function to find the count of subarrays static ArrayList<Integer> countOfSubArray(int[] arr) { int next, i, j; int n = arr.length; ArrayList<Integer> ans = new ArrayList<Integer>(); for (i = 0; i < n; i++) { boolean flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.add(next); flag = true; break; } } if (flag == false) { ans.add(next); } } return ans; } // Driver Code public static void main(String args[]) { int[] arr = { 1, 4, 2, 5, 3 }; ArrayList<Integer> ans = countOfSubArray(arr); for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + \" \"); } }} // This code is contributed by gfgking.", "e": 29395, "s": 28265, "text": null }, { "code": "# Python code for the above approach # Function to find the count of subarraysdef countOfSubArray(arr): n = len(arr) ans = [] for i in range(n): flag = 0 # If the next smaller element # is not found then # length - current index # would be the answer next = n - i for j in range(i + 1, n): if arr[i] > arr[j]: # If the next smaller # element is found then # the difference of indices # will be the count next = j - i ans.append(next) flag = 1 break if flag == 0: ans.append(next) return ans # Driver Codearr = [1, 4, 2, 5, 3]ans = countOfSubArray(arr) for i in range(len(ans)): print(ans[i], end = \" \") # This code is contributed by Potta Lokesh", "e": 30260, "s": 29395, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the count of subarrays static List<int> countOfSubArray(int[] arr) { int next, i, j; int n = arr.Length; List<int> ans = new List<int>(); for (i = 0; i < n; i++) { bool flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.Add(next); flag = true; break; } } if (flag == false) { ans.Add(next); } } return ans; } // Driver Code public static void Main() { int[] arr = { 1, 4, 2, 5, 3 }; List<int> ans = countOfSubArray(arr); for (int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + \" \"); } }} // This code is contributed by ukasp.", "e": 31346, "s": 30260, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the count of subarrays const countOfSubArray = (arr) => { let next, i, j; let n = arr.length; let ans = []; for (i = 0; i < n; i++) { let flag = false; // If the next smaller element // is not found then // length - current index // would be the answer next = n - i; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { // If the next smaller // element is found then // the difference of indices // will be the count next = j - i; ans.push(next); flag = true; break; } } if (flag == false) { ans.push(next); } } return ans; } // Driver Code let arr = [1, 4, 2, 5, 3]; let ans = countOfSubArray(arr); for (let i = 0; i < ans.length; i++) { document.write(`${ans[i]} `); } // This code is contributed by rakeshsahni </script>", "e": 32535, "s": 31346, "text": null }, { "code": null, "e": 32549, "s": 32538, "text": "5 1 3 1 1 " }, { "code": null, "e": 32596, "s": 32551, "text": "Time Complexity: O(N2) Auxiliary Space: O(1)" }, { "code": null, "e": 32877, "s": 32598, "text": "Efficient Solution: This problem basically asks to find how far is the current index from the index of the next smaller number to the number at the current index. The most optimal way to solve this problem is by making use of a stack.Follow the below steps to solve the problem:" }, { "code": null, "e": 32954, "s": 32879, "text": "Iterate over each number of the given array arr[] using the current index." }, { "code": null, "e": 33014, "s": 32954, "text": "If the stack is empty, push the current index to the stack." }, { "code": null, "e": 33360, "s": 33014, "text": "If the stack is not empty then do the following:If the number at the current index is lesser than the number of the index at top of the stack, push the current index.If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index" }, { "code": null, "e": 33479, "s": 33360, "text": "If the number at the current index is lesser than the number of the index at top of the stack, push the current index." }, { "code": null, "e": 33659, "s": 33479, "text": "If the number at the current index is greater than the number of the index at top of the stack, then update the count of subarrays as the index at top of the stack – current index" }, { "code": null, "e": 33734, "s": 33659, "text": "Pop the stack once the number of days has been updated in the output list." }, { "code": null, "e": 33845, "s": 33734, "text": "Repeat the above steps for all the indices in the stack that are greater than the number at the current index." }, { "code": null, "e": 33898, "s": 33847, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33904, "s": 33900, "text": "C++" }, { "code": null, "e": 33909, "s": 33904, "text": "Java" }, { "code": null, "e": 33917, "s": 33909, "text": "Python3" }, { "code": null, "e": 33920, "s": 33917, "text": "C#" }, { "code": null, "e": 33931, "s": 33920, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to determine how many count// of subarrays are possible// with each numbervector<int> countOfSubArray(vector<int> arr){ stack<int> st; // To store the answer vector<int> v; int n = arr.size(); // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.size() > 0 && arr[st.top()] >= arr[i]) { // Pop the element st.pop(); } if (st.size() == 0) { v.push_back(n - i); } else { v.push_back(st.top() - i); } // Push the current index st.push(i); } // reverse the output reverse(v.begin(), v.end()); return v;} // Driver Codeint main(){ // Given numbers vector<int> arr{ 1, 4, 2, 5, 3 }; // Function Call vector<int> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.size(); i++) { cout << ans[i] << \" \"; } return 0;}", "e": 35065, "s": 33931, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to determine how many count// of subarrays are possible// with each numberstatic Vector<Integer> countOfSubArray(int[] arr){ Stack<Integer> st = new Stack<Integer>(); // To store the answer Vector<Integer> v = new Vector<Integer>(); int n = arr.length; // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.size() > 0 && arr[st.peek()] >= arr[i]) { // Pop the element st.pop(); } if (st.size() == 0) { v.add(n - i); } else { v.add(st.peek() - i); } // Push the current index st.add(i); } // reverse the output Collections.reverse(v); return v;} // Driver Codepublic static void main(String[] args){ // Given numbers int []arr ={ 1, 4, 2, 5, 3 }; // Function Call Vector<Integer> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i)+ \" \"); } }} // This code is contributed by shikhasingrajput", "e": 36332, "s": 35065, "text": null }, { "code": "# Python program for the above approach # Function to determine how many count# of subarrays are possible# with each numberdef countOfSubArray(arr): st = [] # To store the answer v = [] n = len(arr) # Traverse all the numbers for i in range(n - 1,-1,-1): # Check if current index is the # next smaller element of # any previous indices while len(st) > 0 and arr[st[len(st)-1]] >= arr[i] : # Pop the element st.pop() if (len(st) == 0): v.append(n - i) else: v.append(st[len(st) - 1]- i) # Push the current index st.append(i) # reverse the output v = v[::-1] return v # Driver Code # Given numbersarr = [ 1, 4, 2, 5, 3 ] # Function Callans = countOfSubArray(arr) # Printing the resultfor i in range(len(ans)): print(ans[i],end = \" \") # This code is contributed by shinjanpatra", "e": 37252, "s": 36332, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to determine how many count // of subarrays are possible // with each number static List<int> countOfSubArray(int[] arr) { Stack<int> st = new Stack<int>(); // To store the answer List<int> v = new List<int>(); int n = arr.Length; // Traverse all the numbers for (int i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.Count > 0 && arr[st.Peek()] >= arr[i]) { // Pop the element st.Pop(); } if (st.Count == 0) { v.Add(n - i); } else { v.Add(st.Peek() - i); } // Push the current index st.Push(i); } // reverse the output v.Reverse(); return v; } // Driver Code public static void Main(String[] args) { // Given numbers int []arr ={ 1, 4, 2, 5, 3 }; // Function Call List<int> ans = countOfSubArray(arr); // Printing the result for (int i = 0; i < ans.Count; i++) { Console.Write(ans[i]+ \" \"); } }} // This code is contributed by 29AjayKumar", "e": 38454, "s": 37252, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to determine how many count// of subarrays are possible// with each numberfunction countOfSubArray(arr){ let st = []; // To store the answer let v = []; let n = arr.length; // Traverse all the numbers for (let i = n - 1; i >= 0; i--) { // Check if current index is the // next smaller element of // any previous indices while (st.length > 0 && arr[st[st.length-1]] >= arr[i]) { // Pop the element st.pop(); } if (st.length == 0) { v.push(n - i); } else { v.push(st[st.length - 1]- i); } // Push the current index st.push(i); } // reverse the output v.reverse(); return v;} // Driver Code // Given numberslet arr = [ 1, 4, 2, 5, 3 ]; // Function Calllet ans = countOfSubArray(arr); // Printing the resultfor (let i = 0; i < ans.length; i++) { document.write(ans[i],\" \");} // This code is contributed by shinjanpatra </script>", "e": 39544, "s": 38454, "text": null }, { "code": null, "e": 39558, "s": 39547, "text": "5 1 3 1 1 " }, { "code": null, "e": 39606, "s": 39560, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 39620, "s": 39608, "text": "rakeshsahni" }, { "code": null, "e": 39634, "s": 39620, "text": "lokeshpotta20" }, { "code": null, "e": 39642, "s": 39634, "text": "gfgking" }, { "code": null, "e": 39648, "s": 39642, "text": "ukasp" }, { "code": null, "e": 39665, "s": 39648, "text": "shikhasingrajput" }, { "code": null, "e": 39677, "s": 39665, "text": "29AjayKumar" }, { "code": null, "e": 39692, "s": 39677, "text": "sagartomar9927" }, { "code": null, "e": 39705, "s": 39692, "text": "shinjanpatra" }, { "code": null, "e": 39720, "s": 39705, "text": "Algo-Geek 2021" }, { "code": null, "e": 39729, "s": 39720, "text": "subarray" }, { "code": null, "e": 39739, "s": 39729, "text": "Algo Geek" }, { "code": null, "e": 39746, "s": 39739, "text": "Arrays" }, { "code": null, "e": 39752, "s": 39746, "text": "Stack" }, { "code": null, "e": 39759, "s": 39752, "text": "Arrays" }, { "code": null, "e": 39765, "s": 39759, "text": "Stack" }, { "code": null, "e": 39863, "s": 39765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39872, "s": 39863, "text": "Comments" }, { "code": null, "e": 39885, "s": 39872, "text": "Old Comments" }, { "code": null, "e": 39931, "s": 39885, "text": "Check if given matrix is Zero Division matrix" }, { "code": null, "e": 39996, "s": 39931, "text": "Check if all duplicate elements in the Array are adjacent or not" }, { "code": null, "e": 40046, "s": 39996, "text": "Find Characteristic Polynomial of a Square Matrix" }, { "code": null, "e": 40101, "s": 40046, "text": "Find all substrings containing exactly K unique vowels" }, { "code": null, "e": 40153, "s": 40101, "text": "Calculate the sum of sum of numbers in range L to R" }, { "code": null, "e": 40168, "s": 40153, "text": "Arrays in Java" }, { "code": null, "e": 40184, "s": 40168, "text": "Arrays in C/C++" }, { "code": null, "e": 40211, "s": 40184, "text": "Program for array rotation" }, { "code": null, "e": 40259, "s": 40211, "text": "Stack Data Structure (Introduction and Program)" } ]
How to create new Mongodb database using Node.js ? - GeeksforGeeks
20 Nov, 2020 mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project. Please refer this link for connect() method. Installing module: npm install mongodb Starting MongoDB server: mongod --dbpath=data --bind_ip 127.0.0.1 Data is the directory name where server is located. 127.0.0.1 ip address where server will be running. Data is the directory name where server is located. 127.0.0.1 ip address where server will be running. Project Structure: Filename index.js Javascript const MongoClient = require('mongodb'); // server locationconst url = 'mongodb://localhost:27017';MongoClient.connect(url).then((client) => { console.log('Database created'); // database name const db = client.db("GFGNodejs"); // collection name db.createCollection("GFGNEW");}) Output: Mongodb Database: Node.js-Misc Technical Scripter 2020 MongoDB Node.js Technical Scripter Web Technologies Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB updateOne() Method - db.Collection.updateOne() Installation of Node.js on Linux Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.readFile() Method Node.js fs.writeFile() Method
[ { "code": null, "e": 24534, "s": 24506, "text": "\n20 Nov, 2020" }, { "code": null, "e": 24826, "s": 24534, "text": "mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project." }, { "code": null, "e": 24871, "s": 24826, "text": "Please refer this link for connect() method." }, { "code": null, "e": 24890, "s": 24871, "text": "Installing module:" }, { "code": null, "e": 24911, "s": 24890, "text": "npm install mongodb\n" }, { "code": null, "e": 24936, "s": 24911, "text": "Starting MongoDB server:" }, { "code": null, "e": 24978, "s": 24936, "text": "mongod --dbpath=data --bind_ip 127.0.0.1\n" }, { "code": null, "e": 25081, "s": 24978, "text": "Data is the directory name where server is located. 127.0.0.1 ip address where server will be running." }, { "code": null, "e": 25134, "s": 25081, "text": "Data is the directory name where server is located. " }, { "code": null, "e": 25185, "s": 25134, "text": "127.0.0.1 ip address where server will be running." }, { "code": null, "e": 25204, "s": 25185, "text": "Project Structure:" }, { "code": null, "e": 25222, "s": 25204, "text": "Filename index.js" }, { "code": null, "e": 25233, "s": 25222, "text": "Javascript" }, { "code": "const MongoClient = require('mongodb'); // server locationconst url = 'mongodb://localhost:27017';MongoClient.connect(url).then((client) => { console.log('Database created'); // database name const db = client.db(\"GFGNodejs\"); // collection name db.createCollection(\"GFGNEW\");})", "e": 25542, "s": 25233, "text": null }, { "code": null, "e": 25550, "s": 25542, "text": "Output:" }, { "code": null, "e": 25568, "s": 25550, "text": "Mongodb Database:" }, { "code": null, "e": 25581, "s": 25568, "text": "Node.js-Misc" }, { "code": null, "e": 25605, "s": 25581, "text": "Technical Scripter 2020" }, { "code": null, "e": 25613, "s": 25605, "text": "MongoDB" }, { "code": null, "e": 25621, "s": 25613, "text": "Node.js" }, { "code": null, "e": 25640, "s": 25621, "text": "Technical Scripter" }, { "code": null, "e": 25657, "s": 25640, "text": "Web Technologies" }, { "code": null, "e": 25673, "s": 25657, "text": "Write From Home" }, { "code": null, "e": 25771, "s": 25673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25809, "s": 25771, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 25834, "s": 25809, "text": "MongoDB - limit() Method" }, { "code": null, "e": 25861, "s": 25834, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 25897, "s": 25861, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 25952, "s": 25897, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 25985, "s": 25952, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26018, "s": 25985, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 26066, "s": 26018, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26095, "s": 26066, "text": "Node.js fs.readFile() Method" } ]
Cleaning Financial Time Series data with Python | by Ronald Wahome | Towards Data Science
A hypothetical company, ABC Financial Services Corp makes financial investments decisions on behalf of it’s clients based on the company’s economic research. A lot of these decisions involve speculating on future prices of financial instruments. ABC Corp utilizes several economic indicators but there is one in particular that is heavily weighted in their analysis and that is the University of Michigan’s Consumer Sentiment Survey (CSI). The only problem is that they have to wait for the release of this data (released once a month) which erodes some of ABC’s edge in the market. To stay competitive, they would like a way to predict this number ahead of time. I propose using a form of Machine Learning (ML) to make time series predictions on the final Consumer Sentiment number that’s yet to be released. To do this we are going to use other economic data (as features for the ML algorithm) which is released before the CSI. We’ll use this collection of data to construct a final dataset that is ready for a predictive algorithm. The historical datasets that we’ll use are listed below and can be downloaded from the following links: The Dow Jones Index : Source (Yahoo Finance) US Unemployment (Jobless Claims) data from the US Department of Labor : Source (Federal Reserve) Historical price of Crude Oil in the open market : Source (Federal Reserve) New Housing Starts from US Census Bureau : Source (Federal Reserve) Total Vehicles Sold : Source (Federal Reserve) Retail Sales data from US Census Bureau : Source (Federal Reserve) Federal Interest Rates : Source (Federal Reserve) The University of Michigan’s Consumer Sentiment Survey — data to predict : Source (University of Michigan) We’ll use Python with the Pandas library to handle our data cleaning task. We are going to use can use Jupyter Notebook which is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. It is a really great tool for data scientists. You can head over to Anaconda.org to download the latest version which comes pre-loaded with most data science libraries. We will combine the above datasets into one table using pandas and then do the necessary cleaning. Some of the above datasets have been seasonally adjusted to remove the influences of predictable seasonal patterns. In actual prediction learning/testing, we would experiment with both types of datasets. Data cleaning is highly dependent on the type of data and the task you’re trying to achieve. In our case we combine data from different sources and clean up the resulting dataframe. In image classification data, we may have to reshape and resize the images and create labels while a sentiment analysis task may need to be checked for grammatical errors and keyword extraction. To do this, we’ll need a few imports from the python library as shown below. # Import necessary modulesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom scipy import statsfrom datetime import datetimefrom functools import reduceimport datetime Import the data tables into Pandas Dataframe. # load all the datasets to pandas DataFramesdow = pd.read_csv('data/Dow Jones Industrial Average DJI.csv')unemp = pd.read_csv('data/Civilian Unemployment Rate UNRATE.csv')oil = pd.read_csv('data/Crude Oil Prices MCOILBRENTEU.csv')hstarts = pd.read_csv('data/Housing Starts HOUST.csv')cars = pd.read_csv('data/Total Vehicle SalesTOTALSA .csv')retail = pd.read_csv('data/Advance Retail Sales_RSXFS.csv')fedrate = pd.read_csv('data/Federal Interest Rates FEDFUNDS.csv')umcsi = pd.read_excel('data/consumer_sent_UMCH_tbmics.xls',header=3) After loading up the data, the first thing we do is visually inspect the data to understand how it is structured, it’s contents and to note anything out of the ordinary. Most of the data that you are going to come across is at least thousands of rows long so I like to inspect random chucks of rows at a time. We use the head() and tail() functions to inspect the top and the bottom sections of the table respectively. # view the top of the dow jones tabledow.head() # view the top of the umcsi tableumcsi.head() # view the bottom of the data tableumcsi.tail() We can also use a loop to iterate through all tables and get back the sizes. From this step we can start to anticipate the kinds of joins we need to do or decide whether we statistically have enough data to get started. Remember bad data is worse than no data. # get the shape of the different datasetsdflist = [dow, unemp, oil, hstarts, cars, retail, fedrate, umcsi]for i, dfr in enumerate(dflist): print(dflist[i].shape) Another useful pandas tool when we are inspecting data is the describe() function that gives a snapshot of the general statistics of all the numerical columns in the data. # we look at the statistical charateristics of the datsetsfor i, dfr in enumerate(dflist): print(dflist[i].describe()) We also want to know if we are dealing with data containing null values as this can result in bad data if ignored. One way to get the null values is to use the isnull() function to extract this information. We use a loop below to iterate over all the data tables. # see which datasets have null valuesfor i, dfr in enumerate(dflist): print(dflist[i].isnull().sum().sum()) Some of the observations below are not apparent from the images above but are visible from the original notebook available here in my GitHub repository. In this case, the data we acquired is not overly complicated with hundreds of columns but it is good to bear in mind that this is not always the case and we must be comfortable handling really large messy data. From the inspections above, there are some things that need to be rectified before we can our achieve a final clean dataset. The date formats need to be converted to a uniform format across all datasets. The date ranges are also very inconsistent. The start dates range from 1947 to 1992. The dates in umcsi are in two columns (String month & float year) making it hard to merge with other datsets on that column. umcsi also has 3 null values so we have to remove entire rows where this exists. For our purposes, the dow dataframe also has extra columns so we will need to get rid of some of them. These are just some of the modifications that I can observe but there is likely going to be other complications. It is also necessary to comment your code so your colleagues can understand what you are doing. At some point we also have to change the date format from String to a format that supports plotting. The Dow Jones data comes with a lot of extra columns that we don’t need in our final dataframe so we are going to use pandas drop function to loose the extra columns. # drop the unnecessary columns dow.drop(['Open','High','Low','Adj Close','Volume'],axis=1,inplace=True)# view the final table after dropping unnecessary columnsdow.head() # rename columns to upper case to match other dfsdow.columns = ['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'ADJ CLOSE', 'VOLUME']# view result after renaming columnsdow.head() Most of these steps can be combined into fewer steps but I break them down so we can follow along and also we can confirm that we are achieving the intended results. Next we drop those columns that have null values from the data table. There are times when we may need to combine these null columns and then drop them later where we can fill in the values from other tables or gain additional columns (information). The inplace flag below permanently removes the dropped rows. # drop NaN Valuesumcsi.dropna(inplace=True) The umcsi table contains year values as data type float which may be problematic when we start getting decimals numbers for years. I created a function that creates a new integer column from the float column. We can then drop the old float year column inplace(). Sometimes the date columns are in string format and we have to parse the date using pandas built in functions or we can create our own columns for those unique cases. And there will be many of those cases when you’re cleaning data. # create 'Year' column with int values instead of float# casting functiondef to_int(x): return int(x)# use function to convert floats to intumcsi['Year'] = umcsi['Unnamed: 1'].apply(to_int)umcsi.head() Observe that we have month and year as separate columns which need to be combined to match the date format from the rest of the data tables. For that we use pandas datetime functions which are very capable of handling most date and time manipulations. As it turns out, the other tables have dates in string data type so we will also have to change the umcsi date column to string. This will make sense because as a time series, any table joinings will be on the date column as the key. # combine year columns to one column formatumcsi['DATE'] = umcsi.apply(lambda x: datetime.datetime.strptime("{0} {1}".format(x['Year'],x['DATE OF SURVEY']), "%Y %B"),axis=1)# turn date format to string to match other DATE's. We'll merge the data on this column so this is a vital step.def to_str(x): return str(x)[:10]umcsi['DATE'] = umcsi['DATE'].apply(to_str)umcsi.head() Our umcsi table is looking good with the exception of the old float date column and the month column so we have to get rid of that. We should also move the final date column to the front column for the sake of staying organized. # drop unneeded columns columnumcsi.drop(['Unnamed: 1','Year','DATE OF SURVEY'], axis=1, inplace=True)# move 'DATE' column to the frontcols = list(umcsi)cols.insert(0, cols.pop(cols.index('DATE')))umcsi = umcsi.reindex(columns = cols)umcsi.head() With all tables in a cohesive format, we can go ahead and join them and do some final cleanup steps. We shall concatenate the tables with date column as the key. We’ll use the all powerful lambda function for this one to get it done on the fly. Actually we will wrap a few more functions to demonstrate just how powerful pandas is for data manipulations. # concatenate all dataframes into one final dataframe dfs = [dow,unemp,oil,hstarts,cars,retail,fedrate,umcsi] # we perform the joins on DATE column as key and drop null valuesdf = reduce(lambda left,right: pd.merge(left,right,on='DATE', how='outer'), dfs).dropna() df.head(5) We now have a final pandas dataframe even though it still needs a bit more cleanup. Next we have to remove outliers from our final table since these outliers are likely to introduce a lot of noise to our machine learning task later on. # remove all rows with outliers in at least one rowdf = df[(np.abs(stats.zscore(df.drop(['DATE'], axis=1))) < 3).all(axis=1)]# show final size after removing outliersdf.shape Python has a specialized format for dealing with time columns which is very efficient. We can extract the datetime.datetime format from current string format using the strip() function. Again we’ll use the lambda function to apply it to all rows on the fly. # change the DATE column from String to python's # datetime.datetime format df['DATE'] = df['DATE'].apply(lambda x: datetime.datetime.strptime(x,"%Y-%m-%d")) The final step is to rename the columns to more user friendly names for those that go on to consume this data. # rename columns to more user friendly namesdf.columns = ['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'ADJ CLOSE', 'VOLUME', 'UNEMP %','OIL PRICE','NEW HOMES','NEW CARS SOLD', 'RETAIL SALES','FED INTRST %','CSI' ]# preview final tabledf.head(20) Data cleaning comes in all shapes and sizes and there is no one template to handle all situations. While we do not know how the data will perform for the task of predicting the CSI, we do know that the data supplied has been processed to facilitate fast adoption and testing in a ML enviroment. Sure we could have engineered more features and processed the current ones some more but that would be too presumptuous on our part as to how the ML team would proceed. For example we could have normalized the features to a uniform scale but did not. In conclusion, like most tasks in the data science world, the best we can do is keep asking questions in the right team and experiment deeper based on those questions.
[ { "code": null, "e": 612, "s": 172, "text": "A hypothetical company, ABC Financial Services Corp makes financial investments decisions on behalf of it’s clients based on the company’s economic research. A lot of these decisions involve speculating on future prices of financial instruments. ABC Corp utilizes several economic indicators but there is one in particular that is heavily weighted in their analysis and that is the University of Michigan’s Consumer Sentiment Survey (CSI)." }, { "code": null, "e": 982, "s": 612, "text": "The only problem is that they have to wait for the release of this data (released once a month) which erodes some of ABC’s edge in the market. To stay competitive, they would like a way to predict this number ahead of time. I propose using a form of Machine Learning (ML) to make time series predictions on the final Consumer Sentiment number that’s yet to be released." }, { "code": null, "e": 1207, "s": 982, "text": "To do this we are going to use other economic data (as features for the ML algorithm) which is released before the CSI. We’ll use this collection of data to construct a final dataset that is ready for a predictive algorithm." }, { "code": null, "e": 1311, "s": 1207, "text": "The historical datasets that we’ll use are listed below and can be downloaded from the following links:" }, { "code": null, "e": 1356, "s": 1311, "text": "The Dow Jones Index : Source (Yahoo Finance)" }, { "code": null, "e": 1453, "s": 1356, "text": "US Unemployment (Jobless Claims) data from the US Department of Labor : Source (Federal Reserve)" }, { "code": null, "e": 1529, "s": 1453, "text": "Historical price of Crude Oil in the open market : Source (Federal Reserve)" }, { "code": null, "e": 1597, "s": 1529, "text": "New Housing Starts from US Census Bureau : Source (Federal Reserve)" }, { "code": null, "e": 1644, "s": 1597, "text": "Total Vehicles Sold : Source (Federal Reserve)" }, { "code": null, "e": 1711, "s": 1644, "text": "Retail Sales data from US Census Bureau : Source (Federal Reserve)" }, { "code": null, "e": 1761, "s": 1711, "text": "Federal Interest Rates : Source (Federal Reserve)" }, { "code": null, "e": 1868, "s": 1761, "text": "The University of Michigan’s Consumer Sentiment Survey — data to predict : Source (University of Michigan)" }, { "code": null, "e": 2313, "s": 1868, "text": "We’ll use Python with the Pandas library to handle our data cleaning task. We are going to use can use Jupyter Notebook which is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. It is a really great tool for data scientists. You can head over to Anaconda.org to download the latest version which comes pre-loaded with most data science libraries." }, { "code": null, "e": 2616, "s": 2313, "text": "We will combine the above datasets into one table using pandas and then do the necessary cleaning. Some of the above datasets have been seasonally adjusted to remove the influences of predictable seasonal patterns. In actual prediction learning/testing, we would experiment with both types of datasets." }, { "code": null, "e": 2993, "s": 2616, "text": "Data cleaning is highly dependent on the type of data and the task you’re trying to achieve. In our case we combine data from different sources and clean up the resulting dataframe. In image classification data, we may have to reshape and resize the images and create labels while a sentiment analysis task may need to be checked for grammatical errors and keyword extraction." }, { "code": null, "e": 3070, "s": 2993, "text": "To do this, we’ll need a few imports from the python library as shown below." }, { "code": null, "e": 3299, "s": 3070, "text": "# Import necessary modulesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom scipy import statsfrom datetime import datetimefrom functools import reduceimport datetime" }, { "code": null, "e": 3345, "s": 3299, "text": "Import the data tables into Pandas Dataframe." }, { "code": null, "e": 3896, "s": 3345, "text": "# load all the datasets to pandas DataFramesdow = pd.read_csv('data/Dow Jones Industrial Average DJI.csv')unemp = pd.read_csv('data/Civilian Unemployment Rate UNRATE.csv')oil = pd.read_csv('data/Crude Oil Prices MCOILBRENTEU.csv')hstarts = pd.read_csv('data/Housing Starts HOUST.csv')cars = pd.read_csv('data/Total Vehicle SalesTOTALSA .csv')retail = pd.read_csv('data/Advance Retail Sales_RSXFS.csv')fedrate = pd.read_csv('data/Federal Interest Rates FEDFUNDS.csv')umcsi = pd.read_excel('data/consumer_sent_UMCH_tbmics.xls',header=3)" }, { "code": null, "e": 4206, "s": 3896, "text": "After loading up the data, the first thing we do is visually inspect the data to understand how it is structured, it’s contents and to note anything out of the ordinary. Most of the data that you are going to come across is at least thousands of rows long so I like to inspect random chucks of rows at a time." }, { "code": null, "e": 4315, "s": 4206, "text": "We use the head() and tail() functions to inspect the top and the bottom sections of the table respectively." }, { "code": null, "e": 4363, "s": 4315, "text": "# view the top of the dow jones tabledow.head()" }, { "code": null, "e": 4409, "s": 4363, "text": "# view the top of the umcsi tableumcsi.head()" }, { "code": null, "e": 4457, "s": 4409, "text": "# view the bottom of the data tableumcsi.tail()" }, { "code": null, "e": 4718, "s": 4457, "text": "We can also use a loop to iterate through all tables and get back the sizes. From this step we can start to anticipate the kinds of joins we need to do or decide whether we statistically have enough data to get started. Remember bad data is worse than no data." }, { "code": null, "e": 4880, "s": 4718, "text": "# get the shape of the different datasetsdflist = [dow, unemp, oil, hstarts, cars, retail, fedrate, umcsi]for i, dfr in enumerate(dflist): print(dflist[i].shape)" }, { "code": null, "e": 5052, "s": 4880, "text": "Another useful pandas tool when we are inspecting data is the describe() function that gives a snapshot of the general statistics of all the numerical columns in the data." }, { "code": null, "e": 5174, "s": 5052, "text": "# we look at the statistical charateristics of the datsetsfor i, dfr in enumerate(dflist): print(dflist[i].describe())" }, { "code": null, "e": 5438, "s": 5174, "text": "We also want to know if we are dealing with data containing null values as this can result in bad data if ignored. One way to get the null values is to use the isnull() function to extract this information. We use a loop below to iterate over all the data tables." }, { "code": null, "e": 5549, "s": 5438, "text": "# see which datasets have null valuesfor i, dfr in enumerate(dflist): print(dflist[i].isnull().sum().sum())" }, { "code": null, "e": 5702, "s": 5549, "text": "Some of the observations below are not apparent from the images above but are visible from the original notebook available here in my GitHub repository." }, { "code": null, "e": 5913, "s": 5702, "text": "In this case, the data we acquired is not overly complicated with hundreds of columns but it is good to bear in mind that this is not always the case and we must be comfortable handling really large messy data." }, { "code": null, "e": 6038, "s": 5913, "text": "From the inspections above, there are some things that need to be rectified before we can our achieve a final clean dataset." }, { "code": null, "e": 6117, "s": 6038, "text": "The date formats need to be converted to a uniform format across all datasets." }, { "code": null, "e": 6202, "s": 6117, "text": "The date ranges are also very inconsistent. The start dates range from 1947 to 1992." }, { "code": null, "e": 6327, "s": 6202, "text": "The dates in umcsi are in two columns (String month & float year) making it hard to merge with other datsets on that column." }, { "code": null, "e": 6408, "s": 6327, "text": "umcsi also has 3 null values so we have to remove entire rows where this exists." }, { "code": null, "e": 6511, "s": 6408, "text": "For our purposes, the dow dataframe also has extra columns so we will need to get rid of some of them." }, { "code": null, "e": 6624, "s": 6511, "text": "These are just some of the modifications that I can observe but there is likely going to be other complications." }, { "code": null, "e": 6720, "s": 6624, "text": "It is also necessary to comment your code so your colleagues can understand what you are doing." }, { "code": null, "e": 6821, "s": 6720, "text": "At some point we also have to change the date format from String to a format that supports plotting." }, { "code": null, "e": 6988, "s": 6821, "text": "The Dow Jones data comes with a lot of extra columns that we don’t need in our final dataframe so we are going to use pandas drop function to loose the extra columns." }, { "code": null, "e": 7159, "s": 6988, "text": "# drop the unnecessary columns dow.drop(['Open','High','Low','Adj Close','Volume'],axis=1,inplace=True)# view the final table after dropping unnecessary columnsdow.head()" }, { "code": null, "e": 7332, "s": 7159, "text": "# rename columns to upper case to match other dfsdow.columns = ['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'ADJ CLOSE', 'VOLUME']# view result after renaming columnsdow.head()" }, { "code": null, "e": 7748, "s": 7332, "text": "Most of these steps can be combined into fewer steps but I break them down so we can follow along and also we can confirm that we are achieving the intended results. Next we drop those columns that have null values from the data table. There are times when we may need to combine these null columns and then drop them later where we can fill in the values from other tables or gain additional columns (information)." }, { "code": null, "e": 7809, "s": 7748, "text": "The inplace flag below permanently removes the dropped rows." }, { "code": null, "e": 7853, "s": 7809, "text": "# drop NaN Valuesumcsi.dropna(inplace=True)" }, { "code": null, "e": 8348, "s": 7853, "text": "The umcsi table contains year values as data type float which may be problematic when we start getting decimals numbers for years. I created a function that creates a new integer column from the float column. We can then drop the old float year column inplace(). Sometimes the date columns are in string format and we have to parse the date using pandas built in functions or we can create our own columns for those unique cases. And there will be many of those cases when you’re cleaning data." }, { "code": null, "e": 8553, "s": 8348, "text": "# create 'Year' column with int values instead of float# casting functiondef to_int(x): return int(x)# use function to convert floats to intumcsi['Year'] = umcsi['Unnamed: 1'].apply(to_int)umcsi.head()" }, { "code": null, "e": 9039, "s": 8553, "text": "Observe that we have month and year as separate columns which need to be combined to match the date format from the rest of the data tables. For that we use pandas datetime functions which are very capable of handling most date and time manipulations. As it turns out, the other tables have dates in string data type so we will also have to change the umcsi date column to string. This will make sense because as a time series, any table joinings will be on the date column as the key." }, { "code": null, "e": 9416, "s": 9039, "text": "# combine year columns to one column formatumcsi['DATE'] = umcsi.apply(lambda x: datetime.datetime.strptime(\"{0} {1}\".format(x['Year'],x['DATE OF SURVEY']), \"%Y %B\"),axis=1)# turn date format to string to match other DATE's. We'll merge the data on this column so this is a vital step.def to_str(x): return str(x)[:10]umcsi['DATE'] = umcsi['DATE'].apply(to_str)umcsi.head()" }, { "code": null, "e": 9645, "s": 9416, "text": "Our umcsi table is looking good with the exception of the old float date column and the month column so we have to get rid of that. We should also move the final date column to the front column for the sake of staying organized." }, { "code": null, "e": 9892, "s": 9645, "text": "# drop unneeded columns columnumcsi.drop(['Unnamed: 1','Year','DATE OF SURVEY'], axis=1, inplace=True)# move 'DATE' column to the frontcols = list(umcsi)cols.insert(0, cols.pop(cols.index('DATE')))umcsi = umcsi.reindex(columns = cols)umcsi.head()" }, { "code": null, "e": 10247, "s": 9892, "text": "With all tables in a cohesive format, we can go ahead and join them and do some final cleanup steps. We shall concatenate the tables with date column as the key. We’ll use the all powerful lambda function for this one to get it done on the fly. Actually we will wrap a few more functions to demonstrate just how powerful pandas is for data manipulations." }, { "code": null, "e": 10524, "s": 10247, "text": "# concatenate all dataframes into one final dataframe dfs = [dow,unemp,oil,hstarts,cars,retail,fedrate,umcsi] # we perform the joins on DATE column as key and drop null valuesdf = reduce(lambda left,right: pd.merge(left,right,on='DATE', how='outer'), dfs).dropna() df.head(5)" }, { "code": null, "e": 10760, "s": 10524, "text": "We now have a final pandas dataframe even though it still needs a bit more cleanup. Next we have to remove outliers from our final table since these outliers are likely to introduce a lot of noise to our machine learning task later on." }, { "code": null, "e": 10935, "s": 10760, "text": "# remove all rows with outliers in at least one rowdf = df[(np.abs(stats.zscore(df.drop(['DATE'], axis=1))) < 3).all(axis=1)]# show final size after removing outliersdf.shape" }, { "code": null, "e": 11193, "s": 10935, "text": "Python has a specialized format for dealing with time columns which is very efficient. We can extract the datetime.datetime format from current string format using the strip() function. Again we’ll use the lambda function to apply it to all rows on the fly." }, { "code": null, "e": 11352, "s": 11193, "text": "# change the DATE column from String to python's # datetime.datetime format df['DATE'] = df['DATE'].apply(lambda x: datetime.datetime.strptime(x,\"%Y-%m-%d\"))" }, { "code": null, "e": 11463, "s": 11352, "text": "The final step is to rename the columns to more user friendly names for those that go on to consume this data." }, { "code": null, "e": 11724, "s": 11463, "text": "# rename columns to more user friendly namesdf.columns = ['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'ADJ CLOSE', 'VOLUME', 'UNEMP %','OIL PRICE','NEW HOMES','NEW CARS SOLD', 'RETAIL SALES','FED INTRST %','CSI' ]# preview final tabledf.head(20)" }, { "code": null, "e": 11823, "s": 11724, "text": "Data cleaning comes in all shapes and sizes and there is no one template to handle all situations." }, { "code": null, "e": 12019, "s": 11823, "text": "While we do not know how the data will perform for the task of predicting the CSI, we do know that the data supplied has been processed to facilitate fast adoption and testing in a ML enviroment." }, { "code": null, "e": 12270, "s": 12019, "text": "Sure we could have engineered more features and processed the current ones some more but that would be too presumptuous on our part as to how the ML team would proceed. For example we could have normalized the features to a uniform scale but did not." } ]
Python os.read() Method
Python method read() reads at most n bytes from file desciptor fd, return a string containing the bytes read. If the end of file referred to by fd has been reached, an empty string is returned. Following is the syntax for read() method − os.read(fd,n) fd − This is the file descriptor of the file. fd − This is the file descriptor of the file. n − These are n bytes from file descriptor fd. n − These are n bytes from file descriptor fd. This method returns a string containing the bytes read. The following example shows the usage of read() method. # !/usr/bin/python import os, sys # Open a file fd = os.open("f1.txt",os.O_RDWR) # Reading text ret = os.read(fd,12) print ret # Close opened file os.close(fd) print "Closed the file successfully!!" Let us compile and run the above program, this will print the contents of file f1.txt − This is test Closed the file successfully!! 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": 2438, "s": 2244, "text": "Python method read() reads at most n bytes from file desciptor fd, return a string containing the bytes read. If the end of file referred to by fd has been reached, an empty string is returned." }, { "code": null, "e": 2482, "s": 2438, "text": "Following is the syntax for read() method −" }, { "code": null, "e": 2497, "s": 2482, "text": "os.read(fd,n)\n" }, { "code": null, "e": 2543, "s": 2497, "text": "fd − This is the file descriptor of the file." }, { "code": null, "e": 2589, "s": 2543, "text": "fd − This is the file descriptor of the file." }, { "code": null, "e": 2636, "s": 2589, "text": "n − These are n bytes from file descriptor fd." }, { "code": null, "e": 2683, "s": 2636, "text": "n − These are n bytes from file descriptor fd." }, { "code": null, "e": 2739, "s": 2683, "text": "This method returns a string containing the bytes read." }, { "code": null, "e": 2795, "s": 2739, "text": "The following example shows the usage of read() method." }, { "code": null, "e": 2998, "s": 2795, "text": "# !/usr/bin/python\n\nimport os, sys\n# Open a file\nfd = os.open(\"f1.txt\",os.O_RDWR)\n\t\n# Reading text\nret = os.read(fd,12)\nprint ret\n\n# Close opened file\nos.close(fd)\nprint \"Closed the file successfully!!\"" }, { "code": null, "e": 3086, "s": 2998, "text": "Let us compile and run the above program, this will print the contents of file f1.txt −" }, { "code": null, "e": 3131, "s": 3086, "text": "This is test\nClosed the file successfully!!\n" }, { "code": null, "e": 3168, "s": 3131, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3184, "s": 3168, "text": " Malhar Lathkar" }, { "code": null, "e": 3217, "s": 3184, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3236, "s": 3217, "text": " Arnab Chakraborty" }, { "code": null, "e": 3271, "s": 3236, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3293, "s": 3271, "text": " In28Minutes Official" }, { "code": null, "e": 3327, "s": 3293, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3355, "s": 3327, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3390, "s": 3355, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3404, "s": 3390, "text": " Lets Kode It" }, { "code": null, "e": 3437, "s": 3404, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3454, "s": 3437, "text": " Abhilash Nelson" }, { "code": null, "e": 3461, "s": 3454, "text": " Print" }, { "code": null, "e": 3472, "s": 3461, "text": " Add Notes" } ]
JavaFX - UI Controls
Every user interface considers the following three main aspects − UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial. UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter. Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. JavaFX provides several classes in the package javafx.scene.control. To create various GUI components (controls), JavaFX supports several controls such as date picker, button text field, etc. Each control is represented by a class; you can create a control by instantiating its respective class. Following is the list of commonly used controls while the GUI is designed using JavaFX. Label A Label object is a component for placing text. Button This class creates a labeled button. ColorPicker A ColorPicker provides a pane of controls designed to allow a user to manipulate and select a color. CheckBox A CheckBox is a graphical component that can be in either an on(true) or off (false) state. RadioButton The RadioButton class is a graphical component, which can either be in a ON (true) or OFF (false) state in a group. ListView A ListView component presents the user with a scrolling list of text items. TextField A TextField object is a text component that allows for the editing of a single line of text. PasswordField A PasswordField object is a text component specialized for password entry. Scrollbar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values. FileChooser A FileChooser control represents a dialog window from which the user can select a file. ProgressBar As the task progresses towards completion, the progress bar displays the task's percentage of completion. Slider A Slider lets the user graphically select a value by sliding a knob within a bounded interval. The following program is an example which displays a login page in JavaFX. Here, we are using the controls label, text field, password field and button. Save this code in a file with the name LoginPage.java. import javafx.application.Application; import static javafx.application.Application.launch; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class LoginPage extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text("Email"); //creating label password Text text2 = new Text("Password"); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password PasswordField textField2 = new PasswordField(); //Creating Buttons Button button1 = new Button("Submit"); Button button2 = new Button("Clear"); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); //Styling nodes button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;"); button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;"); text1.setStyle("-fx-font: normal bold 20px 'serif' "); text2.setStyle("-fx-font: normal bold 20px 'serif' "); gridPane.setStyle("-fx-background-color: BEIGE;"); //Creating a scene object Scene scene = new Scene(gridPane); //Setting title to the Stage stage.setTitle("CSS Example"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac LoginPage.java java LoginPage On executing, the above program generates a JavaFX window as shown below. The following program is an example of a registration form, which demonstrates controls in JavaFX such as Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice List, etc. Save this code in a file with the name Registration.java. import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.DatePicker; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.ToggleButton; import javafx.stage.Stage; public class Registration extends Application { @Override public void start(Stage stage) { //Label for name Text nameLabel = new Text("Name"); //Text field for name TextField nameText = new TextField(); //Label for date of birth Text dobLabel = new Text("Date of birth"); //date picker to choose date DatePicker datePicker = new DatePicker(); //Label for gender Text genderLabel = new Text("gender"); //Toggle group of radio buttons ToggleGroup groupGender = new ToggleGroup(); RadioButton maleRadio = new RadioButton("male"); maleRadio.setToggleGroup(groupGender); RadioButton femaleRadio = new RadioButton("female"); femaleRadio.setToggleGroup(groupGender); //Label for reservation Text reservationLabel = new Text("Reservation"); //Toggle button for reservation ToggleButton Reservation = new ToggleButton(); ToggleButton yes = new ToggleButton("Yes"); ToggleButton no = new ToggleButton("No"); ToggleGroup groupReservation = new ToggleGroup(); yes.setToggleGroup(groupReservation); no.setToggleGroup(groupReservation); //Label for technologies known Text technologiesLabel = new Text("Technologies Known"); //check box for education CheckBox javaCheckBox = new CheckBox("Java"); javaCheckBox.setIndeterminate(false); //check box for education CheckBox dotnetCheckBox = new CheckBox("DotNet"); javaCheckBox.setIndeterminate(false); //Label for education Text educationLabel = new Text("Educational qualification"); //list View for educational qualification ObservableList<String> names = FXCollections.observableArrayList( "Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd"); ListView<String> educationListView = new ListView<String>(names); //Label for location Text locationLabel = new Text("location"); //Choice box for location ChoiceBox locationchoiceBox = new ChoiceBox(); locationchoiceBox.getItems().addAll ("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam"); //Label for register Button buttonRegister = new Button("Register"); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(500, 500); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(nameLabel, 0, 0); gridPane.add(nameText, 1, 0); gridPane.add(dobLabel, 0, 1); gridPane.add(datePicker, 1, 1); gridPane.add(genderLabel, 0, 2); gridPane.add(maleRadio, 1, 2); gridPane.add(femaleRadio, 2, 2); gridPane.add(reservationLabel, 0, 3); gridPane.add(yes, 1, 3); gridPane.add(no, 2, 3); gridPane.add(technologiesLabel, 0, 4); gridPane.add(javaCheckBox, 1, 4); gridPane.add(dotnetCheckBox, 2, 4); gridPane.add(educationLabel, 0, 5); gridPane.add(educationListView, 1, 5); gridPane.add(locationLabel, 0, 6); gridPane.add(locationchoiceBox, 1, 6); gridPane.add(buttonRegister, 2, 8); //Styling nodes buttonRegister.setStyle( "-fx-background-color: darkslateblue; -fx-textfill: white;"); nameLabel.setStyle("-fx-font: normal bold 15px 'serif' "); dobLabel.setStyle("-fx-font: normal bold 15px 'serif' "); genderLabel.setStyle("-fx-font: normal bold 15px 'serif' "); reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' "); technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' "); educationLabel.setStyle("-fx-font: normal bold 15px 'serif' "); locationLabel.setStyle("-fx-font: normal bold 15px 'serif' "); //Setting the back ground color gridPane.setStyle("-fx-background-color: BEIGE;"); //Creating a scene object Scene scene = new Scene(gridPane); //Setting title to the Stage stage.setTitle("Registration Form"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac Registration.java java Registration On executing, the above program generates a JavaFX window as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 1966, "s": 1900, "text": "Every user interface considers the following three main aspects −" }, { "code": null, "e": 2198, "s": 1966, "text": "UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial." }, { "code": null, "e": 2430, "s": 2198, "text": "UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial." }, { "code": null, "e": 2624, "s": 2430, "text": "Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter." }, { "code": null, "e": 2818, "s": 2624, "text": "Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter." }, { "code": null, "e": 2957, "s": 2818, "text": "Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter." }, { "code": null, "e": 3096, "s": 2957, "text": "Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter." }, { "code": null, "e": 3288, "s": 3096, "text": "JavaFX provides several classes in the package javafx.scene.control. To create various GUI components (controls), JavaFX supports several controls such as date picker, button text field, etc." }, { "code": null, "e": 3392, "s": 3288, "text": "Each control is represented by a class; you can create a control by instantiating its respective class." }, { "code": null, "e": 3480, "s": 3392, "text": "Following is the list of commonly used controls while the GUI is designed using JavaFX." }, { "code": null, "e": 3486, "s": 3480, "text": "Label" }, { "code": null, "e": 3534, "s": 3486, "text": "A Label object is a component for placing text." }, { "code": null, "e": 3541, "s": 3534, "text": "Button" }, { "code": null, "e": 3578, "s": 3541, "text": "This class creates a labeled button." }, { "code": null, "e": 3590, "s": 3578, "text": "ColorPicker" }, { "code": null, "e": 3691, "s": 3590, "text": "A ColorPicker provides a pane of controls designed to allow a user to manipulate and select a color." }, { "code": null, "e": 3700, "s": 3691, "text": "CheckBox" }, { "code": null, "e": 3792, "s": 3700, "text": "A CheckBox is a graphical component that can be in either an on(true) or off (false) state." }, { "code": null, "e": 3804, "s": 3792, "text": "RadioButton" }, { "code": null, "e": 3920, "s": 3804, "text": "The RadioButton class is a graphical component, which can either be in a ON (true) or OFF (false) state in a group." }, { "code": null, "e": 3929, "s": 3920, "text": "ListView" }, { "code": null, "e": 4005, "s": 3929, "text": "A ListView component presents the user with a scrolling list of text items." }, { "code": null, "e": 4015, "s": 4005, "text": "TextField" }, { "code": null, "e": 4108, "s": 4015, "text": "A TextField object is a text component that allows for the editing of a single line of text." }, { "code": null, "e": 4122, "s": 4108, "text": "PasswordField" }, { "code": null, "e": 4197, "s": 4122, "text": "A PasswordField object is a text component specialized for password entry." }, { "code": null, "e": 4207, "s": 4197, "text": "Scrollbar" }, { "code": null, "e": 4317, "s": 4207, "text": "A Scrollbar control represents a scroll bar component in order to enable user to select from range of values." }, { "code": null, "e": 4329, "s": 4317, "text": "FileChooser" }, { "code": null, "e": 4417, "s": 4329, "text": "A FileChooser control represents a dialog window from which the user can select a file." }, { "code": null, "e": 4429, "s": 4417, "text": "ProgressBar" }, { "code": null, "e": 4535, "s": 4429, "text": "As the task progresses towards completion, the progress bar displays the task's percentage of completion." }, { "code": null, "e": 4542, "s": 4535, "text": "Slider" }, { "code": null, "e": 4637, "s": 4542, "text": "A Slider lets the user graphically select a value by sliding a knob within a bounded interval." }, { "code": null, "e": 4790, "s": 4637, "text": "The following program is an example which displays a login page in JavaFX. Here, we are using the controls label, text field, password field and button." }, { "code": null, "e": 4845, "s": 4790, "text": "Save this code in a file with the name LoginPage.java." }, { "code": null, "e": 7414, "s": 4845, "text": "import javafx.application.Application; \nimport static javafx.application.Application.launch; \nimport javafx.geometry.Insets; \nimport javafx.geometry.Pos; \n\nimport javafx.scene.Scene; \nimport javafx.scene.control.Button; \nimport javafx.scene.control.PasswordField; \nimport javafx.scene.layout.GridPane; \nimport javafx.scene.text.Text; \nimport javafx.scene.control.TextField; \nimport javafx.stage.Stage; \n \npublic class LoginPage extends Application { \n @Override \n public void start(Stage stage) { \n //creating label email \n Text text1 = new Text(\"Email\"); \n \n //creating label password \n Text text2 = new Text(\"Password\"); \n \n //Creating Text Filed for email \n TextField textField1 = new TextField(); \n \n //Creating Text Filed for password \n PasswordField textField2 = new PasswordField(); \n \n //Creating Buttons \n Button button1 = new Button(\"Submit\"); \n Button button2 = new Button(\"Clear\"); \n \n //Creating a Grid Pane \n GridPane gridPane = new GridPane(); \n \n //Setting size for the pane \n gridPane.setMinSize(400, 200); \n \n //Setting the padding \n gridPane.setPadding(new Insets(10, 10, 10, 10)); \n \n //Setting the vertical and horizontal gaps between the columns \n gridPane.setVgap(5); \n gridPane.setHgap(5); \n \n //Setting the Grid alignment \n gridPane.setAlignment(Pos.CENTER); \n \n //Arranging all the nodes in the grid \n gridPane.add(text1, 0, 0); \n gridPane.add(textField1, 1, 0); \n gridPane.add(text2, 0, 1); \n gridPane.add(textField2, 1, 1); \n gridPane.add(button1, 0, 2); \n gridPane.add(button2, 1, 2); \n \n //Styling nodes \n button1.setStyle(\"-fx-background-color: darkslateblue; -fx-text-fill: white;\"); \n button2.setStyle(\"-fx-background-color: darkslateblue; -fx-text-fill: white;\"); \n \n text1.setStyle(\"-fx-font: normal bold 20px 'serif' \"); \n text2.setStyle(\"-fx-font: normal bold 20px 'serif' \"); \n gridPane.setStyle(\"-fx-background-color: BEIGE;\"); \n \n //Creating a scene object \n Scene scene = new Scene(gridPane); \n \n //Setting title to the Stage \n stage.setTitle(\"CSS Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene);\n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 7508, "s": 7414, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 7547, "s": 7508, "text": "javac LoginPage.java \njava LoginPage \n" }, { "code": null, "e": 7621, "s": 7547, "text": "On executing, the above program generates a JavaFX window as shown below." }, { "code": null, "e": 7809, "s": 7621, "text": "The following program is an example of a registration form, which demonstrates controls in JavaFX such as Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice List, etc." }, { "code": null, "e": 7867, "s": 7809, "text": "Save this code in a file with the name Registration.java." }, { "code": null, "e": 13481, "s": 7867, "text": "import javafx.application.Application; \nimport javafx.collections.FXCollections; \nimport javafx.collections.ObservableList; \n\nimport javafx.geometry.Insets; \nimport javafx.geometry.Pos; \n\nimport javafx.scene.Scene; \nimport javafx.scene.control.Button; \nimport javafx.scene.control.CheckBox; \nimport javafx.scene.control.ChoiceBox; \nimport javafx.scene.control.DatePicker; \nimport javafx.scene.control.ListView; \nimport javafx.scene.control.RadioButton; \nimport javafx.scene.layout.GridPane; \nimport javafx.scene.text.Text; \nimport javafx.scene.control.TextField; \nimport javafx.scene.control.ToggleGroup; \nimport javafx.scene.control.ToggleButton; \nimport javafx.stage.Stage; \n \npublic class Registration extends Application { \n @Override \n public void start(Stage stage) { \n //Label for name \n Text nameLabel = new Text(\"Name\"); \n \n //Text field for name \n TextField nameText = new TextField(); \n \n //Label for date of birth \n Text dobLabel = new Text(\"Date of birth\"); \n \n //date picker to choose date \n DatePicker datePicker = new DatePicker(); \n \n //Label for gender\n Text genderLabel = new Text(\"gender\"); \n \n //Toggle group of radio buttons \n ToggleGroup groupGender = new ToggleGroup(); \n RadioButton maleRadio = new RadioButton(\"male\"); \n maleRadio.setToggleGroup(groupGender); \n RadioButton femaleRadio = new RadioButton(\"female\"); \n femaleRadio.setToggleGroup(groupGender); \n \n //Label for reservation \n Text reservationLabel = new Text(\"Reservation\"); \n \n //Toggle button for reservation \n ToggleButton Reservation = new ToggleButton(); \n ToggleButton yes = new ToggleButton(\"Yes\"); \n ToggleButton no = new ToggleButton(\"No\"); \n ToggleGroup groupReservation = new ToggleGroup(); \n yes.setToggleGroup(groupReservation); \n no.setToggleGroup(groupReservation); \n \n //Label for technologies known \n Text technologiesLabel = new Text(\"Technologies Known\"); \n \n //check box for education \n CheckBox javaCheckBox = new CheckBox(\"Java\"); \n javaCheckBox.setIndeterminate(false); \n \n //check box for education \n CheckBox dotnetCheckBox = new CheckBox(\"DotNet\"); \n javaCheckBox.setIndeterminate(false); \n \n //Label for education \n Text educationLabel = new Text(\"Educational qualification\"); \n \n //list View for educational qualification \n ObservableList<String> names = FXCollections.observableArrayList( \n \"Engineering\", \"MCA\", \"MBA\", \"Graduation\", \"MTECH\", \"Mphil\", \"Phd\"); \n ListView<String> educationListView = new ListView<String>(names); \n \n //Label for location \n Text locationLabel = new Text(\"location\"); \n \n //Choice box for location \n ChoiceBox locationchoiceBox = new ChoiceBox(); \n locationchoiceBox.getItems().addAll\n (\"Hyderabad\", \"Chennai\", \"Delhi\", \"Mumbai\", \"Vishakhapatnam\"); \n \n //Label for register \n Button buttonRegister = new Button(\"Register\"); \n \n //Creating a Grid Pane \n GridPane gridPane = new GridPane(); \n \n //Setting size for the pane \n gridPane.setMinSize(500, 500); \n \n //Setting the padding \n gridPane.setPadding(new Insets(10, 10, 10, 10)); \n \n //Setting the vertical and horizontal gaps between the columns \n gridPane.setVgap(5); \n gridPane.setHgap(5); \n \n //Setting the Grid alignment \n gridPane.setAlignment(Pos.CENTER); \n \n //Arranging all the nodes in the grid \n gridPane.add(nameLabel, 0, 0); \n gridPane.add(nameText, 1, 0); \n \n gridPane.add(dobLabel, 0, 1); \n gridPane.add(datePicker, 1, 1); \n \n gridPane.add(genderLabel, 0, 2); \n gridPane.add(maleRadio, 1, 2); \n gridPane.add(femaleRadio, 2, 2); \n gridPane.add(reservationLabel, 0, 3); \n gridPane.add(yes, 1, 3); \n gridPane.add(no, 2, 3); \n \n gridPane.add(technologiesLabel, 0, 4); \n gridPane.add(javaCheckBox, 1, 4); \n gridPane.add(dotnetCheckBox, 2, 4); \n \n gridPane.add(educationLabel, 0, 5); \n gridPane.add(educationListView, 1, 5); \n \n gridPane.add(locationLabel, 0, 6); \n gridPane.add(locationchoiceBox, 1, 6); \n \n gridPane.add(buttonRegister, 2, 8); \n \n //Styling nodes \n buttonRegister.setStyle(\n \"-fx-background-color: darkslateblue; -fx-textfill: white;\"); \n \n nameLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n dobLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n genderLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n reservationLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n technologiesLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n educationLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n locationLabel.setStyle(\"-fx-font: normal bold 15px 'serif' \"); \n \n //Setting the back ground color \n gridPane.setStyle(\"-fx-background-color: BEIGE;\"); \n \n //Creating a scene object \n Scene scene = new Scene(gridPane); \n \n //Setting title to the Stage \n stage.setTitle(\"Registration Form\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 13575, "s": 13481, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 13620, "s": 13575, "text": "javac Registration.java \njava Registration \n" }, { "code": null, "e": 13694, "s": 13620, "text": "On executing, the above program generates a JavaFX window as shown below." }, { "code": null, "e": 13729, "s": 13694, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 13740, "s": 13729, "text": " Syed Raza" }, { "code": null, "e": 13776, "s": 13740, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 13812, "s": 13776, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 13845, "s": 13812, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 13881, "s": 13845, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 13888, "s": 13881, "text": " Print" }, { "code": null, "e": 13899, "s": 13888, "text": " Add Notes" } ]
Check if a number can be written as a sum of 'k' prime numbers - GeeksforGeeks
10 Mar, 2022 Given two numbers N and K. We need to find out if ‘N’ can be written as sum of ‘K’ prime numbers. Given N <= 10^9 Examples : Input : N = 10 K = 2 Output : Yes 10 can be written as 5 + 5 Input : N = 2 K = 2 Output : No The idea is to use Goldbach’s conjecture which says that every even integer (greater than 2) can be expressed as sum of two primes.If the N >= 2K and K = 1: the answer will be Yes iff N is a prime numberIf N >= 2K and K = 2: If N is an even number answer will be Yes(Goldbach’s conjecture) and if N is odd answer will be No if N-2 is not a prime number and Yes if N-2 is a prime number. This is because we know odd + odd = even and even + odd = odd. So when N is odd, and K = 2 one number must be 2 as it is the only even prime number so now the answer depends on whether N-2 is odd or not. If N >= 2K and K >= 3: Answer will always be Yes. When N is even N – 2*(K-2) is also even so N – 2*(K – 2) can be written as sum of two prime numbers (Goldbach’s conjecture) p, q and N can be written as 2, 2 .....K – 2 times, p, q. When N is odd N – 3 -2*(K – 3) is even so it can be written as sum of two prime numbers p, q and N can be written as 2, 2 .....K-3 times, 3, p, q C++ Java Python3 C# PHP Javascript // C++ implementation to check if N can be// written as sum of k primes#include<bits/stdc++.h>using namespace std; // Checking if a number is prime or notbool isprime(int x){ // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true;} // Returns true if N can be written as sum// of K primesbool isSumOfKprimes(int N, int K){ // N < 2K directly return false if (N < 2*K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true;} // Driver functionint main(){ int n = 10, k = 2; if (isSumOfKprimes (n, k)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java implementation to check if N can be// written as sum of k primespublic class Prime{ // Checking if a number is prime or not static boolean isprime(int x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i=2; i*i<=x; i++) if (x%i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes static boolean isSumOfKprimes(int N, int K) { // N < 2K directly return false if (N < 2*K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N%2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } public static void main (String[] args) { int n = 10, k = 2; if (isSumOfKprimes (n, k)) System.out.print("Yes"); else System.out.print("No"); }}// Contributed by Saket Kumar # Python implementation to check# if N can be written as sum of# k primes # Checking if a number is prime# or not def isprime(x): # check for numbers from 2 # to sqrt(x) if it is divisible # return false i = 2 while(i * i <= x): if (x % i == 0): return 0 i += 1 return 1 # Returns true if N can be written# as sum of K primes def isSumOfKprimes(N, K): # N < 2K directly return false if (N < 2 * K): return 0 # If K = 1 return value depends # on primality of N if (K == 1): return isprime(N) if (K == 2): # if N is even directly # return true; if (N % 2 == 0): return 1 # If N is odd, then one # prime must be 2. All # other primes are odd # and cannot have a pair # sum as even. return isprime(N - 2) # If K >= 3 return true; return 1 # Driver functionn = 15k = 2if (isSumOfKprimes(n, k)): print("Yes")else: print("No") # This code is Contributed by Sam007. // C# implementation to check if N can be// written as sum of k primesusing System; class GFG { // Checking if a number is prime or not static bool isprime(int x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes static bool isSumOfKprimes(int N, int K) { // N < 2K directly return false if (N < 2 * K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } // Driver function public static void Main () { int n = 10, k = 2; if (isSumOfKprimes (n, k)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Sam007 <?php// PHP implementation to check// if N can be written as sum// of k primes // Checking if a number// is prime or notfunction isprime($x){ // check for numbers from 2 // to sqrt(x) if it is // divisible return false for ($i = 2; $i * $i <= $x; $i++) if ($x % $i == 0) return false; return true;} // Returns true if N can be// written as sum of K primesfunction isSumOfKprimes($N, $K){ // N < 2K directly return false if ($N < 2 * $K) return false; // If K = 1 return value // depends on primality of N if ($K == 1) return isprime($N); if ($K == 2) { // if N is even directly // return true; if ($N % 2 == 0) return true; // If N is odd, then one prime // must be 2. All other primes // are odd and cannot have a // pair sum as even. return isprime($N - 2); } // If K >= 3 return true; return true;} // Driver Code$n = 10; $k = 2;if (isSumOfKprimes ($n, $k)) echo "Yes";else echo"No" ; // This code is contributed by vt?> <script>// javascript implementation to check if N can be// written as sum of k primes // Checking if a number is prime or not function isprime(x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes function isSumOfKprimes(N, K) { // N < 2K directly return false if (N < 2 * K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } // Driver code var n = 10, k = 2; if (isSumOfKprimes(n, k)) document.write("Yes"); else document.write("No"); // This code is contributed by gauravrajput1</script> Output : Yes Time Complexity: O(sqrt(x))Auxiliary Space: O(1) This article is contributed by Ayush Jha 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. Sam007 vt_m ammar53 ManasChhabra2 GauravRajput1 yashwant94308 aryan13sethi singhh3010 number-theory Numbers Prime Number sieve Zoho Mathematical Zoho number-theory Mathematical Prime Number Numbers sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Program for Decimal to Binary Conversion Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Minimum number of jumps to reach end
[ { "code": null, "e": 24748, "s": 24720, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24862, "s": 24748, "text": "Given two numbers N and K. We need to find out if ‘N’ can be written as sum of ‘K’ prime numbers. Given N <= 10^9" }, { "code": null, "e": 24874, "s": 24862, "text": "Examples : " }, { "code": null, "e": 24979, "s": 24874, "text": "Input : N = 10 K = 2\nOutput : Yes \n 10 can be written as 5 + 5\n\nInput : N = 2 K = 2\nOutput : No" }, { "code": null, "e": 25949, "s": 24979, "text": "The idea is to use Goldbach’s conjecture which says that every even integer (greater than 2) can be expressed as sum of two primes.If the N >= 2K and K = 1: the answer will be Yes iff N is a prime numberIf N >= 2K and K = 2: If N is an even number answer will be Yes(Goldbach’s conjecture) and if N is odd answer will be No if N-2 is not a prime number and Yes if N-2 is a prime number. This is because we know odd + odd = even and even + odd = odd. So when N is odd, and K = 2 one number must be 2 as it is the only even prime number so now the answer depends on whether N-2 is odd or not. If N >= 2K and K >= 3: Answer will always be Yes. When N is even N – 2*(K-2) is also even so N – 2*(K – 2) can be written as sum of two prime numbers (Goldbach’s conjecture) p, q and N can be written as 2, 2 .....K – 2 times, p, q. When N is odd N – 3 -2*(K – 3) is even so it can be written as sum of two prime numbers p, q and N can be written as 2, 2 .....K-3 times, 3, p, q " }, { "code": null, "e": 25953, "s": 25949, "text": "C++" }, { "code": null, "e": 25958, "s": 25953, "text": "Java" }, { "code": null, "e": 25966, "s": 25958, "text": "Python3" }, { "code": null, "e": 25969, "s": 25966, "text": "C#" }, { "code": null, "e": 25973, "s": 25969, "text": "PHP" }, { "code": null, "e": 25984, "s": 25973, "text": "Javascript" }, { "code": "// C++ implementation to check if N can be// written as sum of k primes#include<bits/stdc++.h>using namespace std; // Checking if a number is prime or notbool isprime(int x){ // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true;} // Returns true if N can be written as sum// of K primesbool isSumOfKprimes(int N, int K){ // N < 2K directly return false if (N < 2*K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true;} // Driver functionint main(){ int n = 10, k = 2; if (isSumOfKprimes (n, k)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 27091, "s": 25984, "text": null }, { "code": "// Java implementation to check if N can be// written as sum of k primespublic class Prime{ // Checking if a number is prime or not static boolean isprime(int x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i=2; i*i<=x; i++) if (x%i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes static boolean isSumOfKprimes(int N, int K) { // N < 2K directly return false if (N < 2*K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N%2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } public static void main (String[] args) { int n = 10, k = 2; if (isSumOfKprimes (n, k)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}// Contributed by Saket Kumar", "e": 28442, "s": 27091, "text": null }, { "code": "# Python implementation to check# if N can be written as sum of# k primes # Checking if a number is prime# or not def isprime(x): # check for numbers from 2 # to sqrt(x) if it is divisible # return false i = 2 while(i * i <= x): if (x % i == 0): return 0 i += 1 return 1 # Returns true if N can be written# as sum of K primes def isSumOfKprimes(N, K): # N < 2K directly return false if (N < 2 * K): return 0 # If K = 1 return value depends # on primality of N if (K == 1): return isprime(N) if (K == 2): # if N is even directly # return true; if (N % 2 == 0): return 1 # If N is odd, then one # prime must be 2. All # other primes are odd # and cannot have a pair # sum as even. return isprime(N - 2) # If K >= 3 return true; return 1 # Driver functionn = 15k = 2if (isSumOfKprimes(n, k)): print(\"Yes\")else: print(\"No\") # This code is Contributed by Sam007.", "e": 29471, "s": 28442, "text": null }, { "code": "// C# implementation to check if N can be// written as sum of k primesusing System; class GFG { // Checking if a number is prime or not static bool isprime(int x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes static bool isSumOfKprimes(int N, int K) { // N < 2K directly return false if (N < 2 * K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } // Driver function public static void Main () { int n = 10, k = 2; if (isSumOfKprimes (n, k)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Sam007", "e": 30857, "s": 29471, "text": null }, { "code": "<?php// PHP implementation to check// if N can be written as sum// of k primes // Checking if a number// is prime or notfunction isprime($x){ // check for numbers from 2 // to sqrt(x) if it is // divisible return false for ($i = 2; $i * $i <= $x; $i++) if ($x % $i == 0) return false; return true;} // Returns true if N can be// written as sum of K primesfunction isSumOfKprimes($N, $K){ // N < 2K directly return false if ($N < 2 * $K) return false; // If K = 1 return value // depends on primality of N if ($K == 1) return isprime($N); if ($K == 2) { // if N is even directly // return true; if ($N % 2 == 0) return true; // If N is odd, then one prime // must be 2. All other primes // are odd and cannot have a // pair sum as even. return isprime($N - 2); } // If K >= 3 return true; return true;} // Driver Code$n = 10; $k = 2;if (isSumOfKprimes ($n, $k)) echo \"Yes\";else echo\"No\" ; // This code is contributed by vt?>", "e": 31935, "s": 30857, "text": null }, { "code": "<script>// javascript implementation to check if N can be// written as sum of k primes // Checking if a number is prime or not function isprime(x) { // check for numbers from 2 to sqrt(x) // if it is divisible return false for (i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } // Returns true if N can be written as sum // of K primes function isSumOfKprimes(N, K) { // N < 2K directly return false if (N < 2 * K) return false; // If K = 1 return value depends on primality of N if (K == 1) return isprime(N); if (K == 2) { // if N is even directly return true; if (N % 2 == 0) return true; // If N is odd, then one prime must // be 2. All other primes are odd // and cannot have a pair sum as even. return isprime(N - 2); } // If K >= 3 return true; return true; } // Driver code var n = 10, k = 2; if (isSumOfKprimes(n, k)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by gauravrajput1</script>", "e": 33205, "s": 31935, "text": null }, { "code": null, "e": 33215, "s": 33205, "text": "Output : " }, { "code": null, "e": 33219, "s": 33215, "text": "Yes" }, { "code": null, "e": 33268, "s": 33219, "text": "Time Complexity: O(sqrt(x))Auxiliary Space: O(1)" }, { "code": null, "e": 33685, "s": 33268, "text": "This article is contributed by Ayush Jha 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": 33692, "s": 33685, "text": "Sam007" }, { "code": null, "e": 33697, "s": 33692, "text": "vt_m" }, { "code": null, "e": 33705, "s": 33697, "text": "ammar53" }, { "code": null, "e": 33719, "s": 33705, "text": "ManasChhabra2" }, { "code": null, "e": 33733, "s": 33719, "text": "GauravRajput1" }, { "code": null, "e": 33747, "s": 33733, "text": "yashwant94308" }, { "code": null, "e": 33760, "s": 33747, "text": "aryan13sethi" }, { "code": null, "e": 33771, "s": 33760, "text": "singhh3010" }, { "code": null, "e": 33785, "s": 33771, "text": "number-theory" }, { "code": null, "e": 33793, "s": 33785, "text": "Numbers" }, { "code": null, "e": 33806, "s": 33793, "text": "Prime Number" }, { "code": null, "e": 33812, "s": 33806, "text": "sieve" }, { "code": null, "e": 33817, "s": 33812, "text": "Zoho" }, { "code": null, "e": 33830, "s": 33817, "text": "Mathematical" }, { "code": null, "e": 33835, "s": 33830, "text": "Zoho" }, { "code": null, "e": 33849, "s": 33835, "text": "number-theory" }, { "code": null, "e": 33862, "s": 33849, "text": "Mathematical" }, { "code": null, "e": 33875, "s": 33862, "text": "Prime Number" }, { "code": null, "e": 33883, "s": 33875, "text": "Numbers" }, { "code": null, "e": 33889, "s": 33883, "text": "sieve" }, { "code": null, "e": 33987, "s": 33889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34030, "s": 33987, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34054, "s": 34030, "text": "Merge two sorted arrays" }, { "code": null, "e": 34068, "s": 34054, "text": "Prime Numbers" }, { "code": null, "e": 34117, "s": 34068, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 34151, "s": 34117, "text": "Program for factorial of a number" }, { "code": null, "e": 34192, "s": 34151, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34213, "s": 34192, "text": "Operators in C / C++" }, { "code": null, "e": 34256, "s": 34213, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34309, "s": 34256, "text": "Find minimum number of coins that make a given value" } ]
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound) - GeeksforGeeks
31 May, 2021 Binary search is an important component in competitive programming or any algorithmic competition, having knowledge of shorthand functions reduces the time to code them. This searching only works when container is sorted. Related functions are discussed below.1.binary_search(start_ptr, end_ptr, num) : This function returns boolean true if the element is present in the container, else returns false. CPP // C++ code to demonstrate the working of binary_search() #include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers vector<int> arr = {10, 15, 20, 25, 30, 35}; // using binary_search to check if 15 exists if (binary_search(arr.begin(), arr.end(), 15)) cout << "15 exists in vector"; else cout << "15 does not exist"; cout << endl; // using binary_search to check if 23 exists if (binary_search(arr.begin(), arr.end(), 23)) cout << "23 exists in vector"; else cout << "23 does not exist"; cout << endl; } Output: 15 exists in vector 23 does not exist 2. lower_bound(start_ptr, end_ptr, num) : Returns pointer to “position of num” if container contains 1 occurrence of num. Returns pointer to “first position of num” if container contains multiple occurrence of num. Returns pointer to “position of next higher number than num” if container does not contain occurrence of num. Subtracting the pointer to 1st position i.e “vect.begin()” returns the actual index. CPP // C++ code to demonstrate the working of lower_bound()#include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers // for single occurrence vector<int> arr1 = {10, 15, 20, 25, 30, 35}; // initializing vector of integers // for multiple occurrences vector<int> arr2 = {10, 15, 20, 20, 25, 30, 35}; // initializing vector of integers // for no occurrence vector<int> arr3 = {10, 15, 25, 30, 35}; // using lower_bound() to check if 20 exists // single occurrence // prints 2 cout << "The position of 20 using lower_bound " " (in single occurrence case) : "; cout << lower_bound(arr1.begin(), arr1.end(), 20) - arr1.begin(); cout << endl; // using lower_bound() to check if 20 exists // multiple occurrence // prints 2 cout << "The position of 20 using lower_bound " "(in multiple occurrence case) : "; cout << lower_bound(arr2.begin(), arr2.end(), 20) - arr2.begin(); cout << endl; // using lower_bound() to check if 20 exists // no occurrence // prints 2 ( index of next higher) cout << "The position of 20 using lower_bound " "(in no occurrence case) : "; cout << lower_bound(arr3.begin(), arr3.end(), 20) - arr3.begin(); cout << endl; } Output: The position of 20 using lower_bound (in single occurrence case) : 2 The position of 20 using lower_bound (in multiple occurrence case) : 2 The position of 20 using lower_bound (in no occurrence case) : 2 3. upper_bound(start_ptr, end_ptr, num) : Returns pointer to “position of next higher number than num” if container contains 1 occurrence of num. Returns pointer to “first position of next higher number than last occurrence of num” if container contains multiple occurrence of num. Returns pointer to “position of next higher number than num” if container does not contain occurrence of num. Subtracting the pointer to 1st position i.e “vect.begin()” returns the actual index. Binary search is the most efficient search algorithm. CPP // C++ code to demonstrate the working of upper_bound()#include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers // for single occurrence vector<int> arr1 = {10, 15, 20, 25, 30, 35}; // initializing vector of integers // for multiple occurrences vector<int> arr2 = {10, 15, 20, 20, 25, 30, 35}; // initializing vector of integers // for no occurrence vector<int> arr3 = {10, 15, 25, 30, 35}; // using upper_bound() to check if 20 exists // single occurrence // prints 3 cout << "The position of 20 using upper_bound" " (in single occurrence case) : "; cout << upper_bound(arr1.begin(), arr1.end(), 20) - arr1.begin(); cout << endl; // using upper_bound() to check if 20 exists // multiple occurrence // prints 4 cout << "The position of 20 using upper_bound " "(in multiple occurrence case) : "; cout << upper_bound(arr2.begin(), arr2.end(), 20) - arr2.begin(); cout << endl; // using upper_bound() to check if 20 exists // no occurrence // prints 2 ( index of next higher) cout << "The position of 20 using upper_bound" " (in no occurrence case) : "; cout << upper_bound(arr3.begin(), arr3.end(), 20) - arr3.begin(); cout << endl; } Output: The position of 20 using upper_bound (in single occurrence case) : 3 The position of 20 using upper_bound (in multiple occurrence case) : 4 The position of 20 using upper_bound (in no occurrence case) : 2 Time Complexity :O(logN) -where N is number of elements in array. This article is contributed by Manjeet Singh(HBD.N). 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. cchallenge2020 sainischalreddy1505 Binary Search cpp-algorithm-library cpp-binary-search STL C++ STL Binary Search CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtual Function in C++ C++ Classes and Objects Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Polymorphism in C++ Copy Constructor in C++ Multidimensional Arrays in C / C++ Friend class and function in C++
[ { "code": null, "e": 24320, "s": 24292, "text": "\n31 May, 2021" }, { "code": null, "e": 24723, "s": 24320, "text": "Binary search is an important component in competitive programming or any algorithmic competition, having knowledge of shorthand functions reduces the time to code them. This searching only works when container is sorted. Related functions are discussed below.1.binary_search(start_ptr, end_ptr, num) : This function returns boolean true if the element is present in the container, else returns false. " }, { "code": null, "e": 24727, "s": 24723, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of binary_search() #include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers vector<int> arr = {10, 15, 20, 25, 30, 35}; // using binary_search to check if 15 exists if (binary_search(arr.begin(), arr.end(), 15)) cout << \"15 exists in vector\"; else cout << \"15 does not exist\"; cout << endl; // using binary_search to check if 23 exists if (binary_search(arr.begin(), arr.end(), 23)) cout << \"23 exists in vector\"; else cout << \"23 does not exist\"; cout << endl; }", "e": 25346, "s": 24727, "text": null }, { "code": null, "e": 25356, "s": 25346, "text": "Output: " }, { "code": null, "e": 25394, "s": 25356, "text": "15 exists in vector\n23 does not exist" }, { "code": null, "e": 25805, "s": 25394, "text": "2. lower_bound(start_ptr, end_ptr, num) : Returns pointer to “position of num” if container contains 1 occurrence of num. Returns pointer to “first position of num” if container contains multiple occurrence of num. Returns pointer to “position of next higher number than num” if container does not contain occurrence of num. Subtracting the pointer to 1st position i.e “vect.begin()” returns the actual index. " }, { "code": null, "e": 25809, "s": 25805, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of lower_bound()#include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers // for single occurrence vector<int> arr1 = {10, 15, 20, 25, 30, 35}; // initializing vector of integers // for multiple occurrences vector<int> arr2 = {10, 15, 20, 20, 25, 30, 35}; // initializing vector of integers // for no occurrence vector<int> arr3 = {10, 15, 25, 30, 35}; // using lower_bound() to check if 20 exists // single occurrence // prints 2 cout << \"The position of 20 using lower_bound \" \" (in single occurrence case) : \"; cout << lower_bound(arr1.begin(), arr1.end(), 20) - arr1.begin(); cout << endl; // using lower_bound() to check if 20 exists // multiple occurrence // prints 2 cout << \"The position of 20 using lower_bound \" \"(in multiple occurrence case) : \"; cout << lower_bound(arr2.begin(), arr2.end(), 20) - arr2.begin(); cout << endl; // using lower_bound() to check if 20 exists // no occurrence // prints 2 ( index of next higher) cout << \"The position of 20 using lower_bound \" \"(in no occurrence case) : \"; cout << lower_bound(arr3.begin(), arr3.end(), 20) - arr3.begin(); cout << endl; }", "e": 27175, "s": 25809, "text": null }, { "code": null, "e": 27185, "s": 27175, "text": "Output: " }, { "code": null, "e": 27390, "s": 27185, "text": "The position of 20 using lower_bound (in single occurrence case) : 2\nThe position of 20 using lower_bound (in multiple occurrence case) : 2\nThe position of 20 using lower_bound (in no occurrence case) : 2" }, { "code": null, "e": 27867, "s": 27390, "text": "3. upper_bound(start_ptr, end_ptr, num) : Returns pointer to “position of next higher number than num” if container contains 1 occurrence of num. Returns pointer to “first position of next higher number than last occurrence of num” if container contains multiple occurrence of num. Returns pointer to “position of next higher number than num” if container does not contain occurrence of num. Subtracting the pointer to 1st position i.e “vect.begin()” returns the actual index." }, { "code": null, "e": 27922, "s": 27867, "text": "Binary search is the most efficient search algorithm. " }, { "code": null, "e": 27926, "s": 27922, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of upper_bound()#include<bits/stdc++.h>using namespace std; int main(){ // initializing vector of integers // for single occurrence vector<int> arr1 = {10, 15, 20, 25, 30, 35}; // initializing vector of integers // for multiple occurrences vector<int> arr2 = {10, 15, 20, 20, 25, 30, 35}; // initializing vector of integers // for no occurrence vector<int> arr3 = {10, 15, 25, 30, 35}; // using upper_bound() to check if 20 exists // single occurrence // prints 3 cout << \"The position of 20 using upper_bound\" \" (in single occurrence case) : \"; cout << upper_bound(arr1.begin(), arr1.end(), 20) - arr1.begin(); cout << endl; // using upper_bound() to check if 20 exists // multiple occurrence // prints 4 cout << \"The position of 20 using upper_bound \" \"(in multiple occurrence case) : \"; cout << upper_bound(arr2.begin(), arr2.end(), 20) - arr2.begin(); cout << endl; // using upper_bound() to check if 20 exists // no occurrence // prints 2 ( index of next higher) cout << \"The position of 20 using upper_bound\" \" (in no occurrence case) : \"; cout << upper_bound(arr3.begin(), arr3.end(), 20) - arr3.begin(); cout << endl; }", "e": 29290, "s": 27926, "text": null }, { "code": null, "e": 29300, "s": 29290, "text": "Output: " }, { "code": null, "e": 29505, "s": 29300, "text": "The position of 20 using upper_bound (in single occurrence case) : 3\nThe position of 20 using upper_bound (in multiple occurrence case) : 4\nThe position of 20 using upper_bound (in no occurrence case) : 2" }, { "code": null, "e": 29571, "s": 29505, "text": "Time Complexity :O(logN) -where N is number of elements in array." }, { "code": null, "e": 29999, "s": 29571, "text": "This article is contributed by Manjeet Singh(HBD.N). 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": 30014, "s": 29999, "text": "cchallenge2020" }, { "code": null, "e": 30034, "s": 30014, "text": "sainischalreddy1505" }, { "code": null, "e": 30048, "s": 30034, "text": "Binary Search" }, { "code": null, "e": 30070, "s": 30048, "text": "cpp-algorithm-library" }, { "code": null, "e": 30088, "s": 30070, "text": "cpp-binary-search" }, { "code": null, "e": 30092, "s": 30088, "text": "STL" }, { "code": null, "e": 30096, "s": 30092, "text": "C++" }, { "code": null, "e": 30100, "s": 30096, "text": "STL" }, { "code": null, "e": 30114, "s": 30100, "text": "Binary Search" }, { "code": null, "e": 30118, "s": 30114, "text": "CPP" }, { "code": null, "e": 30216, "s": 30118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30240, "s": 30216, "text": "Virtual Function in C++" }, { "code": null, "e": 30264, "s": 30240, "text": "C++ Classes and Objects" }, { "code": null, "e": 30295, "s": 30264, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30315, "s": 30295, "text": "Constructors in C++" }, { "code": null, "e": 30343, "s": 30315, "text": "Operator Overloading in C++" }, { "code": null, "e": 30371, "s": 30343, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30391, "s": 30371, "text": "Polymorphism in C++" }, { "code": null, "e": 30415, "s": 30391, "text": "Copy Constructor in C++" }, { "code": null, "e": 30450, "s": 30415, "text": "Multidimensional Arrays in C / C++" } ]
Python String lstrip() method - GeeksforGeeks
19 Aug, 2021 Python String lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces. Syntax: string.lstrip(characters) Parameters: characters [optional]: A set of characters to remove as leading characters. Returns: Returns a copy of the string with leading characters stripped. Python3 # Python3 program to demonstrate the use of # lstrip() method using default parameter # string which is to be stripped string = " geeksforgeeks" # Removes spaces from left. print(string.lstrip()) Output: geeksforgeeks Python3 # Python3 program to demonstrate the use of # lstrip() method using optional parameters # string which is to be stripped string = "++++x...y!!z* geeksforgeeks" # Removes given set of characters from left. print(string.lstrip("+.!*xyz")) Output: geeksforgeeks Python3 # string which is to be stripped string = "geeks for geeks" # Argument doesn't contain leading 'g' # So, no characters are removed print(string.lstrip('ge')) Output: ks for geeks There is a runtime error when we try to strip anything except a string. Python3 # Python3 program to demonstrate the use of # strip() method error string = " geeks for geeks "list =[1, 2, 3] # prints the error message print(list.lstrip()) Output: print(list.lstrip()) AttributeError: 'list' object has no attribute 'lstrip' YangSu1 AmiyaRanjanRout python-string Python-string-functions 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 Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25139, "s": 25111, "text": "\n19 Aug, 2021" }, { "code": null, "e": 25322, "s": 25139, "text": "Python String lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces." }, { "code": null, "e": 25331, "s": 25322, "text": "Syntax: " }, { "code": null, "e": 25357, "s": 25331, "text": "string.lstrip(characters)" }, { "code": null, "e": 25370, "s": 25357, "text": "Parameters: " }, { "code": null, "e": 25446, "s": 25370, "text": "characters [optional]: A set of characters to remove as leading characters." }, { "code": null, "e": 25456, "s": 25446, "text": "Returns: " }, { "code": null, "e": 25519, "s": 25456, "text": "Returns a copy of the string with leading characters stripped." }, { "code": null, "e": 25527, "s": 25519, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of # lstrip() method using default parameter # string which is to be stripped string = \" geeksforgeeks\" # Removes spaces from left. print(string.lstrip())", "e": 25732, "s": 25527, "text": null }, { "code": null, "e": 25740, "s": 25732, "text": "Output:" }, { "code": null, "e": 25754, "s": 25740, "text": "geeksforgeeks" }, { "code": null, "e": 25762, "s": 25754, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of # lstrip() method using optional parameters # string which is to be stripped string = \"++++x...y!!z* geeksforgeeks\" # Removes given set of characters from left. print(string.lstrip(\"+.!*xyz\"))", "e": 26004, "s": 25762, "text": null }, { "code": null, "e": 26013, "s": 26004, "text": "Output: " }, { "code": null, "e": 26027, "s": 26013, "text": "geeksforgeeks" }, { "code": null, "e": 26035, "s": 26027, "text": "Python3" }, { "code": "# string which is to be stripped string = \"geeks for geeks\" # Argument doesn't contain leading 'g' # So, no characters are removed print(string.lstrip('ge'))", "e": 26194, "s": 26035, "text": null }, { "code": null, "e": 26203, "s": 26194, "text": "Output: " }, { "code": null, "e": 26216, "s": 26203, "text": "ks for geeks" }, { "code": null, "e": 26289, "s": 26216, "text": "There is a runtime error when we try to strip anything except a string. " }, { "code": null, "e": 26297, "s": 26289, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of # strip() method error string = \" geeks for geeks \"list =[1, 2, 3] # prints the error message print(list.lstrip())", "e": 26460, "s": 26297, "text": null }, { "code": null, "e": 26469, "s": 26460, "text": "Output: " }, { "code": null, "e": 26547, "s": 26469, "text": "print(list.lstrip()) \nAttributeError: 'list' object has no attribute 'lstrip'" }, { "code": null, "e": 26555, "s": 26547, "text": "YangSu1" }, { "code": null, "e": 26571, "s": 26555, "text": "AmiyaRanjanRout" }, { "code": null, "e": 26585, "s": 26571, "text": "python-string" }, { "code": null, "e": 26609, "s": 26585, "text": "Python-string-functions" }, { "code": null, "e": 26616, "s": 26609, "text": "Python" }, { "code": null, "e": 26714, "s": 26616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26742, "s": 26714, "text": "Read JSON file using Python" }, { "code": null, "e": 26792, "s": 26742, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26814, "s": 26792, "text": "Python map() function" }, { "code": null, "e": 26858, "s": 26814, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26876, "s": 26858, "text": "Python Dictionary" }, { "code": null, "e": 26899, "s": 26876, "text": "Taking input in Python" }, { "code": null, "e": 26934, "s": 26899, "text": "Read a file line by line in Python" }, { "code": null, "e": 26966, "s": 26934, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26988, "s": 26966, "text": "Enumerate() in Python" } ]
Naive Bayes Classifiers for Text Classification | by Pınar Ersoy | Towards Data Science
Text classification can be described as one of the major subdivisions of the Natural Language Processing field. The text-based datasets composed of unstructured formatted content. This nature causes them to extract meaningful pieces in a difficult way. To be able to cope with this task, it is critical to choose the corresponding technique. Serving this purpose, Naive Bayes Classifier approaches can be performed by considering the structure types of the algorithms. The general formula of the Bayes Theorem can be simply highlighted as the following. P (X|Y) = ( P(Y|X) * P(X) ) / P(Y) By observing the formulation, X and Y can be accepted as events with the assumption that X is appearing while Y has already happened. With the help of this methodology, the inference of single occupancy of an event does not influence the other one can be raised which is also named as naive approach. The upcoming sections of this article include three distinct methods as Multinomial, Bernoulli, and Gaussian Naive Bayes. The Multinomial Naive Bayes can be accepted as the probabilistic approach to classifying documents in the case of acknowledging the frequency of a specified word in a text document. The term “bag of words” [1] is widely used as the selected document to be processed under the context of Naive Bayes while depicting the document itself as a bag and each vocabulary in the texture as the items in the bag by permitting multiple occurrences. To be able to properly classify, the existence of the word in the given text shall be known beforehand. This classifier achieves well on discrete types as the number of words found in a document. An example of the usage area of this approach can be the prediction of the matching category of the document with the help of the occurrences of the words allocated in the document. The output of this algorithm produces a vector composed of integer frequency values of the word set. P(M|N) = ( P(M) * P(N|M) ) / P(N) The Bernoulli or “Multivariate Bernoulli” [2] Naive Bayes may be expressed as the statistical method that generates outputs on a boolean basis by exploiting the desired text’s existence. This classifier feeds from Bernoulli Distribution [3] which has a discrete nature. P(M) = 1-p for M = 0, p for M = 1P(Mi|N)= P(i|N) * Mi + ( 1 - P(i|N) ) * (1 - Mi) This kind of Naive Bayes classifier can be useful when an undesired word would like to be detected or a specific type of word would like to be tagged in a given document. Also, it differentiates from the multinomial method by generating binary output as 1–0, True-False, or Yes-No. The concept of classifying text-formatted data has a wider tendency to work with categorical types. In addition to discrete data, Naive Bayes can be applied to continuous types, too. The Gaussian Naive Bayes can be useful to be applied on real or continuous-valued datasets rather than categorical or discrete-valued features. In the formula, the underlined Probability Density Function belongs to Gaussian by generating a calculation of the probability of any additional input word. Probability Density Function (x, mean, stdDev) = (1 / (sqrt(2 * PI) * stdDev)) * exp(-((x-(mean^2))/(2*(stdDev^2)))) The reason why is that the corresponding classification is actualized by considering a Gaussian distribution [4]. For the usage area, the datasets that have words with corresponding continuous values as height or width can be proper for the Gaussian Naive Bayes algorithm to be performed on. The Naive Bayes classifiers provide insightful outcomes in the fields of detecting sentiments and spam in text contexts [5]. Varying to the fields, the need for a classifier also differentiates, since the math behind the algorithm changes. In order to be able to accurately produce correct word classes and categories, it is highly essential to define the type of problem. Thank you so much for reading! Text Classification using Naive BayesMultivariate Bernoulli DistributionBernoulli DistributionGaussian Distribution FunctionNaive Bayes and Sentiment Classification Text Classification using Naive Bayes Multivariate Bernoulli Distribution Bernoulli Distribution Gaussian Distribution Function Naive Bayes and Sentiment Classification
[ { "code": null, "e": 641, "s": 172, "text": "Text classification can be described as one of the major subdivisions of the Natural Language Processing field. The text-based datasets composed of unstructured formatted content. This nature causes them to extract meaningful pieces in a difficult way. To be able to cope with this task, it is critical to choose the corresponding technique. Serving this purpose, Naive Bayes Classifier approaches can be performed by considering the structure types of the algorithms." }, { "code": null, "e": 726, "s": 641, "text": "The general formula of the Bayes Theorem can be simply highlighted as the following." }, { "code": null, "e": 761, "s": 726, "text": "P (X|Y) = ( P(Y|X) * P(X) ) / P(Y)" }, { "code": null, "e": 1062, "s": 761, "text": "By observing the formulation, X and Y can be accepted as events with the assumption that X is appearing while Y has already happened. With the help of this methodology, the inference of single occupancy of an event does not influence the other one can be raised which is also named as naive approach." }, { "code": null, "e": 1184, "s": 1062, "text": "The upcoming sections of this article include three distinct methods as Multinomial, Bernoulli, and Gaussian Naive Bayes." }, { "code": null, "e": 1366, "s": 1184, "text": "The Multinomial Naive Bayes can be accepted as the probabilistic approach to classifying documents in the case of acknowledging the frequency of a specified word in a text document." }, { "code": null, "e": 1623, "s": 1366, "text": "The term “bag of words” [1] is widely used as the selected document to be processed under the context of Naive Bayes while depicting the document itself as a bag and each vocabulary in the texture as the items in the bag by permitting multiple occurrences." }, { "code": null, "e": 2001, "s": 1623, "text": "To be able to properly classify, the existence of the word in the given text shall be known beforehand. This classifier achieves well on discrete types as the number of words found in a document. An example of the usage area of this approach can be the prediction of the matching category of the document with the help of the occurrences of the words allocated in the document." }, { "code": null, "e": 2102, "s": 2001, "text": "The output of this algorithm produces a vector composed of integer frequency values of the word set." }, { "code": null, "e": 2136, "s": 2102, "text": "P(M|N) = ( P(M) * P(N|M) ) / P(N)" }, { "code": null, "e": 2406, "s": 2136, "text": "The Bernoulli or “Multivariate Bernoulli” [2] Naive Bayes may be expressed as the statistical method that generates outputs on a boolean basis by exploiting the desired text’s existence. This classifier feeds from Bernoulli Distribution [3] which has a discrete nature." }, { "code": null, "e": 2497, "s": 2406, "text": "P(M) = 1-p for M = 0, p for M = 1P(Mi|N)= P(i|N) * Mi + ( 1 - P(i|N) ) * (1 - Mi)" }, { "code": null, "e": 2779, "s": 2497, "text": "This kind of Naive Bayes classifier can be useful when an undesired word would like to be detected or a specific type of word would like to be tagged in a given document. Also, it differentiates from the multinomial method by generating binary output as 1–0, True-False, or Yes-No." }, { "code": null, "e": 2962, "s": 2779, "text": "The concept of classifying text-formatted data has a wider tendency to work with categorical types. In addition to discrete data, Naive Bayes can be applied to continuous types, too." }, { "code": null, "e": 3106, "s": 2962, "text": "The Gaussian Naive Bayes can be useful to be applied on real or continuous-valued datasets rather than categorical or discrete-valued features." }, { "code": null, "e": 3263, "s": 3106, "text": "In the formula, the underlined Probability Density Function belongs to Gaussian by generating a calculation of the probability of any additional input word." }, { "code": null, "e": 3380, "s": 3263, "text": "Probability Density Function (x, mean, stdDev) = (1 / (sqrt(2 * PI) * stdDev)) * exp(-((x-(mean^2))/(2*(stdDev^2))))" }, { "code": null, "e": 3494, "s": 3380, "text": "The reason why is that the corresponding classification is actualized by considering a Gaussian distribution [4]." }, { "code": null, "e": 3672, "s": 3494, "text": "For the usage area, the datasets that have words with corresponding continuous values as height or width can be proper for the Gaussian Naive Bayes algorithm to be performed on." }, { "code": null, "e": 4045, "s": 3672, "text": "The Naive Bayes classifiers provide insightful outcomes in the fields of detecting sentiments and spam in text contexts [5]. Varying to the fields, the need for a classifier also differentiates, since the math behind the algorithm changes. In order to be able to accurately produce correct word classes and categories, it is highly essential to define the type of problem." }, { "code": null, "e": 4076, "s": 4045, "text": "Thank you so much for reading!" }, { "code": null, "e": 4241, "s": 4076, "text": "Text Classification using Naive BayesMultivariate Bernoulli DistributionBernoulli DistributionGaussian Distribution FunctionNaive Bayes and Sentiment Classification" }, { "code": null, "e": 4279, "s": 4241, "text": "Text Classification using Naive Bayes" }, { "code": null, "e": 4315, "s": 4279, "text": "Multivariate Bernoulli Distribution" }, { "code": null, "e": 4338, "s": 4315, "text": "Bernoulli Distribution" }, { "code": null, "e": 4369, "s": 4338, "text": "Gaussian Distribution Function" } ]
AWT Image Class
Image control is superclass for all image classes representing graphical images. Following is the declaration for java.awt.Image class: public abstract class Image extends Object Following are the fields for java.awt.Image class: protected float accelerationPriority -- Priority for accelerating this image. protected float accelerationPriority -- Priority for accelerating this image. static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm. static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm. static int SCALE_DEFAULT -- Use the default image-scaling algorithm. static int SCALE_DEFAULT -- Use the default image-scaling algorithm. static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image. static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image. static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class. static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class. static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed. static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed. static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched. static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched. Image() void flush() Flushes all reconstructable resources being used by this Image object. float getAccelerationPriority() Returns the current value of the acceleration priority hint. ImageCapabilities getCapabilities(GraphicsConfiguration gc) Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration. abstract Graphics getGraphics() Creates a graphics context for drawing to an off-screen image. abstract int getHeight(ImageObserver observer) Determines the height of the image. abstract Object getProperty(String name, ImageObserver observer) Gets a property of this image by name. Image getScaledInstance(int width, int height, int hints) Creates a scaled version of this image. abstract ImageProducer getSource() Gets the object that produces the pixels for the image. abstract int getWidth(ImageObserver observer) Determines the width of the image. void setAccelerationPriority(float priority) Sets a hint for this image about how important acceleration is. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showImageDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showImageDemo(){ headerLabel.setText("Control in action: Image"); controlPanel.add(new ImageComponent("resources/java.jpg")); mainFrame.setVisible(true); } class ImageComponent extends Component { BufferedImage img; public void paint(Graphics g) { g.drawImage(img, 0, 0, null); } public ImageComponent(String path) { try { img = ImageIO.read(new File(path)); } catch (IOException e) { e.printStackTrace(); } } public Dimension getPreferredSize() { if (img == null) { return new Dimension(100,100); } else { return new Dimension(img.getWidth(), img.getHeight()); } } } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1829, "s": 1747, "text": "Image control is superclass for all image classes representing graphical images. " }, { "code": null, "e": 1884, "s": 1829, "text": "Following is the declaration for java.awt.Image class:" }, { "code": null, "e": 1930, "s": 1884, "text": "public abstract class Image\n extends Object" }, { "code": null, "e": 1981, "s": 1930, "text": "Following are the fields for java.awt.Image class:" }, { "code": null, "e": 2060, "s": 1981, "text": "protected float accelerationPriority -- Priority for accelerating this image." }, { "code": null, "e": 2139, "s": 2060, "text": "protected float accelerationPriority -- Priority for accelerating this image." }, { "code": null, "e": 2234, "s": 2139, "text": "static int SCALE_AREA_AVERAGING -- \n Use the Area Averaging image scaling algorithm." }, { "code": null, "e": 2329, "s": 2234, "text": "static int SCALE_AREA_AVERAGING -- \n Use the Area Averaging image scaling algorithm." }, { "code": null, "e": 2399, "s": 2329, "text": "static int SCALE_DEFAULT -- Use the default image-scaling algorithm." }, { "code": null, "e": 2469, "s": 2399, "text": "static int SCALE_DEFAULT -- Use the default image-scaling algorithm." }, { "code": null, "e": 2610, "s": 2469, "text": "static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image." }, { "code": null, "e": 2751, "s": 2610, "text": "static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image." }, { "code": null, "e": 2858, "s": 2751, "text": "static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class." }, { "code": null, "e": 2965, "s": 2858, "text": "static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class." }, { "code": null, "e": 3094, "s": 2965, "text": "static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed." }, { "code": null, "e": 3223, "s": 3094, "text": "static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed." }, { "code": null, "e": 3384, "s": 3223, "text": "static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched." }, { "code": null, "e": 3545, "s": 3384, "text": "static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched." }, { "code": null, "e": 3553, "s": 3545, "text": "Image()" }, { "code": null, "e": 3567, "s": 3553, "text": "void flush() " }, { "code": null, "e": 3639, "s": 3567, "text": " Flushes all reconstructable resources being used by this Image object." }, { "code": null, "e": 3672, "s": 3639, "text": "float getAccelerationPriority() " }, { "code": null, "e": 3734, "s": 3672, "text": " Returns the current value of the acceleration priority hint." }, { "code": null, "e": 3795, "s": 3734, "text": "ImageCapabilities getCapabilities(GraphicsConfiguration gc) " }, { "code": null, "e": 3931, "s": 3795, "text": " Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration." }, { "code": null, "e": 3964, "s": 3931, "text": "abstract Graphics getGraphics() " }, { "code": null, "e": 4027, "s": 3964, "text": "Creates a graphics context for drawing to an off-screen image." }, { "code": null, "e": 4075, "s": 4027, "text": "abstract int getHeight(ImageObserver observer) " }, { "code": null, "e": 4111, "s": 4075, "text": "Determines the height of the image." }, { "code": null, "e": 4177, "s": 4111, "text": "abstract Object getProperty(String name, ImageObserver observer) " }, { "code": null, "e": 4216, "s": 4177, "text": "Gets a property of this image by name." }, { "code": null, "e": 4275, "s": 4216, "text": "Image getScaledInstance(int width, int height, int hints) " }, { "code": null, "e": 4315, "s": 4275, "text": "Creates a scaled version of this image." }, { "code": null, "e": 4351, "s": 4315, "text": "abstract ImageProducer getSource() " }, { "code": null, "e": 4407, "s": 4351, "text": "Gets the object that produces the pixels for the image." }, { "code": null, "e": 4454, "s": 4407, "text": "abstract int getWidth(ImageObserver observer) " }, { "code": null, "e": 4489, "s": 4454, "text": "Determines the width of the image." }, { "code": null, "e": 4535, "s": 4489, "text": "void setAccelerationPriority(float priority) " }, { "code": null, "e": 4599, "s": 4535, "text": "Sets a hint for this image about how important acceleration is." }, { "code": null, "e": 4655, "s": 4599, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 4672, "s": 4655, "text": "java.lang.Object" }, { "code": null, "e": 4689, "s": 4672, "text": "java.lang.Object" }, { "code": null, "e": 4803, "s": 4689, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 6782, "s": 4803, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showImageDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showImageDemo(){\n headerLabel.setText(\"Control in action: Image\"); \n\n controlPanel.add(new ImageComponent(\"resources/java.jpg\"));\n mainFrame.setVisible(true); \n }\n\t\n class ImageComponent extends Component {\n\n BufferedImage img;\n\n public void paint(Graphics g) {\n g.drawImage(img, 0, 0, null);\n }\n\n public ImageComponent(String path) {\n try {\n img = ImageIO.read(new File(path));\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public Dimension getPreferredSize() {\n if (img == null) {\n return new Dimension(100,100);\n } else {\n return new Dimension(img.getWidth(), img.getHeight());\n }\n }\n }\n}" }, { "code": null, "e": 6873, "s": 6782, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 6929, "s": 6873, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 7026, "s": 6929, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 7076, "s": 7026, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 7104, "s": 7076, "text": "Verify the following output" }, { "code": null, "e": 7137, "s": 7104, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7145, "s": 7137, "text": " EduOLC" }, { "code": null, "e": 7152, "s": 7145, "text": " Print" }, { "code": null, "e": 7163, "s": 7152, "text": " Add Notes" } ]
Compare two files using Hashing in Python - GeeksforGeeks
10 Jun, 2021 In this article, we would be creating a program that would determine, whether two files provided to it are the same or not. By the same means that their contents are the same or not (excluding any metadata). We would be using Cryptographic Hashes for this purpose. A cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. We would be using this property of Cryptographic hash functions to identify the contents of two files, and then would compare that to determine whether they are same or not. Note: The probability of getting the same has for two different data set is very very low. And even then the good cryptographic hash functions are made so that hash collisions are accidental rather than intentional. We would be using SHA256 (Secure hash algorithm 256) as a hash function in this program. SHA256 is very resistant to collisions. We would be using hashlib library’s sha256() to use the implementation of the function in python. hashlib module is preinstalled in most python distributions. If it doesn’t exists in your environment, then you can get the module by running the following command in the command– pip install hashlib Below is the implementation.Text File 1: Text File 2: Python3 import sysimport hashlib def hashfile(file): # A arbitrary (but fixed) buffer # size (change accordingly) # 65536 = 65536 bytes = 64 kilobytes BUF_SIZE = 65536 # Initializing the sha256() method sha256 = hashlib.sha256() # Opening the file provided as # the first commandline argument with open(file, 'rb') as f: while True: # reading data = BUF_SIZE from # the file and saving it in a # variable data = f.read(BUF_SIZE) # True if eof = 1 if not data: break # Passing that data to that sh256 hash # function (updating the function with # that data) sha256.update(data) # sha256.hexdigest() hashes all the input # data passed to the sha256() via sha256.update() # Acts as a finalize method, after which # all the input data gets hashed hexdigest() # hashes the data, and returns the output # in hexadecimal format return sha256.hexdigest() # Calling hashfile() function to obtain hashes# of the files, and saving the result# in a variablef1_hash = hashfile(sys.argv[1])f2_hash = hashfile(sys.argv[2]) # Doing primitive string comparison to# check whether the two hashes match or notif f1_hash == f2_hash: print("Both files are same") print(f"Hash: {f1_hash}") else: print("Files are different!") print(f"Hash of File 1: {f1_hash}") print(f"Hash of File 2: {f2_hash}") Output:For Different Files as Input: For Same Files as Input: Explanation:-We take in input the filenames (via command-line argument), therefore the file paths must be provided from the command line. The function hashfile() is defined, to deal with arbitrary file sizes without running out of memory. As if we pass all the data in a file to the sha256.update() function, it doesn’t hash the data properly leading to inconsistency in the results. hashfile() returns the hash of the file in base16 (hexadecimal format). We call the same function for both the files and store their hashes in two separate variables. After which we use the hashes to compare them. If both the hashes are same (meaning the files contain same data), we output the message Both files are same and then the hash. If they are different we output a negative message, and the hash of each file (so that the user can visually see the different hashes). VasuDev4 clintra python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n10 Jun, 2021" }, { "code": null, "e": 26156, "s": 25555, "text": "In this article, we would be creating a program that would determine, whether two files provided to it are the same or not. By the same means that their contents are the same or not (excluding any metadata). We would be using Cryptographic Hashes for this purpose. A cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. We would be using this property of Cryptographic hash functions to identify the contents of two files, and then would compare that to determine whether they are same or not. " }, { "code": null, "e": 26372, "s": 26156, "text": "Note: The probability of getting the same has for two different data set is very very low. And even then the good cryptographic hash functions are made so that hash collisions are accidental rather than intentional." }, { "code": null, "e": 26780, "s": 26372, "text": "We would be using SHA256 (Secure hash algorithm 256) as a hash function in this program. SHA256 is very resistant to collisions. We would be using hashlib library’s sha256() to use the implementation of the function in python. hashlib module is preinstalled in most python distributions. If it doesn’t exists in your environment, then you can get the module by running the following command in the command– " }, { "code": null, "e": 26800, "s": 26780, "text": "pip install hashlib" }, { "code": null, "e": 26842, "s": 26800, "text": "Below is the implementation.Text File 1: " }, { "code": null, "e": 26856, "s": 26842, "text": "Text File 2: " }, { "code": null, "e": 26864, "s": 26856, "text": "Python3" }, { "code": "import sysimport hashlib def hashfile(file): # A arbitrary (but fixed) buffer # size (change accordingly) # 65536 = 65536 bytes = 64 kilobytes BUF_SIZE = 65536 # Initializing the sha256() method sha256 = hashlib.sha256() # Opening the file provided as # the first commandline argument with open(file, 'rb') as f: while True: # reading data = BUF_SIZE from # the file and saving it in a # variable data = f.read(BUF_SIZE) # True if eof = 1 if not data: break # Passing that data to that sh256 hash # function (updating the function with # that data) sha256.update(data) # sha256.hexdigest() hashes all the input # data passed to the sha256() via sha256.update() # Acts as a finalize method, after which # all the input data gets hashed hexdigest() # hashes the data, and returns the output # in hexadecimal format return sha256.hexdigest() # Calling hashfile() function to obtain hashes# of the files, and saving the result# in a variablef1_hash = hashfile(sys.argv[1])f2_hash = hashfile(sys.argv[2]) # Doing primitive string comparison to# check whether the two hashes match or notif f1_hash == f2_hash: print(\"Both files are same\") print(f\"Hash: {f1_hash}\") else: print(\"Files are different!\") print(f\"Hash of File 1: {f1_hash}\") print(f\"Hash of File 2: {f2_hash}\")", "e": 28373, "s": 26864, "text": null }, { "code": null, "e": 28411, "s": 28373, "text": "Output:For Different Files as Input: " }, { "code": null, "e": 28437, "s": 28411, "text": "For Same Files as Input: " }, { "code": null, "e": 29300, "s": 28437, "text": "Explanation:-We take in input the filenames (via command-line argument), therefore the file paths must be provided from the command line. The function hashfile() is defined, to deal with arbitrary file sizes without running out of memory. As if we pass all the data in a file to the sha256.update() function, it doesn’t hash the data properly leading to inconsistency in the results. hashfile() returns the hash of the file in base16 (hexadecimal format). We call the same function for both the files and store their hashes in two separate variables. After which we use the hashes to compare them. If both the hashes are same (meaning the files contain same data), we output the message Both files are same and then the hash. If they are different we output a negative message, and the hash of each file (so that the user can visually see the different hashes). " }, { "code": null, "e": 29309, "s": 29300, "text": "VasuDev4" }, { "code": null, "e": 29317, "s": 29309, "text": "clintra" }, { "code": null, "e": 29332, "s": 29317, "text": "python-utility" }, { "code": null, "e": 29339, "s": 29332, "text": "Python" }, { "code": null, "e": 29437, "s": 29339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29469, "s": 29437, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29511, "s": 29469, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29553, "s": 29511, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29609, "s": 29553, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29636, "s": 29609, "text": "Python Classes and Objects" }, { "code": null, "e": 29667, "s": 29636, "text": "Python | os.path.join() method" }, { "code": null, "e": 29696, "s": 29667, "text": "Create a directory in Python" }, { "code": null, "e": 29718, "s": 29696, "text": "Defaultdict in Python" }, { "code": null, "e": 29757, "s": 29718, "text": "Python | Get unique values from a list" } ]
How to create a Dictionary in PowerShell?
To create a dictionary in the PowerShell we need to use the class Dictionary from the .Net namespace System.Collections.Generic. It has TKey and TValue. Its basic syntax is Dictionary<TKey,TValue> To learn more about this .Net namespace check the link below. https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0 To create a dictionary we will first create the object for the dictionary object class with the datatypes. In the below example, we need to add the Country name and the country code. So we need String and Int. $countrydata = New-Object System.Collections.Generic.Dictionary"[String,Int]" Once we check the type of the $countrydata variable, it should be the dictionary. For example, PS C:\> $Countrydata.GetType() | ft -AutoSize IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Dictionary`2 System.Object Let’s check which methods are available. PS C:\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype Name MemberType ---- ---------- Add Method Clear Method Contains Method ContainsKey Method ContainsValue Method CopyTo Method EnsureCapacity Method Equals Method GetEnumerator Method GetHashCode Method GetObjectData Method GetType Method OnDeserialization Method Remove Method ToString Method TrimExcess Method TryAdd Method TryGetValue Method So we can use Add() method to insert the members. PS C:\> $Countrydata.Add("India",91) PS C:\> $Countrydata.Add("Algeria",213) Once you check the value, its output should be in the Key-Value pair. PS C:\> $Countrydata Key Value --- ----- India 91 Algeria 213 Generally, PowerShell programmers don’t use the directory because of its uncommon syntax and tend to use the Hashtable because can be easily created.
[ { "code": null, "e": 1235, "s": 1062, "text": "To create a dictionary in the PowerShell we need to use the class Dictionary from the .Net namespace System.Collections.Generic. It has TKey and TValue. Its basic syntax is" }, { "code": null, "e": 1259, "s": 1235, "text": "Dictionary<TKey,TValue>" }, { "code": null, "e": 1321, "s": 1259, "text": "To learn more about this .Net namespace check the link below." }, { "code": null, "e": 1418, "s": 1321, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0" }, { "code": null, "e": 1628, "s": 1418, "text": "To create a dictionary we will first create the object for the dictionary object class with the datatypes. In the below example, we need to add the Country name and the country code. So we need String and Int." }, { "code": null, "e": 1706, "s": 1628, "text": "$countrydata = New-Object System.Collections.Generic.Dictionary\"[String,Int]\"" }, { "code": null, "e": 1801, "s": 1706, "text": "Once we check the type of the $countrydata variable, it should be the dictionary. For example," }, { "code": null, "e": 1847, "s": 1801, "text": "PS C:\\> $Countrydata.GetType() | ft -AutoSize" }, { "code": null, "e": 1972, "s": 1847, "text": "IsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True Dictionary`2 System.Object" }, { "code": null, "e": 2013, "s": 1972, "text": "Let’s check which methods are available." }, { "code": null, "e": 2092, "s": 2013, "text": "PS C:\\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype" }, { "code": null, "e": 2672, "s": 2092, "text": "Name MemberType\n---- ----------\nAdd Method\nClear Method\nContains Method\nContainsKey Method\nContainsValue Method\nCopyTo Method\nEnsureCapacity Method\nEquals Method\nGetEnumerator Method\nGetHashCode Method\nGetObjectData Method\nGetType Method\nOnDeserialization Method\nRemove Method\nToString Method\nTrimExcess Method\nTryAdd Method\nTryGetValue Method" }, { "code": null, "e": 2722, "s": 2672, "text": "So we can use Add() method to insert the members." }, { "code": null, "e": 2799, "s": 2722, "text": "PS C:\\> $Countrydata.Add(\"India\",91)\nPS C:\\> $Countrydata.Add(\"Algeria\",213)" }, { "code": null, "e": 2869, "s": 2799, "text": "Once you check the value, its output should be in the Key-Value pair." }, { "code": null, "e": 2890, "s": 2869, "text": "PS C:\\> $Countrydata" }, { "code": null, "e": 2946, "s": 2890, "text": "Key Value\n--- -----\nIndia 91\nAlgeria 213" }, { "code": null, "e": 3096, "s": 2946, "text": "Generally, PowerShell programmers don’t use the directory because of its uncommon syntax and tend to use the Hashtable because can be easily created." } ]
C# Program To Remove Duplicates From A Given String - GeeksforGeeks
11 Dec, 2021 Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. METHOD 1 (Simple) C# // C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;class GFG {static String removeDuplicate(char []str, int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } char [] ans = new char[index]; Array.Copy(str, ans, index); return String.Join("", ans);} // Driver codepublic static void Main(String[] args){ char []str = "geeksforgeeks".ToCharArray(); int n = str.Length; Console.WriteLine(removeDuplicate(str, n));}} // This code is contributed by PrinciRaj1992 Output: geksfor Time Complexity : O(n * n) Auxiliary Space : O(1) Keeps order of elements the same as input. METHOD 2 (Use BST) use set which implements a self-balancing Binary Search Tree. C# // C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '�' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= "geeksforgeeks".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1 Output: efgkors Time Complexity: O(n Log n) Auxiliary Space: O(n) Thanks to Anivesh Tiwari for suggesting this approach. It does not keep the order of elements the same as the input but prints them in sorted order. METHOD 3 (Use Sorting) Algorithm: 1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string. Example: Input string: geeksforgeeks 1) Sort the characters eeeefggkkorss 2) Remove duplicates efgkorskkorss 3) Remove extra characters efgkors Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order. Implementation: C# // C# program to remove duplicates, the order of// characters is not maintained in this programusing System; class GFG { /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char []arr = str.ToCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.Length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.Substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char []temp = str.ToCharArray(); Array.Sort(temp); str = String.Join("",temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void Main(String[] args) { String str = "geeksforgeeks"; Console.WriteLine(removeDups(str)); }} // This code is contributed by 29AjayKumar Output: efgkors Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort. Auxiliary Space: O(1) METHOD 4 (Use Hashing ) Algorithm: 1: Initialize: str = "test string" /* input string */ ip_ind = 0 /* index to keep track of location of next character in input string */ res_ind = 0 /* index to keep track of location of next character in the resultant string */ bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is already processed or not */ 2: Do following for each character *(str + ip_ind) in input string: (a) if bin_hash is not set for *(str + ip_ind) then // if program sees the character *(str + ip_ind) first time (i) Set bin_hash for *(str + ip_ind) (ii) Move *(str + ip_ind) to the resultant string. This is done in-place. (iii) res_ind++ (b) ip_ind++ /* String obtained after this step is "te stringing" */ 3: Remove extra characters at the end of the resultant string. /* String obtained after this step is "te string" */ Implementation: C# // C# program to remove duplicatesusing System;using System.Collections.Generic; class GFG{ /* Function removes duplicate characters from the string. This function work in-place */ void removeDuplicates(String str) { HashSet<char> lhs = new HashSet<char>(); for(int i = 0; i < str.Length; i++) lhs.Add(str[i]); // print string after deleting // duplicate elements foreach(char ch in lhs) Console.Write(ch); } // Driver Code public static void Main(String []args) { String str = "geeksforgeeks"; GFG r = new GFG(); r.removeDuplicates(str); }} // This code is contributed by Rajput-Ji Output: geksfor Time Complexity: O(n) Important Points: Method 2 doesn’t maintain the characters as original strings, but method 4 does. It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly. calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘�’. the malloc() followed by memset() could also be used. The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100 Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method C# // C# program to create a unique stringusing System; public class IndexOf { // Function to make the string unique public static String unique(String s) { String str = ""; int len = s.Length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.IndexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void Main(String[] args) { // Input string with repeating chars String s = "geeksforgeeks"; Console.WriteLine(unique(s)); }} // This code is contributed by Princi Singh Output: geksfor Thanks debjitdbb for suggesting this approach. Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method C# // C# program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occur and therefore it helps us check if an element exists in a String in O(1) time complexity with constant space. */using System;using System.Collections.Generic; public class GFG{ static char[] removeDuplicates(char []s,int n){ Dictionary<char,int> exists = new Dictionary<char, int>(); String st = ""; for(int i = 0; i < n; i++){ if(!exists.ContainsKey(s[i])) { st += s[i]; exists.Add(s[i], 1); } } return st.ToCharArray();} // driver codepublic static void Main(String[] args){ char []s = "geeksforgeeks".ToCharArray(); int n = s.Length; Console.Write(removeDuplicates(s,n));}} // This code is contributed by umadevi9616 Output: geksfor Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach. Please refer complete article on Remove duplicates from a given string for more details! frequency-counting C Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string Handling multiple clients on server with multithreading using Socket Programming in C/C++ Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25028, "s": 25000, "text": "\n11 Dec, 2021" }, { "code": null, "e": 25174, "s": 25028, "text": "Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string." }, { "code": null, "e": 25193, "s": 25174, "text": "METHOD 1 (Simple) " }, { "code": null, "e": 25196, "s": 25193, "text": "C#" }, { "code": "// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;class GFG {static String removeDuplicate(char []str, int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } char [] ans = new char[index]; Array.Copy(str, ans, index); return String.Join(\"\", ans);} // Driver codepublic static void Main(String[] args){ char []str = \"geeksforgeeks\".ToCharArray(); int n = str.Length; Console.WriteLine(removeDuplicate(str, n));}} // This code is contributed by PrinciRaj1992 ", "e": 26187, "s": 25196, "text": null }, { "code": null, "e": 26197, "s": 26187, "text": "Output: " }, { "code": null, "e": 26205, "s": 26197, "text": "geksfor" }, { "code": null, "e": 26299, "s": 26205, "text": "Time Complexity : O(n * n) Auxiliary Space : O(1) Keeps order of elements the same as input. " }, { "code": null, "e": 26381, "s": 26299, "text": "METHOD 2 (Use BST) use set which implements a self-balancing Binary Search Tree. " }, { "code": null, "e": 26384, "s": 26381, "text": "C#" }, { "code": "// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '�' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= \"geeksforgeeks\".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1", "e": 27127, "s": 26384, "text": null }, { "code": null, "e": 27137, "s": 27127, "text": "Output: " }, { "code": null, "e": 27147, "s": 27137, "text": " efgkors" }, { "code": null, "e": 27197, "s": 27147, "text": "Time Complexity: O(n Log n) Auxiliary Space: O(n)" }, { "code": null, "e": 27252, "s": 27197, "text": "Thanks to Anivesh Tiwari for suggesting this approach." }, { "code": null, "e": 27346, "s": 27252, "text": "It does not keep the order of elements the same as the input but prints them in sorted order." }, { "code": null, "e": 27381, "s": 27346, "text": "METHOD 3 (Use Sorting) Algorithm: " }, { "code": null, "e": 27576, "s": 27381, "text": " 1) Sort the elements.\n 2) Now in a loop, remove duplicates by comparing the \n current character with previous character.\n 3) Remove extra characters at the end of the resultant string." }, { "code": null, "e": 27587, "s": 27576, "text": "Example: " }, { "code": null, "e": 27735, "s": 27587, "text": "Input string: geeksforgeeks\n1) Sort the characters\n eeeefggkkorss\n2) Remove duplicates\n efgkorskkorss\n3) Remove extra characters\n efgkors" }, { "code": null, "e": 28047, "s": 27735, "text": "Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order." }, { "code": null, "e": 28065, "s": 28047, "text": "Implementation: " }, { "code": null, "e": 28068, "s": 28065, "text": "C#" }, { "code": "// C# program to remove duplicates, the order of// characters is not maintained in this programusing System; class GFG { /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char []arr = str.ToCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.Length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.Substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char []temp = str.ToCharArray(); Array.Sort(temp); str = String.Join(\"\",temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void Main(String[] args) { String str = \"geeksforgeeks\"; Console.WriteLine(removeDups(str)); }} // This code is contributed by 29AjayKumar", "e": 29421, "s": 28068, "text": null }, { "code": null, "e": 29431, "s": 29421, "text": "Output: " }, { "code": null, "e": 29439, "s": 29431, "text": "efgkors" }, { "code": null, "e": 29528, "s": 29439, "text": "Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort." }, { "code": null, "e": 29550, "s": 29528, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29575, "s": 29550, "text": "METHOD 4 (Use Hashing ) " }, { "code": null, "e": 29588, "s": 29575, "text": "Algorithm: " }, { "code": null, "e": 30704, "s": 29588, "text": "1: Initialize:\n str = \"test string\" /* input string */\n ip_ind = 0 /* index to keep track of location of next\n character in input string */\n res_ind = 0 /* index to keep track of location of\n next character in the resultant string */\n bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is \n already processed or not */\n2: Do following for each character *(str + ip_ind) in input string:\n (a) if bin_hash is not set for *(str + ip_ind) then\n // if program sees the character *(str + ip_ind) first time\n (i) Set bin_hash for *(str + ip_ind)\n (ii) Move *(str + ip_ind) to the resultant string.\n This is done in-place.\n (iii) res_ind++\n (b) ip_ind++\n /* String obtained after this step is \"te stringing\" */\n3: Remove extra characters at the end of the resultant string.\n /* String obtained after this step is \"te string\" */" }, { "code": null, "e": 30722, "s": 30704, "text": "Implementation: " }, { "code": null, "e": 30725, "s": 30722, "text": "C#" }, { "code": "// C# program to remove duplicatesusing System;using System.Collections.Generic; class GFG{ /* Function removes duplicate characters from the string. This function work in-place */ void removeDuplicates(String str) { HashSet<char> lhs = new HashSet<char>(); for(int i = 0; i < str.Length; i++) lhs.Add(str[i]); // print string after deleting // duplicate elements foreach(char ch in lhs) Console.Write(ch); } // Driver Code public static void Main(String []args) { String str = \"geeksforgeeks\"; GFG r = new GFG(); r.removeDuplicates(str); }} // This code is contributed by Rajput-Ji", "e": 31433, "s": 30725, "text": null }, { "code": null, "e": 31443, "s": 31433, "text": "Output: " }, { "code": null, "e": 31451, "s": 31443, "text": "geksfor" }, { "code": null, "e": 31473, "s": 31451, "text": "Time Complexity: O(n)" }, { "code": null, "e": 31493, "s": 31473, "text": "Important Points: " }, { "code": null, "e": 31574, "s": 31493, "text": "Method 2 doesn’t maintain the characters as original strings, but method 4 does." }, { "code": null, "e": 31698, "s": 31574, "text": "It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly." }, { "code": null, "e": 31879, "s": 31698, "text": "calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘�’. the malloc() followed by memset() could also be used." }, { "code": null, "e": 32135, "s": 31879, "text": "The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100" }, { "code": null, "e": 32210, "s": 32135, "text": "Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method " }, { "code": null, "e": 32213, "s": 32210, "text": "C#" }, { "code": "// C# program to create a unique stringusing System; public class IndexOf { // Function to make the string unique public static String unique(String s) { String str = \"\"; int len = s.Length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.IndexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void Main(String[] args) { // Input string with repeating chars String s = \"geeksforgeeks\"; Console.WriteLine(unique(s)); }} // This code is contributed by Princi Singh", "e": 33221, "s": 32213, "text": null }, { "code": null, "e": 33231, "s": 33221, "text": "Output: " }, { "code": null, "e": 33239, "s": 33231, "text": "geksfor" }, { "code": null, "e": 33287, "s": 33239, "text": "Thanks debjitdbb for suggesting this approach. " }, { "code": null, "e": 33377, "s": 33287, "text": "Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method " }, { "code": null, "e": 33380, "s": 33377, "text": "C#" }, { "code": "// C# program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occur and therefore it helps us check if an element exists in a String in O(1) time complexity with constant space. */using System;using System.Collections.Generic; public class GFG{ static char[] removeDuplicates(char []s,int n){ Dictionary<char,int> exists = new Dictionary<char, int>(); String st = \"\"; for(int i = 0; i < n; i++){ if(!exists.ContainsKey(s[i])) { st += s[i]; exists.Add(s[i], 1); } } return st.ToCharArray();} // driver codepublic static void Main(String[] args){ char []s = \"geeksforgeeks\".ToCharArray(); int n = s.Length; Console.Write(removeDuplicates(s,n));}} // This code is contributed by umadevi9616", "e": 34169, "s": 33380, "text": null }, { "code": null, "e": 34179, "s": 34169, "text": "Output: " }, { "code": null, "e": 34187, "s": 34179, "text": "geksfor" }, { "code": null, "e": 34289, "s": 34187, "text": "Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach. " }, { "code": null, "e": 34378, "s": 34289, "text": "Please refer complete article on Remove duplicates from a given string for more details!" }, { "code": null, "e": 34397, "s": 34378, "text": "frequency-counting" }, { "code": null, "e": 34408, "s": 34397, "text": "C Programs" }, { "code": null, "e": 34416, "s": 34408, "text": "Strings" }, { "code": null, "e": 34424, "s": 34416, "text": "Strings" }, { "code": null, "e": 34522, "s": 34424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34563, "s": 34522, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 34594, "s": 34563, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 34628, "s": 34594, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 34669, "s": 34628, "text": "C program to find the length of a string" }, { "code": null, "e": 34759, "s": 34669, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 34805, "s": 34759, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34830, "s": 34805, "text": "Reverse a string in Java" }, { "code": null, "e": 34864, "s": 34830, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 34879, "s": 34864, "text": "C++ Data Types" } ]
Java - Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are − Visible to the package, the default. No modifiers are needed. Visible to the class only (private). Visible to the world (public). Visible to the package and all subclasses (protected). Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public. Variables and methods can be declared without any modifiers, as in the following examples − String version = "1.5.1"; boolean processOrder() { return true; } Methods, variables, and constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world. The following class uses private access control − public class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } } Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly. So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value. A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. The following function uses public access control − public static void main(String[] arguments) { // ... } The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class. Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected. Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. The following parent class uses protected access control, to allow its child class override openSpeaker() method − class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation details } } class StreamingAudioPlayer extends AudioPlayer { boolean openSpeaker(Speaker sp) { // implementation details } } Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier. The following rules for inherited methods are enforced − Methods declared public in a superclass also must be public in all subclasses. Methods declared public in a superclass also must be public in all subclasses. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private. Methods declared private are not inherited at all, so there is no rule for them. Methods declared private are not inherited at all, so there is no rule for them. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2521, "s": 2377, "text": "Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are −" }, { "code": null, "e": 2583, "s": 2521, "text": "Visible to the package, the default. No modifiers are needed." }, { "code": null, "e": 2620, "s": 2583, "text": "Visible to the class only (private)." }, { "code": null, "e": 2651, "s": 2620, "text": "Visible to the world (public)." }, { "code": null, "e": 2706, "s": 2651, "text": "Visible to the package and all subclasses (protected)." }, { "code": null, "e": 2817, "s": 2706, "text": "Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc." }, { "code": null, "e": 3053, "s": 2817, "text": "A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public." }, { "code": null, "e": 3145, "s": 3053, "text": "Variables and methods can be declared without any modifiers, as in the following examples −" }, { "code": null, "e": 3215, "s": 3145, "text": "String version = \"1.5.1\";\n\nboolean processOrder() {\n return true;\n}" }, { "code": null, "e": 3333, "s": 3215, "text": "Methods, variables, and constructors that are declared private can only be accessed within the declared class itself." }, { "code": null, "e": 3435, "s": 3333, "text": "Private access modifier is the most restrictive access level. Class and interfaces cannot be private." }, { "code": null, "e": 3557, "s": 3435, "text": "Variables that are declared private can be accessed outside the class, if public getter methods are present in the class." }, { "code": null, "e": 3674, "s": 3557, "text": "Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world." }, { "code": null, "e": 3724, "s": 3674, "text": "The following class uses private access control −" }, { "code": null, "e": 3913, "s": 3724, "text": "public class Logger {\n private String format;\n\n public String getFormat() {\n return this.format;\n }\n\n public void setFormat(String format) {\n this.format = format;\n }\n}" }, { "code": null, "e": 4046, "s": 3913, "text": "Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly." }, { "code": null, "e": 4228, "s": 4046, "text": "So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value." }, { "code": null, "e": 4457, "s": 4228, "text": "A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe." }, { "code": null, "e": 4694, "s": 4457, "text": "However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses." }, { "code": null, "e": 4746, "s": 4694, "text": "The following function uses public access control −" }, { "code": null, "e": 4804, "s": 4746, "text": "public static void main(String[] arguments) {\n // ...\n}" }, { "code": null, "e": 4947, "s": 4804, "text": "The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class." }, { "code": null, "e": 5151, "s": 4947, "text": "Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class." }, { "code": null, "e": 5339, "s": 5151, "text": "The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected." }, { "code": null, "e": 5481, "s": 5339, "text": "Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it." }, { "code": null, "e": 5596, "s": 5481, "text": "The following parent class uses protected access control, to allow its child class override openSpeaker() method −" }, { "code": null, "e": 5828, "s": 5596, "text": "class AudioPlayer {\n protected boolean openSpeaker(Speaker sp) {\n // implementation details\n }\n}\n\nclass StreamingAudioPlayer extends AudioPlayer {\n boolean openSpeaker(Speaker sp) {\n // implementation details\n }\n}" }, { "code": null, "e": 6151, "s": 5828, "text": "Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier." }, { "code": null, "e": 6208, "s": 6151, "text": "The following rules for inherited methods are enforced −" }, { "code": null, "e": 6287, "s": 6208, "text": "Methods declared public in a superclass also must be public in all subclasses." }, { "code": null, "e": 6366, "s": 6287, "text": "Methods declared public in a superclass also must be public in all subclasses." }, { "code": null, "e": 6483, "s": 6366, "text": "Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private." }, { "code": null, "e": 6600, "s": 6483, "text": "Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private." }, { "code": null, "e": 6681, "s": 6600, "text": "Methods declared private are not inherited at all, so there is no rule for them." }, { "code": null, "e": 6762, "s": 6681, "text": "Methods declared private are not inherited at all, so there is no rule for them." }, { "code": null, "e": 6795, "s": 6762, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6811, "s": 6795, "text": " Malhar Lathkar" }, { "code": null, "e": 6844, "s": 6811, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6860, "s": 6844, "text": " Malhar Lathkar" }, { "code": null, "e": 6895, "s": 6860, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6909, "s": 6895, "text": " Anadi Sharma" }, { "code": null, "e": 6943, "s": 6909, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6957, "s": 6943, "text": " Tushar Kale" }, { "code": null, "e": 6994, "s": 6957, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7009, "s": 6994, "text": " Monica Mittal" }, { "code": null, "e": 7042, "s": 7009, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7061, "s": 7042, "text": " Arnab Chakraborty" }, { "code": null, "e": 7068, "s": 7061, "text": " Print" }, { "code": null, "e": 7079, "s": 7068, "text": " Add Notes" } ]
GATE | GATE-CS-2015 (Set 1) | Question 21 - GeeksforGeeks
28 Jun, 2021 The output of the following C program is __________. void f1 (int a, int b){ int c; c=a; a=b; b=c;}void f2 (int *a, int *b){ int c; c=*a; *a=*b;*b=c;}int main(){ int a=4, b=5, c=6; f1(a, b); f2(&b, &c); printf (“%d”, c-a-b); return 0;} (A) -5(B) -4(C) 5(D) 3Answer: (A)Explanation: The function call to to f1(a, b) won’t have any effect as the values are passed by value. The function call f2(&b, &c) swaps values of b and c. So b becomes 6 and c becomes 5. Value of c-a-b becomes 5-4-6 which is -5.Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2007 | Question 64 GATE | GATE-CS-2014-(Set-2) | Question 65
[ { "code": null, "e": 24466, "s": 24438, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24519, "s": 24466, "text": "The output of the following C program is __________." }, { "code": "void f1 (int a, int b){ int c; c=a; a=b; b=c;}void f2 (int *a, int *b){ int c; c=*a; *a=*b;*b=c;}int main(){ int a=4, b=5, c=6; f1(a, b); f2(&b, &c); printf (“%d”, c-a-b); return 0;}", "e": 24711, "s": 24519, "text": null }, { "code": null, "e": 24847, "s": 24711, "text": "(A) -5(B) -4(C) 5(D) 3Answer: (A)Explanation: The function call to to f1(a, b) won’t have any effect as the values are passed by value." }, { "code": null, "e": 24996, "s": 24847, "text": "The function call f2(&b, &c) swaps values of b and c. So b becomes 6 and c becomes 5. Value of c-a-b becomes 5-4-6 which is -5.Quiz of this Question" }, { "code": null, "e": 25017, "s": 24996, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25043, "s": 25017, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25048, "s": 25043, "text": "GATE" }, { "code": null, "e": 25146, "s": 25048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25155, "s": 25146, "text": "Comments" }, { "code": null, "e": 25168, "s": 25155, "text": "Old Comments" }, { "code": null, "e": 25202, "s": 25168, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25235, "s": 25202, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25277, "s": 25235, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25319, "s": 25277, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25361, "s": 25319, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25395, "s": 25361, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25429, "s": 25395, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25471, "s": 25429, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25505, "s": 25471, "text": "GATE | GATE-CS-2007 | Question 64" } ]
3 Divisors | Practice | GeeksforGeeks
You have given a list of q queries and for every query, you are given an integer N. The task is to find how many numbers(less than or equal to N) have number of divisors exactly equal to 3. Example 1: Input: q = 1 query[0] = 6 Output: 1 Explanation: There is only one number 4 which has exactly three divisors 1, 2 and 4 and less than equal to 6. Example 2: Input: q = 2 query[0] = 6 query[1] = 10 Output: 1 2 Explanation: For query 1 it is covered in the example 1. query 2: There are two numbers 4 and 9 having exactly 3 divisors and less than equal to 10. Your Task: You don't need to read input or print anything. Your task is to complete the function threeDivisors() which takes an integer q and a list of integer of size q as input parameter and returns the list containing the count of the numbers having exactly 3 divisors for each query. Expected Time Complexity: O(NlogN), Expected Auxiliary Space: O(N), where N is min(10^6,N) Constraints : 1 <= q <= 103 1 <= query[i] <= 1012 +1 sourabhgharad19061 month ago static ArrayList<Integer> threeDivisors(ArrayList<Long> query, int q){ // code here ArrayList<Integer> res = new ArrayList<>(); long max = 0; for(int i=0;i<q;i++){ max = Math.max(max,query.get(i)); } long nmax = (long)Math.sqrt(max); //nmax means new maximum boolean arr[] = new boolean[(int)nmax+1]; Arrays.fill(arr,true); for(int i=2;i<=nmax;i++){ if(arr[i]){ for(int j=2;j*i<=nmax;j++){ arr[j*i] = false; } } } int sum = 0; int ans[] = new int[arr.length]; for(int i=2;i<arr.length;i++){ if(arr[i]){ sum++; } ans[i] = sum; } for(int i=0;i<query.size();i++){ res.add((int)ans[(int)Math.sqrt(query.get(i))]); } return res; } 0 sourabhgharad1906 This comment was deleted. 0 santosh9yogi5 months ago // JavaScript // running time is too much plz suggest me to reduce running timing class Solution{ threeDivisors(query, q){ //code here let ans = 0; for(let i = 1; i < query; i++){ let j = 1; let count = 0; while(j <= i ){ if( i%j === 0){ count++; }else continue; } if(count == 3){ ans++; } else continue; } return ans; } } 0 kstgeek1236 months ago q = int(input())for i in range(q): n = int(input()) L=[] k=0 i=1 while i*i <= n: L.append(i) i += 1 for x in L: if x**0.5 != int(x**0.5): #print(x) k += 1 print(k) 0 user0037 This comment was deleted. +1 Raushan Kumar8 months ago Raushan Kumar class Solution{public: int m = 1000001; void seive(vector<long long="">&isprime,vector<long long="">&primes){ isprime[0] = 0; isprime[1] = 0; for(int i = 2; i <= sqrt(m); i++){ if(isprime[i]){ for(int j = 2; j*i <= m; j++){ isprime[j*i] = 0; } } } int count = 0; for(int i = 2; i <= m; i++){ if(isprime[i]) count++; primes[i] = count; } } vector<int> threeDivisors(vector<long long=""> query, int q) { vector<long long="">isprime(1000001,1); vector<long long="">primes(1000001,0); seive(isprime,primes); vector<int>v; for(int i = 0; i < q; i++){ int p = primes[int(sqrt(query[i]))]; v.push_back(p); } return v; }}; 0 DiedToday9 months ago DiedToday Just Count the prime numbers whose square lies between 1 to N. 0 Mufeed Amir1 year ago Mufeed Amir PYTHON SOLUTION-0.21 sec class Solution: def threeDivisors(self, query, q): import math as mt n=mt.floor(mt.sqrt(max(query))) arr=[False for x in range(0,n+1)] arr[0]=arr[1]=True i=2 while i<=mt.sqrt(n): for j in range(i*i,n+1,i): arr[j]=True i=i+1 a=0 aa=[] for y in range(0,n+1): if arr[y]==False: a=a+1 aa.append(a) bomb=[] for i in range(0,q): b=aa[mt.floor(mt.sqrt(query[i]))] bomb.append(b) return bomb 0 Pramod Tarpe1 year ago Pramod Tarpe vector<int> threeDivisors(vector<long long=""> query, int q){ int sieve[1000001]; for(int i=2;i<1000001;i++){ sieve[i] = 1; } sieve[0] = sieve[1] = 0; for(long long i=0;i<1000001;i++){ if(sieve[i]&1){ long long index = i*i; while(index < 1000001){ sieve[index] = 0; index += i; } } } for(int i=1;i<1000001;i++){ sieve[i] += sieve[i-1]; } vector<int> ans; for(int i=0;i<q;i++){ long="" long="" root="sqrt(query[i]);" ans.push_back(sieve[root]);="" }="" return="" ans;="" }<="" code=""> 0 Akash Kumar Seth1 year ago Akash Kumar Seth Python solutiondef threeDivisors(self, query, q): # square of prime number less than or equal to query satisfy the condition result = [0]*q sortedQueryIndex = sorted(range(q), key=query.__getitem__) query.sort() # find primeSquare of max query x = int(max(query) ** 0.5) primeSquare = self.primeNumSquare(x) #set the num of divisor for each query to result count = 0 i = 0 for j in range(q): while i < len(primeSquare) and primeSquare[i] <= query[j]: count += 1 i += 1 result[sortedQueryIndex[j]] = count return result def primeNumSquare(self, n): if n < 2: return 0 primes = [1] * (n + 1) primeSquare = [] for i in range(2, n + 1): if primes[i]: for j in range(i, n + 1, i): primes[j] = 0 primeSquare.append(i ** 2) return primeSquare 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": 430, "s": 238, "text": "You have given a list of q queries and for every query, you are given an integer N. The task is to find how many numbers(less than or equal to N) have number of divisors exactly equal to 3. " }, { "code": null, "e": 441, "s": 430, "text": "Example 1:" }, { "code": null, "e": 587, "s": 441, "text": "Input:\nq = 1\nquery[0] = 6\nOutput:\n1\nExplanation:\nThere is only one number 4 which has\nexactly three divisors 1, 2 and 4 and\nless than equal to 6." }, { "code": null, "e": 598, "s": 587, "text": "Example 2:" }, { "code": null, "e": 800, "s": 598, "text": "Input:\nq = 2\nquery[0] = 6\nquery[1] = 10\nOutput:\n1\n2\nExplanation:\nFor query 1 it is covered in the\nexample 1.\nquery 2: There are two numbers 4 and 9\nhaving exactly 3 divisors and less than\nequal to 10.\n" }, { "code": null, "e": 1183, "s": 800, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function threeDivisors() which takes an integer q and a list of integer of size q as input parameter and returns the list containing the count of the numbers having exactly 3 divisors for each query.\n\nExpected Time Complexity: O(NlogN), \nExpected Auxiliary Space: O(N), where N is min(10^6,N)" }, { "code": null, "e": 1233, "s": 1183, "text": "Constraints :\n1 <= q <= 103\n1 <= query[i] <= 1012" }, { "code": null, "e": 1236, "s": 1233, "text": "+1" }, { "code": null, "e": 1265, "s": 1236, "text": "sourabhgharad19061 month ago" }, { "code": null, "e": 2189, "s": 1265, "text": " static ArrayList<Integer> threeDivisors(ArrayList<Long> query, int q){\n // code here\n ArrayList<Integer> res = new ArrayList<>();\n long max = 0;\n for(int i=0;i<q;i++){\n max = Math.max(max,query.get(i));\n }\n long nmax = (long)Math.sqrt(max); //nmax means new maximum\n boolean arr[] = new boolean[(int)nmax+1];\n Arrays.fill(arr,true);\n for(int i=2;i<=nmax;i++){\n if(arr[i]){\n for(int j=2;j*i<=nmax;j++){\n arr[j*i] = false;\n }\n }\n }\n int sum = 0;\n int ans[] = new int[arr.length];\n for(int i=2;i<arr.length;i++){\n if(arr[i]){\n sum++;\n }\n ans[i] = sum;\n }\n for(int i=0;i<query.size();i++){\n res.add((int)ans[(int)Math.sqrt(query.get(i))]);\n }\n return res;\n }\n " }, { "code": null, "e": 2191, "s": 2189, "text": "0" }, { "code": null, "e": 2209, "s": 2191, "text": "sourabhgharad1906" }, { "code": null, "e": 2235, "s": 2209, "text": "This comment was deleted." }, { "code": null, "e": 2237, "s": 2235, "text": "0" }, { "code": null, "e": 2262, "s": 2237, "text": "santosh9yogi5 months ago" }, { "code": null, "e": 2276, "s": 2262, "text": "// JavaScript" }, { "code": null, "e": 2344, "s": 2276, "text": "// running time is too much plz suggest me to reduce running timing" }, { "code": null, "e": 2829, "s": 2344, "text": "class Solution{\n threeDivisors(query, q){\n //code here\n let ans = 0;\n \n for(let i = 1; i < query; i++){\n let j = 1;\n let count = 0;\n while(j <= i ){\n \n if( i%j === 0){\n count++;\n }else continue;\n \n }\n if(count == 3){\n ans++;\n }\n else continue;\n }\n return ans;\n }\n}" }, { "code": null, "e": 2831, "s": 2829, "text": "0" }, { "code": null, "e": 2854, "s": 2831, "text": "kstgeek1236 months ago" }, { "code": null, "e": 3083, "s": 2854, "text": "q = int(input())for i in range(q): n = int(input()) L=[] k=0 i=1 while i*i <= n: L.append(i) i += 1 for x in L: if x**0.5 != int(x**0.5): #print(x) k += 1 print(k) " }, { "code": null, "e": 3085, "s": 3083, "text": "0" }, { "code": null, "e": 3094, "s": 3085, "text": "user0037" }, { "code": null, "e": 3120, "s": 3094, "text": "This comment was deleted." }, { "code": null, "e": 3123, "s": 3120, "text": "+1" }, { "code": null, "e": 3149, "s": 3123, "text": "Raushan Kumar8 months ago" }, { "code": null, "e": 3163, "s": 3149, "text": "Raushan Kumar" }, { "code": null, "e": 4109, "s": 3163, "text": "class Solution{public: int m = 1000001; void seive(vector<long long=\"\">&isprime,vector<long long=\"\">&primes){ isprime[0] = 0; isprime[1] = 0; for(int i = 2; i <= sqrt(m); i++){ if(isprime[i]){ for(int j = 2; j*i <= m; j++){ isprime[j*i] = 0; } } } int count = 0; for(int i = 2; i <= m; i++){ if(isprime[i]) count++; primes[i] = count; } } vector<int> threeDivisors(vector<long long=\"\"> query, int q) { vector<long long=\"\">isprime(1000001,1); vector<long long=\"\">primes(1000001,0); seive(isprime,primes); vector<int>v; for(int i = 0; i < q; i++){ int p = primes[int(sqrt(query[i]))]; v.push_back(p); } return v; }};" }, { "code": null, "e": 4111, "s": 4109, "text": "0" }, { "code": null, "e": 4133, "s": 4111, "text": "DiedToday9 months ago" }, { "code": null, "e": 4143, "s": 4133, "text": "DiedToday" }, { "code": null, "e": 4209, "s": 4143, "text": "Just Count the prime numbers whose square lies between 1 to N." }, { "code": null, "e": 4211, "s": 4209, "text": "0" }, { "code": null, "e": 4233, "s": 4211, "text": "Mufeed Amir1 year ago" }, { "code": null, "e": 4245, "s": 4233, "text": "Mufeed Amir" }, { "code": null, "e": 4270, "s": 4245, "text": "PYTHON SOLUTION-0.21 sec" }, { "code": null, "e": 4559, "s": 4270, "text": "class Solution: def threeDivisors(self, query, q): import math as mt n=mt.floor(mt.sqrt(max(query))) arr=[False for x in range(0,n+1)] arr[0]=arr[1]=True i=2 while i<=mt.sqrt(n): for j in range(i*i,n+1,i): arr[j]=True" }, { "code": null, "e": 4838, "s": 4559, "text": " i=i+1 a=0 aa=[] for y in range(0,n+1): if arr[y]==False: a=a+1 aa.append(a) bomb=[] for i in range(0,q): b=aa[mt.floor(mt.sqrt(query[i]))] bomb.append(b) return bomb" }, { "code": null, "e": 4840, "s": 4838, "text": "0" }, { "code": null, "e": 4863, "s": 4840, "text": "Pramod Tarpe1 year ago" }, { "code": null, "e": 4876, "s": 4863, "text": "Pramod Tarpe" }, { "code": null, "e": 5464, "s": 4876, "text": "vector<int> threeDivisors(vector<long long=\"\"> query, int q){ int sieve[1000001]; for(int i=2;i<1000001;i++){ sieve[i] = 1; } sieve[0] = sieve[1] = 0; for(long long i=0;i<1000001;i++){ if(sieve[i]&1){ long long index = i*i; while(index < 1000001){ sieve[index] = 0; index += i; } } } for(int i=1;i<1000001;i++){ sieve[i] += sieve[i-1]; } vector<int> ans; for(int i=0;i<q;i++){ long=\"\" long=\"\" root=\"sqrt(query[i]);\" ans.push_back(sieve[root]);=\"\" }=\"\" return=\"\" ans;=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 5466, "s": 5464, "text": "0" }, { "code": null, "e": 5493, "s": 5466, "text": "Akash Kumar Seth1 year ago" }, { "code": null, "e": 5510, "s": 5493, "text": "Akash Kumar Seth" }, { "code": null, "e": 6493, "s": 5510, "text": "Python solutiondef threeDivisors(self, query, q): # square of prime number less than or equal to query satisfy the condition result = [0]*q sortedQueryIndex = sorted(range(q), key=query.__getitem__) query.sort() # find primeSquare of max query x = int(max(query) ** 0.5) primeSquare = self.primeNumSquare(x) #set the num of divisor for each query to result count = 0 i = 0 for j in range(q): while i < len(primeSquare) and primeSquare[i] <= query[j]: count += 1 i += 1 result[sortedQueryIndex[j]] = count return result def primeNumSquare(self, n): if n < 2: return 0 primes = [1] * (n + 1) primeSquare = [] for i in range(2, n + 1): if primes[i]: for j in range(i, n + 1, i): primes[j] = 0 primeSquare.append(i ** 2) return primeSquare" }, { "code": null, "e": 6639, "s": 6493, "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": 6675, "s": 6639, "text": " Login to access your submissions. " }, { "code": null, "e": 6685, "s": 6675, "text": "\nProblem\n" }, { "code": null, "e": 6695, "s": 6685, "text": "\nContest\n" }, { "code": null, "e": 6758, "s": 6695, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6906, "s": 6758, "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": 7114, "s": 6906, "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": 7220, "s": 7114, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Seeing the random forest from the decision trees: An explanation of Random Forest | by Michelle Jane Tat | Towards Data Science
Over this past weekend, I got a little bored and decided to brush up on my R a bit. I have been programming in Python almost exclusively as a fellow at Insight, but I actually not had done much predictive analytics in R, save for pretty vanilla linear regressions. I wanted a somewhat clean data source where I can play around with modeling a bit in R. Thus, a good source of clean data is good ole’ kaggle. I decided to work on a Video Game Sales data set. Decision trees, and their cousins like bagged decision trees, random forest, gradient boosted decision trees etc., are commonly referred to as ensemble methods. To understand more complicated ensemble methods, I think it’s good to understand the most common of these methods, decision trees and random forest. Let take the simplest example: regression using decision trees. For a given data set with n-dimensions, a you can grow a ‘decision tree’ with n-branches, and n-leaves. The goal of a decision tree is to determine branches that reduce the residual sums of squares the most, and provide the most predictive leaves as possible. Perhaps a figure will help... The figure above represents a baseball related data set, where we want to determine the log salary of a player. On the left figure, if a player has less than 4.5 years experience, they are predicted to make 5.11 thousands of dollars. If a player has greater than 4.5 years experience, but fewer than 117.5 hits, they are predicted to make 6 thousands of dollars (again, log based). In the data on the right, the predicted values represent the subspaces R1, R2, and R3 respectively. The above example uses continuous data, but we can extend this to classification. In a classification setting, we are essentially growing branches that reduce classification error, although it’s not as straightforward as that. In the classification setting, we take an entropy-like measure, and try to reduce the amount of entropy at each branch to provide the best branch split. The Gini Index is a commonly used metric. p-hat mk represents the proportion of observations in the mth region from the kth class. In essence, the Gini index is a measure of variance. The higher the variance, the more mis-classification there is. Therefore lower values of the Gini Index yield better classification. Decision trees are commonly referred to as being “greedy”. This is simply a function of how the algorithm tries to determine the best way to reduce error. Unfortunately, this leads to model over-fitting and model over generalization. One method used to combat this is called bootstrap aggregation or ‘bagging’ for short. If you understand the idea of bootstrapping in statistics (in terms of estimating variance and error of an unknown population), the bagging is similar when it comes to decision trees. In bagging, we decide how many repeated bootstraps we want to take from our data set, fit them all to the same decision tree, then aggregate them back together. This gives us a more robust result, and is less prone to over fitting. Further, typically one third of the sample is left out of each bagged tree. We can then fit the bagged tree to the that sample, and obtain out-of-bag error rates. This essentially is a decision trees version of cross-validation, although you could perform cross-validation on top of out of bag error rates! Now that we have a general understanding of decision trees and bagging, the concept of random forest is relatively straightforward. A vanilla random forest is a bagged decision tree whereby an additional algorithm takes a random sample of m predictors at each split. This works to decorrelate trees used in random forest, and is useful in automatically combating multi-collinearity. In classification, all trees are aggregated back together. From this aggregation, the model essentially takes a poll / vote to assign data to a category. For a given observation, we can predict the class by observing what class each bagged tree outputs for that observation. Then we look across all trees to see how many times that observation was predicted. A class is then assigned to that observation if it is predicted from the majority of bagged trees. An overview of the dataset can be found here. All my terribly messy code can be found on my github. The goal for this example was to see if sales numbers and the console a game was on could predict it’s genre (e.g., sports, action, RPG, strategy, etc.). In this example, I make use of caret and ggplot2. I use the package dummies to generate dummy variables for categorical predictors. I wanted to get some practice using caret, which is essentially R’s version of scikit-learn. But first, as with any data set, it’s worth exploring it a little bit. My general approach is to look for quirkiness in the data first, explore potential correlations, then dig a bit deeper to see if there are any other trends worth noting in the data. Ideally, you will want to examine the data in every which way before modeling it. For brevity, I skipped some of the data exploration and jumped towards some modeling. First, I inspected the data for missing values. There were a ton of NaNs so I went ahead and did K-Nearest Neighbor Imputation using the DMwR package. Next, I wanted to generally inspect the sales data to find if there were any outliers. There were. And the distribution was highly skewed. I went ahead and normalized them using a log transform. From here, I generated dummy variables for the different consoles each game was on, and then examined the correlations. Global sales, not surprisingly, were correlated with all other sales. Critic Scores and counts were not. Not pictured here are correlations by console. There was not anything of note there, given the sparsity of console dummy data. One may simply remove the Global Sales variable in lieu of keeping all the other sales variables, if multi-collinearity was a huge concern. In caret , I did a 80%-20% train-test split, as common practice for conducting modeling. I relabeled all the genres as numbers, and they are as follows: SportsPlatformerRacingRPGPuzzleMiscellaneousShooterSimulationActionFightingAdventureStrategy Sports Platformer Racing RPG Puzzle Miscellaneous Shooter Simulation Action Fighting Adventure Strategy I did some grid searching on the number of features available at each tree split. Recall that Random Forest doesn’t take all available features when it creates a split for each node in the tree. This is a manipulable hyperparameter in the model. mtry <- sqrt(ncol(vg))tunegrid <- expand.grid(.mtry = mtry) In the code snippet above, I took the square root of number of columns as the initial number features available. Doing a grid search expands upon that such that caret will iterate through the initial start variable, then do another sqrt(ncol(vg)) additional features in the next fit iteration, then assess the model once more. metric <- 'Accuracy'control <- trainControl(method = 'repeatedcv', number = 10, repeats = 2, search = 'random', savePredictions = TRUE) Next, I set my metric as accuracy, since this is a classification procedure. I do cross validation to evaluate if my training data is wonky in any way. 5–10 number of folds (denoted as the number parameter) is typical. I do a random search because it’s a bit quicker and less computationally intensive. Using caret, I trained two models. One with 15 bagged trees. Another with 500 bagged trees. The 500 tree model took some time to run (maybe about 30 minutes?). One could easily incorporate the number of bagged trees in a grid search. For brevity (and time), I just compared two models. Note I allowed the model to use Box Cox to determine how to normalize the data appropriately (which it log transformed the data). model_train1 <- train(Genre ~ ., data = vg_train, method = 'rf', trControl = control, tunegrid = tunegrid, metric = metric, ntree = 15, preProcess = c('BoxCox'))model_train2 <- train(Genre ~ ., data = vg_train, method = 'rf', trControl = control, tunegrid = tunegrid, metric = metric, ntree = 500, preProcess = c('BoxCox')) The results from my cross validation show that the 500 tree model did a tiny bit better...but only a tiny bit. 21 features per split seems appropriate given the cross validation results. My accuracy is utterly terrible however. My overall accuracy in Model 2 is only 34.4%. Random Forests allow us to look at feature importances, which is the how much the Gini Index for a feature decreases at each split. The more the Gini Index decreases for a feature, the more important it is. The figure below rates the features from 0–100, with 100 being the most important. It seems user count, and critic count are particularly important. However, given how poor the model fit is, I’m not sure how entirely useful interpreting any of these variables is. I’ve included a snippet of the variable importance code in case you want to replicate this. # Save the variable importance values from our model object generated from caret.x<-varImp(model_train2, scale = TRUE)# Get the row names of the variable importance datarownames(x$importance)# Convert the variable importance data into a dataframeimportance <- data.frame(rownames(x$importance), x$importance$Overall)# Relabel the datanames(importance)<-c('Platform', 'Importance')# Order the data from greatest importance to least importantimportance <- transform(importance, Platform = reorder(Platform, Importance))# Plot the data with ggplot.ggplot(data=importance, aes(x=Platform, y=Importance)) + geom_bar(stat = 'identity',colour = "blue", fill = "white") + coord_flip()) We can look at a confusion matrix to see how much accurate classification and mis-classification there was. The diagonal indicates correct % of classification. Off diagonals indicate the % of times the model misclassified a genre. It’s pretty awful. Shooters got classified correct 68% of the time...but was mis-classified as Strategy games a big percent of the time too. Why did our model do so poorly? There are several reasons. The model tends to be under fitting the data. This could mean random forest was not complex enough to capture trends in the data, and we might have to use a more complex approach using another model. However, the more likely candidate is that the features are simply not predictive of video game genres. And if our features are sort of crappy, we can do one of two things: We can engineer some additional features for our given data set. For example, we might be able to create a variable that denotes the average critic score of each genre of game in the data as a predictor (but that might be uninteresting). What we likely have to do is scrape some additional information from a video game repository that may have additional historical sales data from each type of genre of video game. A second easy thing to do is to simply take the aggregate sum of sales for each genre, then apply it across the entire data set. So many options! Or maybe the answer is even simpler. It could be that the data are imbalanced in terms of classes. If this were the case (and it is, if you examine the data further), you may want to prune back or combine genres to rectify this. Random forest is a commonly used model in machine learning, and is often referred to as an off-the-shelf model that is used frequently. In many cases, it out performs many of its parametric equivalents, and is less computationally intensive to boot. Of course, with any model, make sure you know why you should choose a model, such as a Random Forest (hint, maybe you don’t know the distribution of your data, maybe your data is very high dimensional, maybe you have lots of collinearity, maybe you want a model that is easy to interpret). Don’t go about choosing a model willy-nilly like I did here. :-) I don’t really delve deep into the mechanics of random forest. If you want to take a deep dive, I highly recommend two books: Introduction to Statistical Learning: Applications in R Elements of Statistical Learning The latter is considered the machine learning bible to some!
[ { "code": null, "e": 630, "s": 172, "text": "Over this past weekend, I got a little bored and decided to brush up on my R a bit. I have been programming in Python almost exclusively as a fellow at Insight, but I actually not had done much predictive analytics in R, save for pretty vanilla linear regressions. I wanted a somewhat clean data source where I can play around with modeling a bit in R. Thus, a good source of clean data is good ole’ kaggle. I decided to work on a Video Game Sales data set." }, { "code": null, "e": 791, "s": 630, "text": "Decision trees, and their cousins like bagged decision trees, random forest, gradient boosted decision trees etc., are commonly referred to as ensemble methods." }, { "code": null, "e": 1294, "s": 791, "text": "To understand more complicated ensemble methods, I think it’s good to understand the most common of these methods, decision trees and random forest. Let take the simplest example: regression using decision trees. For a given data set with n-dimensions, a you can grow a ‘decision tree’ with n-branches, and n-leaves. The goal of a decision tree is to determine branches that reduce the residual sums of squares the most, and provide the most predictive leaves as possible. Perhaps a figure will help..." }, { "code": null, "e": 1776, "s": 1294, "text": "The figure above represents a baseball related data set, where we want to determine the log salary of a player. On the left figure, if a player has less than 4.5 years experience, they are predicted to make 5.11 thousands of dollars. If a player has greater than 4.5 years experience, but fewer than 117.5 hits, they are predicted to make 6 thousands of dollars (again, log based). In the data on the right, the predicted values represent the subspaces R1, R2, and R3 respectively." }, { "code": null, "e": 2198, "s": 1776, "text": "The above example uses continuous data, but we can extend this to classification. In a classification setting, we are essentially growing branches that reduce classification error, although it’s not as straightforward as that. In the classification setting, we take an entropy-like measure, and try to reduce the amount of entropy at each branch to provide the best branch split. The Gini Index is a commonly used metric." }, { "code": null, "e": 2473, "s": 2198, "text": "p-hat mk represents the proportion of observations in the mth region from the kth class. In essence, the Gini index is a measure of variance. The higher the variance, the more mis-classification there is. Therefore lower values of the Gini Index yield better classification." }, { "code": null, "e": 2707, "s": 2473, "text": "Decision trees are commonly referred to as being “greedy”. This is simply a function of how the algorithm tries to determine the best way to reduce error. Unfortunately, this leads to model over-fitting and model over generalization." }, { "code": null, "e": 2978, "s": 2707, "text": "One method used to combat this is called bootstrap aggregation or ‘bagging’ for short. If you understand the idea of bootstrapping in statistics (in terms of estimating variance and error of an unknown population), the bagging is similar when it comes to decision trees." }, { "code": null, "e": 3210, "s": 2978, "text": "In bagging, we decide how many repeated bootstraps we want to take from our data set, fit them all to the same decision tree, then aggregate them back together. This gives us a more robust result, and is less prone to over fitting." }, { "code": null, "e": 3517, "s": 3210, "text": "Further, typically one third of the sample is left out of each bagged tree. We can then fit the bagged tree to the that sample, and obtain out-of-bag error rates. This essentially is a decision trees version of cross-validation, although you could perform cross-validation on top of out of bag error rates!" }, { "code": null, "e": 3900, "s": 3517, "text": "Now that we have a general understanding of decision trees and bagging, the concept of random forest is relatively straightforward. A vanilla random forest is a bagged decision tree whereby an additional algorithm takes a random sample of m predictors at each split. This works to decorrelate trees used in random forest, and is useful in automatically combating multi-collinearity." }, { "code": null, "e": 4054, "s": 3900, "text": "In classification, all trees are aggregated back together. From this aggregation, the model essentially takes a poll / vote to assign data to a category." }, { "code": null, "e": 4358, "s": 4054, "text": "For a given observation, we can predict the class by observing what class each bagged tree outputs for that observation. Then we look across all trees to see how many times that observation was predicted. A class is then assigned to that observation if it is predicted from the majority of bagged trees." }, { "code": null, "e": 4404, "s": 4358, "text": "An overview of the dataset can be found here." }, { "code": null, "e": 4458, "s": 4404, "text": "All my terribly messy code can be found on my github." }, { "code": null, "e": 4612, "s": 4458, "text": "The goal for this example was to see if sales numbers and the console a game was on could predict it’s genre (e.g., sports, action, RPG, strategy, etc.)." }, { "code": null, "e": 4744, "s": 4612, "text": "In this example, I make use of caret and ggplot2. I use the package dummies to generate dummy variables for categorical predictors." }, { "code": null, "e": 5258, "s": 4744, "text": "I wanted to get some practice using caret, which is essentially R’s version of scikit-learn. But first, as with any data set, it’s worth exploring it a little bit. My general approach is to look for quirkiness in the data first, explore potential correlations, then dig a bit deeper to see if there are any other trends worth noting in the data. Ideally, you will want to examine the data in every which way before modeling it. For brevity, I skipped some of the data exploration and jumped towards some modeling." }, { "code": null, "e": 5409, "s": 5258, "text": "First, I inspected the data for missing values. There were a ton of NaNs so I went ahead and did K-Nearest Neighbor Imputation using the DMwR package." }, { "code": null, "e": 5548, "s": 5409, "text": "Next, I wanted to generally inspect the sales data to find if there were any outliers. There were. And the distribution was highly skewed." }, { "code": null, "e": 5604, "s": 5548, "text": "I went ahead and normalized them using a log transform." }, { "code": null, "e": 6096, "s": 5604, "text": "From here, I generated dummy variables for the different consoles each game was on, and then examined the correlations. Global sales, not surprisingly, were correlated with all other sales. Critic Scores and counts were not. Not pictured here are correlations by console. There was not anything of note there, given the sparsity of console dummy data. One may simply remove the Global Sales variable in lieu of keeping all the other sales variables, if multi-collinearity was a huge concern." }, { "code": null, "e": 6249, "s": 6096, "text": "In caret , I did a 80%-20% train-test split, as common practice for conducting modeling. I relabeled all the genres as numbers, and they are as follows:" }, { "code": null, "e": 6342, "s": 6249, "text": "SportsPlatformerRacingRPGPuzzleMiscellaneousShooterSimulationActionFightingAdventureStrategy" }, { "code": null, "e": 6349, "s": 6342, "text": "Sports" }, { "code": null, "e": 6360, "s": 6349, "text": "Platformer" }, { "code": null, "e": 6367, "s": 6360, "text": "Racing" }, { "code": null, "e": 6371, "s": 6367, "text": "RPG" }, { "code": null, "e": 6378, "s": 6371, "text": "Puzzle" }, { "code": null, "e": 6392, "s": 6378, "text": "Miscellaneous" }, { "code": null, "e": 6400, "s": 6392, "text": "Shooter" }, { "code": null, "e": 6411, "s": 6400, "text": "Simulation" }, { "code": null, "e": 6418, "s": 6411, "text": "Action" }, { "code": null, "e": 6427, "s": 6418, "text": "Fighting" }, { "code": null, "e": 6437, "s": 6427, "text": "Adventure" }, { "code": null, "e": 6446, "s": 6437, "text": "Strategy" }, { "code": null, "e": 6692, "s": 6446, "text": "I did some grid searching on the number of features available at each tree split. Recall that Random Forest doesn’t take all available features when it creates a split for each node in the tree. This is a manipulable hyperparameter in the model." }, { "code": null, "e": 6752, "s": 6692, "text": "mtry <- sqrt(ncol(vg))tunegrid <- expand.grid(.mtry = mtry)" }, { "code": null, "e": 7079, "s": 6752, "text": "In the code snippet above, I took the square root of number of columns as the initial number features available. Doing a grid search expands upon that such that caret will iterate through the initial start variable, then do another sqrt(ncol(vg)) additional features in the next fit iteration, then assess the model once more." }, { "code": null, "e": 7215, "s": 7079, "text": "metric <- 'Accuracy'control <- trainControl(method = 'repeatedcv', number = 10, repeats = 2, search = 'random', savePredictions = TRUE)" }, { "code": null, "e": 7518, "s": 7215, "text": "Next, I set my metric as accuracy, since this is a classification procedure. I do cross validation to evaluate if my training data is wonky in any way. 5–10 number of folds (denoted as the number parameter) is typical. I do a random search because it’s a bit quicker and less computationally intensive." }, { "code": null, "e": 7804, "s": 7518, "text": "Using caret, I trained two models. One with 15 bagged trees. Another with 500 bagged trees. The 500 tree model took some time to run (maybe about 30 minutes?). One could easily incorporate the number of bagged trees in a grid search. For brevity (and time), I just compared two models." }, { "code": null, "e": 7934, "s": 7804, "text": "Note I allowed the model to use Box Cox to determine how to normalize the data appropriately (which it log transformed the data)." }, { "code": null, "e": 8258, "s": 7934, "text": "model_train1 <- train(Genre ~ ., data = vg_train, method = 'rf', trControl = control, tunegrid = tunegrid, metric = metric, ntree = 15, preProcess = c('BoxCox'))model_train2 <- train(Genre ~ ., data = vg_train, method = 'rf', trControl = control, tunegrid = tunegrid, metric = metric, ntree = 500, preProcess = c('BoxCox'))" }, { "code": null, "e": 8445, "s": 8258, "text": "The results from my cross validation show that the 500 tree model did a tiny bit better...but only a tiny bit. 21 features per split seems appropriate given the cross validation results." }, { "code": null, "e": 8532, "s": 8445, "text": "My accuracy is utterly terrible however. My overall accuracy in Model 2 is only 34.4%." }, { "code": null, "e": 8822, "s": 8532, "text": "Random Forests allow us to look at feature importances, which is the how much the Gini Index for a feature decreases at each split. The more the Gini Index decreases for a feature, the more important it is. The figure below rates the features from 0–100, with 100 being the most important." }, { "code": null, "e": 9095, "s": 8822, "text": "It seems user count, and critic count are particularly important. However, given how poor the model fit is, I’m not sure how entirely useful interpreting any of these variables is. I’ve included a snippet of the variable importance code in case you want to replicate this." }, { "code": null, "e": 9774, "s": 9095, "text": "# Save the variable importance values from our model object generated from caret.x<-varImp(model_train2, scale = TRUE)# Get the row names of the variable importance datarownames(x$importance)# Convert the variable importance data into a dataframeimportance <- data.frame(rownames(x$importance), x$importance$Overall)# Relabel the datanames(importance)<-c('Platform', 'Importance')# Order the data from greatest importance to least importantimportance <- transform(importance, Platform = reorder(Platform, Importance))# Plot the data with ggplot.ggplot(data=importance, aes(x=Platform, y=Importance)) + geom_bar(stat = 'identity',colour = \"blue\", fill = \"white\") + coord_flip())" }, { "code": null, "e": 10005, "s": 9774, "text": "We can look at a confusion matrix to see how much accurate classification and mis-classification there was. The diagonal indicates correct % of classification. Off diagonals indicate the % of times the model misclassified a genre." }, { "code": null, "e": 10146, "s": 10005, "text": "It’s pretty awful. Shooters got classified correct 68% of the time...but was mis-classified as Strategy games a big percent of the time too." }, { "code": null, "e": 10509, "s": 10146, "text": "Why did our model do so poorly? There are several reasons. The model tends to be under fitting the data. This could mean random forest was not complex enough to capture trends in the data, and we might have to use a more complex approach using another model. However, the more likely candidate is that the features are simply not predictive of video game genres." }, { "code": null, "e": 10816, "s": 10509, "text": "And if our features are sort of crappy, we can do one of two things: We can engineer some additional features for our given data set. For example, we might be able to create a variable that denotes the average critic score of each genre of game in the data as a predictor (but that might be uninteresting)." }, { "code": null, "e": 11141, "s": 10816, "text": "What we likely have to do is scrape some additional information from a video game repository that may have additional historical sales data from each type of genre of video game. A second easy thing to do is to simply take the aggregate sum of sales for each genre, then apply it across the entire data set. So many options!" }, { "code": null, "e": 11370, "s": 11141, "text": "Or maybe the answer is even simpler. It could be that the data are imbalanced in terms of classes. If this were the case (and it is, if you examine the data further), you may want to prune back or combine genres to rectify this." }, { "code": null, "e": 11975, "s": 11370, "text": "Random forest is a commonly used model in machine learning, and is often referred to as an off-the-shelf model that is used frequently. In many cases, it out performs many of its parametric equivalents, and is less computationally intensive to boot. Of course, with any model, make sure you know why you should choose a model, such as a Random Forest (hint, maybe you don’t know the distribution of your data, maybe your data is very high dimensional, maybe you have lots of collinearity, maybe you want a model that is easy to interpret). Don’t go about choosing a model willy-nilly like I did here. :-)" }, { "code": null, "e": 12101, "s": 11975, "text": "I don’t really delve deep into the mechanics of random forest. If you want to take a deep dive, I highly recommend two books:" }, { "code": null, "e": 12157, "s": 12101, "text": "Introduction to Statistical Learning: Applications in R" }, { "code": null, "e": 12190, "s": 12157, "text": "Elements of Statistical Learning" } ]
How to Implement a Strategy Pattern using Enum in Java? - GeeksforGeeks
22 Feb, 2021 The strategy design pattern is intended to provide a way to choose from a variety of interchangeable strategies. Classic implementation includes an architecture to be implemented by each technique and offers a concrete implementation for execution. The method is chosen from an interface reference, and the execution method is called. The classic implementation of the Strategy design pattern: The strategy interface must be implemented by all strategies. public interface Strategy { public void execute(); } All strategies must implement the strategy interface two classes showing the implementation of the Strategy interface and created an execute method. public class StrategyA implements Strategy { @Override public void execute(){ System.out.print("Executing strategy A"); } } public class StrategyB implements Strategy { @Override public void execute() { System.out.print("Executing strategy B"); } } The main class will select the strategy and execute the execute method of the strategy we chose. public class GFG { private Strategy strategy; public void setStrategy(Strategy strategy){ this.strategy = strategy; } public void executeStrategy(){ this.strategy.execute(); } } An example of using the Strategy. public class UseStrategy { public static void main(String[] args){ Context context = new Context(); context.setStrategy(new StrategyA()); context.executeStrategy(); context.setStrategy(new StrategyB()); context.executeStrategy(); } } Enum implementation of the Strategy design pattern: It will have two classes: an enum class and a class that uses it. All the magic happens in the enum, where the concrete implementation of the strategy is done to define each enum constant. Java // Java program to Implement a Strategy Pattern using Enum enum Strategy { STRATEGY_A { @Override void execute() { System.out.println("Executing strategy A"); } }, STRATEGY_B { @Override void execute() { System.out.println("Executing strategy B"); } }; abstract void execute();} class UseStrategy { public static void main(String[] args) { UseStrategy useStrategy = new UseStrategy(); useStrategy.perform(Strategy.STRATEGY_A); useStrategy.perform(Strategy.STRATEGY_B); } private void perform(Strategy strategy) { strategy.execute(); }} Executing strategy A Executing strategy B Java-Enumeration Java-Pattern Picked How To Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Check the OS Version in Linux? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24952, "s": 24924, "text": "\n22 Feb, 2021" }, { "code": null, "e": 25287, "s": 24952, "text": "The strategy design pattern is intended to provide a way to choose from a variety of interchangeable strategies. Classic implementation includes an architecture to be implemented by each technique and offers a concrete implementation for execution. The method is chosen from an interface reference, and the execution method is called." }, { "code": null, "e": 25346, "s": 25287, "text": "The classic implementation of the Strategy design pattern:" }, { "code": null, "e": 25408, "s": 25346, "text": "The strategy interface must be implemented by all strategies." }, { "code": null, "e": 25463, "s": 25408, "text": "public interface Strategy {\n public void execute();\n}" }, { "code": null, "e": 25612, "s": 25463, "text": "All strategies must implement the strategy interface two classes showing the implementation of the Strategy interface and created an execute method." }, { "code": null, "e": 25742, "s": 25612, "text": "public class StrategyA implements Strategy {\n @Override\n public void execute(){\n System.out.print(\"Executing strategy A\");\n }\n}" }, { "code": null, "e": 25873, "s": 25742, "text": "public class StrategyB implements Strategy {\n @Override\n public void execute() {\n System.out.print(\"Executing strategy B\");\n }\n}" }, { "code": null, "e": 25970, "s": 25873, "text": "The main class will select the strategy and execute the execute method of the strategy we chose." }, { "code": null, "e": 26162, "s": 25970, "text": "public class GFG {\n\n private Strategy strategy;\n\n public void setStrategy(Strategy strategy){\n this.strategy = strategy;\n }\n\n public void executeStrategy(){\n this.strategy.execute();\n }\n}" }, { "code": null, "e": 26196, "s": 26162, "text": "An example of using the Strategy." }, { "code": null, "e": 26434, "s": 26196, "text": "public class UseStrategy {\n\npublic static void main(String[] args){\n\nContext context = new Context();\n\ncontext.setStrategy(new StrategyA());\ncontext.executeStrategy();\n\ncontext.setStrategy(new StrategyB());\ncontext.executeStrategy();\n}\n}" }, { "code": null, "e": 26486, "s": 26434, "text": "Enum implementation of the Strategy design pattern:" }, { "code": null, "e": 26675, "s": 26486, "text": "It will have two classes: an enum class and a class that uses it. All the magic happens in the enum, where the concrete implementation of the strategy is done to define each enum constant." }, { "code": null, "e": 26680, "s": 26675, "text": "Java" }, { "code": "// Java program to Implement a Strategy Pattern using Enum enum Strategy { STRATEGY_A { @Override void execute() { System.out.println(\"Executing strategy A\"); } }, STRATEGY_B { @Override void execute() { System.out.println(\"Executing strategy B\"); } }; abstract void execute();} class UseStrategy { public static void main(String[] args) { UseStrategy useStrategy = new UseStrategy(); useStrategy.perform(Strategy.STRATEGY_A); useStrategy.perform(Strategy.STRATEGY_B); } private void perform(Strategy strategy) { strategy.execute(); }}", "e": 27283, "s": 26680, "text": null }, { "code": null, "e": 27325, "s": 27283, "text": "Executing strategy A\nExecuting strategy B" }, { "code": null, "e": 27342, "s": 27325, "text": "Java-Enumeration" }, { "code": null, "e": 27355, "s": 27342, "text": "Java-Pattern" }, { "code": null, "e": 27362, "s": 27355, "text": "Picked" }, { "code": null, "e": 27369, "s": 27362, "text": "How To" }, { "code": null, "e": 27374, "s": 27369, "text": "Java" }, { "code": null, "e": 27388, "s": 27374, "text": "Java Programs" }, { "code": null, "e": 27393, "s": 27388, "text": "Java" }, { "code": null, "e": 27491, "s": 27393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27525, "s": 27491, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27574, "s": 27525, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27632, "s": 27574, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27674, "s": 27632, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27712, "s": 27674, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 27727, "s": 27712, "text": "Arrays in Java" }, { "code": null, "e": 27771, "s": 27727, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27793, "s": 27771, "text": "For-each loop in Java" }, { "code": null, "e": 27829, "s": 27793, "text": "Arrays.sort() in Java with examples" } ]
Dot notation in JavaScript
The dot notation is used to access the object properties in JavaScript. Following is the code to implement dot notation − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Dot notation in JavaScript.</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to access the student1 object properties using dot notation</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function Student(name, age, standard) { this.name = name; this.age = age; this.standard = standard; } let student = new Student("Rohan", 18, 12); BtnEle.addEventListener("click", () => { resEle.innerHTML = "student1.name = " + student1.name + "<br>"; resEle.innerHTML += "student1.age = " + student1.age + "<br>"; resEle.innerHTML += "student1.standard = " + student1.standard + "<br>"; }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1184, "s": 1062, "text": "The dot notation is used to access the object properties in JavaScript. Following is the code\nto implement dot notation −" }, { "code": null, "e": 1195, "s": 1184, "text": " Live Demo" }, { "code": null, "e": 2337, "s": 1195, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Dot notation in JavaScript.</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to access the student1 object properties using dot notation</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function Student(name, age, standard) {\n this.name = name;\n this.age = age;\n this.standard = standard;\n }\n let student = new Student(\"Rohan\", 18, 12);\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = \"student1.name = \" + student1.name + \"<br>\";\n resEle.innerHTML += \"student1.age = \" + student1.age + \"<br>\";\n resEle.innerHTML += \"student1.standard = \" + student1.standard + \"<br>\";\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2375, "s": 2337, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Redis - Server Slaveof Command
Redis SLAVEOF command can change the replication settings of a slave on the fly. If a Redis server is already acting as a slave, the command SLAVEOF NO ONE will turn off the replication, turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the server a slave of another server listening at the specified hostname and port. If a server is already a slave of some master, SLAVEOF hostname port will stop the replication against the old server and start the synchronization against the new one, discarding the old dataset. Simple string reply. Following is the basic syntax of Redis SLAVEOF command. redis 127.0.0.1:6379> SLAVEOF host port 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2603, "s": 2045, "text": "Redis SLAVEOF command can change the replication settings of a slave on the fly. If a Redis server is already acting as a slave, the command SLAVEOF NO ONE will turn off the replication, turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the server a slave of another server listening at the specified hostname and port. If a server is already a slave of some master, SLAVEOF hostname port will stop the replication against the old server and start the synchronization against the new one, discarding the old dataset." }, { "code": null, "e": 2624, "s": 2603, "text": "Simple string reply." }, { "code": null, "e": 2680, "s": 2624, "text": "Following is the basic syntax of Redis SLAVEOF command." }, { "code": null, "e": 2721, "s": 2680, "text": "redis 127.0.0.1:6379> SLAVEOF host port\n" }, { "code": null, "e": 2753, "s": 2721, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2773, "s": 2753, "text": " Skillbakerystudios" }, { "code": null, "e": 2780, "s": 2773, "text": " Print" }, { "code": null, "e": 2791, "s": 2780, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: A navigation menu
[]
pause method - Action Chains in Selenium Python - GeeksforGeeks
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around pause method on Action Chains in Python Selenium. pause method is used to pause all inputs for the specified duration in seconds. Pause method is highly important and useful in case one is executing some command that takes some javascript to load or a similar situation where there is a time gap between two operations. Syntax – pause(seconds) pause(1024) To demonstrate, pause method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element. Program – # import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # action.pause(1000) # click the itemaction.click(on_element = element) # perform the operationaction.perform() Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 May, 2020" }, { "code": null, "e": 26309, "s": 25537, "text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around pause method on Action Chains in Python Selenium. pause method is used to pause all inputs for the specified duration in seconds. Pause method is highly important and useful in case one is executing some command that takes some javascript to load or a similar situation where there is a time gap between two operations." }, { "code": null, "e": 26318, "s": 26309, "text": "Syntax –" }, { "code": null, "e": 26333, "s": 26318, "text": "pause(seconds)" }, { "code": null, "e": 26346, "s": 26333, "text": "pause(1024)\n" }, { "code": null, "e": 26483, "s": 26346, "text": "To demonstrate, pause method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element." }, { "code": null, "e": 26493, "s": 26483, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # action.pause(1000) # click the itemaction.click(on_element = element) # perform the operationaction.perform()", "e": 27050, "s": 26493, "text": null }, { "code": null, "e": 27059, "s": 27050, "text": "Output –" }, { "code": null, "e": 27075, "s": 27059, "text": "Python-selenium" }, { "code": null, "e": 27084, "s": 27075, "text": "selenium" }, { "code": null, "e": 27091, "s": 27084, "text": "Python" }, { "code": null, "e": 27189, "s": 27091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27221, "s": 27189, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27263, "s": 27221, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27305, "s": 27263, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27332, "s": 27305, "text": "Python Classes and Objects" }, { "code": null, "e": 27388, "s": 27332, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27410, "s": 27388, "text": "Defaultdict in Python" }, { "code": null, "e": 27449, "s": 27410, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27480, "s": 27449, "text": "Python | os.path.join() method" }, { "code": null, "e": 27509, "s": 27480, "text": "Create a directory in Python" } ]
What does buffer flush means in C++ ? - GeeksforGeeks
08 Oct, 2021 A buffer flush is the transfer of computer data from a temporary storage area to the computer’s permanent memory. For instance, if we make any changes in a file, the changes we see on one computer screen are stored temporarily in a buffer. Usually, a temporary file comes into existence when we open any word document and is automatically destroyed when we close our main file. Thus when we save our work, the changes that we’ve made to our document since the last time we saved it are flushed from the buffer to permanent storage on the hard disk. In C++, we can explicitly be flushed to force the buffer to be written. Generally, the std::endl function works the same by inserting a new-line character and flushes the stream. stdout/cout is line-buffered that is the output doesn’t get sent to the OS until you write a newline or explicitly flush the buffer. For instance, C++ // Causes only one write to underlying file// instead of 5, which is much better for// performance.std::cout << a << " + " << b << " = " << std::endl; But there is certain disadvantage something like, C++ // Below is C++ program#include <iostream>#include <thread>#include <chrono> using namespace std; int main(){ for (int i = 1; i <= 5; ++i) { cout << i << " "; this_thread::sleep_for(chrono::seconds(1)); } cout << endl; return 0;} The above program will output 1 2 3 4 5 at once. Therefore in such cases, an additional “flush” function is used to ensure that the output gets displayed according to our requirements. For instance, C++ // C++ program to demonstrate the// use of flush function#include <iostream>#include <thread>#include <chrono>using namespace std;int main(){ for (int i = 1; i <= 5; ++i) { cout << i << " " << flush; this_thread::sleep_for(chrono::seconds(1)); } return 0;} The above program will print the numbers(1 2 3 4 5) one by one rather than once. The reason is flush function flushed the output to the file/terminal instantly. Note: You can’t run the program on an online compiler to see the difference, since they give output only when it terminates. Hence you need to run all the above programs in an offline compiler like GCC or clang.Reading cin flushes cout so we don’t need an explicit flush to do this. You can’t run the program on an online compiler to see the difference, since they give output only when it terminates. Hence you need to run all the above programs in an offline compiler like GCC or clang. Reading cin flushes cout so we don’t need an explicit flush to do this. References: http://searchstorage.techtarget.com/definition/buffer-flush https://stackoverflow.com/questions/15042849/what-does-flushing-the-buffer-mean Related Article : Use of fflush(stdin) in C This article is contributed by Shubham Bansal. 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. PaneerParatha69 anujeetkunturkar12 tanwarsinghvaibhav cpp-input-output C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 26183, "s": 26155, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26732, "s": 26183, "text": "A buffer flush is the transfer of computer data from a temporary storage area to the computer’s permanent memory. For instance, if we make any changes in a file, the changes we see on one computer screen are stored temporarily in a buffer. Usually, a temporary file comes into existence when we open any word document and is automatically destroyed when we close our main file. Thus when we save our work, the changes that we’ve made to our document since the last time we saved it are flushed from the buffer to permanent storage on the hard disk." }, { "code": null, "e": 27058, "s": 26732, "text": "In C++, we can explicitly be flushed to force the buffer to be written. Generally, the std::endl function works the same by inserting a new-line character and flushes the stream. stdout/cout is line-buffered that is the output doesn’t get sent to the OS until you write a newline or explicitly flush the buffer. For instance," }, { "code": null, "e": 27062, "s": 27058, "text": "C++" }, { "code": "// Causes only one write to underlying file// instead of 5, which is much better for// performance.std::cout << a << \" + \" << b << \" = \" << std::endl;", "e": 27213, "s": 27062, "text": null }, { "code": null, "e": 27264, "s": 27213, "text": "But there is certain disadvantage something like, " }, { "code": null, "e": 27268, "s": 27264, "text": "C++" }, { "code": "// Below is C++ program#include <iostream>#include <thread>#include <chrono> using namespace std; int main(){ for (int i = 1; i <= 5; ++i) { cout << i << \" \"; this_thread::sleep_for(chrono::seconds(1)); } cout << endl; return 0;}", "e": 27513, "s": 27268, "text": null }, { "code": null, "e": 27562, "s": 27513, "text": "The above program will output 1 2 3 4 5 at once." }, { "code": null, "e": 27713, "s": 27562, "text": "Therefore in such cases, an additional “flush” function is used to ensure that the output gets displayed according to our requirements. For instance, " }, { "code": null, "e": 27717, "s": 27713, "text": "C++" }, { "code": "// C++ program to demonstrate the// use of flush function#include <iostream>#include <thread>#include <chrono>using namespace std;int main(){ for (int i = 1; i <= 5; ++i) { cout << i << \" \" << flush; this_thread::sleep_for(chrono::seconds(1)); } return 0;}", "e": 27992, "s": 27717, "text": null }, { "code": null, "e": 28156, "s": 27992, "text": "The above program will print the \nnumbers(1 2 3 4 5) one by one rather than once. \nThe reason is flush function flushed the output \nto the file/terminal instantly." }, { "code": null, "e": 28163, "s": 28156, "text": "Note: " }, { "code": null, "e": 28440, "s": 28163, "text": "You can’t run the program on an online compiler to see the difference, since they give output only when it terminates. Hence you need to run all the above programs in an offline compiler like GCC or clang.Reading cin flushes cout so we don’t need an explicit flush to do this." }, { "code": null, "e": 28646, "s": 28440, "text": "You can’t run the program on an online compiler to see the difference, since they give output only when it terminates. Hence you need to run all the above programs in an offline compiler like GCC or clang." }, { "code": null, "e": 28718, "s": 28646, "text": "Reading cin flushes cout so we don’t need an explicit flush to do this." }, { "code": null, "e": 28732, "s": 28718, "text": "References: " }, { "code": null, "e": 28792, "s": 28732, "text": "http://searchstorage.techtarget.com/definition/buffer-flush" }, { "code": null, "e": 28872, "s": 28792, "text": "https://stackoverflow.com/questions/15042849/what-does-flushing-the-buffer-mean" }, { "code": null, "e": 28916, "s": 28872, "text": "Related Article : Use of fflush(stdin) in C" }, { "code": null, "e": 29215, "s": 28916, "text": "This article is contributed by Shubham Bansal. 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. " }, { "code": null, "e": 29231, "s": 29215, "text": "PaneerParatha69" }, { "code": null, "e": 29250, "s": 29231, "text": "anujeetkunturkar12" }, { "code": null, "e": 29269, "s": 29250, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 29286, "s": 29269, "text": "cpp-input-output" }, { "code": null, "e": 29290, "s": 29286, "text": "C++" }, { "code": null, "e": 29294, "s": 29290, "text": "CPP" }, { "code": null, "e": 29392, "s": 29294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29411, "s": 29392, "text": "Inheritance in C++" }, { "code": null, "e": 29454, "s": 29411, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29478, "s": 29454, "text": "C++ Classes and Objects" }, { "code": null, "e": 29502, "s": 29478, "text": "Virtual Function in C++" }, { "code": null, "e": 29533, "s": 29502, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29553, "s": 29533, "text": "Constructors in C++" }, { "code": null, "e": 29581, "s": 29553, "text": "Operator Overloading in C++" }, { "code": null, "e": 29609, "s": 29581, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29643, "s": 29609, "text": "vector erase() and clear() in C++" } ]
Python | Get indices of True values in a binary list - GeeksforGeeks
02 Jan, 2019 Boolean lists are often used by the developers to check for True values during hashing. Boolean list is also used in certain dynamic programming paradigms in dynamic programming. Let’s discuss certain ways to get indices of true values in list in Python. Method #1 : Using enumerate() and list comprehension enumerate() can do the task of hashing index with its value and coupled with list comprehension can let us check for the true values. # Python3 code to demonstrate # to return true value indices.# using enumerate() + list comprehension # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print ("The original list is : " + str(test_list)) # using enumerate() + list comprehension# to return true indices.res = [i for i, val in enumerate(test_list) if val] # printing resultprint ("The list indices having True values are : " + str(res)) The original list is : [True, False, True, False, True, True, False] The list indices having True values are : [0, 2, 4, 5] Method #2 : Using lambda + filter() + range() filter() function coupled with lambda can perform this task with help of range function. range() function is used to traverse the entire list and filter checks for true values. # Python3 code to demonstrate # to return true value indices.# using lambda + filter() + range() # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print ("The original list is : " + str(test_list)) # using lambda + filter() + range()# to return true indices.res = list(filter(lambda i: test_list[i], range(len(test_list)))) # printing resultprint ("The list indices having True values are : " + str(res)) The original list is : [True, False, True, False, True, True, False] The list indices having True values are : [0, 2, 4, 5] Method #3 : Using itertools.compress() compress function checks for all the elements in list and returns the list of indices with True values. This is most Pythonic and elegant way to perform this particular task. # Python3 code to demonstrate # to return true value indices.# using itertools.compress()from itertools import compress # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print ("The original list is : " + str(test_list)) # using itertools.compress()# to return true indices.res = list(compress(range(len(test_list)), test_list)) # printing resultprint ("The list indices having True values are : " + str(res)) The original list is : [True, False, True, False, True, True, False] The list indices having True values are : [0, 2, 4, 5] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25557, "s": 25529, "text": "\n02 Jan, 2019" }, { "code": null, "e": 25812, "s": 25557, "text": "Boolean lists are often used by the developers to check for True values during hashing. Boolean list is also used in certain dynamic programming paradigms in dynamic programming. Let’s discuss certain ways to get indices of true values in list in Python." }, { "code": null, "e": 25865, "s": 25812, "text": "Method #1 : Using enumerate() and list comprehension" }, { "code": null, "e": 25999, "s": 25865, "text": "enumerate() can do the task of hashing index with its value and coupled with list comprehension can let us check for the true values." }, { "code": "# Python3 code to demonstrate # to return true value indices.# using enumerate() + list comprehension # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print (\"The original list is : \" + str(test_list)) # using enumerate() + list comprehension# to return true indices.res = [i for i, val in enumerate(test_list) if val] # printing resultprint (\"The list indices having True values are : \" + str(res))", "e": 26459, "s": 25999, "text": null }, { "code": null, "e": 26584, "s": 26459, "text": "The original list is : [True, False, True, False, True, True, False]\nThe list indices having True values are : [0, 2, 4, 5]\n" }, { "code": null, "e": 26631, "s": 26584, "text": " Method #2 : Using lambda + filter() + range()" }, { "code": null, "e": 26808, "s": 26631, "text": "filter() function coupled with lambda can perform this task with help of range function. range() function is used to traverse the entire list and filter checks for true values." }, { "code": "# Python3 code to demonstrate # to return true value indices.# using lambda + filter() + range() # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print (\"The original list is : \" + str(test_list)) # using lambda + filter() + range()# to return true indices.res = list(filter(lambda i: test_list[i], range(len(test_list)))) # printing resultprint (\"The list indices having True values are : \" + str(res))", "e": 27272, "s": 26808, "text": null }, { "code": null, "e": 27398, "s": 27272, "text": "The original list is : [True, False, True, False, True, True, False]\nThe list indices having True values are : [0, 2, 4, 5]\n" }, { "code": null, "e": 27438, "s": 27398, "text": " Method #3 : Using itertools.compress()" }, { "code": null, "e": 27613, "s": 27438, "text": "compress function checks for all the elements in list and returns the list of indices with True values. This is most Pythonic and elegant way to perform this particular task." }, { "code": "# Python3 code to demonstrate # to return true value indices.# using itertools.compress()from itertools import compress # initializing list test_list = [True, False, True, False, True, True, False] # printing original list print (\"The original list is : \" + str(test_list)) # using itertools.compress()# to return true indices.res = list(compress(range(len(test_list)), test_list)) # printing resultprint (\"The list indices having True values are : \" + str(res))", "e": 28082, "s": 27613, "text": null }, { "code": null, "e": 28207, "s": 28082, "text": "The original list is : [True, False, True, False, True, True, False]\nThe list indices having True values are : [0, 2, 4, 5]\n" }, { "code": null, "e": 28228, "s": 28207, "text": "Python list-programs" }, { "code": null, "e": 28235, "s": 28228, "text": "Python" }, { "code": null, "e": 28251, "s": 28235, "text": "Python Programs" }, { "code": null, "e": 28349, "s": 28251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28384, "s": 28349, "text": "Read a file line by line in Python" }, { "code": null, "e": 28416, "s": 28384, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28438, "s": 28416, "text": "Enumerate() in Python" }, { "code": null, "e": 28480, "s": 28438, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28510, "s": 28480, "text": "Iterate over a list in Python" }, { "code": null, "e": 28553, "s": 28510, "text": "Python program to convert a list to string" }, { "code": null, "e": 28575, "s": 28553, "text": "Defaultdict in Python" }, { "code": null, "e": 28614, "s": 28575, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28660, "s": 28614, "text": "Python | Split string into list of characters" } ]
Info Edge India Interview Experience for Software Engineer Role 2021 (Off-Campus) - GeeksforGeeks
26 Feb, 2021 Round 1: Online Test (24 Jan 2021) 15 Aptitude MCQs (20 Minutes): Medium difficulty. 20 Technical MCQs (20 Minutes): Easy to medium difficulty. Round 2: Tech Interview 1 (3 Feb 2021) IntroductionProject 1 discussion (Web Development based)Project 2 discussion (ML/DL based)Coding Ques: https://www.google.com/amp/s/www.geeksforgeeks.org/happy-number/amp/Coding Ques: We toss a dice, and whichever number comes up, we move by that. Find the number of probability (or ways) to reach a distance of exactly x in exactly m dice spins.Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4]) Introduction Project 1 discussion (Web Development based) Project 2 discussion (ML/DL based) Coding Ques: https://www.google.com/amp/s/www.geeksforgeeks.org/happy-number/amp/ Coding Ques: We toss a dice, and whichever number comes up, we move by that. Find the number of probability (or ways) to reach a distance of exactly x in exactly m dice spins.Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4]) Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4]) Note: After discussing the approach, both codes need to be written in any local IDE of your choice. Round 3: Tech Interview 2 (18 Feb 2021) Started with a friendly discussion for 30 minutes about interests, hobbies, school life, college life, company preference – Service based/Product based, already have an offer or not – just to make the candidate comfortable. Main Interview starts with OS: What is thread?What is process?Should we divide a process into sub-threads or sub-processes, advantages/disadvantages of doing so?Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs?What are page faults?Reasons for more page faults?Effect on page faults on OS and on which part of OS (Ans is Kernal)? What is thread? What is process? Should we divide a process into sub-threads or sub-processes, advantages/disadvantages of doing so?Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs? Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs? What are page faults? Reasons for more page faults? Effect on page faults on OS and on which part of OS (Ans is Kernal)? Moved to DBMS: Advantages of DBMS?ACID properties?Explain how DBMS solves the issue of concurrency?Joins and its 4 types? Advantages of DBMS? ACID properties? Explain how DBMS solves the issue of concurrency? Joins and its 4 types? Coding Questions: Given a sorted array rotated sometimes, search for a number?Ex. [6,7,1,3,4], target = 7, answer= TrueSolution expected: Modified Binary search (logn) + write the codeSame question of tech round 1, but a bit modified. Find the number of ways to reach a distance of exactly x in exactly n moves. In each move, we can move a distance between 1 to m (m is given)Ex. Distance=10, moves=2, m=6, answer=3 ways ([4,6], [5,5], [6,4]) + write the code Given a sorted array rotated sometimes, search for a number?Ex. [6,7,1,3,4], target = 7, answer= TrueSolution expected: Modified Binary search (logn) + write the code Ex. [6,7,1,3,4], target = 7, answer= True Solution expected: Modified Binary search (logn) + write the code Same question of tech round 1, but a bit modified. Find the number of ways to reach a distance of exactly x in exactly n moves. In each move, we can move a distance between 1 to m (m is given)Ex. Distance=10, moves=2, m=6, answer=3 ways ([4,6], [5,5], [6,4]) + write the code Ex. Distance=10, moves=2, m=6, answer=3 ways ([4,6], [5,5], [6,4]) + write the code Round 4: Technical Round 3 (23 Feb 2021) Can you define the only constructor of a class as private? If yes, how will you create the objects?SQL Query involving Date and indexCoding Ques: Evaluate the expr with x,y,z given:Ex: x+y*z, x=1,y=2,z=3, answer=7 Ex. (x+y) / (x+z), x=1,y=5, z=2, answer = 2And write the code.Solution: Convert to postfix, then solve using stack.Round 5: HR Round (24 Feb 2021):How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge?Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes arrow_drop_upSave Can you define the only constructor of a class as private? If yes, how will you create the objects? SQL Query involving Date and index Coding Ques: Evaluate the expr with x,y,z given:Ex: x+y*z, x=1,y=2,z=3, answer=7 Ex. (x+y) / (x+z), x=1,y=5, z=2, answer = 2And write the code.Solution: Convert to postfix, then solve using stack.Round 5: HR Round (24 Feb 2021):How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge?Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes arrow_drop_upSave Ex: x+y*z, x=1,y=2,z=3, answer=7 Ex. (x+y) / (x+z), x=1,y=5, z=2, answer = 2 And write the code. Solution: Convert to postfix, then solve using stack. Round 5: HR Round (24 Feb 2021): How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge? How were the technical Rounds? How would you rate yourself in the rounds? Since you chose 7-8, what would you try to improve? Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site) How do you keep yourself updated in tech? (I said medium and Linkedin) Why do you want to join Info Edge? Special thanks to GeeksforGeeks for the preparation resources. All the very best InfoEdge Marketing Off-Campus Interview Experiences InfoEdge Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 EPAM Interview Experience (Off-Campus) Amazon Interview Experience for SDE-1 (Off-Campus) 2022
[ { "code": null, "e": 26695, "s": 26667, "text": "\n26 Feb, 2021" }, { "code": null, "e": 26730, "s": 26695, "text": "Round 1: Online Test (24 Jan 2021)" }, { "code": null, "e": 26780, "s": 26730, "text": "15 Aptitude MCQs (20 Minutes): Medium difficulty." }, { "code": null, "e": 26839, "s": 26780, "text": "20 Technical MCQs (20 Minutes): Easy to medium difficulty." }, { "code": null, "e": 26878, "s": 26839, "text": "Round 2: Tech Interview 1 (3 Feb 2021)" }, { "code": null, "e": 27284, "s": 26878, "text": "IntroductionProject 1 discussion (Web Development based)Project 2 discussion (ML/DL based)Coding Ques: https://www.google.com/amp/s/www.geeksforgeeks.org/happy-number/amp/Coding Ques: We toss a dice, and whichever number comes up, we move by that. Find the number of probability (or ways) to reach a distance of exactly x in exactly m dice spins.Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4])" }, { "code": null, "e": 27297, "s": 27284, "text": "Introduction" }, { "code": null, "e": 27342, "s": 27297, "text": "Project 1 discussion (Web Development based)" }, { "code": null, "e": 27377, "s": 27342, "text": "Project 2 discussion (ML/DL based)" }, { "code": null, "e": 27459, "s": 27377, "text": "Coding Ques: https://www.google.com/amp/s/www.geeksforgeeks.org/happy-number/amp/" }, { "code": null, "e": 27694, "s": 27459, "text": "Coding Ques: We toss a dice, and whichever number comes up, we move by that. Find the number of probability (or ways) to reach a distance of exactly x in exactly m dice spins.Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4])" }, { "code": null, "e": 27754, "s": 27694, "text": "Ex. Distance=10, spins=2, answer=3 ways ([4,6],[5,5],[6,4])" }, { "code": null, "e": 27854, "s": 27754, "text": "Note: After discussing the approach, both codes need to be written in any local IDE of your choice." }, { "code": null, "e": 27894, "s": 27854, "text": "Round 3: Tech Interview 2 (18 Feb 2021)" }, { "code": null, "e": 28118, "s": 27894, "text": "Started with a friendly discussion for 30 minutes about interests, hobbies, school life, college life, company preference – Service based/Product based, already have an offer or not – just to make the candidate comfortable." }, { "code": null, "e": 28149, "s": 28118, "text": "Main Interview starts with OS:" }, { "code": null, "e": 28573, "s": 28149, "text": "What is thread?What is process?Should we divide a process into sub-threads or sub-processes, advantages/disadvantages of doing so?Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs?What are page faults?Reasons for more page faults?Effect on page faults on OS and on which part of OS (Ans is Kernal)?" }, { "code": null, "e": 28589, "s": 28573, "text": "What is thread?" }, { "code": null, "e": 28606, "s": 28589, "text": "What is process?" }, { "code": null, "e": 28881, "s": 28606, "text": "Should we divide a process into sub-threads or sub-processes, advantages/disadvantages of doing so?Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs?" }, { "code": null, "e": 29057, "s": 28881, "text": "Two Scenarios: In one we have a program to do basic arithmetic operations and in the other, we have to call external services, how many threads would you run the two programs?" }, { "code": null, "e": 29079, "s": 29057, "text": "What are page faults?" }, { "code": null, "e": 29109, "s": 29079, "text": "Reasons for more page faults?" }, { "code": null, "e": 29178, "s": 29109, "text": "Effect on page faults on OS and on which part of OS (Ans is Kernal)?" }, { "code": null, "e": 29193, "s": 29178, "text": "Moved to DBMS:" }, { "code": null, "e": 29300, "s": 29193, "text": "Advantages of DBMS?ACID properties?Explain how DBMS solves the issue of concurrency?Joins and its 4 types?" }, { "code": null, "e": 29320, "s": 29300, "text": "Advantages of DBMS?" }, { "code": null, "e": 29337, "s": 29320, "text": "ACID properties?" }, { "code": null, "e": 29387, "s": 29337, "text": "Explain how DBMS solves the issue of concurrency?" }, { "code": null, "e": 29410, "s": 29387, "text": "Joins and its 4 types?" }, { "code": null, "e": 29428, "s": 29410, "text": "Coding Questions:" }, { "code": null, "e": 29871, "s": 29428, "text": "Given a sorted array rotated sometimes, search for a number?Ex. [6,7,1,3,4], target = 7, answer= TrueSolution expected: Modified Binary search (logn) + write the codeSame question of tech round 1, but a bit modified. Find the number of ways to reach a distance of exactly x in exactly n moves. In each move, we can move a distance between 1 to m (m is given)Ex. Distance=10, moves=2, m=6, answer=3 ways \n([4,6], [5,5], [6,4]) + write the code" }, { "code": null, "e": 30038, "s": 29871, "text": "Given a sorted array rotated sometimes, search for a number?Ex. [6,7,1,3,4], target = 7, answer= TrueSolution expected: Modified Binary search (logn) + write the code" }, { "code": null, "e": 30080, "s": 30038, "text": "Ex. [6,7,1,3,4], target = 7, answer= True" }, { "code": null, "e": 30146, "s": 30080, "text": "Solution expected: Modified Binary search (logn) + write the code" }, { "code": null, "e": 30423, "s": 30146, "text": "Same question of tech round 1, but a bit modified. Find the number of ways to reach a distance of exactly x in exactly n moves. In each move, we can move a distance between 1 to m (m is given)Ex. Distance=10, moves=2, m=6, answer=3 ways \n([4,6], [5,5], [6,4]) + write the code" }, { "code": null, "e": 30508, "s": 30423, "text": "Ex. Distance=10, moves=2, m=6, answer=3 ways \n([4,6], [5,5], [6,4]) + write the code" }, { "code": null, "e": 30549, "s": 30508, "text": "Round 4: Technical Round 3 (23 Feb 2021)" }, { "code": null, "e": 31365, "s": 30549, "text": "Can you define the only constructor of a class as private? If yes, how will you create the objects?SQL Query involving Date and indexCoding Ques: Evaluate the expr with x,y,z given:Ex: x+y*z, x=1,y=2,z=3, answer=7\nEx. (x+y) / (x+z), x=1,y=5, z=2, answer = 2And write the code.Solution: Convert to postfix, then solve using stack.Round 5: HR Round (24 Feb 2021):How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge?Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31465, "s": 31365, "text": "Can you define the only constructor of a class as private? If yes, how will you create the objects?" }, { "code": null, "e": 31500, "s": 31465, "text": "SQL Query involving Date and index" }, { "code": null, "e": 32183, "s": 31500, "text": "Coding Ques: Evaluate the expr with x,y,z given:Ex: x+y*z, x=1,y=2,z=3, answer=7\nEx. (x+y) / (x+z), x=1,y=5, z=2, answer = 2And write the code.Solution: Convert to postfix, then solve using stack.Round 5: HR Round (24 Feb 2021):How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge?Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32260, "s": 32183, "text": "Ex: x+y*z, x=1,y=2,z=3, answer=7\nEx. (x+y) / (x+z), x=1,y=5, z=2, answer = 2" }, { "code": null, "e": 32280, "s": 32260, "text": "And write the code." }, { "code": null, "e": 32334, "s": 32280, "text": "Solution: Convert to postfix, then solve using stack." }, { "code": null, "e": 32367, "s": 32334, "text": "Round 5: HR Round (24 Feb 2021):" }, { "code": null, "e": 32706, "s": 32367, "text": "How were the technical Rounds?How would you rate yourself in the rounds?Since you chose 7-8, what would you try to improve?Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)How do you keep yourself updated in tech? (I said medium and Linkedin)Why do you want to join Info Edge?" }, { "code": null, "e": 32737, "s": 32706, "text": "How were the technical Rounds?" }, { "code": null, "e": 32780, "s": 32737, "text": "How would you rate yourself in the rounds?" }, { "code": null, "e": 32832, "s": 32780, "text": "Since you chose 7-8, what would you try to improve?" }, { "code": null, "e": 32944, "s": 32832, "text": "Since your domain in web development, what changes would you suggest to our site? (I told I have seen the site)" }, { "code": null, "e": 33015, "s": 32944, "text": "How do you keep yourself updated in tech? (I said medium and Linkedin)" }, { "code": null, "e": 33050, "s": 33015, "text": "Why do you want to join Info Edge?" }, { "code": null, "e": 33132, "s": 33050, "text": "Special thanks to GeeksforGeeks for the preparation resources. All the very best " }, { "code": null, "e": 33141, "s": 33132, "text": "InfoEdge" }, { "code": null, "e": 33151, "s": 33141, "text": "Marketing" }, { "code": null, "e": 33162, "s": 33151, "text": "Off-Campus" }, { "code": null, "e": 33184, "s": 33162, "text": "Interview Experiences" }, { "code": null, "e": 33193, "s": 33184, "text": "InfoEdge" }, { "code": null, "e": 33291, "s": 33193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33342, "s": 33291, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 33384, "s": 33342, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 33420, "s": 33384, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 33456, "s": 33420, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 33484, "s": 33456, "text": "Amazon Interview Experience" }, { "code": null, "e": 33522, "s": 33484, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 33594, "s": 33522, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 33640, "s": 33594, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 33679, "s": 33640, "text": "EPAM Interview Experience (Off-Campus)" } ]
AngularJS | ng-keypress Directive - GeeksforGeeks
26 Mar, 2019 The ng-keypress Directive in AngluarJS is used to apply custom behavior on a keypress event. It is supported by <input>, <select> and <textarea> element. Syntax: <element ng-keypress="expression"> Contents... </element> Where expression tells what to do when key is pressed. Example: This example uses ng-keypress Directive to display key value. <!DOCTYPE html><html> <head> <title>ng-keypress Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script type="text/javascript"> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.getkeys = function (event) { $scope.keyval = event.keyCode; } }); </script></head> <body style="text-align:center"> <div ng-app="app" ng-controller="geek"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>ng-keypress Directive</h2> Enter Text: <input type="text" ng-keypress="getkeys($event)" > <br><br> <span style="color:Red"> Key Code: {{keyval}} </span> </div></body> </html> Output: AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26354, "s": 26326, "text": "\n26 Mar, 2019" }, { "code": null, "e": 26508, "s": 26354, "text": "The ng-keypress Directive in AngluarJS is used to apply custom behavior on a keypress event. It is supported by <input>, <select> and <textarea> element." }, { "code": null, "e": 26516, "s": 26508, "text": "Syntax:" }, { "code": null, "e": 26574, "s": 26516, "text": "<element ng-keypress=\"expression\"> Contents... </element>" }, { "code": null, "e": 26629, "s": 26574, "text": "Where expression tells what to do when key is pressed." }, { "code": null, "e": 26700, "s": 26629, "text": "Example: This example uses ng-keypress Directive to display key value." }, { "code": "<!DOCTYPE html><html> <head> <title>ng-keypress Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script type=\"text/javascript\"> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.getkeys = function (event) { $scope.keyval = event.keyCode; } }); </script></head> <body style=\"text-align:center\"> <div ng-app=\"app\" ng-controller=\"geek\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>ng-keypress Directive</h2> Enter Text: <input type=\"text\" ng-keypress=\"getkeys($event)\" > <br><br> <span style=\"color:Red\"> Key Code: {{keyval}} </span> </div></body> </html>", "e": 27583, "s": 26700, "text": null }, { "code": null, "e": 27591, "s": 27583, "text": "Output:" }, { "code": null, "e": 27612, "s": 27591, "text": "AngularJS-Directives" }, { "code": null, "e": 27622, "s": 27612, "text": "AngularJS" }, { "code": null, "e": 27639, "s": 27622, "text": "Web Technologies" }, { "code": null, "e": 27737, "s": 27639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27772, "s": 27737, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27807, "s": 27772, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 27831, "s": 27807, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27884, "s": 27831, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27919, "s": 27884, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 27959, "s": 27919, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27992, "s": 27959, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28037, "s": 27992, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28080, "s": 28037, "text": "How to fetch data from an API in ReactJS ?" } ]
Merge Two data.table Objects in R - GeeksforGeeks
23 Aug, 2021 data.table is a package that is used for working with tabular data in R. It provides an enhanced version of “data.frames”, which are the standard data structure for storing data in base R. Installing “data.table” package is no different from other R packages. Its recommended to run “install.packages()” to get the latest version on the CRAN repository. Syntax: install.packages('data.table') The syntax of data.table is shown in the image below : The first parameter of “data.table” i refers to rows. It implies subsetting rows. The second parameter of “data.table” j refers to columns. It implies subsetting columns (dropping / keeping). The third parameter of “data.table” by refers to adding a group so that all calculations would be done within a group. For merging the same syntax is used except it is preceded by merge. Syntax: merge.data.table Example: R program to merge two data.table objects R # Load data.table packagelibrary(“data.table”)print(“first class”)# Create first data.tableclass1 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'), Subjects = c('Hindi','English','Maths','Science'), Marks1 = c(89,78,72,64)) # Print first data.table print(class1) print("second class") # Create second data.table class2 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'), Subjects = c('Hindi','English','Maths','Science'), Marks2 = c(56,64,53,88)) # Print second data.table print(class2) print("merge first and second class") # Merge data.tables merge_class <- merge.data.table(class1, class2, by.x = "Subjects", by.y = "Subjects") # Print merged data.table print(merge_class) print(“first class”) # Create first data.tableclass1 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'), Subjects = c('Hindi','English','Maths','Science'), Marks1 = c(89,78,72,64)) # Print first data.table print(class1) print("second class") # Create second data.table class2 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'), Subjects = c('Hindi','English','Maths','Science'), Marks2 = c(56,64,53,88)) # Print second data.table print(class2) print("merge first and second class") # Merge data.tables merge_class <- merge.data.table(class1, class2, by.x = "Subjects", by.y = "Subjects") # Print merged data.table print(merge_class) Output: Example: R program to merge two data.table objects R # Load data.table packagelibrary(“data.table”)# table 1D1 = data.table(char=rep(c(“a”,”b”,”c”),each=2),num=c(1,3,6), num1=1:6)D1# table 2D2 = data.table(char=rep(c(“d”,”e”,”f”),each=2),num=c(9,12,15), num1=1:6)D2# merge tableD3 = merge.data.table(D1,D2, by.x=”num1′′, by.y=”num1′′)D3 # table 1D1 = data.table(char=rep(c(“a”,”b”,”c”),each=2),num=c(1,3,6), num1=1:6)D1 # table 2D2 = data.table(char=rep(c(“d”,”e”,”f”),each=2),num=c(9,12,15), num1=1:6)D2 # merge tableD3 = merge.data.table(D1,D2, by.x=”num1′′, by.y=”num1′′)D3 Output: Picked R DataTable R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26676, "s": 26487, "text": "data.table is a package that is used for working with tabular data in R. It provides an enhanced version of “data.frames”, which are the standard data structure for storing data in base R." }, { "code": null, "e": 26842, "s": 26676, "text": "Installing “data.table” package is no different from other R packages. Its recommended to run “install.packages()” to get the latest version on the CRAN repository. " }, { "code": null, "e": 26850, "s": 26842, "text": "Syntax:" }, { "code": null, "e": 26881, "s": 26850, "text": "install.packages('data.table')" }, { "code": null, "e": 26936, "s": 26881, "text": "The syntax of data.table is shown in the image below :" }, { "code": null, "e": 27018, "s": 26936, "text": "The first parameter of “data.table” i refers to rows. It implies subsetting rows." }, { "code": null, "e": 27128, "s": 27018, "text": "The second parameter of “data.table” j refers to columns. It implies subsetting columns (dropping / keeping)." }, { "code": null, "e": 27247, "s": 27128, "text": "The third parameter of “data.table” by refers to adding a group so that all calculations would be done within a group." }, { "code": null, "e": 27315, "s": 27247, "text": "For merging the same syntax is used except it is preceded by merge." }, { "code": null, "e": 27323, "s": 27315, "text": "Syntax:" }, { "code": null, "e": 27340, "s": 27323, "text": "merge.data.table" }, { "code": null, "e": 27391, "s": 27340, "text": "Example: R program to merge two data.table objects" }, { "code": null, "e": 27393, "s": 27391, "text": "R" }, { "code": "# Load data.table packagelibrary(“data.table”)print(“first class”)# Create first data.tableclass1 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'),\nSubjects = c('Hindi','English','Maths','Science'),\nMarks1 = c(89,78,72,64))\n# Print first data.table\nprint(class1)\nprint(\"second class\")\n# Create second data.table\nclass2 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'),\nSubjects = c('Hindi','English','Maths','Science'),\nMarks2 = c(56,64,53,88))\n# Print second data.table\nprint(class2)\nprint(\"merge first and second class\")\n# Merge data.tables\nmerge_class <- merge.data.table(class1, class2, by.x = \"Subjects\",\nby.y = \"Subjects\")\n# Print merged data.table\nprint(merge_class)", "e": 28097, "s": 27393, "text": null }, { "code": null, "e": 28118, "s": 28097, "text": "print(“first class”)" }, { "code": null, "e": 28756, "s": 28118, "text": "# Create first data.tableclass1 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'),\nSubjects = c('Hindi','English','Maths','Science'),\nMarks1 = c(89,78,72,64))\n# Print first data.table\nprint(class1)\nprint(\"second class\")\n# Create second data.table\nclass2 <- data.table(stu_name = c('Naveen','Nupur','Ritika','Praveen'),\nSubjects = c('Hindi','English','Maths','Science'),\nMarks2 = c(56,64,53,88))\n# Print second data.table\nprint(class2)\nprint(\"merge first and second class\")\n# Merge data.tables\nmerge_class <- merge.data.table(class1, class2, by.x = \"Subjects\",\nby.y = \"Subjects\")\n# Print merged data.table\nprint(merge_class)" }, { "code": null, "e": 28764, "s": 28756, "text": "Output:" }, { "code": null, "e": 28815, "s": 28764, "text": "Example: R program to merge two data.table objects" }, { "code": null, "e": 28817, "s": 28815, "text": "R" }, { "code": "# Load data.table packagelibrary(“data.table”)# table 1D1 = data.table(char=rep(c(“a”,”b”,”c”),each=2),num=c(1,3,6), num1=1:6)D1# table 2D2 = data.table(char=rep(c(“d”,”e”,”f”),each=2),num=c(9,12,15), num1=1:6)D2# merge tableD3 = merge.data.table(D1,D2, by.x=”num1′′, by.y=”num1′′)D3", "e": 29101, "s": 28817, "text": null }, { "code": null, "e": 29184, "s": 29101, "text": "# table 1D1 = data.table(char=rep(c(“a”,”b”,”c”),each=2),num=c(1,3,6), num1=1:6)D1" }, { "code": null, "e": 29269, "s": 29184, "text": "# table 2D2 = data.table(char=rep(c(“d”,”e”,”f”),each=2),num=c(9,12,15), num1=1:6)D2" }, { "code": null, "e": 29341, "s": 29269, "text": "# merge tableD3 = merge.data.table(D1,D2, by.x=”num1′′, by.y=”num1′′)D3" }, { "code": null, "e": 29349, "s": 29341, "text": "Output:" }, { "code": null, "e": 29356, "s": 29349, "text": "Picked" }, { "code": null, "e": 29368, "s": 29356, "text": "R DataTable" }, { "code": null, "e": 29379, "s": 29368, "text": "R Language" }, { "code": null, "e": 29477, "s": 29379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29529, "s": 29477, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29564, "s": 29529, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29602, "s": 29564, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29660, "s": 29602, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29703, "s": 29660, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29740, "s": 29703, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29789, "s": 29740, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29815, "s": 29789, "text": "Time Series Analysis in R" }, { "code": null, "e": 29852, "s": 29815, "text": "Logistic Regression in R Programming" } ]
Convert Array to LinkedList in Java - GeeksforGeeks
31 Mar, 2022 Array is contiguous memory allocation while LinkedList is a block of elements randomly placed in the memory which are linked together where a block is holding the address of another block in memory. Sometimes as per requirement or because of space issues in memory where there are bigger chunks of code in the enterprising world it becomes necessary to convert arrays to List. Here conversion of array to LinkedList is demonstrated. Methods: Using asList() method of Collections classUsing addAll() method of Collections class Using asList() method of Collections class Using addAll() method of Collections class Method 1: Using asList() method of Collections class This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serialized and implements RandomAccess. This runs in O(1) time. Syntax: public static List asList(T... a) ; Parameters: This method takes the array a which is required to be converted into a List. Here array of parameters works similar to an object array parameter. Approach: Create an array.Convert the array to List.Create LinkedList from the List using the constructor. Create an array. Convert the array to List. Create LinkedList from the List using the constructor. Example Java // Java Program to convert Array to LinkedList // Importing array, List & LinkedList classes from// java.util packageimport java.util.Arrays;import java.util.LinkedList;import java.util.List; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Create a string Array String[] strArr = { "A", "B", "C", "D", "E" }; // Convert array to list List<String> list = Arrays.asList(strArr); // Create a LinkedList and // pass List in LinkedList constructor LinkedList<String> linkedList = new LinkedList<String>(list); // Display and print all elements of LinkedList System.out.println("LinkedList of above array : " + linkedList); }} LinkedList of above array : [A, B, C, D, E] Method 2: Using addAll() method of Collections class This method is used to append all the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator. Syntax: boolean addAll(Collection C) ; Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list. Return Value: The method returns true if at least one action of append is performed else return false. Approach: Create an array.Create an empty LinkedList.Use addAll() method of collections class which takes two objects as parameters.First object as where to be convertedSecond object as which to be converted. Create an array. Create an empty LinkedList. Use addAll() method of collections class which takes two objects as parameters.First object as where to be convertedSecond object as which to be converted. First object as where to be converted Second object as which to be converted. Example Java // Java Program to convert Array to LinkedList // Importing array, List & LinkedList, Collections classes// from java.util packageimport java.util.Arrays;import java.util.Collections;import java.util.LinkedList;import java.util.List; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Create an Array // here string type String[] strArr = { "G", "E", "E", "K", "S" }; // Create an empty LinkedList LinkedList<String> linkedList = new LinkedList<String>(); // Append all elements of array to linked list // using Collections.addAll() method Collections.addAll(linkedList, strArr); // Print the above LinkedList received System.out.println("Converted LinkedList : "+linkedList); }} Converted LinkedList : [G, E, E, K, S] simmytarika5 varshagumber28 simranarora5sos Java-Arrays Java-Collections java-LinkedList Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25249, "s": 25221, "text": "\n31 Mar, 2022" }, { "code": null, "e": 25683, "s": 25249, "text": "Array is contiguous memory allocation while LinkedList is a block of elements randomly placed in the memory which are linked together where a block is holding the address of another block in memory. Sometimes as per requirement or because of space issues in memory where there are bigger chunks of code in the enterprising world it becomes necessary to convert arrays to List. Here conversion of array to LinkedList is demonstrated. " }, { "code": null, "e": 25693, "s": 25683, "text": "Methods: " }, { "code": null, "e": 25778, "s": 25693, "text": "Using asList() method of Collections classUsing addAll() method of Collections class" }, { "code": null, "e": 25821, "s": 25778, "text": "Using asList() method of Collections class" }, { "code": null, "e": 25864, "s": 25821, "text": "Using addAll() method of Collections class" }, { "code": null, "e": 25917, "s": 25864, "text": "Method 1: Using asList() method of Collections class" }, { "code": null, "e": 26119, "s": 25917, "text": "This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serialized and implements RandomAccess. This runs in O(1) time. " }, { "code": null, "e": 26128, "s": 26119, "text": "Syntax: " }, { "code": null, "e": 26164, "s": 26128, "text": "public static List asList(T... a) ;" }, { "code": null, "e": 26322, "s": 26164, "text": "Parameters: This method takes the array a which is required to be converted into a List. Here array of parameters works similar to an object array parameter." }, { "code": null, "e": 26332, "s": 26322, "text": "Approach:" }, { "code": null, "e": 26429, "s": 26332, "text": "Create an array.Convert the array to List.Create LinkedList from the List using the constructor." }, { "code": null, "e": 26446, "s": 26429, "text": "Create an array." }, { "code": null, "e": 26473, "s": 26446, "text": "Convert the array to List." }, { "code": null, "e": 26528, "s": 26473, "text": "Create LinkedList from the List using the constructor." }, { "code": null, "e": 26536, "s": 26528, "text": "Example" }, { "code": null, "e": 26541, "s": 26536, "text": "Java" }, { "code": "// Java Program to convert Array to LinkedList // Importing array, List & LinkedList classes from// java.util packageimport java.util.Arrays;import java.util.LinkedList;import java.util.List; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Create a string Array String[] strArr = { \"A\", \"B\", \"C\", \"D\", \"E\" }; // Convert array to list List<String> list = Arrays.asList(strArr); // Create a LinkedList and // pass List in LinkedList constructor LinkedList<String> linkedList = new LinkedList<String>(list); // Display and print all elements of LinkedList System.out.println(\"LinkedList of above array : \" + linkedList); }}", "e": 27324, "s": 26541, "text": null }, { "code": null, "e": 27368, "s": 27324, "text": "LinkedList of above array : [A, B, C, D, E]" }, { "code": null, "e": 27421, "s": 27368, "text": "Method 2: Using addAll() method of Collections class" }, { "code": null, "e": 27612, "s": 27421, "text": "This method is used to append all the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator. " }, { "code": null, "e": 27621, "s": 27612, "text": "Syntax: " }, { "code": null, "e": 27652, "s": 27621, "text": "boolean addAll(Collection C) ;" }, { "code": null, "e": 27796, "s": 27652, "text": "Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list." }, { "code": null, "e": 27899, "s": 27796, "text": "Return Value: The method returns true if at least one action of append is performed else return false." }, { "code": null, "e": 27910, "s": 27899, "text": "Approach: " }, { "code": null, "e": 28109, "s": 27910, "text": "Create an array.Create an empty LinkedList.Use addAll() method of collections class which takes two objects as parameters.First object as where to be convertedSecond object as which to be converted." }, { "code": null, "e": 28126, "s": 28109, "text": "Create an array." }, { "code": null, "e": 28154, "s": 28126, "text": "Create an empty LinkedList." }, { "code": null, "e": 28310, "s": 28154, "text": "Use addAll() method of collections class which takes two objects as parameters.First object as where to be convertedSecond object as which to be converted." }, { "code": null, "e": 28348, "s": 28310, "text": "First object as where to be converted" }, { "code": null, "e": 28388, "s": 28348, "text": "Second object as which to be converted." }, { "code": null, "e": 28398, "s": 28388, "text": "Example " }, { "code": null, "e": 28403, "s": 28398, "text": "Java" }, { "code": "// Java Program to convert Array to LinkedList // Importing array, List & LinkedList, Collections classes// from java.util packageimport java.util.Arrays;import java.util.Collections;import java.util.LinkedList;import java.util.List; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Create an Array // here string type String[] strArr = { \"G\", \"E\", \"E\", \"K\", \"S\" }; // Create an empty LinkedList LinkedList<String> linkedList = new LinkedList<String>(); // Append all elements of array to linked list // using Collections.addAll() method Collections.addAll(linkedList, strArr); // Print the above LinkedList received System.out.println(\"Converted LinkedList : \"+linkedList); }}", "e": 29223, "s": 28403, "text": null }, { "code": null, "e": 29262, "s": 29223, "text": "Converted LinkedList : [G, E, E, K, S]" }, { "code": null, "e": 29277, "s": 29264, "text": "simmytarika5" }, { "code": null, "e": 29292, "s": 29277, "text": "varshagumber28" }, { "code": null, "e": 29308, "s": 29292, "text": "simranarora5sos" }, { "code": null, "e": 29320, "s": 29308, "text": "Java-Arrays" }, { "code": null, "e": 29337, "s": 29320, "text": "Java-Collections" }, { "code": null, "e": 29353, "s": 29337, "text": "java-LinkedList" }, { "code": null, "e": 29360, "s": 29353, "text": "Picked" }, { "code": null, "e": 29384, "s": 29360, "text": "Technical Scripter 2020" }, { "code": null, "e": 29389, "s": 29384, "text": "Java" }, { "code": null, "e": 29403, "s": 29389, "text": "Java Programs" }, { "code": null, "e": 29422, "s": 29403, "text": "Technical Scripter" }, { "code": null, "e": 29427, "s": 29422, "text": "Java" }, { "code": null, "e": 29444, "s": 29427, "text": "Java-Collections" }, { "code": null, "e": 29542, "s": 29444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29557, "s": 29542, "text": "Stream In Java" }, { "code": null, "e": 29578, "s": 29557, "text": "Constructors in Java" }, { "code": null, "e": 29597, "s": 29578, "text": "Exceptions in Java" }, { "code": null, "e": 29627, "s": 29597, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29673, "s": 29627, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29699, "s": 29673, "text": "Java Programming Examples" }, { "code": null, "e": 29733, "s": 29699, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29780, "s": 29733, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29812, "s": 29780, "text": "How to Iterate HashMap in Java?" } ]
Basic Graphic Programming in C++ - GeeksforGeeks
06 Jan, 2017 IntroductionSo far we have been using C language for simple console output only. Most of us are unaware that using C++, low level graphics program can also be made. This means we can incorporate shapes,colors and designer fonts in our program. This article deals with the steps to enable the DevC++ compiler to generate graphics .Configuring DevC++ Step 1: Download the DevC++ version 5.11 from here. Step 2: Download the Graphics header files, and etc stuff needed from the given dropbox link. Step 3: Extract the contents of the rar file. Step 4: Go to the location where DevC++ is installed. For me its D drive. Go inside the MinGW64 folder. Copy the graphics.h and winbgim.h in the include folder and D:\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include folder. Step 5:Copy the libbgi.a file into lib folder and in D:\Dev-Cpp\MinGW64\x86_64-w64-mingw32\lib folder. Step 6: Copy the ConsoleAppGraphics.template, ConsoleApp_cpp_graph.txt files and paste them inside the template folder of the devc++ installer location. Now we are done with configuring of the DevC++ to support graphics programming. We shall write our very first graphics program now.Running the first graphics program Open DevC++. Click file ->New ->Project.Make sure you get the Console Graphics option. However, we are not going to click on it.Choose Empty Project option and Give a project name and make sure the selected language is C++.Copy the following code to the editor window.#include<graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd,&gm, "C:\\tc\\bgi"); circle(300,300,50); closegraph(); getch(); } Go to “Project” menu and choose “Project Options” (or just press ALT+P).Go to the “Parameters” tab In the “Linker” field, enter the following text:-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32Click OK and Compile and run the project and you’ll get this output: Open DevC++. Click file ->New ->Project. Make sure you get the Console Graphics option. However, we are not going to click on it. Choose Empty Project option and Give a project name and make sure the selected language is C++. Copy the following code to the editor window.#include<graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd,&gm, "C:\\tc\\bgi"); circle(300,300,50); closegraph(); getch(); } #include<graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd,&gm, "C:\\tc\\bgi"); circle(300,300,50); closegraph(); getch(); } Go to “Project” menu and choose “Project Options” (or just press ALT+P). Go to the “Parameters” tab In the “Linker” field, enter the following text:-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32 Click OK and Compile and run the project and you’ll get this output: Program Explanation The initgraph function- ?Initializes the graphics system. In C Program execution starts with main() similarly Graphics Environment Starts with this function. initgraph() initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode This article is contributed by Mudit Maheshwari. 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 computer-graphics Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation Simple Chat Room using Python Java Swing | Simple User Registration Form OpenCV C++ Program for Face Detection Twitter Sentiment Analysis using Python Banking Transaction System using Java Snake Game in C Face Detection using Python and OpenCV with webcam Program for Employee Management System A Group chat application in Java
[ { "code": null, "e": 25886, "s": 25858, "text": "\n06 Jan, 2017" }, { "code": null, "e": 26236, "s": 25886, "text": "IntroductionSo far we have been using C language for simple console output only. Most of us are unaware that using C++, low level graphics program can also be made. This means we can incorporate shapes,colors and designer fonts in our program. This article deals with the steps to enable the DevC++ compiler to generate graphics .Configuring DevC++" }, { "code": null, "e": 26288, "s": 26236, "text": "Step 1: Download the DevC++ version 5.11 from here." }, { "code": null, "e": 26382, "s": 26288, "text": "Step 2: Download the Graphics header files, and etc stuff needed from the given dropbox link." }, { "code": null, "e": 26428, "s": 26382, "text": "Step 3: Extract the contents of the rar file." }, { "code": null, "e": 26646, "s": 26428, "text": "Step 4: Go to the location where DevC++ is installed. For me its D drive. Go inside the MinGW64 folder. Copy the graphics.h and winbgim.h in the include folder and D:\\Dev-Cpp\\MinGW64\\x86_64-w64-mingw32\\include folder." }, { "code": null, "e": 26749, "s": 26646, "text": "Step 5:Copy the libbgi.a file into lib folder and in D:\\Dev-Cpp\\MinGW64\\x86_64-w64-mingw32\\lib folder." }, { "code": null, "e": 26902, "s": 26749, "text": "Step 6: Copy the ConsoleAppGraphics.template, ConsoleApp_cpp_graph.txt files and paste them inside the template folder of the devc++ installer location." }, { "code": null, "e": 27068, "s": 26902, "text": "Now we are done with configuring of the DevC++ to support graphics programming. We shall write our very first graphics program now.Running the first graphics program" }, { "code": null, "e": 27772, "s": 27068, "text": "Open DevC++. Click file ->New ->Project.Make sure you get the Console Graphics option. However, we are not going to click on it.Choose Empty Project option and Give a project name and make sure the selected language is C++.Copy the following code to the editor window.#include<graphics.h>\n#include <conio.h>\nint main()\n{\n int gd = DETECT, gm;\n initgraph(&gd,&gm, \"C:\\\\tc\\\\bgi\");\n circle(300,300,50);\n closegraph();\n getch();\n}\n\nGo to “Project” menu and choose “Project Options” (or just press ALT+P).Go to the “Parameters” tab In the “Linker” field, enter the following text:-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32Click OK and Compile and run the project and you’ll get this output:" }, { "code": null, "e": 27813, "s": 27772, "text": "Open DevC++. Click file ->New ->Project." }, { "code": null, "e": 27902, "s": 27813, "text": "Make sure you get the Console Graphics option. However, we are not going to click on it." }, { "code": null, "e": 27998, "s": 27902, "text": "Choose Empty Project option and Give a project name and make sure the selected language is C++." }, { "code": null, "e": 28219, "s": 27998, "text": "Copy the following code to the editor window.#include<graphics.h>\n#include <conio.h>\nint main()\n{\n int gd = DETECT, gm;\n initgraph(&gd,&gm, \"C:\\\\tc\\\\bgi\");\n circle(300,300,50);\n closegraph();\n getch();\n}\n\n" }, { "code": null, "e": 28395, "s": 28219, "text": "#include<graphics.h>\n#include <conio.h>\nint main()\n{\n int gd = DETECT, gm;\n initgraph(&gd,&gm, \"C:\\\\tc\\\\bgi\");\n circle(300,300,50);\n closegraph();\n getch();\n}\n\n" }, { "code": null, "e": 28468, "s": 28395, "text": "Go to “Project” menu and choose “Project Options” (or just press ALT+P)." }, { "code": null, "e": 28589, "s": 28468, "text": "Go to the “Parameters” tab In the “Linker” field, enter the following text:-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32" }, { "code": null, "e": 28658, "s": 28589, "text": "Click OK and Compile and run the project and you’ll get this output:" }, { "code": null, "e": 28678, "s": 28658, "text": "Program Explanation" }, { "code": null, "e": 28736, "s": 28678, "text": "The initgraph function- ?Initializes the graphics system." }, { "code": null, "e": 28836, "s": 28736, "text": "In C Program execution starts with main() similarly Graphics Environment Starts with this function." }, { "code": null, "e": 28998, "s": 28836, "text": "initgraph() initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode" }, { "code": null, "e": 29268, "s": 28998, "text": "This article is contributed by Mudit Maheshwari. 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." }, { "code": null, "e": 29392, "s": 29268, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 29410, "s": 29392, "text": "computer-graphics" }, { "code": null, "e": 29418, "s": 29410, "text": "Project" }, { "code": null, "e": 29516, "s": 29418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29565, "s": 29516, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 29595, "s": 29565, "text": "Simple Chat Room using Python" }, { "code": null, "e": 29638, "s": 29595, "text": "Java Swing | Simple User Registration Form" }, { "code": null, "e": 29676, "s": 29638, "text": "OpenCV C++ Program for Face Detection" }, { "code": null, "e": 29716, "s": 29676, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 29754, "s": 29716, "text": "Banking Transaction System using Java" }, { "code": null, "e": 29770, "s": 29754, "text": "Snake Game in C" }, { "code": null, "e": 29821, "s": 29770, "text": "Face Detection using Python and OpenCV with webcam" }, { "code": null, "e": 29860, "s": 29821, "text": "Program for Employee Management System" } ]
Stack search() Method in Java - GeeksforGeeks
13 Aug, 2019 The java.util.Stack.search(Object element) method in Java is used to search for an element in the stack and get its distance from the top. This method starts the count of the position from 1 and not from 0. The element that is on the top of the stack is considered to be at position 1. If more than one element is present, the index of the element closest to the top is returned. The method returns its position if the element is successfully found and returns -1 if the element is absent. Syntax: STACK.search(element) Parameters: The method accepts one parameter element which refers to the element that is required to be searched for in the Stack. Return Value: The method returns the position of the element if it is successfully found in the stack (taking the count as base 1) else -1 is returned. Below programs illustrate the working of java.util.Stack.search() method:Program 1: // Java code to demonstrate search() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Stacking strings STACK.push("Geeks"); STACK.push("4"); STACK.push("Geeks"); STACK.push("Welcomes"); STACK.push("You"); // Displaying the Stack System.out.println("The stack is: " + STACK); // Checking for the element "4" System.out.println("Does the stack contains '4'? " + STACK.search("4")); // Checking for the element "Hello" System.out.println("Does the stack contains 'Hello'? " + STACK.search("Hello")); // Checking for the element "Geeks" System.out.println("Does the stack contains 'Geeks'? " + STACK.search("Geeks")); }} The stack is: [Geeks, 4, Geeks, Welcomes, You] Does the stack contains '4'? 4 Does the stack contains 'Hello'? -1 Does the stack contains 'Geeks'? 3 Program 2: // Java code to demonstrate search() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Stacking int values STACK.push(8); STACK.push(5); STACK.push(9); STACK.push(2); STACK.push(4); // Displaying the Stack System.out.println("The stack is: " + STACK); // Checking for the element 9 System.out.println("Does the stack contains '9'? " + STACK.search(9)); // Checking for the element 10 System.out.println("Does the stack contains '10'? " + STACK.search(10)); // Checking for the element 11 System.out.println("Does the stack contains '11'? " + STACK.search(11)); }} The stack is: [8, 5, 9, 2, 4] Does the stack contains '9'? 3 Does the stack contains '10'? -1 Does the stack contains '11'? -1 sharmahs Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25719, "s": 25691, "text": "\n13 Aug, 2019" }, { "code": null, "e": 26209, "s": 25719, "text": "The java.util.Stack.search(Object element) method in Java is used to search for an element in the stack and get its distance from the top. This method starts the count of the position from 1 and not from 0. The element that is on the top of the stack is considered to be at position 1. If more than one element is present, the index of the element closest to the top is returned. The method returns its position if the element is successfully found and returns -1 if the element is absent." }, { "code": null, "e": 26217, "s": 26209, "text": "Syntax:" }, { "code": null, "e": 26239, "s": 26217, "text": "STACK.search(element)" }, { "code": null, "e": 26370, "s": 26239, "text": "Parameters: The method accepts one parameter element which refers to the element that is required to be searched for in the Stack." }, { "code": null, "e": 26522, "s": 26370, "text": "Return Value: The method returns the position of the element if it is successfully found in the stack (taking the count as base 1) else -1 is returned." }, { "code": null, "e": 26606, "s": 26522, "text": "Below programs illustrate the working of java.util.Stack.search() method:Program 1:" }, { "code": "// Java code to demonstrate search() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Stacking strings STACK.push(\"Geeks\"); STACK.push(\"4\"); STACK.push(\"Geeks\"); STACK.push(\"Welcomes\"); STACK.push(\"You\"); // Displaying the Stack System.out.println(\"The stack is: \" + STACK); // Checking for the element \"4\" System.out.println(\"Does the stack contains '4'? \" + STACK.search(\"4\")); // Checking for the element \"Hello\" System.out.println(\"Does the stack contains 'Hello'? \" + STACK.search(\"Hello\")); // Checking for the element \"Geeks\" System.out.println(\"Does the stack contains 'Geeks'? \" + STACK.search(\"Geeks\")); }}", "e": 27580, "s": 26606, "text": null }, { "code": null, "e": 27730, "s": 27580, "text": "The stack is: [Geeks, 4, Geeks, Welcomes, You]\nDoes the stack contains '4'? 4\nDoes the stack contains 'Hello'? -1\nDoes the stack contains 'Geeks'? 3\n" }, { "code": null, "e": 27741, "s": 27730, "text": "Program 2:" }, { "code": "// Java code to demonstrate search() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Stacking int values STACK.push(8); STACK.push(5); STACK.push(9); STACK.push(2); STACK.push(4); // Displaying the Stack System.out.println(\"The stack is: \" + STACK); // Checking for the element 9 System.out.println(\"Does the stack contains '9'? \" + STACK.search(9)); // Checking for the element 10 System.out.println(\"Does the stack contains '10'? \" + STACK.search(10)); // Checking for the element 11 System.out.println(\"Does the stack contains '11'? \" + STACK.search(11)); }}", "e": 28669, "s": 27741, "text": null }, { "code": null, "e": 28797, "s": 28669, "text": "The stack is: [8, 5, 9, 2, 4]\nDoes the stack contains '9'? 3\nDoes the stack contains '10'? -1\nDoes the stack contains '11'? -1\n" }, { "code": null, "e": 28806, "s": 28797, "text": "sharmahs" }, { "code": null, "e": 28826, "s": 28806, "text": "Java - util package" }, { "code": null, "e": 28843, "s": 28826, "text": "Java-Collections" }, { "code": null, "e": 28858, "s": 28843, "text": "Java-Functions" }, { "code": null, "e": 28869, "s": 28858, "text": "Java-Stack" }, { "code": null, "e": 28874, "s": 28869, "text": "Java" }, { "code": null, "e": 28879, "s": 28874, "text": "Java" }, { "code": null, "e": 28896, "s": 28879, "text": "Java-Collections" }, { "code": null, "e": 28994, "s": 28896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29009, "s": 28994, "text": "Arrays in Java" }, { "code": null, "e": 29053, "s": 29009, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29075, "s": 29053, "text": "For-each loop in Java" }, { "code": null, "e": 29126, "s": 29075, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29162, "s": 29126, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 29192, "s": 29162, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29217, "s": 29192, "text": "Reverse a string in Java" }, { "code": null, "e": 29232, "s": 29217, "text": "Stream In Java" }, { "code": null, "e": 29251, "s": 29232, "text": "Interfaces in Java" } ]
Sum of f(a[i], a[j]) over all pairs in an array of n integers - GeeksforGeeks
29 May, 2021 Given an array of n integers, find the sum of f(a[i], a[j]) of all pairs (i, j) such that (1 <= i < j <= n). f(a[i], a[j]): If |a[j]-a[i]| > 1 f(a[i], a[j]) = a[j] - a[i] Else // if |a[j]-a[i]| <= 1 f(a[i], a[j]) = 0 Examples: Input : 6 6 4 4 Output : -8 Explanation: All pairs are: (6 - 6) + (6 - 6) + (6 - 6) + (4 - 6) + (4 - 6) + (4 - 6) + (4 - 6) + (4 - 4) + (4 - 4) = -8 Input: 1 2 3 1 3 Output: 4 Explanation: the pairs that add up are: (3, 1), (3, 1) to give 4, rest all pairs according to condition gives 0. A naive approach is to iterate through all pairs and calculate f(a[i], a[j]), and summing it up while traversing two nested loops will give us our answer. Time Complexity: O(n^2) An efficient approach would be to use a map/hash function to keep a count of every occurring number and then traverse through the list. While traversing through the list, we multiply the count of numbers that are before it and the number itself. Then subtract this result with the pre-sum of the number before that number to get the sum of the difference of all pairs possible with that number. To remove all pairs whose absolute difference is <=1, simply subtract the count of occurrence of (number-1) and (number+1) from the previously computed sum. Here we subtract the count of (number-1) from the computed sum as it had been previously added to the sum, and we add the (number+1) count since the negative has been added to the pre-computed sum of all pairs.Time Complexity: O(n) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to calculate the// sum of f(a[i], aj])#include <bits/stdc++.h>using namespace std; // Function to calculate the sumint sum(int a[], int n){ // map to keep a count of occurrences unordered_map<int, int> cnt; // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum. int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // if the (a[i]-1) is present then // subtract that value as f(a[i], a[i]-1)=0 if (cnt[a[i] - 1]) ans -= cnt[a[i] - 1]; // if the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt[a[i] + 1]) ans += cnt[a[i] + 1]; // keeping a counter for every element cnt[a[i]]++; } return ans;} // Driver codeint main(){ int a[] = { 1, 2, 3, 1, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << sum(a, n); return 0;} // Java program to calculate // the sum of f(a[i], aj])import java.util.*;public class GfG { // Function to calculate the sum public static int sum(int a[], int n) { // Map to keep a count of occurrences Map<Integer,Integer> cnt = new HashMap<Integer,Integer>(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // If the (a[i]-1) is present then subtract // that value as f(a[i], a[i]-1) = 0 if (cnt.containsKey(a[i] - 1)) ans -= cnt.get(a[i] - 1); // If the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt.containsKey(a[i] + 1)) ans += cnt.get(a[i] + 1); // keeping a counter for every element if(cnt.containsKey(a[i])) { cnt.put(a[i], cnt.get(a[i]) + 1); } else { cnt.put(a[i], 1); } } return ans; } // Driver code public static void main(String args[]) { int a[] = { 1, 2, 3, 1, 3 }; int n = a.length; System.out.println(sum(a, n)); }} // This code is contributed by Swetank Modi # Python3 program to calculate the# sum of f(a[i], aj]) # Function to calculate the sumdef sum(a, n): # map to keep a count of occurrences cnt = dict() # Traverse in the list from start to end # number of times a[i] can be in a pair and # to get the difference we subtract pre_sum. ans = 0 pre_sum = 0 for i in range(n): ans += (i * a[i]) - pre_sum pre_sum += a[i] # if the (a[i]-1) is present then # subtract that value as f(a[i], a[i]-1)=0 if (a[i] - 1) in cnt: ans -= cnt[a[i] - 1] # if the (a[i]+1) is present then add that # value as f(a[i], a[i]-1)=0 here we add # as a[i]-(a[i]-1)<0 which would have been # added as negative sum, so we add to remove # this pair from the sum value if (a[i] + 1) in cnt: ans += cnt[a[i] + 1] # keeping a counter for every element if a[i] not in cnt: cnt[a[i]] = 0 cnt[a[i]] += 1 return ans # Driver Codeif __name__ == '__main__': a = [1, 2, 3, 1, 3] n = len(a) print(sum(a, n)) # This code is contributed by# SHUBHAMSINGH10 using System;using System.Collections.Generic; // C# program to calculate // the sum of f(a[i], aj])public class GfG{ // Function to calculate the sum public static int sum(int[] a, int n) { // Map to keep a count of occurrences IDictionary<int, int> cnt = new Dictionary<int, int>(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // If the (a[i]-1) is present then subtract // that value as f(a[i], a[i]-1) = 0 if (cnt.ContainsKey(a[i] - 1)) { ans -= cnt[a[i] - 1]; } // If the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt.ContainsKey(a[i] + 1)) { ans += cnt[a[i] + 1]; } // keeping a counter for every element if (cnt.ContainsKey(a[i])) { cnt[a[i]] = cnt[a[i]] + 1; } else { cnt[a[i]] = 1; } } return ans; } // Driver code public static void Main(string[] args) { int[] a = new int[] {1, 2, 3, 1, 3}; int n = a.Length; Console.WriteLine(sum(a, n)); }} // This code is contributed by Shrikant13 <script> // Javascript program to calculate the// sum of f(a[i], aj]) // Function to calculate the sumfunction sum(a, n){ // map to keep a count of occurrences var cnt = new Map(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum. var ans = 0, pre_sum = 0; for (var i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // if the (a[i]-1) is present then // subtract that value as f(a[i], a[i]-1)=0 if (cnt.has(a[i] - 1)) ans -= cnt.get(a[i] - 1); // if the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if(cnt.has(a[i] + 1)) ans += cnt.get(a[i] + 1); // keeping a counter for every element if(cnt.has(a[i])) cnt.set(a[i], cnt.get(a[i])+1) else cnt.set(a[i], 1) } return ans;} // Driver codevar a = [1, 2, 3, 1, 3];var n = a.length;document.write( sum(a, n)); </script> Output: 4 shrikanth13 SHUBHAMSINGH10 famously cpp-unordered_map Arrays Competitive Programming Hash Mathematical Arrays Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26449, "s": 26421, "text": "\n29 May, 2021" }, { "code": null, "e": 26560, "s": 26449, "text": "Given an array of n integers, find the sum of f(a[i], a[j]) of all pairs (i, j) such that (1 <= i < j <= n). " }, { "code": null, "e": 26576, "s": 26560, "text": "f(a[i], a[j]): " }, { "code": null, "e": 26676, "s": 26576, "text": "If |a[j]-a[i]| > 1\n f(a[i], a[j]) = a[j] - a[i] \nElse // if |a[j]-a[i]| <= 1\n f(a[i], a[j]) = 0" }, { "code": null, "e": 26687, "s": 26676, "text": "Examples: " }, { "code": null, "e": 26985, "s": 26687, "text": "Input : 6 6 4 4 \nOutput : -8 \nExplanation: \nAll pairs are: (6 - 6) + (6 - 6) +\n(6 - 6) + (4 - 6) + (4 - 6) + (4 - 6) + \n(4 - 6) + (4 - 4) + (4 - 4) = -8\n\nInput: 1 2 3 1 3\nOutput: 4 \nExplanation: the pairs that add up are:\n(3, 1), (3, 1) to give 4, rest all pairs \naccording to condition gives 0. " }, { "code": null, "e": 27166, "s": 26985, "text": "A naive approach is to iterate through all pairs and calculate f(a[i], a[j]), and summing it up while traversing two nested loops will give us our answer. Time Complexity: O(n^2) " }, { "code": null, "e": 27951, "s": 27166, "text": "An efficient approach would be to use a map/hash function to keep a count of every occurring number and then traverse through the list. While traversing through the list, we multiply the count of numbers that are before it and the number itself. Then subtract this result with the pre-sum of the number before that number to get the sum of the difference of all pairs possible with that number. To remove all pairs whose absolute difference is <=1, simply subtract the count of occurrence of (number-1) and (number+1) from the previously computed sum. Here we subtract the count of (number-1) from the computed sum as it had been previously added to the sum, and we add the (number+1) count since the negative has been added to the pre-computed sum of all pairs.Time Complexity: O(n) " }, { "code": null, "e": 28003, "s": 27951, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28007, "s": 28003, "text": "C++" }, { "code": null, "e": 28012, "s": 28007, "text": "Java" }, { "code": null, "e": 28020, "s": 28012, "text": "Python3" }, { "code": null, "e": 28023, "s": 28020, "text": "C#" }, { "code": null, "e": 28034, "s": 28023, "text": "Javascript" }, { "code": "// CPP program to calculate the// sum of f(a[i], aj])#include <bits/stdc++.h>using namespace std; // Function to calculate the sumint sum(int a[], int n){ // map to keep a count of occurrences unordered_map<int, int> cnt; // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum. int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // if the (a[i]-1) is present then // subtract that value as f(a[i], a[i]-1)=0 if (cnt[a[i] - 1]) ans -= cnt[a[i] - 1]; // if the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt[a[i] + 1]) ans += cnt[a[i] + 1]; // keeping a counter for every element cnt[a[i]]++; } return ans;} // Driver codeint main(){ int a[] = { 1, 2, 3, 1, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << sum(a, n); return 0;}", "e": 29203, "s": 28034, "text": null }, { "code": "// Java program to calculate // the sum of f(a[i], aj])import java.util.*;public class GfG { // Function to calculate the sum public static int sum(int a[], int n) { // Map to keep a count of occurrences Map<Integer,Integer> cnt = new HashMap<Integer,Integer>(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // If the (a[i]-1) is present then subtract // that value as f(a[i], a[i]-1) = 0 if (cnt.containsKey(a[i] - 1)) ans -= cnt.get(a[i] - 1); // If the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt.containsKey(a[i] + 1)) ans += cnt.get(a[i] + 1); // keeping a counter for every element if(cnt.containsKey(a[i])) { cnt.put(a[i], cnt.get(a[i]) + 1); } else { cnt.put(a[i], 1); } } return ans; } // Driver code public static void main(String args[]) { int a[] = { 1, 2, 3, 1, 3 }; int n = a.length; System.out.println(sum(a, n)); }} // This code is contributed by Swetank Modi", "e": 30792, "s": 29203, "text": null }, { "code": "# Python3 program to calculate the# sum of f(a[i], aj]) # Function to calculate the sumdef sum(a, n): # map to keep a count of occurrences cnt = dict() # Traverse in the list from start to end # number of times a[i] can be in a pair and # to get the difference we subtract pre_sum. ans = 0 pre_sum = 0 for i in range(n): ans += (i * a[i]) - pre_sum pre_sum += a[i] # if the (a[i]-1) is present then # subtract that value as f(a[i], a[i]-1)=0 if (a[i] - 1) in cnt: ans -= cnt[a[i] - 1] # if the (a[i]+1) is present then add that # value as f(a[i], a[i]-1)=0 here we add # as a[i]-(a[i]-1)<0 which would have been # added as negative sum, so we add to remove # this pair from the sum value if (a[i] + 1) in cnt: ans += cnt[a[i] + 1] # keeping a counter for every element if a[i] not in cnt: cnt[a[i]] = 0 cnt[a[i]] += 1 return ans # Driver Codeif __name__ == '__main__': a = [1, 2, 3, 1, 3] n = len(a) print(sum(a, n)) # This code is contributed by# SHUBHAMSINGH10", "e": 31942, "s": 30792, "text": null }, { "code": "using System;using System.Collections.Generic; // C# program to calculate // the sum of f(a[i], aj])public class GfG{ // Function to calculate the sum public static int sum(int[] a, int n) { // Map to keep a count of occurrences IDictionary<int, int> cnt = new Dictionary<int, int>(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum int ans = 0, pre_sum = 0; for (int i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // If the (a[i]-1) is present then subtract // that value as f(a[i], a[i]-1) = 0 if (cnt.ContainsKey(a[i] - 1)) { ans -= cnt[a[i] - 1]; } // If the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if (cnt.ContainsKey(a[i] + 1)) { ans += cnt[a[i] + 1]; } // keeping a counter for every element if (cnt.ContainsKey(a[i])) { cnt[a[i]] = cnt[a[i]] + 1; } else { cnt[a[i]] = 1; } } return ans; } // Driver code public static void Main(string[] args) { int[] a = new int[] {1, 2, 3, 1, 3}; int n = a.Length; Console.WriteLine(sum(a, n)); }} // This code is contributed by Shrikant13", "e": 33614, "s": 31942, "text": null }, { "code": "<script> // Javascript program to calculate the// sum of f(a[i], aj]) // Function to calculate the sumfunction sum(a, n){ // map to keep a count of occurrences var cnt = new Map(); // Traverse in the list from start to end // number of times a[i] can be in a pair and // to get the difference we subtract pre_sum. var ans = 0, pre_sum = 0; for (var i = 0; i < n; i++) { ans += (i * a[i]) - pre_sum; pre_sum += a[i]; // if the (a[i]-1) is present then // subtract that value as f(a[i], a[i]-1)=0 if (cnt.has(a[i] - 1)) ans -= cnt.get(a[i] - 1); // if the (a[i]+1) is present then // add that value as f(a[i], a[i]-1)=0 // here we add as a[i]-(a[i]-1)<0 which would // have been added as negative sum, so we add // to remove this pair from the sum value if(cnt.has(a[i] + 1)) ans += cnt.get(a[i] + 1); // keeping a counter for every element if(cnt.has(a[i])) cnt.set(a[i], cnt.get(a[i])+1) else cnt.set(a[i], 1) } return ans;} // Driver codevar a = [1, 2, 3, 1, 3];var n = a.length;document.write( sum(a, n)); </script>", "e": 34807, "s": 33614, "text": null }, { "code": null, "e": 34817, "s": 34807, "text": "Output: " }, { "code": null, "e": 34819, "s": 34817, "text": "4" }, { "code": null, "e": 34833, "s": 34821, "text": "shrikanth13" }, { "code": null, "e": 34848, "s": 34833, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 34857, "s": 34848, "text": "famously" }, { "code": null, "e": 34875, "s": 34857, "text": "cpp-unordered_map" }, { "code": null, "e": 34882, "s": 34875, "text": "Arrays" }, { "code": null, "e": 34906, "s": 34882, "text": "Competitive Programming" }, { "code": null, "e": 34911, "s": 34906, "text": "Hash" }, { "code": null, "e": 34924, "s": 34911, "text": "Mathematical" }, { "code": null, "e": 34931, "s": 34924, "text": "Arrays" }, { "code": null, "e": 34936, "s": 34931, "text": "Hash" }, { "code": null, "e": 34949, "s": 34936, "text": "Mathematical" }, { "code": null, "e": 35047, "s": 34949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35091, "s": 35047, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35139, "s": 35091, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35162, "s": 35139, "text": "Introduction to Arrays" }, { "code": null, "e": 35194, "s": 35162, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35208, "s": 35194, "text": "Linear Search" }, { "code": null, "e": 35251, "s": 35208, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 35294, "s": 35251, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 35335, "s": 35294, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35413, "s": 35335, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Open Applications using Python - GeeksforGeeks
07 Apr, 2022 In this article, we are going to create a menu of system applications using Python3. We are going to include the below applications in the menu: GOOGLE CHROME MS EDGE MS EXCEL MS POWERPOINT MS WORD VLC PLAYER NOTEPAD ILLUSTRATOR PHOTOSHOP TELEGRAM You can chat with it or type number of applications to be opened or simply, you can also type software name or its short form like 'Photoshop' -> 'PS' pyttsx3: It is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3. An application invokes the pyttsx3.init() factory function to get a reference to a pyttsx3. Engine instance. It is a very easy to use tool which converts the entered text into speech. It can be installed using the below command: pip install pyttsx3 Below code snippet showcases the use of the above module: Python3 # create objectengine = pyttsx3.init() # assign voicevoices = engine.getProperty('voices') #changing index changes voices but only 0 and 1 are working hereengine.setProperty('voice', voices[1].id) # run toolengine.runAndWait() print("") os: The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. Below is the program to create an Application Menu using Python Python3 # import required moduleimport pyttsx3import os # driver code # create object and assign voiceengine = pyttsx3.init()voices = engine.getProperty('voices') # changing index changes voices but only# 0 and 1 are working hereengine.setProperty('voice', voices[1].id)engine.runAndWait()print("")print("") # introductionprint(" =============================================== Hello World!! ================================================")engine.say('Hello World!!') print("")print(" My name is Divy Shah,I make this tool With this help of tool you can open below things.......") print("\n\t 1.MICROSOFT WORD \t 2.MICROSOFT POWERPOINT \n\t 3.MICROSOFT EXCEL \t 4.GOOGLE CHROME \n\t 5.VLC PLAYER \t 6.ADOBE ILLUSTRATOR \n\t 7.ADOBE PHOTOSHOP \t 8.MICROSOFT EDGE \n\t 9.NOTEPAD \t 10.TELEGRAM \n\n\t\t 0. FOR EXIT") print("\n (YOU CAN USE NUMBER OR YOU CAN DO CHAT LIKE 'OPEN NOTEBOOK' etc....)") print("\n ============================================ Welcome To My Tools ============================================")pyttsx3.speak("Welcome to my tools")print("")print("") pyttsx3.speak("chat with me with your requirements") while True: # take input print(" CHAT WITH ME WITH YOUR REQUIREMENTS : ", end='') p = input() p = p.upper() print(p) if ("DONT" in p) or ("DON'T" in p) or ("NOT" in p): pyttsx3.speak("Type Again") print(".") print(".") continue # assignments for different applications in the menu elif ("GOOGLE" in p) or ("SEARCH" in p) or ("WEB BROWSER" in p) or ("CHROME" in p) or ("BROWSER" in p) or ("4" in p): pyttsx3.speak("Opening") pyttsx3.speak("GOOGLE CHROME") print(".") print(".") os.system("chrome") elif ("IE" in p) or ("MSEDGE" in p) or ("EDGE" in p) or ("8" in p): pyttsx3.speak("Opening") pyttsx3.speak("MICROSOFT EDGE") print(".") print(".") os.system("msedge") elif ("NOTE" in p) or ("NOTES" in p) or ("NOTEPAD" in p) or ("EDITOR" in p) or ("9" in p): pyttsx3.speak("Opening") pyttsx3.speak("NOTEPAD") print(".") print(".") os.system("Notepad") elif ("VLCPLAYER" in p) or ("PLAYER" in p) or ("VIDEO PLAYER" in p) or ("5" in p): pyttsx3.speak("Opening") pyttsx3.speak("VLC PLAYER") print(".") print(".") os.system("VLC") elif ("ILLUSTRATOR" in p) or ("AI" in p) or ("6" in p): pyttsx3.speak("Opening") pyttsx3.speak("ADOBE ILLUSTRATOR") print(".") print(".") os.system("illustrator") elif ("PHOTOSHOP" in p) or ("PS" in p) or ("PHOTOSHOP CC" in p) or ("7" in p): pyttsx3.speak("Opening") pyttsx3.speak("ADOBE PHOTOSHOP") print(".") print(".") os.system("photoshop") elif ("TELEGRAM" in p) or ("TG" in p) or ("10" in p): pyttsx3.speak("Opening") pyttsx3.speak("TELEGRAM") print(".") print(".") os.system("telegram") elif ("EXCEL" in p) or ("MSEXCEL" in p) or ("SHEET" in p) or ("WINEXCEL" in p) or ("3" in p): pyttsx3.speak("Opening") pyttsx3.speak("MICROSOFT EXCEL") print(".") print(".") os.system("excel") elif ("SLIDE" in p) or ("MSPOWERPOINT" in p) or ("PPT" in p) or ("POWERPNT" in p) or ("2" in p): pyttsx3.speak("Opening") pyttsx3.speak("MICROSOFT POWERPOINT") print(".") print(".") os.system("powerpnt") elif ("WORD" in p) or ("MSWORD" in p) or ("1" in p): pyttsx3.speak("Opening") pyttsx3.speak("MICROSOFT WORD") print(".") print(".") os.system("winword") # close the program elif ("EXIT" in p) or ("QUIT" in p) or ("CLOSE" in p) or ("0" in p): pyttsx3.speak("Exiting") break # for invalid input else: pyttsx3.speak(p) print("Is Invalid,Please Try Again") pyttsx3.speak("is Invalid,Please try again") print(".") print(".") Output: rajeev0719singh sumitgumber28 sweetyty sagartomar9927 python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n07 Apr, 2022" }, { "code": null, "e": 25707, "s": 25561, "text": "In this article, we are going to create a menu of system applications using Python3. We are going to include the below applications in the menu: " }, { "code": null, "e": 25721, "s": 25707, "text": "GOOGLE CHROME" }, { "code": null, "e": 25729, "s": 25721, "text": "MS EDGE" }, { "code": null, "e": 25738, "s": 25729, "text": "MS EXCEL" }, { "code": null, "e": 25752, "s": 25738, "text": "MS POWERPOINT" }, { "code": null, "e": 25760, "s": 25752, "text": "MS WORD" }, { "code": null, "e": 25771, "s": 25760, "text": "VLC PLAYER" }, { "code": null, "e": 25779, "s": 25771, "text": "NOTEPAD" }, { "code": null, "e": 25791, "s": 25779, "text": "ILLUSTRATOR" }, { "code": null, "e": 25801, "s": 25791, "text": "PHOTOSHOP" }, { "code": null, "e": 25810, "s": 25801, "text": "TELEGRAM" }, { "code": null, "e": 25941, "s": 25810, "text": "You can chat with it or type number of applications to be opened or simply, you can also type software name or its short form like" }, { "code": null, "e": 25961, "s": 25941, "text": "'Photoshop' -> 'PS'" }, { "code": null, "e": 26343, "s": 25961, "text": "pyttsx3: It is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3. An application invokes the pyttsx3.init() factory function to get a reference to a pyttsx3. Engine instance. It is a very easy to use tool which converts the entered text into speech. It can be installed using the below command:" }, { "code": null, "e": 26363, "s": 26343, "text": "pip install pyttsx3" }, { "code": null, "e": 26421, "s": 26363, "text": "Below code snippet showcases the use of the above module:" }, { "code": null, "e": 26429, "s": 26421, "text": "Python3" }, { "code": "# create objectengine = pyttsx3.init() # assign voicevoices = engine.getProperty('voices') #changing index changes voices but only 0 and 1 are working hereengine.setProperty('voice', voices[1].id) # run toolengine.runAndWait() print(\"\")", "e": 26666, "s": 26429, "text": null }, { "code": null, "e": 26897, "s": 26669, "text": "os: The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 26963, "s": 26899, "text": "Below is the program to create an Application Menu using Python" }, { "code": null, "e": 26973, "s": 26965, "text": "Python3" }, { "code": "# import required moduleimport pyttsx3import os # driver code # create object and assign voiceengine = pyttsx3.init()voices = engine.getProperty('voices') # changing index changes voices but only# 0 and 1 are working hereengine.setProperty('voice', voices[1].id)engine.runAndWait()print(\"\")print(\"\") # introductionprint(\" =============================================== Hello World!! ================================================\")engine.say('Hello World!!') print(\"\")print(\" My name is Divy Shah,I make this tool With this help of tool you can open below things.......\") print(\"\\n\\t 1.MICROSOFT WORD \\t 2.MICROSOFT POWERPOINT \\n\\t 3.MICROSOFT EXCEL \\t 4.GOOGLE CHROME \\n\\t 5.VLC PLAYER \\t 6.ADOBE ILLUSTRATOR \\n\\t 7.ADOBE PHOTOSHOP \\t 8.MICROSOFT EDGE \\n\\t 9.NOTEPAD \\t 10.TELEGRAM \\n\\n\\t\\t 0. FOR EXIT\") print(\"\\n (YOU CAN USE NUMBER OR YOU CAN DO CHAT LIKE 'OPEN NOTEBOOK' etc....)\") print(\"\\n ============================================ Welcome To My Tools ============================================\")pyttsx3.speak(\"Welcome to my tools\")print(\"\")print(\"\") pyttsx3.speak(\"chat with me with your requirements\") while True: # take input print(\" CHAT WITH ME WITH YOUR REQUIREMENTS : \", end='') p = input() p = p.upper() print(p) if (\"DONT\" in p) or (\"DON'T\" in p) or (\"NOT\" in p): pyttsx3.speak(\"Type Again\") print(\".\") print(\".\") continue # assignments for different applications in the menu elif (\"GOOGLE\" in p) or (\"SEARCH\" in p) or (\"WEB BROWSER\" in p) or (\"CHROME\" in p) or (\"BROWSER\" in p) or (\"4\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"GOOGLE CHROME\") print(\".\") print(\".\") os.system(\"chrome\") elif (\"IE\" in p) or (\"MSEDGE\" in p) or (\"EDGE\" in p) or (\"8\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"MICROSOFT EDGE\") print(\".\") print(\".\") os.system(\"msedge\") elif (\"NOTE\" in p) or (\"NOTES\" in p) or (\"NOTEPAD\" in p) or (\"EDITOR\" in p) or (\"9\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"NOTEPAD\") print(\".\") print(\".\") os.system(\"Notepad\") elif (\"VLCPLAYER\" in p) or (\"PLAYER\" in p) or (\"VIDEO PLAYER\" in p) or (\"5\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"VLC PLAYER\") print(\".\") print(\".\") os.system(\"VLC\") elif (\"ILLUSTRATOR\" in p) or (\"AI\" in p) or (\"6\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"ADOBE ILLUSTRATOR\") print(\".\") print(\".\") os.system(\"illustrator\") elif (\"PHOTOSHOP\" in p) or (\"PS\" in p) or (\"PHOTOSHOP CC\" in p) or (\"7\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"ADOBE PHOTOSHOP\") print(\".\") print(\".\") os.system(\"photoshop\") elif (\"TELEGRAM\" in p) or (\"TG\" in p) or (\"10\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"TELEGRAM\") print(\".\") print(\".\") os.system(\"telegram\") elif (\"EXCEL\" in p) or (\"MSEXCEL\" in p) or (\"SHEET\" in p) or (\"WINEXCEL\" in p) or (\"3\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"MICROSOFT EXCEL\") print(\".\") print(\".\") os.system(\"excel\") elif (\"SLIDE\" in p) or (\"MSPOWERPOINT\" in p) or (\"PPT\" in p) or (\"POWERPNT\" in p) or (\"2\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"MICROSOFT POWERPOINT\") print(\".\") print(\".\") os.system(\"powerpnt\") elif (\"WORD\" in p) or (\"MSWORD\" in p) or (\"1\" in p): pyttsx3.speak(\"Opening\") pyttsx3.speak(\"MICROSOFT WORD\") print(\".\") print(\".\") os.system(\"winword\") # close the program elif (\"EXIT\" in p) or (\"QUIT\" in p) or (\"CLOSE\" in p) or (\"0\" in p): pyttsx3.speak(\"Exiting\") break # for invalid input else: pyttsx3.speak(p) print(\"Is Invalid,Please Try Again\") pyttsx3.speak(\"is Invalid,Please try again\") print(\".\") print(\".\")", "e": 30959, "s": 26973, "text": null }, { "code": null, "e": 30967, "s": 30959, "text": "Output:" }, { "code": null, "e": 30983, "s": 30967, "text": "rajeev0719singh" }, { "code": null, "e": 30997, "s": 30983, "text": "sumitgumber28" }, { "code": null, "e": 31006, "s": 30997, "text": "sweetyty" }, { "code": null, "e": 31021, "s": 31006, "text": "sagartomar9927" }, { "code": null, "e": 31036, "s": 31021, "text": "python-utility" }, { "code": null, "e": 31060, "s": 31036, "text": "Technical Scripter 2020" }, { "code": null, "e": 31067, "s": 31060, "text": "Python" }, { "code": null, "e": 31086, "s": 31067, "text": "Technical Scripter" }, { "code": null, "e": 31184, "s": 31086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31216, "s": 31184, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31258, "s": 31216, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31300, "s": 31258, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31327, "s": 31300, "text": "Python Classes and Objects" }, { "code": null, "e": 31383, "s": 31327, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31405, "s": 31383, "text": "Defaultdict in Python" }, { "code": null, "e": 31444, "s": 31405, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31475, "s": 31444, "text": "Python | os.path.join() method" }, { "code": null, "e": 31504, "s": 31475, "text": "Create a directory in Python" } ]
How to format a float in JavaScript ? - GeeksforGeeks
25 Sep, 2019 Format a float number means to round off a number up to the given decimal place, ceiling, flooring, etc. There are many operations used to format the float number which are given below: Math.ceil() Method float.toFixed() Method Math.round() Method Math.floor() Method float.toExponential() Method number.toPrecision() Method Math.ceil(), float.toFixed() and Math.round() Method: All the methods are similar and giving the same output. The implementation of Math.ceil() and Math.round() are totally same but the Math.round() function is used to round a number to its nearest integer. Example: <!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Format a float value 6.56759 in JavaScript </h3> <p id="d1"></p> <p id="d2"></p> <p id="d3"></p> <p id="d4"></p> <p id="d5"></p> <script> var n = 6.56759; // Rounds to next highest integer document.getElementById("d1").innerHTML = "Math.ceil(n) = " + Math.ceil(n) + "<br />Math.round(n) = " + Math.round(n) + "<br />n.toFixed() = " + n.toFixed(); // Rounds to the highest decimal upto one point document.getElementById("d2").innerHTML = "Math.ceil(n*10)/10 = " + Math.ceil(n*10)/10 + "<br />Math.round(n*10)/10 = " + Math.round(n*10)/10 + "<br />n.toFixed(1) = " + n.toFixed(1); // Rounds to the highest decimal upto two points document.getElementById("d3").innerHTML = "Math.ceil(n*100)/100 = " + Math.ceil(n*100)/100 + "<br />Math.round(n*100)/100 = " + Math.round(n*100)/100 + "<br />n.toFixed(2) = " + n.toFixed(2); // Rounds to the highest decimal upto three points document.getElementById("d4").innerHTML = "Math.ceil(n*1000)/1000 = " + Math.ceil(n*1000)/1000 + "<br />Math.round(n*1000)/1000 = " + Math.round(n*1000)/1000 + "<br />n.toFixed(3) = " + n.toFixed(3); // Rounds to the specified length, as the // manipulation stops to the original float document.getElementById("d5").innerHTML = "Math.ceil(n*1000000000)/1000000000 = " + Math.ceil(n*1000000000)/1000000000 + "<br />Math.round(n*1000000000)/1000000000 = " + Math.round(n*1000000000)/1000000000 + "<br />n.toFixed(9) = " + n.toFixed(9); </script></body> </html> Output: Math.floor() Method: The Math.floor() function is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value. Example: <!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Format a float value 6.56759 in JavaScript </h3> <p id="d1"></p> <p id="d2"></p> <p id="d3"></p> <script> var n = 6.56759; // Rounds off to the floor value document.getElementById("d1").innerHTML = "Math.floor(n) = " + Math.floor(n); // Rounds off upto one decimal place document.getElementById("d2").innerHTML = "Math.floor(n*10)/10 = " + Math.floor(n*10)/10; // Rounds off upto two decimal place document.getElementById("d3").innerHTML = "Math.floor(n*100)/100 = " + Math.floor(n*100)/100; </script></body> </html> Output: float.toExponential() Method: The toExponential() method is used to convert a number to its exponential form. It returns a string representing the Number object in exponential notation. Example: <!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Format a float number in JavaScript </h3> <p id="GFG"></p> <script> var n1 = 5.569999999999999999999; var n2 = 5.569999999999; // The complexity of the float results // in its conversion document.getElementById("GFG").innerHTML = "n1.toExponential() = " + n1.toExponential() + "<br />n2.toExponential() = " + n2.toExponential(); </script></body> </html> Output: number.toPrecision() Method: The toPrecision() method is used to format a number to a specific precision or length. If the formatted number requires more number of digits than the original number then decimals and nulls are also added to create the specified length. Example: <!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Format a float number in JavaScript </h3> <p id="d1"></p> <p id="d2"></p> <p id="d3"></p> <script> var n1 = 13.3714; var n2 = 0.0016588874; var n3 = 13.3714; document.getElementById("d1").innerHTML = "n1.toPrecision() = " + n1.toPrecision() + "<br \>n1.toPrecision(2) = " + n1.toPrecision(2) + "<br \>n1.toPrecision(3) = " + n1.toPrecision(3) + "<br \>n1.toPrecision(10) = " + n1.toPrecision(10); document.getElementById("d2").innerHTML = "n2.toPrecision() = " + n2.toPrecision() + "<br \>n2.toPrecision(2) = " + n2.toPrecision(2) + "<br \>n2.toPrecision(3) = " + n2.toPrecision(3) + "<br \>n2.toPrecision(10) = " + n2.toPrecision(10); document.getElementById("d3").innerHTML = "n3.toPrecision() = " + n3.toPrecision() + "<br \>n3.toPrecision(2) = " + n3.toPrecision(2) + "<br \>n3.toPrecision(3) = " + n3.toPrecision(3) + "<br \>n3.toPrecision(10) = " + n3.toPrecision(10); </script></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26201, "s": 26173, "text": "\n25 Sep, 2019" }, { "code": null, "e": 26387, "s": 26201, "text": "Format a float number means to round off a number up to the given decimal place, ceiling, flooring, etc. There are many operations used to format the float number which are given below:" }, { "code": null, "e": 26406, "s": 26387, "text": "Math.ceil() Method" }, { "code": null, "e": 26429, "s": 26406, "text": "float.toFixed() Method" }, { "code": null, "e": 26449, "s": 26429, "text": "Math.round() Method" }, { "code": null, "e": 26469, "s": 26449, "text": "Math.floor() Method" }, { "code": null, "e": 26498, "s": 26469, "text": "float.toExponential() Method" }, { "code": null, "e": 26526, "s": 26498, "text": "number.toPrecision() Method" }, { "code": null, "e": 26784, "s": 26526, "text": "Math.ceil(), float.toFixed() and Math.round() Method: All the methods are similar and giving the same output. The implementation of Math.ceil() and Math.round() are totally same but the Math.round() function is used to round a number to its nearest integer." }, { "code": null, "e": 26793, "s": 26784, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Format a float value 6.56759 in JavaScript </h3> <p id=\"d1\"></p> <p id=\"d2\"></p> <p id=\"d3\"></p> <p id=\"d4\"></p> <p id=\"d5\"></p> <script> var n = 6.56759; // Rounds to next highest integer document.getElementById(\"d1\").innerHTML = \"Math.ceil(n) = \" + Math.ceil(n) + \"<br />Math.round(n) = \" + Math.round(n) + \"<br />n.toFixed() = \" + n.toFixed(); // Rounds to the highest decimal upto one point document.getElementById(\"d2\").innerHTML = \"Math.ceil(n*10)/10 = \" + Math.ceil(n*10)/10 + \"<br />Math.round(n*10)/10 = \" + Math.round(n*10)/10 + \"<br />n.toFixed(1) = \" + n.toFixed(1); // Rounds to the highest decimal upto two points document.getElementById(\"d3\").innerHTML = \"Math.ceil(n*100)/100 = \" + Math.ceil(n*100)/100 + \"<br />Math.round(n*100)/100 = \" + Math.round(n*100)/100 + \"<br />n.toFixed(2) = \" + n.toFixed(2); // Rounds to the highest decimal upto three points document.getElementById(\"d4\").innerHTML = \"Math.ceil(n*1000)/1000 = \" + Math.ceil(n*1000)/1000 + \"<br />Math.round(n*1000)/1000 = \" + Math.round(n*1000)/1000 + \"<br />n.toFixed(3) = \" + n.toFixed(3); // Rounds to the specified length, as the // manipulation stops to the original float document.getElementById(\"d5\").innerHTML = \"Math.ceil(n*1000000000)/1000000000 = \" + Math.ceil(n*1000000000)/1000000000 + \"<br />Math.round(n*1000000000)/1000000000 = \" + Math.round(n*1000000000)/1000000000 + \"<br />n.toFixed(9) = \" + n.toFixed(9); </script></body> </html>", "e": 28945, "s": 26793, "text": null }, { "code": null, "e": 28953, "s": 28945, "text": "Output:" }, { "code": null, "e": 29142, "s": 28953, "text": "Math.floor() Method: The Math.floor() function is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value." }, { "code": null, "e": 29151, "s": 29142, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Format a float value 6.56759 in JavaScript </h3> <p id=\"d1\"></p> <p id=\"d2\"></p> <p id=\"d3\"></p> <script> var n = 6.56759; // Rounds off to the floor value document.getElementById(\"d1\").innerHTML = \"Math.floor(n) = \" + Math.floor(n); // Rounds off upto one decimal place document.getElementById(\"d2\").innerHTML = \"Math.floor(n*10)/10 = \" + Math.floor(n*10)/10; // Rounds off upto two decimal place document.getElementById(\"d3\").innerHTML = \"Math.floor(n*100)/100 = \" + Math.floor(n*100)/100; </script></body> </html>", "e": 30070, "s": 29151, "text": null }, { "code": null, "e": 30078, "s": 30070, "text": "Output:" }, { "code": null, "e": 30264, "s": 30078, "text": "float.toExponential() Method: The toExponential() method is used to convert a number to its exponential form. It returns a string representing the Number object in exponential notation." }, { "code": null, "e": 30273, "s": 30264, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Format a float number in JavaScript </h3> <p id=\"GFG\"></p> <script> var n1 = 5.569999999999999999999; var n2 = 5.569999999999; // The complexity of the float results // in its conversion document.getElementById(\"GFG\").innerHTML = \"n1.toExponential() = \" + n1.toExponential() + \"<br />n2.toExponential() = \" + n2.toExponential(); </script></body> </html>", "e": 30964, "s": 30273, "text": null }, { "code": null, "e": 30972, "s": 30964, "text": "Output:" }, { "code": null, "e": 31239, "s": 30972, "text": "number.toPrecision() Method: The toPrecision() method is used to format a number to a specific precision or length. If the formatted number requires more number of digits than the original number then decimals and nulls are also added to create the specified length." }, { "code": null, "e": 31248, "s": 31239, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to format a float value in javascript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Format a float number in JavaScript </h3> <p id=\"d1\"></p> <p id=\"d2\"></p> <p id=\"d3\"></p> <script> var n1 = 13.3714; var n2 = 0.0016588874; var n3 = 13.3714; document.getElementById(\"d1\").innerHTML = \"n1.toPrecision() = \" + n1.toPrecision() + \"<br \\>n1.toPrecision(2) = \" + n1.toPrecision(2) + \"<br \\>n1.toPrecision(3) = \" + n1.toPrecision(3) + \"<br \\>n1.toPrecision(10) = \" + n1.toPrecision(10); document.getElementById(\"d2\").innerHTML = \"n2.toPrecision() = \" + n2.toPrecision() + \"<br \\>n2.toPrecision(2) = \" + n2.toPrecision(2) + \"<br \\>n2.toPrecision(3) = \" + n2.toPrecision(3) + \"<br \\>n2.toPrecision(10) = \" + n2.toPrecision(10); document.getElementById(\"d3\").innerHTML = \"n3.toPrecision() = \" + n3.toPrecision() + \"<br \\>n3.toPrecision(2) = \" + n3.toPrecision(2) + \"<br \\>n3.toPrecision(3) = \" + n3.toPrecision(3) + \"<br \\>n3.toPrecision(10) = \" + n3.toPrecision(10); </script></body> </html>", "e": 32641, "s": 31248, "text": null }, { "code": null, "e": 32649, "s": 32641, "text": "Output:" }, { "code": null, "e": 32665, "s": 32649, "text": "JavaScript-Misc" }, { "code": null, "e": 32672, "s": 32665, "text": "Picked" }, { "code": null, "e": 32683, "s": 32672, "text": "JavaScript" }, { "code": null, "e": 32700, "s": 32683, "text": "Web Technologies" }, { "code": null, "e": 32727, "s": 32700, "text": "Web technologies Questions" }, { "code": null, "e": 32825, "s": 32727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32865, "s": 32825, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32910, "s": 32865, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32971, "s": 32910, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33043, "s": 32971, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 33095, "s": 33043, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 33135, "s": 33095, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33168, "s": 33135, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33213, "s": 33168, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33256, "s": 33213, "text": "How to fetch data from an API in ReactJS ?" } ]
Horizontal Boxplots with Seaborn in Python - GeeksforGeeks
12 Nov, 2020 Prerequisite: seaborn The Boxplots are used to visualize the distribution of data which is useful when a comparison of data is required. Sometimes, Boxplot is also known as a box-and-whisker plot. The box shows the quartiles of dataset and whiskers extend to show rest of the distribution. In this article, we are going to implement the Horizontal boxplot with seaborn using python. Seaborn uses the boxplot() method to draw a boxplot. We can turn the boxplot into a horizontal boxplot by two methods first, we need to switch x and y attributes and pass it to the boxplot( ) method, and the other is to use the orient=”h” option and pass it to the boxplot() method. Method 1: Switching x and y attribute Python3 # import library & datasetimport seaborn as sns df = sns.load_dataset('iris') # Just switch x and ysns.boxplot(y=df["species"], x=df["sepal_length"]) Output: Horizontal Boxplot Method 2: Using orient = h Python3 # import library & datasetimport seaborn as sns tips = sns.load_dataset("tips")ax = sns.boxplot(data=tips, orient="h", palette="Set2") Output : Horizontal Boxplot Python-Seaborn 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 Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 28005, "s": 27977, "text": "\n12 Nov, 2020" }, { "code": null, "e": 28027, "s": 28005, "text": "Prerequisite: seaborn" }, { "code": null, "e": 28388, "s": 28027, "text": "The Boxplots are used to visualize the distribution of data which is useful when a comparison of data is required. Sometimes, Boxplot is also known as a box-and-whisker plot. The box shows the quartiles of dataset and whiskers extend to show rest of the distribution. In this article, we are going to implement the Horizontal boxplot with seaborn using python." }, { "code": null, "e": 28671, "s": 28388, "text": "Seaborn uses the boxplot() method to draw a boxplot. We can turn the boxplot into a horizontal boxplot by two methods first, we need to switch x and y attributes and pass it to the boxplot( ) method, and the other is to use the orient=”h” option and pass it to the boxplot() method." }, { "code": null, "e": 28709, "s": 28671, "text": "Method 1: Switching x and y attribute" }, { "code": null, "e": 28717, "s": 28709, "text": "Python3" }, { "code": "# import library & datasetimport seaborn as sns df = sns.load_dataset('iris') # Just switch x and ysns.boxplot(y=df[\"species\"], x=df[\"sepal_length\"])", "e": 28871, "s": 28717, "text": null }, { "code": null, "e": 28879, "s": 28871, "text": "Output:" }, { "code": null, "e": 28898, "s": 28879, "text": "Horizontal Boxplot" }, { "code": null, "e": 28925, "s": 28898, "text": "Method 2: Using orient = h" }, { "code": null, "e": 28933, "s": 28925, "text": "Python3" }, { "code": "# import library & datasetimport seaborn as sns tips = sns.load_dataset(\"tips\")ax = sns.boxplot(data=tips, orient=\"h\", palette=\"Set2\")", "e": 29071, "s": 28933, "text": null }, { "code": null, "e": 29080, "s": 29071, "text": "Output :" }, { "code": null, "e": 29099, "s": 29080, "text": "Horizontal Boxplot" }, { "code": null, "e": 29114, "s": 29099, "text": "Python-Seaborn" }, { "code": null, "e": 29121, "s": 29114, "text": "Python" }, { "code": null, "e": 29219, "s": 29121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29247, "s": 29219, "text": "Read JSON file using Python" }, { "code": null, "e": 29297, "s": 29247, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29319, "s": 29297, "text": "Python map() function" }, { "code": null, "e": 29363, "s": 29319, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 29381, "s": 29363, "text": "Python Dictionary" }, { "code": null, "e": 29404, "s": 29381, "text": "Taking input in Python" }, { "code": null, "e": 29439, "s": 29404, "text": "Read a file line by line in Python" }, { "code": null, "e": 29471, "s": 29439, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29493, "s": 29471, "text": "Enumerate() in Python" } ]
C++ Array Library - empty() Function
The C++ function std::array::empty() tests whether size of array is zero or not. Following is the declaration for std::array::empty() function form std::array header. constexpr bool empty() noexcept; None Returns true if array size is 0 otherwise false. This member function never throws exception. Constant i.e. O(1) In below example size of arr1 is 0 that is why it will be treated as empty array and member function will return true value for arr1. #include <iostream> #include <array> using namespace std; int main(void) { /* array size is zero, it will be treated as empty array */ array<int, 0> arr1; array<int, 10> arr2; if (arr1.empty()) cout << "arr1 is empty" << endl; else cout << "arr1 is not empty" << endl; if (arr2.empty()) cout << "arr2 is empty" << endl; else cout << "arr2 is not empty" << endl; } Let us compile and run the above program, this will produce the following result − arr1 is empty arr2 is not empty Print Add Notes Bookmark this page
[ { "code": null, "e": 2684, "s": 2603, "text": "The C++ function std::array::empty() tests whether size of array is zero or not." }, { "code": null, "e": 2770, "s": 2684, "text": "Following is the declaration for std::array::empty() function form std::array header." }, { "code": null, "e": 2803, "s": 2770, "text": "constexpr bool empty() noexcept;" }, { "code": null, "e": 2808, "s": 2803, "text": "None" }, { "code": null, "e": 2857, "s": 2808, "text": "Returns true if array size is 0 otherwise false." }, { "code": null, "e": 2902, "s": 2857, "text": "This member function never throws exception." }, { "code": null, "e": 2921, "s": 2902, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3055, "s": 2921, "text": "In below example size of arr1 is 0 that is why it will be treated as empty\narray and member function will return true value for arr1." }, { "code": null, "e": 3475, "s": 3055, "text": "#include <iostream>\n#include <array>\n\nusing namespace std;\n\nint main(void) {\n \n /* array size is zero, it will be treated as empty array */\n array<int, 0> arr1; \n array<int, 10> arr2;\n\n if (arr1.empty())\n cout << \"arr1 is empty\" << endl;\n else\n cout << \"arr1 is not empty\" << endl;\n\n if (arr2.empty())\n cout << \"arr2 is empty\" << endl;\n else\n cout << \"arr2 is not empty\" << endl;\n}" }, { "code": null, "e": 3558, "s": 3475, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3591, "s": 3558, "text": "arr1 is empty\narr2 is not empty\n" }, { "code": null, "e": 3598, "s": 3591, "text": " Print" }, { "code": null, "e": 3609, "s": 3598, "text": " Add Notes" } ]
Implementing Counting Sort using map in C++ - GeeksforGeeks
09 Sep, 2019 Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it’s space complexity, for a small collection of values, it will also require a huge amount of unused space. So, we need two things to overcome this: A data structure which occupies the space for input elements only and not for all the elements other than inputs.The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use. A data structure which occupies the space for input elements only and not for all the elements other than inputs. The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use. So Map in C++ satisfies both the condition. Thus we can achieve this through a map. Examples: Input: arr[] = {1, 4, 3, 5, 1}Output: 1 1 3 4 5 Input: arr[] = {1, -1, -3, 8, -3}Output: -3 -3 -1 1 8 Below is the implementation of Counting Sort using map in C++: // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sort the array using counting sortvoid countingSort(vector<int> arr, int n){ // Map to store the frequency // of the array elements map<int, int> freqMap; for (auto i = arr.begin(); i != arr.end(); i++) { freqMap[*i]++; } int i = 0; // For every element of the map for (auto it : freqMap) { // Value of the element int val = it.first; // Its frequency int freq = it.second; for (int j = 0; j < freq; j++) arr[i++] = val; } // Print the sorted array for (auto i = arr.begin(); i != arr.end(); i++) { cout << *i << " "; }} // Driver codeint main(){ vector<int> arr = { 1, 4, 3, 5, 1 }; int n = arr.size(); countingSort(arr, n); return 0;} 1 1 3 4 5 counting-sort cpp-map Algorithms Sorting Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing Difference between Informed and Uninformed Search in AI K means Clustering - Introduction SCAN (Elevator) Disk Scheduling Algorithms
[ { "code": null, "e": 24299, "s": 24271, "text": "\n09 Sep, 2019" }, { "code": null, "e": 24546, "s": 24299, "text": "Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it’s space complexity, for a small collection of values, it will also require a huge amount of unused space." }, { "code": null, "e": 24587, "s": 24546, "text": "So, we need two things to overcome this:" }, { "code": null, "e": 24806, "s": 24587, "text": "A data structure which occupies the space for input elements only and not for all the elements other than inputs.The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use." }, { "code": null, "e": 24920, "s": 24806, "text": "A data structure which occupies the space for input elements only and not for all the elements other than inputs." }, { "code": null, "e": 25026, "s": 24920, "text": "The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use." }, { "code": null, "e": 25110, "s": 25026, "text": "So Map in C++ satisfies both the condition. Thus we can achieve this through a map." }, { "code": null, "e": 25120, "s": 25110, "text": "Examples:" }, { "code": null, "e": 25168, "s": 25120, "text": "Input: arr[] = {1, 4, 3, 5, 1}Output: 1 1 3 4 5" }, { "code": null, "e": 25222, "s": 25168, "text": "Input: arr[] = {1, -1, -3, 8, -3}Output: -3 -3 -1 1 8" }, { "code": null, "e": 25285, "s": 25222, "text": "Below is the implementation of Counting Sort using map in C++:" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sort the array using counting sortvoid countingSort(vector<int> arr, int n){ // Map to store the frequency // of the array elements map<int, int> freqMap; for (auto i = arr.begin(); i != arr.end(); i++) { freqMap[*i]++; } int i = 0; // For every element of the map for (auto it : freqMap) { // Value of the element int val = it.first; // Its frequency int freq = it.second; for (int j = 0; j < freq; j++) arr[i++] = val; } // Print the sorted array for (auto i = arr.begin(); i != arr.end(); i++) { cout << *i << \" \"; }} // Driver codeint main(){ vector<int> arr = { 1, 4, 3, 5, 1 }; int n = arr.size(); countingSort(arr, n); return 0;}", "e": 26145, "s": 25285, "text": null }, { "code": null, "e": 26156, "s": 26145, "text": "1 1 3 4 5\n" }, { "code": null, "e": 26170, "s": 26156, "text": "counting-sort" }, { "code": null, "e": 26178, "s": 26170, "text": "cpp-map" }, { "code": null, "e": 26189, "s": 26178, "text": "Algorithms" }, { "code": null, "e": 26197, "s": 26189, "text": "Sorting" }, { "code": null, "e": 26205, "s": 26197, "text": "Sorting" }, { "code": null, "e": 26216, "s": 26205, "text": "Algorithms" }, { "code": null, "e": 26314, "s": 26216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26323, "s": 26314, "text": "Comments" }, { "code": null, "e": 26336, "s": 26323, "text": "Old Comments" }, { "code": null, "e": 26361, "s": 26336, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 26390, "s": 26361, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 26446, "s": 26390, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 26480, "s": 26446, "text": "K means Clustering - Introduction" } ]
Flutter - Named Routes - GeeksforGeeks
30 Jun, 2021 An app has to display multiple screens depending upon the user’s needs. A user needs to back and forth from the multiple screens to the home screen. In, Flutter this is done with the help of Navigator. Note: In Flutter, screens and pages are called routes. In this article, we will explore the process of navigating through two named routes. To do so follow the below steps: Create two routes.Navigate to the second route using Navigator.push().Return to the first route using Navigator.pop() Create two routes. Navigate to the second route using Navigator.push(). Return to the first route using Navigator.pop() Let’s explore them in detail. Here we will create two routes, the first route will have a single button that on tap leads to the second route, and similarly, the second route will have a single button that brings the user back to the first route. To do so follow the below code: Dart class FirstRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('First Route'), ), body: Center( child: RaisedButton( child: Text('Open route'), onPressed: () { // Navigation to second route }, ), ), ); }} class SecondRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Second Route"), ), body: Center( child: RaisedButton( onPressed: () { // Navigation to first route }, child: Text('Go back!'), ), ), ); }} To switch to a new route, use the Navigator.push() method. The push() method adds a Route to the stack of routes managed by the Navigator. In the build() method of the first Route widget, update the onPressed() callback to lead to the second route as below: Dart // onPressed actiononPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => SecondRoute()), );} To implement a return to the original route, update the onPressed() callback in the second Route as below: Dart // onPressed action in second routeonPressed: () { Navigator.pop(context);} Complete Source Code: Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Named Routes', initialRoute: '/', routes: { '/': (context) => First_route(), '/second': (context) => Second_route(), }, ));} class First_route extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GFG First Route'), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( child: Text('Launch screen'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), ), ); }} class Second_route extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GFG Second Route"), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( onPressed: () { Navigator.pop(context); }, child: Text('Go back!'), ), ), ); }} Output: Media error: Format(s) not supported or source(s) not found hanifullah007 android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget
[ { "code": null, "e": 25523, "s": 25495, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25725, "s": 25523, "text": "An app has to display multiple screens depending upon the user’s needs. A user needs to back and forth from the multiple screens to the home screen. In, Flutter this is done with the help of Navigator." }, { "code": null, "e": 25781, "s": 25725, "text": "Note: In Flutter, screens and pages are called routes. " }, { "code": null, "e": 25899, "s": 25781, "text": "In this article, we will explore the process of navigating through two named routes. To do so follow the below steps:" }, { "code": null, "e": 26017, "s": 25899, "text": "Create two routes.Navigate to the second route using Navigator.push().Return to the first route using Navigator.pop()" }, { "code": null, "e": 26036, "s": 26017, "text": "Create two routes." }, { "code": null, "e": 26089, "s": 26036, "text": "Navigate to the second route using Navigator.push()." }, { "code": null, "e": 26137, "s": 26089, "text": "Return to the first route using Navigator.pop()" }, { "code": null, "e": 26167, "s": 26137, "text": "Let’s explore them in detail." }, { "code": null, "e": 26416, "s": 26167, "text": "Here we will create two routes, the first route will have a single button that on tap leads to the second route, and similarly, the second route will have a single button that brings the user back to the first route. To do so follow the below code:" }, { "code": null, "e": 26421, "s": 26416, "text": "Dart" }, { "code": "class FirstRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('First Route'), ), body: Center( child: RaisedButton( child: Text('Open route'), onPressed: () { // Navigation to second route }, ), ), ); }} class SecondRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"Second Route\"), ), body: Center( child: RaisedButton( onPressed: () { // Navigation to first route }, child: Text('Go back!'), ), ), ); }}", "e": 27150, "s": 26421, "text": null }, { "code": null, "e": 27408, "s": 27150, "text": "To switch to a new route, use the Navigator.push() method. The push() method adds a Route to the stack of routes managed by the Navigator. In the build() method of the first Route widget, update the onPressed() callback to lead to the second route as below:" }, { "code": null, "e": 27413, "s": 27408, "text": "Dart" }, { "code": "// onPressed actiononPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => SecondRoute()), );}", "e": 27541, "s": 27413, "text": null }, { "code": null, "e": 27648, "s": 27541, "text": "To implement a return to the original route, update the onPressed() callback in the second Route as below:" }, { "code": null, "e": 27653, "s": 27648, "text": "Dart" }, { "code": "// onPressed action in second routeonPressed: () { Navigator.pop(context);}", "e": 27730, "s": 27653, "text": null }, { "code": null, "e": 27752, "s": 27730, "text": "Complete Source Code:" }, { "code": null, "e": 27757, "s": 27752, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Named Routes', initialRoute: '/', routes: { '/': (context) => First_route(), '/second': (context) => Second_route(), }, ));} class First_route extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GFG First Route'), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( child: Text('Launch screen'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), ), ); }} class Second_route extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GFG Second Route\"), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( onPressed: () { Navigator.pop(context); }, child: Text('Go back!'), ), ), ); }}", "e": 28812, "s": 27757, "text": null }, { "code": null, "e": 28820, "s": 28812, "text": "Output:" }, { "code": null, "e": 28880, "s": 28820, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 28894, "s": 28880, "text": "hanifullah007" }, { "code": null, "e": 28902, "s": 28894, "text": "android" }, { "code": null, "e": 28910, "s": 28902, "text": "Flutter" }, { "code": null, "e": 28915, "s": 28910, "text": "Dart" }, { "code": null, "e": 28923, "s": 28915, "text": "Flutter" }, { "code": null, "e": 29021, "s": 28923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29030, "s": 29021, "text": "Comments" }, { "code": null, "e": 29043, "s": 29030, "text": "Old Comments" }, { "code": null, "e": 29071, "s": 29043, "text": "Listview.builder in Flutter" }, { "code": null, "e": 29103, "s": 29071, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 29125, "s": 29103, "text": "Flutter - Asset Image" }, { "code": null, "e": 29150, "s": 29125, "text": "Splash Screen in Flutter" }, { "code": null, "e": 29189, "s": 29150, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29221, "s": 29189, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 29260, "s": 29221, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29286, "s": 29260, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 29312, "s": 29286, "text": "Flutter - Flexible Widget" } ]
Program for diamond pattern with different layers - GeeksforGeeks
28 May, 2021 Given a number n and using 0-n numbers you have to print such a pattern.Examples: Input : n = 5 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 4 5 4 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Input : n = 3 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 The idea here is to count the space in beginning of string. In this pattern there are ((2 * n) + 1) rows. In rows form 0 to n number of spaces is (2 * (n – i)). In row number from (n + 1) to (2 * n), number of space is ((i – n) * 2).Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ code to print the pattern#include <bits/stdc++.h>using namespace std; // function to generate the pattern.void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) cout << " "; cout << 0 << endl; // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) cout << " "; } else { for (int j = 1; j <= (i % n) * 2; j++) cout << " "; } if (i < n) { for (int j = 0; j <= i % n; j++) cout << j << " "; for (int j = (i % n) - 1; j > 0; j--) cout << j << " "; cout << 0; } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) cout << j << " "; for (int j = (n - (i - n)) - 1; j > 0; j--) cout << j << " "; cout << 0; } else { for (int j = 0; j <= n; j++) cout << j << " "; for (int j = n - 1; j > 0; j--) cout << j << " "; cout << 0; } cout << endl; } // putting the space in last line for (int i = 1; i <= n * 2; i++) cout << " "; cout << 0;} // driver function.int main(){ int n = 4; pattern(n); return 0;} // Java code to print the patternimport java.util.*;import java.lang.*; public class GeeksforGeeks{ // function to generate the pattern. public static void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) System.out.print(" "); System.out.print(0 + "\n"); // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) System.out.print(" "); } else { for (int j = 1; j <= (i % n) * 2; j++) System.out.print(" "); } if (i < n) { for (int j = 0; j <= i % n; j++) System.out.print(j + " "); for (int j = (i % n) - 1; j > 0; j--) System.out.print(j + " "); System.out.print(0); } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) System.out.print(j + " "); for (int j = (n - (i - n)) - 1; j > 0; j--) System.out.print(j + " "); System.out.print(0); } else { for (int j = 0; j <= n; j++) System.out.print(j + " "); for (int j = n - 1; j > 0; j--) System.out.print(j + " "); System.out.print(0); } System.out.print("\n"); } // putting the space in last line for (int i = 1; i <= n * 2; i++) System.out.print(" "); System.out.print(0); } // driver code public static void main(String argc[]){ int n = 4; pattern(n); }} /*This code is contributed by Sagar Shukla.*/ # Python3 code to print the pattern # function to generate the pattern.def pattern(n): # putting the space in line 1 for i in range(1, n * 2 + 1): print(end = " ") print("0") # generating the middle pattern. for i in range(1, n * 2): # printing the increasing pattern if (i < n): for j in range(1, (n - i) * 2 + 1): print(end = " ") else: for j in range(1, (i % n) * 2 + 1): print(end = " ") if (i < n): for j in range(i % n + 1): print(j, end = " ") for j in range(i % n - 1, -1, -1): print(j, end = " ") # printing the decreasing pattern elif (i > n): for j in range(n - (i - n) + 1): print(j, end = " ") for j in range((n - (i - n)) - 1, -1, -1): print(j, end = " ") else: for j in range(n + 1): print(j, end = " ") for j in range(n - 1, -1, -1): print(j, end = " ") print() # putting the space in last line for i in range(1, n * 2 + 1): print(end = " ") print("0", end = "") # Driver Coden = 4;pattern(n); # This code is contributed by# mohit kumar 29 // C# code to print the patternusing System; public class GeeksforGeeks{ // function to generate the pattern. public static void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) Console.Write(" "); Console.Write(0 + "\n"); // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) Console.Write(" "); } else { for (int j = 1; j <= (i % n) * 2; j++) Console.Write(" "); } if (i < n) { for (int j = 0; j <= i % n; j++) Console.Write(j + " "); for (int j = (i % n) - 1; j > 0; j--) Console.Write(j + " "); Console.Write(0); } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) Console.Write(j + " "); for (int j = (n - (i - n)) - 1; j > 0; j--) Console.Write(j + " "); Console.Write(0); } else { for (int j = 0; j <= n; j++) Console.Write(j + " "); for (int j = n - 1; j > 0; j--) Console.Write(j + " "); Console.Write(0); } Console.Write("\n"); } // putting the space in last line for (int i = 1; i <= n * 2; i++) Console.Write(" "); Console.Write(0); } // driver code public static void Main(string []argc){ int n = 4; pattern(n); }} // This code is contributed by rutvik_56. <?php// PHP code to print// the pattern // function to generate// the pattern.function pattern($n){ // putting the // space in line 1 for ($i = 1; $i <= $n * 2; $i++) echo " "; echo 0 , "\n"; // generating the // middle pattern. for ($i = 1; $i <= ($n * 2) - 1; $i++) { // printing the // increasing pattern if ($i < $n) { for ($j = 1; $j <= ($n - $i) * 2; $j++) echo " "; } else { for ($j = 1; $j <= ($i % $n) * 2; $j++) echo " "; } if ($i < $n) { for ($j = 0; $j <= $i % $n; $j++) echo $j , " "; for ($j = ($i % $n) - 1; $j > 0; $j--) echo $j , " "; echo 0; } // printing the // decreasing pattern else if ($i > $n) { for ($j = 0; $j <= $n - ($i - $n); $j++) echo $j , " "; for ($j = ($n - ($i - $n)) - 1; $j > 0; $j--) echo $j , " "; echo 0; } else { for ($j = 0; $j <= $n; $j++) echo $j ," "; for ($j = $n - 1; $j > 0; $j--) echo $j , " "; echo 0; } echo "\n"; } // putting the space // in last line for ($i = 1; $i <= $n * 2; $i++) echo " "; echo 0;} // Driver Code$n = 4;pattern($n); // This code is contributed by ajit?> <script>// Javascript code to print the pattern // function to generate the pattern. function pattern(n) { // putting the space in line 1 for (let i = 1; i <= n * 2; i++) document.write(" "); document.write(0 + "<br>"); // generating the middle pattern. for (let i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (let j = 1; j <= (n - i) * 2; j++) document.write(" "); } else { for (let j = 1; j <= (i % n) * 2; j++) document.write(" "); } if (i < n) { for (let j = 0; j <= i % n; j++) document.write(j + " "); for (let j = (i % n) - 1; j > 0; j--) document.write(j + " "); document.write(0); } // printing the decreasing pattern else if (i > n) { for (let j = 0; j <= n - (i - n); j++) document.write(j + " "); for (let j = (n - (i - n)) - 1; j > 0; j--) document.write(j + " "); document.write(0); } else { for (let j = 0; j <= n; j++) document.write(j + " "); for (let j = n - 1; j > 0; j--) document.write(j + " "); document.write(0); } document.write("<br>"); } // putting the space in last line for (let i = 1; i <= n * 2; i++) document.write(" "); document.write(0); } let n = 4; pattern(n); // This code is contributed by patel2127</script> Output: 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Abhishek Sharma 44 jit_t mohit kumar 29 patel2127 rutvik_56 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Pure Virtual Functions and Abstract Classes in C++ Destructors in C++ Difference between Abstract Class and Interface in Java Python Exception Handling Exception Handling in C++ Taking input from console in Python
[ { "code": null, "e": 25573, "s": 25545, "text": "\n28 May, 2021" }, { "code": null, "e": 25657, "s": 25573, "text": "Given a number n and using 0-n numbers you have to print such a pattern.Examples: " }, { "code": null, "e": 25960, "s": 25657, "text": "Input : n = 5\nOutput :\n 0\n 0 1 0\n 0 1 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 3 4 3 2 1 0\n0 1 2 3 4 5 4 3 2 1 0\n 0 1 2 3 4 3 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0\n\nInput : n = 3\nOutput :\n 0\n 0 1 0\n 0 1 2 1 0\n0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0" }, { "code": null, "e": 26244, "s": 25962, "text": "The idea here is to count the space in beginning of string. In this pattern there are ((2 * n) + 1) rows. In rows form 0 to n number of spaces is (2 * (n – i)). In row number from (n + 1) to (2 * n), number of space is ((i – n) * 2).Below is the implementation of above approach: " }, { "code": null, "e": 26248, "s": 26244, "text": "C++" }, { "code": null, "e": 26253, "s": 26248, "text": "Java" }, { "code": null, "e": 26261, "s": 26253, "text": "Python3" }, { "code": null, "e": 26264, "s": 26261, "text": "C#" }, { "code": null, "e": 26268, "s": 26264, "text": "PHP" }, { "code": null, "e": 26279, "s": 26268, "text": "Javascript" }, { "code": "// C++ code to print the pattern#include <bits/stdc++.h>using namespace std; // function to generate the pattern.void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) cout << \" \"; cout << 0 << endl; // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) cout << \" \"; } else { for (int j = 1; j <= (i % n) * 2; j++) cout << \" \"; } if (i < n) { for (int j = 0; j <= i % n; j++) cout << j << \" \"; for (int j = (i % n) - 1; j > 0; j--) cout << j << \" \"; cout << 0; } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) cout << j << \" \"; for (int j = (n - (i - n)) - 1; j > 0; j--) cout << j << \" \"; cout << 0; } else { for (int j = 0; j <= n; j++) cout << j << \" \"; for (int j = n - 1; j > 0; j--) cout << j << \" \"; cout << 0; } cout << endl; } // putting the space in last line for (int i = 1; i <= n * 2; i++) cout << \" \"; cout << 0;} // driver function.int main(){ int n = 4; pattern(n); return 0;}", "e": 27746, "s": 26279, "text": null }, { "code": "// Java code to print the patternimport java.util.*;import java.lang.*; public class GeeksforGeeks{ // function to generate the pattern. public static void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) System.out.print(\" \"); System.out.print(0 + \"\\n\"); // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) System.out.print(\" \"); } else { for (int j = 1; j <= (i % n) * 2; j++) System.out.print(\" \"); } if (i < n) { for (int j = 0; j <= i % n; j++) System.out.print(j + \" \"); for (int j = (i % n) - 1; j > 0; j--) System.out.print(j + \" \"); System.out.print(0); } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) System.out.print(j + \" \"); for (int j = (n - (i - n)) - 1; j > 0; j--) System.out.print(j + \" \"); System.out.print(0); } else { for (int j = 0; j <= n; j++) System.out.print(j + \" \"); for (int j = n - 1; j > 0; j--) System.out.print(j + \" \"); System.out.print(0); } System.out.print(\"\\n\"); } // putting the space in last line for (int i = 1; i <= n * 2; i++) System.out.print(\" \"); System.out.print(0); } // driver code public static void main(String argc[]){ int n = 4; pattern(n); }} /*This code is contributed by Sagar Shukla.*/", "e": 29534, "s": 27746, "text": null }, { "code": "# Python3 code to print the pattern # function to generate the pattern.def pattern(n): # putting the space in line 1 for i in range(1, n * 2 + 1): print(end = \" \") print(\"0\") # generating the middle pattern. for i in range(1, n * 2): # printing the increasing pattern if (i < n): for j in range(1, (n - i) * 2 + 1): print(end = \" \") else: for j in range(1, (i % n) * 2 + 1): print(end = \" \") if (i < n): for j in range(i % n + 1): print(j, end = \" \") for j in range(i % n - 1, -1, -1): print(j, end = \" \") # printing the decreasing pattern elif (i > n): for j in range(n - (i - n) + 1): print(j, end = \" \") for j in range((n - (i - n)) - 1, -1, -1): print(j, end = \" \") else: for j in range(n + 1): print(j, end = \" \") for j in range(n - 1, -1, -1): print(j, end = \" \") print() # putting the space in last line for i in range(1, n * 2 + 1): print(end = \" \") print(\"0\", end = \"\") # Driver Coden = 4;pattern(n); # This code is contributed by# mohit kumar 29", "e": 30828, "s": 29534, "text": null }, { "code": "// C# code to print the patternusing System; public class GeeksforGeeks{ // function to generate the pattern. public static void pattern(int n){ // putting the space in line 1 for (int i = 1; i <= n * 2; i++) Console.Write(\" \"); Console.Write(0 + \"\\n\"); // generating the middle pattern. for (int i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (int j = 1; j <= (n - i) * 2; j++) Console.Write(\" \"); } else { for (int j = 1; j <= (i % n) * 2; j++) Console.Write(\" \"); } if (i < n) { for (int j = 0; j <= i % n; j++) Console.Write(j + \" \"); for (int j = (i % n) - 1; j > 0; j--) Console.Write(j + \" \"); Console.Write(0); } // printing the decreasing pattern else if (i > n) { for (int j = 0; j <= n - (i - n); j++) Console.Write(j + \" \"); for (int j = (n - (i - n)) - 1; j > 0; j--) Console.Write(j + \" \"); Console.Write(0); } else { for (int j = 0; j <= n; j++) Console.Write(j + \" \"); for (int j = n - 1; j > 0; j--) Console.Write(j + \" \"); Console.Write(0); } Console.Write(\"\\n\"); } // putting the space in last line for (int i = 1; i <= n * 2; i++) Console.Write(\" \"); Console.Write(0); } // driver code public static void Main(string []argc){ int n = 4; pattern(n); }} // This code is contributed by rutvik_56.", "e": 32537, "s": 30828, "text": null }, { "code": "<?php// PHP code to print// the pattern // function to generate// the pattern.function pattern($n){ // putting the // space in line 1 for ($i = 1; $i <= $n * 2; $i++) echo \" \"; echo 0 , \"\\n\"; // generating the // middle pattern. for ($i = 1; $i <= ($n * 2) - 1; $i++) { // printing the // increasing pattern if ($i < $n) { for ($j = 1; $j <= ($n - $i) * 2; $j++) echo \" \"; } else { for ($j = 1; $j <= ($i % $n) * 2; $j++) echo \" \"; } if ($i < $n) { for ($j = 0; $j <= $i % $n; $j++) echo $j , \" \"; for ($j = ($i % $n) - 1; $j > 0; $j--) echo $j , \" \"; echo 0; } // printing the // decreasing pattern else if ($i > $n) { for ($j = 0; $j <= $n - ($i - $n); $j++) echo $j , \" \"; for ($j = ($n - ($i - $n)) - 1; $j > 0; $j--) echo $j , \" \"; echo 0; } else { for ($j = 0; $j <= $n; $j++) echo $j ,\" \"; for ($j = $n - 1; $j > 0; $j--) echo $j , \" \"; echo 0; } echo \"\\n\"; } // putting the space // in last line for ($i = 1; $i <= $n * 2; $i++) echo \" \"; echo 0;} // Driver Code$n = 4;pattern($n); // This code is contributed by ajit?>", "e": 34268, "s": 32537, "text": null }, { "code": "<script>// Javascript code to print the pattern // function to generate the pattern. function pattern(n) { // putting the space in line 1 for (let i = 1; i <= n * 2; i++) document.write(\" \"); document.write(0 + \"<br>\"); // generating the middle pattern. for (let i = 1; i <= (n * 2) - 1; i++) { // printing the increasing pattern if (i < n) { for (let j = 1; j <= (n - i) * 2; j++) document.write(\" \"); } else { for (let j = 1; j <= (i % n) * 2; j++) document.write(\" \"); } if (i < n) { for (let j = 0; j <= i % n; j++) document.write(j + \" \"); for (let j = (i % n) - 1; j > 0; j--) document.write(j + \" \"); document.write(0); } // printing the decreasing pattern else if (i > n) { for (let j = 0; j <= n - (i - n); j++) document.write(j + \" \"); for (let j = (n - (i - n)) - 1; j > 0; j--) document.write(j + \" \"); document.write(0); } else { for (let j = 0; j <= n; j++) document.write(j + \" \"); for (let j = n - 1; j > 0; j--) document.write(j + \" \"); document.write(0); } document.write(\"<br>\"); } // putting the space in last line for (let i = 1; i <= n * 2; i++) document.write(\" \"); document.write(0); } let n = 4; pattern(n); // This code is contributed by patel2127</script>", "e": 35907, "s": 34268, "text": null }, { "code": null, "e": 35917, "s": 35907, "text": "Output: " }, { "code": null, "e": 36039, "s": 35917, "text": " 0\n 0 1 0\n 0 1 2 1 0\n 0 1 2 3 2 1 0\n0 1 2 3 4 3 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0" }, { "code": null, "e": 36060, "s": 36041, "text": "Abhishek Sharma 44" }, { "code": null, "e": 36066, "s": 36060, "text": "jit_t" }, { "code": null, "e": 36081, "s": 36066, "text": "mohit kumar 29" }, { "code": null, "e": 36091, "s": 36081, "text": "patel2127" }, { "code": null, "e": 36101, "s": 36091, "text": "rutvik_56" }, { "code": null, "e": 36118, "s": 36101, "text": "pattern-printing" }, { "code": null, "e": 36137, "s": 36118, "text": "School Programming" }, { "code": null, "e": 36154, "s": 36137, "text": "pattern-printing" }, { "code": null, "e": 36252, "s": 36154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36273, "s": 36252, "text": "Constructors in Java" }, { "code": null, "e": 36292, "s": 36273, "text": "Exceptions in Java" }, { "code": null, "e": 36319, "s": 36292, "text": "Ternary Operator in Python" }, { "code": null, "e": 36343, "s": 36319, "text": "Inline Functions in C++" }, { "code": null, "e": 36394, "s": 36343, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 36413, "s": 36394, "text": "Destructors in C++" }, { "code": null, "e": 36469, "s": 36413, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 36495, "s": 36469, "text": "Python Exception Handling" }, { "code": null, "e": 36521, "s": 36495, "text": "Exception Handling in C++" } ]
Find whether a subarray is in form of a mountain or not - GeeksforGeeks
25 Aug, 2021 We are given an array of integers and a range, we need to find whether the subarray which falls in this range has values in the form of a mountain or not. All values of the subarray are said to be in the form of a mountain if either all values are increasing or decreasing or first increasing and then decreasing. More formally a subarray [a1, a2, a3 ... aN] is said to be in form of a mountain if there exist an integer K, 1 <= K <= N such that, a1 <= a2 <= a3 .. <= aK >= a(K+1) >= a(K+2) .... >= aN Examples: Input : Arr[] = [2 3 2 4 4 6 3 2], Range = [0, 2] Output : Yes Explanation: The output is yes , subarray is [2 3 2], so subarray first increases and then decreases Input: Arr[] = [2 3 2 4 4 6 3 2], Range = [2, 7] Output: Yes Explanation: The output is yes , subarray is [2 4 4 6 3 2], so subarray first increases and then decreases Input: Arr[]= [2 3 2 4 4 6 3 2], Range = [1, 3] Output: no Explanation: The output is no, subarray is [3 2 4], so subarray is not in the form above stated Solution: Approach: The problem has multiple queries so for each query the solution should be calculated with least possible time complexity. So create two extra spaces of the length of the original array. For every element find the last index on the left side which is increasing i.e. greater than its previous element and find the element on the right side will store the first index on the right side which is decreasing i.e. greater than its next element. If these value can be calculated for every index in constant time then for every given range the answer can be given in constant time. Algorithm: Create two extra spaces of length n,left and right and a extra variable lastptrInitialize left[0] = 0 and lastptr = 0Traverse the original array from second index to the endFor every index check if it is greater than the previous element, if yes then update the lastptr with the current index.For every index store the lastptr in left[i]initialize right[N-1] = N-1 and lastptr = N-1Traverse the original array from second last index to the startFor every index check if it is greater than the next element, if yes then update the lastptr with the current index.For every index store the lastptr in right[i]Now process the queriesfor every query l, r, if right[l] >= left[r] then print yes else no Create two extra spaces of length n,left and right and a extra variable lastptrInitialize left[0] = 0 and lastptr = 0Traverse the original array from second index to the endFor every index check if it is greater than the previous element, if yes then update the lastptr with the current index.For every index store the lastptr in left[i]initialize right[N-1] = N-1 and lastptr = N-1Traverse the original array from second last index to the startFor every index check if it is greater than the next element, if yes then update the lastptr with the current index.For every index store the lastptr in right[i]Now process the queriesfor every query l, r, if right[l] >= left[r] then print yes else no Create two extra spaces of length n,left and right and a extra variable lastptr Initialize left[0] = 0 and lastptr = 0 Traverse the original array from second index to the end For every index check if it is greater than the previous element, if yes then update the lastptr with the current index. For every index store the lastptr in left[i] initialize right[N-1] = N-1 and lastptr = N-1 Traverse the original array from second last index to the start For every index check if it is greater than the next element, if yes then update the lastptr with the current index. For every index store the lastptr in right[i] Now process the queries for every query l, r, if right[l] >= left[r] then print yes else no Implementation: C++ Java Python3 C# Javascript // C++ program to check whether a subarray is in// mountain form or not#include <bits/stdc++.h>using namespace std; // Utility method to construct left and right arrayint preprocess(int arr[], int N, int left[], int right[]){ // Initialize first left index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // Initialize last right index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; }} // Method returns true if arr[L..R] is in mountain formbool isSubarrayMountainForm(int arr[], int left[], int right[], int L, int R){ // return true only if right at starting range is // greater than left at ending range return (right[L] >= left[R]);} // Driver code to test above methodsint main(){ int arr[] = {2, 3, 2, 4, 4, 6, 3, 2}; int N = sizeof(arr) / sizeof(int); int left[N], right[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) cout << "Subarray is in mountain form\n"; else cout << "Subarray is not in mountain form\n"; L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) cout << "Subarray is in mountain form\n"; else cout << "Subarray is not in mountain form\n"; return 0;} // Java program to check whether a subarray is in// mountain form or notclass SubArray{ // Utility method to construct left and right array static void preprocess(int arr[], int N, int left[], int right[]) { // initialize first left index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if arr[L..R] is in mountain form static boolean isSubarrayMountainForm(int arr[], int left[], int right[], int L, int R) { // return true only if right at starting range is // greater than left at ending range return (right[L] >= left[R]); } public static void main(String[] args) { int arr[] = {2, 3, 2, 4, 4, 6, 3, 2}; int N = arr.length; int left[] = new int[N]; int right[] = new int[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) System.out.println("Subarray is in mountain form"); else System.out.println("Subarray is not in mountain form"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) System.out.println("Subarray is in mountain form"); else System.out.println("Subarray is not in mountain form"); }}// This Code is Contributed by Saket Kumar # Python 3 program to check whether a subarray is in# mountain form or not # Utility method to construct left and right arraydef preprocess(arr, N, left, right): # initialize first left index as that index only left[0] = 0 lastIncr = 0 for i in range(1,N): # if current value is greater than previous, # update last increasing if (arr[i] > arr[i - 1]): lastIncr = i left[i] = lastIncr # initialize last right index as that index only right[N - 1] = N - 1 firstDecr = N - 1 i = N - 2 while(i >= 0): # if current value is greater than next, # update first decreasing if (arr[i] > arr[i + 1]): firstDecr = i right[i] = firstDecr i -= 1 # method returns true if arr[L..R] is in mountain formdef isSubarrayMountainForm(arr, left, right, L, R): # return true only if right at starting range is # greater than left at ending range return (right[L] >= left[R]) # Driver codeif __name__ == '__main__': arr = [2, 3, 2, 4, 4, 6, 3, 2] N = len(arr) left = [0 for i in range(N)] right = [0 for i in range(N)] preprocess(arr, N, left, right) L = 0 R = 2 if (isSubarrayMountainForm(arr, left, right, L, R)): print("Subarray is in mountain form") else: print("Subarray is not in mountain form") L = 1 R = 3 if (isSubarrayMountainForm(arr, left, right, L, R)): print("Subarray is in mountain form") else: print("Subarray is not in mountain form") # This code is contributed by# Surendra_Gangwar // C# program to check whether// a subarray is in mountain// form or notusing System; class GFG{ // Utility method to construct // left and right array static void preprocess(int []arr, int N, int []left, int []right) { // initialize first left // index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is // greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right // index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is // greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if // arr[L..R] is in mountain form static bool isSubarrayMountainForm(int []arr, int []left, int []right, int L, int R) { // return true only if right at // starting range is greater // than left at ending range return (right[L] >= left[R]); } // Driver Code static public void Main () { int []arr = {2, 3, 2, 4, 4, 6, 3, 2}; int N = arr.Length; int []left = new int[N]; int []right = new int[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) Console.WriteLine("Subarray is in " + "mountain form"); else Console.WriteLine("Subarray is not " + "in mountain form"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) Console.WriteLine("Subarray is in " + "mountain form"); else Console.WriteLine("Subarray is not " + "in mountain form"); }} // This code is contributed by aj_36 <script> // Javascript program to check whether // a subarray is in mountain // form or not // Utility method to construct // left and right array function preprocess(arr, N, left, right) { // initialize first left // index as that index only left[0] = 0; let lastIncr = 0; for (let i = 1; i < N; i++) { // if current value is // greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right // index as that index only right[N - 1] = N - 1; let firstDecr = N - 1; for (let i = N - 2; i >= 0; i--) { // if current value is // greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if // arr[L..R] is in mountain form function isSubarrayMountainForm(arr, left, right, L, R) { // return true only if right at // starting range is greater // than left at ending range return (right[L] >= left[R]); } let arr = [2, 3, 2, 4, 4, 6, 3, 2]; let N = arr.length; let left = new Array(N); let right = new Array(N); preprocess(arr, N, left, right); let L = 0; let R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) document.write("Subarray is in " + "mountain form" + "</br>"); else document.write("Subarray is not " + "in mountain form" + "</br>"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) document.write("Subarray is in " + "mountain form"); else document.write("Subarray is not " + "in mountain form"); </script> Output: Subarray is in mountain form Subarray is not in mountain form Complexity Analysis: Time Complexity:O(n). Only two traversals are needed so the time complexity is O(n).Space Complexity:O(n). Two extra space of length n is required so the space complexity is O(n). Time Complexity:O(n). Only two traversals are needed so the time complexity is O(n). Space Complexity:O(n). Two extra space of length n is required so the space complexity is O(n). This article is contributed by Utkarsh Trivedi. 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. jit_t SURENDRA_GANGWAR andrew1234 mukesh07 arorakashish0911 adnanirshad158 Amazon array-range-queries FactSet Advanced Data Structure Arrays Amazon FactSet Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Segment Tree | Set 1 (Sum of given range) Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26521, "s": 26493, "text": "\n25 Aug, 2021" }, { "code": null, "e": 27024, "s": 26521, "text": "We are given an array of integers and a range, we need to find whether the subarray which falls in this range has values in the form of a mountain or not. All values of the subarray are said to be in the form of a mountain if either all values are increasing or decreasing or first increasing and then decreasing. More formally a subarray [a1, a2, a3 ... aN] is said to be in form of a mountain if there exist an integer K, 1 <= K <= N such that, a1 <= a2 <= a3 .. <= aK >= a(K+1) >= a(K+2) .... >= aN " }, { "code": null, "e": 27035, "s": 27024, "text": "Examples: " }, { "code": null, "e": 27534, "s": 27035, "text": "Input : Arr[] = [2 3 2 4 4 6 3 2], Range = [0, 2]\nOutput : Yes\n\nExplanation: The output is yes , subarray is [2 3 2], \nso subarray first increases and then decreases\n\nInput: Arr[] = [2 3 2 4 4 6 3 2], Range = [2, 7]\nOutput: Yes\n\nExplanation: The output is yes , subarray is [2 4 4 6 3 2], \nso subarray first increases and then decreases\n\n\nInput: Arr[]= [2 3 2 4 4 6 3 2], Range = [1, 3]\nOutput: no\n\nExplanation: The output is no, subarray is [3 2 4], \nso subarray is not in the form above stated" }, { "code": null, "e": 27545, "s": 27534, "text": "Solution: " }, { "code": null, "e": 28130, "s": 27545, "text": "Approach: The problem has multiple queries so for each query the solution should be calculated with least possible time complexity. So create two extra spaces of the length of the original array. For every element find the last index on the left side which is increasing i.e. greater than its previous element and find the element on the right side will store the first index on the right side which is decreasing i.e. greater than its next element. If these value can be calculated for every index in constant time then for every given range the answer can be given in constant time." }, { "code": null, "e": 28838, "s": 28130, "text": "Algorithm: Create two extra spaces of length n,left and right and a extra variable lastptrInitialize left[0] = 0 and lastptr = 0Traverse the original array from second index to the endFor every index check if it is greater than the previous element, if yes then update the lastptr with the current index.For every index store the lastptr in left[i]initialize right[N-1] = N-1 and lastptr = N-1Traverse the original array from second last index to the startFor every index check if it is greater than the next element, if yes then update the lastptr with the current index.For every index store the lastptr in right[i]Now process the queriesfor every query l, r, if right[l] >= left[r] then print yes else no" }, { "code": null, "e": 29535, "s": 28838, "text": "Create two extra spaces of length n,left and right and a extra variable lastptrInitialize left[0] = 0 and lastptr = 0Traverse the original array from second index to the endFor every index check if it is greater than the previous element, if yes then update the lastptr with the current index.For every index store the lastptr in left[i]initialize right[N-1] = N-1 and lastptr = N-1Traverse the original array from second last index to the startFor every index check if it is greater than the next element, if yes then update the lastptr with the current index.For every index store the lastptr in right[i]Now process the queriesfor every query l, r, if right[l] >= left[r] then print yes else no" }, { "code": null, "e": 29615, "s": 29535, "text": "Create two extra spaces of length n,left and right and a extra variable lastptr" }, { "code": null, "e": 29654, "s": 29615, "text": "Initialize left[0] = 0 and lastptr = 0" }, { "code": null, "e": 29711, "s": 29654, "text": "Traverse the original array from second index to the end" }, { "code": null, "e": 29832, "s": 29711, "text": "For every index check if it is greater than the previous element, if yes then update the lastptr with the current index." }, { "code": null, "e": 29877, "s": 29832, "text": "For every index store the lastptr in left[i]" }, { "code": null, "e": 29923, "s": 29877, "text": "initialize right[N-1] = N-1 and lastptr = N-1" }, { "code": null, "e": 29987, "s": 29923, "text": "Traverse the original array from second last index to the start" }, { "code": null, "e": 30104, "s": 29987, "text": "For every index check if it is greater than the next element, if yes then update the lastptr with the current index." }, { "code": null, "e": 30150, "s": 30104, "text": "For every index store the lastptr in right[i]" }, { "code": null, "e": 30174, "s": 30150, "text": "Now process the queries" }, { "code": null, "e": 30242, "s": 30174, "text": "for every query l, r, if right[l] >= left[r] then print yes else no" }, { "code": null, "e": 30258, "s": 30242, "text": "Implementation:" }, { "code": null, "e": 30262, "s": 30258, "text": "C++" }, { "code": null, "e": 30267, "s": 30262, "text": "Java" }, { "code": null, "e": 30275, "s": 30267, "text": "Python3" }, { "code": null, "e": 30278, "s": 30275, "text": "C#" }, { "code": null, "e": 30289, "s": 30278, "text": "Javascript" }, { "code": "// C++ program to check whether a subarray is in// mountain form or not#include <bits/stdc++.h>using namespace std; // Utility method to construct left and right arrayint preprocess(int arr[], int N, int left[], int right[]){ // Initialize first left index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // Initialize last right index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; }} // Method returns true if arr[L..R] is in mountain formbool isSubarrayMountainForm(int arr[], int left[], int right[], int L, int R){ // return true only if right at starting range is // greater than left at ending range return (right[L] >= left[R]);} // Driver code to test above methodsint main(){ int arr[] = {2, 3, 2, 4, 4, 6, 3, 2}; int N = sizeof(arr) / sizeof(int); int left[N], right[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) cout << \"Subarray is in mountain form\\n\"; else cout << \"Subarray is not in mountain form\\n\"; L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) cout << \"Subarray is in mountain form\\n\"; else cout << \"Subarray is not in mountain form\\n\"; return 0;}", "e": 32017, "s": 30289, "text": null }, { "code": "// Java program to check whether a subarray is in// mountain form or notclass SubArray{ // Utility method to construct left and right array static void preprocess(int arr[], int N, int left[], int right[]) { // initialize first left index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if arr[L..R] is in mountain form static boolean isSubarrayMountainForm(int arr[], int left[], int right[], int L, int R) { // return true only if right at starting range is // greater than left at ending range return (right[L] >= left[R]); } public static void main(String[] args) { int arr[] = {2, 3, 2, 4, 4, 6, 3, 2}; int N = arr.length; int left[] = new int[N]; int right[] = new int[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) System.out.println(\"Subarray is in mountain form\"); else System.out.println(\"Subarray is not in mountain form\"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) System.out.println(\"Subarray is in mountain form\"); else System.out.println(\"Subarray is not in mountain form\"); }}// This Code is Contributed by Saket Kumar", "e": 34071, "s": 32017, "text": null }, { "code": "# Python 3 program to check whether a subarray is in# mountain form or not # Utility method to construct left and right arraydef preprocess(arr, N, left, right): # initialize first left index as that index only left[0] = 0 lastIncr = 0 for i in range(1,N): # if current value is greater than previous, # update last increasing if (arr[i] > arr[i - 1]): lastIncr = i left[i] = lastIncr # initialize last right index as that index only right[N - 1] = N - 1 firstDecr = N - 1 i = N - 2 while(i >= 0): # if current value is greater than next, # update first decreasing if (arr[i] > arr[i + 1]): firstDecr = i right[i] = firstDecr i -= 1 # method returns true if arr[L..R] is in mountain formdef isSubarrayMountainForm(arr, left, right, L, R): # return true only if right at starting range is # greater than left at ending range return (right[L] >= left[R]) # Driver codeif __name__ == '__main__': arr = [2, 3, 2, 4, 4, 6, 3, 2] N = len(arr) left = [0 for i in range(N)] right = [0 for i in range(N)] preprocess(arr, N, left, right) L = 0 R = 2 if (isSubarrayMountainForm(arr, left, right, L, R)): print(\"Subarray is in mountain form\") else: print(\"Subarray is not in mountain form\") L = 1 R = 3 if (isSubarrayMountainForm(arr, left, right, L, R)): print(\"Subarray is in mountain form\") else: print(\"Subarray is not in mountain form\") # This code is contributed by# Surendra_Gangwar", "e": 35648, "s": 34071, "text": null }, { "code": "// C# program to check whether// a subarray is in mountain// form or notusing System; class GFG{ // Utility method to construct // left and right array static void preprocess(int []arr, int N, int []left, int []right) { // initialize first left // index as that index only left[0] = 0; int lastIncr = 0; for (int i = 1; i < N; i++) { // if current value is // greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right // index as that index only right[N - 1] = N - 1; int firstDecr = N - 1; for (int i = N - 2; i >= 0; i--) { // if current value is // greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if // arr[L..R] is in mountain form static bool isSubarrayMountainForm(int []arr, int []left, int []right, int L, int R) { // return true only if right at // starting range is greater // than left at ending range return (right[L] >= left[R]); } // Driver Code static public void Main () { int []arr = {2, 3, 2, 4, 4, 6, 3, 2}; int N = arr.Length; int []left = new int[N]; int []right = new int[N]; preprocess(arr, N, left, right); int L = 0; int R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) Console.WriteLine(\"Subarray is in \" + \"mountain form\"); else Console.WriteLine(\"Subarray is not \" + \"in mountain form\"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) Console.WriteLine(\"Subarray is in \" + \"mountain form\"); else Console.WriteLine(\"Subarray is not \" + \"in mountain form\"); }} // This code is contributed by aj_36", "e": 38051, "s": 35648, "text": null }, { "code": "<script> // Javascript program to check whether // a subarray is in mountain // form or not // Utility method to construct // left and right array function preprocess(arr, N, left, right) { // initialize first left // index as that index only left[0] = 0; let lastIncr = 0; for (let i = 1; i < N; i++) { // if current value is // greater than previous, // update last increasing if (arr[i] > arr[i - 1]) lastIncr = i; left[i] = lastIncr; } // initialize last right // index as that index only right[N - 1] = N - 1; let firstDecr = N - 1; for (let i = N - 2; i >= 0; i--) { // if current value is // greater than next, // update first decreasing if (arr[i] > arr[i + 1]) firstDecr = i; right[i] = firstDecr; } } // method returns true if // arr[L..R] is in mountain form function isSubarrayMountainForm(arr, left, right, L, R) { // return true only if right at // starting range is greater // than left at ending range return (right[L] >= left[R]); } let arr = [2, 3, 2, 4, 4, 6, 3, 2]; let N = arr.length; let left = new Array(N); let right = new Array(N); preprocess(arr, N, left, right); let L = 0; let R = 2; if (isSubarrayMountainForm(arr, left, right, L, R)) document.write(\"Subarray is in \" + \"mountain form\" + \"</br>\"); else document.write(\"Subarray is not \" + \"in mountain form\" + \"</br>\"); L = 1; R = 3; if (isSubarrayMountainForm(arr, left, right, L, R)) document.write(\"Subarray is in \" + \"mountain form\"); else document.write(\"Subarray is not \" + \"in mountain form\"); </script>", "e": 39959, "s": 38051, "text": null }, { "code": null, "e": 39967, "s": 39959, "text": "Output:" }, { "code": null, "e": 40029, "s": 39967, "text": "Subarray is in mountain form\nSubarray is not in mountain form" }, { "code": null, "e": 40230, "s": 40029, "text": "Complexity Analysis: Time Complexity:O(n). Only two traversals are needed so the time complexity is O(n).Space Complexity:O(n). Two extra space of length n is required so the space complexity is O(n)." }, { "code": null, "e": 40315, "s": 40230, "text": "Time Complexity:O(n). Only two traversals are needed so the time complexity is O(n)." }, { "code": null, "e": 40411, "s": 40315, "text": "Space Complexity:O(n). Two extra space of length n is required so the space complexity is O(n)." }, { "code": null, "e": 40835, "s": 40411, "text": "This article is contributed by Utkarsh Trivedi. 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": 40841, "s": 40835, "text": "jit_t" }, { "code": null, "e": 40858, "s": 40841, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 40869, "s": 40858, "text": "andrew1234" }, { "code": null, "e": 40878, "s": 40869, "text": "mukesh07" }, { "code": null, "e": 40895, "s": 40878, "text": "arorakashish0911" }, { "code": null, "e": 40910, "s": 40895, "text": "adnanirshad158" }, { "code": null, "e": 40917, "s": 40910, "text": "Amazon" }, { "code": null, "e": 40937, "s": 40917, "text": "array-range-queries" }, { "code": null, "e": 40945, "s": 40937, "text": "FactSet" }, { "code": null, "e": 40969, "s": 40945, "text": "Advanced Data Structure" }, { "code": null, "e": 40976, "s": 40969, "text": "Arrays" }, { "code": null, "e": 40983, "s": 40976, "text": "Amazon" }, { "code": null, "e": 40991, "s": 40983, "text": "FactSet" }, { "code": null, "e": 40998, "s": 40991, "text": "Arrays" }, { "code": null, "e": 41096, "s": 40998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41130, "s": 41096, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 41170, "s": 41130, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 41198, "s": 41170, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 41230, "s": 41198, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 41272, "s": 41230, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 41287, "s": 41272, "text": "Arrays in Java" }, { "code": null, "e": 41303, "s": 41287, "text": "Arrays in C/C++" }, { "code": null, "e": 41371, "s": 41303, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 41417, "s": 41371, "text": "Write a program to reverse an array or string" } ]
Queries for maximum difference between prime numbers in given ranges - GeeksforGeeks
01 Jun, 2021 Given n queries of the form range [L, R]. The task is to find the maximum difference between two prime numbers in the range for each query. If there are no prime in the range then print 0. All ranges are below 100005. Examples: Input : Q = 3 query1 = [2, 5] query2 = [2, 2] query3 = [24, 28] Output : 3 0 0 In first query, 2 and 5 are prime number in the range with maximum difference which is 3. In second there is only 1 prime number in range, so output is 0. And in third query, there is no prime number in the given range so the output is 0. The idea is to compute Prime numbers using Sieve of Eratosthenes along with some precomputing. Below are the step to solve the question: Step 1: Find the prime numbers using Sieve of Eratosthenes algorithm. Step 2: Make an array, let say prefix[], where prefix[i] represents largest prime number smaller or equal to i. Step 3: Make an array, let say suffix[], where suffix[i] represents smallest prime number greater or equal to i. Step 4: Now for each query having [L, R], do the following: if (prefix[R] R) return 0; else return prefix[R] - suffix[L]; Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP program to find maximum differences between// two prime numbers in given ranges#include <bits/stdc++.h>using namespace std;#define MAX 100005 // Declare global variables to assign heap memory and avoid// stack overflowbool prime[MAX];int prefix[MAX], suffix[MAX]; // Precompute Sieve, Prefix array, Suffix arrayvoid precompute(int prefix[], int suffix[]){ memset(prime, true, sizeof(prime)); // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) prime[j] = false; } } prefix[1] = 1; suffix[MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) prefix[i] = i; else prefix[i] = prefix[i - 1]; } // Precompute Suffix array. for (int i = MAX - 1; i > 1; i--) { if (prime[i]) suffix[i] = i; else suffix[i] = suffix[i + 1]; }} // Function to solve each queryint query(int prefix[], int suffix[], int L, int R){ if (prefix[R] < L || suffix[L] > R) return 0; else return prefix[R] - suffix[L];} // Driven Programint main(){ int q = 3; int L[] = { 2, 2, 24 }; int R[] = { 5, 2, 28 }; precompute(prefix, suffix); for (int i = 0; i < q; i++) cout << query(prefix, suffix, L[i], R[i]) << endl; return 0;} // Java program to find maximum differences between// two prime numbers in given ranges public class GFG { final static int MAX = 100005; // Precompute Sieve, Prefix array, Suffix array static void precompute(int prefix[], int suffix[]) { boolean prime[] = new boolean[MAX]; for (int i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = (int)1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for (int i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } } } // Function to solve each query static int query(int prefix[], int suffix[], int L, int R) { if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; } } // Driven Program public static void main(String[] args) { int q = 3; int L[] = { 2, 2, 24 }; int R[] = { 5, 2, 28 }; int prefix[] = new int[MAX], suffix[] = new int[MAX]; precompute(prefix, suffix); for (int i = 0; i < q; i++) { System.out.println( query(prefix, suffix, L[i], R[i])); } }}/*This code is contributed by Rajput-Ji*/ # Python 3 program to find maximum# differences between two prime numbers# in given rangesfrom math import sqrt MAX = 100005 # Precompute Sieve, Prefix array, Suffix arraydef precompute(prefix, suffix): prime = [True for i in range(MAX)] # Sieve of Eratosthenes k = int(sqrt(MAX)) for i in range(2, k, 1): if (prime[i]): for j in range(i * i, MAX, i): prime[j] = False prefix[1] = 1 suffix[MAX - 1] = int(1e9 + 7) # Precomputing Prefix array. for i in range(2, MAX, 1): if (prime[i]): prefix[i] = i else: prefix[i] = prefix[i - 1] # Precompute Suffix array. i = MAX - 2 while(i > 1): if (prime[i]): suffix[i] = i else: suffix[i] = suffix[i + 1] i -= 1 # Function to solve each query def query(prefix, suffix, L, R): if (prefix[R] < L or suffix[L] > R): return 0 else: return prefix[R] - suffix[L] # Driver Codeif __name__ == '__main__': q = 3 L = [2, 2, 24] R = [5, 2, 28] prefix = [0 for i in range(MAX)] suffix = [0 for i in range(MAX)] precompute(prefix, suffix) for i in range(0, q, 1): print(query(prefix, suffix, L[i], R[i])) # This code is contributed by# Surendra_Gangwar // C# program to find maximum differences between// two prime numbers in given rangesusing System; public class GFG { static readonly int MAX = 100005; // Precompute Sieve, Prefix array, Suffix array static void precompute(int[] prefix, int[] suffix) { bool[] prime = new bool[MAX]; for (int i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = (int)1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for (int i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } } } // Function to solve each query static int query(int[] prefix, int[] suffix, int L, int R) { if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; } } // Driven Program public static void Main() { int q = 3; int[] L = { 2, 2, 24 }; int[] R = { 5, 2, 28 }; int[] prefix = new int[MAX]; int[] suffix = new int[MAX]; precompute(prefix, suffix); for (int i = 0; i < q; i++) { Console.WriteLine( query(prefix, suffix, L[i], R[i])); } }} /*This code is contributed by 29AjayKumar*/ <?php// PHP program to find maximum differences// between two prime numbers in given ranges$MAX = 100005; // Precompute Sieve, Prefix array,// Suffix arrayfunction precompute(&$prefix, &$suffix){ global $MAX; $prime = array_fill(0, $MAX, true); // Sieve of Eratosthenes for ($i = 2; $i * $i < $MAX; $i++) { if ($prime[$i]) { for ($j = $i * $i; $j < $MAX; $j += $i) $prime[$j] = false; } } $prefix[1] = 1; $suffix[$MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for ($i = 2; $i < $MAX; $i++) { if ($prime[$i]) $prefix[$i] = $i; else $prefix[$i] = $prefix[$i - 1]; } // Precompute Suffix array. for ($i = $MAX - 1; $i > 1; $i--) { if ($prime[$i]) $suffix[$i] = $i; else $suffix[$i] = $suffix[$i + 1]; }} // Function to solve each queryfunction query($prefix, $suffix, $L, $R){ if ($prefix[$R] < $L || $suffix[$L] > $R) return 0; else return $prefix[$R] - $suffix[$L];} // Driver Code$q = 3;$L = array( 2, 2, 24 );$R = array( 5, 2, 28 ); $prefix = array_fill(0, $MAX + 1, 0);$suffix = array_fill(0, $MAX + 1, 0);precompute($prefix, $suffix); for ($i = 0; $i < $q; $i++) echo query($prefix, $suffix, $L[$i], $R[$i]) . "\n"; // This code is contributed by mits?> <script> // JavaScript program to find maximum// differences between two prime// numbers in given ranges let MAX = 100005; // Precompute Sieve, Prefix array, Suffix arrayfunction precompute(prefix, suffix){ let prime = []; for(let i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for(let i = 2; i * i < MAX; i++) { if (prime[i]) { for(let j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for(let i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for(let i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } }} // Function to solve each queryfunction query(prefix, suffix, L, R){ if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; }} // Driver Codelet q = 3;let L = [ 2, 2, 24 ];let R = [ 5, 2, 28 ];let prefix = [], suffix = []; precompute(prefix, suffix); for(let i = 0; i < q; i++){ document.write(query(prefix, suffix, L[i], R[i]) + "<br/>");} // This code is contributed by sanjoy_62 </script> Output: 3 0 0 sourabh1031 Rajput-Ji 29AjayKumar Mithun Kumar SURENDRA_GANGWAR shivamagrawal3 sanjoy_62 coding_pandaa Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Merge two sorted arrays with O(1) extra space Singular Value Decomposition (SVD) Program to multiply two matrices
[ { "code": null, "e": 26073, "s": 26045, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26291, "s": 26073, "text": "Given n queries of the form range [L, R]. The task is to find the maximum difference between two prime numbers in the range for each query. If there are no prime in the range then print 0. All ranges are below 100005." }, { "code": null, "e": 26302, "s": 26291, "text": "Examples: " }, { "code": null, "e": 26665, "s": 26302, "text": "Input : Q = 3\n query1 = [2, 5]\n query2 = [2, 2]\n query3 = [24, 28]\nOutput : 3\n 0\n 0\nIn first query, 2 and 5 are prime number \nin the range with maximum difference which \nis 3. In second there \nis only 1 prime number in range, so output\nis 0. And in third query, there is no prime number in the given range so the output is 0." }, { "code": null, "e": 26761, "s": 26665, "text": "The idea is to compute Prime numbers using Sieve of Eratosthenes along with some precomputing. " }, { "code": null, "e": 27158, "s": 26761, "text": "Below are the step to solve the question: Step 1: Find the prime numbers using Sieve of Eratosthenes algorithm. Step 2: Make an array, let say prefix[], where prefix[i] represents largest prime number smaller or equal to i. Step 3: Make an array, let say suffix[], where suffix[i] represents smallest prime number greater or equal to i. Step 4: Now for each query having [L, R], do the following:" }, { "code": null, "e": 27233, "s": 27158, "text": " if (prefix[R] R)\n return 0;\n else\n return prefix[R] - suffix[L];" }, { "code": null, "e": 27281, "s": 27233, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 27285, "s": 27281, "text": "C++" }, { "code": null, "e": 27290, "s": 27285, "text": "Java" }, { "code": null, "e": 27298, "s": 27290, "text": "Python3" }, { "code": null, "e": 27301, "s": 27298, "text": "C#" }, { "code": null, "e": 27305, "s": 27301, "text": "PHP" }, { "code": null, "e": 27316, "s": 27305, "text": "Javascript" }, { "code": "// CPP program to find maximum differences between// two prime numbers in given ranges#include <bits/stdc++.h>using namespace std;#define MAX 100005 // Declare global variables to assign heap memory and avoid// stack overflowbool prime[MAX];int prefix[MAX], suffix[MAX]; // Precompute Sieve, Prefix array, Suffix arrayvoid precompute(int prefix[], int suffix[]){ memset(prime, true, sizeof(prime)); // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) prime[j] = false; } } prefix[1] = 1; suffix[MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) prefix[i] = i; else prefix[i] = prefix[i - 1]; } // Precompute Suffix array. for (int i = MAX - 1; i > 1; i--) { if (prime[i]) suffix[i] = i; else suffix[i] = suffix[i + 1]; }} // Function to solve each queryint query(int prefix[], int suffix[], int L, int R){ if (prefix[R] < L || suffix[L] > R) return 0; else return prefix[R] - suffix[L];} // Driven Programint main(){ int q = 3; int L[] = { 2, 2, 24 }; int R[] = { 5, 2, 28 }; precompute(prefix, suffix); for (int i = 0; i < q; i++) cout << query(prefix, suffix, L[i], R[i]) << endl; return 0;}", "e": 28718, "s": 27316, "text": null }, { "code": "// Java program to find maximum differences between// two prime numbers in given ranges public class GFG { final static int MAX = 100005; // Precompute Sieve, Prefix array, Suffix array static void precompute(int prefix[], int suffix[]) { boolean prime[] = new boolean[MAX]; for (int i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = (int)1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for (int i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } } } // Function to solve each query static int query(int prefix[], int suffix[], int L, int R) { if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; } } // Driven Program public static void main(String[] args) { int q = 3; int L[] = { 2, 2, 24 }; int R[] = { 5, 2, 28 }; int prefix[] = new int[MAX], suffix[] = new int[MAX]; precompute(prefix, suffix); for (int i = 0; i < q; i++) { System.out.println( query(prefix, suffix, L[i], R[i])); } }}/*This code is contributed by Rajput-Ji*/", "e": 30575, "s": 28718, "text": null }, { "code": "# Python 3 program to find maximum# differences between two prime numbers# in given rangesfrom math import sqrt MAX = 100005 # Precompute Sieve, Prefix array, Suffix arraydef precompute(prefix, suffix): prime = [True for i in range(MAX)] # Sieve of Eratosthenes k = int(sqrt(MAX)) for i in range(2, k, 1): if (prime[i]): for j in range(i * i, MAX, i): prime[j] = False prefix[1] = 1 suffix[MAX - 1] = int(1e9 + 7) # Precomputing Prefix array. for i in range(2, MAX, 1): if (prime[i]): prefix[i] = i else: prefix[i] = prefix[i - 1] # Precompute Suffix array. i = MAX - 2 while(i > 1): if (prime[i]): suffix[i] = i else: suffix[i] = suffix[i + 1] i -= 1 # Function to solve each query def query(prefix, suffix, L, R): if (prefix[R] < L or suffix[L] > R): return 0 else: return prefix[R] - suffix[L] # Driver Codeif __name__ == '__main__': q = 3 L = [2, 2, 24] R = [5, 2, 28] prefix = [0 for i in range(MAX)] suffix = [0 for i in range(MAX)] precompute(prefix, suffix) for i in range(0, q, 1): print(query(prefix, suffix, L[i], R[i])) # This code is contributed by# Surendra_Gangwar", "e": 31875, "s": 30575, "text": null }, { "code": "// C# program to find maximum differences between// two prime numbers in given rangesusing System; public class GFG { static readonly int MAX = 100005; // Precompute Sieve, Prefix array, Suffix array static void precompute(int[] prefix, int[] suffix) { bool[] prime = new bool[MAX]; for (int i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for (int i = 2; i * i < MAX; i++) { if (prime[i]) { for (int j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = (int)1e9 + 7; // Precomputing Prefix array. for (int i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for (int i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } } } // Function to solve each query static int query(int[] prefix, int[] suffix, int L, int R) { if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; } } // Driven Program public static void Main() { int q = 3; int[] L = { 2, 2, 24 }; int[] R = { 5, 2, 28 }; int[] prefix = new int[MAX]; int[] suffix = new int[MAX]; precompute(prefix, suffix); for (int i = 0; i < q; i++) { Console.WriteLine( query(prefix, suffix, L[i], R[i])); } }} /*This code is contributed by 29AjayKumar*/", "e": 33704, "s": 31875, "text": null }, { "code": "<?php// PHP program to find maximum differences// between two prime numbers in given ranges$MAX = 100005; // Precompute Sieve, Prefix array,// Suffix arrayfunction precompute(&$prefix, &$suffix){ global $MAX; $prime = array_fill(0, $MAX, true); // Sieve of Eratosthenes for ($i = 2; $i * $i < $MAX; $i++) { if ($prime[$i]) { for ($j = $i * $i; $j < $MAX; $j += $i) $prime[$j] = false; } } $prefix[1] = 1; $suffix[$MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for ($i = 2; $i < $MAX; $i++) { if ($prime[$i]) $prefix[$i] = $i; else $prefix[$i] = $prefix[$i - 1]; } // Precompute Suffix array. for ($i = $MAX - 1; $i > 1; $i--) { if ($prime[$i]) $suffix[$i] = $i; else $suffix[$i] = $suffix[$i + 1]; }} // Function to solve each queryfunction query($prefix, $suffix, $L, $R){ if ($prefix[$R] < $L || $suffix[$L] > $R) return 0; else return $prefix[$R] - $suffix[$L];} // Driver Code$q = 3;$L = array( 2, 2, 24 );$R = array( 5, 2, 28 ); $prefix = array_fill(0, $MAX + 1, 0);$suffix = array_fill(0, $MAX + 1, 0);precompute($prefix, $suffix); for ($i = 0; $i < $q; $i++) echo query($prefix, $suffix, $L[$i], $R[$i]) . \"\\n\"; // This code is contributed by mits?>", "e": 35089, "s": 33704, "text": null }, { "code": "<script> // JavaScript program to find maximum// differences between two prime// numbers in given ranges let MAX = 100005; // Precompute Sieve, Prefix array, Suffix arrayfunction precompute(prefix, suffix){ let prime = []; for(let i = 0; i < MAX; i++) { prime[i] = true; } // Sieve of Eratosthenes for(let i = 2; i * i < MAX; i++) { if (prime[i]) { for(let j = i * i; j < MAX; j += i) { prime[j] = false; } } } prefix[1] = 1; suffix[MAX - 1] = 1e9 + 7; // Precomputing Prefix array. for(let i = 2; i < MAX; i++) { if (prime[i]) { prefix[i] = i; } else { prefix[i] = prefix[i - 1]; } } // Precompute Suffix array. for(let i = MAX - 2; i > 1; i--) { if (prime[i]) { suffix[i] = i; } else { suffix[i] = suffix[i + 1]; } }} // Function to solve each queryfunction query(prefix, suffix, L, R){ if (prefix[R] < L || suffix[L] > R) { return 0; } else { return prefix[R] - suffix[L]; }} // Driver Codelet q = 3;let L = [ 2, 2, 24 ];let R = [ 5, 2, 28 ];let prefix = [], suffix = []; precompute(prefix, suffix); for(let i = 0; i < q; i++){ document.write(query(prefix, suffix, L[i], R[i]) + \"<br/>\");} // This code is contributed by sanjoy_62 </script>", "e": 36555, "s": 35089, "text": null }, { "code": null, "e": 36564, "s": 36555, "text": "Output: " }, { "code": null, "e": 36571, "s": 36564, "text": "3\n0\n0 " }, { "code": null, "e": 36583, "s": 36571, "text": "sourabh1031" }, { "code": null, "e": 36593, "s": 36583, "text": "Rajput-Ji" }, { "code": null, "e": 36605, "s": 36593, "text": "29AjayKumar" }, { "code": null, "e": 36618, "s": 36605, "text": "Mithun Kumar" }, { "code": null, "e": 36635, "s": 36618, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36650, "s": 36635, "text": "shivamagrawal3" }, { "code": null, "e": 36660, "s": 36650, "text": "sanjoy_62" }, { "code": null, "e": 36674, "s": 36660, "text": "coding_pandaa" }, { "code": null, "e": 36687, "s": 36674, "text": "Prime Number" }, { "code": null, "e": 36693, "s": 36687, "text": "sieve" }, { "code": null, "e": 36706, "s": 36693, "text": "Mathematical" }, { "code": null, "e": 36719, "s": 36706, "text": "Mathematical" }, { "code": null, "e": 36732, "s": 36719, "text": "Prime Number" }, { "code": null, "e": 36738, "s": 36732, "text": "sieve" }, { "code": null, "e": 36836, "s": 36738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36880, "s": 36836, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 36911, "s": 36880, "text": "Modular multiplicative inverse" }, { "code": null, "e": 36936, "s": 36911, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 36968, "s": 36936, "text": "Check if a number is Palindrome" }, { "code": null, "e": 37010, "s": 36968, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 37054, "s": 37010, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 37118, "s": 37054, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 37164, "s": 37118, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 37199, "s": 37164, "text": "Singular Value Decomposition (SVD)" } ]
Practice questions on Height balanced/AVL Tree - GeeksforGeeks
07 Feb, 2018 AVL tree is binary search tree with additional property that difference between height of left sub-tree and right sub-tree of any node can’t be more than 1. Here are some key points about AVL trees: If there are n nodes in AVL tree, minimum height of AVL tree is floor(log2n). If there are n nodes in AVL tree, maximum height can’t exceed 1.44*log2n. If height of AVL tree is h, maximum number of nodes can be 2h+1 – 1. Minimum number of nodes in a tree with height h can be represented as:N(h) = N(h-1) + N(h-2) + 1 for n>2 where N(0) = 1 and N(1) = 2. The complexity of searching, inserting and deletion in AVL tree is O(log n). We have discussed types of questions based on AVL trees. Type 1: Relationship between number of nodes and height of AVL tree –Given number of nodes, the question can be asked to find minimum and maximum height of AVL tree. Also, given the height, maximum or minimum number of nodes can be asked. Que – 1. What is the maximum height of any AVL-tree with 7 nodes? Assume that the height of a tree with a single node is 0.(A) 2(B) 3(C) 4(D) 5 Solution: For finding maximum height, the nodes should be minimum at each level. Assumingheight as 2, minimum number of nodes required:N(h) = N(h-1) + N(h-2) + 1N(2) = N(1) + N(0) + 1 = 2 + 1 + 1 = 4.It means, height 2 is achieved using minimum 4 nodes. Assuming height as 3, minimum number of nodes required:N(h) = N(h-1) + N(h-2) + 1N(3) = N(2) + N(1) + 1 = 4 + 2 + 1 = 7.It means, height 3 is achieved using minimum 7 nodes. Therefore, using 7 nodes, we can achieve maximum height as 3. Following is the AVL tree with 7 nodes and height 3. Que – 2. What is the worst case possible height of AVL tree?(A) 2*logn(B) 1.44*log n(C) Depends upon implementation(D) θ(n) Solution: The worst case possible height of AVL tree with n nodes is 1.44*logn. This can be verified using AVL tree having 7 nodes and maximum height. Checking for option (A), 2*log7 = 5.6, however height of tree is 3.Checking for option (B), 1.44*log7 = 4, which is near to 3.Checking for option (D), n = 7, however height of tree is 3.Out of these, option (B) is the best possible answer. Type 2: Based on complexity of insertion, deletion and searching in AVL tree – Que – 3. Which of the following is TRUE?(A) The cost of searching an AVL tree is θ(log n) but that of a binary search tree is O(n)(B) The cost of searching an AVL tree is θ(log n) but that of a complete binary tree is θ(n log n)(C) The cost of searching a binary search tree is O(log n ) but that of an AVL tree is θ(n)(D) The cost of searching an AVL tree is θ(n log n) but that of a binary search tree is O(n) Solution: AVL tree’s time complexity of searching, insertion and deletion = O(logn). But a binary search tree, may be skewed tree, so in worst case BST searching, insertion and deletion complexity = O(n). Que – 4. The worst case running time to search for an element in a balanced in a binary search tree with n*2^n elements is Solution: Time taken to search an element is Θ(logn) where n is number of elements in AVL tree.As number of elements given is n*2^n, the searching complexity will be Θ(log(n*2^n)) which can be written as: = Θ(log(n*2^n)) = Θ(log(n)) + Θ(log(2^n)) = Θ(log(n)) + Θ(nlog(2)) = Θ(log(n)) + Θ(n) As logn is asymptotically smaller than n, Θ(log(n)) + Θ(n) can be written as Θ(n) which matches option C. Type 3: Insertion and Deletion in AVL tree –The question can be asked on the resultant tree when keys are inserted or deleted from AVL tree. Appropriate rotations need to be made if balance factor is disturbed. Que – 5. Consider the following AVL tree.Which of the following is updated AVL tree after insertion of 70? (A) (B) (C) (D) None Solution: The element is first inserted in the same way as BST. Therefore after insertion of 70, BST can be shown as: However, balance factor is disturbed requiring RL rotation. To remove RL rotation, it is first converted into RR rotation as:After removal of RR rotation, AVL tree generated is same as option (C). GATE CS MCQ Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Difference between Clustered and Non-clustered index Introduction of Process Synchronization User Datagram Protocol (UDP) Data Structures and Algorithms | Set 25 Operating Systems | Set 1 Computer Networks | Set 1 Computer Networks | Set 2 Database Management Systems | Set 1
[ { "code": null, "e": 24582, "s": 24554, "text": "\n07 Feb, 2018" }, { "code": null, "e": 24781, "s": 24582, "text": "AVL tree is binary search tree with additional property that difference between height of left sub-tree and right sub-tree of any node can’t be more than 1. Here are some key points about AVL trees:" }, { "code": null, "e": 24859, "s": 24781, "text": "If there are n nodes in AVL tree, minimum height of AVL tree is floor(log2n)." }, { "code": null, "e": 24933, "s": 24859, "text": "If there are n nodes in AVL tree, maximum height can’t exceed 1.44*log2n." }, { "code": null, "e": 25002, "s": 24933, "text": "If height of AVL tree is h, maximum number of nodes can be 2h+1 – 1." }, { "code": null, "e": 25136, "s": 25002, "text": "Minimum number of nodes in a tree with height h can be represented as:N(h) = N(h-1) + N(h-2) + 1 for n>2 where N(0) = 1 and N(1) = 2." }, { "code": null, "e": 25213, "s": 25136, "text": "The complexity of searching, inserting and deletion in AVL tree is O(log n)." }, { "code": null, "e": 25270, "s": 25213, "text": "We have discussed types of questions based on AVL trees." }, { "code": null, "e": 25509, "s": 25270, "text": "Type 1: Relationship between number of nodes and height of AVL tree –Given number of nodes, the question can be asked to find minimum and maximum height of AVL tree. Also, given the height, maximum or minimum number of nodes can be asked." }, { "code": null, "e": 25653, "s": 25509, "text": "Que – 1. What is the maximum height of any AVL-tree with 7 nodes? Assume that the height of a tree with a single node is 0.(A) 2(B) 3(C) 4(D) 5" }, { "code": null, "e": 25907, "s": 25653, "text": "Solution: For finding maximum height, the nodes should be minimum at each level. Assumingheight as 2, minimum number of nodes required:N(h) = N(h-1) + N(h-2) + 1N(2) = N(1) + N(0) + 1 = 2 + 1 + 1 = 4.It means, height 2 is achieved using minimum 4 nodes." }, { "code": null, "e": 26081, "s": 25907, "text": "Assuming height as 3, minimum number of nodes required:N(h) = N(h-1) + N(h-2) + 1N(3) = N(2) + N(1) + 1 = 4 + 2 + 1 = 7.It means, height 3 is achieved using minimum 7 nodes." }, { "code": null, "e": 26196, "s": 26081, "text": "Therefore, using 7 nodes, we can achieve maximum height as 3. Following is the AVL tree with 7 nodes and height 3." }, { "code": null, "e": 26320, "s": 26196, "text": "Que – 2. What is the worst case possible height of AVL tree?(A) 2*logn(B) 1.44*log n(C) Depends upon implementation(D) θ(n)" }, { "code": null, "e": 26471, "s": 26320, "text": "Solution: The worst case possible height of AVL tree with n nodes is 1.44*logn. This can be verified using AVL tree having 7 nodes and maximum height." }, { "code": null, "e": 26711, "s": 26471, "text": "Checking for option (A), 2*log7 = 5.6, however height of tree is 3.Checking for option (B), 1.44*log7 = 4, which is near to 3.Checking for option (D), n = 7, however height of tree is 3.Out of these, option (B) is the best possible answer." }, { "code": null, "e": 26790, "s": 26711, "text": "Type 2: Based on complexity of insertion, deletion and searching in AVL tree –" }, { "code": null, "e": 27202, "s": 26790, "text": "Que – 3. Which of the following is TRUE?(A) The cost of searching an AVL tree is θ(log n) but that of a binary search tree is O(n)(B) The cost of searching an AVL tree is θ(log n) but that of a complete binary tree is θ(n log n)(C) The cost of searching a binary search tree is O(log n ) but that of an AVL tree is θ(n)(D) The cost of searching an AVL tree is θ(n log n) but that of a binary search tree is O(n)" }, { "code": null, "e": 27407, "s": 27202, "text": "Solution: AVL tree’s time complexity of searching, insertion and deletion = O(logn). But a binary search tree, may be skewed tree, so in worst case BST searching, insertion and deletion complexity = O(n)." }, { "code": null, "e": 27530, "s": 27407, "text": "Que – 4. The worst case running time to search for an element in a balanced in a binary search tree with n*2^n elements is" }, { "code": null, "e": 27735, "s": 27530, "text": "Solution: Time taken to search an element is Θ(logn) where n is number of elements in AVL tree.As number of elements given is n*2^n, the searching complexity will be Θ(log(n*2^n)) which can be written as:" }, { "code": null, "e": 27822, "s": 27735, "text": "= Θ(log(n*2^n))\n= Θ(log(n)) + Θ(log(2^n))\n= Θ(log(n)) + Θ(nlog(2))\n= Θ(log(n)) + Θ(n)\n" }, { "code": null, "e": 27928, "s": 27822, "text": "As logn is asymptotically smaller than n, Θ(log(n)) + Θ(n) can be written as Θ(n) which matches option C." }, { "code": null, "e": 28139, "s": 27928, "text": "Type 3: Insertion and Deletion in AVL tree –The question can be asked on the resultant tree when keys are inserted or deleted from AVL tree. Appropriate rotations need to be made if balance factor is disturbed." }, { "code": null, "e": 28246, "s": 28139, "text": "Que – 5. Consider the following AVL tree.Which of the following is updated AVL tree after insertion of 70?" }, { "code": null, "e": 28250, "s": 28246, "text": "(A)" }, { "code": null, "e": 28254, "s": 28250, "text": "(B)" }, { "code": null, "e": 28258, "s": 28254, "text": "(C)" }, { "code": null, "e": 28267, "s": 28258, "text": "(D) None" }, { "code": null, "e": 28385, "s": 28267, "text": "Solution: The element is first inserted in the same way as BST. Therefore after insertion of 70, BST can be shown as:" }, { "code": null, "e": 28582, "s": 28385, "text": "However, balance factor is disturbed requiring RL rotation. To remove RL rotation, it is first converted into RR rotation as:After removal of RR rotation, AVL tree generated is same as option (C)." }, { "code": null, "e": 28590, "s": 28582, "text": "GATE CS" }, { "code": null, "e": 28594, "s": 28590, "text": "MCQ" }, { "code": null, "e": 28599, "s": 28594, "text": "Tree" }, { "code": null, "e": 28604, "s": 28599, "text": "Tree" }, { "code": null, "e": 28702, "s": 28604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28736, "s": 28702, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 28777, "s": 28736, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 28830, "s": 28777, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 28870, "s": 28830, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 28899, "s": 28870, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 28939, "s": 28899, "text": "Data Structures and Algorithms | Set 25" }, { "code": null, "e": 28965, "s": 28939, "text": "Operating Systems | Set 1" }, { "code": null, "e": 28991, "s": 28965, "text": "Computer Networks | Set 1" }, { "code": null, "e": 29017, "s": 28991, "text": "Computer Networks | Set 2" } ]
Find K distinct positive odd integers with sum N - GeeksforGeeks
21 Apr, 2021 Given two integers N and K, the task is to find K distinct positive odd integers such that their sum is equal to the given number N.Examples: Input: N = 10, K = 2 Output: 1 9 Explanation: Two odd positive integers such that their sum is 10 can be (1, 9) or (3, 7).Input: N = 10, K = 4 Output: NO Explanation: There does not exists four odd positive integers with sum 10. Approach: The number N can be represented as the sum of K positive odd integers only is the following two conditions satisfies: If the square of K is less than or equal to N and,If the sum of N and K is an even number. If the square of K is less than or equal to N and, If the sum of N and K is an even number. If these conditions are satisfied then there exist K positive odd integers whose sum is N.To generate K such odd numbers: Print first K-1 odd numbers starting from 1, i.e. 1, 3, 5, 7, 9....... The last odd number will be : N – (Sum of first K-1 odd positive integers) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find K// odd positive integers such that// their sum is equal to given number #include <bits/stdc++.h>using namespace std; #define ll long long int // Function to find K odd positive// integers such that their sum is Nvoid findDistinctOddSum(ll n, ll k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ cout << val << " "; sum += val; val += 2; } cout << n - sum << endl; } else cout << "NO \n";} // Driver Codeint main(){ ll n = 100; ll k = 4; findDistinctOddSum(n, k); return 0;} // Java implementation to find K// odd positive integers such that// their sum is equal to given numberimport java.util.*; class GFG{ // Function to find K odd positive// integers such that their sum is Nstatic void findDistinctOddSum(int n, int k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ System.out.print(val+ " "); sum += val; val += 2; } System.out.print(n - sum +"\n"); } else System.out.print("NO \n");} // Driver Codepublic static void main(String[] args){ int n = 100; int k = 4; findDistinctOddSum(n, k);}} // This code is contributed by PrinciRaj1992 # Python3 implementation to find K# odd positive integers such that# their summ is equal to given number # Function to find K odd positive# integers such that their summ is Ndef findDistinctOddsumm(n, k): # Condition to check if there # are enough values to check if ((k * k) <= n and (n + k) % 2 == 0): val = 1 summ = 0 for i in range(1, k): print(val, end = " ") summ += val val += 2 print(n - summ) else: print("NO") # Driver Coden = 100k = 4findDistinctOddsumm(n, k) # This code is contributed by shubhamsingh10 // C# implementation to find K// odd positive integers such that// their sum is equal to given numberusing System; public class GFG{ // Function to find K odd positive// integers such that their sum is Nstatic void findDistinctOddSum(int n, int k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ Console.Write(val+ " "); sum += val; val += 2; } Console.Write(n - sum +"\n"); } else Console.Write("NO \n");} // Driver Codepublic static void Main(String[] args){ int n = 100; int k = 4; findDistinctOddSum(n, k);}}// This code is contributed by 29AjayKumar <script> // Function to find K odd positive// integers such that their sum is Nfunction findDistinctOddSum(n,k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ var val = 1; var sum = 0; for(var i = 1; i < k; i++){ document.write( val+ " "); sum += val; val += 2; } document.write( n - sum) ; } else document.write( "NO \n");} // Driver Codevar n = 100; var k = 4; findDistinctOddSum(n, k); </script> 1 3 5 91 Performance Analysis: Time Complexity: In the above-given approach, there is one loop which takes O(K) time in the worst case. Therefore, the time complexity for this approach will be O(K). Auxiliary Space: O(1) SHUBHAMSINGH10 princiraj1992 29AjayKumar akshitsaxenaa09 Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Program for Decimal to Binary Conversion Program to find sum of elements in a given array Sieve of Eratosthenes The Knight's tour problem | Backtracking-1 Program for factorial of a number Find all factors of a natural number | Set 1
[ { "code": null, "e": 24944, "s": 24916, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25088, "s": 24944, "text": "Given two integers N and K, the task is to find K distinct positive odd integers such that their sum is equal to the given number N.Examples: " }, { "code": null, "e": 25319, "s": 25088, "text": "Input: N = 10, K = 2 Output: 1 9 Explanation: Two odd positive integers such that their sum is 10 can be (1, 9) or (3, 7).Input: N = 10, K = 4 Output: NO Explanation: There does not exists four odd positive integers with sum 10. " }, { "code": null, "e": 25451, "s": 25321, "text": "Approach: The number N can be represented as the sum of K positive odd integers only is the following two conditions satisfies: " }, { "code": null, "e": 25542, "s": 25451, "text": "If the square of K is less than or equal to N and,If the sum of N and K is an even number." }, { "code": null, "e": 25593, "s": 25542, "text": "If the square of K is less than or equal to N and," }, { "code": null, "e": 25634, "s": 25593, "text": "If the sum of N and K is an even number." }, { "code": null, "e": 25758, "s": 25634, "text": "If these conditions are satisfied then there exist K positive odd integers whose sum is N.To generate K such odd numbers: " }, { "code": null, "e": 25829, "s": 25758, "text": "Print first K-1 odd numbers starting from 1, i.e. 1, 3, 5, 7, 9......." }, { "code": null, "e": 25904, "s": 25829, "text": "The last odd number will be : N – (Sum of first K-1 odd positive integers)" }, { "code": null, "e": 25957, "s": 25904, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25961, "s": 25957, "text": "C++" }, { "code": null, "e": 25966, "s": 25961, "text": "Java" }, { "code": null, "e": 25974, "s": 25966, "text": "Python3" }, { "code": null, "e": 25977, "s": 25974, "text": "C#" }, { "code": null, "e": 25988, "s": 25977, "text": "Javascript" }, { "code": "// C++ implementation to find K// odd positive integers such that// their sum is equal to given number #include <bits/stdc++.h>using namespace std; #define ll long long int // Function to find K odd positive// integers such that their sum is Nvoid findDistinctOddSum(ll n, ll k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ cout << val << \" \"; sum += val; val += 2; } cout << n - sum << endl; } else cout << \"NO \\n\";} // Driver Codeint main(){ ll n = 100; ll k = 4; findDistinctOddSum(n, k); return 0;}", "e": 26710, "s": 25988, "text": null }, { "code": "// Java implementation to find K// odd positive integers such that// their sum is equal to given numberimport java.util.*; class GFG{ // Function to find K odd positive// integers such that their sum is Nstatic void findDistinctOddSum(int n, int k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ System.out.print(val+ \" \"); sum += val; val += 2; } System.out.print(n - sum +\"\\n\"); } else System.out.print(\"NO \\n\");} // Driver Codepublic static void main(String[] args){ int n = 100; int k = 4; findDistinctOddSum(n, k);}} // This code is contributed by PrinciRaj1992", "e": 27493, "s": 26710, "text": null }, { "code": "# Python3 implementation to find K# odd positive integers such that# their summ is equal to given number # Function to find K odd positive# integers such that their summ is Ndef findDistinctOddsumm(n, k): # Condition to check if there # are enough values to check if ((k * k) <= n and (n + k) % 2 == 0): val = 1 summ = 0 for i in range(1, k): print(val, end = \" \") summ += val val += 2 print(n - summ) else: print(\"NO\") # Driver Coden = 100k = 4findDistinctOddsumm(n, k) # This code is contributed by shubhamsingh10", "e": 28095, "s": 27493, "text": null }, { "code": "// C# implementation to find K// odd positive integers such that// their sum is equal to given numberusing System; public class GFG{ // Function to find K odd positive// integers such that their sum is Nstatic void findDistinctOddSum(int n, int k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ int val = 1; int sum = 0; for(int i = 1; i < k; i++){ Console.Write(val+ \" \"); sum += val; val += 2; } Console.Write(n - sum +\"\\n\"); } else Console.Write(\"NO \\n\");} // Driver Codepublic static void Main(String[] args){ int n = 100; int k = 4; findDistinctOddSum(n, k);}}// This code is contributed by 29AjayKumar", "e": 28867, "s": 28095, "text": null }, { "code": "<script> // Function to find K odd positive// integers such that their sum is Nfunction findDistinctOddSum(n,k){ // Condition to check if there // are enough values to check if ((k * k) <= n && (n + k) % 2 == 0){ var val = 1; var sum = 0; for(var i = 1; i < k; i++){ document.write( val+ \" \"); sum += val; val += 2; } document.write( n - sum) ; } else document.write( \"NO \\n\");} // Driver Codevar n = 100; var k = 4; findDistinctOddSum(n, k); </script>", "e": 29425, "s": 28867, "text": null }, { "code": null, "e": 29434, "s": 29425, "text": "1 3 5 91" }, { "code": null, "e": 29458, "s": 29434, "text": "Performance Analysis: " }, { "code": null, "e": 29626, "s": 29458, "text": "Time Complexity: In the above-given approach, there is one loop which takes O(K) time in the worst case. Therefore, the time complexity for this approach will be O(K)." }, { "code": null, "e": 29648, "s": 29626, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29665, "s": 29650, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 29679, "s": 29665, "text": "princiraj1992" }, { "code": null, "e": 29691, "s": 29679, "text": "29AjayKumar" }, { "code": null, "e": 29707, "s": 29691, "text": "akshitsaxenaa09" }, { "code": null, "e": 29720, "s": 29707, "text": "Mathematical" }, { "code": null, "e": 29739, "s": 29720, "text": "Technical Scripter" }, { "code": null, "e": 29752, "s": 29739, "text": "Mathematical" }, { "code": null, "e": 29850, "s": 29752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29859, "s": 29850, "text": "Comments" }, { "code": null, "e": 29872, "s": 29859, "text": "Old Comments" }, { "code": null, "e": 29896, "s": 29872, "text": "Merge two sorted arrays" }, { "code": null, "e": 29939, "s": 29896, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29953, "s": 29939, "text": "Prime Numbers" }, { "code": null, "e": 29995, "s": 29953, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30036, "s": 29995, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30085, "s": 30036, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30107, "s": 30085, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30150, "s": 30107, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30184, "s": 30150, "text": "Program for factorial of a number" } ]
How to get the IP address of the Android device programmatically using Kotlin?
This example demonstrates how to get the IP address of the Android device programmatically using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:id="@+id/getIPAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textAlignment="center" android:textColor="@android:color/background_dark" android:text="IP address of your Device" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Context import android.net.wifi.WifiManager import android.os.Bundle import android.text.format.Formatter import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val textView: TextView = findViewById(R.id.getIPAddress) val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val ipAddress: String = Formatter.formatIpAddress(wifiManager.connectionInfo.ipAddress) textView.text = "Your Device IP Address: $ipAddress" } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1167, "s": 1062, "text": "This example demonstrates how to get the IP address of the Android device programmatically using Kotlin." }, { "code": null, "e": 1296, "s": 1167, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1361, "s": 1296, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2398, "s": 1361, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/getIPAddress\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:text=\"IP address of your Device\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2453, "s": 2398, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3192, "s": 2453, "text": "import android.content.Context\nimport android.net.wifi.WifiManager\nimport android.os.Bundle\nimport android.text.format.Formatter\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val textView: TextView = findViewById(R.id.getIPAddress)\n val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager\n val ipAddress: String = Formatter.formatIpAddress(wifiManager.connectionInfo.ipAddress)\n textView.text = \"Your Device IP Address: $ipAddress\"\n }\n}" }, { "code": null, "e": 3247, "s": 3192, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3992, "s": 3247, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4340, "s": 3992, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Count prime numbers in range [L, R] whose single digit sum is also prime - GeeksforGeeks
19 Jan, 2022 Given two integers L and R. The task is to count the prime numbers in the range [L, R], whose single sum is also a prime number. A single sum is obtained by adding the digits of a number until a single digit is left. Examples Input: L = 5, R = 20 Output: 3Explanation: Prime numbers in the range L = 5 to R = 20 are {5, 7, 11, 13, 17, 19}Their “single sum” of digits is {5, 7, 2, 4, 8, 1}. Only {5, 7, 2} are prime. Hence the answer is 3. Input: L = 1, R = 10 Output: 4Explanation: Prime numbers in the range L = 1 to R = 10 are {2, 3, 5, 7}. Their “single sum” of digits is {2, 3, 5, 7}. Since all the numbers are prime, hence the answer is 4. Approach: The naive approach is to iterate for each number in the range [L, R] and check if the number is prime or not. If the number is prime, find the single sum of its digits and again check whether the single sum is prime or not. If the single sum is prime, then increment the counter and print the current element in the range [L, R]. Below is the implementation of the above approach. C++14 Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to check whether number// is prime or notbool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true;} // Function to find single digit sumint SingleDigitSum(int& n){ if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9;} // Function to find single digit primesint countSingleDigitPrimes(int l, int r){ int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count;} // Driver Codeint main(){ // Input range int L = 1, R = 10; // Function Call cout << countSingleDigitPrimes(L, R); return 0;} // Java program to implement// the above approachclass GFG{ // Function to check whether number // is prime or not static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum static int SingleDigitSum(int n) { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes static int countSingleDigitPrimes(int l, int r) { int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code public static void main(String args[]) { // Input range int L = 1, R = 10; // Function Call System.out.println(countSingleDigitPrimes(L, R)); }} // This code is contributed by gfgking # Python program for above approachimport math # Function to check whether number# is prime or notdef isPrime(n): # Corner case if n <= 1: return False # Check from 2 to square root of n for i in range(2, math.floor(math.sqrt(n)) + 1): if n % i == 0: return False return True # Function to find single digit sumdef SingleDigitSum(n): if n <= 9: return n return 9 if (n % 9 == 0) else n % 9 # Function to find single digit primesdef countSingleDigitPrimes(l, r): count = 0 i = None for i in range(l, r + 1): if isPrime(i) and isPrime(SingleDigitSum(i)): count += 1 return count # Driver Code # Input rangeL = 1R = 10 # Function Callprint(countSingleDigitPrimes(L, R)) # This code is contributed by gfgking // C# program to implement// the above approachusing System;class GFG{ // Function to check whether number // is prime or not static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= Math.Sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum static int SingleDigitSum(int n) { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes static int countSingleDigitPrimes(int l, int r) { int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code public static void Main() { // Input range int L = 1, R = 10; // Function Call Console.Write(countSingleDigitPrimes(L, R)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript program for above approach // Function to check whether number // is prime or not const isPrime = (n) => { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (let i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum const SingleDigitSum = (n) => { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes const countSingleDigitPrimes = (l, r) => { let count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code // Input range let L = 1, R = 10; // Function Call document.write(countSingleDigitPrimes(L, R)); // This code is contributed by rakeshsahni </script> 4 Time Complexity: O((R – L)*N^(1/2)) where N is the prime number in the range [L, R]. Auxiliary Space: O(1) rakeshsahni gfgking samim2000 germanshephered48 Algo-Geek 2021 array-range-queries Prime Number Algo Geek Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find simple moving average | Set-2 Divide given number into two even parts Check if the given string is valid English word or not Count of Palindrome Strings in given Array of strings Sorting given character Array using Linked List Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25937, "s": 25909, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26154, "s": 25937, "text": "Given two integers L and R. The task is to count the prime numbers in the range [L, R], whose single sum is also a prime number. A single sum is obtained by adding the digits of a number until a single digit is left." }, { "code": null, "e": 26163, "s": 26154, "text": "Examples" }, { "code": null, "e": 26377, "s": 26163, "text": "Input: L = 5, R = 20 Output: 3Explanation: Prime numbers in the range L = 5 to R = 20 are {5, 7, 11, 13, 17, 19}Their “single sum” of digits is {5, 7, 2, 4, 8, 1}. Only {5, 7, 2} are prime. Hence the answer is 3." }, { "code": null, "e": 26586, "s": 26377, "text": "Input: L = 1, R = 10 Output: 4Explanation: Prime numbers in the range L = 1 to R = 10 are {2, 3, 5, 7}. Their “single sum” of digits is {2, 3, 5, 7}. Since all the numbers are prime, hence the answer is 4." }, { "code": null, "e": 26927, "s": 26586, "text": "Approach: The naive approach is to iterate for each number in the range [L, R] and check if the number is prime or not. If the number is prime, find the single sum of its digits and again check whether the single sum is prime or not. If the single sum is prime, then increment the counter and print the current element in the range [L, R]." }, { "code": null, "e": 26978, "s": 26927, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26984, "s": 26978, "text": "C++14" }, { "code": null, "e": 26989, "s": 26984, "text": "Java" }, { "code": null, "e": 26997, "s": 26989, "text": "Python3" }, { "code": null, "e": 27000, "s": 26997, "text": "C#" }, { "code": null, "e": 27011, "s": 27000, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to check whether number// is prime or notbool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true;} // Function to find single digit sumint SingleDigitSum(int& n){ if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9;} // Function to find single digit primesint countSingleDigitPrimes(int l, int r){ int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count;} // Driver Codeint main(){ // Input range int L = 1, R = 10; // Function Call cout << countSingleDigitPrimes(L, R); return 0;}", "e": 27888, "s": 27011, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to check whether number // is prime or not static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum static int SingleDigitSum(int n) { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes static int countSingleDigitPrimes(int l, int r) { int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code public static void main(String args[]) { // Input range int L = 1, R = 10; // Function Call System.out.println(countSingleDigitPrimes(L, R)); }} // This code is contributed by gfgking", "e": 28858, "s": 27888, "text": null }, { "code": "# Python program for above approachimport math # Function to check whether number# is prime or notdef isPrime(n): # Corner case if n <= 1: return False # Check from 2 to square root of n for i in range(2, math.floor(math.sqrt(n)) + 1): if n % i == 0: return False return True # Function to find single digit sumdef SingleDigitSum(n): if n <= 9: return n return 9 if (n % 9 == 0) else n % 9 # Function to find single digit primesdef countSingleDigitPrimes(l, r): count = 0 i = None for i in range(l, r + 1): if isPrime(i) and isPrime(SingleDigitSum(i)): count += 1 return count # Driver Code # Input rangeL = 1R = 10 # Function Callprint(countSingleDigitPrimes(L, R)) # This code is contributed by gfgking", "e": 29652, "s": 28858, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to check whether number // is prime or not static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (int i = 2; i <= Math.Sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum static int SingleDigitSum(int n) { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes static int countSingleDigitPrimes(int l, int r) { int count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code public static void Main() { // Input range int L = 1, R = 10; // Function Call Console.Write(countSingleDigitPrimes(L, R)); }} // This code is contributed by Samim Hossain Mondal.", "e": 30626, "s": 29652, "text": null }, { "code": "<script> // JavaScript program for above approach // Function to check whether number // is prime or not const isPrime = (n) => { // Corner case if (n <= 1) return false; // Check from 2 to square root of n for (let i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function to find single digit sum const SingleDigitSum = (n) => { if (n <= 9) return n; return (n % 9 == 0) ? 9 : n % 9; } // Function to find single digit primes const countSingleDigitPrimes = (l, r) => { let count = 0, i; for (i = l; i <= r; i++) { if (isPrime(i) && isPrime(SingleDigitSum(i))) { count++; } } return count; } // Driver Code // Input range let L = 1, R = 10; // Function Call document.write(countSingleDigitPrimes(L, R)); // This code is contributed by rakeshsahni </script>", "e": 31648, "s": 30626, "text": null }, { "code": null, "e": 31650, "s": 31648, "text": "4" }, { "code": null, "e": 31758, "s": 31650, "text": " Time Complexity: O((R – L)*N^(1/2)) where N is the prime number in the range [L, R]. Auxiliary Space: O(1)" }, { "code": null, "e": 31772, "s": 31760, "text": "rakeshsahni" }, { "code": null, "e": 31780, "s": 31772, "text": "gfgking" }, { "code": null, "e": 31790, "s": 31780, "text": "samim2000" }, { "code": null, "e": 31808, "s": 31790, "text": "germanshephered48" }, { "code": null, "e": 31823, "s": 31808, "text": "Algo-Geek 2021" }, { "code": null, "e": 31843, "s": 31823, "text": "array-range-queries" }, { "code": null, "e": 31856, "s": 31843, "text": "Prime Number" }, { "code": null, "e": 31866, "s": 31856, "text": "Algo Geek" }, { "code": null, "e": 31879, "s": 31866, "text": "Mathematical" }, { "code": null, "e": 31892, "s": 31879, "text": "Mathematical" }, { "code": null, "e": 31905, "s": 31892, "text": "Prime Number" }, { "code": null, "e": 32003, "s": 31905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32012, "s": 32003, "text": "Comments" }, { "code": null, "e": 32025, "s": 32012, "text": "Old Comments" }, { "code": null, "e": 32071, "s": 32025, "text": "Program to find simple moving average | Set-2" }, { "code": null, "e": 32111, "s": 32071, "text": "Divide given number into two even parts" }, { "code": null, "e": 32166, "s": 32111, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 32220, "s": 32166, "text": "Count of Palindrome Strings in given Array of strings" }, { "code": null, "e": 32268, "s": 32220, "text": "Sorting given character Array using Linked List" }, { "code": null, "e": 32298, "s": 32268, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32313, "s": 32298, "text": "C++ Data Types" }, { "code": null, "e": 32373, "s": 32313, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32416, "s": 32373, "text": "Set in C++ Standard Template Library (STL)" } ]
Valid String | Practice | GeeksforGeeks
Given binary string str of size N the task is to check if the given string is valid or not. A string is called valid if the number of 0's equals the number of 1's and at any moment starting from the left of the string number 0's must be greater than or equals to the number of 1's. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. 3. The next line contains a binary string without spaces. Output: For each test case, print "yes" if string is valid. Otherwise, print "no" (without quotes) Constraints: 1. 1 <= T <= 100 2. 1 <= N <= 104 3. '0' <= str[i] <= '1' Example: Input: 2 4 0011 3 001 Output: yes no Explanation: Test Case 1: String has an equal number of ones and zeros and at each index(starting from left) the number of occurrences of 0's is greater than or equals to the number of occurrences 1's. 0 dipawalimandaokar3212 months ago Why this solution is wrong? #include <iostream>using namespace std; void is_valid(string s,int n){ int c1=0,c0=0;for(int i=0;i<n;i++){ if( s[i]=='0') c0++; else c1++;}if(c1==c0)cout<<"yes"<<endl;elsecout<<"no"<<endl;} int main() {int t,n;string s;cin>>t;while(t--){ cin>>n; cin>>s; if(n%2!=0) cout<<"no"; else is_valid(s,n); } return 0;} 0 dipawalimandaokar3212 months ago What's wrong with this code?please tell me! #include <iostream>using namespace std;bool is_valid_string(string str,int N){int count0,count1; for(int i=0;i<N;i++){ if(str[i]=='0') count0++;else count1++;} if(count0!=count1)return false; else return true; }int main() {//codeint T,N ;string str ; cin>>T;while(T--){cin>>N;cin>>str; if(is_valid_string(str,N))cout<<"yes"<<endl;elsecout<<"no"<<endl; } return 0;} 0 snipperwolf3 months ago for _ in range(int(input())): n=int(input()) s=input() flag=1 count,count1=0,0 if s.count('0')==s.count('1'): for i in s: if i=='0': count+=1 if i=='1': count1+=1 if count>=count1: continue else: flag=-1 break if flag== -1: print("no") else: print("yes") else: print("no") 0 chessnoobdj3 months ago C++ without extra space #include<iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n, cnt_zero = 0, cnt_one = 0; cin >> n; bool flg = true; for(int i=0; i<n; i++){ char x; cin >> x; cnt_zero += (x == '0') ? 1 : 0; cnt_one += (x == '0') ? 0 : 1; flg = (cnt_zero < cnt_one) ? false : flg; } cout << ((flg && cnt_zero==cnt_one) ? "yes" : "no") << "\n"; } return 0; } 0 avinav26113 months ago Easiest C++ Solution 0 raunakmishra12435 months ago #include<stack> using namespace std; int valid(string s) { stack<char>st; for(int i=0;i<s.length();i++) { if(s[i]=='0') st.push(s[i]); else { if(st.empty()) return 0; else { st.pop(); } } } if(st.empty()) return 1; return 0; } int main() { stack<int>s; int t; cin>>t; while(t--) { int n; cin>>n; string s; cin>>s; if(valid(s)) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; } 0 imranwahid6 months ago Easy C++ solution 0 Mayank Manik This comment was deleted. 0 Mayank Manik This comment was deleted. 0 Om Bohare10 months ago Om Bohare // FOR JAVA TRY THIS // JUST 0.3 SEC //******************************************************// Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0){ int n = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); Stack<character> st = new Stack<>(); boolean q = true; for(int i = 0;i < n; i++){ char ch = s.charAt(i); if(ch == '0'){ st.push(ch); }else{ if(st.size() > 0){ st.pop(); }else{ q = false; break; } } } if(st.size() == 0 && q == true){ System.out.println("yes"); }else{ System.out.println("no"); } t--;} 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": 509, "s": 226, "text": "Given binary string str of size N the task is to check if the given string is valid or not. A string is called valid if the number of 0's equals the number of 1's and at any moment starting from the left of the string number 0's must be greater than or equals to the number of 1's. " }, { "code": null, "e": 776, "s": 509, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N.\n3. The next line contains a binary string without spaces." }, { "code": null, "e": 980, "s": 776, "text": "\nOutput: For each test case, print \"yes\" if string is valid. Otherwise, print \"no\" (without quotes)\n\nConstraints:\n1. 1 <= T <= 100\n2. 1 <= N <= 104\n3. '0' <= str[i] <= '1'\n\nExample:\nInput:\n2\n4\n0011\n3\n001" }, { "code": null, "e": 1198, "s": 980, "text": "Output:\nyes\nno\n\nExplanation:\nTest Case 1: String has an equal number of ones and zeros and at each index(starting from left) the number of occurrences of 0's is greater than or equals to the number of occurrences 1's." }, { "code": null, "e": 1200, "s": 1198, "text": "0" }, { "code": null, "e": 1233, "s": 1200, "text": "dipawalimandaokar3212 months ago" }, { "code": null, "e": 1261, "s": 1233, "text": "Why this solution is wrong?" }, { "code": null, "e": 1301, "s": 1261, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 1457, "s": 1301, "text": "void is_valid(string s,int n){ int c1=0,c0=0;for(int i=0;i<n;i++){ if( s[i]=='0') c0++; else c1++;}if(c1==c0)cout<<\"yes\"<<endl;elsecout<<\"no\"<<endl;}" }, { "code": null, "e": 1597, "s": 1457, "text": "int main() {int t,n;string s;cin>>t;while(t--){ cin>>n; cin>>s; if(n%2!=0) cout<<\"no\"; else is_valid(s,n); } return 0;}" }, { "code": null, "e": 1599, "s": 1597, "text": "0" }, { "code": null, "e": 1632, "s": 1599, "text": "dipawalimandaokar3212 months ago" }, { "code": null, "e": 1676, "s": 1632, "text": "What's wrong with this code?please tell me!" }, { "code": null, "e": 1836, "s": 1676, "text": "#include <iostream>using namespace std;bool is_valid_string(string str,int N){int count0,count1; for(int i=0;i<N;i++){ if(str[i]=='0') count0++;else count1++;}" }, { "code": null, "e": 1868, "s": 1836, "text": "if(count0!=count1)return false;" }, { "code": null, "e": 1886, "s": 1868, "text": "else return true;" }, { "code": null, "e": 1929, "s": 1888, "text": "}int main() {//codeint T,N ;string str ;" }, { "code": null, "e": 1964, "s": 1929, "text": "cin>>T;while(T--){cin>>N;cin>>str;" }, { "code": null, "e": 2030, "s": 1964, "text": "if(is_valid_string(str,N))cout<<\"yes\"<<endl;elsecout<<\"no\"<<endl;" }, { "code": null, "e": 2034, "s": 2032, "text": "}" }, { "code": null, "e": 2045, "s": 2034, "text": "return 0;}" }, { "code": null, "e": 2047, "s": 2045, "text": "0" }, { "code": null, "e": 2071, "s": 2047, "text": "snipperwolf3 months ago" }, { "code": null, "e": 2510, "s": 2071, "text": "for _ in range(int(input())): n=int(input()) s=input() flag=1 count,count1=0,0 if s.count('0')==s.count('1'): for i in s: if i=='0': count+=1 if i=='1': count1+=1 if count>=count1: continue else: flag=-1 break if flag== -1: print(\"no\") else: print(\"yes\") else: print(\"no\")" }, { "code": null, "e": 2512, "s": 2510, "text": "0" }, { "code": null, "e": 2536, "s": 2512, "text": "chessnoobdj3 months ago" }, { "code": null, "e": 2560, "s": 2536, "text": "C++ without extra space" }, { "code": null, "e": 3056, "s": 2560, "text": "#include<iostream>\nusing namespace std;\n\nint main(){\n int t;\n cin >> t;\n while(t--){\n int n, cnt_zero = 0, cnt_one = 0;\n cin >> n;\n bool flg = true;\n for(int i=0; i<n; i++){\n char x;\n cin >> x;\n cnt_zero += (x == '0') ? 1 : 0;\n cnt_one += (x == '0') ? 0 : 1;\n flg = (cnt_zero < cnt_one) ? false : flg;\n }\n cout << ((flg && cnt_zero==cnt_one) ? \"yes\" : \"no\") << \"\\n\";\n }\n return 0;\n}" }, { "code": null, "e": 3058, "s": 3056, "text": "0" }, { "code": null, "e": 3081, "s": 3058, "text": "avinav26113 months ago" }, { "code": null, "e": 3102, "s": 3081, "text": "Easiest C++ Solution" }, { "code": null, "e": 3106, "s": 3104, "text": "0" }, { "code": null, "e": 3135, "s": 3106, "text": "raunakmishra12435 months ago" }, { "code": null, "e": 3710, "s": 3135, "text": "#include<stack>\nusing namespace std;\nint valid(string s)\n{\n \n stack<char>st;\n\tfor(int i=0;i<s.length();i++)\n\t{\n\t if(s[i]=='0')\n\t st.push(s[i]);\n\t else \n\t {\n\t if(st.empty())\n\t return 0;\n\t else\n\t {\n\t st.pop();\n\t \n\t }\n\t \n\t }\n\t \n\t}\n if(st.empty())\n return 1;\n return 0;\n \n}\nint main() {\n\tstack<int>s;\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{ \n\t int n;\n\t cin>>n;\n\t string s;\n\t cin>>s;\n\t if(valid(s))\n\t cout<<\"yes\"<<endl;\n\t else\n\t cout<<\"no\"<<endl;\n }\n\treturn 0;\n}" }, { "code": null, "e": 3712, "s": 3710, "text": "0" }, { "code": null, "e": 3735, "s": 3712, "text": "imranwahid6 months ago" }, { "code": null, "e": 3753, "s": 3735, "text": "Easy C++ solution" }, { "code": null, "e": 3755, "s": 3753, "text": "0" }, { "code": null, "e": 3768, "s": 3755, "text": "Mayank Manik" }, { "code": null, "e": 3794, "s": 3768, "text": "This comment was deleted." }, { "code": null, "e": 3796, "s": 3794, "text": "0" }, { "code": null, "e": 3809, "s": 3796, "text": "Mayank Manik" }, { "code": null, "e": 3835, "s": 3809, "text": "This comment was deleted." }, { "code": null, "e": 3837, "s": 3835, "text": "0" }, { "code": null, "e": 3860, "s": 3837, "text": "Om Bohare10 months ago" }, { "code": null, "e": 3870, "s": 3860, "text": "Om Bohare" }, { "code": null, "e": 3966, "s": 3870, "text": "// FOR JAVA TRY THIS // JUST 0.3 SEC //******************************************************//" }, { "code": null, "e": 4003, "s": 3966, "text": "Scanner sc = new Scanner(System.in);" }, { "code": null, "e": 4025, "s": 4003, "text": "int t = sc.nextInt();" }, { "code": null, "e": 4039, "s": 4025, "text": "while(t > 0){" }, { "code": null, "e": 4079, "s": 4039, "text": " int n = sc.nextInt(); sc.nextLine();" }, { "code": null, "e": 4107, "s": 4079, "text": " String s = sc.nextLine();" }, { "code": null, "e": 4275, "s": 4107, "text": " Stack<character> st = new Stack<>(); boolean q = true; for(int i = 0;i < n; i++){ char ch = s.charAt(i); if(ch == '0'){ st.push(ch); }else{" }, { "code": null, "e": 4327, "s": 4275, "text": " if(st.size() > 0){ st.pop();" }, { "code": null, "e": 4409, "s": 4327, "text": " }else{ q = false; break; } } }" }, { "code": null, "e": 4518, "s": 4409, "text": " if(st.size() == 0 && q == true){ System.out.println(\"yes\"); }else{ System.out.println(\"no\"); }" }, { "code": null, "e": 4528, "s": 4518, "text": " t--;}" }, { "code": null, "e": 4674, "s": 4528, "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": 4710, "s": 4674, "text": " Login to access your submissions. " }, { "code": null, "e": 4720, "s": 4710, "text": "\nProblem\n" }, { "code": null, "e": 4730, "s": 4720, "text": "\nContest\n" }, { "code": null, "e": 4793, "s": 4730, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4941, "s": 4793, "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": 5149, "s": 4941, "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": 5255, "s": 5149, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Fuzzy matching at scale. From 3.7 hours to 0.2 seconds. How to... | by Josh Taylor | Towards Data Science
### Update December 2020: A faster, simpler way of fuzzy matching is now included at the end of this post with the full code to implement it on any dataset### Data in the real world is messy. Dealing with messy data sets is painful and burns through time which could be spent analysing the data itself. This article focuses in on ‘fuzzy’ matching and how this can help to automate significant challenges in a large number of data science workflows through: Deduplication. Aligning similar categories or entities in a data set (for example, we may need to combine ‘D J Trump’, ‘D. Trump’ and ‘Donald Trump’ into the same entity).Record Linkage. Joining data sets on a particular entity (for example, joining records of ‘D J Trump’ to a URL of his Wikipedia page). Deduplication. Aligning similar categories or entities in a data set (for example, we may need to combine ‘D J Trump’, ‘D. Trump’ and ‘Donald Trump’ into the same entity). Record Linkage. Joining data sets on a particular entity (for example, joining records of ‘D J Trump’ to a URL of his Wikipedia page). By using a novel approach borrowed from the field of Natural Language Processing we can perform these two tasks on large data sets. There are many algorithms which can provide fuzzy matching (see here how to implement in Python) but they quickly fall down when used on even modest data sets of greater than a few thousand records. The reason for this is that they compare each record to all the other records in the data set. In computer science, this is known as quadratic time and can quickly form a barrier when dealing with larger data sets: What makes this worse is that most string matching functions are also dependant on the length of the two strings being compared and can therefore slow down even further when comparing long text. The solution to this problem comes from a well known NLP algorithm. Term Frequency, Inverse Document Frequency (or tf-idf) has been used in language problems since 1972. It is a simple algorithm which splits text into ‘chunks’ (or ngrams), counts the occurrence of each chunk for a given sample and then applies a weighting to this based on how rare the chunk is across all the samples of a data set. This means that useful words are filtered from the ‘noise’ of more common words which occur within text. Whilst these chunks are normally applied to whole words, there is no reason why the same technique cannot be applied to sets of characters within words. For example, we could split each word into 3 character ngrams, for the word ‘Department’, this would output: ' De', 'Dep', 'epa', 'par', 'art', 'rtm', 'tme', 'men', 'ent', 'nt ' We can then compare these chunks across a matrix of items which represents our data set to look for close matches. This method of finding close matches should be both very efficient and also produce good quality matches through its ability to place greater importance on groups of characters which are less common across the data. Lets put it to the test! The example we will use to test this algorithm is a set of UK public organisations who have published contracts on Contracts Finder. The names of these organisations are very messy and it appears as if they have been typed-into the system via a free-text field. We will first explore how to dedupe close matches. The process is made painless using Python’s Scikit-Learn library: Create a function to split our stings into character ngrams.Create a tf-idf matrix from these characters using Scikit-Learn.Use cosine similarity to show close matches across the population. Create a function to split our stings into character ngrams. Create a tf-idf matrix from these characters using Scikit-Learn. Use cosine similarity to show close matches across the population. The ngram function The below function is used as both a cleaning function of the text data as well as a way of splitting text into ngrams. Comments have been added in the code to show the purpose of each line: Applying the function and creating a tf-idf matrix The great thing about the tf-idf implementation in Scikit is that it allows for a custom function to be added to it. We can therefore add-in the function we have created above and build the matrix in just a few lines of code: from sklearn.feature_extraction.text import TfidfVectorizerorg_names = names['buyer'].unique()vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)tf_idf_matrix = vectorizer.fit_transform(org_names) Finding close matches through cosine similarity You could use the cosine similarity function from Scikit here however it is not the most efficient way of finding close matches as it returns a closeness score for every item in the dataset for each sample. Instead, we are going to use a faster implementation of this which can be found here: import numpy as npfrom scipy.sparse import csr_matrix!pip install sparse_dot_topn import sparse_dot_topn.sparse_dot_topn as ctdef awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M*ntop indptr = np.zeros(M+1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype)ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data)return csr_matrix((data,indices,indptr),shape=(M,N)) Putting all of this together we get the following result: Very impressive, but how fast is it? Let us compare against a more traditional method of computing close matches using the ‘fuzzywuzzy’ library: !pip install fuzzywuzzyfrom fuzzywuzzy import fuzzfrom fuzzywuzzy import processt1 = time.time()print(process.extractOne('Ministry of Justice', org_names)) #org names is our list of organisation namest = time.time()-t1print("SELFTIMED:", t)print("Estimated hours to complete for full dataset:", (t*len(org_names))/60/60)Outputs:SELFTIMED: 3.7s Estimated hrs to complete for full dataset: 3.78hrs Yikes the baseline time for this using traditional methods is around 3.7 hrs. How long did it take our algorithm to work its magic? import timet1 = time.time()matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 10, 0.85)t = time.time()-t1print("SELFTIMED:", t)Outputs: SELFTIMED: 0.19s Wow — we have reduced the estimated time from 3.7hrs to around a fifth of a second (an approximate 66,000X speed-up!) If we want to use this technique to match against another data source then we can recycle the majority of our code. In the below section we will see how this is achieved and also use the K Nearest Neighbour algorithm as an alternative closeness measure. The dataset we would like to join on is a set of ‘clean’ organisation names created by the Office for National Statistics (ONS): As can be shown in the code below, the only difference in this approach is to transform the messy data set using the tdif matrix which has been learned on the clean data set. The ‘getNearestN’ then uses Scikit’s implementation of K Nearest Neighbours to find the closest matches in the dataset: from sklearn.metrics.pairwise import cosine_similarityfrom sklearn.feature_extraction.text import TfidfVectorizerimport reclean_org_names = pd.read_excel('Gov Orgs ONS.xlsx')clean_org_names = clean_org_names.iloc[:, 0:6]org_name_clean = clean_org_names['Institutions'].unique()print('Vecorizing the data - this could take a few minutes for large datasets...')vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams, lowercase=False)tfidf = vectorizer.fit_transform(org_name_clean)print('Vecorizing completed...')from sklearn.neighbors import NearestNeighborsnbrs = NearestNeighbors(n_neighbors=1, n_jobs=-1).fit(tfidf)org_column = 'buyer' #column to match against in the messy dataunique_org = set(names[org_column].values) # set used for increased performance###matching query:def getNearestN(query): queryTFIDF_ = vectorizer.transform(query) distances, indices = nbrs.kneighbors(queryTFIDF_) return distances, indicesimport timet1 = time.time()print('getting nearest n...')distances, indices = getNearestN(unique_org)t = time.time()-t1print("COMPLETED IN:", t)unique_org = list(unique_org) #need to convert back to a listprint('finding matches...')matches = []for i,j in enumerate(indices): temp = [round(distances[i][0],2), clean_org_names.values[j][0][0],unique_org[i]] matches.append(temp)print('Building data frame...') matches = pd.DataFrame(matches, columns=['Match confidence (lower is better)','Matched name','Origional name'])print('Done') This produces the following results: As can be seen from this sample, not all items appear across both data sets, however the K Nearest Neighbour will still have a go at finding the closest match. As such, we would need to apply a threshold to the closeness score to determine what counts as a match. Matching the 3,651 entities to our clean data set (containing c3,000 entities) took less than a second using this method. Whilst we have built our own function to find close matches across vectors in this post, there are many libraries that exist whose sole purpose is to accelerate this process. Unfortunately most of these require vectors to be dense and cannot process large, sparse (mostly empty) matrices that we have created in this post. Luckily, one library does work well with sparse matrices; NMSLIB. I have written about this library in more detail here, but in essence, NMSLIB can create an index over a matrix and perform blazing-fast queries on this given an input to search on. The full, documented code to implement this on any dataset can be found below: drive.google.com In summary, tf-idf can be a highly effective and highly performant way of cleaning, deduping and matching data when dealing with larger record counts. Code, References and further reading: Please see the colab document below to view the full code for this post: colab.research.google.com This article is inspired by the following post on Van Den Blog: bergvca.github.io Further information on tf-idf can be found in the below article
[ { "code": null, "e": 330, "s": 171, "text": "### Update December 2020: A faster, simpler way of fuzzy matching is now included at the end of this post with the full code to implement it on any dataset###" }, { "code": null, "e": 474, "s": 330, "text": "Data in the real world is messy. Dealing with messy data sets is painful and burns through time which could be spent analysing the data itself." }, { "code": null, "e": 628, "s": 474, "text": "This article focuses in on ‘fuzzy’ matching and how this can help to automate significant challenges in a large number of data science workflows through:" }, { "code": null, "e": 934, "s": 628, "text": "Deduplication. Aligning similar categories or entities in a data set (for example, we may need to combine ‘D J Trump’, ‘D. Trump’ and ‘Donald Trump’ into the same entity).Record Linkage. Joining data sets on a particular entity (for example, joining records of ‘D J Trump’ to a URL of his Wikipedia page)." }, { "code": null, "e": 1106, "s": 934, "text": "Deduplication. Aligning similar categories or entities in a data set (for example, we may need to combine ‘D J Trump’, ‘D. Trump’ and ‘Donald Trump’ into the same entity)." }, { "code": null, "e": 1241, "s": 1106, "text": "Record Linkage. Joining data sets on a particular entity (for example, joining records of ‘D J Trump’ to a URL of his Wikipedia page)." }, { "code": null, "e": 1373, "s": 1241, "text": "By using a novel approach borrowed from the field of Natural Language Processing we can perform these two tasks on large data sets." }, { "code": null, "e": 1572, "s": 1373, "text": "There are many algorithms which can provide fuzzy matching (see here how to implement in Python) but they quickly fall down when used on even modest data sets of greater than a few thousand records." }, { "code": null, "e": 1787, "s": 1572, "text": "The reason for this is that they compare each record to all the other records in the data set. In computer science, this is known as quadratic time and can quickly form a barrier when dealing with larger data sets:" }, { "code": null, "e": 1982, "s": 1787, "text": "What makes this worse is that most string matching functions are also dependant on the length of the two strings being compared and can therefore slow down even further when comparing long text." }, { "code": null, "e": 2152, "s": 1982, "text": "The solution to this problem comes from a well known NLP algorithm. Term Frequency, Inverse Document Frequency (or tf-idf) has been used in language problems since 1972." }, { "code": null, "e": 2488, "s": 2152, "text": "It is a simple algorithm which splits text into ‘chunks’ (or ngrams), counts the occurrence of each chunk for a given sample and then applies a weighting to this based on how rare the chunk is across all the samples of a data set. This means that useful words are filtered from the ‘noise’ of more common words which occur within text." }, { "code": null, "e": 2750, "s": 2488, "text": "Whilst these chunks are normally applied to whole words, there is no reason why the same technique cannot be applied to sets of characters within words. For example, we could split each word into 3 character ngrams, for the word ‘Department’, this would output:" }, { "code": null, "e": 2819, "s": 2750, "text": "' De', 'Dep', 'epa', 'par', 'art', 'rtm', 'tme', 'men', 'ent', 'nt '" }, { "code": null, "e": 3175, "s": 2819, "text": "We can then compare these chunks across a matrix of items which represents our data set to look for close matches. This method of finding close matches should be both very efficient and also produce good quality matches through its ability to place greater importance on groups of characters which are less common across the data. Lets put it to the test!" }, { "code": null, "e": 3437, "s": 3175, "text": "The example we will use to test this algorithm is a set of UK public organisations who have published contracts on Contracts Finder. The names of these organisations are very messy and it appears as if they have been typed-into the system via a free-text field." }, { "code": null, "e": 3554, "s": 3437, "text": "We will first explore how to dedupe close matches. The process is made painless using Python’s Scikit-Learn library:" }, { "code": null, "e": 3745, "s": 3554, "text": "Create a function to split our stings into character ngrams.Create a tf-idf matrix from these characters using Scikit-Learn.Use cosine similarity to show close matches across the population." }, { "code": null, "e": 3806, "s": 3745, "text": "Create a function to split our stings into character ngrams." }, { "code": null, "e": 3871, "s": 3806, "text": "Create a tf-idf matrix from these characters using Scikit-Learn." }, { "code": null, "e": 3938, "s": 3871, "text": "Use cosine similarity to show close matches across the population." }, { "code": null, "e": 3957, "s": 3938, "text": "The ngram function" }, { "code": null, "e": 4148, "s": 3957, "text": "The below function is used as both a cleaning function of the text data as well as a way of splitting text into ngrams. Comments have been added in the code to show the purpose of each line:" }, { "code": null, "e": 4199, "s": 4148, "text": "Applying the function and creating a tf-idf matrix" }, { "code": null, "e": 4425, "s": 4199, "text": "The great thing about the tf-idf implementation in Scikit is that it allows for a custom function to be added to it. We can therefore add-in the function we have created above and build the matrix in just a few lines of code:" }, { "code": null, "e": 4626, "s": 4425, "text": "from sklearn.feature_extraction.text import TfidfVectorizerorg_names = names['buyer'].unique()vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)tf_idf_matrix = vectorizer.fit_transform(org_names)" }, { "code": null, "e": 4674, "s": 4626, "text": "Finding close matches through cosine similarity" }, { "code": null, "e": 4967, "s": 4674, "text": "You could use the cosine similarity function from Scikit here however it is not the most efficient way of finding close matches as it returns a closeness score for every item in the dataset for each sample. Instead, we are going to use a faster implementation of this which can be found here:" }, { "code": null, "e": 5844, "s": 4967, "text": "import numpy as npfrom scipy.sparse import csr_matrix!pip install sparse_dot_topn import sparse_dot_topn.sparse_dot_topn as ctdef awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M*ntop indptr = np.zeros(M+1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype)ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data)return csr_matrix((data,indices,indptr),shape=(M,N))" }, { "code": null, "e": 5902, "s": 5844, "text": "Putting all of this together we get the following result:" }, { "code": null, "e": 6047, "s": 5902, "text": "Very impressive, but how fast is it? Let us compare against a more traditional method of computing close matches using the ‘fuzzywuzzy’ library:" }, { "code": null, "e": 6443, "s": 6047, "text": "!pip install fuzzywuzzyfrom fuzzywuzzy import fuzzfrom fuzzywuzzy import processt1 = time.time()print(process.extractOne('Ministry of Justice', org_names)) #org names is our list of organisation namest = time.time()-t1print(\"SELFTIMED:\", t)print(\"Estimated hours to complete for full dataset:\", (t*len(org_names))/60/60)Outputs:SELFTIMED: 3.7s Estimated hrs to complete for full dataset: 3.78hrs" }, { "code": null, "e": 6575, "s": 6443, "text": "Yikes the baseline time for this using traditional methods is around 3.7 hrs. How long did it take our algorithm to work its magic?" }, { "code": null, "e": 6749, "s": 6575, "text": "import timet1 = time.time()matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 10, 0.85)t = time.time()-t1print(\"SELFTIMED:\", t)Outputs: SELFTIMED: 0.19s" }, { "code": null, "e": 6867, "s": 6749, "text": "Wow — we have reduced the estimated time from 3.7hrs to around a fifth of a second (an approximate 66,000X speed-up!)" }, { "code": null, "e": 7121, "s": 6867, "text": "If we want to use this technique to match against another data source then we can recycle the majority of our code. In the below section we will see how this is achieved and also use the K Nearest Neighbour algorithm as an alternative closeness measure." }, { "code": null, "e": 7250, "s": 7121, "text": "The dataset we would like to join on is a set of ‘clean’ organisation names created by the Office for National Statistics (ONS):" }, { "code": null, "e": 7425, "s": 7250, "text": "As can be shown in the code below, the only difference in this approach is to transform the messy data set using the tdif matrix which has been learned on the clean data set." }, { "code": null, "e": 7545, "s": 7425, "text": "The ‘getNearestN’ then uses Scikit’s implementation of K Nearest Neighbours to find the closest matches in the dataset:" }, { "code": null, "e": 9001, "s": 7545, "text": "from sklearn.metrics.pairwise import cosine_similarityfrom sklearn.feature_extraction.text import TfidfVectorizerimport reclean_org_names = pd.read_excel('Gov Orgs ONS.xlsx')clean_org_names = clean_org_names.iloc[:, 0:6]org_name_clean = clean_org_names['Institutions'].unique()print('Vecorizing the data - this could take a few minutes for large datasets...')vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams, lowercase=False)tfidf = vectorizer.fit_transform(org_name_clean)print('Vecorizing completed...')from sklearn.neighbors import NearestNeighborsnbrs = NearestNeighbors(n_neighbors=1, n_jobs=-1).fit(tfidf)org_column = 'buyer' #column to match against in the messy dataunique_org = set(names[org_column].values) # set used for increased performance###matching query:def getNearestN(query): queryTFIDF_ = vectorizer.transform(query) distances, indices = nbrs.kneighbors(queryTFIDF_) return distances, indicesimport timet1 = time.time()print('getting nearest n...')distances, indices = getNearestN(unique_org)t = time.time()-t1print(\"COMPLETED IN:\", t)unique_org = list(unique_org) #need to convert back to a listprint('finding matches...')matches = []for i,j in enumerate(indices): temp = [round(distances[i][0],2), clean_org_names.values[j][0][0],unique_org[i]] matches.append(temp)print('Building data frame...') matches = pd.DataFrame(matches, columns=['Match confidence (lower is better)','Matched name','Origional name'])print('Done')" }, { "code": null, "e": 9038, "s": 9001, "text": "This produces the following results:" }, { "code": null, "e": 9302, "s": 9038, "text": "As can be seen from this sample, not all items appear across both data sets, however the K Nearest Neighbour will still have a go at finding the closest match. As such, we would need to apply a threshold to the closeness score to determine what counts as a match." }, { "code": null, "e": 9424, "s": 9302, "text": "Matching the 3,651 entities to our clean data set (containing c3,000 entities) took less than a second using this method." }, { "code": null, "e": 9599, "s": 9424, "text": "Whilst we have built our own function to find close matches across vectors in this post, there are many libraries that exist whose sole purpose is to accelerate this process." }, { "code": null, "e": 10074, "s": 9599, "text": "Unfortunately most of these require vectors to be dense and cannot process large, sparse (mostly empty) matrices that we have created in this post. Luckily, one library does work well with sparse matrices; NMSLIB. I have written about this library in more detail here, but in essence, NMSLIB can create an index over a matrix and perform blazing-fast queries on this given an input to search on. The full, documented code to implement this on any dataset can be found below:" }, { "code": null, "e": 10091, "s": 10074, "text": "drive.google.com" }, { "code": null, "e": 10242, "s": 10091, "text": "In summary, tf-idf can be a highly effective and highly performant way of cleaning, deduping and matching data when dealing with larger record counts." }, { "code": null, "e": 10280, "s": 10242, "text": "Code, References and further reading:" }, { "code": null, "e": 10353, "s": 10280, "text": "Please see the colab document below to view the full code for this post:" }, { "code": null, "e": 10379, "s": 10353, "text": "colab.research.google.com" }, { "code": null, "e": 10443, "s": 10379, "text": "This article is inspired by the following post on Van Den Blog:" }, { "code": null, "e": 10461, "s": 10443, "text": "bergvca.github.io" } ]
Error handling in PHP - GeeksforGeeks
21 Nov, 2021 Prerequisite: Types of Error PHP is used for web development. Error handling in PHP is almost similar to error handling in all programming languages. The default error handling in PHP will give file name line number and error type. Ways to handle PHP Errors: Using die() method Custom Error Handling Basic error handling: Using die() function The die() function print a message and exit from current script.Syntax: die( $message ) Example: php <?php // Php code showing default error handling $file = fopen("geeks.txt", "w");?> Note: Run the above code and geeks.txt file is not present then it will display an run-time error message. Runtime Error: PHP Warning: fopen(geeks.txt): failed to open stream: Permission denied in /home/dac923dff0a2558b37ba742613273073.php on line 2 To prevent this error use die() function. Below is the implementation of die() function:Example: php <?php // PHP code to check errors // If file is not present// then exit from scriptif( !file_exists("geeks.txt") ) { die("File is not present");} // If file is present// then continueelse { $file = fopen("geeks.txt", "w");}?> Note: If geeks.txt file not present then it will display output. Output File is not present Custom Error handling: Creating a custom error handler in PHP is quite simple. Create a function that can be called when a error has been occurred in PHP.Syntax: error_function( $error_level, $error_message, $error_file, $error_line, $error_context) Parameters: This function accepts five parameters as mentioned above and described below: $error_level: It is required parameter and it must be an integer. There are predefined error levels. $error_message: It is required parameter and it is the message which user want to print. $error_file: It is optional parameter and used to specify the file in which error has been occurred. $error_line: It is optional parameter and used to specify the line number in which error has been occurred. $error_context: It is optional parameter and used to specify an array containing every variable and their value when error has been occurred. error_level: These are the possible error level which are listed below: 1 : .E_ERROR :fatal runtime error execution of script has been halted 2 : E_WARNING :non fatal runtime error execution of script has been halted 4 : E_PARSE :compile time error it is generated by the parser 8 :E_NOTICE :The script found something that might be an error 16 :E_CORE_ERROR :Fatal errors that occurred during initial startup of script 32 :E_CORE_WARNING :Non fatal errors that occurred during initial startup of script 8191 :E_ALL :All errors and warning set_error_handler() Function: After creating myerror() function need to set custom error handler because in normal way PHP handles it but if user doing custom error handling then user have to set it in place of argument and pass out myerror function as a string.Example: php <?php // Creates my error function which prints message//to userfunction myerror($error_no, $error_msg) { echo "Error: [$error_no] $error_msg "; echo "\n Now Script will end"; // When error occurred script has to be stopped die();} // Setting set_error_handlerset_error_handler("myerror"); $a = 10;$b = 0; // This will generate errorecho($a / $b);;?> Output: Error: [2] Division by zero Now Script will end Conclusion: It is always try to error handling using Custom error handling because it will show more specified message according to the user that can be helpful to the user. If error is not handle using Custom error handling then a error occurred then out script will be halted by default but if it handle error using Custom error handling then it can continue script after displaying error message. Akanksha_Rai varshagumber28 PHP-basics PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? How to convert array to string in PHP ? How to delete an array element based on key in PHP?
[ { "code": null, "e": 40529, "s": 40501, "text": "\n21 Nov, 2021" }, { "code": null, "e": 40762, "s": 40529, "text": "Prerequisite: Types of Error PHP is used for web development. Error handling in PHP is almost similar to error handling in all programming languages. The default error handling in PHP will give file name line number and error type. " }, { "code": null, "e": 40791, "s": 40762, "text": "Ways to handle PHP Errors: " }, { "code": null, "e": 40810, "s": 40791, "text": "Using die() method" }, { "code": null, "e": 40832, "s": 40810, "text": "Custom Error Handling" }, { "code": null, "e": 40949, "s": 40832, "text": "Basic error handling: Using die() function The die() function print a message and exit from current script.Syntax: " }, { "code": null, "e": 40965, "s": 40949, "text": "die( $message )" }, { "code": null, "e": 40976, "s": 40965, "text": "Example: " }, { "code": null, "e": 40980, "s": 40976, "text": "php" }, { "code": "<?php // Php code showing default error handling $file = fopen(\"geeks.txt\", \"w\");?>", "e": 41064, "s": 40980, "text": null }, { "code": null, "e": 41187, "s": 41064, "text": "Note: Run the above code and geeks.txt file is not present then it will display an run-time error message. Runtime Error: " }, { "code": null, "e": 41317, "s": 41187, "text": " PHP Warning: fopen(geeks.txt): failed to open stream: Permission denied \nin /home/dac923dff0a2558b37ba742613273073.php on line 2" }, { "code": null, "e": 41416, "s": 41317, "text": "To prevent this error use die() function. Below is the implementation of die() function:Example: " }, { "code": null, "e": 41420, "s": 41416, "text": "php" }, { "code": "<?php // PHP code to check errors // If file is not present// then exit from scriptif( !file_exists(\"geeks.txt\") ) { die(\"File is not present\");} // If file is present// then continueelse { $file = fopen(\"geeks.txt\", \"w\");}?>", "e": 41652, "s": 41420, "text": null }, { "code": null, "e": 41725, "s": 41652, "text": "Note: If geeks.txt file not present then it will display output. Output " }, { "code": null, "e": 41745, "s": 41725, "text": "File is not present" }, { "code": null, "e": 41909, "s": 41745, "text": "Custom Error handling: Creating a custom error handler in PHP is quite simple. Create a function that can be called when a error has been occurred in PHP.Syntax: " }, { "code": null, "e": 41997, "s": 41909, "text": "error_function( $error_level, $error_message, $error_file, $error_line, $error_context)" }, { "code": null, "e": 42089, "s": 41997, "text": "Parameters: This function accepts five parameters as mentioned above and described below: " }, { "code": null, "e": 42190, "s": 42089, "text": "$error_level: It is required parameter and it must be an integer. There are predefined error levels." }, { "code": null, "e": 42279, "s": 42190, "text": "$error_message: It is required parameter and it is the message which user want to print." }, { "code": null, "e": 42380, "s": 42279, "text": "$error_file: It is optional parameter and used to specify the file in which error has been occurred." }, { "code": null, "e": 42488, "s": 42380, "text": "$error_line: It is optional parameter and used to specify the line number in which error has been occurred." }, { "code": null, "e": 42630, "s": 42488, "text": "$error_context: It is optional parameter and used to specify an array containing every variable and their value when error has been occurred." }, { "code": null, "e": 42703, "s": 42630, "text": "error_level: These are the possible error level which are listed below: " }, { "code": null, "e": 42773, "s": 42703, "text": "1 : .E_ERROR :fatal runtime error execution of script has been halted" }, { "code": null, "e": 42848, "s": 42773, "text": "2 : E_WARNING :non fatal runtime error execution of script has been halted" }, { "code": null, "e": 42910, "s": 42848, "text": "4 : E_PARSE :compile time error it is generated by the parser" }, { "code": null, "e": 42973, "s": 42910, "text": "8 :E_NOTICE :The script found something that might be an error" }, { "code": null, "e": 43051, "s": 42973, "text": "16 :E_CORE_ERROR :Fatal errors that occurred during initial startup of script" }, { "code": null, "e": 43135, "s": 43051, "text": "32 :E_CORE_WARNING :Non fatal errors that occurred during initial startup of script" }, { "code": null, "e": 43171, "s": 43135, "text": "8191 :E_ALL :All errors and warning" }, { "code": null, "e": 43443, "s": 43171, "text": "set_error_handler() Function: After creating myerror() function need to set custom error handler because in normal way PHP handles it but if user doing custom error handling then user have to set it in place of argument and pass out myerror function as a string.Example: " }, { "code": null, "e": 43447, "s": 43443, "text": "php" }, { "code": "<?php // Creates my error function which prints message//to userfunction myerror($error_no, $error_msg) { echo \"Error: [$error_no] $error_msg \"; echo \"\\n Now Script will end\"; // When error occurred script has to be stopped die();} // Setting set_error_handlerset_error_handler(\"myerror\"); $a = 10;$b = 0; // This will generate errorecho($a / $b);;?>", "e": 43815, "s": 43447, "text": null }, { "code": null, "e": 43824, "s": 43815, "text": "Output: " }, { "code": null, "e": 43874, "s": 43824, "text": "Error: [2] Division by zero \n Now Script will end" }, { "code": null, "e": 44274, "s": 43874, "text": "Conclusion: It is always try to error handling using Custom error handling because it will show more specified message according to the user that can be helpful to the user. If error is not handle using Custom error handling then a error occurred then out script will be halted by default but if it handle error using Custom error handling then it can continue script after displaying error message." }, { "code": null, "e": 44287, "s": 44274, "text": "Akanksha_Rai" }, { "code": null, "e": 44302, "s": 44287, "text": "varshagumber28" }, { "code": null, "e": 44313, "s": 44302, "text": "PHP-basics" }, { "code": null, "e": 44317, "s": 44313, "text": "PHP" }, { "code": null, "e": 44330, "s": 44317, "text": "PHP Programs" }, { "code": null, "e": 44347, "s": 44330, "text": "Web Technologies" }, { "code": null, "e": 44351, "s": 44347, "text": "PHP" }, { "code": null, "e": 44449, "s": 44351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44458, "s": 44449, "text": "Comments" }, { "code": null, "e": 44471, "s": 44458, "text": "Old Comments" }, { "code": null, "e": 44521, "s": 44471, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 44566, "s": 44521, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 44610, "s": 44566, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 44634, "s": 44610, "text": "PHP in_array() Function" }, { "code": null, "e": 44674, "s": 44634, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 44724, "s": 44674, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 44769, "s": 44724, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 44813, "s": 44769, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 44853, "s": 44813, "text": "How to convert array to string in PHP ?" } ]
Write a Python program to separate a series of alphabets and digits and convert them to a dataframe
Assume you have a series and the result for separating alphabets and digits and store it in dataframe as, series is: 0 abx123 1 bcd25 2 cxy30 dtype: object Dataframe is 0 1 0 abx 123 1 bcd 25 2 cxy 30 To solve this, we will follow the below approach, Define a series. Define a series. Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe − Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe − series.str.extract(r'(\w+[a-z])(\d+)') Let’s see the below implementation to get a better understanding − import pandas as pd series = pd.Series(['abx123', 'bcd25', 'cxy30']) print("series is:\n",series) df = series.str.extract(r'(\w+[a-z])(\d+)') print("Dataframe is\n:" ,df) series is: 0 abx123 1 bcd25 2 cxy30 dtype: object Dataframe is : 0 1 0 abx 123 1 bcd 25 2 cxy 30
[ { "code": null, "e": 1168, "s": 1062, "text": "Assume you have a series and the result for separating alphabets and digits and store it in dataframe as," }, { "code": null, "e": 1277, "s": 1168, "text": "series is:\n0 abx123\n1 bcd25\n2 cxy30\ndtype: object\nDataframe is\n 0 1\n0 abx 123\n1 bcd 25\n2 cxy 30" }, { "code": null, "e": 1327, "s": 1277, "text": "To solve this, we will follow the below approach," }, { "code": null, "e": 1344, "s": 1327, "text": "Define a series." }, { "code": null, "e": 1361, "s": 1344, "text": "Define a series." }, { "code": null, "e": 1491, "s": 1361, "text": "Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe −" }, { "code": null, "e": 1621, "s": 1491, "text": "Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe −" }, { "code": null, "e": 1660, "s": 1621, "text": "series.str.extract(r'(\\w+[a-z])(\\d+)')" }, { "code": null, "e": 1727, "s": 1660, "text": "Let’s see the below implementation to get a better understanding −" }, { "code": null, "e": 1898, "s": 1727, "text": "import pandas as pd\nseries = pd.Series(['abx123', 'bcd25', 'cxy30'])\nprint(\"series is:\\n\",series)\ndf = series.str.extract(r'(\\w+[a-z])(\\d+)')\nprint(\"Dataframe is\\n:\" ,df)" }, { "code": null, "e": 2007, "s": 1898, "text": "series is:\n0 abx123\n1 bcd25\n2 cxy30\ndtype: object\nDataframe is\n: 0 1\n0 abx 123\n1 bcd 25\n2 cxy 30" } ]
MySQL - UNIX_TIMESTAMP() Function
The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values. The MYSQL UNIX_TIMESTAMP() function converts the date or datetime expression as a UNIX timestamp and returns the result in the form of a string. Following is the syntax of the above function – UNIX_TIMESTAMP(expr); Where, expr is the date-time or the time expression from which you need to get the UNIX timestamp. Following example demonstrates the usage of the UNIX_TIMESTAMP() function – mysql> SELECT UNIX_TIMESTAMP('1078:06:23'); +------------------------------+ | UNIX_TIMESTAMP('1078:06:23') | +------------------------------+ | 0 | +------------------------------+ 1 row in set (0.19 sec) Following is another example of this function – mysql> SELECT UNIX_TIMESTAMP('2012:11:01'); +------------------------------+ | UNIX_TIMESTAMP('2012:11:01') | +------------------------------+ | 1351708200 | +------------------------------+ 1 row in set (0.00 sec) We can also pass the date-time expression as an argument to this function – mysql> SELECT UNIX_TIMESTAMP('2015-09-05 09:40:45.2300'); +--------------------------------------------+ | UNIX_TIMESTAMP('2015-09-05 09:40:45.2300') | +--------------------------------------------+ | 1441426245.2300 | +--------------------------------------------+ 1 row in set (0.00 sec) If you invoke this function without passing any arguments it returns the current (UNIX) timestamp — mysql> SELECT UNIX_TIMESTAMP(); +------------------+ | UNIX_TIMESTAMP() | +------------------+ | 1626608542 | +------------------+ 1 row in set (0.00 sec) mysql> SELECT UNIX_TIMESTAMP('1986:06:26'); +------------------------------+ | UNIX_TIMESTAMP('1986:06:26') | +------------------------------+ | 520108200 | +------------------------------+ 1 row in set (0.00 sec) We can pass the result of the NOW() function as an argument to this function – mysql> SELECT UNIX_TIMESTAMP(NOW()); +-----------------------+ | UNIX_TIMESTAMP(NOW()) | +-----------------------+ | 1626608693 | +-----------------------+ 1 row in set (0.00 sec) You can also pass the column name as an argument to this function. Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below – mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements − mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); mysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following query displays UNIX TIMESTAMPs for all the entities in the Date_Of_Birth column— mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, UNIX_TIMESTAMP(Date_Of_Birth) as UnixTimestamp FROM MyPlayers; +------------+------------+---------------+-------------+---------------+ | First_Name | Last_Name | Date_Of_Birth | Country | UnixTimestamp | +------------+------------+---------------+-------------+---------------+ | Shikhar | Dhawan | 1981-12-05 | India | 376338600 | | Jonathan | Trott | 1981-04-22 | SouthAfrica | 356725800 | | Kumara | Sangakkara | 1977-10-27 | Srilanka | 246738600 | | Virat | Kohli | 1988-11-05 | India | 594671400 | | Rohit | Sharma | 1987-04-30 | India | 546719400 | | Ravindra | Jadeja | 1988-12-06 | India | 597349800 | | James | Anderson | 1982-06-30 | England | 394223400 | +------------+------------+---------------+-------------+---------------+ 7 rows in set (0.00 sec) Let us create another table with name Sales in MySQL database using CREATE statement as follows – mysql> CREATE TABLE sales( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DispatchTime time, Price INT, Location VARCHAR(255) ); Query OK, 0 rows affected (2.22 sec) Now, we will insert 5 records in Sales table using INSERT statements − insert into sales values (1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into sales values (2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into sales values (3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into sales values (4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into sales values (5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); In the following query we are passing the DispatchTime column as an argument to the UNIX_TIMESTAMP() function — mysql> SELECT ProductName, CustomerName, DispatchDate, DispatchTime, Price, UNIX_TIMESTAMP(DispatchTime) as UnixTimestamp FROM sales; +-------------+--------------+--------------+--------------+-------+---------------+ | ProductName | CustomerName | DispatchDate | DispatchTime | Price | UnixTimestamp | +-------------+--------------+--------------+--------------+-------+---------------+ | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | 1626586200 | | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | 1626586200 | | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | 1626586199 | | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | 1626583252 | | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | 1626586739 | +-------------+--------------+--------------+--------------+-------+---------------+ 5 rows in set (0.00 sec) Suppose we have created a table named SubscribersData with 5 records in it using the following queries – mysql> CREATE TABLE SubscribersData( SubscriberName VARCHAR(255), PackageName VARCHAR(255), SubscriptionDate date, SubscriptionTime time ); insert into SubscribersData values('Raja', 'Premium', Date('2020-10-21'), Time('20:53:49')); insert into SubscribersData values('Roja', 'Basic', Date('2020-11-26'), Time('10:13:19')); insert into SubscribersData values('Puja', 'Moderate', Date('2021-03-07'), Time('05:43:20')); insert into SubscribersData values('Vanaja', 'Basic', Date('2021-02-21'), Time('16:36:39')); insert into SubscribersData values('Jalaja', 'Premium', Date('2021-01-30'), Time('12:45:45')); Following query displays the values of the columns SubscriptionDate, SubscriptionTime as a single column SubscriptionTimestamp – mysql> SELECT SubscriberName, PackageName, SubscriptionDate, SubscriptionTime, UNIX_TIMESTAMP(SubscriptionDate) as UnixTimestamp FROM SubscribersData; +----------------+-------------+------------------+------------------+---------------+ | SubscriberName | PackageName | SubscriptionDate | SubscriptionTime | UnixTimestamp | +----------------+-------------+------------------+------------------+---------------+ | Raja | Premium | 2020-10-21 | 20:53:49 | 1603218600 | | Roja | Basic | 2020-11-26 | 10:13:19 | 1606329000 | | Puja | Moderate | 2021-03-07 | 05:43:20 | 1615055400 | | Vanaja | Basic | 2021-02-21 | 16:36:39 | 1613845800 | | Jalaja | Premium | 2021-01-30 | 12:45:45 | 1611945000 | +----------------+-------------+------------------+------------------+---------------+ 5 rows in set (0.13 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2664, "s": 2333, "text": "The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values." }, { "code": null, "e": 2809, "s": 2664, "text": "The MYSQL UNIX_TIMESTAMP() function converts the date or datetime expression as a UNIX timestamp and returns the result in the form of a string." }, { "code": null, "e": 2857, "s": 2809, "text": "Following is the syntax of the above function –" }, { "code": null, "e": 2880, "s": 2857, "text": "UNIX_TIMESTAMP(expr);\n" }, { "code": null, "e": 2979, "s": 2880, "text": "Where, expr is the date-time or the time expression from which you need to get the UNIX timestamp." }, { "code": null, "e": 3055, "s": 2979, "text": "Following example demonstrates the usage of the UNIX_TIMESTAMP() function –" }, { "code": null, "e": 3288, "s": 3055, "text": "mysql> SELECT UNIX_TIMESTAMP('1078:06:23');\n+------------------------------+\n| UNIX_TIMESTAMP('1078:06:23') |\n+------------------------------+\n| 0 |\n+------------------------------+\n1 row in set (0.19 sec)" }, { "code": null, "e": 3336, "s": 3288, "text": "Following is another example of this function –" }, { "code": null, "e": 3569, "s": 3336, "text": "mysql> SELECT UNIX_TIMESTAMP('2012:11:01');\n+------------------------------+\n| UNIX_TIMESTAMP('2012:11:01') |\n+------------------------------+\n| 1351708200 |\n+------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3645, "s": 3569, "text": "We can also pass the date-time expression as an argument to this function –" }, { "code": null, "e": 3962, "s": 3645, "text": "mysql> SELECT UNIX_TIMESTAMP('2015-09-05 09:40:45.2300');\n+--------------------------------------------+\n| UNIX_TIMESTAMP('2015-09-05 09:40:45.2300') |\n+--------------------------------------------+\n| 1441426245.2300 |\n+--------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4062, "s": 3962, "text": "If you invoke this function without passing any arguments it returns the current (UNIX) timestamp —" }, { "code": null, "e": 4223, "s": 4062, "text": "mysql> SELECT UNIX_TIMESTAMP();\n+------------------+\n| UNIX_TIMESTAMP() |\n+------------------+\n| 1626608542 |\n+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4456, "s": 4223, "text": "mysql> SELECT UNIX_TIMESTAMP('1986:06:26');\n+------------------------------+\n| UNIX_TIMESTAMP('1986:06:26') |\n+------------------------------+\n| 520108200 |\n+------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4535, "s": 4456, "text": "We can pass the result of the NOW() function as an argument to this function –" }, { "code": null, "e": 4726, "s": 4535, "text": "mysql> SELECT UNIX_TIMESTAMP(NOW());\n+-----------------------+\n| UNIX_TIMESTAMP(NOW()) |\n+-----------------------+\n| 1626608693 |\n+-----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4893, "s": 4726, "text": "You can also pass the column name as an argument to this function. Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below –" }, { "code": null, "e": 5079, "s": 4893, "text": "mysql> CREATE TABLE MyPlayers(\n\tID INT,\n\tFirst_Name VARCHAR(255),\n\tLast_Name VARCHAR(255),\n\tDate_Of_Birth date,\n\tPlace_Of_Birth VARCHAR(255),\n\tCountry VARCHAR(255),\n\tPRIMARY KEY (ID)\n);" }, { "code": null, "e": 5154, "s": 5079, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 5865, "s": 5154, "text": "mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\nmysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\nmysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 5956, "s": 5865, "text": "Following query displays UNIX TIMESTAMPs for all the entities in the Date_Of_Birth column—" }, { "code": null, "e": 6921, "s": 5956, "text": "mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, UNIX_TIMESTAMP(Date_Of_Birth) as UnixTimestamp FROM MyPlayers;\n+------------+------------+---------------+-------------+---------------+\n| First_Name | Last_Name | Date_Of_Birth | Country | UnixTimestamp |\n+------------+------------+---------------+-------------+---------------+\n| Shikhar | Dhawan | 1981-12-05 | India | 376338600 |\n| Jonathan | Trott | 1981-04-22 | SouthAfrica | 356725800 |\n| Kumara | Sangakkara | 1977-10-27 | Srilanka | 246738600 | \n| Virat | Kohli | 1988-11-05 | India | 594671400 |\n| Rohit | Sharma | 1987-04-30 | India | 546719400 |\n| Ravindra | Jadeja | 1988-12-06 | India | 597349800 |\n| James | Anderson | 1982-06-30 | England | 394223400 |\n+------------+------------+---------------+-------------+---------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 7019, "s": 6921, "text": "Let us create another table with name Sales in MySQL database using CREATE statement as follows –" }, { "code": null, "e": 7225, "s": 7019, "text": "mysql> CREATE TABLE sales(\n\tID INT,\n\tProductName VARCHAR(255),\n\tCustomerName VARCHAR(255),\n\tDispatchDate date,\n\tDispatchTime time,\n\tPrice INT,\n\tLocation VARCHAR(255)\n);\nQuery OK, 0 rows affected (2.22 sec)" }, { "code": null, "e": 7296, "s": 7225, "text": "Now, we will insert 5 records in Sales table using INSERT statements −" }, { "code": null, "e": 7829, "s": 7296, "text": "insert into sales values (1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into sales values (2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into sales values (3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into sales values (4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into sales values (5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 7941, "s": 7829, "text": "In the following query we are passing the DispatchTime column as an argument to the UNIX_TIMESTAMP() function —" }, { "code": null, "e": 8865, "s": 7941, "text": "mysql> SELECT ProductName, CustomerName, DispatchDate, DispatchTime, Price, UNIX_TIMESTAMP(DispatchTime) as UnixTimestamp FROM sales;\n+-------------+--------------+--------------+--------------+-------+---------------+\n| ProductName | CustomerName | DispatchDate | DispatchTime | Price | UnixTimestamp |\n+-------------+--------------+--------------+--------------+-------+---------------+\n| Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | 1626586200 |\n| Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | 1626586200 |\n| Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | 1626586199 |\n| Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | 1626583252 |\n| Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | 1626586739 |\n+-------------+--------------+--------------+--------------+-------+---------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 8970, "s": 8865, "text": "Suppose we have created a table named SubscribersData with 5 records in it using the following queries –" }, { "code": null, "e": 9580, "s": 8970, "text": "mysql> CREATE TABLE SubscribersData(\n\tSubscriberName VARCHAR(255),\n\tPackageName VARCHAR(255),\n\tSubscriptionDate date,\n\tSubscriptionTime time\n);\ninsert into SubscribersData values('Raja', 'Premium', Date('2020-10-21'), Time('20:53:49'));\ninsert into SubscribersData values('Roja', 'Basic', Date('2020-11-26'), Time('10:13:19'));\ninsert into SubscribersData values('Puja', 'Moderate', Date('2021-03-07'), Time('05:43:20'));\ninsert into SubscribersData values('Vanaja', 'Basic', Date('2021-02-21'), Time('16:36:39'));\ninsert into SubscribersData values('Jalaja', 'Premium', Date('2021-01-30'), Time('12:45:45'));" }, { "code": null, "e": 9709, "s": 9580, "text": "Following query displays the values of the columns SubscriptionDate, SubscriptionTime as a single column SubscriptionTimestamp –" }, { "code": null, "e": 10668, "s": 9709, "text": "mysql> SELECT SubscriberName, PackageName, SubscriptionDate, SubscriptionTime, UNIX_TIMESTAMP(SubscriptionDate) as UnixTimestamp FROM SubscribersData;\n+----------------+-------------+------------------+------------------+---------------+\n| SubscriberName | PackageName | SubscriptionDate | SubscriptionTime | UnixTimestamp |\n+----------------+-------------+------------------+------------------+---------------+\n| Raja | Premium | 2020-10-21 | 20:53:49 | 1603218600 |\n| Roja | Basic | 2020-11-26 | 10:13:19 | 1606329000 |\n| Puja | Moderate | 2021-03-07 | 05:43:20 | 1615055400 |\n| Vanaja | Basic | 2021-02-21 | 16:36:39 | 1613845800 |\n| Jalaja | Premium | 2021-01-30 | 12:45:45 | 1611945000 |\n+----------------+-------------+------------------+------------------+---------------+\n5 rows in set (0.13 sec)" }, { "code": null, "e": 10701, "s": 10668, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 10729, "s": 10701, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10764, "s": 10729, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10781, "s": 10764, "text": " Frahaan Hussain" }, { "code": null, "e": 10815, "s": 10781, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10850, "s": 10815, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 10884, "s": 10850, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 10912, "s": 10884, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 10945, "s": 10912, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10965, "s": 10945, "text": " Harshit Srivastava" }, { "code": null, "e": 10998, "s": 10965, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 11016, "s": 10998, "text": " Trevoir Williams" }, { "code": null, "e": 11023, "s": 11016, "text": " Print" }, { "code": null, "e": 11034, "s": 11023, "text": " Add Notes" } ]
Program for Christmas Tree in C
Here we will see one interesting problem. In this problem, we will see how to print Christmas tree randomly. So the tree will be flickering like Christmas tree lights. To print a Christmas tree, we will print pyramids of various sizes just one beneath another. For the decorative leaves a random character is printed from a given list of characters. The height and randomness is adjustable. Here after generating a tree, the whole screen is cleared, then generate again, that’s why this is looking like flickering tree. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define REFRESH_RATE 40000 #define RANDOM_NESS 5 // The higer value indicates less random void clear_screen() { system("@cls||clear"); } void display_random_leaf() { char type_of_leaves[5] = { '.', '*', '+', 'o', 'O' }; //these are the leaf types int temp = rand() % RANDOM_NESS; if (temp == 1) printf("%c ", type_of_leaves[rand() % 5]); //if temp is 1, then use other leaves else printf("%c ", type_of_leaves[1]); //otherwise print * } void tree_triangle(int f, int n, int toth) { int i, j, k = 2 * toth - 2; for (i = 0; i < f - 1; i++) k--; for (i = f - 1; i < n; i++) { //i will point the number of rows for (j = 0; j < k; j++) // Used to put spaces printf(" "); k = k - 1; for (j = 0; j <= i; j++) display_random_leaf(); printf("\n"); } } void display_tree(int h) { int start = 1, end = 0, diff = 3; while (end < h + 1) { end = start + diff; tree_triangle(start, end, h); diff++; start = end - 2; } } void display_log(int n) { //print the log of the tree int i, j, k = 2 * n - 4; for (i = 1; i <= 6; i++) { for (j = 0; j < k; j++) printf(" "); for (j = 1; j <= 6; j++) printf("#"); printf("\n"); } } main() { srand(time(NULL)); int ht = 15; while (1) { clear_screen(); display_tree(ht); display_log(ht); usleep(REFRESH_RATE); //use sleep before replacing } }
[ { "code": null, "e": 1230, "s": 1062, "text": "Here we will see one interesting problem. In this problem, we will see how to print Christmas tree randomly. So the tree will be flickering like Christmas tree lights." }, { "code": null, "e": 1453, "s": 1230, "text": "To print a Christmas tree, we will print pyramids of various sizes just one beneath another. For the decorative leaves a random character is printed from a given list of characters. The height and randomness is adjustable." }, { "code": null, "e": 1582, "s": 1453, "text": "Here after generating a tree, the whole screen is cleared, then generate again, that’s why this is looking like flickering tree." }, { "code": null, "e": 3123, "s": 1582, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <unistd.h>\n#define REFRESH_RATE 40000\n#define RANDOM_NESS 5 // The higer value indicates less random\nvoid clear_screen() {\n system(\"@cls||clear\");\n}\nvoid display_random_leaf() {\n char type_of_leaves[5] = { '.', '*', '+', 'o', 'O' }; //these are the leaf types\n int temp = rand() % RANDOM_NESS;\n if (temp == 1)\n printf(\"%c \", type_of_leaves[rand() % 5]); //if temp is 1, then use other leaves\n else\n printf(\"%c \", type_of_leaves[1]); //otherwise print *\n}\nvoid tree_triangle(int f, int n, int toth) {\n int i, j, k = 2 * toth - 2;\n for (i = 0; i < f - 1; i++)\n k--;\n for (i = f - 1; i < n; i++) { //i will point the number of rows\n for (j = 0; j < k; j++) // Used to put spaces\n printf(\" \");\n k = k - 1;\n for (j = 0; j <= i; j++)\n display_random_leaf();\n printf(\"\\n\");\n }\n}\nvoid display_tree(int h) {\n int start = 1, end = 0, diff = 3;\n while (end < h + 1) {\n end = start + diff;\n tree_triangle(start, end, h);\n diff++;\n start = end - 2;\n }\n}\nvoid display_log(int n) { //print the log of the tree\n int i, j, k = 2 * n - 4;\n for (i = 1; i <= 6; i++) {\n for (j = 0; j < k; j++)\n printf(\" \");\n for (j = 1; j <= 6; j++)\n printf(\"#\");\n printf(\"\\n\");\n }\n}\nmain() {\n srand(time(NULL));\n int ht = 15;\n while (1) {\n clear_screen();\n display_tree(ht);\n display_log(ht);\n usleep(REFRESH_RATE); //use sleep before replacing\n }\n}" } ]
Construct ∈-NFA of Regular Language L = {ab,ba}
The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ ε-NFA is defined in five tuple representation {Q, q0, Σ, δ, F} Where, δ − Q × (Σ∪ε)→2Q δ − Q × (Σ∪ε)→2Q Q − Finite set of states Q − Finite set of states Σ − Finite set of the input symbol Σ − Finite set of the input symbol q0 − Initial state q0 − Initial state F − Final state F − Final state δ − Transition function δ − Transition function NFA and NFA with epsilon both are almost the same; the only difference is their transition function. NFA transition function is as follows − δ − Q X Σ→ 2Q NFA with ε- transition functions is as follows − δ: Q × (Σ∪ε)→2Q Construct NFA with epsilon for a given language L= {ab, ba}. Follow the steps given below − Step 1 − NFA with epsilon for (a+b) is given below − It accepts either a or b as an input, and both go to the final state. Step 2 − NFA with epsilon for ab is as follows − Concatenating a and b with epsilon, and a must followed by b then only it can reach the final state. Step 3 − NFA with epsilon for ba is as follows − Concatenating b and a with epsilon, and b must follow by a then only it can reach the final state. Step 4 − Now the final NFA with epsilon for the language L={ab, ba}. The language consists of strings ab or ba, it can be written as (ab + ba). So the final ε-NFA having two paths, one path is for ab and another path is for ba both goes to the final state. In the above steps we individually construct the structures for ab and ba. Now, add those two structures to get our result.
[ { "code": null, "e": 1209, "s": 1062, "text": "The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ" }, { "code": null, "e": 1255, "s": 1209, "text": "ε-NFA is defined in five tuple representation" }, { "code": null, "e": 1272, "s": 1255, "text": "{Q, q0, Σ, δ, F}" }, { "code": null, "e": 1279, "s": 1272, "text": "Where," }, { "code": null, "e": 1296, "s": 1279, "text": "δ − Q × (Σ∪ε)→2Q" }, { "code": null, "e": 1313, "s": 1296, "text": "δ − Q × (Σ∪ε)→2Q" }, { "code": null, "e": 1338, "s": 1313, "text": "Q − Finite set of states" }, { "code": null, "e": 1363, "s": 1338, "text": "Q − Finite set of states" }, { "code": null, "e": 1398, "s": 1363, "text": "Σ − Finite set of the input symbol" }, { "code": null, "e": 1433, "s": 1398, "text": "Σ − Finite set of the input symbol" }, { "code": null, "e": 1452, "s": 1433, "text": "q0 − Initial state" }, { "code": null, "e": 1471, "s": 1452, "text": "q0 − Initial state" }, { "code": null, "e": 1487, "s": 1471, "text": "F − Final state" }, { "code": null, "e": 1503, "s": 1487, "text": "F − Final state" }, { "code": null, "e": 1527, "s": 1503, "text": "δ − Transition function" }, { "code": null, "e": 1551, "s": 1527, "text": "δ − Transition function" }, { "code": null, "e": 1652, "s": 1551, "text": "NFA and NFA with epsilon both are almost the same; the only difference is their transition function." }, { "code": null, "e": 1692, "s": 1652, "text": "NFA transition function is as follows −" }, { "code": null, "e": 1706, "s": 1692, "text": "δ − Q X Σ→ 2Q" }, { "code": null, "e": 1755, "s": 1706, "text": "NFA with ε- transition functions is as follows −" }, { "code": null, "e": 1771, "s": 1755, "text": "δ: Q × (Σ∪ε)→2Q" }, { "code": null, "e": 1832, "s": 1771, "text": "Construct NFA with epsilon for a given language L= {ab, ba}." }, { "code": null, "e": 1863, "s": 1832, "text": "Follow the steps given below −" }, { "code": null, "e": 1916, "s": 1863, "text": "Step 1 − NFA with epsilon for (a+b) is given below −" }, { "code": null, "e": 1986, "s": 1916, "text": "It accepts either a or b as an input, and both go to the final state." }, { "code": null, "e": 2035, "s": 1986, "text": "Step 2 − NFA with epsilon for ab is as follows −" }, { "code": null, "e": 2136, "s": 2035, "text": "Concatenating a and b with epsilon, and a must followed by b then only it can reach the final state." }, { "code": null, "e": 2185, "s": 2136, "text": "Step 3 − NFA with epsilon for ba is as follows −" }, { "code": null, "e": 2284, "s": 2185, "text": "Concatenating b and a with epsilon, and b must follow by a then only it can reach the final state." }, { "code": null, "e": 2353, "s": 2284, "text": "Step 4 − Now the final NFA with epsilon for the language L={ab, ba}." }, { "code": null, "e": 2541, "s": 2353, "text": "The language consists of strings ab or ba, it can be written as (ab + ba). So the final ε-NFA having two paths, one path is for ab and another path is for ba both goes to the final state." }, { "code": null, "e": 2665, "s": 2541, "text": "In the above steps we individually construct the structures for ab and ba. Now, add those two structures to get our result." } ]
Java Examples - New File Creation
How to create a new file ? This example demonstrates the way of creating a new file by using File() constructor and file.createNewFile() method of File class. import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { try { File file = new File("C:/myfile.txt"); if(file.createNewFile())System.out.println("Success!"); else System.out.println ("Error, file already exists."); } catch(IOException ioe) { ioe.printStackTrace(); } } } The above code sample will produce the following result (if "myfile.txt does not exist before) Success! The following is an another sample example of File create import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class JavaApplication1 { public static void main(String[] args) throws IOException { createFileUsingFileClass(); createFileUsingFileOutputStreamClass(); createFileIn_NIO(); // TODO code application logic here } private static void createFileUsingFileClass() throws IOException { File file = new File("c://testFile1.txt"); //Create the file if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } //Write Content FileWriter writer = new FileWriter(file); writer.write("Test data"); writer.close(); } private static void createFileUsingFileOutputStreamClass() throws IOException { String data = "Test data"; FileOutputStream out = new FileOutputStream("c://testFile2.txt"); out.write(data.getBytes()); out.close(); } private static void createFileIn_NIO() throws IOException { String data = "Test data"; Files.write(Paths.get("c://testFile3.txt"), data.getBytes()); List<String> lines = Arrays.asList("1st line", "2nd line"); Files.write(Paths.get( "file6.txt"), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2095, "s": 2068, "text": "How to create a new file ?" }, { "code": null, "e": 2227, "s": 2095, "text": "This example demonstrates the way of creating a new file by using File() constructor and file.createNewFile() method of File class." }, { "code": null, "e": 2628, "s": 2227, "text": "import java.io.File;\nimport java.io.IOException;\n\npublic class Main {\n public static void main(String[] args) {\n try {\n File file = new File(\"C:/myfile.txt\");\n \n if(file.createNewFile())System.out.println(\"Success!\");\n else System.out.println (\"Error, file already exists.\");\n }\n catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2723, "s": 2628, "text": "The above code sample will produce the following result (if \"myfile.txt does not exist before)" }, { "code": null, "e": 2733, "s": 2723, "text": "Success!\n" }, { "code": null, "e": 2791, "s": 2733, "text": "The following is an another sample example of File create" }, { "code": null, "e": 4454, "s": 2791, "text": "import java.io.IOException;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class JavaApplication1 { \n public static void main(String[] args) throws IOException {\n createFileUsingFileClass();\n createFileUsingFileOutputStreamClass();\n createFileIn_NIO();\n // TODO code application logic here\n } \n private static void createFileUsingFileClass() throws IOException { \n File file = new File(\"c://testFile1.txt\");\n \n //Create the file\n if (file.createNewFile()) { \n System.out.println(\"File is created!\");\n } else {\n System.out.println(\"File already exists.\");\n } \n \n //Write Content\n FileWriter writer = new FileWriter(file);\n writer.write(\"Test data\");\n writer.close();\n } \n private static void createFileUsingFileOutputStreamClass() throws IOException { \n String data = \"Test data\";\n FileOutputStream out = new FileOutputStream(\"c://testFile2.txt\");\n out.write(data.getBytes());\n out.close();\n } \n private static void createFileIn_NIO() throws IOException { \n String data = \"Test data\";\n Files.write(Paths.get(\"c://testFile3.txt\"), data.getBytes());\n List<String> lines = Arrays.asList(\"1st line\", \"2nd line\");\n Files.write(Paths.get(\n \"file6.txt\"), lines, StandardCharsets.UTF_8, \n StandardOpenOption.CREATE, StandardOpenOption.APPEND);\n }\n}" }, { "code": null, "e": 4461, "s": 4454, "text": " Print" }, { "code": null, "e": 4472, "s": 4461, "text": " Add Notes" } ]
Introduction to Linux Shell and Shell Scripting - GeeksforGeeks
26 Sep, 2017 If you are using any major operating system you are indirectly interacting to shell. If you are running Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every time you use terminal. In this article I will discuss about linux shells and shell scripting so before understanding shell scripting we have to get familiar with following terminologies – Kernel Shell TerminalWhat is KernelThe kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages following resources of the Linux system –File managementProcess managementI/O managementMemory managementDevice management etc.It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only responsible for development of Linux kernel.Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.What is ShellA shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal.linux shellShell is broadly classified into two categories –Command Line ShellGraphical shellCommand Line ShellShell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –linux command lineIn above screenshot “ls” command with “-l” option is executed.It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.Graphical ShellsGraphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –GUI shellThere are several shells are available for Linux systems like –BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc.Each shell does the same job but understand different commands and provide different built in functions.Shell ScriptingUsually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.shA shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements –Shell Keywords – if, else, break etc.Shell commands – cd, ls, echo, pwd, touch etc.FunctionsControl flow – if..then..else, case and shell loops etc.Why do we need shell scriptsThere are many reasons to write shell scripts –To avoid repetitive work and automationSystem admins use shell scripting for routine backupsSystem monitoringAdding new functionality to the shell etc.Advantages of shell scriptsThe command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntaxWriting shell scripts are much quickerQuick startInteractive debugging etc.Disadvantages of shell scriptsProne to costly errors, a single mistake can change the command which might be harmfulSlow execution speedDesign flaws within the language syntax or implementationNot well suited for large and complex taskProvide minimal data structure unlike other scripting languages. etcSimple demo of shell scripting using Bash ShellIf you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh”# !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to "/" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in "${path_arr[@]}" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ "$1" = "$dir" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done}For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command –$ chmod -x path/to/our/file/jump.sh Now to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command –$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc Now open you terminal and try out new “jump” functionality by typing following command-$ jump dir_name just like below screenshot –Resources for learning Bash Scriptinghttps://bash.cyberciti.biz/guide/The_bash_shellhttp://tldp.org/LDP/abs/html/Referenceshttps://en.wikipedia.org/wiki/Shell_scripthttps://en.wikipedia.org/wiki/Shell_(computing)This article is contributed by Atul Kumar. 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.My Personal Notes arrow_drop_upSave What is Kernel The kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages following resources of the Linux system – File management Process management I/O management Memory management Device management etc.It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only responsible for development of Linux kernel.Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.What is ShellA shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal.linux shellShell is broadly classified into two categories –Command Line ShellGraphical shellCommand Line ShellShell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –linux command lineIn above screenshot “ls” command with “-l” option is executed.It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.Graphical ShellsGraphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –GUI shellThere are several shells are available for Linux systems like –BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc.Each shell does the same job but understand different commands and provide different built in functions.Shell ScriptingUsually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.shA shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements –Shell Keywords – if, else, break etc.Shell commands – cd, ls, echo, pwd, touch etc.FunctionsControl flow – if..then..else, case and shell loops etc.Why do we need shell scriptsThere are many reasons to write shell scripts –To avoid repetitive work and automationSystem admins use shell scripting for routine backupsSystem monitoringAdding new functionality to the shell etc.Advantages of shell scriptsThe command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntaxWriting shell scripts are much quickerQuick startInteractive debugging etc.Disadvantages of shell scriptsProne to costly errors, a single mistake can change the command which might be harmfulSlow execution speedDesign flaws within the language syntax or implementationNot well suited for large and complex taskProvide minimal data structure unlike other scripting languages. etcSimple demo of shell scripting using Bash ShellIf you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh”# !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to "/" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in "${path_arr[@]}" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ "$1" = "$dir" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done}For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command –$ chmod -x path/to/our/file/jump.sh Now to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command –$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc Now open you terminal and try out new “jump” functionality by typing following command-$ jump dir_name just like below screenshot –Resources for learning Bash Scriptinghttps://bash.cyberciti.biz/guide/The_bash_shellhttp://tldp.org/LDP/abs/html/Referenceshttps://en.wikipedia.org/wiki/Shell_scripthttps://en.wikipedia.org/wiki/Shell_(computing)This article is contributed by Atul Kumar. 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.My Personal Notes arrow_drop_upSave What is Shell A shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal. linux shell Command Line Shell Graphical shell Command Line Shell Shell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this – linux command line It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems. Graphical Shells Graphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system – GUI shell There are several shells are available for Linux systems like – BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS. CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language. KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc. Each shell does the same job but understand different commands and provide different built in functions. Shell Scripting Usually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.sh A shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements – Shell Keywords – if, else, break etc. Shell commands – cd, ls, echo, pwd, touch etc. Functions Control flow – if..then..else, case and shell loops etc. Why do we need shell scripts There are many reasons to write shell scripts – To avoid repetitive work and automation System admins use shell scripting for routine backups System monitoring Adding new functionality to the shell etc. Advantages of shell scripts The command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntax Writing shell scripts are much quicker Quick start Interactive debugging etc. Disadvantages of shell scripts Prone to costly errors, a single mistake can change the command which might be harmful Slow execution speed Design flaws within the language syntax or implementation Not well suited for large and complex task Provide minimal data structure unlike other scripting languages. etc Simple demo of shell scripting using Bash Shell If you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory – It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh” # !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to "/" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in "${path_arr[@]}" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ "$1" = "$dir" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done} For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command – $ chmod -x path/to/our/file/jump.sh Now to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command – $ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc Now open you terminal and try out new “jump” functionality by typing following command- $ jump dir_name just like below screenshot – Resources for learning Bash Scripting https://bash.cyberciti.biz/guide/The_bash_shell http://tldp.org/LDP/abs/html/ References https://en.wikipedia.org/wiki/Shell_script https://en.wikipedia.org/wiki/Shell_(computing) This article is contributed by Atul Kumar. 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. Linux-Unix Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples 'crontab' in Linux with Examples echo command in Linux with Examples Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 24271, "s": 24243, "text": "\n26 Sep, 2017" }, { "code": null, "e": 24650, "s": 24271, "text": "If you are using any major operating system you are indirectly interacting to shell. If you are running Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every time you use terminal. In this article I will discuss about linux shells and shell scripting so before understanding shell scripting we have to get familiar with following terminologies –" }, { "code": null, "e": 24657, "s": 24650, "text": "Kernel" }, { "code": null, "e": 24663, "s": 24657, "text": "Shell" }, { "code": null, "e": 32258, "s": 24663, "text": "TerminalWhat is KernelThe kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages following resources of the Linux system –File managementProcess managementI/O managementMemory managementDevice management etc.It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only responsible for development of Linux kernel.Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.What is ShellA shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal.linux shellShell is broadly classified into two categories –Command Line ShellGraphical shellCommand Line ShellShell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –linux command lineIn above screenshot “ls” command with “-l” option is executed.It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.Graphical ShellsGraphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –GUI shellThere are several shells are available for Linux systems like –BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc.Each shell does the same job but understand different commands and provide different built in functions.Shell ScriptingUsually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.shA shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements –Shell Keywords – if, else, break etc.Shell commands – cd, ls, echo, pwd, touch etc.FunctionsControl flow – if..then..else, case and shell loops etc.Why do we need shell scriptsThere are many reasons to write shell scripts –To avoid repetitive work and automationSystem admins use shell scripting for routine backupsSystem monitoringAdding new functionality to the shell etc.Advantages of shell scriptsThe command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntaxWriting shell scripts are much quickerQuick startInteractive debugging etc.Disadvantages of shell scriptsProne to costly errors, a single mistake can change the command which might be harmfulSlow execution speedDesign flaws within the language syntax or implementationNot well suited for large and complex taskProvide minimal data structure unlike other scripting languages. etcSimple demo of shell scripting using Bash ShellIf you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh”# !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to \"/\" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in \"${path_arr[@]}\" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ \"$1\" = \"$dir\" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done}For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command –$ chmod -x path/to/our/file/jump.sh\nNow to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command –$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc\nNow open you terminal and try out new “jump” functionality by typing following command-$ jump dir_name\njust like below screenshot –Resources for learning Bash Scriptinghttps://bash.cyberciti.biz/guide/The_bash_shellhttp://tldp.org/LDP/abs/html/Referenceshttps://en.wikipedia.org/wiki/Shell_scripthttps://en.wikipedia.org/wiki/Shell_(computing)This article is contributed by Atul Kumar. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32273, "s": 32258, "text": "What is Kernel" }, { "code": null, "e": 32463, "s": 32273, "text": "The kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages following resources of the Linux system –" }, { "code": null, "e": 32479, "s": 32463, "text": "File management" }, { "code": null, "e": 32498, "s": 32479, "text": "Process management" }, { "code": null, "e": 32513, "s": 32498, "text": "I/O management" }, { "code": null, "e": 32531, "s": 32513, "text": "Memory management" }, { "code": null, "e": 39851, "s": 32531, "text": "Device management etc.It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only responsible for development of Linux kernel.Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.What is ShellA shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal.linux shellShell is broadly classified into two categories –Command Line ShellGraphical shellCommand Line ShellShell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –linux command lineIn above screenshot “ls” command with “-l” option is executed.It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.Graphical ShellsGraphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –GUI shellThere are several shells are available for Linux systems like –BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc.Each shell does the same job but understand different commands and provide different built in functions.Shell ScriptingUsually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.shA shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements –Shell Keywords – if, else, break etc.Shell commands – cd, ls, echo, pwd, touch etc.FunctionsControl flow – if..then..else, case and shell loops etc.Why do we need shell scriptsThere are many reasons to write shell scripts –To avoid repetitive work and automationSystem admins use shell scripting for routine backupsSystem monitoringAdding new functionality to the shell etc.Advantages of shell scriptsThe command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntaxWriting shell scripts are much quickerQuick startInteractive debugging etc.Disadvantages of shell scriptsProne to costly errors, a single mistake can change the command which might be harmfulSlow execution speedDesign flaws within the language syntax or implementationNot well suited for large and complex taskProvide minimal data structure unlike other scripting languages. etcSimple demo of shell scripting using Bash ShellIf you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh”# !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to \"/\" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in \"${path_arr[@]}\" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ \"$1\" = \"$dir\" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done}For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command –$ chmod -x path/to/our/file/jump.sh\nNow to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command –$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc\nNow open you terminal and try out new “jump” functionality by typing following command-$ jump dir_name\njust like below screenshot –Resources for learning Bash Scriptinghttps://bash.cyberciti.biz/guide/The_bash_shellhttp://tldp.org/LDP/abs/html/Referenceshttps://en.wikipedia.org/wiki/Shell_scripthttps://en.wikipedia.org/wiki/Shell_(computing)This article is contributed by Atul Kumar. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 39865, "s": 39851, "text": "What is Shell" }, { "code": null, "e": 40258, "s": 39865, "text": "A shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal." }, { "code": null, "e": 40270, "s": 40258, "text": "linux shell" }, { "code": null, "e": 40289, "s": 40270, "text": "Command Line Shell" }, { "code": null, "e": 40305, "s": 40289, "text": "Graphical shell" }, { "code": null, "e": 40324, "s": 40305, "text": "Command Line Shell" }, { "code": null, "e": 40682, "s": 40324, "text": "Shell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –" }, { "code": null, "e": 40701, "s": 40682, "text": "linux command line" }, { "code": null, "e": 41136, "s": 40701, "text": "It will list all the files in current working directory in long listing format.Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems." }, { "code": null, "e": 41153, "s": 41136, "text": "Graphical Shells" }, { "code": null, "e": 41577, "s": 41153, "text": "Graphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –" }, { "code": null, "e": 41587, "s": 41577, "text": "GUI shell" }, { "code": null, "e": 41651, "s": 41587, "text": "There are several shells are available for Linux systems like –" }, { "code": null, "e": 41831, "s": 41651, "text": "BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS." }, { "code": null, "e": 41926, "s": 41831, "text": "CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language." }, { "code": null, "e": 42027, "s": 41926, "text": "KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc." }, { "code": null, "e": 42132, "s": 42027, "text": "Each shell does the same job but understand different commands and provide different built in functions." }, { "code": null, "e": 42148, "s": 42132, "text": "Shell Scripting" }, { "code": null, "e": 42698, "s": 42148, "text": "Usually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.sh" }, { "code": null, "e": 42945, "s": 42698, "text": "A shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.A shell script comprises following elements –" }, { "code": null, "e": 42983, "s": 42945, "text": "Shell Keywords – if, else, break etc." }, { "code": null, "e": 43030, "s": 42983, "text": "Shell commands – cd, ls, echo, pwd, touch etc." }, { "code": null, "e": 43040, "s": 43030, "text": "Functions" }, { "code": null, "e": 43097, "s": 43040, "text": "Control flow – if..then..else, case and shell loops etc." }, { "code": null, "e": 43126, "s": 43097, "text": "Why do we need shell scripts" }, { "code": null, "e": 43174, "s": 43126, "text": "There are many reasons to write shell scripts –" }, { "code": null, "e": 43214, "s": 43174, "text": "To avoid repetitive work and automation" }, { "code": null, "e": 43268, "s": 43214, "text": "System admins use shell scripting for routine backups" }, { "code": null, "e": 43286, "s": 43268, "text": "System monitoring" }, { "code": null, "e": 43329, "s": 43286, "text": "Adding new functionality to the shell etc." }, { "code": null, "e": 43357, "s": 43329, "text": "Advantages of shell scripts" }, { "code": null, "e": 43509, "s": 43357, "text": "The command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntax" }, { "code": null, "e": 43548, "s": 43509, "text": "Writing shell scripts are much quicker" }, { "code": null, "e": 43560, "s": 43548, "text": "Quick start" }, { "code": null, "e": 43587, "s": 43560, "text": "Interactive debugging etc." }, { "code": null, "e": 43618, "s": 43587, "text": "Disadvantages of shell scripts" }, { "code": null, "e": 43705, "s": 43618, "text": "Prone to costly errors, a single mistake can change the command which might be harmful" }, { "code": null, "e": 43726, "s": 43705, "text": "Slow execution speed" }, { "code": null, "e": 43784, "s": 43726, "text": "Design flaws within the language syntax or implementation" }, { "code": null, "e": 43827, "s": 43784, "text": "Not well suited for large and complex task" }, { "code": null, "e": 43896, "s": 43827, "text": "Provide minimal data structure unlike other scripting languages. etc" }, { "code": null, "e": 43944, "s": 43896, "text": "Simple demo of shell scripting using Bash Shell" }, { "code": null, "e": 44148, "s": 43944, "text": "If you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –" }, { "code": null, "e": 44369, "s": 44148, "text": "It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing “cd ../” command again and again. Save the script as “jump.sh”" }, { "code": "# !/bin/bash # A simple bash script to move up to desired directory level directly function jump(){ # original value of Internal Field Separator OLDIFS=$IFS # setting field separator to \"/\" IFS=/ # converting working path into array of directories in path # eg. /my/path/is/like/this # into [, my, path, is, like, this] path_arr=($PWD) # setting IFS to original value IFS=$OLDIFS local pos=-1 # ${path_arr[@]} gives all the values in path_arr for dir in \"${path_arr[@]}\" do # find the number of directories to move up to # reach at target directory pos=$[$pos+1] if [ \"$1\" = \"$dir\" ];then # length of the path_arr dir_in_path=${#path_arr[@]} #current working directory cwd=$PWD limit=$[$dir_in_path-$pos-1] for ((i=0; i<limit; i++)) do cwd=$cwd/.. done cd $cwd break fi done}", "e": 45368, "s": 44369, "text": null }, { "code": null, "e": 45507, "s": 45368, "text": "For now we cannot execute our shell script because it do not have permissions. We have to make it executable by typing following command –" }, { "code": null, "e": 45544, "s": 45507, "text": "$ chmod -x path/to/our/file/jump.sh\n" }, { "code": null, "e": 45980, "s": 45544, "text": "Now to make this available on every terminal session, we have to put this in “.bashrc” file.“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions and aliases, define our prompt and define other settings that we want to use whenever we open a new terminal window.Now open terminal and type following command –" }, { "code": null, "e": 46036, "s": 45980, "text": "$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc\n" }, { "code": null, "e": 46124, "s": 46036, "text": "Now open you terminal and try out new “jump” functionality by typing following command-" }, { "code": null, "e": 46141, "s": 46124, "text": "$ jump dir_name\n" }, { "code": null, "e": 46170, "s": 46141, "text": "just like below screenshot –" }, { "code": null, "e": 46208, "s": 46170, "text": "Resources for learning Bash Scripting" }, { "code": null, "e": 46256, "s": 46208, "text": "https://bash.cyberciti.biz/guide/The_bash_shell" }, { "code": null, "e": 46286, "s": 46256, "text": "http://tldp.org/LDP/abs/html/" }, { "code": null, "e": 46297, "s": 46286, "text": "References" }, { "code": null, "e": 46340, "s": 46297, "text": "https://en.wikipedia.org/wiki/Shell_script" }, { "code": null, "e": 46388, "s": 46340, "text": "https://en.wikipedia.org/wiki/Shell_(computing)" }, { "code": null, "e": 46810, "s": 46388, "text": "This article is contributed by Atul Kumar. 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." }, { "code": null, "e": 46821, "s": 46810, "text": "Linux-Unix" }, { "code": null, "e": 46839, "s": 46821, "text": "Operating Systems" }, { "code": null, "e": 46857, "s": 46839, "text": "Operating Systems" }, { "code": null, "e": 46955, "s": 46857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46964, "s": 46955, "text": "Comments" }, { "code": null, "e": 46977, "s": 46964, "text": "Old Comments" }, { "code": null, "e": 47012, "s": 46977, "text": "tar command in Linux with examples" }, { "code": null, "e": 47050, "s": 47012, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 47085, "s": 47050, "text": "Cat command in Linux with examples" }, { "code": null, "e": 47118, "s": 47085, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 47154, "s": 47118, "text": "echo command in Linux with Examples" }, { "code": null, "e": 47193, "s": 47154, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 47220, "s": 47193, "text": "Types of Operating Systems" }, { "code": null, "e": 47269, "s": 47220, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 47309, "s": 47269, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
How to apply machine learning and deep learning methods to audio analysis | by Gideon Mendels | Towards Data Science
Author: Niko Laskaris, Customer Facing Data Scientist, Comet.ml To view the code, training visualizations, and more information about the python example at the end of this post, visit the Comet project page. While much of the writing and literature on deep learning concerns computer vision and natural language processing (NLP), audio analysis — a field that includes automatic speech recognition (ASR), digital signal processing, and music classification, tagging, and generation — is a growing subdomain of deep learning applications. Some of the most popular and widespread machine learning systems, virtual assistants Alexa, Siri and Google Home, are largely products built atop models that can extract information from audio signals. Many of our users at Comet are working on audio related machine learning tasks such as audio classification, speech recognition and speech synthesis, so we built them tools to analyze, explore and understand audio data using Comet’s meta machine-learning platform. Audio modeling, training and debugging using Comet This post is focused on showing how data scientists and AI practitioners can use Comet to apply machine learning and deep learning methods in the domain of audio analysis. To understand how models can extract information from digital audio signals, we’ll dive into some of the core feature engineering methods for audio analysis. We will then use Librosa, a great python library for audio analysis, to code up a short python example training a neural architecture on the UrbanSound8k dataset. Building machine learning models to classify, describe, or generate audio typically concerns modeling tasks where the input data are audio samples. Example waveform of an audio dataset sample from UrbanSound8k These audio samples are usually represented as time series, where the y-axis measurement is the amplitude of the waveform. The amplitude is usually measured as a function of the change in pressure around the microphone or receiver device that originally picked up the audio. Unless there is metadata associated with your audio samples, these time series signals will often be your only input data for fitting a model. Looking at the samples below, taken from each of the ten classes in the Urbansound8k dataset, it is clear from an eye test that the waveform itself may not necessarily yield clear class identifying information. Consider the waveforms for the engine_idling, siren, and jackhammer classes — they look quite similar. It turns out one of the best features to extract from audio waveforms (and digital signals in general) has been around since the 1980’s and is still state-of-the-art: Mel Frequency Cepstral Coefficients (MFCCs), introduced by Davis and Mermelstein in 1980. Below we will go through a technical discussion of how MFCCs are generated and why they are useful in audio analysis. This section is somewhat technical, so before we dive in, let’s define a few key terms pertaining to digital signal processing and audio analysis. We’ll link to wikipedia and additional resources if you’d like to dig even deeper. Sampling and Sampling Frequency In signal processing, sampling is the reduction of a continuous signal into a series of discrete values. The sampling frequency or rate is the number of samples taken over some fixed amount of time. A high sampling frequency results in less information loss but higher computational expense, and low sampling frequencies have higher information loss but are fast and cheap to compute. Amplitude The amplitude of a sound wave is a measure of its change over a period (usually of time). Another common definition of amplitude is a function of the magnitude of the difference between a variable’s extreme values. Fourier Transform The Fourier Transform decomposes a function of time (signal) into constituent frequencies. In the same way a musical chord can be expressed by the volumes and frequencies of its constituent notes, a Fourier Transform of a function displays the amplitude (amount) of each frequency present in the underlying function (signal). Top: a digital signal; Bottom: the Fourier Transform of the signal There are variants of the Fourier Transform including the Short-time fourier transform, which is implemented in the Librosa library and involves splitting an audio signal into frames and then taking the Fourier Transform of each frame. In audio processing generally, the Fourier is an elegant and useful way to decompose an audio signal into its constituent frequencies. *Resources: by far the best video I’ve found on the Fourier Transform is from 3Blue1Brown* Periodogram In signal processing, a periodogram is an estimate of the spectral density of a signal. The periodogram above shows the power spectrum of two sinusoidal basis functions of ~30Hz and ~50Hz. The output of a Fourier Transform can be thought of as being (not exactly) essentially a periodogram. Spectral Density The power spectrum of a time series is a way to describe the distribution of power into discrete frequency components composing that signal. The statistical average of a signal, measured by its frequency content, is called its spectrum. The spectral density of a digital signal describes the frequency content of the signal. Mel-Scale The mel-scale is a scale of pitches judged by listeners to be equal in distance from one another. The reference point between the mel-scale and normal frequency measurement is arbitrarily defined by assigning the perceptual pitch of 1000 mels to 1000 Hz. Above about 500 Hz, increasingly large intervals are judged by listeners to produce equal pitch increments. The name mel comes from the word melody to indicate the scale is based on pitch comparisons. The formula to convert f hertz into m mels is: Cepstrum The cepstrum is the result of taking the Fourier Transform of the logarithm of the estimated power spectrum of a signal. Stectrogram Mel-frequency spectrogram of an audio sample in the Urbansound8k dataset A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. A nice way to think about spectrograms is as a stacked view of periodograms across some time-interval digital signal. Cochlea The spiral cavity of the inner ear containing the organ of Corti, which produces nerve impulses in response to sound vibrations. Dataset preprocessing, feature extraction and feature engineering are steps we take to extract information from the underlying data, information that in a machine learning context should be useful for predicting the class of a sample or the value of some target variable. In audio analysis this process is largely based on finding components of an audio signal that can help us distinguish it from other signals. MFCCs, as mentioned above, remain a state of the art tool for extracting information from audio samples. Despite libraries like Librosa giving us a python one-liner to compute MFCCs for an audio sample, the underlying math is a bit complicated, so we’ll go through it step by step and include some useful links for further learning. Slice the signal into short frames (of time)Compute the periodogram estimate of the power spectrum for each frameApply the mel filterbank to the power spectra and sum the energy in each filterTake the discrete cosine transform (DCT) of the log filterbank energies Slice the signal into short frames (of time) Compute the periodogram estimate of the power spectrum for each frame Apply the mel filterbank to the power spectra and sum the energy in each filter Take the discrete cosine transform (DCT) of the log filterbank energies Excellent additional reading on MFCC derivation and computation can be found at blog posts here and here. Slice the signal into short frames Slice the signal into short frames Slicing the audio signal into short frames is useful in that it allows us to sample our audio into discrete time-steps. We assume that on short enough time scales the audio signal doesn’t change. Typical values for the duration of the short frames are between 20–40ms. It is also conventional to overlap each frame 10–15ms. *Note that the overlapping frames will make the features we eventually generate highly correlated. This is the basis for why we have to take the discrete cosine transform at the end of all of this.* 2. Compute the power spectrum for each frame Once we have our frames we need to calculate the power spectrum of each frame. The power spectrum of a time series describes the distribution of power into frequency components composing that signal. According to Fourier analysis, any physical signal can be decomposed into a number of discrete frequencies, or a spectrum of frequencies over a continuous range. The statistical average of a certain signal as analyzed in terms of its frequency content is called its spectrum. Source: University of Maryland, Harmonic Analysis and the Fourier Transform We apply the Short-time fourier transform to each frame to obtain a power spectra for each. 3. Apply the mel filterbank to the power spectra and sum the energy in each filter We still have some work to do once we have our power spectra. The human cochlea does not discern between nearby frequencies well, and this effect only becomes more pronounced as frequencies increase. The mel-scale is a tool that allows us to approximate the human auditory system’s response more closely than linear frequency bands. As can be seen in the visualization above, the mel filters get wider as the frequency increases — we care less about variations at higher frequencies. At low frequencies, where differences are more discernible to the human ear and thus more important in our analysis, the filters are narrow. The magnitudes from our power spectra, which were found by applying the Fourier transform to our input data, are binned by correlating them with each triangular Mel filter. This binning is usually applied such that each coefficient is multiplied by the corresponding filter gain, so each Mel filter comes to hold a weighted sum representing the spectral magnitude in that channel. Once we have our filterbank energies, we take the logarithm of each. This is yet another step motivated by the constraints of human hearing: humans don’t perceive changes in volume on a linear scale. To double the perceived volume of an audio wave, the wave’s energy must increase by a factor of 8. If an audiowave is already high volume (high energy), large variations in that wave’s energy may not sound very different. 4. Take the discrete cosine transform (DCT) of the log filterbank energies Because our filterbank energies are overlapping (see step 1), there is usually a strong correlation between them. Taking the discrete cosine transform can help decorrelate the energies. ***** Thankfully for us, the creators of Librosa have abstracted out a ton of this math and made it easy to generate MFCCs for your audio data. Let’s go through a simple python example to show how this analysis looks in action. We’re going to be fitting a simple neural network (keras + tensorflow backend) to the UrbanSound8k dataset. To begin let’s load our dependencies, including numpy, pandas, keras, scikit-learn, and librosa. #### Dependencies ######## Import Comet for experiment tracking and visual toolsfrom comet_ml import Experiment####import IPython.display as ipdimport numpy as npimport pandas as pdimport librosaimport matplotlib.pyplot as pltfrom scipy.io import wavfile as wavfrom sklearn import metrics from sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split from keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activationfrom keras.optimizers import Adamfrom keras.utils import to_categorical To begin, let’s create a Comet experiment as a wrapper for all of our work. We’ll be able to capture any and all artifacts (audio files, visualizations, model, dataset, system information, training metrics, etc.) automatically. experiment = Experiment(api_key="API_KEY", project_name="urbansound8k") Let’s load in the dataset and grab a sample for each class from the dataset. We can inspect these samples visually and acoustically using Comet. # Load datasetdf = pd.read_csv('UrbanSound8K/metadata/UrbanSound8K.csv')# Create a list of the class labelslabels = list(df['class'].unique())# Let's grab a single audio file from each classfiles = dict()for i in range(len(labels)): tmp = df[df['class'] == labels[i]][:1].reset_index() path = 'UrbanSound8K/audio/fold{}/{}'.format(tmp['fold'][0], tmp['slice_file_name'][0]) files[labels[i]] = path We can look at the waveforms for each sample using librosa’s display.waveplot function. fig = plt.figure(figsize=(15,15))# Log graphic of waveforms to Cometexperiment.log_image('class_examples.png')fig.subplots_adjust(hspace=0.4, wspace=0.4)for i, label in enumerate(labels): fn = files[label] fig.add_subplot(5, 2, i+1) plt.title(label) data, sample_rate = librosa.load(fn) librosa.display.waveplot(data, sr= sample_rate)plt.savefig('class_examples.png') We’ll save this graphic to our Comet experiment. # Log graphic of waveforms to Cometexperiment.log_image('class_examples.png') Next, we’ll log the audio files themselves. # Log audio files to Comet for debuggingfor label in labels: fn = files[label] experiment.log_audio(fn, metadata = {'name': label}) Once we log the samples to Comet, we can listen to samples, inspect metadata, and much more right from the UI. Preprocessing Now we can extract features from our data. We’re going to be using librosa, but we’ll also show another utility, scipy.io, for comparison and to observe some implicit preprocessing that’s happening. fn = 'UrbanSound8K/audio/fold1/191431-9-0-66.wav'librosa_audio, librosa_sample_rate = librosa.load(fn)scipy_sample_rate, scipy_audio = wav.read(fn)print("Original sample rate: {}".format(scipy_sample_rate))print("Librosa sample rate: {}".format(librosa_sample_rate)) Original sample rate: 48000Librosa sample rate: 22050 Librosa’s load function will convert the sampling rate to 22.05 KHz automatically. It will also normalize the bit depth between -1 and 1. print('Original audio file min~max range: {} to {}'.format(np.min(scipy_audio), np.max(scipy_audio)))print('Librosa audio file min~max range: {0:.2f} to {0:.2f}'.format(np.min(librosa_audio), np.max(librosa_audio))) >Original audio file min~max range: -1869 to 1665> Librosa audio file min~max range: -0.05 to -0.05 Librosa also converts the audio signal to mono from stereo. plt.figure(figsize=(12, 4))plt.plot(scipy_audio)plt.savefig('original_audio.png')experiment.log_image('original_audio.png') Original Audio (note that it’s in stereo — two audio sources) # Librosa: mono trackplt.figure(figsize=(12,4))plt.plot(librosa_audio)plt.savefig('librosa_audio.png')experiment.log_image('librosa_audio.png') Librosa audio: converted to mono Extracting MFCCs from audio using Librosa Remember all the math we went through to understand mel-frequency cepstrum coefficients earlier? Using Librosa, here’s how you extract them from audio (using the librosa_audio we defined above) mfccs = librosa.feature.mfcc(y=librosa_audio, sr=librosa_sample_rate, n_mfcc = 40) That’s it! print(mfccs.shape) > (40, 173) Librosa calculated 40 MFCCs over a 173 frame audio sample. plt.figure(figsize=(8,8))librosa.display.specshow(mfccs, sr=librosa_sample_rate, x_axis='time')plt.savefig('MFCCs.png')experiment.log_image('MFCCs.png') We’ll define a simple function to extract MFCCs for every file in our dataset. def extract_features(file_name):audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast') mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40) mfccs_processed = np.mean(mfccs.T,axis=0) return mfccs_processed Now let’s extract features. features = []# Iterate through each sound file and extract the features for index, row in metadata.iterrows():file_name = os.path.join(os.path.abspath(fulldatasetpath),'fold'+str(row["fold"])+'/',str(row["slice_file_name"])) class_label = row["class"] data = extract_features(file_name) features.append([data, class_label])# Convert into a Panda dataframe featuresdf = pd.DataFrame(features, columns=['feature','class_label']) We now have a dataframe where each row has a label (class) and a single feature column, comprised of 40 MFCCs. featuresdf.head() featuresdf.iloc[0]['feature'] array([-2.1579300e+02, 7.1666122e+01, -1.3181377e+02, -5.2091331e+01,-2.2115969e+01, -2.1764181e+01, -1.1183747e+01, 1.8912683e+01,6.7266388e+00, 1.4556893e+01, -1.1782045e+01, 2.3010368e+00, -1.7251305e+01, 1.0052421e+01, -6.0095000e+00, -1.3153191e+00, -1.7693510e+01, 1.1171228e+00, -4.3699470e+00, 7.2629538e+00, -1.1815971e+01, -7.4952612e+00, 5.4577131e+00, -2.9442446e+00, -5.8693886e+00, -9.8654032e-02, -3.2121708e+00, 4.6092505e+00, -5.8293257e+00, -5.3475075e+00, 1.3341187e+00, 7.1307826e+00, -7.9450034e-02, 1.7109241e+00, -5.6942000e+00, -2.9041715e+00, 3.0366952e+00, -1.6827590e+00, -8.8585770e-01, 3.5438776e-01], dtype=float32) Now that we have successfully extracted our features from the underlying audio data, we can build and train a model. Model building and training We’ll start by converting our MFCCs to numpy arrays, and encoding our classification labels. from sklearn.preprocessing import LabelEncoderfrom keras.utils import to_categorical# Convert features and corresponding classification labels into numpy arraysX = np.array(featuresdf.feature.tolist())y = np.array(featuresdf.class_label.tolist())# Encode the classification labelsle = LabelEncoder()yy = to_categorical(le.fit_transform(y)) Our dataset will be split into training and test sets. # split the dataset from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=0.2, random_state = 127) Let’s define and compile a simple feedforward neural network architecture. num_labels = yy.shape[1]filter_size = 2def build_model_graph(input_shape=(40,)): model = Sequential() model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_labels)) model.add(Activation('softmax')) # Compile the model model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') return modelmodel = build_model_graph() Let’s look at a model summary and compute pre-training accuracy. # Display model architecture summary model.summary()# Calculate pre-training accuracy score = model.evaluate(x_test, y_test, verbose=0)accuracy = 100*score[1] print("Pre-training accuracy: %.4f%%" % accuracy) Pre-training accuracy: 12.2496% Now it’s time to train our model. from keras.callbacks import ModelCheckpoint from datetime import datetime num_epochs = 100num_batch_size = 32model.fit(x_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(x_test, y_test), verbose=1) Training completed in time: Even before training completed, Comet keeps track of the key information about our experiment. We can visualize our accuracy and loss curves in real time from the Comet UI (note the orange spin wheel indicates that training is in process). Comet’s experiment visualization dashboard Once trained we can evaluate our model on the train and test data. # Evaluating the model on the training and testing setscore = model.evaluate(x_train, y_train, verbose=0)print("Training Accuracy: {0:.2%}".format(score[1]))score = model.evaluate(x_test, y_test, verbose=0)print("Testing Accuracy: {0:.2%}".format(score[1])) Training Accuracy: 93.00%Testing Accuracy: 87.35% Our model has trained rather well, but there is likely lots of room for improvement, perhaps using Comet’s Hyperparameter Optimization tool. In a small amount of code we’ve been able to extract mathematically complex MFCCs from audio data, build and train a neural network to classify audio based on those MFCCs, and evaluate our model on the test data.
[ { "code": null, "e": 236, "s": 172, "text": "Author: Niko Laskaris, Customer Facing Data Scientist, Comet.ml" }, { "code": null, "e": 380, "s": 236, "text": "To view the code, training visualizations, and more information about the python example at the end of this post, visit the Comet project page." }, { "code": null, "e": 912, "s": 380, "text": "While much of the writing and literature on deep learning concerns computer vision and natural language processing (NLP), audio analysis — a field that includes automatic speech recognition (ASR), digital signal processing, and music classification, tagging, and generation — is a growing subdomain of deep learning applications. Some of the most popular and widespread machine learning systems, virtual assistants Alexa, Siri and Google Home, are largely products built atop models that can extract information from audio signals." }, { "code": null, "e": 1177, "s": 912, "text": "Many of our users at Comet are working on audio related machine learning tasks such as audio classification, speech recognition and speech synthesis, so we built them tools to analyze, explore and understand audio data using Comet’s meta machine-learning platform." }, { "code": null, "e": 1228, "s": 1177, "text": "Audio modeling, training and debugging using Comet" }, { "code": null, "e": 1721, "s": 1228, "text": "This post is focused on showing how data scientists and AI practitioners can use Comet to apply machine learning and deep learning methods in the domain of audio analysis. To understand how models can extract information from digital audio signals, we’ll dive into some of the core feature engineering methods for audio analysis. We will then use Librosa, a great python library for audio analysis, to code up a short python example training a neural architecture on the UrbanSound8k dataset." }, { "code": null, "e": 1869, "s": 1721, "text": "Building machine learning models to classify, describe, or generate audio typically concerns modeling tasks where the input data are audio samples." }, { "code": null, "e": 1931, "s": 1869, "text": "Example waveform of an audio dataset sample from UrbanSound8k" }, { "code": null, "e": 2349, "s": 1931, "text": "These audio samples are usually represented as time series, where the y-axis measurement is the amplitude of the waveform. The amplitude is usually measured as a function of the change in pressure around the microphone or receiver device that originally picked up the audio. Unless there is metadata associated with your audio samples, these time series signals will often be your only input data for fitting a model." }, { "code": null, "e": 2663, "s": 2349, "text": "Looking at the samples below, taken from each of the ten classes in the Urbansound8k dataset, it is clear from an eye test that the waveform itself may not necessarily yield clear class identifying information. Consider the waveforms for the engine_idling, siren, and jackhammer classes — they look quite similar." }, { "code": null, "e": 3268, "s": 2663, "text": "It turns out one of the best features to extract from audio waveforms (and digital signals in general) has been around since the 1980’s and is still state-of-the-art: Mel Frequency Cepstral Coefficients (MFCCs), introduced by Davis and Mermelstein in 1980. Below we will go through a technical discussion of how MFCCs are generated and why they are useful in audio analysis. This section is somewhat technical, so before we dive in, let’s define a few key terms pertaining to digital signal processing and audio analysis. We’ll link to wikipedia and additional resources if you’d like to dig even deeper." }, { "code": null, "e": 3300, "s": 3268, "text": "Sampling and Sampling Frequency" }, { "code": null, "e": 3685, "s": 3300, "text": "In signal processing, sampling is the reduction of a continuous signal into a series of discrete values. The sampling frequency or rate is the number of samples taken over some fixed amount of time. A high sampling frequency results in less information loss but higher computational expense, and low sampling frequencies have higher information loss but are fast and cheap to compute." }, { "code": null, "e": 3695, "s": 3685, "text": "Amplitude" }, { "code": null, "e": 3910, "s": 3695, "text": "The amplitude of a sound wave is a measure of its change over a period (usually of time). Another common definition of amplitude is a function of the magnitude of the difference between a variable’s extreme values." }, { "code": null, "e": 3928, "s": 3910, "text": "Fourier Transform" }, { "code": null, "e": 4254, "s": 3928, "text": "The Fourier Transform decomposes a function of time (signal) into constituent frequencies. In the same way a musical chord can be expressed by the volumes and frequencies of its constituent notes, a Fourier Transform of a function displays the amplitude (amount) of each frequency present in the underlying function (signal)." }, { "code": null, "e": 4321, "s": 4254, "text": "Top: a digital signal; Bottom: the Fourier Transform of the signal" }, { "code": null, "e": 4692, "s": 4321, "text": "There are variants of the Fourier Transform including the Short-time fourier transform, which is implemented in the Librosa library and involves splitting an audio signal into frames and then taking the Fourier Transform of each frame. In audio processing generally, the Fourier is an elegant and useful way to decompose an audio signal into its constituent frequencies." }, { "code": null, "e": 4783, "s": 4692, "text": "*Resources: by far the best video I’ve found on the Fourier Transform is from 3Blue1Brown*" }, { "code": null, "e": 4795, "s": 4783, "text": "Periodogram" }, { "code": null, "e": 5086, "s": 4795, "text": "In signal processing, a periodogram is an estimate of the spectral density of a signal. The periodogram above shows the power spectrum of two sinusoidal basis functions of ~30Hz and ~50Hz. The output of a Fourier Transform can be thought of as being (not exactly) essentially a periodogram." }, { "code": null, "e": 5103, "s": 5086, "text": "Spectral Density" }, { "code": null, "e": 5428, "s": 5103, "text": "The power spectrum of a time series is a way to describe the distribution of power into discrete frequency components composing that signal. The statistical average of a signal, measured by its frequency content, is called its spectrum. The spectral density of a digital signal describes the frequency content of the signal." }, { "code": null, "e": 5438, "s": 5428, "text": "Mel-Scale" }, { "code": null, "e": 5894, "s": 5438, "text": "The mel-scale is a scale of pitches judged by listeners to be equal in distance from one another. The reference point between the mel-scale and normal frequency measurement is arbitrarily defined by assigning the perceptual pitch of 1000 mels to 1000 Hz. Above about 500 Hz, increasingly large intervals are judged by listeners to produce equal pitch increments. The name mel comes from the word melody to indicate the scale is based on pitch comparisons." }, { "code": null, "e": 5941, "s": 5894, "text": "The formula to convert f hertz into m mels is:" }, { "code": null, "e": 5950, "s": 5941, "text": "Cepstrum" }, { "code": null, "e": 6071, "s": 5950, "text": "The cepstrum is the result of taking the Fourier Transform of the logarithm of the estimated power spectrum of a signal." }, { "code": null, "e": 6083, "s": 6071, "text": "Stectrogram" }, { "code": null, "e": 6156, "s": 6083, "text": "Mel-frequency spectrogram of an audio sample in the Urbansound8k dataset" }, { "code": null, "e": 6382, "s": 6156, "text": "A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. A nice way to think about spectrograms is as a stacked view of periodograms across some time-interval digital signal." }, { "code": null, "e": 6390, "s": 6382, "text": "Cochlea" }, { "code": null, "e": 6519, "s": 6390, "text": "The spiral cavity of the inner ear containing the organ of Corti, which produces nerve impulses in response to sound vibrations." }, { "code": null, "e": 6932, "s": 6519, "text": "Dataset preprocessing, feature extraction and feature engineering are steps we take to extract information from the underlying data, information that in a machine learning context should be useful for predicting the class of a sample or the value of some target variable. In audio analysis this process is largely based on finding components of an audio signal that can help us distinguish it from other signals." }, { "code": null, "e": 7265, "s": 6932, "text": "MFCCs, as mentioned above, remain a state of the art tool for extracting information from audio samples. Despite libraries like Librosa giving us a python one-liner to compute MFCCs for an audio sample, the underlying math is a bit complicated, so we’ll go through it step by step and include some useful links for further learning." }, { "code": null, "e": 7529, "s": 7265, "text": "Slice the signal into short frames (of time)Compute the periodogram estimate of the power spectrum for each frameApply the mel filterbank to the power spectra and sum the energy in each filterTake the discrete cosine transform (DCT) of the log filterbank energies" }, { "code": null, "e": 7574, "s": 7529, "text": "Slice the signal into short frames (of time)" }, { "code": null, "e": 7644, "s": 7574, "text": "Compute the periodogram estimate of the power spectrum for each frame" }, { "code": null, "e": 7724, "s": 7644, "text": "Apply the mel filterbank to the power spectra and sum the energy in each filter" }, { "code": null, "e": 7796, "s": 7724, "text": "Take the discrete cosine transform (DCT) of the log filterbank energies" }, { "code": null, "e": 7902, "s": 7796, "text": "Excellent additional reading on MFCC derivation and computation can be found at blog posts here and here." }, { "code": null, "e": 7937, "s": 7902, "text": "Slice the signal into short frames" }, { "code": null, "e": 7972, "s": 7937, "text": "Slice the signal into short frames" }, { "code": null, "e": 8296, "s": 7972, "text": "Slicing the audio signal into short frames is useful in that it allows us to sample our audio into discrete time-steps. We assume that on short enough time scales the audio signal doesn’t change. Typical values for the duration of the short frames are between 20–40ms. It is also conventional to overlap each frame 10–15ms." }, { "code": null, "e": 8495, "s": 8296, "text": "*Note that the overlapping frames will make the features we eventually generate highly correlated. This is the basis for why we have to take the discrete cosine transform at the end of all of this.*" }, { "code": null, "e": 8540, "s": 8495, "text": "2. Compute the power spectrum for each frame" }, { "code": null, "e": 9016, "s": 8540, "text": "Once we have our frames we need to calculate the power spectrum of each frame. The power spectrum of a time series describes the distribution of power into frequency components composing that signal. According to Fourier analysis, any physical signal can be decomposed into a number of discrete frequencies, or a spectrum of frequencies over a continuous range. The statistical average of a certain signal as analyzed in terms of its frequency content is called its spectrum." }, { "code": null, "e": 9092, "s": 9016, "text": "Source: University of Maryland, Harmonic Analysis and the Fourier Transform" }, { "code": null, "e": 9184, "s": 9092, "text": "We apply the Short-time fourier transform to each frame to obtain a power spectra for each." }, { "code": null, "e": 9267, "s": 9184, "text": "3. Apply the mel filterbank to the power spectra and sum the energy in each filter" }, { "code": null, "e": 9600, "s": 9267, "text": "We still have some work to do once we have our power spectra. The human cochlea does not discern between nearby frequencies well, and this effect only becomes more pronounced as frequencies increase. The mel-scale is a tool that allows us to approximate the human auditory system’s response more closely than linear frequency bands." }, { "code": null, "e": 9892, "s": 9600, "text": "As can be seen in the visualization above, the mel filters get wider as the frequency increases — we care less about variations at higher frequencies. At low frequencies, where differences are more discernible to the human ear and thus more important in our analysis, the filters are narrow." }, { "code": null, "e": 10273, "s": 9892, "text": "The magnitudes from our power spectra, which were found by applying the Fourier transform to our input data, are binned by correlating them with each triangular Mel filter. This binning is usually applied such that each coefficient is multiplied by the corresponding filter gain, so each Mel filter comes to hold a weighted sum representing the spectral magnitude in that channel." }, { "code": null, "e": 10695, "s": 10273, "text": "Once we have our filterbank energies, we take the logarithm of each. This is yet another step motivated by the constraints of human hearing: humans don’t perceive changes in volume on a linear scale. To double the perceived volume of an audio wave, the wave’s energy must increase by a factor of 8. If an audiowave is already high volume (high energy), large variations in that wave’s energy may not sound very different." }, { "code": null, "e": 10770, "s": 10695, "text": "4. Take the discrete cosine transform (DCT) of the log filterbank energies" }, { "code": null, "e": 10956, "s": 10770, "text": "Because our filterbank energies are overlapping (see step 1), there is usually a strong correlation between them. Taking the discrete cosine transform can help decorrelate the energies." }, { "code": null, "e": 10962, "s": 10956, "text": "*****" }, { "code": null, "e": 11184, "s": 10962, "text": "Thankfully for us, the creators of Librosa have abstracted out a ton of this math and made it easy to generate MFCCs for your audio data. Let’s go through a simple python example to show how this analysis looks in action." }, { "code": null, "e": 11389, "s": 11184, "text": "We’re going to be fitting a simple neural network (keras + tensorflow backend) to the UrbanSound8k dataset. To begin let’s load our dependencies, including numpy, pandas, keras, scikit-learn, and librosa." }, { "code": null, "e": 11935, "s": 11389, "text": "#### Dependencies ######## Import Comet for experiment tracking and visual toolsfrom comet_ml import Experiment####import IPython.display as ipdimport numpy as npimport pandas as pdimport librosaimport matplotlib.pyplot as pltfrom scipy.io import wavfile as wavfrom sklearn import metrics from sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split from keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activationfrom keras.optimizers import Adamfrom keras.utils import to_categorical" }, { "code": null, "e": 12163, "s": 11935, "text": "To begin, let’s create a Comet experiment as a wrapper for all of our work. We’ll be able to capture any and all artifacts (audio files, visualizations, model, dataset, system information, training metrics, etc.) automatically." }, { "code": null, "e": 12258, "s": 12163, "text": "experiment = Experiment(api_key=\"API_KEY\", project_name=\"urbansound8k\")" }, { "code": null, "e": 12403, "s": 12258, "text": "Let’s load in the dataset and grab a sample for each class from the dataset. We can inspect these samples visually and acoustically using Comet." }, { "code": null, "e": 12810, "s": 12403, "text": "# Load datasetdf = pd.read_csv('UrbanSound8K/metadata/UrbanSound8K.csv')# Create a list of the class labelslabels = list(df['class'].unique())# Let's grab a single audio file from each classfiles = dict()for i in range(len(labels)): tmp = df[df['class'] == labels[i]][:1].reset_index() path = 'UrbanSound8K/audio/fold{}/{}'.format(tmp['fold'][0], tmp['slice_file_name'][0]) files[labels[i]] = path" }, { "code": null, "e": 12898, "s": 12810, "text": "We can look at the waveforms for each sample using librosa’s display.waveplot function." }, { "code": null, "e": 13281, "s": 12898, "text": "fig = plt.figure(figsize=(15,15))# Log graphic of waveforms to Cometexperiment.log_image('class_examples.png')fig.subplots_adjust(hspace=0.4, wspace=0.4)for i, label in enumerate(labels): fn = files[label] fig.add_subplot(5, 2, i+1) plt.title(label) data, sample_rate = librosa.load(fn) librosa.display.waveplot(data, sr= sample_rate)plt.savefig('class_examples.png')" }, { "code": null, "e": 13330, "s": 13281, "text": "We’ll save this graphic to our Comet experiment." }, { "code": null, "e": 13408, "s": 13330, "text": "# Log graphic of waveforms to Cometexperiment.log_image('class_examples.png')" }, { "code": null, "e": 13452, "s": 13408, "text": "Next, we’ll log the audio files themselves." }, { "code": null, "e": 13590, "s": 13452, "text": "# Log audio files to Comet for debuggingfor label in labels: fn = files[label] experiment.log_audio(fn, metadata = {'name': label})" }, { "code": null, "e": 13701, "s": 13590, "text": "Once we log the samples to Comet, we can listen to samples, inspect metadata, and much more right from the UI." }, { "code": null, "e": 13715, "s": 13701, "text": "Preprocessing" }, { "code": null, "e": 13914, "s": 13715, "text": "Now we can extract features from our data. We’re going to be using librosa, but we’ll also show another utility, scipy.io, for comparison and to observe some implicit preprocessing that’s happening." }, { "code": null, "e": 14181, "s": 13914, "text": "fn = 'UrbanSound8K/audio/fold1/191431-9-0-66.wav'librosa_audio, librosa_sample_rate = librosa.load(fn)scipy_sample_rate, scipy_audio = wav.read(fn)print(\"Original sample rate: {}\".format(scipy_sample_rate))print(\"Librosa sample rate: {}\".format(librosa_sample_rate))" }, { "code": null, "e": 14235, "s": 14181, "text": "Original sample rate: 48000Librosa sample rate: 22050" }, { "code": null, "e": 14373, "s": 14235, "text": "Librosa’s load function will convert the sampling rate to 22.05 KHz automatically. It will also normalize the bit depth between -1 and 1." }, { "code": null, "e": 14589, "s": 14373, "text": "print('Original audio file min~max range: {} to {}'.format(np.min(scipy_audio), np.max(scipy_audio)))print('Librosa audio file min~max range: {0:.2f} to {0:.2f}'.format(np.min(librosa_audio), np.max(librosa_audio)))" }, { "code": null, "e": 14689, "s": 14589, "text": ">Original audio file min~max range: -1869 to 1665> Librosa audio file min~max range: -0.05 to -0.05" }, { "code": null, "e": 14749, "s": 14689, "text": "Librosa also converts the audio signal to mono from stereo." }, { "code": null, "e": 14873, "s": 14749, "text": "plt.figure(figsize=(12, 4))plt.plot(scipy_audio)plt.savefig('original_audio.png')experiment.log_image('original_audio.png')" }, { "code": null, "e": 14935, "s": 14873, "text": "Original Audio (note that it’s in stereo — two audio sources)" }, { "code": null, "e": 15079, "s": 14935, "text": "# Librosa: mono trackplt.figure(figsize=(12,4))plt.plot(librosa_audio)plt.savefig('librosa_audio.png')experiment.log_image('librosa_audio.png')" }, { "code": null, "e": 15112, "s": 15079, "text": "Librosa audio: converted to mono" }, { "code": null, "e": 15154, "s": 15112, "text": "Extracting MFCCs from audio using Librosa" }, { "code": null, "e": 15348, "s": 15154, "text": "Remember all the math we went through to understand mel-frequency cepstrum coefficients earlier? Using Librosa, here’s how you extract them from audio (using the librosa_audio we defined above)" }, { "code": null, "e": 15431, "s": 15348, "text": "mfccs = librosa.feature.mfcc(y=librosa_audio, sr=librosa_sample_rate, n_mfcc = 40)" }, { "code": null, "e": 15442, "s": 15431, "text": "That’s it!" }, { "code": null, "e": 15461, "s": 15442, "text": "print(mfccs.shape)" }, { "code": null, "e": 15473, "s": 15461, "text": "> (40, 173)" }, { "code": null, "e": 15532, "s": 15473, "text": "Librosa calculated 40 MFCCs over a 173 frame audio sample." }, { "code": null, "e": 15685, "s": 15532, "text": "plt.figure(figsize=(8,8))librosa.display.specshow(mfccs, sr=librosa_sample_rate, x_axis='time')plt.savefig('MFCCs.png')experiment.log_image('MFCCs.png')" }, { "code": null, "e": 15764, "s": 15685, "text": "We’ll define a simple function to extract MFCCs for every file in our dataset." }, { "code": null, "e": 16010, "s": 15764, "text": "def extract_features(file_name):audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast') mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40) mfccs_processed = np.mean(mfccs.T,axis=0) return mfccs_processed" }, { "code": null, "e": 16038, "s": 16010, "text": "Now let’s extract features." }, { "code": null, "e": 16482, "s": 16038, "text": "features = []# Iterate through each sound file and extract the features for index, row in metadata.iterrows():file_name = os.path.join(os.path.abspath(fulldatasetpath),'fold'+str(row[\"fold\"])+'/',str(row[\"slice_file_name\"])) class_label = row[\"class\"] data = extract_features(file_name) features.append([data, class_label])# Convert into a Panda dataframe featuresdf = pd.DataFrame(features, columns=['feature','class_label'])" }, { "code": null, "e": 16593, "s": 16482, "text": "We now have a dataframe where each row has a label (class) and a single feature column, comprised of 40 MFCCs." }, { "code": null, "e": 16611, "s": 16593, "text": "featuresdf.head()" }, { "code": null, "e": 16641, "s": 16611, "text": "featuresdf.iloc[0]['feature']" }, { "code": null, "e": 17287, "s": 16641, "text": "array([-2.1579300e+02, 7.1666122e+01, -1.3181377e+02, -5.2091331e+01,-2.2115969e+01, -2.1764181e+01, -1.1183747e+01, 1.8912683e+01,6.7266388e+00, 1.4556893e+01, -1.1782045e+01, 2.3010368e+00, -1.7251305e+01, 1.0052421e+01, -6.0095000e+00, -1.3153191e+00, -1.7693510e+01, 1.1171228e+00, -4.3699470e+00, 7.2629538e+00, -1.1815971e+01, -7.4952612e+00, 5.4577131e+00, -2.9442446e+00, -5.8693886e+00, -9.8654032e-02, -3.2121708e+00, 4.6092505e+00, -5.8293257e+00, -5.3475075e+00, 1.3341187e+00, 7.1307826e+00, -7.9450034e-02, 1.7109241e+00, -5.6942000e+00, -2.9041715e+00, 3.0366952e+00, -1.6827590e+00, -8.8585770e-01, 3.5438776e-01], dtype=float32)" }, { "code": null, "e": 17404, "s": 17287, "text": "Now that we have successfully extracted our features from the underlying audio data, we can build and train a model." }, { "code": null, "e": 17432, "s": 17404, "text": "Model building and training" }, { "code": null, "e": 17525, "s": 17432, "text": "We’ll start by converting our MFCCs to numpy arrays, and encoding our classification labels." }, { "code": null, "e": 17865, "s": 17525, "text": "from sklearn.preprocessing import LabelEncoderfrom keras.utils import to_categorical# Convert features and corresponding classification labels into numpy arraysX = np.array(featuresdf.feature.tolist())y = np.array(featuresdf.class_label.tolist())# Encode the classification labelsle = LabelEncoder()yy = to_categorical(le.fit_transform(y))" }, { "code": null, "e": 17920, "s": 17865, "text": "Our dataset will be split into training and test sets." }, { "code": null, "e": 18087, "s": 17920, "text": "# split the dataset from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=0.2, random_state = 127)" }, { "code": null, "e": 18162, "s": 18087, "text": "Let’s define and compile a simple feedforward neural network architecture." }, { "code": null, "e": 18661, "s": 18162, "text": "num_labels = yy.shape[1]filter_size = 2def build_model_graph(input_shape=(40,)): model = Sequential() model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_labels)) model.add(Activation('softmax')) # Compile the model model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') return modelmodel = build_model_graph()" }, { "code": null, "e": 18726, "s": 18661, "text": "Let’s look at a model summary and compute pre-training accuracy." }, { "code": null, "e": 18885, "s": 18726, "text": "# Display model architecture summary model.summary()# Calculate pre-training accuracy score = model.evaluate(x_test, y_test, verbose=0)accuracy = 100*score[1]" }, { "code": null, "e": 18935, "s": 18885, "text": "print(\"Pre-training accuracy: %.4f%%\" % accuracy)" }, { "code": null, "e": 18967, "s": 18935, "text": "Pre-training accuracy: 12.2496%" }, { "code": null, "e": 19001, "s": 18967, "text": "Now it’s time to train our model." }, { "code": null, "e": 19229, "s": 19001, "text": "from keras.callbacks import ModelCheckpoint from datetime import datetime num_epochs = 100num_batch_size = 32model.fit(x_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(x_test, y_test), verbose=1)" }, { "code": null, "e": 19257, "s": 19229, "text": "Training completed in time:" }, { "code": null, "e": 19497, "s": 19257, "text": "Even before training completed, Comet keeps track of the key information about our experiment. We can visualize our accuracy and loss curves in real time from the Comet UI (note the orange spin wheel indicates that training is in process)." }, { "code": null, "e": 19540, "s": 19497, "text": "Comet’s experiment visualization dashboard" }, { "code": null, "e": 19607, "s": 19540, "text": "Once trained we can evaluate our model on the train and test data." }, { "code": null, "e": 19865, "s": 19607, "text": "# Evaluating the model on the training and testing setscore = model.evaluate(x_train, y_train, verbose=0)print(\"Training Accuracy: {0:.2%}\".format(score[1]))score = model.evaluate(x_test, y_test, verbose=0)print(\"Testing Accuracy: {0:.2%}\".format(score[1]))" }, { "code": null, "e": 19915, "s": 19865, "text": "Training Accuracy: 93.00%Testing Accuracy: 87.35%" } ]
Medical Image Analysis using probabilistic layers and Grad-Cam | by Rik Kraan | Towards Data Science
Interest in artificial intelligence applications for image analysis in healthcare is increasing fast. The number of publications in academic journals concerning machine learning is growing exponentially and consequently several image-recognition applications have been implemented in daily clinical practice. Accurate algorithms can serve as additional diagnostic tools for physicians in order to facilitate and accelerate the workflow and, most importantly, improve the accuracy of the diagnostic process. Image analysis algorithms should be added to the physician’s toolbox and not be regarded as a potential replacement of medical specialists. Despite physicians being concerned with and responsible for their patients’ well-being, most are not familiar with the mathematical details of machine learning algorithms. Therefore, medical applications should not serve as ‘black boxes’, but provide additional information on how the model came to its predictions. This blog demonstrates two possible techniques for acquiring this information: probabilistic layers, which can be used to address the uncertainty on a model’s predictions and Grad-CAM a method for demonstrating which pixels contribute most to the model’s outcome. In this blog we will focus on dermatoscopic images, but the presented techniques are applicable to other medical fields (e.g. radiology and pathology) as well. The two techniques will be illustrated using Kaggle’s public HAM (“Human Against Machine”) 10000 dataset which contains over 10000 images of 7 classes of pigmented skin lesions, including several types of skin cancer (i.e. melanoma and basal cell carcinoma) and less invasive types like benign keratosis-like lesions and physiological melanocytic lesions. Although the dataset contains additional features as age and location valuable for classifying skin lesions, for illustrative purposes this blog will merely focus on the imaging data. On the left several example images, all obtained with a dermatoscope are depicted. First, a basic convolutional neural network was trained using the VGG16 architecture with predefined weights. The weights of the first layers were frozen and only the last 6 layers were retrained. An additional dense layer with a softmax activation function was added. After 10 epochs of training the transfer learned model yielded a validation accuracy of 82%. At this moment, the output of the model consists of an array representing the probabilities an image belongs to each of the 7 classes (see below). [[2.3303068e-09 1.2782693e-10 1.4191615e-02 1.8526940e-14 3.9408263e-02 9.4640017e-01 2.1815825e-11]] These predictions can already guide physicians in the right direction, however additional information of the model’s method of ‘thinking’ will increase understanding of and trust in these kind of deep learning models. The next sections will illustrate that for this purpose probabilistic layers and Grad-CAM can be extremely valuable. Adding a probabilistic layer to a model’s architecture is a valuable method to evaluate the uncertainty of a model’s predictions. The fundamental difference between ‘normal’ and probabilistic layers is that probabilistic layers assume weights to have a certain distribution instead of being point estimates. Probabilistic layers approximate the posterior distribution of the weights by variational inference. Essentially, the posterior distribution is approximated through a Gaussian distributed surrogate function. During each forward pass, weights of a probabilistic layer are sampled from this surrogate distribution. As a consequence, introducing the same input multiple times will result in slightly different predictions each time. In a classification problem, the model will yield a distribution of probabilities for each class. This probability distribution can be used to asses the uncertainty of a model’s predictions: if the uncertainty is limited, repeated predictions will be very close to each other, while a wide distribution of predictions imply a large model uncertainty. This blog will focus on implementation of a specific probabilistic dense layer (Flipout), which can be easily achieved using the Tensorflow Probability module. Instead of adding a normal dense layer to the predefined VGG16 network we add a dense Flipout layer using the same method. The full mathematical background of Flipout was described by Wen et al. and can be found at https://arxiv.org/abs/1803.04386. After training the model, the output of our dense Flipout layer looks similar at first glance: an array representing a probability for each of the 6 classes. However, as aforementioned each prediction of the same image is slightly different as a result of the Flipout layer sampling weights out of a distribution each forward pass. By repeating the predictions for a certain image multiple times, a distribution of probabilities can be obtained for each of the 7 classes of skin lesions. Each of the images on the left shows the probability distribution of an image belonging to the class ‘melanocytic nevi’ (blue) or ‘melanoma (orange) generated by passing each image through the network 100 times. The x-axis reflects the probability of the image belonging to one of the classes, while the height of the plots express the distribution density. The value of the additional information for physicians can be illustrated with the depicted density plots. Let’s have a look at the left plot: passing the first image through a ‘normal’ convolution neural network would yield a low point estimate for the class ‘melanocytic nevi’ (blue) and a high point estimate for the class ‘melanoma’ (orange). The probabilistic Flipout layer enables the evaluation of the uncertainty of these predictions. Specifically, the left plot shows little variation in the predicted (low) probabilities for the class ‘melanocytic nevi’. However, the distribution of the ‘melanoma’ class has much more variation, implying that the probability of the image belonging to the class ‘melanoma’ is quite uncertain. In summary, a ‘normal’ convolutional neural network would provide a probability for each class, while a model containing a probabilistic Flipout layer yields a distribution of probabilities for each class and can thus be used to evaluate the uncertainty of the model’s predictions. Physicians can use this extra information to gain a better understanding of the predictions and use his/her knowledge to confirm or exclude a certain diagnosis. Gradient-weighted Class Activation Mapping (Grad-CAM) is a method that extracts gradients from a convolutional neural network’s final convolutional layer and uses this information to highlight regions most responsible for the predicted probability the image belongs to a predefined class. The steps of Grad-CAM include extracting the gradients with subsequent global average pooling. A ReLU activation function is added to only depict the regions of the image that have a positive contribution to the predefined class. The resulting attention map can be plotted over the original image and can be interpreted as a visual tool for identifying regions the model ‘looks at’ to predict if an image belongs to a specific class. Readers interested in the mathematical theory behind Grad-CAM are encouraged to read the paper by Selvaraju et al. via https://arxiv.org/abs/1610.02391. The code below demonstrates the relative ease of implementing Grad-CAM with our basic model. These images demonstrate the original image of a melanoma and the same image with a superimposed attention map created using the Grad-CAM algorithm. These images clearly illustrate that Grad-CAM yields additional information that is useful for daily clinical practice. This attention map reflects which parts of the skin lesion is affecting the model’s predictions most. Possibly, this information can be valuable to guide skin biopsies in search for confirmation of the suspected diagnosis. In addition, provided that the algorithm is accurate in it’s predictions, repeated use of the algorithm with incorporated visual features in different patients will increase a physician’s trust in the algorithm’s predictions. Convolutional neural networks have the potential to provide additional diagnostic tools for several medical specialties as radiologists, dermatologists and pathologists. However, models that merely provide class-predictions are not sufficient. We believe that introducing methods as adding a probabilistic reasoning and Grad-CAM provide insight in the model’s decisive properties and are therefore essential for physicians to understand and start embracing machine learning algorithms in daily clinical practice. Rik Kraan is medical doctor working as data scientist at Vantage AI, a data science consultancy company in the Netherlands. Feel free to get in touch via [email protected] Special thanks to Richard Bartels and Loek Gerrits
[ { "code": null, "e": 679, "s": 172, "text": "Interest in artificial intelligence applications for image analysis in healthcare is increasing fast. The number of publications in academic journals concerning machine learning is growing exponentially and consequently several image-recognition applications have been implemented in daily clinical practice. Accurate algorithms can serve as additional diagnostic tools for physicians in order to facilitate and accelerate the workflow and, most importantly, improve the accuracy of the diagnostic process." }, { "code": null, "e": 1559, "s": 679, "text": "Image analysis algorithms should be added to the physician’s toolbox and not be regarded as a potential replacement of medical specialists. Despite physicians being concerned with and responsible for their patients’ well-being, most are not familiar with the mathematical details of machine learning algorithms. Therefore, medical applications should not serve as ‘black boxes’, but provide additional information on how the model came to its predictions. This blog demonstrates two possible techniques for acquiring this information: probabilistic layers, which can be used to address the uncertainty on a model’s predictions and Grad-CAM a method for demonstrating which pixels contribute most to the model’s outcome. In this blog we will focus on dermatoscopic images, but the presented techniques are applicable to other medical fields (e.g. radiology and pathology) as well." }, { "code": null, "e": 1915, "s": 1559, "text": "The two techniques will be illustrated using Kaggle’s public HAM (“Human Against Machine”) 10000 dataset which contains over 10000 images of 7 classes of pigmented skin lesions, including several types of skin cancer (i.e. melanoma and basal cell carcinoma) and less invasive types like benign keratosis-like lesions and physiological melanocytic lesions." }, { "code": null, "e": 2182, "s": 1915, "text": "Although the dataset contains additional features as age and location valuable for classifying skin lesions, for illustrative purposes this blog will merely focus on the imaging data. On the left several example images, all obtained with a dermatoscope are depicted." }, { "code": null, "e": 2451, "s": 2182, "text": "First, a basic convolutional neural network was trained using the VGG16 architecture with predefined weights. The weights of the first layers were frozen and only the last 6 layers were retrained. An additional dense layer with a softmax activation function was added." }, { "code": null, "e": 2691, "s": 2451, "text": "After 10 epochs of training the transfer learned model yielded a validation accuracy of 82%. At this moment, the output of the model consists of an array representing the probabilities an image belongs to each of the 7 classes (see below)." }, { "code": null, "e": 2793, "s": 2691, "text": "[[2.3303068e-09 1.2782693e-10 1.4191615e-02 1.8526940e-14 3.9408263e-02 9.4640017e-01 2.1815825e-11]]" }, { "code": null, "e": 3128, "s": 2793, "text": "These predictions can already guide physicians in the right direction, however additional information of the model’s method of ‘thinking’ will increase understanding of and trust in these kind of deep learning models. The next sections will illustrate that for this purpose probabilistic layers and Grad-CAM can be extremely valuable." }, { "code": null, "e": 3749, "s": 3128, "text": "Adding a probabilistic layer to a model’s architecture is a valuable method to evaluate the uncertainty of a model’s predictions. The fundamental difference between ‘normal’ and probabilistic layers is that probabilistic layers assume weights to have a certain distribution instead of being point estimates. Probabilistic layers approximate the posterior distribution of the weights by variational inference. Essentially, the posterior distribution is approximated through a Gaussian distributed surrogate function. During each forward pass, weights of a probabilistic layer are sampled from this surrogate distribution." }, { "code": null, "e": 4217, "s": 3749, "text": "As a consequence, introducing the same input multiple times will result in slightly different predictions each time. In a classification problem, the model will yield a distribution of probabilities for each class. This probability distribution can be used to asses the uncertainty of a model’s predictions: if the uncertainty is limited, repeated predictions will be very close to each other, while a wide distribution of predictions imply a large model uncertainty." }, { "code": null, "e": 4626, "s": 4217, "text": "This blog will focus on implementation of a specific probabilistic dense layer (Flipout), which can be easily achieved using the Tensorflow Probability module. Instead of adding a normal dense layer to the predefined VGG16 network we add a dense Flipout layer using the same method. The full mathematical background of Flipout was described by Wen et al. and can be found at https://arxiv.org/abs/1803.04386." }, { "code": null, "e": 5114, "s": 4626, "text": "After training the model, the output of our dense Flipout layer looks similar at first glance: an array representing a probability for each of the 6 classes. However, as aforementioned each prediction of the same image is slightly different as a result of the Flipout layer sampling weights out of a distribution each forward pass. By repeating the predictions for a certain image multiple times, a distribution of probabilities can be obtained for each of the 7 classes of skin lesions." }, { "code": null, "e": 5472, "s": 5114, "text": "Each of the images on the left shows the probability distribution of an image belonging to the class ‘melanocytic nevi’ (blue) or ‘melanoma (orange) generated by passing each image through the network 100 times. The x-axis reflects the probability of the image belonging to one of the classes, while the height of the plots express the distribution density." }, { "code": null, "e": 6209, "s": 5472, "text": "The value of the additional information for physicians can be illustrated with the depicted density plots. Let’s have a look at the left plot: passing the first image through a ‘normal’ convolution neural network would yield a low point estimate for the class ‘melanocytic nevi’ (blue) and a high point estimate for the class ‘melanoma’ (orange). The probabilistic Flipout layer enables the evaluation of the uncertainty of these predictions. Specifically, the left plot shows little variation in the predicted (low) probabilities for the class ‘melanocytic nevi’. However, the distribution of the ‘melanoma’ class has much more variation, implying that the probability of the image belonging to the class ‘melanoma’ is quite uncertain." }, { "code": null, "e": 6652, "s": 6209, "text": "In summary, a ‘normal’ convolutional neural network would provide a probability for each class, while a model containing a probabilistic Flipout layer yields a distribution of probabilities for each class and can thus be used to evaluate the uncertainty of the model’s predictions. Physicians can use this extra information to gain a better understanding of the predictions and use his/her knowledge to confirm or exclude a certain diagnosis." }, { "code": null, "e": 6941, "s": 6652, "text": "Gradient-weighted Class Activation Mapping (Grad-CAM) is a method that extracts gradients from a convolutional neural network’s final convolutional layer and uses this information to highlight regions most responsible for the predicted probability the image belongs to a predefined class." }, { "code": null, "e": 7528, "s": 6941, "text": "The steps of Grad-CAM include extracting the gradients with subsequent global average pooling. A ReLU activation function is added to only depict the regions of the image that have a positive contribution to the predefined class. The resulting attention map can be plotted over the original image and can be interpreted as a visual tool for identifying regions the model ‘looks at’ to predict if an image belongs to a specific class. Readers interested in the mathematical theory behind Grad-CAM are encouraged to read the paper by Selvaraju et al. via https://arxiv.org/abs/1610.02391." }, { "code": null, "e": 7621, "s": 7528, "text": "The code below demonstrates the relative ease of implementing Grad-CAM with our basic model." }, { "code": null, "e": 8339, "s": 7621, "text": "These images demonstrate the original image of a melanoma and the same image with a superimposed attention map created using the Grad-CAM algorithm. These images clearly illustrate that Grad-CAM yields additional information that is useful for daily clinical practice. This attention map reflects which parts of the skin lesion is affecting the model’s predictions most. Possibly, this information can be valuable to guide skin biopsies in search for confirmation of the suspected diagnosis. In addition, provided that the algorithm is accurate in it’s predictions, repeated use of the algorithm with incorporated visual features in different patients will increase a physician’s trust in the algorithm’s predictions." }, { "code": null, "e": 8852, "s": 8339, "text": "Convolutional neural networks have the potential to provide additional diagnostic tools for several medical specialties as radiologists, dermatologists and pathologists. However, models that merely provide class-predictions are not sufficient. We believe that introducing methods as adding a probabilistic reasoning and Grad-CAM provide insight in the model’s decisive properties and are therefore essential for physicians to understand and start embracing machine learning algorithms in daily clinical practice." }, { "code": null, "e": 9031, "s": 8852, "text": "Rik Kraan is medical doctor working as data scientist at Vantage AI, a data science consultancy company in the Netherlands. Feel free to get in touch via [email protected]" } ]
Inline Functions in C++ - GeeksforGeeks
07 Sep, 2018 Inline function is one of the important feature of C++. So, let’s first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function’s code. This overhead occurs for small functions because execution time of small function is less than the switching time. C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.The syntax for defining the function inline is: inline return-type function-name(parameters) { // function code } Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlining in such circumstances like:1) If a function contains a loop. (for, while, do-while)2) If a function contains static variables.3) If a function is recursive.4) If a function return type is other than void, and the return statement doesn’t exist in function body.5) If a function contains switch or goto statement. Inline functions provide following advantages:1) Function call overhead doesn’t occur.2) It also saves the overhead of push/pop variables on the stack when function is called.3) It also saves overhead of a return call from a function.4) When you inline a function, you may enable compiler to perform context specific optimization on the body of function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by considering the flows of calling context and the called context.5) Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return. Inline function disadvantages:1) The added variables from the inlined function consumes additional registers, After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization. This means that when inline function body is substituted at the point of function call, total number of variables used by the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization. 2) If you use too many inline functions then the size of the binary executable file will be large, because of the duplication of same code. 3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from that of cache memory to that of primary memory. 4) Inline function may increase compile time overhead if someone changes the code inside the inline function then all the calling location has to be recompiled because compiler would require to replace all the code once again to reflect the changes, otherwise it will continue with old functionality. 5) Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed. 6) Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade. The following program demonstrates the use of use of inline function. #include <iostream>using namespace std;inline int cube(int s){ return s*s*s;}int main(){ cout << "The cube of 3 is: " << cube(3) << "\n"; return 0;} //Output: The cube of 3 is: 27 Inline function and classes:It is also possible to define the inline function inside the class. In fact, all the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you need to explicitly declare inline function in the class then just declare the function inside the class and define it outside the class using inline keyword.For example: class S{public: inline int square(int s) // redundant use of inline { // this function is automatically inline // function body }}; The above style is considered as a bad programming style. The best programming style is to just write the prototype of function inside the class and specify it as an inline in the function definition.For example: class S{public: int square(int s); // declare the function}; inline int S::square(int s) // use inline prefix{ } The following program demonstrates this concept: #include <iostream>using namespace std;class operation{ int a,b,add,sub,mul; float div;public: void get(); void sum(); void difference(); void product(); void division();};inline void operation :: get(){ cout << "Enter first value:"; cin >> a; cout << "Enter second value:"; cin >> b;} inline void operation :: sum(){ add = a+b; cout << "Addition of two numbers: " << a+b << "\n";} inline void operation :: difference(){ sub = a-b; cout << "Difference of two numbers: " << a-b << "\n";} inline void operation :: product(){ mul = a*b; cout << "Product of two numbers: " << a*b << "\n";} inline void operation ::division(){ div=a/b; cout<<"Division of two numbers: "<<a/b<<"\n" ;} int main(){ cout << "Program using inline function\n"; operation s; s.get(); s.sum(); s.difference(); s.product(); s.division(); return 0;} Output: Enter first value: 45 Enter second value: 15 Addition of two numbers: 60 Difference of two numbers: 30 Product of two numbers: 675 Division of two numbers: 3 What is wrong with macro?Readers familiar with the C language knows that C language uses macro. The preprocessor replace all macro calls directly within the macro code. It is recommended to always use inline function instead of macro. According to Dr. Bjarne Stroustrup the creator of C++ that macros are almost never necessary in C++ and they are error prone. There are some problems with the use of macros in C++. Macro cannot access private members of class. Macros looks like function call but they are actually not.Example: #include <iostream>using namespace std;class S{ int m;public:#define MAC(S::m) // error}; C++ compiler checks the argument types of inline functions and necessary conversions are performed correctly. Preprocessor macro is not capable for doing this. One other thing is that the macros are managed by preprocessor and inline functions are managed by C++ compiler. Remember: It is true that all the functions defined inside the class are implicitly inline and C++ compiler will perform inline call of these functions, but C++ compiler cannot perform inlining if the function is virtual. The reason is call to a virtual function is resolved at runtime instead of compile time. Virtual means wait until runtime and inline means during compilation, if the compiler doesn’t know which function will be called, how it can perform inlining? One other thing to remember is that it is only useful to make the function inline if the time spent during a function call is more compared to the function body execution time. An example where inline function has no effect at all: inline void show(){ cout << "value of S = " << S << endl;} The above function relatively takes a long time to execute. In general function which performs input output (I/O) operation shouldn’t be defined as inline because it spends a considerable amount of time. Technically inlining of show() function is of limited value because the amount of time the I/O statement will take far exceeds the overhead of a function call. Depending upon the compiler you are using the compiler may show you warning if the function is not expanded inline. Programming languages like Java & C# doesn’t support inline functions.But in Java, the compiler can perform inlining when the small final method is called, because final methods can’t be overridden by sub classes and call to a final method is resolved at compile time. In C# JIT compiler can also optimize code by inlining small function calls (like replacing body of a small function when it is called in a loop). Last thing to keep in mind that inline functions are the valuable feature of C++. An appropriate use of inline function can provide performance enhancement but if inline functions are used arbitrarily then they can’t provide better result. In other words don’t expect better performance of program. Don’t make every function inline. It is better to keep inline functions as small as possible. References:1) Effective C++ , Scott Meyers2) http://www.parashift.com/c++-faq/inline-and-perf.html3) http://www.cplusplus.com/forum/articles/20600/4) Thinking in C++, Volume 1, Bruce Eckel.5) C++ the complete reference, Herbert Schildt This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Functions C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Socket Programming in C/C++ Python Dictionary Reverse a string in Java Interfaces in Java Overriding in Java Types of Operating Systems
[ { "code": null, "e": 26571, "s": 26543, "text": "\n07 Sep, 2018" }, { "code": null, "e": 26728, "s": 26571, "text": "Inline function is one of the important feature of C++. So, let’s first understand why inline functions are used and what is the purpose of inline function?" }, { "code": null, "e": 27738, "s": 26728, "text": "When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function’s code. This overhead occurs for small functions because execution time of small function is less than the switching time." }, { "code": null, "e": 28190, "s": 27738, "text": "C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.The syntax for defining the function inline is:" }, { "code": null, "e": 28262, "s": 28190, "text": "inline return-type function-name(parameters)\n{\n // function code\n} " }, { "code": null, "e": 28724, "s": 28262, "text": "Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlining in such circumstances like:1) If a function contains a loop. (for, while, do-while)2) If a function contains static variables.3) If a function is recursive.4) If a function return type is other than void, and the return statement doesn’t exist in function body.5) If a function contains switch or goto statement." }, { "code": null, "e": 29395, "s": 28724, "text": "Inline functions provide following advantages:1) Function call overhead doesn’t occur.2) It also saves the overhead of push/pop variables on the stack when function is called.3) It also saves overhead of a return call from a function.4) When you inline a function, you may enable compiler to perform context specific optimization on the body of function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by considering the flows of calling context and the called context.5) Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return." }, { "code": null, "e": 30038, "s": 29395, "text": "Inline function disadvantages:1) The added variables from the inlined function consumes additional registers, After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization. This means that when inline function body is substituted at the point of function call, total number of variables used by the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization." }, { "code": null, "e": 30178, "s": 30038, "text": "2) If you use too many inline functions then the size of the binary executable file will be large, because of the duplication of same code." }, { "code": null, "e": 30346, "s": 30178, "text": "3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from that of cache memory to that of primary memory." }, { "code": null, "e": 30647, "s": 30346, "text": "4) Inline function may increase compile time overhead if someone changes the code inside the inline function then all the calling location has to be recompiled because compiler would require to replace all the code once again to reflect the changes, otherwise it will continue with old functionality." }, { "code": null, "e": 30780, "s": 30647, "text": "5) Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed." }, { "code": null, "e": 30953, "s": 30780, "text": "6) Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade." }, { "code": null, "e": 31023, "s": 30953, "text": "The following program demonstrates the use of use of inline function." }, { "code": "#include <iostream>using namespace std;inline int cube(int s){ return s*s*s;}int main(){ cout << \"The cube of 3 is: \" << cube(3) << \"\\n\"; return 0;} //Output: The cube of 3 is: 27", "e": 31212, "s": 31023, "text": null }, { "code": null, "e": 31630, "s": 31212, "text": "Inline function and classes:It is also possible to define the inline function inside the class. In fact, all the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you need to explicitly declare inline function in the class then just declare the function inside the class and define it outside the class using inline keyword.For example:" }, { "code": "class S{public: inline int square(int s) // redundant use of inline { // this function is automatically inline // function body }};", "e": 31785, "s": 31630, "text": null }, { "code": null, "e": 31998, "s": 31785, "text": "The above style is considered as a bad programming style. The best programming style is to just write the prototype of function inside the class and specify it as an inline in the function definition.For example:" }, { "code": "class S{public: int square(int s); // declare the function}; inline int S::square(int s) // use inline prefix{ }", "e": 32116, "s": 31998, "text": null }, { "code": null, "e": 32165, "s": 32116, "text": "The following program demonstrates this concept:" }, { "code": "#include <iostream>using namespace std;class operation{ int a,b,add,sub,mul; float div;public: void get(); void sum(); void difference(); void product(); void division();};inline void operation :: get(){ cout << \"Enter first value:\"; cin >> a; cout << \"Enter second value:\"; cin >> b;} inline void operation :: sum(){ add = a+b; cout << \"Addition of two numbers: \" << a+b << \"\\n\";} inline void operation :: difference(){ sub = a-b; cout << \"Difference of two numbers: \" << a-b << \"\\n\";} inline void operation :: product(){ mul = a*b; cout << \"Product of two numbers: \" << a*b << \"\\n\";} inline void operation ::division(){ div=a/b; cout<<\"Division of two numbers: \"<<a/b<<\"\\n\" ;} int main(){ cout << \"Program using inline function\\n\"; operation s; s.get(); s.sum(); s.difference(); s.product(); s.division(); return 0;}", "e": 33070, "s": 32165, "text": null }, { "code": null, "e": 33078, "s": 33070, "text": "Output:" }, { "code": null, "e": 33237, "s": 33078, "text": "Enter first value: 45\nEnter second value: 15\nAddition of two numbers: 60\nDifference of two numbers: 30\nProduct of two numbers: 675\nDivision of two numbers: 3 " }, { "code": null, "e": 33766, "s": 33237, "text": "What is wrong with macro?Readers familiar with the C language knows that C language uses macro. The preprocessor replace all macro calls directly within the macro code. It is recommended to always use inline function instead of macro. According to Dr. Bjarne Stroustrup the creator of C++ that macros are almost never necessary in C++ and they are error prone. There are some problems with the use of macros in C++. Macro cannot access private members of class. Macros looks like function call but they are actually not.Example:" }, { "code": "#include <iostream>using namespace std;class S{ int m;public:#define MAC(S::m) // error};", "e": 33862, "s": 33766, "text": null }, { "code": null, "e": 34135, "s": 33862, "text": "C++ compiler checks the argument types of inline functions and necessary conversions are performed correctly. Preprocessor macro is not capable for doing this. One other thing is that the macros are managed by preprocessor and inline functions are managed by C++ compiler." }, { "code": null, "e": 34605, "s": 34135, "text": "Remember: It is true that all the functions defined inside the class are implicitly inline and C++ compiler will perform inline call of these functions, but C++ compiler cannot perform inlining if the function is virtual. The reason is call to a virtual function is resolved at runtime instead of compile time. Virtual means wait until runtime and inline means during compilation, if the compiler doesn’t know which function will be called, how it can perform inlining?" }, { "code": null, "e": 34837, "s": 34605, "text": "One other thing to remember is that it is only useful to make the function inline if the time spent during a function call is more compared to the function body execution time. An example where inline function has no effect at all:" }, { "code": "inline void show(){ cout << \"value of S = \" << S << endl;}", "e": 34899, "s": 34837, "text": null }, { "code": null, "e": 35263, "s": 34899, "text": "The above function relatively takes a long time to execute. In general function which performs input output (I/O) operation shouldn’t be defined as inline because it spends a considerable amount of time. Technically inlining of show() function is of limited value because the amount of time the I/O statement will take far exceeds the overhead of a function call." }, { "code": null, "e": 35794, "s": 35263, "text": "Depending upon the compiler you are using the compiler may show you warning if the function is not expanded inline. Programming languages like Java & C# doesn’t support inline functions.But in Java, the compiler can perform inlining when the small final method is called, because final methods can’t be overridden by sub classes and call to a final method is resolved at compile time. In C# JIT compiler can also optimize code by inlining small function calls (like replacing body of a small function when it is called in a loop)." }, { "code": null, "e": 36187, "s": 35794, "text": "Last thing to keep in mind that inline functions are the valuable feature of C++. An appropriate use of inline function can provide performance enhancement but if inline functions are used arbitrarily then they can’t provide better result. In other words don’t expect better performance of program. Don’t make every function inline. It is better to keep inline functions as small as possible." }, { "code": null, "e": 36423, "s": 36187, "text": "References:1) Effective C++ , Scott Meyers2) http://www.parashift.com/c++-faq/inline-and-perf.html3) http://www.cplusplus.com/forum/articles/20600/4) Thinking in C++, Volume 1, Bruce Eckel.5) C++ the complete reference, Herbert Schildt" }, { "code": null, "e": 36593, "s": 36423, "text": "This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36607, "s": 36593, "text": "CPP-Functions" }, { "code": null, "e": 36611, "s": 36607, "text": "C++" }, { "code": null, "e": 36630, "s": 36611, "text": "School Programming" }, { "code": null, "e": 36634, "s": 36630, "text": "CPP" }, { "code": null, "e": 36732, "s": 36634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36741, "s": 36732, "text": "Comments" }, { "code": null, "e": 36754, "s": 36741, "text": "Old Comments" }, { "code": null, "e": 36772, "s": 36754, "text": "Vector in C++ STL" }, { "code": null, "e": 36818, "s": 36772, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 36841, "s": 36818, "text": "std::sort() in C++ STL" }, { "code": null, "e": 36868, "s": 36841, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 36896, "s": 36868, "text": "Socket Programming in C/C++" }, { "code": null, "e": 36914, "s": 36896, "text": "Python Dictionary" }, { "code": null, "e": 36939, "s": 36914, "text": "Reverse a string in Java" }, { "code": null, "e": 36958, "s": 36939, "text": "Interfaces in Java" }, { "code": null, "e": 36977, "s": 36958, "text": "Overriding in Java" } ]
Find minimum speed to finish all Jobs - GeeksforGeeks
26 May, 2021 Given an array A and an integer H where and . Each element A[i] represents remaining pending jobs to be done and H represents hours left to complete all of the jobs. The task is to find the minimum speed in jobs per Hour at which person needs to work to complete all jobs in H hours.Note: If A[i] has less job to be done than speed of person then he finish all of the work of A[i] and won’t go to next element during this hour.Examples: Input: A[] = [3, 6, 7, 11], H = 8 Output: 4 Input: A[] = [30, 11, 23, 4, 20], H = 5 Output: 30 Approach: If the person can finish all the jobs (within H hours) with an speed of K jobs/hour then he can finish all jobs with a larger speed too.If we let ispossible(K) be true if and only if the person can finish with a job speed of K, then there is some X such that ispossible(K) = True if and only if K >= X.For example, with A = [3, 6, 7, 11] and H = 8, there is some X = 4 so that ispossible(1) = ispossible(2) = ispossible(3) = False, and ispossible(4) = ispossible(5) = ... = True.We can do a binary search on the values of ispossible(K) to find the first X such that ispossible(X) is True which will be our answer.Now, as it is not allowed to move from one element to other during the current hour even if the job is completed than the maximum possible value of K can be the maximum element in the array A[]. So, to find the value of ispossible(K), (i.e. whether person with a job speed of K can finish all jobs in H hours), do binary search in the range (1, max_element_of_array).Also, for each A[i] of jobs > 0, we can deduce that person finishes it in Math.ceil(A[i] / K) or ((A[i]-1) / K) + 1 hours, and we add these for all elements to find the total time to complete all of the jobs and compare it with H to check if it is possible to finish all jobs with a speed of K jobs/hour. Below is the implementation of above approach: C++ Java C# Python3 Javascript // CPP program to find minimum speed// to finish all jobs #include <bits/stdc++.h>using namespace std; // Function to check if the person can do// all jobs in H hours with speed Kbool isPossible(int A[], int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsint minJobSpeed(int A[], int n, int H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array int* max = max_element(A, A + n); int lo = 1, hi = *max; // Use binary search to find smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programint main(){ int A[] = { 3, 6, 7, 11 }, H = 8; int n = sizeof(A) / sizeof(A[0]); // Print required maxLenwer cout << minJobSpeed(A, n, H); return 0;} // Java program to find minimum speed// to finish all jobsclass GFG{ // Function To findmax value in Arraystatic int findmax(int[] A){ int r = A[0]; for(int i = 1; i < A.length; i++) r = Math.max(r, A[i]); return r;} // Function to check if the person can do// all jobs in H hours with speed Kstatic boolean isPossible(int[] A, int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsstatic int minJobSpeed(int[] A, int n, int H){ // If H < N it is not possible to // complete all jobs as person can // not move from one element to // another during current hour if (H < n) return -1; // Max element of array int max = findmax(A); int lo = 1, hi = max; // Use binary search to find // smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver Codepublic static void main(String[] args){ int[] A = { 3, 6, 7, 11 }; int H = 8; int n = A.length; // Print required maxLenwer System.out.println(minJobSpeed(A, n, H));}} // This code is contributed by mits // C# program to find minimum speed// to finish all jobs using System;using System.Linq; class GFG{ // Function to check if the person can do// all jobs in H hours with speed Kstatic bool isPossible(int[] A, int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsstatic int minJobSpeed(int[] A, int n, int H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array int max = A.Max(); int lo = 1, hi = max; // Use binary search to find smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programpublic static void Main(){ int[] A = { 3, 6, 7, 11 }; int H = 8; int n = A.Length; // Print required maxLenwer Console.WriteLine(minJobSpeed(A, n, H));}} # Python3 program to find minimum# speed to finish all jobs # Function to check if the person can do# all jobs in H hours with speed Kdef isPossible(A, n, H, K): time = 0 for i in range(n): time += (A[i] - 1) // K + 1 return time <= H # Function to return the minimum speed# of person to complete all jobsdef minJobSpeed(A, n, H): # If H < N it is not possible to complete # all jobs as person can not move from # one element to another during current hour if H < n: return -1 # Max element of array Max = max(A) lo, hi = 1, Max # Use binary search to find smallest K while lo < hi: mi = lo + (hi - lo) // 2 if not isPossible(A, n, H, mi): lo = mi + 1 else: hi = mi return lo if __name__ == "__main__": A = [3, 6, 7, 11] H = 8 n = len(A) # Print required maxLenwer print(minJobSpeed(A, n, H)) # This code is contributed by Rituraj Jain <script> // Javascript program to find minimum speed// to finish all jobs // Function to check if the person can do// all jobs in H hours with speed Kfunction isPossible(A, n, H, K){ var time = 0; for (var i = 0; i < n; ++i) time += parseInt((A[i] - 1) / K) + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsfunction minJobSpeed(A, n, H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array var max = A.reduce((a,b)=> Math.max(a,b)); var lo = 1, hi = max; // Use binary search to find smallest K while (lo < hi) { var mi = lo + parseInt((hi - lo) / 2); if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programvar A = [3, 6, 7, 11], H = 8;var n = A.length; // Print required maxLenwerdocument.write( minJobSpeed(A, n, H)); // This code is contributed by famously.</script> 4 Time Complexity: O(N*log(M)), where N is the length of array and M is max(A). tufan_gupta2000 Mithun Kumar rituraj_jain famously Binary Search Constructive Algorithms Mathematical Searching Searching Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24718, "s": 24690, "text": "\n26 May, 2021" }, { "code": null, "e": 25157, "s": 24718, "text": "Given an array A and an integer H where and . Each element A[i] represents remaining pending jobs to be done and H represents hours left to complete all of the jobs. The task is to find the minimum speed in jobs per Hour at which person needs to work to complete all jobs in H hours.Note: If A[i] has less job to be done than speed of person then he finish all of the work of A[i] and won’t go to next element during this hour.Examples: " }, { "code": null, "e": 25253, "s": 25157, "text": "Input: A[] = [3, 6, 7, 11], H = 8\nOutput: 4\n\nInput: A[] = [30, 11, 23, 4, 20], H = 5\nOutput: 30" }, { "code": null, "e": 26599, "s": 25255, "text": "Approach: If the person can finish all the jobs (within H hours) with an speed of K jobs/hour then he can finish all jobs with a larger speed too.If we let ispossible(K) be true if and only if the person can finish with a job speed of K, then there is some X such that ispossible(K) = True if and only if K >= X.For example, with A = [3, 6, 7, 11] and H = 8, there is some X = 4 so that ispossible(1) = ispossible(2) = ispossible(3) = False, and ispossible(4) = ispossible(5) = ... = True.We can do a binary search on the values of ispossible(K) to find the first X such that ispossible(X) is True which will be our answer.Now, as it is not allowed to move from one element to other during the current hour even if the job is completed than the maximum possible value of K can be the maximum element in the array A[]. So, to find the value of ispossible(K), (i.e. whether person with a job speed of K can finish all jobs in H hours), do binary search in the range (1, max_element_of_array).Also, for each A[i] of jobs > 0, we can deduce that person finishes it in Math.ceil(A[i] / K) or ((A[i]-1) / K) + 1 hours, and we add these for all elements to find the total time to complete all of the jobs and compare it with H to check if it is possible to finish all jobs with a speed of K jobs/hour. Below is the implementation of above approach: " }, { "code": null, "e": 26603, "s": 26599, "text": "C++" }, { "code": null, "e": 26608, "s": 26603, "text": "Java" }, { "code": null, "e": 26611, "s": 26608, "text": "C#" }, { "code": null, "e": 26619, "s": 26611, "text": "Python3" }, { "code": null, "e": 26630, "s": 26619, "text": "Javascript" }, { "code": "// CPP program to find minimum speed// to finish all jobs #include <bits/stdc++.h>using namespace std; // Function to check if the person can do// all jobs in H hours with speed Kbool isPossible(int A[], int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsint minJobSpeed(int A[], int n, int H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array int* max = max_element(A, A + n); int lo = 1, hi = *max; // Use binary search to find smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programint main(){ int A[] = { 3, 6, 7, 11 }, H = 8; int n = sizeof(A) / sizeof(A[0]); // Print required maxLenwer cout << minJobSpeed(A, n, H); return 0;}", "e": 27736, "s": 26630, "text": null }, { "code": "// Java program to find minimum speed// to finish all jobsclass GFG{ // Function To findmax value in Arraystatic int findmax(int[] A){ int r = A[0]; for(int i = 1; i < A.length; i++) r = Math.max(r, A[i]); return r;} // Function to check if the person can do// all jobs in H hours with speed Kstatic boolean isPossible(int[] A, int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsstatic int minJobSpeed(int[] A, int n, int H){ // If H < N it is not possible to // complete all jobs as person can // not move from one element to // another during current hour if (H < n) return -1; // Max element of array int max = findmax(A); int lo = 1, hi = max; // Use binary search to find // smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver Codepublic static void main(String[] args){ int[] A = { 3, 6, 7, 11 }; int H = 8; int n = A.length; // Print required maxLenwer System.out.println(minJobSpeed(A, n, H));}} // This code is contributed by mits", "e": 29085, "s": 27736, "text": null }, { "code": "// C# program to find minimum speed// to finish all jobs using System;using System.Linq; class GFG{ // Function to check if the person can do// all jobs in H hours with speed Kstatic bool isPossible(int[] A, int n, int H, int K){ int time = 0; for (int i = 0; i < n; ++i) time += (A[i] - 1) / K + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsstatic int minJobSpeed(int[] A, int n, int H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array int max = A.Max(); int lo = 1, hi = max; // Use binary search to find smallest K while (lo < hi) { int mi = lo + (hi - lo) / 2; if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programpublic static void Main(){ int[] A = { 3, 6, 7, 11 }; int H = 8; int n = A.Length; // Print required maxLenwer Console.WriteLine(minJobSpeed(A, n, H));}}", "e": 30205, "s": 29085, "text": null }, { "code": "# Python3 program to find minimum# speed to finish all jobs # Function to check if the person can do# all jobs in H hours with speed Kdef isPossible(A, n, H, K): time = 0 for i in range(n): time += (A[i] - 1) // K + 1 return time <= H # Function to return the minimum speed# of person to complete all jobsdef minJobSpeed(A, n, H): # If H < N it is not possible to complete # all jobs as person can not move from # one element to another during current hour if H < n: return -1 # Max element of array Max = max(A) lo, hi = 1, Max # Use binary search to find smallest K while lo < hi: mi = lo + (hi - lo) // 2 if not isPossible(A, n, H, mi): lo = mi + 1 else: hi = mi return lo if __name__ == \"__main__\": A = [3, 6, 7, 11] H = 8 n = len(A) # Print required maxLenwer print(minJobSpeed(A, n, H)) # This code is contributed by Rituraj Jain", "e": 31193, "s": 30205, "text": null }, { "code": "<script> // Javascript program to find minimum speed// to finish all jobs // Function to check if the person can do// all jobs in H hours with speed Kfunction isPossible(A, n, H, K){ var time = 0; for (var i = 0; i < n; ++i) time += parseInt((A[i] - 1) / K) + 1; return time <= H;} // Function to return the minimum speed// of person to complete all jobsfunction minJobSpeed(A, n, H){ // If H < N it is not possible to complete // all jobs as person can not move from // one element to another during current hour if (H < n) return -1; // Max element of array var max = A.reduce((a,b)=> Math.max(a,b)); var lo = 1, hi = max; // Use binary search to find smallest K while (lo < hi) { var mi = lo + parseInt((hi - lo) / 2); if (!isPossible(A, n, H, mi)) lo = mi + 1; else hi = mi; } return lo;} // Driver programvar A = [3, 6, 7, 11], H = 8;var n = A.length; // Print required maxLenwerdocument.write( minJobSpeed(A, n, H)); // This code is contributed by famously.</script>", "e": 32271, "s": 31193, "text": null }, { "code": null, "e": 32273, "s": 32271, "text": "4" }, { "code": null, "e": 32354, "s": 32275, "text": "Time Complexity: O(N*log(M)), where N is the length of array and M is max(A). " }, { "code": null, "e": 32370, "s": 32354, "text": "tufan_gupta2000" }, { "code": null, "e": 32383, "s": 32370, "text": "Mithun Kumar" }, { "code": null, "e": 32396, "s": 32383, "text": "rituraj_jain" }, { "code": null, "e": 32405, "s": 32396, "text": "famously" }, { "code": null, "e": 32419, "s": 32405, "text": "Binary Search" }, { "code": null, "e": 32443, "s": 32419, "text": "Constructive Algorithms" }, { "code": null, "e": 32456, "s": 32443, "text": "Mathematical" }, { "code": null, "e": 32466, "s": 32456, "text": "Searching" }, { "code": null, "e": 32476, "s": 32466, "text": "Searching" }, { "code": null, "e": 32489, "s": 32476, "text": "Mathematical" }, { "code": null, "e": 32503, "s": 32489, "text": "Binary Search" }, { "code": null, "e": 32601, "s": 32503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32633, "s": 32601, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 32677, "s": 32633, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32702, "s": 32677, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32735, "s": 32702, "text": "Program to multiply two matrices" }, { "code": null, "e": 32766, "s": 32735, "text": "Modular multiplicative inverse" }, { "code": null, "e": 32780, "s": 32766, "text": "Binary Search" }, { "code": null, "e": 32848, "s": 32780, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32862, "s": 32848, "text": "Linear Search" }, { "code": null, "e": 32886, "s": 32862, "text": "Find the Missing Number" } ]
Angular 2 - Modules
Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. Let’s inspect the code which gets added to the demo application. In Visual Studio code, go to the app.module.ts folder in your app folder. This is known as the root module class. The following code will be present in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule ({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Let’s go through each line of the code in detail. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The BrowserModule is required by default for any web based angular application. The BrowserModule is required by default for any web based angular application. The bootstrap option tells Angular which Component to bootstrap in the application. The bootstrap option tells Angular which Component to bootstrap in the application. A module is made up of the following parts − Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2604, "s": 2297, "text": "Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. Let’s inspect the code which gets added to the demo application." }, { "code": null, "e": 2718, "s": 2604, "text": "In Visual Studio code, go to the app.module.ts folder in your app folder. This is known as the root module class." }, { "code": null, "e": 2780, "s": 2718, "text": "The following code will be present in the app.module.ts file." }, { "code": null, "e": 3095, "s": 2780, "text": "import { NgModule } from '@angular/core'; \nimport { BrowserModule } from '@angular/platform-browser'; \nimport { AppComponent } from './app.component'; \n\n@NgModule ({ \n imports: [ BrowserModule ], \n declarations: [ AppComponent ], \n bootstrap: [ AppComponent ] \n}) \nexport class AppModule { } " }, { "code": null, "e": 3145, "s": 3095, "text": "Let’s go through each line of the code in detail." }, { "code": null, "e": 3344, "s": 3145, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 3543, "s": 3344, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 3647, "s": 3543, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 3751, "s": 3647, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 3831, "s": 3751, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 3911, "s": 3831, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 3995, "s": 3911, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 4079, "s": 3995, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 4124, "s": 4079, "text": "A module is made up of the following parts −" }, { "code": null, "e": 4431, "s": 4124, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 4738, "s": 4431, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 4851, "s": 4738, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 4964, "s": 4851, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 5095, "s": 4964, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 5226, "s": 5095, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 5261, "s": 5226, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5275, "s": 5261, "text": " Anadi Sharma" }, { "code": null, "e": 5310, "s": 5275, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5324, "s": 5310, "text": " Anadi Sharma" }, { "code": null, "e": 5359, "s": 5324, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5379, "s": 5359, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5414, "s": 5379, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5431, "s": 5414, "text": " Frahaan Hussain" }, { "code": null, "e": 5464, "s": 5431, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5476, "s": 5464, "text": " Senol Atac" }, { "code": null, "e": 5511, "s": 5476, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5523, "s": 5511, "text": " Senol Atac" }, { "code": null, "e": 5530, "s": 5523, "text": " Print" }, { "code": null, "e": 5541, "s": 5530, "text": " Add Notes" } ]
Tagged Template Literals in JavaScript
Template literals also allow us to create tagged template literals. The tagged literal is just like a function definition and allows us to parse template literals. The tagged literal doesn’t contain the parenthesis and the tag function gets the array of string values as first argument.The rest of the arguments are then passed to the other related parameters. Following is the code to implement tagged template literals in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Tagged Template Literals in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function sampleTag(strings, name, age, rollNo) { let section; if (rollNo > 50) { section = "A"; } else { section = "B"; } return `${name} roll no: ${rollNo} age :${age} is in section ${section}`; } let name = "Rohan", age = 16, rollNo = 22; BtnEle.addEventListener("click", () => { resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in the school`; }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1423, "s": 1062, "text": "Template literals also allow us to create tagged template literals. The tagged literal is just like a function definition and allows us to parse template literals. The tagged literal doesn’t contain the parenthesis and the tag function gets the array of string values as first argument.The rest of the arguments are then passed to the other related parameters." }, { "code": null, "e": 1499, "s": 1423, "text": "Following is the code to implement tagged template literals in JavaScript −" }, { "code": null, "e": 1510, "s": 1499, "text": " Live Demo" }, { "code": null, "e": 2711, "s": 1510, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Tagged Template Literals in JavaScript</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function sampleTag(strings, name, age, rollNo) {\n let section;\n if (rollNo > 50) {\n section = \"A\";\n } else {\n section = \"B\";\n }\n return `${name} roll no: ${rollNo} age :${age} is in section ${section}`;\n }\n let name = \"Rohan\",\n age = 16,\n rollNo = 22;\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in\n the school`;\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2749, "s": 2711, "text": "On clicking the ‘CLICK HERE’ button −" } ]
How to get the local Administrators group members using PowerShell?
To get the local Administrators group members using PowerShell, you need to use the GetLocalGroupMember command. This command is available in PowerShell version 5.1 onwards and the module for it is Microsoft.PowerShell.LocalAccounts. This module is not available in the 32-bit PowerShell version but on a 64-bit system. In the below example, we need to retrieve the Local Administrators group members, Get-LocalGroupMember -Group "Administrators" ObjectClass Name PrincipalSource ----------- ---- --------------- User LABDOMAIN\delta Group LABDOMAIN\Domain Admins User TEST1-WIN2K12\Administrator User TEST1-WIN2K12\LocalAdmin Name Property shows the members of the local administrator groups. To retrieve the local Administrators group members from the remote servers, we need to use the Invoke-Command method. Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember - Name 'Administrators'} ObjectClass Name PrincipalSource PSComputerName ----------- ---- --------------- -------------- User LABDOMAIN\Delta ActiveDirectory Test1-Win2k16 Group LABDOMAIN\Domain Admins ActiveDirectory Test1-Win2k16 User TEST1-WIN2K16\Administrator Local Test1-Win2k16 User TEST1-WIN2K16\LocalAdmin Local Test1-Win2k16 User TEST1-WIN2K16\Localuser Local Test1-Win2k16 You can also filter the specific user as shown below. Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember - Name 'Administrators' | where{$_.Name -like "*Alpha*"}} ObjectClass Name PrincipalSource PSComputerName ----------- ---- --------------- -------------- User LABDOMAIN\alpha ActiveDirectory Test1-Win2k16 In the earlier PowerShell version, this command wasn’t supported. You can also retrieve the output using cmd. net localgroup administrators Alias name administrators Comment Administrators have complete and unrestricted access to the comput er/domain Members ------------------------------------------------------------------------------- Administrator Delta Domain Admins Enterprise Admins The command completed successfully. To get only the members, we will store the output in the variable and operate. $members = net localgroup administrators $members[6..($members.Length-3)] Administrator Delta Domain Admins Enterprise Admins To run this command on the remote computer, Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{ $members = Invoke-Expression -command "Net Localgroup Administrators" $members[6..($members.Length-3)] } Administrator LABDOMAIN\Delta LABDOMAIN\Domain Admins LocalAdmin Similarly, you can use any local group name instead of the Administrators group.
[ { "code": null, "e": 1382, "s": 1062, "text": "To get the local Administrators group members using PowerShell, you need to use the GetLocalGroupMember command. This command is available in PowerShell version 5.1 onwards and the module for it is Microsoft.PowerShell.LocalAccounts. This module is not available in the 32-bit PowerShell version but on a 64-bit system." }, { "code": null, "e": 1464, "s": 1382, "text": "In the below example, we need to retrieve the Local Administrators group members," }, { "code": null, "e": 1509, "s": 1464, "text": "Get-LocalGroupMember -Group \"Administrators\"" }, { "code": null, "e": 1748, "s": 1509, "text": "ObjectClass Name PrincipalSource\n----------- ---- ---------------\nUser LABDOMAIN\\delta\nGroup LABDOMAIN\\Domain Admins\nUser TEST1-WIN2K12\\Administrator\nUser TEST1-WIN2K12\\LocalAdmin" }, { "code": null, "e": 1933, "s": 1748, "text": "Name Property shows the members of the local administrator groups. To retrieve the local Administrators group members from the remote servers, we need to use the Invoke-Command method." }, { "code": null, "e": 2035, "s": 1933, "text": "Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember -\nName 'Administrators'}" }, { "code": null, "e": 2618, "s": 2035, "text": "ObjectClass Name PrincipalSource PSComputerName\n----------- ---- --------------- --------------\nUser LABDOMAIN\\Delta ActiveDirectory Test1-Win2k16\nGroup LABDOMAIN\\Domain Admins ActiveDirectory Test1-Win2k16\nUser TEST1-WIN2K16\\Administrator Local Test1-Win2k16\nUser TEST1-WIN2K16\\LocalAdmin Local Test1-Win2k16\nUser TEST1-WIN2K16\\Localuser Local Test1-Win2k16" }, { "code": null, "e": 2672, "s": 2618, "text": "You can also filter the specific user as shown below." }, { "code": null, "e": 2807, "s": 2672, "text": "Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember -\nName 'Administrators' | where{$_.Name -like \"*Alpha*\"}}" }, { "code": null, "e": 3004, "s": 2807, "text": "ObjectClass Name PrincipalSource PSComputerName\n----------- ---- --------------- --------------\nUser LABDOMAIN\\alpha ActiveDirectory Test1-Win2k16" }, { "code": null, "e": 3114, "s": 3004, "text": "In the earlier PowerShell version, this command wasn’t supported. You can also retrieve the output using cmd." }, { "code": null, "e": 3144, "s": 3114, "text": "net localgroup administrators" }, { "code": null, "e": 3440, "s": 3144, "text": "Alias name administrators\nComment Administrators have complete and unrestricted access to the comput\ner/domain\nMembers\n-------------------------------------------------------------------------------\nAdministrator\nDelta\nDomain Admins\nEnterprise Admins\nThe command completed successfully." }, { "code": null, "e": 3519, "s": 3440, "text": "To get only the members, we will store the output in the variable and operate." }, { "code": null, "e": 3593, "s": 3519, "text": "$members = net localgroup administrators\n$members[6..($members.Length-3)]" }, { "code": null, "e": 3645, "s": 3593, "text": "Administrator\nDelta\nDomain Admins\nEnterprise Admins" }, { "code": null, "e": 3689, "s": 3645, "text": "To run this command on the remote computer," }, { "code": null, "e": 3857, "s": 3689, "text": "Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{\n $members = Invoke-Expression -command \"Net Localgroup Administrators\"\n $members[6..($members.Length-3)]\n}" }, { "code": null, "e": 3922, "s": 3857, "text": "Administrator\nLABDOMAIN\\Delta\nLABDOMAIN\\Domain Admins\nLocalAdmin" }, { "code": null, "e": 4003, "s": 3922, "text": "Similarly, you can use any local group name instead of the Administrators group." } ]
Ruby/TK - Fonts, Colors and Images
Several Tk widgets, such as the label, text, and canvas, allow you to specify the fonts used to display text, typically via a font configuration option. There is already a default list of fonts, which can be used for different requirements − TkDefaultFont The default for all GUI items not otherwise specified. TkTextFont Used for entry widgets, listboxes, etc. TkFixedFont A standard fixed-width font. TkMenuFont The font used for menu items. TkHeadingFont The font typically used for column headings in lists and tables. TkCaptionFont A font for window and dialog caption bars. TkSmallCaptionFont A smaller caption font for subwindows or tool dialogs TkIconFont A font for icon captions. TkTooltipFont A font for tooltips. You can use any of these fonts in the following way − TkLabel.new(root) {text 'Attention!'; font TkCaptionFont} If you are willing to create your new font using different family and font type, then here is a simple syntax to create a font − TkFont.new ( .....Standard Options.... ) You can specify one or more standard option separated by comma. Foundry Family Weight Slant Swidth Pixel Point Xres Yres Space Avgwidth Registry Encoding There are various ways to specify colors. Full details can be found in the colors command reference. The system will provide the right colors for most things. Like with fonts, both Mac and Windows specifies a large number of system-specific color names (see the reference). You can also specify fonts via RGB, like in HTML, e.g. "#3FF" or "#FF016A". Finally, Tk recognizes the set of color names defined by X11; normally these are not used, except for very common ones such as "red", "black", etc. For themed Tk widgets, colors are often used in defining styles that are applied to widgets, rather than applying the color to a widget directly. require 'tk' $resultsVar = TkVariable.new root = TkRoot.new root.title = "Window" myFont = TkFont.new("family" => 'Helvetica', "size" => 20, "weight" => 'bold') Lbl = TkLabel.new(root) do textvariable borderwidth 5 font myFont foreground "red" relief "groove" pack("side" => "right", "padx"=> "50", "pady"=> "50") end Lbl['textvariable'] = $resultsVar $resultsVar.value = 'New value to display' Tk.mainloop This will produce the following result − Ruby/Tk includes support for GIF and PPM/PNM images. However, there is a Tk extension library called "Img", which adds support for many others: BMP, XBM, XPM, PNG, JPEG, TIFF, etc. Though not included directly in the Tk core, Img is usually included with other packaged distributions. Here, we will see the basics of how to use images, displaying them in labels or buttons for example. We create an image object, usually from a file on disk. require 'tk' $resultsVar = TkVariable.new root = TkRoot.new root.title = "Window" image = TkPhotoImage.new image.file = "zara.gif" label = TkLabel.new(root) label.image = image label.place('height' => image.height, 'width' => image.width, 'x' => 10, 'y' => 10) Tk.mainloop This will produce the following result − Tk's images are actually quite powerful and sophisticated and provide a wide variety of ways to inspect and modify images. You can find out more from the image command reference and the photo command reference. 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": 2447, "s": 2294, "text": "Several Tk widgets, such as the label, text, and canvas, allow you to specify the fonts used to display text, typically via a font configuration option." }, { "code": null, "e": 2536, "s": 2447, "text": "There is already a default list of fonts, which can be used for different requirements −" }, { "code": null, "e": 2550, "s": 2536, "text": "TkDefaultFont" }, { "code": null, "e": 2605, "s": 2550, "text": "The default for all GUI items not otherwise specified." }, { "code": null, "e": 2616, "s": 2605, "text": "TkTextFont" }, { "code": null, "e": 2656, "s": 2616, "text": "Used for entry widgets, listboxes, etc." }, { "code": null, "e": 2668, "s": 2656, "text": "TkFixedFont" }, { "code": null, "e": 2697, "s": 2668, "text": "A standard fixed-width font." }, { "code": null, "e": 2708, "s": 2697, "text": "TkMenuFont" }, { "code": null, "e": 2738, "s": 2708, "text": "The font used for menu items." }, { "code": null, "e": 2752, "s": 2738, "text": "TkHeadingFont" }, { "code": null, "e": 2817, "s": 2752, "text": "The font typically used for column headings in lists and tables." }, { "code": null, "e": 2831, "s": 2817, "text": "TkCaptionFont" }, { "code": null, "e": 2874, "s": 2831, "text": "A font for window and dialog caption bars." }, { "code": null, "e": 2893, "s": 2874, "text": "TkSmallCaptionFont" }, { "code": null, "e": 2947, "s": 2893, "text": "A smaller caption font for subwindows or tool dialogs" }, { "code": null, "e": 2958, "s": 2947, "text": "TkIconFont" }, { "code": null, "e": 2984, "s": 2958, "text": "A font for icon captions." }, { "code": null, "e": 2998, "s": 2984, "text": "TkTooltipFont" }, { "code": null, "e": 3019, "s": 2998, "text": "A font for tooltips." }, { "code": null, "e": 3073, "s": 3019, "text": "You can use any of these fonts in the following way −" }, { "code": null, "e": 3131, "s": 3073, "text": "TkLabel.new(root) {text 'Attention!'; font TkCaptionFont}" }, { "code": null, "e": 3260, "s": 3131, "text": "If you are willing to create your new font using different family and font type, then here is a simple syntax to create a font −" }, { "code": null, "e": 3305, "s": 3260, "text": "TkFont.new (\n .....Standard Options....\n)\n" }, { "code": null, "e": 3369, "s": 3305, "text": "You can specify one or more standard option separated by comma." }, { "code": null, "e": 3377, "s": 3369, "text": "Foundry" }, { "code": null, "e": 3384, "s": 3377, "text": "Family" }, { "code": null, "e": 3391, "s": 3384, "text": "Weight" }, { "code": null, "e": 3397, "s": 3391, "text": "Slant" }, { "code": null, "e": 3404, "s": 3397, "text": "Swidth" }, { "code": null, "e": 3410, "s": 3404, "text": "Pixel" }, { "code": null, "e": 3416, "s": 3410, "text": "Point" }, { "code": null, "e": 3421, "s": 3416, "text": "Xres" }, { "code": null, "e": 3426, "s": 3421, "text": "Yres" }, { "code": null, "e": 3432, "s": 3426, "text": "Space" }, { "code": null, "e": 3441, "s": 3432, "text": "Avgwidth" }, { "code": null, "e": 3450, "s": 3441, "text": "Registry" }, { "code": null, "e": 3459, "s": 3450, "text": "Encoding" }, { "code": null, "e": 3560, "s": 3459, "text": "There are various ways to specify colors. Full details can be found in the colors command reference." }, { "code": null, "e": 3733, "s": 3560, "text": "The system will provide the right colors for most things. Like with fonts, both Mac and Windows specifies a large number of system-specific color names (see the reference)." }, { "code": null, "e": 3809, "s": 3733, "text": "You can also specify fonts via RGB, like in HTML, e.g. \"#3FF\" or \"#FF016A\"." }, { "code": null, "e": 3957, "s": 3809, "text": "Finally, Tk recognizes the set of color names defined by X11; normally these are not used, except for very common ones such as \"red\", \"black\", etc." }, { "code": null, "e": 4103, "s": 3957, "text": "For themed Tk widgets, colors are often used in defining styles that are applied to widgets, rather than applying the color to a widget directly." }, { "code": null, "e": 4538, "s": 4103, "text": "require 'tk'\n\n$resultsVar = TkVariable.new\nroot = TkRoot.new\nroot.title = \"Window\"\nmyFont = TkFont.new(\"family\" => 'Helvetica', \"size\" => 20, \"weight\" => 'bold')\nLbl = TkLabel.new(root) do\n textvariable\n borderwidth 5\n font myFont\n foreground \"red\"\n relief \"groove\"\n pack(\"side\" => \"right\", \"padx\"=> \"50\", \"pady\"=> \"50\")\nend\n\nLbl['textvariable'] = $resultsVar\n$resultsVar.value = 'New value to display'\n\nTk.mainloop" }, { "code": null, "e": 4579, "s": 4538, "text": "This will produce the following result −" }, { "code": null, "e": 4864, "s": 4579, "text": "Ruby/Tk includes support for GIF and PPM/PNM images. However, there is a Tk extension library called \"Img\", which adds support for many others: BMP, XBM, XPM, PNG, JPEG, TIFF, etc. Though not included directly in the Tk core, Img is usually included with other packaged distributions." }, { "code": null, "e": 5021, "s": 4864, "text": "Here, we will see the basics of how to use images, displaying them in labels or buttons for example. We create an image object, usually from a file on disk." }, { "code": null, "e": 5298, "s": 5021, "text": "require 'tk'\n\n$resultsVar = TkVariable.new\nroot = TkRoot.new\nroot.title = \"Window\"\n\nimage = TkPhotoImage.new\nimage.file = \"zara.gif\"\n\nlabel = TkLabel.new(root) \nlabel.image = image\nlabel.place('height' => image.height, 'width' => image.width, 'x' => 10, 'y' => 10)\nTk.mainloop" }, { "code": null, "e": 5339, "s": 5298, "text": "This will produce the following result −" }, { "code": null, "e": 5550, "s": 5339, "text": "Tk's images are actually quite powerful and sophisticated and provide a wide variety of ways to inspect and modify images. You can find out more from the image command reference and the photo command reference." }, { "code": null, "e": 5585, "s": 5550, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 5613, "s": 5585, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5648, "s": 5613, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5668, "s": 5648, "text": " Skillbakerystudios" }, { "code": null, "e": 5703, "s": 5668, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 5713, "s": 5703, "text": " YouAccel" }, { "code": null, "e": 5747, "s": 5713, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 5765, "s": 5747, "text": " Programming Line" }, { "code": null, "e": 5798, "s": 5765, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 5821, "s": 5798, "text": " Stone River ELearning" }, { "code": null, "e": 5856, "s": 5821, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5879, "s": 5856, "text": " Stone River ELearning" }, { "code": null, "e": 5886, "s": 5879, "text": " Print" }, { "code": null, "e": 5897, "s": 5886, "text": " Add Notes" } ]
Object.ReferenceEquals() Method in C# - GeeksforGeeks
10 Apr, 2019 Object.ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden. So, if a user is going to test the two objects references for equality and he is not sure about the implementation of the Equals method, then he can call the ReferenceEquals method. Syntax: public static bool ReferenceEquals (object ob1, object ob2); Parameters:ob1: It is the first object to compare.ob2: It is the second object to compare. Return Value: This method returns true if ob1 is the same instance as ob2 or if both are null otherwise, it returns false. Below programs illustrate the use of Object.ReferenceEquals() Method: Example 1: // C# program to demonstrate the// Object.ReferenceEquals(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 object v1 = null; // Declaring and initializing value2 object v2 = null; // using ReferenceEquals(object, // object) method bool status = Object.ReferenceEquals(v1, v2); // checking the status if (status) Console.WriteLine("null is equal to null"); else Console.WriteLine("null is not equal to null"); }} null is equal to null Example 2: // C# program to demonstrate the// Object.ReferenceEquals(Object, Object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { object p = new Object(); object q = null; // calling get() method get(p, null); // assigning p to q q = p; get(p, q); get(q, null); } // defining get() method public static void get(object v1, object v2) { // using ReferenceEquals(Object) method bool status = Object.ReferenceEquals(v1, v2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", v1, v2); else Console.WriteLine("{0} is not equal to {1}", v1, v2); }} System.Object is not equal to System.Object is equal to System.Object System.Object is not equal to Note: Here, null will never be printed in the output. Important Points: If both ob1 and ob2 represent the same instance of a value type, the then this method nevertheless returns false. If ob1 and ob2 are strings, then this method will return true if the string is interned because this method will never perform a test for value equality. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.object.referenceequals?view=netcore-2.1 RohitPrasad3 CSharp Object Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to calculate Electricity Bill Linked List Implementation in C# C# | How to insert an element in an Array? HashSet in C# with Examples Lambda Expressions in C# Main Method in C# Difference between Hashtable and Dictionary in C# C# | Dictionary.Add() Method Collections in C# Different Ways to Convert Char Array to String in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n10 Apr, 2019" }, { "code": null, "e": 24249, "s": 23911, "text": "Object.ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden. So, if a user is going to test the two objects references for equality and he is not sure about the implementation of the Equals method, then he can call the ReferenceEquals method." }, { "code": null, "e": 24318, "s": 24249, "text": "Syntax: public static bool ReferenceEquals (object ob1, object ob2);" }, { "code": null, "e": 24409, "s": 24318, "text": "Parameters:ob1: It is the first object to compare.ob2: It is the second object to compare." }, { "code": null, "e": 24532, "s": 24409, "text": "Return Value: This method returns true if ob1 is the same instance as ob2 or if both are null otherwise, it returns false." }, { "code": null, "e": 24602, "s": 24532, "text": "Below programs illustrate the use of Object.ReferenceEquals() Method:" }, { "code": null, "e": 24613, "s": 24602, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Object.ReferenceEquals(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 object v1 = null; // Declaring and initializing value2 object v2 = null; // using ReferenceEquals(object, // object) method bool status = Object.ReferenceEquals(v1, v2); // checking the status if (status) Console.WriteLine(\"null is equal to null\"); else Console.WriteLine(\"null is not equal to null\"); }}", "e": 25238, "s": 24613, "text": null }, { "code": null, "e": 25261, "s": 25238, "text": "null is equal to null\n" }, { "code": null, "e": 25272, "s": 25261, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Object.ReferenceEquals(Object, Object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { object p = new Object(); object q = null; // calling get() method get(p, null); // assigning p to q q = p; get(p, q); get(q, null); } // defining get() method public static void get(object v1, object v2) { // using ReferenceEquals(Object) method bool status = Object.ReferenceEquals(v1, v2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", v1, v2); else Console.WriteLine(\"{0} is not equal to {1}\", v1, v2); }}", "e": 26157, "s": 25272, "text": null }, { "code": null, "e": 26260, "s": 26157, "text": "System.Object is not equal to \nSystem.Object is equal to System.Object\nSystem.Object is not equal to \n" }, { "code": null, "e": 26314, "s": 26260, "text": "Note: Here, null will never be printed in the output." }, { "code": null, "e": 26332, "s": 26314, "text": "Important Points:" }, { "code": null, "e": 26446, "s": 26332, "text": "If both ob1 and ob2 represent the same instance of a value type, the then this method nevertheless returns false." }, { "code": null, "e": 26600, "s": 26446, "text": "If ob1 and ob2 are strings, then this method will return true if the string is interned because this method will never perform a test for value equality." }, { "code": null, "e": 26611, "s": 26600, "text": "Reference:" }, { "code": null, "e": 26702, "s": 26611, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.object.referenceequals?view=netcore-2.1" }, { "code": null, "e": 26715, "s": 26702, "text": "RohitPrasad3" }, { "code": null, "e": 26735, "s": 26715, "text": "CSharp Object Class" }, { "code": null, "e": 26749, "s": 26735, "text": "CSharp-method" }, { "code": null, "e": 26752, "s": 26749, "text": "C#" }, { "code": null, "e": 26850, "s": 26752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26859, "s": 26850, "text": "Comments" }, { "code": null, "e": 26872, "s": 26859, "text": "Old Comments" }, { "code": null, "e": 26910, "s": 26872, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 26943, "s": 26910, "text": "Linked List Implementation in C#" }, { "code": null, "e": 26986, "s": 26943, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27014, "s": 26986, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27039, "s": 27014, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27057, "s": 27039, "text": "Main Method in C#" }, { "code": null, "e": 27107, "s": 27057, "text": "Difference between Hashtable and Dictionary in C#" }, { "code": null, "e": 27136, "s": 27107, "text": "C# | Dictionary.Add() Method" }, { "code": null, "e": 27154, "s": 27136, "text": "Collections in C#" } ]
PyQt5 QDockWidget – Setting Features of it - GeeksforGeeks
28 Jul, 2020 In this article we will see how we can set features to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). There are many features already enabled for the dock, also there are feature like movable, closable, flotable, horizontal title bar or there is an option of setting all features or setting no features. In order to do this we will use setFeatures method with the dock widget object. Syntax : dock.setFeatures(QDockWidget.DockWidgetClosable) Argument : It takes feature as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget("GeeksforGeeks", self) # push button push = QPushButton("Press", self) # setting widget to the dock dock.setWidget(push) # setting feature to the dock dock.setFeatures(QDockWidget.DockWidgetClosable) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QDockWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file
[ { "code": null, "e": 24481, "s": 24453, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24777, "s": 24481, "text": "In this article we will see how we can set features to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window)." }, { "code": null, "e": 24979, "s": 24777, "text": "There are many features already enabled for the dock, also there are feature like movable, closable, flotable, horizontal title bar or there is an option of setting all features or setting no features." }, { "code": null, "e": 25059, "s": 24979, "text": "In order to do this we will use setFeatures method with the dock widget object." }, { "code": null, "e": 25117, "s": 25059, "text": "Syntax : dock.setFeatures(QDockWidget.DockWidgetClosable)" }, { "code": null, "e": 25157, "s": 25117, "text": "Argument : It takes feature as argument" }, { "code": null, "e": 25182, "s": 25157, "text": "Return : It returns None" }, { "code": null, "e": 25210, "s": 25182, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(\"GeeksforGeeks\", self) # push button push = QPushButton(\"Press\", self) # setting widget to the dock dock.setWidget(push) # setting feature to the dock dock.setFeatures(QDockWidget.DockWidgetClosable) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26498, "s": 25210, "text": null }, { "code": null, "e": 26507, "s": 26498, "text": "Output :" }, { "code": null, "e": 26531, "s": 26507, "text": "Python PyQt-QDockWidget" }, { "code": null, "e": 26542, "s": 26531, "text": "Python-gui" }, { "code": null, "e": 26554, "s": 26542, "text": "Python-PyQt" }, { "code": null, "e": 26561, "s": 26554, "text": "Python" }, { "code": null, "e": 26659, "s": 26561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26668, "s": 26659, "text": "Comments" }, { "code": null, "e": 26681, "s": 26668, "text": "Old Comments" }, { "code": null, "e": 26718, "s": 26681, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26754, "s": 26718, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26772, "s": 26754, "text": "Python Dictionary" }, { "code": null, "e": 26795, "s": 26772, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26817, "s": 26795, "text": "Enumerate() in Python" }, { "code": null, "e": 26856, "s": 26817, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26889, "s": 26856, "text": "Python | Convert set into a list" }, { "code": null, "e": 26938, "s": 26889, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26971, "s": 26938, "text": "Graph Plotting in Python | Set 1" } ]
HTML | onselect Event Attribute - GeeksforGeeks
03 Aug, 2021 The onselect event attribute works when some text has been selected in an element. It is the part of event attribute. It is supported by many HTML elements such as <input type = “file”>, <input type = “password”>, <input type = “text”>, and <textarea>. Supported Tags: <input type=”file”> <input type=”password”> <input type=”text”> <textarea> Syntax: <element onselect = "script"> Example: HTML <!DOCTYPE html><html> <head> <title>onselect event attribute</title> <style> h1 { color:green; } body { text-align:center; } </style> <script> function Geeks() { alert("Text selected!"); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2>onselect event attribute</h2> Text Box: <input type="text" value="GeeksforGeeks: A computer science portal for geeks" onselect="Geeks()"> </body></html> </html> Output: Supported Browsers: The browser supported by onselect attribute are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 hritikbhatnagar2182 HTML-Attributes CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 23769, "s": 23741, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24022, "s": 23769, "text": "The onselect event attribute works when some text has been selected in an element. It is the part of event attribute. It is supported by many HTML elements such as <input type = “file”>, <input type = “password”>, <input type = “text”>, and <textarea>." }, { "code": null, "e": 24039, "s": 24022, "text": "Supported Tags: " }, { "code": null, "e": 24059, "s": 24039, "text": "<input type=”file”>" }, { "code": null, "e": 24084, "s": 24059, "text": " <input type=”password”>" }, { "code": null, "e": 24106, "s": 24084, "text": " <input type=”text”> " }, { "code": null, "e": 24118, "s": 24106, "text": " <textarea>" }, { "code": null, "e": 24127, "s": 24118, "text": "Syntax: " }, { "code": null, "e": 24157, "s": 24127, "text": "<element onselect = \"script\">" }, { "code": null, "e": 24167, "s": 24157, "text": "Example: " }, { "code": null, "e": 24172, "s": 24167, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>onselect event attribute</title> <style> h1 { color:green; } body { text-align:center; } </style> <script> function Geeks() { alert(\"Text selected!\"); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2>onselect event attribute</h2> Text Box: <input type=\"text\" value=\"GeeksforGeeks: A computer science portal for geeks\" onselect=\"Geeks()\"> </body></html> </html>", "e": 24774, "s": 24172, "text": null }, { "code": null, "e": 24783, "s": 24774, "text": "Output: " }, { "code": null, "e": 24866, "s": 24783, "text": "Supported Browsers: The browser supported by onselect attribute are listed below: " }, { "code": null, "e": 24879, "s": 24866, "text": "Apple Safari" }, { "code": null, "e": 24893, "s": 24879, "text": "Google Chrome" }, { "code": null, "e": 24901, "s": 24893, "text": "Firefox" }, { "code": null, "e": 24907, "s": 24901, "text": "Opera" }, { "code": null, "e": 24925, "s": 24907, "text": "Internet Explorer" }, { "code": null, "e": 25062, "s": 24925, "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": 25079, "s": 25062, "text": "arorakashish0911" }, { "code": null, "e": 25099, "s": 25079, "text": "hritikbhatnagar2182" }, { "code": null, "e": 25115, "s": 25099, "text": "HTML-Attributes" }, { "code": null, "e": 25119, "s": 25115, "text": "CSS" }, { "code": null, "e": 25124, "s": 25119, "text": "HTML" }, { "code": null, "e": 25141, "s": 25124, "text": "Web Technologies" }, { "code": null, "e": 25146, "s": 25141, "text": "HTML" }, { "code": null, "e": 25244, "s": 25146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25294, "s": 25244, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25356, "s": 25294, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25414, "s": 25356, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 25462, "s": 25414, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25512, "s": 25462, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 25562, "s": 25512, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25624, "s": 25562, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25684, "s": 25624, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25732, "s": 25684, "text": "How to update Node.js and NPM to next version ?" } ]
ByteBuffer order() method in Java with Examples - GeeksforGeeks
17 Jun, 2019 The order() method of java.nio.ByteBuffer class is used to retrieve this buffer’s byte order. The byte order is used when reading or writing multibyte values, and when creating buffers that are views of this byte buffer. The order of a newly-created byte buffer is always BIG_ENDIAN. Syntax: public final ByteOrder order() Return Value: This method returns this buffer’s byte order. Below are the examples to illustrate the order() method: Examples 1: // Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20) .put(30); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= 3; i++) System.out.print(bb.getInt() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer's current position // using order() method ByteOrder value = bb.order(); // print the int value System.out.println("\n\nByte Value: " + value); }} Original ByteBuffer: 10 20 30 Byte Value: BIG_ENDIAN Examples 2: // Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // Reads the Int at this buffer's current position // using order() method ByteOrder value = bb.order(); // print the int value System.out.println("Byte Value: " + value); }} Byte Value: BIG_ENDIAN The order(ByteOrder bo) method of ByteBuffer is used to modifie this buffer’s byte order. Syntax: public final ByteBuffer order(ByteOrder bo) Parameters: This method takes the new byte order, either BIG_ENDIAN or LITTLE_ENDIAN as a parameter. Return Value: This method returns This buffer. Below are the examples to illustrate the order(ByteOrder bo) method: Examples 1: // Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // Reads the Int at this buffer's current position // using order() method ByteOrder oldbyteorder = bb.order(); // print the result System.out.println("Old Byte Order: " + oldbyteorder); // Modifies this buffer's byte order // by using order() method ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder()); // Reads the Int at this buffer's current position // using order() method ByteOrder newbyteorder = bb1.order(); // print the result System.out.println("New Byte Order: " + newbyteorder); }} Old Byte Order: BIG_ENDIAN New Byte Order: LITTLE_ENDIAN Examples 2: // Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20) .put(30); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= 3; i++) System.out.print(bb.getInt() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer's current position // using order() method ByteOrder oldbyteorder = bb.order(); // print the result System.out.println("Old Byte Order: " + oldbyteorder); // Modifies this buffer's byte order // by using order() method ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder()); // Reads the Int at this buffer's current position // using order() method ByteOrder newbyteorder = bb1.order(); // print the result System.out.println("New Byte Order: " + newbyteorder); }} Original ByteBuffer: 10 20 30 Old Byte Order: BIG_ENDIAN New Byte Order: LITTLE_ENDIAN Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#order– https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#order-java.nio.ByteOrder- Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n17 Jun, 2019" }, { "code": null, "e": 24232, "s": 23948, "text": "The order() method of java.nio.ByteBuffer class is used to retrieve this buffer’s byte order. The byte order is used when reading or writing multibyte values, and when creating buffers that are views of this byte buffer. The order of a newly-created byte buffer is always BIG_ENDIAN." }, { "code": null, "e": 24240, "s": 24232, "text": "Syntax:" }, { "code": null, "e": 24271, "s": 24240, "text": "public final ByteOrder order()" }, { "code": null, "e": 24331, "s": 24271, "text": "Return Value: This method returns this buffer’s byte order." }, { "code": null, "e": 24388, "s": 24331, "text": "Below are the examples to illustrate the order() method:" }, { "code": null, "e": 24400, "s": 24388, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20) .put(30); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= 3; i++) System.out.print(bb.getInt() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer's current position // using order() method ByteOrder value = bb.order(); // print the int value System.out.println(\"\\n\\nByte Value: \" + value); }}", "e": 25318, "s": 24400, "text": null }, { "code": null, "e": 25375, "s": 25318, "text": "Original ByteBuffer: \n10 20 30 \n\nByte Value: BIG_ENDIAN\n" }, { "code": null, "e": 25387, "s": 25375, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // Reads the Int at this buffer's current position // using order() method ByteOrder value = bb.order(); // print the int value System.out.println(\"Byte Value: \" + value); }}", "e": 25887, "s": 25387, "text": null }, { "code": null, "e": 25911, "s": 25887, "text": "Byte Value: BIG_ENDIAN\n" }, { "code": null, "e": 26001, "s": 25911, "text": "The order(ByteOrder bo) method of ByteBuffer is used to modifie this buffer’s byte order." }, { "code": null, "e": 26009, "s": 26001, "text": "Syntax:" }, { "code": null, "e": 26053, "s": 26009, "text": "public final ByteBuffer order(ByteOrder bo)" }, { "code": null, "e": 26154, "s": 26053, "text": "Parameters: This method takes the new byte order, either BIG_ENDIAN or LITTLE_ENDIAN as a parameter." }, { "code": null, "e": 26201, "s": 26154, "text": "Return Value: This method returns This buffer." }, { "code": null, "e": 26270, "s": 26201, "text": "Below are the examples to illustrate the order(ByteOrder bo) method:" }, { "code": null, "e": 26282, "s": 26270, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // Reads the Int at this buffer's current position // using order() method ByteOrder oldbyteorder = bb.order(); // print the result System.out.println(\"Old Byte Order: \" + oldbyteorder); // Modifies this buffer's byte order // by using order() method ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder()); // Reads the Int at this buffer's current position // using order() method ByteOrder newbyteorder = bb1.order(); // print the result System.out.println(\"New Byte Order: \" + newbyteorder); }}", "e": 27163, "s": 26282, "text": null }, { "code": null, "e": 27221, "s": 27163, "text": "Old Byte Order: BIG_ENDIAN\nNew Byte Order: LITTLE_ENDIAN\n" }, { "code": null, "e": 27233, "s": 27221, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// order() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(12); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20) .put(30); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= 3; i++) System.out.print(bb.getInt() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer's current position // using order() method ByteOrder oldbyteorder = bb.order(); // print the result System.out.println(\"Old Byte Order: \" + oldbyteorder); // Modifies this buffer's byte order // by using order() method ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder()); // Reads the Int at this buffer's current position // using order() method ByteOrder newbyteorder = bb1.order(); // print the result System.out.println(\"New Byte Order: \" + newbyteorder); }}", "e": 28528, "s": 27233, "text": null }, { "code": null, "e": 28617, "s": 28528, "text": "Original ByteBuffer: \n10 20 30 Old Byte Order: BIG_ENDIAN\nNew Byte Order: LITTLE_ENDIAN\n" }, { "code": null, "e": 28628, "s": 28617, "text": "Reference:" }, { "code": null, "e": 28702, "s": 28628, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#order–" }, { "code": null, "e": 28795, "s": 28702, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#order-java.nio.ByteOrder-" }, { "code": null, "e": 28811, "s": 28795, "text": "Java-ByteBuffer" }, { "code": null, "e": 28826, "s": 28811, "text": "Java-Functions" }, { "code": null, "e": 28843, "s": 28826, "text": "Java-NIO package" }, { "code": null, "e": 28848, "s": 28843, "text": "Java" }, { "code": null, "e": 28853, "s": 28848, "text": "Java" }, { "code": null, "e": 28951, "s": 28853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28966, "s": 28951, "text": "Stream In Java" }, { "code": null, "e": 29012, "s": 28966, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29033, "s": 29012, "text": "Constructors in Java" }, { "code": null, "e": 29052, "s": 29033, "text": "Exceptions in Java" }, { "code": null, "e": 29082, "s": 29052, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29099, "s": 29082, "text": "Generics in Java" }, { "code": null, "e": 29142, "s": 29099, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29171, "s": 29142, "text": "HashMap get() Method in Java" }, { "code": null, "e": 29192, "s": 29171, "text": "Introduction to Java" } ]
perform method - Action Chains in Selenium Python - GeeksforGeeks
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around perform method on Action Chains in Python Selenium. perform method is used to perform all stored operations in action instance of ActionChains class. Syntax – perform() Example – <input type ="text" name ="passwd" id ="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd") Now one can use perform method as an Action chain as below – action.click(on_element=element) action.perform() To demonstrate, perform method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element. Program – # import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform() Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 25871, "s": 25843, "text": "\n15 May, 2020" }, { "code": null, "e": 26473, "s": 25871, "text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around perform method on Action Chains in Python Selenium. perform method is used to perform all stored operations in action instance of ActionChains class." }, { "code": null, "e": 26482, "s": 26473, "text": "Syntax –" }, { "code": null, "e": 26492, "s": 26482, "text": "perform()" }, { "code": null, "e": 26502, "s": 26492, "text": "Example –" }, { "code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />", "e": 26556, "s": 26502, "text": null }, { "code": null, "e": 26637, "s": 26556, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")", "e": 26733, "s": 26637, "text": null }, { "code": null, "e": 26794, "s": 26733, "text": "Now one can use perform method as an Action chain as below –" }, { "code": null, "e": 26845, "s": 26794, "text": "action.click(on_element=element)\naction.perform()\n" }, { "code": null, "e": 26984, "s": 26845, "text": "To demonstrate, perform method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element." }, { "code": null, "e": 26994, "s": 26984, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform()", "e": 27477, "s": 26994, "text": null }, { "code": null, "e": 27486, "s": 27477, "text": "Output –" }, { "code": null, "e": 27502, "s": 27486, "text": "Python-selenium" }, { "code": null, "e": 27511, "s": 27502, "text": "selenium" }, { "code": null, "e": 27518, "s": 27511, "text": "Python" }, { "code": null, "e": 27616, "s": 27518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27634, "s": 27616, "text": "Python Dictionary" }, { "code": null, "e": 27666, "s": 27634, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27688, "s": 27666, "text": "Enumerate() in Python" }, { "code": null, "e": 27730, "s": 27688, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27756, "s": 27730, "text": "Python String | replace()" }, { "code": null, "e": 27785, "s": 27756, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27822, "s": 27785, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27858, "s": 27822, "text": "Convert integer to string in Python" }, { "code": null, "e": 27900, "s": 27858, "text": "Check if element exists in list in Python" } ]
HTML | DOM Style order Property - GeeksforGeeks
03 Nov, 2021 The DOM Style order property specifies the order of a flexible element relative to the rest of the flexible elements inside the same container element. Syntax: To set the property:object.style.order = "number | initial | inherit" object.style.order = "number | initial | inherit" To get the property:object.style.orderReturn Values: It returns a String, value which represents the order property of an elementProperty Values:Number: Specifies the order for the flexible element.Default value 0.Initial: Sets the property to its default value.Inherit: Inherits the property from its parent element.Example:<!DOCTYPE html><!DOCTYPE html><html> <head> <title> HTML | DOM Style order Property </title> <style> #main { width: 180px; height: 90px; border: 1px solid #000000; display: flex; } #main div { width: 90px; height: 90px; } </style></head> <body> <!-- two div with different color. --> <div id="main"> <div style="background-color:black;" id="black"></div> <div style="background-color:white;" id="white">I am white.</div> </div> <p>Click the button below to change the order of the four DIV's:</p> <button onclick="myFunction()">CLICK</button> <!-- Change order of div --> <script> function myFunction() { document.getElementById( "black").style.order = "2"; document.getElementById( "white").style.order = "1"; } </script> </body> </html> Output:Before the clicking of button:After the clicking of button:Supported Browser: The browser supported by HTML | DOM Style order Property are listed below:Google ChromeInternet Explorer 12.0FirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave object.style.order Return Values: It returns a String, value which represents the order property of an element Property Values: Number: Specifies the order for the flexible element.Default value 0. Initial: Sets the property to its default value. Inherit: Inherits the property from its parent element. Example: <!DOCTYPE html><!DOCTYPE html><html> <head> <title> HTML | DOM Style order Property </title> <style> #main { width: 180px; height: 90px; border: 1px solid #000000; display: flex; } #main div { width: 90px; height: 90px; } </style></head> <body> <!-- two div with different color. --> <div id="main"> <div style="background-color:black;" id="black"></div> <div style="background-color:white;" id="white">I am white.</div> </div> <p>Click the button below to change the order of the four DIV's:</p> <button onclick="myFunction()">CLICK</button> <!-- Change order of div --> <script> function myFunction() { document.getElementById( "black").style.order = "2"; document.getElementById( "white").style.order = "1"; } </script> </body> </html> Output: Before the clicking of button: After the clicking of button: Supported Browser: The browser supported by HTML | DOM Style order Property are listed below: Google Chrome Internet Explorer 12.0 Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25171, "s": 25143, "text": "\n03 Nov, 2021" }, { "code": null, "e": 25323, "s": 25171, "text": "The DOM Style order property specifies the order of a flexible element relative to the rest of the flexible elements inside the same container element." }, { "code": null, "e": 25331, "s": 25323, "text": "Syntax:" }, { "code": null, "e": 25401, "s": 25331, "text": "To set the property:object.style.order = \"number | initial | inherit\"" }, { "code": null, "e": 25451, "s": 25401, "text": "object.style.order = \"number | initial | inherit\"" }, { "code": null, "e": 27187, "s": 25451, "text": "To get the property:object.style.orderReturn Values: It returns a String, value which represents the order property of an elementProperty Values:Number: Specifies the order for the flexible element.Default value 0.Initial: Sets the property to its default value.Inherit: Inherits the property from its parent element.Example:<!DOCTYPE html><!DOCTYPE html><html> <head> <title> HTML | DOM Style order Property </title> <style> #main { width: 180px; height: 90px; border: 1px solid #000000; display: flex; } #main div { width: 90px; height: 90px; } </style></head> <body> <!-- two div with different color. --> <div id=\"main\"> <div style=\"background-color:black;\" id=\"black\"></div> <div style=\"background-color:white;\" id=\"white\">I am white.</div> </div> <p>Click the button below to change the order of the four DIV's:</p> <button onclick=\"myFunction()\">CLICK</button> <!-- Change order of div --> <script> function myFunction() { document.getElementById( \"black\").style.order = \"2\"; document.getElementById( \"white\").style.order = \"1\"; } </script> </body> </html> Output:Before the clicking of button:After the clicking of button:Supported Browser: The browser supported by HTML | DOM Style order Property are listed below:Google ChromeInternet Explorer 12.0FirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27206, "s": 27187, "text": "object.style.order" }, { "code": null, "e": 27298, "s": 27206, "text": "Return Values: It returns a String, value which represents the order property of an element" }, { "code": null, "e": 27315, "s": 27298, "text": "Property Values:" }, { "code": null, "e": 27385, "s": 27315, "text": "Number: Specifies the order for the flexible element.Default value 0." }, { "code": null, "e": 27434, "s": 27385, "text": "Initial: Sets the property to its default value." }, { "code": null, "e": 27490, "s": 27434, "text": "Inherit: Inherits the property from its parent element." }, { "code": null, "e": 27499, "s": 27490, "text": "Example:" }, { "code": "<!DOCTYPE html><!DOCTYPE html><html> <head> <title> HTML | DOM Style order Property </title> <style> #main { width: 180px; height: 90px; border: 1px solid #000000; display: flex; } #main div { width: 90px; height: 90px; } </style></head> <body> <!-- two div with different color. --> <div id=\"main\"> <div style=\"background-color:black;\" id=\"black\"></div> <div style=\"background-color:white;\" id=\"white\">I am white.</div> </div> <p>Click the button below to change the order of the four DIV's:</p> <button onclick=\"myFunction()\">CLICK</button> <!-- Change order of div --> <script> function myFunction() { document.getElementById( \"black\").style.order = \"2\"; document.getElementById( \"white\").style.order = \"1\"; } </script> </body> </html> ", "e": 28527, "s": 27499, "text": null }, { "code": null, "e": 28535, "s": 28527, "text": "Output:" }, { "code": null, "e": 28566, "s": 28535, "text": "Before the clicking of button:" }, { "code": null, "e": 28596, "s": 28566, "text": "After the clicking of button:" }, { "code": null, "e": 28690, "s": 28596, "text": "Supported Browser: The browser supported by HTML | DOM Style order Property are listed below:" }, { "code": null, "e": 28704, "s": 28690, "text": "Google Chrome" }, { "code": null, "e": 28727, "s": 28704, "text": "Internet Explorer 12.0" }, { "code": null, "e": 28735, "s": 28727, "text": "Firefox" }, { "code": null, "e": 28741, "s": 28735, "text": "Opera" }, { "code": null, "e": 28748, "s": 28741, "text": "Safari" }, { "code": null, "e": 28885, "s": 28748, "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": 28899, "s": 28885, "text": "ManasChhabra2" }, { "code": null, "e": 28908, "s": 28899, "text": "HTML-DOM" }, { "code": null, "e": 28915, "s": 28908, "text": "Picked" }, { "code": null, "e": 28920, "s": 28915, "text": "HTML" }, { "code": null, "e": 28937, "s": 28920, "text": "Web Technologies" }, { "code": null, "e": 28942, "s": 28937, "text": "HTML" }, { "code": null, "e": 29040, "s": 28942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29090, "s": 29040, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29152, "s": 29090, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29200, "s": 29152, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29260, "s": 29200, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29313, "s": 29260, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29353, "s": 29313, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29386, "s": 29353, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29431, "s": 29386, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29474, "s": 29431, "text": "How to fetch data from an API in ReactJS ?" } ]
Priority Queue of Vectors in C++ STL with Examples - GeeksforGeeks
17 Mar, 2020 Priority Queue in STL Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in non increasing order(hence we can see that each element of the queue has a priority{fixed order}) Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. Priority Queue of Vectors in STL: Priority Queue of Vectors can be very efficient in designing complex data structures. Syntax: priority_queue<vector<datatype>> pq; For example: Consider a simple problem where we have to print the maximum vector that is in the queue. // C++ program to demonstrate// use of priority queue for vectors #include <bits/stdc++.h>using namespace std; priority_queue<vector<int> > pq; // Prints maximum vectorvoid Print_Maximum_Vector(vector<int> Vec){ for (int i = 0; i < Vec.size(); i++) { cout << Vec[i] << " "; } cout << endl; return;} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 10, 20, 35, 40 }; vector<int> data_3{ 30, 25, 10, 50 }; vector<int> data_4{ 20, 10, 30, 40 }; vector<int> data_5{ 5, 10, 30, 40 }; // Inserting vectors into priority queue pq.push(data_1); pq.push(data_2); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); // Inserting vectors into priority queue pq.push(data_3); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); // Inserting vectors into priority queue pq.push(data_4); pq.push(data_5); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); return 0;} 10 20 35 40 30 25 10 50 30 25 10 50 cpp-priority-queue cpp-vector C++ Programs Queue Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 25877, "s": 25849, "text": "\n17 Mar, 2020" }, { "code": null, "e": 26175, "s": 25877, "text": "Priority Queue in STL Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in non increasing order(hence we can see that each element of the queue has a priority{fixed order})" }, { "code": null, "e": 26484, "s": 26175, "text": "Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators." }, { "code": null, "e": 26604, "s": 26484, "text": "Priority Queue of Vectors in STL: Priority Queue of Vectors can be very efficient in designing complex data structures." }, { "code": null, "e": 26612, "s": 26604, "text": "Syntax:" }, { "code": null, "e": 26650, "s": 26612, "text": "priority_queue<vector<datatype>> pq;\n" }, { "code": null, "e": 26753, "s": 26650, "text": "For example: Consider a simple problem where we have to print the maximum vector that is in the queue." }, { "code": "// C++ program to demonstrate// use of priority queue for vectors #include <bits/stdc++.h>using namespace std; priority_queue<vector<int> > pq; // Prints maximum vectorvoid Print_Maximum_Vector(vector<int> Vec){ for (int i = 0; i < Vec.size(); i++) { cout << Vec[i] << \" \"; } cout << endl; return;} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 10, 20, 35, 40 }; vector<int> data_3{ 30, 25, 10, 50 }; vector<int> data_4{ 20, 10, 30, 40 }; vector<int> data_5{ 5, 10, 30, 40 }; // Inserting vectors into priority queue pq.push(data_1); pq.push(data_2); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); // Inserting vectors into priority queue pq.push(data_3); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); // Inserting vectors into priority queue pq.push(data_4); pq.push(data_5); // printing the maximum vector till now Print_Maximum_Vector(pq.top()); return 0;}", "e": 27831, "s": 26753, "text": null }, { "code": null, "e": 27870, "s": 27831, "text": "10 20 35 40 \n30 25 10 50 \n30 25 10 50\n" }, { "code": null, "e": 27889, "s": 27870, "text": "cpp-priority-queue" }, { "code": null, "e": 27900, "s": 27889, "text": "cpp-vector" }, { "code": null, "e": 27913, "s": 27900, "text": "C++ Programs" }, { "code": null, "e": 27919, "s": 27913, "text": "Queue" }, { "code": null, "e": 27925, "s": 27919, "text": "Queue" }, { "code": null, "e": 28023, "s": 27925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28064, "s": 28023, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 28123, "s": 28064, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 28144, "s": 28123, "text": "Const keyword in C++" }, { "code": null, "e": 28156, "s": 28144, "text": "cout in C++" }, { "code": null, "e": 28177, "s": 28156, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 28217, "s": 28177, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 28251, "s": 28217, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 28275, "s": 28251, "text": "Queue Interface In Java" }, { "code": null, "e": 28291, "s": 28275, "text": "Queue in Python" } ]
Preprocessor output of cpp file - GeeksforGeeks
19 Jan, 2021 Preprocessing is a stage where preprocessor directives are expanded or processed before source code is sent to the compiler. The most common example of such directive is #include or #define. A preprocessor output has “.i” extension. Two files are created here: C++ MyHeader.h // C++ program for the test.cpp#include "MyHeader.h"#include <iostream>using namespace std;#define VAL 9 // Driver Codeint main(){ // powerOfTwo function is defined // in “MyHeader.h” cout << powerOfTwo(VAL) << endl; return 0;} // Below is code for the header file// named as "MyHeader.h"#pragma once // Function to find the value of 2^xsize_t powerOfTwo(const int x){ // return the value return 1 << x;} Now on command prompt, the output can be preprocessed in two ways: Method 1 – inside cmd.exe: This method is not recommended. g++ -E test.cpp Here, output can’t be shown as header file iostream will expand up to 50000 lines. This will print all the data on the command prompt which might take a few moments as cout is quite slow in printing. Press any key to stop printing on prompt. The command prompt doesn’t retain all 50000 lines. It has its own limits after which earlier outputs can’t be seen. Method 2 – Create an explicit file “.i”: Use the below-given command to get hello.i g++ -E test.cpp -o hello.i Output: Explanation: In the above output, there are only 26000 lines. It is normal as iostream is a big header file and also includes many other header files that do include others. #include directive just copies the content of respective header files.As noticed, the actual program lies at the very end at 26527 lines but still, it gives error messages for the correct line. Also, all content of multiple files is wrapped into hello.i but still error messages received for correct file context. # 7 "MyHeader.h" This is the line control directive. It will tell the compiler that the next line is the 7th line in the file MyHeader.h. If the above code is executed, then the function powerOfTwo() is defined at line number 7. Also, macro VAL is completely replaced by 9. The preprocessor output file can be compiled using the below command: g++ hello.i -o test.exe Preprocessing of include directive : // test.cpp #include<iostream> int main(){ std::cout << "GeekForGeeks" << std::endl #include"MyHeader.h" } // MyHeader.h ; In the above example, the semi-colon is copied and pasted from MyHeader.h to the line next to cout statement by #include directive. Hence, no error will generate here. Also, Myheader.h can be a text file, a python file, or HTML file no matter what, #include will just copy it. CPP-Basics CPP-Output C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25343, "s": 25315, "text": "\n19 Jan, 2021" }, { "code": null, "e": 25576, "s": 25343, "text": "Preprocessing is a stage where preprocessor directives are expanded or processed before source code is sent to the compiler. The most common example of such directive is #include or #define. A preprocessor output has “.i” extension." }, { "code": null, "e": 25604, "s": 25576, "text": "Two files are created here:" }, { "code": null, "e": 25608, "s": 25604, "text": "C++" }, { "code": null, "e": 25619, "s": 25608, "text": "MyHeader.h" }, { "code": "// C++ program for the test.cpp#include \"MyHeader.h\"#include <iostream>using namespace std;#define VAL 9 // Driver Codeint main(){ // powerOfTwo function is defined // in “MyHeader.h” cout << powerOfTwo(VAL) << endl; return 0;}", "e": 25862, "s": 25619, "text": null }, { "code": "// Below is code for the header file// named as \"MyHeader.h\"#pragma once // Function to find the value of 2^xsize_t powerOfTwo(const int x){ // return the value return 1 << x;}", "e": 26048, "s": 25862, "text": null }, { "code": null, "e": 26115, "s": 26048, "text": "Now on command prompt, the output can be preprocessed in two ways:" }, { "code": null, "e": 26174, "s": 26115, "text": "Method 1 – inside cmd.exe: This method is not recommended." }, { "code": null, "e": 26190, "s": 26174, "text": "g++ -E test.cpp" }, { "code": null, "e": 26548, "s": 26190, "text": "Here, output can’t be shown as header file iostream will expand up to 50000 lines. This will print all the data on the command prompt which might take a few moments as cout is quite slow in printing. Press any key to stop printing on prompt. The command prompt doesn’t retain all 50000 lines. It has its own limits after which earlier outputs can’t be seen." }, { "code": null, "e": 26589, "s": 26548, "text": "Method 2 – Create an explicit file “.i”:" }, { "code": null, "e": 26632, "s": 26589, "text": "Use the below-given command to get hello.i" }, { "code": null, "e": 26659, "s": 26632, "text": "g++ -E test.cpp -o hello.i" }, { "code": null, "e": 26667, "s": 26659, "text": "Output:" }, { "code": null, "e": 27155, "s": 26667, "text": "Explanation: In the above output, there are only 26000 lines. It is normal as iostream is a big header file and also includes many other header files that do include others. #include directive just copies the content of respective header files.As noticed, the actual program lies at the very end at 26527 lines but still, it gives error messages for the correct line. Also, all content of multiple files is wrapped into hello.i but still error messages received for correct file context." }, { "code": null, "e": 27172, "s": 27155, "text": "# 7 \"MyHeader.h\"" }, { "code": null, "e": 27429, "s": 27172, "text": "This is the line control directive. It will tell the compiler that the next line is the 7th line in the file MyHeader.h. If the above code is executed, then the function powerOfTwo() is defined at line number 7. Also, macro VAL is completely replaced by 9." }, { "code": null, "e": 27499, "s": 27429, "text": "The preprocessor output file can be compiled using the below command:" }, { "code": null, "e": 27523, "s": 27499, "text": "g++ hello.i -o test.exe" }, { "code": null, "e": 27560, "s": 27523, "text": "Preprocessing of include directive :" }, { "code": null, "e": 27672, "s": 27560, "text": "// test.cpp\n#include<iostream>\n\nint main(){\n std::cout << \"GeekForGeeks\" << std::endl\n #include\"MyHeader.h\"\n}" }, { "code": null, "e": 27688, "s": 27672, "text": "// MyHeader.h\n;" }, { "code": null, "e": 27965, "s": 27688, "text": "In the above example, the semi-colon is copied and pasted from MyHeader.h to the line next to cout statement by #include directive. Hence, no error will generate here. Also, Myheader.h can be a text file, a python file, or HTML file no matter what, #include will just copy it." }, { "code": null, "e": 27976, "s": 27965, "text": "CPP-Basics" }, { "code": null, "e": 27987, "s": 27976, "text": "CPP-Output" }, { "code": null, "e": 27991, "s": 27987, "text": "C++" }, { "code": null, "e": 28004, "s": 27991, "text": "C++ Programs" }, { "code": null, "e": 28008, "s": 28004, "text": "CPP" }, { "code": null, "e": 28106, "s": 28008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28134, "s": 28106, "text": "Operator Overloading in C++" }, { "code": null, "e": 28154, "s": 28134, "text": "Polymorphism in C++" }, { "code": null, "e": 28187, "s": 28154, "text": "Friend class and function in C++" }, { "code": null, "e": 28211, "s": 28187, "text": "Sorting a vector in C++" }, { "code": null, "e": 28236, "s": 28211, "text": "std::string class in C++" }, { "code": null, "e": 28271, "s": 28236, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 28315, "s": 28271, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 28374, "s": 28315, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 28400, "s": 28374, "text": "C++ Program for QuickSort" } ]
Find largest prime factor of a number - GeeksforGeeks
13 Jan, 2022 Given a positive integer ‘n'( 1 <= n <= 1015). Find the largest prime factor of a number. Input: 6 Output: 3 Explanation Prime factor of 6 are- 2, 3 Largest of them is '3' Input: 15 Output: 5 The approach is simple, just factorise the given number by dividing it with the divisor of a number and keep updating the maximum prime factor. See this to understand more. C++ C Java Python3 C# PHP Javascript // C++ Program to find largest prime// factor of number#include <iostream>#include<bits/stdc++.h>using namespace std; // A function to find largest prime factorlong long maxPrimeFactors(long long n){ // Initialize the maximum prime factor // variable with the lowest one long long maxPrime = -1; // Print the number of 2s that divide n while (n % 2 == 0) { maxPrime = 2; n >>= 1; // equivalent to n /= 2 } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n=n/3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i+2) == 0) { maxPrime = i+2; n = n / (i+2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime;} // Driver program to test above functionint main(){ long long n = 15; cout << maxPrimeFactors(n) << endl; n = 25698751364526; cout << maxPrimeFactors(n); } // C Program to find largest prime// factor of number#include <math.h>#include <stdio.h> // A function to find largest prime factorlong long maxPrimeFactors(long long n){ // Initialize the maximum prime factor // variable with the lowest one long long maxPrime = -1; // Print the number of 2s that divide n while (n % 2 == 0) { maxPrime = 2; n >>= 1; // equivalent to n /= 2 } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime;} // Driver program to test above functionint main(){ long long n = 15; printf("%lld\n", maxPrimeFactors(n)); n = 25698751364526; printf("%lld", maxPrimeFactors(n)); return 0;} // Java Program to find largest// prime factor of numberimport java.io.*;import java.util.*; class GFG { // function to find largest prime factor static long maxPrimeFactors(long n) { // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= Math.sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime; } // Driver code public static void main(String[] args) { Long n = 15l; System.out.println(maxPrimeFactors(n)); n = 25698751364526l; System.out.println(maxPrimeFactors(n)); }} # Python3 code to find largest prime# factor of numberimport math # A function to find largest prime factordef maxPrimeFactors (n): # Initialize the maximum prime factor # variable with the lowest one maxPrime = -1 # Print the number of 2s that divide n while n % 2 == 0: maxPrime = 2 n >>= 1 # equivalent to n /= 2 # n must be odd at this point while n % 3 == 0: maxPrime = 3 n=n/3 # now we have to iterate only for integers # who does not have prime factor 2 and 3 for i in range(5, int(math.sqrt(n)) + 1, 6): while n % i == 0: maxPrime = i n = n / i while n % (i+2) == 0: maxPrime = i+2 n = n / (i+2) # This condition is to handle the # case when n is a prime number # greater than 4 if n > 4: maxPrime = n return int(maxPrime) # Driver code to test above functionn = 15print(maxPrimeFactors(n)) n = 25698751364526print(maxPrimeFactors(n)) // C# program to find largest// prime factor of numberusing System; class GFG { // function to find largest prime factor static long maxPrimeFactors(long n) { // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= Math.Sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime; } // Driver code public static void Main() { long n = 15L; Console.WriteLine(maxPrimeFactors(n)); n = 25698751364526L; Console.WriteLine(maxPrimeFactors(n)); }} <?php// PHP Program to find// largest prime factor// of number // A function to find// largest prime factorfunction maxPrimeFactors($n){ // Initialize the maximum // prime factor variable // with the lowest one $maxPrime = -1; // Print the number of // 2s that divide n while ($n % 2 == 0) { $maxPrime = 2; // equivalent to n /= 2 $n >>= 1; } // n must be odd at this point while ($n % 3 == 0) { $maxPrime = 3; $n=$n/3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for ($i = 3; $i <= sqrt($n); $i += 2) { while ($n % $i == 0) { $maxPrime = $i; $n = $n / $i; } while ($n % ($i+2) == 0) { $maxPrime = $i+2; $n = $n / ($i+2); } } // This condition is // to handle the case // when n is a prime // number greater than 4 if ($n > 4) $maxPrime = $n; return $maxPrime;} // Driver Code $n = 15; echo maxPrimeFactors($n), "\n"; $n = 25698751364526; echo maxPrimeFactors($n), "\n"; ?> <script>// Javascript program to find largest prime factorfunction maxPrimeFactor(n) { let maxPrime = -1; while(n % 2 == 0) { n = n / 2; maxPrime = 2; } while(n % 3 == 0) { n = n / 3; maxPrime = 3; } for (let i = 5; i <= Math.sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } return n > 4 ? n : maxPrime;} document.write(maxPrimeFactor(15));document.write(maxPrimeFactor(25698751364526)); // This code is contributed by 8chkh7v1i3lrbhuvxyg3d9gbg9e097eodfhj7qbz.</script> 5 328513 Time complexity: Auxiliary space: jit_t Shivi_Aggarwal nandannits 8chkh7v1i3lrbhuvxyg3d9gbg9e097eodfhj7qbz number-theory prime-factor Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 25861, "s": 25833, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25953, "s": 25861, "text": "Given a positive integer ‘n'( 1 <= n <= 1015). Find the largest prime factor of a number. " }, { "code": null, "e": 26056, "s": 25953, "text": "Input: 6\nOutput: 3\nExplanation\nPrime factor of 6 are- 2, 3\nLargest of them is '3'\n\nInput: 15\nOutput: 5" }, { "code": null, "e": 26233, "s": 26058, "text": "The approach is simple, just factorise the given number by dividing it with the divisor of a number and keep updating the maximum prime factor. See this to understand more. " }, { "code": null, "e": 26237, "s": 26233, "text": "C++" }, { "code": null, "e": 26239, "s": 26237, "text": "C" }, { "code": null, "e": 26244, "s": 26239, "text": "Java" }, { "code": null, "e": 26252, "s": 26244, "text": "Python3" }, { "code": null, "e": 26255, "s": 26252, "text": "C#" }, { "code": null, "e": 26259, "s": 26255, "text": "PHP" }, { "code": null, "e": 26270, "s": 26259, "text": "Javascript" }, { "code": "// C++ Program to find largest prime// factor of number#include <iostream>#include<bits/stdc++.h>using namespace std; // A function to find largest prime factorlong long maxPrimeFactors(long long n){ // Initialize the maximum prime factor // variable with the lowest one long long maxPrime = -1; // Print the number of 2s that divide n while (n % 2 == 0) { maxPrime = 2; n >>= 1; // equivalent to n /= 2 } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n=n/3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i+2) == 0) { maxPrime = i+2; n = n / (i+2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime;} // Driver program to test above functionint main(){ long long n = 15; cout << maxPrimeFactors(n) << endl; n = 25698751364526; cout << maxPrimeFactors(n); }", "e": 27440, "s": 26270, "text": null }, { "code": "// C Program to find largest prime// factor of number#include <math.h>#include <stdio.h> // A function to find largest prime factorlong long maxPrimeFactors(long long n){ // Initialize the maximum prime factor // variable with the lowest one long long maxPrime = -1; // Print the number of 2s that divide n while (n % 2 == 0) { maxPrime = 2; n >>= 1; // equivalent to n /= 2 } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime;} // Driver program to test above functionint main(){ long long n = 15; printf(\"%lld\\n\", maxPrimeFactors(n)); n = 25698751364526; printf(\"%lld\", maxPrimeFactors(n)); return 0;}", "e": 28616, "s": 27440, "text": null }, { "code": "// Java Program to find largest// prime factor of numberimport java.io.*;import java.util.*; class GFG { // function to find largest prime factor static long maxPrimeFactors(long n) { // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= Math.sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime; } // Driver code public static void main(String[] args) { Long n = 15l; System.out.println(maxPrimeFactors(n)); n = 25698751364526l; System.out.println(maxPrimeFactors(n)); }}", "e": 29995, "s": 28616, "text": null }, { "code": "# Python3 code to find largest prime# factor of numberimport math # A function to find largest prime factordef maxPrimeFactors (n): # Initialize the maximum prime factor # variable with the lowest one maxPrime = -1 # Print the number of 2s that divide n while n % 2 == 0: maxPrime = 2 n >>= 1 # equivalent to n /= 2 # n must be odd at this point while n % 3 == 0: maxPrime = 3 n=n/3 # now we have to iterate only for integers # who does not have prime factor 2 and 3 for i in range(5, int(math.sqrt(n)) + 1, 6): while n % i == 0: maxPrime = i n = n / i while n % (i+2) == 0: maxPrime = i+2 n = n / (i+2) # This condition is to handle the # case when n is a prime number # greater than 4 if n > 4: maxPrime = n return int(maxPrime) # Driver code to test above functionn = 15print(maxPrimeFactors(n)) n = 25698751364526print(maxPrimeFactors(n))", "e": 31018, "s": 29995, "text": null }, { "code": "// C# program to find largest// prime factor of numberusing System; class GFG { // function to find largest prime factor static long maxPrimeFactors(long n) { // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point while (n % 3 == 0) { maxPrime = 3; n = n / 3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for (int i = 5; i <= Math.Sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } // This condition is to handle the case // when n is a prime number greater than 4 if (n > 4) maxPrime = n; return maxPrime; } // Driver code public static void Main() { long n = 15L; Console.WriteLine(maxPrimeFactors(n)); n = 25698751364526L; Console.WriteLine(maxPrimeFactors(n)); }}", "e": 32356, "s": 31018, "text": null }, { "code": "<?php// PHP Program to find// largest prime factor// of number // A function to find// largest prime factorfunction maxPrimeFactors($n){ // Initialize the maximum // prime factor variable // with the lowest one $maxPrime = -1; // Print the number of // 2s that divide n while ($n % 2 == 0) { $maxPrime = 2; // equivalent to n /= 2 $n >>= 1; } // n must be odd at this point while ($n % 3 == 0) { $maxPrime = 3; $n=$n/3; } // now we have to iterate only for integers // who does not have prime factor 2 and 3 for ($i = 3; $i <= sqrt($n); $i += 2) { while ($n % $i == 0) { $maxPrime = $i; $n = $n / $i; } while ($n % ($i+2) == 0) { $maxPrime = $i+2; $n = $n / ($i+2); } } // This condition is // to handle the case // when n is a prime // number greater than 4 if ($n > 4) $maxPrime = $n; return $maxPrime;} // Driver Code $n = 15; echo maxPrimeFactors($n), \"\\n\"; $n = 25698751364526; echo maxPrimeFactors($n), \"\\n\"; ?>", "e": 33499, "s": 32356, "text": null }, { "code": "<script>// Javascript program to find largest prime factorfunction maxPrimeFactor(n) { let maxPrime = -1; while(n % 2 == 0) { n = n / 2; maxPrime = 2; } while(n % 3 == 0) { n = n / 3; maxPrime = 3; } for (let i = 5; i <= Math.sqrt(n); i += 6) { while (n % i == 0) { maxPrime = i; n = n / i; } while (n % (i + 2) == 0) { maxPrime = i + 2; n = n / (i + 2); } } return n > 4 ? n : maxPrime;} document.write(maxPrimeFactor(15));document.write(maxPrimeFactor(25698751364526)); // This code is contributed by 8chkh7v1i3lrbhuvxyg3d9gbg9e097eodfhj7qbz.</script>", "e": 34184, "s": 33499, "text": null }, { "code": null, "e": 34193, "s": 34184, "text": "5\n328513" }, { "code": null, "e": 34229, "s": 34193, "text": "Time complexity: Auxiliary space: " }, { "code": null, "e": 34235, "s": 34229, "text": "jit_t" }, { "code": null, "e": 34250, "s": 34235, "text": "Shivi_Aggarwal" }, { "code": null, "e": 34261, "s": 34250, "text": "nandannits" }, { "code": null, "e": 34302, "s": 34261, "text": "8chkh7v1i3lrbhuvxyg3d9gbg9e097eodfhj7qbz" }, { "code": null, "e": 34316, "s": 34302, "text": "number-theory" }, { "code": null, "e": 34329, "s": 34316, "text": "prime-factor" }, { "code": null, "e": 34342, "s": 34329, "text": "Mathematical" }, { "code": null, "e": 34356, "s": 34342, "text": "number-theory" }, { "code": null, "e": 34369, "s": 34356, "text": "Mathematical" }, { "code": null, "e": 34467, "s": 34369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34491, "s": 34467, "text": "Merge two sorted arrays" }, { "code": null, "e": 34534, "s": 34491, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34548, "s": 34534, "text": "Prime Numbers" }, { "code": null, "e": 34621, "s": 34548, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34662, "s": 34621, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34705, "s": 34662, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34726, "s": 34705, "text": "Operators in C / C++" }, { "code": null, "e": 34760, "s": 34726, "text": "Program for factorial of a number" }, { "code": null, "e": 34813, "s": 34760, "text": "Find minimum number of coins that make a given value" } ]
Convert Python datetime to epoch - GeeksforGeeks
23 Aug, 2021 In this article, we are going to discuss various ways by which we can convert Python DateTime to epoch. The epoch time is also known as POSIX time which will indicate the number of seconds passed from January 1, 1970, 00:00:00 (UTC) in most windows and Unix systems. Note: Epoch is platform-dependent which means it depends on the system or operating system you are using. DateTime is the time which is in the given format year/month/day/hours/minutes/seconds:milliseconds strftime() is used to convert string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime(). Syntax: datetime.datetime(timestamp).strftime(‘%s’) Parameter: timestamp is the input datetime $s is used to get the epoch string datetime is the module The parameter %s is a platform dependent format code, it works on Linux. In windows, the same code can be modified to run by %S in place of %s. Example: Python code to convert datetime to epoch using strftime Python3 # import datetime moduleimport datetime # convert datetime to epoch using strftime from# time stamp 2021/7/7/1/2/1# for linux:epoch = datetime.datetime(2021, 7, 7, 1, 2, 1).strftime('%s')# for windows:# epoch = datetime.datetime(2021, 7,7 , 1,2,1).strftime('%S')print(epoch) # convert datetime to epoch using strftime from# time stamp 2021/3/3/4/3/4epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).strftime('%s')print(epoch) # convert datetime to epoch using strftime from# time stamp 2021/7/7/12/12/34epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).strftime('%s')print(epoch) # convert datetime to epoch using strftime from # time stamp 2021/7/7/12/56/00epoch = datetime.datetime(2021, 7, 7, 12, 56, 0).strftime('%s')print(epoch) 1625619721 1614744184 1625659954 1625662560 we can get epoch from DateTime using timestamp(). Syntax: datetime.datetime(timestamp).timestamp() Parameter: datetime is the module timestamp is the input datetime Example: Python code to convert DateTime to epoch using timestamp() Python3 # import datetime moduleimport datetime # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/0/0/0epoch = datetime.datetime(2021, 7, 7, 0, 0, 0).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/3/3/4/3/4epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/12/12/34epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/12/56/00epoch = datetime.datetime(2021, 7, 7, 12, 56, 00).timestamp()print(epoch) 1625616000.0 1614744184.0 1625659954.0 1625662560.0 Picked Python datetime-program Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25804, "s": 25537, "text": "In this article, we are going to discuss various ways by which we can convert Python DateTime to epoch. The epoch time is also known as POSIX time which will indicate the number of seconds passed from January 1, 1970, 00:00:00 (UTC) in most windows and Unix systems." }, { "code": null, "e": 25910, "s": 25804, "text": "Note: Epoch is platform-dependent which means it depends on the system or operating system you are using." }, { "code": null, "e": 25960, "s": 25910, "text": "DateTime is the time which is in the given format" }, { "code": null, "e": 26010, "s": 25960, "text": "year/month/day/hours/minutes/seconds:milliseconds" }, { "code": null, "e": 26163, "s": 26010, "text": "strftime() is used to convert string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime()." }, { "code": null, "e": 26215, "s": 26163, "text": "Syntax: datetime.datetime(timestamp).strftime(‘%s’)" }, { "code": null, "e": 26226, "s": 26215, "text": "Parameter:" }, { "code": null, "e": 26258, "s": 26226, "text": "timestamp is the input datetime" }, { "code": null, "e": 26293, "s": 26258, "text": "$s is used to get the epoch string" }, { "code": null, "e": 26316, "s": 26293, "text": "datetime is the module" }, { "code": null, "e": 26460, "s": 26316, "text": "The parameter %s is a platform dependent format code, it works on Linux. In windows, the same code can be modified to run by %S in place of %s." }, { "code": null, "e": 26525, "s": 26460, "text": "Example: Python code to convert datetime to epoch using strftime" }, { "code": null, "e": 26533, "s": 26525, "text": "Python3" }, { "code": "# import datetime moduleimport datetime # convert datetime to epoch using strftime from# time stamp 2021/7/7/1/2/1# for linux:epoch = datetime.datetime(2021, 7, 7, 1, 2, 1).strftime('%s')# for windows:# epoch = datetime.datetime(2021, 7,7 , 1,2,1).strftime('%S')print(epoch) # convert datetime to epoch using strftime from# time stamp 2021/3/3/4/3/4epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).strftime('%s')print(epoch) # convert datetime to epoch using strftime from# time stamp 2021/7/7/12/12/34epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).strftime('%s')print(epoch) # convert datetime to epoch using strftime from # time stamp 2021/7/7/12/56/00epoch = datetime.datetime(2021, 7, 7, 12, 56, 0).strftime('%s')print(epoch)", "e": 27268, "s": 26533, "text": null }, { "code": null, "e": 27313, "s": 27268, "text": "1625619721\n1614744184\n1625659954\n1625662560\n" }, { "code": null, "e": 27363, "s": 27313, "text": "we can get epoch from DateTime using timestamp()." }, { "code": null, "e": 27412, "s": 27363, "text": "Syntax: datetime.datetime(timestamp).timestamp()" }, { "code": null, "e": 27423, "s": 27412, "text": "Parameter:" }, { "code": null, "e": 27446, "s": 27423, "text": "datetime is the module" }, { "code": null, "e": 27478, "s": 27446, "text": "timestamp is the input datetime" }, { "code": null, "e": 27547, "s": 27478, "text": "Example: Python code to convert DateTime to epoch using timestamp()" }, { "code": null, "e": 27555, "s": 27547, "text": "Python3" }, { "code": "# import datetime moduleimport datetime # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/0/0/0epoch = datetime.datetime(2021, 7, 7, 0, 0, 0).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/3/3/4/3/4epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/12/12/34epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).timestamp()print(epoch) # convert datetime to epoch using timestamp()# from time stamp 2021/7/7/12/56/00epoch = datetime.datetime(2021, 7, 7, 12, 56, 00).timestamp()print(epoch)", "e": 28205, "s": 27555, "text": null }, { "code": null, "e": 28258, "s": 28205, "text": "1625616000.0\n1614744184.0\n1625659954.0\n1625662560.0\n" }, { "code": null, "e": 28265, "s": 28258, "text": "Picked" }, { "code": null, "e": 28289, "s": 28265, "text": "Python datetime-program" }, { "code": null, "e": 28305, "s": 28289, "text": "Python-datetime" }, { "code": null, "e": 28312, "s": 28305, "text": "Python" }, { "code": null, "e": 28410, "s": 28312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28442, "s": 28410, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28484, "s": 28442, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28526, "s": 28484, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28553, "s": 28526, "text": "Python Classes and Objects" }, { "code": null, "e": 28609, "s": 28553, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28648, "s": 28609, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28670, "s": 28648, "text": "Defaultdict in Python" }, { "code": null, "e": 28701, "s": 28670, "text": "Python | os.path.join() method" }, { "code": null, "e": 28730, "s": 28701, "text": "Create a directory in Python" } ]
MongoDB - Bulk.insert() Method - GeeksforGeeks
21 Jul, 2021 In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist. Syntax: Bulk.insert(<document>); Parameter: document: The document that has to be inserted. Examples: In the following examples, we are working with: Database: myDatabase Collection: students Now, let’s use the below commands to make an object of Bulk using initializeUnorderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeUnorderedBulkOp() method is used to generate an unordered list that MongoDB runs in bulk. var bulk = db.students.initializeUnorderedBulkOp(); bulk.insert( { first_name: "Sachin", last_name: "Tendulkar" } ); bulk.insert( { first_name: "Virender", last_name: "Sehwag" } ); bulk.insert( { first_name: "Shikhar", last_name: "Dhawan" } ); bulk.insert( { first_name: "Mohammed", last_name: "Shami" } ); bulk.insert( { first_name: "Shreyas", last_name: "Iyer" } ); bulk.execute(); Let’s check the inserted documents using the below command: db.students.find(); Now, let’s use the below commands to make an object of Bulk using initializeOrderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeOrderedBulkOp() method is used to generate an ordered list that MongoDB runs in bulk. var bulk = db.students.initializeOrderedBulkOp(); bulk.insert( { first_name: "Robin", last_name: "Marvin" } ); bulk.insert( { first_name: "John", last_name: "Hudson" } ); bulk.insert( { first_name: "Nancy", last_name: "Drew" } ); bulk.insert( { first_name: "Tom", last_name: "Wheeler" } ); bulk.insert( { first_name: "Anna", last_name: "Ryder" } ); bulk.execute(); Let’s check the inserted documents. Since we have inserted 5 more items into the collection, run the below command to get the last 5 items from the collection. db.students.find().sort({'_id':-1}).limit(5).pretty() MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB insertMany() Method - db.Collection.insertMany() MongoDB - Update() Method MongoDB Cursor MongoDB updateMany() Method - db.Collection.updateMany()
[ { "code": null, "e": 25517, "s": 25489, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25789, "s": 25517, "text": "In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist. " }, { "code": null, "e": 25797, "s": 25789, "text": "Syntax:" }, { "code": null, "e": 25822, "s": 25797, "text": "Bulk.insert(<document>);" }, { "code": null, "e": 25833, "s": 25822, "text": "Parameter:" }, { "code": null, "e": 25881, "s": 25833, "text": "document: The document that has to be inserted." }, { "code": null, "e": 25891, "s": 25881, "text": "Examples:" }, { "code": null, "e": 25939, "s": 25891, "text": "In the following examples, we are working with:" }, { "code": null, "e": 25960, "s": 25939, "text": "Database: myDatabase" }, { "code": null, "e": 25981, "s": 25960, "text": "Collection: students" }, { "code": null, "e": 26237, "s": 25981, "text": "Now, let’s use the below commands to make an object of Bulk using initializeUnorderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeUnorderedBulkOp() method is used to generate an unordered list that MongoDB runs in bulk." }, { "code": null, "e": 26621, "s": 26237, "text": "var bulk = db.students.initializeUnorderedBulkOp();\nbulk.insert( { first_name: \"Sachin\", last_name: \"Tendulkar\" } );\nbulk.insert( { first_name: \"Virender\", last_name: \"Sehwag\" } );\nbulk.insert( { first_name: \"Shikhar\", last_name: \"Dhawan\" } );\nbulk.insert( { first_name: \"Mohammed\", last_name: \"Shami\" } );\nbulk.insert( { first_name: \"Shreyas\", last_name: \"Iyer\" } );\nbulk.execute();" }, { "code": null, "e": 26681, "s": 26621, "text": "Let’s check the inserted documents using the below command:" }, { "code": null, "e": 26701, "s": 26681, "text": "db.students.find();" }, { "code": null, "e": 26951, "s": 26701, "text": "Now, let’s use the below commands to make an object of Bulk using initializeOrderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeOrderedBulkOp() method is used to generate an ordered list that MongoDB runs in bulk." }, { "code": null, "e": 27316, "s": 26951, "text": "var bulk = db.students.initializeOrderedBulkOp();\nbulk.insert( { first_name: \"Robin\", last_name: \"Marvin\" } );\nbulk.insert( { first_name: \"John\", last_name: \"Hudson\" } );\nbulk.insert( { first_name: \"Nancy\", last_name: \"Drew\" } );\nbulk.insert( { first_name: \"Tom\", last_name: \"Wheeler\" } );\nbulk.insert( { first_name: \"Anna\", last_name: \"Ryder\" } );\nbulk.execute();" }, { "code": null, "e": 27476, "s": 27316, "text": "Let’s check the inserted documents. Since we have inserted 5 more items into the collection, run the below command to get the last 5 items from the collection." }, { "code": null, "e": 27530, "s": 27476, "text": "db.students.find().sort({'_id':-1}).limit(5).pretty()" }, { "code": null, "e": 27545, "s": 27530, "text": "MongoDB-method" }, { "code": null, "e": 27552, "s": 27545, "text": "Picked" }, { "code": null, "e": 27560, "s": 27552, "text": "MongoDB" }, { "code": null, "e": 27658, "s": 27560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27696, "s": 27658, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 27721, "s": 27696, "text": "MongoDB - limit() Method" }, { "code": null, "e": 27748, "s": 27721, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 27784, "s": 27748, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 27808, "s": 27784, "text": "MongoDB - sort() Method" }, { "code": null, "e": 27863, "s": 27808, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 27920, "s": 27863, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 27946, "s": 27920, "text": "MongoDB - Update() Method" }, { "code": null, "e": 27961, "s": 27946, "text": "MongoDB Cursor" } ]
Matplotlib.figure.Figure.draw() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The draw() method figure module of matplotlib library is used to render the figure using matplotlib.backend_bases.RendererBase instance renderer. Syntax: draw(self, renderer) Parameters: This accept the following parameters that are described below: renderer: This parameter is the matplotlib.backend_bases.RendererBase instance renderer. Returns: This method does not return any value. Below examples illustrate the matplotlib.figure.Figure.draw() function in matplotlib.figure: Example 1: # Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig, ax = plt.subplots() def tellme(s): ax.set_title(s, fontsize = 16) fig.canvas.draw() renderer = fig.canvas.renderer fig.draw(renderer) tellme('matplotlib.figure.Figure.draw() \function Example') plt.show() Output: Example 2: # Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 90): ax.view_init(30, angle) fig.canvas.draw() renderer = fig.canvas.renderer fig.draw(renderer) plt.pause(.001) fig.suptitle('matplotlib.figure.Figure.draw() \ function Example') Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25580, "s": 25552, "text": "\n30 Apr, 2020" }, { "code": null, "e": 25891, "s": 25580, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 26037, "s": 25891, "text": "The draw() method figure module of matplotlib library is used to render the figure using matplotlib.backend_bases.RendererBase instance renderer." }, { "code": null, "e": 26066, "s": 26037, "text": "Syntax: draw(self, renderer)" }, { "code": null, "e": 26141, "s": 26066, "text": "Parameters: This accept the following parameters that are described below:" }, { "code": null, "e": 26230, "s": 26141, "text": "renderer: This parameter is the matplotlib.backend_bases.RendererBase instance renderer." }, { "code": null, "e": 26278, "s": 26230, "text": "Returns: This method does not return any value." }, { "code": null, "e": 26371, "s": 26278, "text": "Below examples illustrate the matplotlib.figure.Figure.draw() function in matplotlib.figure:" }, { "code": null, "e": 26382, "s": 26371, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig, ax = plt.subplots() def tellme(s): ax.set_title(s, fontsize = 16) fig.canvas.draw() renderer = fig.canvas.renderer fig.draw(renderer) tellme('matplotlib.figure.Figure.draw() \\function Example') plt.show()", "e": 26732, "s": 26382, "text": null }, { "code": null, "e": 26740, "s": 26732, "text": "Output:" }, { "code": null, "e": 26751, "s": 26740, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 90): ax.view_init(30, angle) fig.canvas.draw() renderer = fig.canvas.renderer fig.draw(renderer) plt.pause(.001) fig.suptitle('matplotlib.figure.Figure.draw() \\ function Example')", "e": 27278, "s": 26751, "text": null }, { "code": null, "e": 27286, "s": 27278, "text": "Output:" }, { "code": null, "e": 27310, "s": 27286, "text": "Matplotlib figure-class" }, { "code": null, "e": 27328, "s": 27310, "text": "Python-matplotlib" }, { "code": null, "e": 27335, "s": 27328, "text": "Python" }, { "code": null, "e": 27433, "s": 27335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27465, "s": 27433, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27507, "s": 27465, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27549, "s": 27507, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27605, "s": 27549, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27632, "s": 27605, "text": "Python Classes and Objects" }, { "code": null, "e": 27663, "s": 27632, "text": "Python | os.path.join() method" }, { "code": null, "e": 27702, "s": 27663, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27731, "s": 27702, "text": "Create a directory in Python" }, { "code": null, "e": 27753, "s": 27731, "text": "Defaultdict in Python" } ]
Instant toEpochMilli() method in Java with Examples - GeeksforGeeks
17 Feb, 2021 The toEpochMilli() method of an Instant class is used to convert this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z to a long value. This method returns that long value.Syntax: public long toEpochMilli() Returns: This method returns number of milliseconds since the epoch of 1970-01-01T00:00:00Z.Exception: This method throws ArithmeticException if numeric overflow occurs.Below programs illustrate the Instant.toEpochMilli() method:Program 1: Java // Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2018-12-30T19:34:50.63Z"); // get millisecond value using toEpochMilli() long value = instant.toEpochMilli(); // print result System.out.println("Millisecond value: " + value); }} Program 2: Java // Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.now(); // current Instant System.out.println("Current Instant: " + instant); // get millisecond value using toEpochMilli() long value = instant.toEpochMilli(); // print result System.out.println("Millisecond value: " + value); }} References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toEpochMilli() arorakashish0911 Java - util package Java-Functions Java-Instant Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Internal Working of HashMap in Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25435, "s": 25225, "text": "The toEpochMilli() method of an Instant class is used to convert this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z to a long value. This method returns that long value.Syntax: " }, { "code": null, "e": 25462, "s": 25435, "text": "public long toEpochMilli()" }, { "code": null, "e": 25704, "s": 25462, "text": "Returns: This method returns number of milliseconds since the epoch of 1970-01-01T00:00:00Z.Exception: This method throws ArithmeticException if numeric overflow occurs.Below programs illustrate the Instant.toEpochMilli() method:Program 1: " }, { "code": null, "e": 25709, "s": 25704, "text": "Java" }, { "code": "// Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2018-12-30T19:34:50.63Z\"); // get millisecond value using toEpochMilli() long value = instant.toEpochMilli(); // print result System.out.println(\"Millisecond value: \" + value); }}", "e": 26183, "s": 25709, "text": null }, { "code": null, "e": 26196, "s": 26183, "text": "Program 2: " }, { "code": null, "e": 26201, "s": 26196, "text": "Java" }, { "code": "// Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.now(); // current Instant System.out.println(\"Current Instant: \" + instant); // get millisecond value using toEpochMilli() long value = instant.toEpochMilli(); // print result System.out.println(\"Millisecond value: \" + value); }}", "e": 26748, "s": 26201, "text": null }, { "code": null, "e": 26842, "s": 26748, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toEpochMilli() " }, { "code": null, "e": 26859, "s": 26842, "text": "arorakashish0911" }, { "code": null, "e": 26879, "s": 26859, "text": "Java - util package" }, { "code": null, "e": 26894, "s": 26879, "text": "Java-Functions" }, { "code": null, "e": 26907, "s": 26894, "text": "Java-Instant" }, { "code": null, "e": 26912, "s": 26907, "text": "Java" }, { "code": null, "e": 26917, "s": 26912, "text": "Java" }, { "code": null, "e": 27015, "s": 26917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27030, "s": 27015, "text": "Stream In Java" }, { "code": null, "e": 27051, "s": 27030, "text": "Constructors in Java" }, { "code": null, "e": 27070, "s": 27051, "text": "Exceptions in Java" }, { "code": null, "e": 27100, "s": 27070, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27146, "s": 27100, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27163, "s": 27146, "text": "Generics in Java" }, { "code": null, "e": 27184, "s": 27163, "text": "Introduction to Java" }, { "code": null, "e": 27220, "s": 27184, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 27263, "s": 27220, "text": "Comparator Interface in Java with Examples" } ]
io.TeeReader() Function in Golang with Examples - GeeksforGeeks
03 May, 2020 In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The TeeReader() function in Go language is used to return a “Reader” that reads from the stated “r” and then writes it to the stated “w”. And here all the reads that are executed through the stated “r” are compared with the equivalent writes to the stated “w”. This method doesn’t require any internal buffering and the write is completed once the read completes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions. Syntax: func TeeReader(r Reader, w Writer) Reader Here, “r” is the stated Reader and “w” is the stated Writer. Return value: It returns a “Reader” that reads from the stated “r” and then writes it to the given “w”. However, any error faced while writing the content is returned as a read error. Below examples illustrates the use of above method: Example 1: // Golang program to illustrate the usage of// io.TeeReader() function // Including main packagepackage main // Importing fmt, io, strings, bytes, and osimport ( "bytes" "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("GfG\n") // Defining buffer var buf bytes.Buffer // Calling TeeReader method with its parameters r := io.TeeReader(reader, &buf) // Calling Copy method with its parameters Reader, err := io.Copy(os.Stdout, r) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("n: %v\n", Reader)} Output: GfG n: 4 In the above example, Copy() method is used in order to return the “Reader”, NewReader() method of strings is used from where the content to be read is written and an external buffer is also used here. Example 2: // Golang program to illustrate the usage of// io.TeeReader() function // Including main packagepackage main // Importing fmt, io, strings, bytes, and osimport ( "bytes" "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal.\n") // Defining buffer var buf bytes.Buffer // Calling TeeReader method with its parameters r := io.TeeReader(reader, &buf) // Calling Copy method with its parameters Reader, err := io.Copy(os.Stdout, r) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("n: %v\n", Reader)} Output: GeeksforGeeks is a CS-Portal. n: 30 Golang-io Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Time Durations in Golang Strings in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Loops in Go Language Defer Keyword in Golang Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n03 May, 2020" }, { "code": null, "e": 26372, "s": 25703, "text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The TeeReader() function in Go language is used to return a “Reader” that reads from the stated “r” and then writes it to the stated “w”. And here all the reads that are executed through the stated “r” are compared with the equivalent writes to the stated “w”. This method doesn’t require any internal buffering and the write is completed once the read completes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions." }, { "code": null, "e": 26380, "s": 26372, "text": "Syntax:" }, { "code": null, "e": 26423, "s": 26380, "text": "func TeeReader(r Reader, w Writer) Reader\n" }, { "code": null, "e": 26484, "s": 26423, "text": "Here, “r” is the stated Reader and “w” is the stated Writer." }, { "code": null, "e": 26668, "s": 26484, "text": "Return value: It returns a “Reader” that reads from the stated “r” and then writes it to the given “w”. However, any error faced while writing the content is returned as a read error." }, { "code": null, "e": 26720, "s": 26668, "text": "Below examples illustrates the use of above method:" }, { "code": null, "e": 26731, "s": 26720, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// io.TeeReader() function // Including main packagepackage main // Importing fmt, io, strings, bytes, and osimport ( \"bytes\" \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"GfG\\n\") // Defining buffer var buf bytes.Buffer // Calling TeeReader method with its parameters r := io.TeeReader(reader, &buf) // Calling Copy method with its parameters Reader, err := io.Copy(os.Stdout, r) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"n: %v\\n\", Reader)}", "e": 27424, "s": 26731, "text": null }, { "code": null, "e": 27432, "s": 27424, "text": "Output:" }, { "code": null, "e": 27442, "s": 27432, "text": "GfG\nn: 4\n" }, { "code": null, "e": 27644, "s": 27442, "text": "In the above example, Copy() method is used in order to return the “Reader”, NewReader() method of strings is used from where the content to be read is written and an external buffer is also used here." }, { "code": null, "e": 27655, "s": 27644, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// io.TeeReader() function // Including main packagepackage main // Importing fmt, io, strings, bytes, and osimport ( \"bytes\" \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"GeeksforGeeks\\nis\\na\\nCS-Portal.\\n\") // Defining buffer var buf bytes.Buffer // Calling TeeReader method with its parameters r := io.TeeReader(reader, &buf) // Calling Copy method with its parameters Reader, err := io.Copy(os.Stdout, r) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"n: %v\\n\", Reader)}", "e": 28377, "s": 27655, "text": null }, { "code": null, "e": 28385, "s": 28377, "text": "Output:" }, { "code": null, "e": 28422, "s": 28385, "text": "GeeksforGeeks\nis\na\nCS-Portal.\nn: 30\n" }, { "code": null, "e": 28432, "s": 28422, "text": "Golang-io" }, { "code": null, "e": 28444, "s": 28432, "text": "Go Language" }, { "code": null, "e": 28542, "s": 28444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28588, "s": 28542, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28617, "s": 28588, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28642, "s": 28617, "text": "Time Durations in Golang" }, { "code": null, "e": 28660, "s": 28642, "text": "Strings in Golang" }, { "code": null, "e": 28681, "s": 28660, "text": "Structures in Golang" }, { "code": null, "e": 28736, "s": 28681, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28751, "s": 28736, "text": "Rune in Golang" }, { "code": null, "e": 28772, "s": 28751, "text": "Loops in Go Language" }, { "code": null, "e": 28796, "s": 28772, "text": "Defer Keyword in Golang" } ]
How to create mat-button-toggle-group as read only mode in AngularJS ? - GeeksforGeeks
30 Nov, 2020 Angular Material is a UI component library developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it, you can enter the below command and can download it. Installation syntax: ng add @angular/material Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import ‘MatButtonToggleModule,’ from ‘@angular/material’ in the app.module.ts file. Then use <mat-button-toggle-group> and </mat-button-toggle> tags to create angular button toggle group. As the MatButtonToggleModule doesn’t consist of read-only property, we can use the disabled property to make it read-only. Once done with the above steps then serve or start the project. Code implementation: app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatButtonModule } from '@angular/material/button';import { MatButtonToggleModule } from '@angular/material/button-toggle'; @NgModule({ imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule, MatButtonToggleModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } app.component.html: HTML <mat-button-toggle-group name="techno" aria-label="technology"> <mat-button-toggle value="html"> HTML </mat-button-toggle> <mat-button-toggle disabled value="css"> CSS </mat-button-toggle> <mat-button-toggle value="javascript"> Javascript </mat-button-toggle> <mat-button-toggle value="jquery"> Jquery </mat-button-toggle></mat-button-toggle-group> Output: Observation: If you clearly observe the above output, you can understand that you can’t select and it is the way how read-only property looks like. AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26354, "s": 26326, "text": "\n30 Nov, 2020" }, { "code": null, "e": 26496, "s": 26354, "text": "Angular Material is a UI component library developed by the Angular team to build design components for desktop and mobile web applications. " }, { "code": null, "e": 26641, "s": 26496, "text": "In order to install it, we need to have angular installed in our project, once you have it, you can enter the below command and can download it." }, { "code": null, "e": 26662, "s": 26641, "text": "Installation syntax:" }, { "code": null, "e": 26687, "s": 26662, "text": "ng add @angular/material" }, { "code": null, "e": 26697, "s": 26687, "text": "Approach:" }, { "code": null, "e": 26768, "s": 26697, "text": "First, install the angular material using the above-mentioned command." }, { "code": null, "e": 26887, "s": 26768, "text": "After completing the installation, Import ‘MatButtonToggleModule,’ from ‘@angular/material’ in the app.module.ts file." }, { "code": null, "e": 26991, "s": 26887, "text": "Then use <mat-button-toggle-group> and </mat-button-toggle> tags to create angular button toggle group." }, { "code": null, "e": 27114, "s": 26991, "text": "As the MatButtonToggleModule doesn’t consist of read-only property, we can use the disabled property to make it read-only." }, { "code": null, "e": 27178, "s": 27114, "text": "Once done with the above steps then serve or start the project." }, { "code": null, "e": 27199, "s": 27178, "text": "Code implementation:" }, { "code": null, "e": 27214, "s": 27199, "text": "app.module.ts:" }, { "code": null, "e": 27225, "s": 27214, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatButtonModule } from '@angular/material/button';import { MatButtonToggleModule } from '@angular/material/button-toggle'; @NgModule({ imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule, MatButtonToggleModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 27938, "s": 27225, "text": null }, { "code": null, "e": 27958, "s": 27938, "text": "app.component.html:" }, { "code": null, "e": 27963, "s": 27958, "text": "HTML" }, { "code": "<mat-button-toggle-group name=\"techno\" aria-label=\"technology\"> <mat-button-toggle value=\"html\"> HTML </mat-button-toggle> <mat-button-toggle disabled value=\"css\"> CSS </mat-button-toggle> <mat-button-toggle value=\"javascript\"> Javascript </mat-button-toggle> <mat-button-toggle value=\"jquery\"> Jquery </mat-button-toggle></mat-button-toggle-group>", "e": 28392, "s": 27963, "text": null }, { "code": null, "e": 28400, "s": 28392, "text": "Output:" }, { "code": null, "e": 28548, "s": 28400, "text": "Observation: If you clearly observe the above output, you can understand that you can’t select and it is the way how read-only property looks like." }, { "code": null, "e": 28563, "s": 28548, "text": "AngularJS-Misc" }, { "code": null, "e": 28570, "s": 28563, "text": "Picked" }, { "code": null, "e": 28580, "s": 28570, "text": "AngularJS" }, { "code": null, "e": 28597, "s": 28580, "text": "Web Technologies" }, { "code": null, "e": 28695, "s": 28597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28730, "s": 28695, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28765, "s": 28730, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28789, "s": 28765, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28824, "s": 28789, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28877, "s": 28824, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28917, "s": 28877, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28950, "s": 28917, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28995, "s": 28950, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29038, "s": 28995, "text": "How to fetch data from an API in ReactJS ?" } ]
Mean, Median and Mode in R Programming - GeeksforGeeks
18 Jan, 2022 The measure of central tendency in R Language represents the whole set of data by a single value. It gives us the location of central points. There are three main measures of central tendency: Mean Median Mode Prerequisite: Before doing any computation, first of all, we need to prepare our data, save our data in external .txt or .csv files and it’s a best practice to save the file in the current directory. After that import, your data into R as follow: Get the CSV file here. R # R program to import data into R # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors=F)# Print the first 6 rowsprint(head(myData)) Output: Product Age Gender Education MaritalStatus Usage Fitness Income Miles 1 TM195 18 Male 14 Single 3 4 29562 112 2 TM195 19 Male 15 Single 2 3 31836 75 3 TM195 19 Female 14 Partnered 4 3 30699 66 4 TM195 19 Male 12 Single 3 3 32973 85 5 TM195 20 Male 13 Partnered 4 2 35247 47 6 TM195 20 Female 14 Partnered 3 3 32973 66 It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count. Where, n = number of terms Example: R # R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors=F) # Compute the mean valuemean = mean(myData$Age)print(mean) Output: [1] 28.78889 It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements. Where n = number of terms Syntax: median(x, na.rm = False) Where, X is a vector and na.rm is used to remove missing value Example: R # R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors=F) # Compute the median valuemedian = median(myData$Age)print(median) Output: [1] 26 It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency. There is no inbuilt function for finding mode in R, so we can create our own function for finding the mode or we can use the package called modest. There is no in-built function for finding mode in R. So let’s create a user-defined function that will return the mode of the data passed. We will be using the table() method for this as it creates a categorical representation of data with the variable names and the frequency in the form of a table. We will sort the column Age column in descending order and will return the 1 value from the sorted values. Example: Finding mode by sorting the column of the dataframe R # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors=F) mode = function(){ return(sort(-table(myData$Age))[1])} mode() Output: 25: -25 We can use the modest package of the R. This package provides methods to find the mode of the univariate data and the mode of the usual probability distribution. Example: R # R program to illustrate# Descriptive Analysis # Import the librarylibrary(modest) # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors=F) # Compute the mode valuemode = mfv(myData$Age)print(mode) Output: [1] 25 nikhilaggarwal3 kumar_satyam rkbhola5 Picked R Math-Function R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30313, "s": 30285, "text": "\n18 Jan, 2022" }, { "code": null, "e": 30507, "s": 30313, "text": "The measure of central tendency in R Language represents the whole set of data by a single value. It gives us the location of central points. There are three main measures of central tendency: " }, { "code": null, "e": 30512, "s": 30507, "text": "Mean" }, { "code": null, "e": 30519, "s": 30512, "text": "Median" }, { "code": null, "e": 30524, "s": 30519, "text": "Mode" }, { "code": null, "e": 30539, "s": 30524, "text": "Prerequisite: " }, { "code": null, "e": 30773, "s": 30539, "text": "Before doing any computation, first of all, we need to prepare our data, save our data in external .txt or .csv files and it’s a best practice to save the file in the current directory. After that import, your data into R as follow: " }, { "code": null, "e": 30798, "s": 30773, "text": "Get the CSV file here. " }, { "code": null, "e": 30800, "s": 30798, "text": "R" }, { "code": "# R program to import data into R # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors=F)# Print the first 6 rowsprint(head(myData))", "e": 30991, "s": 30800, "text": null }, { "code": null, "e": 31000, "s": 30991, "text": "Output: " }, { "code": null, "e": 31505, "s": 31000, "text": " Product Age Gender Education MaritalStatus Usage Fitness Income Miles\n1 TM195 18 Male 14 Single 3 4 29562 112\n2 TM195 19 Male 15 Single 2 3 31836 75\n3 TM195 19 Female 14 Partnered 4 3 30699 66\n4 TM195 19 Male 12 Single 3 3 32973 85\n5 TM195 20 Male 13 Partnered 4 2 35247 47\n6 TM195 20 Female 14 Partnered 3 3 32973 66" }, { "code": null, "e": 31645, "s": 31505, "text": "It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count." }, { "code": null, "e": 31672, "s": 31645, "text": "Where, n = number of terms" }, { "code": null, "e": 31682, "s": 31672, "text": "Example: " }, { "code": null, "e": 31684, "s": 31682, "text": "R" }, { "code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors=F) # Compute the mean valuemean = mean(myData$Age)print(mean)", "e": 31905, "s": 31684, "text": null }, { "code": null, "e": 31914, "s": 31905, "text": "Output: " }, { "code": null, "e": 31927, "s": 31914, "text": "[1] 28.78889" }, { "code": null, "e": 32166, "s": 31927, "text": "It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements." }, { "code": null, "e": 32192, "s": 32166, "text": "Where n = number of terms" }, { "code": null, "e": 32225, "s": 32192, "text": "Syntax: median(x, na.rm = False)" }, { "code": null, "e": 32288, "s": 32225, "text": "Where, X is a vector and na.rm is used to remove missing value" }, { "code": null, "e": 32298, "s": 32288, "text": "Example: " }, { "code": null, "e": 32300, "s": 32298, "text": "R" }, { "code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors=F) # Compute the median valuemedian = median(myData$Age)print(median)", "e": 32529, "s": 32300, "text": null }, { "code": null, "e": 32538, "s": 32529, "text": "Output: " }, { "code": null, "e": 32545, "s": 32538, "text": "[1] 26" }, { "code": null, "e": 32946, "s": 32545, "text": "It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency. There is no inbuilt function for finding mode in R, so we can create our own function for finding the mode or we can use the package called modest." }, { "code": null, "e": 33354, "s": 32946, "text": "There is no in-built function for finding mode in R. So let’s create a user-defined function that will return the mode of the data passed. We will be using the table() method for this as it creates a categorical representation of data with the variable names and the frequency in the form of a table. We will sort the column Age column in descending order and will return the 1 value from the sorted values." }, { "code": null, "e": 33415, "s": 33354, "text": "Example: Finding mode by sorting the column of the dataframe" }, { "code": null, "e": 33417, "s": 33415, "text": "R" }, { "code": "# Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors=F) mode = function(){ return(sort(-table(myData$Age))[1])} mode()", "e": 33597, "s": 33417, "text": null }, { "code": null, "e": 33605, "s": 33597, "text": "Output:" }, { "code": null, "e": 33613, "s": 33605, "text": "25: -25" }, { "code": null, "e": 33775, "s": 33613, "text": "We can use the modest package of the R. This package provides methods to find the mode of the univariate data and the mode of the usual probability distribution." }, { "code": null, "e": 33785, "s": 33775, "text": "Example: " }, { "code": null, "e": 33787, "s": 33785, "text": "R" }, { "code": "# R program to illustrate# Descriptive Analysis # Import the librarylibrary(modest) # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors=F) # Compute the mode valuemode = mfv(myData$Age)print(mode)", "e": 34043, "s": 33787, "text": null }, { "code": null, "e": 34052, "s": 34043, "text": "Output: " }, { "code": null, "e": 34059, "s": 34052, "text": "[1] 25" }, { "code": null, "e": 34075, "s": 34059, "text": "nikhilaggarwal3" }, { "code": null, "e": 34088, "s": 34075, "text": "kumar_satyam" }, { "code": null, "e": 34097, "s": 34088, "text": "rkbhola5" }, { "code": null, "e": 34104, "s": 34097, "text": "Picked" }, { "code": null, "e": 34120, "s": 34104, "text": "R Math-Function" }, { "code": null, "e": 34133, "s": 34120, "text": "R-Statistics" }, { "code": null, "e": 34144, "s": 34133, "text": "R Language" }, { "code": null, "e": 34242, "s": 34144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34287, "s": 34242, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 34345, "s": 34287, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 34397, "s": 34345, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 34429, "s": 34397, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 34492, "s": 34429, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 34536, "s": 34492, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 34588, "s": 34536, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 34653, "s": 34588, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 34688, "s": 34653, "text": "Group by function in R using Dplyr" } ]
Automatic Resource Management in Java ( try with resource statements ) - GeeksforGeeks
24 Jan, 2022 Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. This statement ensures that each resource is closed at the end of the statement, which eases working with external resources that need to be disposed of or closed in case of errors or successful completion of a code block. A resource is an object that must be closed after the program is finished using it. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. In earlier versions of Java before JDK 1.7, the closing of resources was done using the finally block. Java // Java program to illustrate cleaning of// resources before Java 7 import java.io.*;import java.util.*;import java.io.*;class Resource{ public static void main(String args[]) { BufferedReader br = null; String str = " "; System.out.println("Enter the file path"); br = new BufferedReader(new InputStreamReader(System.in)); try { str = br.readLine(); } catch(IOException e) { e.printStackTrace(); } try { String s; // file resource br = new BufferedReader(new FileReader(str)); while ((s = br.readLine()) != null) { // print all the lines in the text file System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) // closing the resource in 'finally' block br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }} Output: hello java In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local. The resource will be closed automatically regardless of whether the try statement completes normally or abruptly. Syntax: The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it: static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } Java // Java program to illustrate// Automatic Resource Management// in Java without finally block import java.io.*;import java.util.*; class Resource { public static void main(String args[]) { String str = ""; BufferedReader br = null; System.out.println("Enter the file path"); br = new BufferedReader( new InputStreamReader(System.in)); try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } // try with Resource // note the syntax difference try (BufferedReader b = new BufferedReader(new FileReader(str))) { String s; while ((s = b.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } }} Output: hello java Multiple resources can be used inside a try-with-resources block and have them all automatically closed. In this case, the resources will be closed in the reverse order in which they were created inside the brackets. Java // Java program to illustrate// Automatic Resource Management// in Java with multiple resource class Resource { public static void main(String s[]) { // note the order of opening the resources try (Demo d = new Demo(); Demo1 d1 = new Demo1()) { int x = 10 / 0; d.show(); d1.show1(); } catch (ArithmeticException e) { System.out.println(e); } }} // custom resource 1class Demo implements AutoCloseable { void show() { System.out.println("inside show"); } public void close() { System.out.println("close from demo"); }} // custom resource 2class Demo1 implements AutoCloseable { void show1() { System.out.println("inside show1"); } public void close() { System.out.println("close from demo1"); }} Output: close from demo1 close from demo Note: In the above example, Demo and Demo1 are the custom resources managed inside the try block. Such resources need to implement the AutoCloseable interface. When we open any such AutoCloseable resource in the special try-with-resource block, immediately after finishing the try block, JVM calls this.close() method on all resources initialized in the try block. Important Points: The finally blocks were used to clean up the resources before Java 7.After java 7, resource cleanup is done automatically.ARM is done when you initialize resources in the try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as the try block finishes.Calling the close() method might lead to unexpected results.A resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid a compile-time error.The resources which are used in multiple resource ARM must be closed in reverse order as given in the above example The finally blocks were used to clean up the resources before Java 7. After java 7, resource cleanup is done automatically. ARM is done when you initialize resources in the try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as the try block finishes. Calling the close() method might lead to unexpected results. A resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid a compile-time error. The resources which are used in multiple resource ARM must be closed in reverse order as given in the above example This article is contributed by Apoorva singh. 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. pskamble nishkarshgandhi Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 25771, "s": 25743, "text": "\n24 Jan, 2022" }, { "code": null, "e": 26055, "s": 25771, "text": "Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. " }, { "code": null, "e": 26278, "s": 26055, "text": "This statement ensures that each resource is closed at the end of the statement, which eases working with external resources that need to be disposed of or closed in case of errors or successful completion of a code block." }, { "code": null, "e": 26503, "s": 26278, "text": "A resource is an object that must be closed after the program is finished using it. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource." }, { "code": null, "e": 26607, "s": 26503, "text": "In earlier versions of Java before JDK 1.7, the closing of resources was done using the finally block. " }, { "code": null, "e": 26612, "s": 26607, "text": "Java" }, { "code": "// Java program to illustrate cleaning of// resources before Java 7 import java.io.*;import java.util.*;import java.io.*;class Resource{ public static void main(String args[]) { BufferedReader br = null; String str = \" \"; System.out.println(\"Enter the file path\"); br = new BufferedReader(new InputStreamReader(System.in)); try { str = br.readLine(); } catch(IOException e) { e.printStackTrace(); } try { String s; // file resource br = new BufferedReader(new FileReader(str)); while ((s = br.readLine()) != null) { // print all the lines in the text file System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) // closing the resource in 'finally' block br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }}", "e": 27881, "s": 26612, "text": null }, { "code": null, "e": 27889, "s": 27881, "text": "Output:" }, { "code": null, "e": 27900, "s": 27889, "text": "hello\njava" }, { "code": null, "e": 28302, "s": 27900, "text": "In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local. The resource will be closed automatically regardless of whether the try statement completes normally or abruptly. " }, { "code": null, "e": 28311, "s": 28302, "text": "Syntax: " }, { "code": null, "e": 28522, "s": 28311, "text": "The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it: " }, { "code": null, "e": 28707, "s": 28522, "text": "static String readFirstLineFromFile(String path) throws IOException\n{\n try (BufferedReader br = new BufferedReader(new FileReader(path)))\n {\n return br.readLine();\n }\n}" }, { "code": null, "e": 28712, "s": 28707, "text": "Java" }, { "code": "// Java program to illustrate// Automatic Resource Management// in Java without finally block import java.io.*;import java.util.*; class Resource { public static void main(String args[]) { String str = \"\"; BufferedReader br = null; System.out.println(\"Enter the file path\"); br = new BufferedReader( new InputStreamReader(System.in)); try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } // try with Resource // note the syntax difference try (BufferedReader b = new BufferedReader(new FileReader(str))) { String s; while ((s = b.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } }}", "e": 29584, "s": 28712, "text": null }, { "code": null, "e": 29592, "s": 29584, "text": "Output:" }, { "code": null, "e": 29604, "s": 29592, "text": "hello \njava" }, { "code": null, "e": 29822, "s": 29604, "text": "Multiple resources can be used inside a try-with-resources block and have them all automatically closed. In this case, the resources will be closed in the reverse order in which they were created inside the brackets. " }, { "code": null, "e": 29827, "s": 29822, "text": "Java" }, { "code": "// Java program to illustrate// Automatic Resource Management// in Java with multiple resource class Resource { public static void main(String s[]) { // note the order of opening the resources try (Demo d = new Demo(); Demo1 d1 = new Demo1()) { int x = 10 / 0; d.show(); d1.show1(); } catch (ArithmeticException e) { System.out.println(e); } }} // custom resource 1class Demo implements AutoCloseable { void show() { System.out.println(\"inside show\"); } public void close() { System.out.println(\"close from demo\"); }} // custom resource 2class Demo1 implements AutoCloseable { void show1() { System.out.println(\"inside show1\"); } public void close() { System.out.println(\"close from demo1\"); }}", "e": 30651, "s": 29827, "text": null }, { "code": null, "e": 30659, "s": 30651, "text": "Output:" }, { "code": null, "e": 30692, "s": 30659, "text": "close from demo1\nclose from demo" }, { "code": null, "e": 31058, "s": 30692, "text": "Note: In the above example, Demo and Demo1 are the custom resources managed inside the try block. Such resources need to implement the AutoCloseable interface. When we open any such AutoCloseable resource in the special try-with-resource block, immediately after finishing the try block, JVM calls this.close() method on all resources initialized in the try block. " }, { "code": null, "e": 31077, "s": 31058, "text": "Important Points: " }, { "code": null, "e": 31666, "s": 31077, "text": "The finally blocks were used to clean up the resources before Java 7.After java 7, resource cleanup is done automatically.ARM is done when you initialize resources in the try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as the try block finishes.Calling the close() method might lead to unexpected results.A resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid a compile-time error.The resources which are used in multiple resource ARM must be closed in reverse order as given in the above example" }, { "code": null, "e": 31736, "s": 31666, "text": "The finally blocks were used to clean up the resources before Java 7." }, { "code": null, "e": 31790, "s": 31736, "text": "After java 7, resource cleanup is done automatically." }, { "code": null, "e": 31974, "s": 31790, "text": "ARM is done when you initialize resources in the try-with-resources block because of the interface AutoCloseable. Its close method is invoked by JVM as soon as the try block finishes." }, { "code": null, "e": 32035, "s": 31974, "text": "Calling the close() method might lead to unexpected results." }, { "code": null, "e": 32144, "s": 32035, "text": "A resource that we use in try-with-resource must be subtypes of AutoCloseable to avoid a compile-time error." }, { "code": null, "e": 32260, "s": 32144, "text": "The resources which are used in multiple resource ARM must be closed in reverse order as given in the above example" }, { "code": null, "e": 32682, "s": 32260, "text": "This article is contributed by Apoorva singh. 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": 32691, "s": 32682, "text": "pskamble" }, { "code": null, "e": 32707, "s": 32691, "text": "nishkarshgandhi" }, { "code": null, "e": 32712, "s": 32707, "text": "Java" }, { "code": null, "e": 32731, "s": 32712, "text": "Technical Scripter" }, { "code": null, "e": 32736, "s": 32731, "text": "Java" }, { "code": null, "e": 32834, "s": 32736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32849, "s": 32834, "text": "Stream In Java" }, { "code": null, "e": 32868, "s": 32849, "text": "Interfaces in Java" }, { "code": null, "e": 32886, "s": 32868, "text": "ArrayList in Java" }, { "code": null, "e": 32906, "s": 32886, "text": "Stack Class in Java" }, { "code": null, "e": 32930, "s": 32906, "text": "Singleton Class in Java" }, { "code": null, "e": 32962, "s": 32930, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32974, "s": 32962, "text": "Set in Java" }, { "code": null, "e": 32997, "s": 32974, "text": "Multithreading in Java" }, { "code": null, "e": 33017, "s": 32997, "text": "Collections in Java" } ]
Java Program to Calculate Sum of Two Byte Values Using Type Casting - GeeksforGeeks
11 Nov, 2020 The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The Sum of two-byte values might cross the given limit of byte, this condition can be handled using storing the sum of two-byte numbers in an integer variable. Example: Input: firstByte = 10, secondByte = 23 Output: Sum = 33 Input: firstByte = 10, secondByte = 23 Output: Sum = 33 Type Casting: Typecasting is simply known as cast one data type, into another data type. For example, in this program, Byte values are cast into an integer. Approach: Declare and initialize the two-byte variable. Declare one int variable. Store the sum of the two-byte numbers into an int variable. Below is the implementation of the above approach Java // Java Program to Calculate Sum of// Two Byte Values Using Type Casting public class GFG { public static void main(String[] args) { // create two variable of byte type byte firstByte = 113; byte secondByte = 123; // create int variable to store result int sum; sum = firstByte + secondByte; System.out.println("sum = " + sum); }} sum = 236 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25251, "s": 25223, "text": "\n11 Nov, 2020" }, { "code": null, "e": 25623, "s": 25251, "text": "The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The Sum of two-byte values might cross the given limit of byte, this condition can be handled using storing the sum of two-byte numbers in an integer variable." }, { "code": null, "e": 25632, "s": 25623, "text": "Example:" }, { "code": null, "e": 25748, "s": 25632, "text": "Input: firstByte = 10, secondByte = 23\nOutput: Sum = 33\n\nInput: firstByte = 10, secondByte = 23\nOutput: Sum = 33\n" }, { "code": null, "e": 25905, "s": 25748, "text": "Type Casting: Typecasting is simply known as cast one data type, into another data type. For example, in this program, Byte values are cast into an integer." }, { "code": null, "e": 25915, "s": 25905, "text": "Approach:" }, { "code": null, "e": 25961, "s": 25915, "text": "Declare and initialize the two-byte variable." }, { "code": null, "e": 25987, "s": 25961, "text": "Declare one int variable." }, { "code": null, "e": 26047, "s": 25987, "text": "Store the sum of the two-byte numbers into an int variable." }, { "code": null, "e": 26097, "s": 26047, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 26102, "s": 26097, "text": "Java" }, { "code": "// Java Program to Calculate Sum of// Two Byte Values Using Type Casting public class GFG { public static void main(String[] args) { // create two variable of byte type byte firstByte = 113; byte secondByte = 123; // create int variable to store result int sum; sum = firstByte + secondByte; System.out.println(\"sum = \" + sum); }}", "e": 26496, "s": 26102, "text": null }, { "code": null, "e": 26508, "s": 26496, "text": "sum = 236\n\n" }, { "code": null, "e": 26513, "s": 26508, "text": "Java" }, { "code": null, "e": 26527, "s": 26513, "text": "Java Programs" }, { "code": null, "e": 26532, "s": 26527, "text": "Java" }, { "code": null, "e": 26630, "s": 26532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26645, "s": 26630, "text": "Stream In Java" }, { "code": null, "e": 26666, "s": 26645, "text": "Constructors in Java" }, { "code": null, "e": 26685, "s": 26666, "text": "Exceptions in Java" }, { "code": null, "e": 26715, "s": 26685, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26761, "s": 26715, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26787, "s": 26761, "text": "Java Programming Examples" }, { "code": null, "e": 26821, "s": 26787, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26868, "s": 26821, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 26900, "s": 26868, "text": "How to Iterate HashMap in Java?" } ]
#define vs #undef in C language - GeeksforGeeks
04 May, 2021 In this article, we will discuss the difference between #define and #undef pre-processor in C language. Pre-Processor: Pre-processor is a program that performs before the compilation. It only notices the # started statement. # is called preprocessor directive. Each preprocessing directive must be on its own line. The word after # is called the preprocessor command. #define: The #define directive defines an identifier and a character sequence (a set of characters) that will be substituted for the identifier each time it is encountered in the source file. Syntax: #define macro-name char-sequence.The identifier is referred to as a macro name and replacement process as a macro replacement. Example: #define PI 3.14Here. PI is the macro-name and 3.14 is the char-sequence. Program 1: Below is the C program illustrating the use of #define: C // C program illustrating the use of// #define#include <stdio.h>#define PI 3.14 // Driver Codeint main(){ int r = 4; float a; a = PI * r * r; printf("area of circle is %f", a); return 0;} area of circle is 50.240002 Explanation: In this example, PI is the macro-name and the char-sequence is 3.14. When the program runs the compiler will check the #define command first and assign the PI as 3.14. Now in the entire program wherever the compiler sees the PI word it will replace it with 3.14. Program 2: Below is the C program printing product of two numbers using #define: C // C program to find the product of// two numbers using #define #include <stdio.h>#define PRODUCT(a, b) a* b // Driver Codeint main(){ printf("product of a and b is " "%d", PRODUCT(3, 4)); return 0;} product of a and b is 12 Explanation: In this example, a macro-name as the product is defined and passes two arguments as a and b and gives the char-sequence as the product of these two arguments. When the compiler sees the macro-name in the print statement, it replaces the macro-name with the product of a and b and gives the answer as their product. #undef: The #undef preprocessor directive is used to undefined macros. Syntax: #undef macro-name Program 3: Below is the C program to illustrate the use of #undef in a program: C // C program to illustrate the use// of #undef in a program#include <stdio.h>#define PI 3.14#undef PI // Driver Codeint main(){ int r = 6; float a; a = PI * r * r; printf("area of circle is %f", a); return 0;} Output: Explanation: In this example, when #undef is used, then it will delete the #define command and the macro will get undefined and the compiler will show the error. C-Macro & Preprocessor Macro & Preprocessor C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25478, "s": 25450, "text": "\n04 May, 2021" }, { "code": null, "e": 25582, "s": 25478, "text": "In this article, we will discuss the difference between #define and #undef pre-processor in C language." }, { "code": null, "e": 25597, "s": 25582, "text": "Pre-Processor:" }, { "code": null, "e": 25662, "s": 25597, "text": "Pre-processor is a program that performs before the compilation." }, { "code": null, "e": 25703, "s": 25662, "text": "It only notices the # started statement." }, { "code": null, "e": 25739, "s": 25703, "text": "# is called preprocessor directive." }, { "code": null, "e": 25793, "s": 25739, "text": "Each preprocessing directive must be on its own line." }, { "code": null, "e": 25846, "s": 25793, "text": "The word after # is called the preprocessor command." }, { "code": null, "e": 25855, "s": 25846, "text": "#define:" }, { "code": null, "e": 26038, "s": 25855, "text": "The #define directive defines an identifier and a character sequence (a set of characters) that will be substituted for the identifier each time it is encountered in the source file." }, { "code": null, "e": 26046, "s": 26038, "text": "Syntax:" }, { "code": null, "e": 26173, "s": 26046, "text": "#define macro-name char-sequence.The identifier is referred to as a macro name and replacement process as a macro replacement." }, { "code": null, "e": 26182, "s": 26173, "text": "Example:" }, { "code": null, "e": 26255, "s": 26182, "text": "#define PI 3.14Here. PI is the macro-name and 3.14 is the char-sequence." }, { "code": null, "e": 26266, "s": 26255, "text": "Program 1:" }, { "code": null, "e": 26323, "s": 26266, "text": "Below is the C program illustrating the use of #define: " }, { "code": null, "e": 26325, "s": 26323, "text": "C" }, { "code": "// C program illustrating the use of// #define#include <stdio.h>#define PI 3.14 // Driver Codeint main(){ int r = 4; float a; a = PI * r * r; printf(\"area of circle is %f\", a); return 0;}", "e": 26533, "s": 26325, "text": null }, { "code": null, "e": 26562, "s": 26533, "text": "area of circle is 50.240002\n" }, { "code": null, "e": 26575, "s": 26562, "text": "Explanation:" }, { "code": null, "e": 26644, "s": 26575, "text": "In this example, PI is the macro-name and the char-sequence is 3.14." }, { "code": null, "e": 26743, "s": 26644, "text": "When the program runs the compiler will check the #define command first and assign the PI as 3.14." }, { "code": null, "e": 26838, "s": 26743, "text": "Now in the entire program wherever the compiler sees the PI word it will replace it with 3.14." }, { "code": null, "e": 26849, "s": 26838, "text": "Program 2:" }, { "code": null, "e": 26920, "s": 26849, "text": " Below is the C program printing product of two numbers using #define:" }, { "code": null, "e": 26922, "s": 26920, "text": "C" }, { "code": "// C program to find the product of// two numbers using #define #include <stdio.h>#define PRODUCT(a, b) a* b // Driver Codeint main(){ printf(\"product of a and b is \" \"%d\", PRODUCT(3, 4)); return 0;}", "e": 27152, "s": 26922, "text": null }, { "code": null, "e": 27178, "s": 27152, "text": "product of a and b is 12\n" }, { "code": null, "e": 27191, "s": 27178, "text": "Explanation:" }, { "code": null, "e": 27350, "s": 27191, "text": "In this example, a macro-name as the product is defined and passes two arguments as a and b and gives the char-sequence as the product of these two arguments." }, { "code": null, "e": 27506, "s": 27350, "text": "When the compiler sees the macro-name in the print statement, it replaces the macro-name with the product of a and b and gives the answer as their product." }, { "code": null, "e": 27514, "s": 27506, "text": "#undef:" }, { "code": null, "e": 27578, "s": 27514, "text": "The #undef preprocessor directive is used to undefined macros. " }, { "code": null, "e": 27586, "s": 27578, "text": "Syntax:" }, { "code": null, "e": 27604, "s": 27586, "text": "#undef macro-name" }, { "code": null, "e": 27615, "s": 27604, "text": "Program 3:" }, { "code": null, "e": 27684, "s": 27615, "text": "Below is the C program to illustrate the use of #undef in a program:" }, { "code": null, "e": 27686, "s": 27684, "text": "C" }, { "code": "// C program to illustrate the use// of #undef in a program#include <stdio.h>#define PI 3.14#undef PI // Driver Codeint main(){ int r = 6; float a; a = PI * r * r; printf(\"area of circle is %f\", a); return 0;}", "e": 27916, "s": 27686, "text": null }, { "code": null, "e": 27924, "s": 27916, "text": "Output:" }, { "code": null, "e": 28087, "s": 27924, "text": "Explanation: In this example, when #undef is used, then it will delete the #define command and the macro will get undefined and the compiler will show the error. " }, { "code": null, "e": 28110, "s": 28087, "text": "C-Macro & Preprocessor" }, { "code": null, "e": 28131, "s": 28110, "text": "Macro & Preprocessor" }, { "code": null, "e": 28142, "s": 28131, "text": "C Language" }, { "code": null, "e": 28153, "s": 28142, "text": "C Programs" }, { "code": null, "e": 28251, "s": 28153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28289, "s": 28251, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28315, "s": 28289, "text": "Exception Handling in C++" }, { "code": null, "e": 28335, "s": 28315, "text": "Multithreading in C" }, { "code": null, "e": 28357, "s": 28335, "text": "'this' pointer in C++" }, { "code": null, "e": 28398, "s": 28357, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28411, "s": 28398, "text": "Strings in C" }, { "code": null, "e": 28452, "s": 28411, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28493, "s": 28452, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28528, "s": 28493, "text": "Header files in C/C++ and its uses" } ]
Overview of Kalman Filter for Self-Driving Car - GeeksforGeeks
18 Oct, 2021 A Kalman Filter is an optimal estimation algorithm. It can help us predict/estimate the position of an object when we are in a state of doubt due to different limitations such as accuracy or physical constraints which we will discuss in a short while. Application of Kalman filter:Kalman filters are used when – Variable of interest that can only be measured indirectly. Measurements are available from various sensors but might be subject to noise i.e Sensor Fusion. Let’s dig deep into each of the uses one by one. Indirect measurement:To measure the Variable of interest(variable under consideration) that can only be measured indirectly. This type of variable is called the state estimated variable. Let’s understand it with an example.Example:Let’s say that you want to know how happy your dog Jacky is. Thus your variable of interest, y is Jacky’s happiness. Now the only way to measure jacky’s happiness is to measure it indirectly as happiness is not a physical state that can be measured directly. You can choose to see Jacky waves his tail and predict whether he is happy or not. You also might have a whole different approach to give you an idea or estimate how happy Jacky is. This unique idea is the Kalman Filter. And that’s what I meant when I said that Kalman filter is an optimal estimation algorithm.Sensor Fusion:Now you have the intuition of what this filter exactly is. Kalman Filter combines the measurement and the prediction to find the optimal estimate of the car’s position.Example:Suppose you have a remote-controlled car and its running at a speed of 1 m/s. let’s say that after 1 second you need to predict the exact position of the car what will be your prediction??Well if you know some basic time, distance and speed formula you will be correctly able to say 1 meter ahead of the current position. But how accurate is this model??There are always some variations from the ideal scenario and that deviation is the cause of the error. Now to minimize the error in the state prediction, the measurement from a sensor is taken. The sensor measurement has some error as well. So now we have two probability distributions(the sensor and the prediction as they are not always a number but the probability distribution function(pdf)) that are supposed to tell the location of the car. Once we combine these two gaussian curve we can get a whole new gaussian that has far less variance.Example:Suppose you have a friend(Sensor 2) who is good at maths and not that great in physics and you(Sensor 1) are good at physics but not so much in maths. Now on the day of the examination, when your target is getting a good result, you and your friend come together in order to excel in both the subjects. You both collaborate to minimize the error and maximize the result(output).Example:It’s just like when you need to find out about an incident, you ask different individuals about it and after listening to all their stories, you make your own which, you seem is far accurate than any of the individual stories. See its always related to our daily lives and we can always make a connection with what we have already experienced. Indirect measurement:To measure the Variable of interest(variable under consideration) that can only be measured indirectly. This type of variable is called the state estimated variable. Let’s understand it with an example.Example:Let’s say that you want to know how happy your dog Jacky is. Thus your variable of interest, y is Jacky’s happiness. Now the only way to measure jacky’s happiness is to measure it indirectly as happiness is not a physical state that can be measured directly. You can choose to see Jacky waves his tail and predict whether he is happy or not. You also might have a whole different approach to give you an idea or estimate how happy Jacky is. This unique idea is the Kalman Filter. And that’s what I meant when I said that Kalman filter is an optimal estimation algorithm. Sensor Fusion:Now you have the intuition of what this filter exactly is. Kalman Filter combines the measurement and the prediction to find the optimal estimate of the car’s position.Example:Suppose you have a remote-controlled car and its running at a speed of 1 m/s. let’s say that after 1 second you need to predict the exact position of the car what will be your prediction??Well if you know some basic time, distance and speed formula you will be correctly able to say 1 meter ahead of the current position. But how accurate is this model??There are always some variations from the ideal scenario and that deviation is the cause of the error. Now to minimize the error in the state prediction, the measurement from a sensor is taken. The sensor measurement has some error as well. So now we have two probability distributions(the sensor and the prediction as they are not always a number but the probability distribution function(pdf)) that are supposed to tell the location of the car. Once we combine these two gaussian curve we can get a whole new gaussian that has far less variance.Example:Suppose you have a friend(Sensor 2) who is good at maths and not that great in physics and you(Sensor 1) are good at physics but not so much in maths. Now on the day of the examination, when your target is getting a good result, you and your friend come together in order to excel in both the subjects. You both collaborate to minimize the error and maximize the result(output).Example:It’s just like when you need to find out about an incident, you ask different individuals about it and after listening to all their stories, you make your own which, you seem is far accurate than any of the individual stories. See its always related to our daily lives and we can always make a connection with what we have already experienced. Code: Python implementation of the 1-D Kalman filter def update(mean1, var1, mean2, var2): new_mean = float(var2 * mean1 + var1 * mean2) / (var1 + var2) new_var = 1./(1./var1 + 1./var2) return [new_mean, new_var] def predict(mean1, var1, mean2, var2): new_mean = mean1 + mean2 new_var = var1 + var2 return [new_mean, new_var] measurements = [5., 6., 7., 9., 10.]motion = [1., 1., 2., 1., 1.]measurement_sig = 4.motion_sig = 2.mu = 0.sig = 10000. # print out ONLY the final values of the meanalthough for a better understanding you may choose to # and the variance in a list [mu, sig]. for measurement, motion in zip(measurements, motion): mu, sig = update(measurement, measurement_sig, mu, sig) mu, sig = predict(motion, motion_sig, mu, sig)print([mu, sig]) Explanation:As we have discussed there are two major steps in the complete process first Update step and then prediction step. These two steps are looped over and over to estimate the exact position of the robot. The prediction step :New position p’ can be calculated using the formula Now to write this complete thing in a single matrix. Prediction Step The update step :The filter you just implemented is in python and that too in 1-D. Mostly we deal with more than one dimension and the language changes for the same. So let’s implement a Kalman filter in C++. Requirement:Eigen libraryYou will need the Eigen library, especially the Dense class in order to work with the linear algebra required in the process. Download the library and paste it in the folder containing the code files, in case you don’t know how libraries work in C++. Also go through the official documentation for a better understanding of how to use its functionality. I have to admit the way they have explained in the documentation is amazing and better than any tutorial you can ask for. Now implementing the same prediction and update function in c++ using this new weapon(library) we have found to deal with the algebra part in the process.Prediction Step: void KalmanFilter::Predict(){ x = F * x; MatrixXd Ft = F.transpose(); P = F * P * Ft + Q;} With that, we were able to calculate the predicted value of X and the covariance matrix P. Update Step: So for lidar, the measurement function looks like this: It also can be represented in a matrix form: Representation in a Matrix form H is the measurement function that maps the state to the measurement and helps in calculating the Error (y) by comparing the measurement(z) with our prediction(H*x). void KalmanFilter::Update(const VectorXd& z){ VectorXd z_pred = H * x; VectorXd y = z - z_pred; MatrixXd Ht = H.transpose(); MatrixXd S = H * P * Ht + R; MatrixXd Si = S.inverse(); MatrixXd PHt = P * Ht; MatrixXd K = PHt * Si; // new estimate x = x + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P = (I - K * H) * P;} Code: // create a 4D state vector, we don't know yet the values of the x statex = VectorXd(4); // state covariance matrix PP = MatrixXd(4, 4);P << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1000, 0, 0, 0, 0, 1000; // measurement covarianceR = MatrixXd(2, 2);R << 0.0225, 0, 0, 0.0225; // measurement matrixH = MatrixXd(2, 4);H << 1, 0, 0, 0, 0, 1, 0, 0; // the initial transition matrix FF = MatrixXd(4, 4);F << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1; // set the acceleration noise componentsnoise_ax = 5;noise_ay = 5; The reason why I didn’t initialize the matrices at first is that that is not the main part while we are writing a Kalman filter. First, we should know how the two main function works. then come the initialization and other stuff. Some drawbacks : We are making this Kalman filter model in order to deal with lidar data that can be dealt with a linear function to predict. Well, we don’t use the only Lidar in a Self-driving car. we also use Radar and to use it we need to make some adjustments in the same code but for starters, this is perfect. We are assuming that the vehicle traced is moving at a constant velocity which is a big assumption thus we will be using a CTRV model which stands for Constant turn rate and velocity magnitude model and while dealing with that we will see a whole new approach to complete the task called the Unscented Kalman filter.My Personal Notes arrow_drop_upSave simmytarika5 Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Any Website to Android App in Android Studio? C++ program for Complex Number Calculator GUI Application for the Student Management System How to create Text Editor using Javascript and HTML ? Python | ToDo GUI Application using Tkinter Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe sum() function in Python
[ { "code": null, "e": 25697, "s": 25669, "text": "\n18 Oct, 2021" }, { "code": null, "e": 25949, "s": 25697, "text": "A Kalman Filter is an optimal estimation algorithm. It can help us predict/estimate the position of an object when we are in a state of doubt due to different limitations such as accuracy or physical constraints which we will discuss in a short while." }, { "code": null, "e": 26009, "s": 25949, "text": "Application of Kalman filter:Kalman filters are used when –" }, { "code": null, "e": 26068, "s": 26009, "text": "Variable of interest that can only be measured indirectly." }, { "code": null, "e": 26165, "s": 26068, "text": "Measurements are available from various sensors but might be subject to noise i.e Sensor Fusion." }, { "code": null, "e": 26214, "s": 26165, "text": "Let’s dig deep into each of the uses one by one." }, { "code": null, "e": 28844, "s": 26214, "text": "Indirect measurement:To measure the Variable of interest(variable under consideration) that can only be measured indirectly. This type of variable is called the state estimated variable. Let’s understand it with an example.Example:Let’s say that you want to know how happy your dog Jacky is. Thus your variable of interest, y is Jacky’s happiness. Now the only way to measure jacky’s happiness is to measure it indirectly as happiness is not a physical state that can be measured directly. You can choose to see Jacky waves his tail and predict whether he is happy or not. You also might have a whole different approach to give you an idea or estimate how happy Jacky is. This unique idea is the Kalman Filter. And that’s what I meant when I said that Kalman filter is an optimal estimation algorithm.Sensor Fusion:Now you have the intuition of what this filter exactly is. Kalman Filter combines the measurement and the prediction to find the optimal estimate of the car’s position.Example:Suppose you have a remote-controlled car and its running at a speed of 1 m/s. let’s say that after 1 second you need to predict the exact position of the car what will be your prediction??Well if you know some basic time, distance and speed formula you will be correctly able to say 1 meter ahead of the current position. But how accurate is this model??There are always some variations from the ideal scenario and that deviation is the cause of the error. Now to minimize the error in the state prediction, the measurement from a sensor is taken. The sensor measurement has some error as well. So now we have two probability distributions(the sensor and the prediction as they are not always a number but the probability distribution function(pdf)) that are supposed to tell the location of the car. Once we combine these two gaussian curve we can get a whole new gaussian that has far less variance.Example:Suppose you have a friend(Sensor 2) who is good at maths and not that great in physics and you(Sensor 1) are good at physics but not so much in maths. Now on the day of the examination, when your target is getting a good result, you and your friend come together in order to excel in both the subjects. You both collaborate to minimize the error and maximize the result(output).Example:It’s just like when you need to find out about an incident, you ask different individuals about it and after listening to all their stories, you make your own which, you seem is far accurate than any of the individual stories. See its always related to our daily lives and we can always make a connection with what we have already experienced." }, { "code": null, "e": 29646, "s": 28844, "text": "Indirect measurement:To measure the Variable of interest(variable under consideration) that can only be measured indirectly. This type of variable is called the state estimated variable. Let’s understand it with an example.Example:Let’s say that you want to know how happy your dog Jacky is. Thus your variable of interest, y is Jacky’s happiness. Now the only way to measure jacky’s happiness is to measure it indirectly as happiness is not a physical state that can be measured directly. You can choose to see Jacky waves his tail and predict whether he is happy or not. You also might have a whole different approach to give you an idea or estimate how happy Jacky is. This unique idea is the Kalman Filter. And that’s what I meant when I said that Kalman filter is an optimal estimation algorithm." }, { "code": null, "e": 31475, "s": 29646, "text": "Sensor Fusion:Now you have the intuition of what this filter exactly is. Kalman Filter combines the measurement and the prediction to find the optimal estimate of the car’s position.Example:Suppose you have a remote-controlled car and its running at a speed of 1 m/s. let’s say that after 1 second you need to predict the exact position of the car what will be your prediction??Well if you know some basic time, distance and speed formula you will be correctly able to say 1 meter ahead of the current position. But how accurate is this model??There are always some variations from the ideal scenario and that deviation is the cause of the error. Now to minimize the error in the state prediction, the measurement from a sensor is taken. The sensor measurement has some error as well. So now we have two probability distributions(the sensor and the prediction as they are not always a number but the probability distribution function(pdf)) that are supposed to tell the location of the car. Once we combine these two gaussian curve we can get a whole new gaussian that has far less variance.Example:Suppose you have a friend(Sensor 2) who is good at maths and not that great in physics and you(Sensor 1) are good at physics but not so much in maths. Now on the day of the examination, when your target is getting a good result, you and your friend come together in order to excel in both the subjects. You both collaborate to minimize the error and maximize the result(output).Example:It’s just like when you need to find out about an incident, you ask different individuals about it and after listening to all their stories, you make your own which, you seem is far accurate than any of the individual stories. See its always related to our daily lives and we can always make a connection with what we have already experienced." }, { "code": null, "e": 31528, "s": 31475, "text": "Code: Python implementation of the 1-D Kalman filter" }, { "code": "def update(mean1, var1, mean2, var2): new_mean = float(var2 * mean1 + var1 * mean2) / (var1 + var2) new_var = 1./(1./var1 + 1./var2) return [new_mean, new_var] def predict(mean1, var1, mean2, var2): new_mean = mean1 + mean2 new_var = var1 + var2 return [new_mean, new_var] measurements = [5., 6., 7., 9., 10.]motion = [1., 1., 2., 1., 1.]measurement_sig = 4.motion_sig = 2.mu = 0.sig = 10000. # print out ONLY the final values of the meanalthough for a better understanding you may choose to # and the variance in a list [mu, sig]. for measurement, motion in zip(measurements, motion): mu, sig = update(measurement, measurement_sig, mu, sig) mu, sig = predict(motion, motion_sig, mu, sig)print([mu, sig])", "e": 32262, "s": 31528, "text": null }, { "code": null, "e": 32475, "s": 32262, "text": "Explanation:As we have discussed there are two major steps in the complete process first Update step and then prediction step. These two steps are looped over and over to estimate the exact position of the robot." }, { "code": null, "e": 32548, "s": 32475, "text": "The prediction step :New position p’ can be calculated using the formula" }, { "code": null, "e": 32601, "s": 32548, "text": "Now to write this complete thing in a single matrix." }, { "code": null, "e": 32617, "s": 32601, "text": "Prediction Step" }, { "code": null, "e": 32826, "s": 32617, "text": "The update step :The filter you just implemented is in python and that too in 1-D. Mostly we deal with more than one dimension and the language changes for the same. So let’s implement a Kalman filter in C++." }, { "code": null, "e": 33327, "s": 32826, "text": "Requirement:Eigen libraryYou will need the Eigen library, especially the Dense class in order to work with the linear algebra required in the process. Download the library and paste it in the folder containing the code files, in case you don’t know how libraries work in C++. Also go through the official documentation for a better understanding of how to use its functionality. I have to admit the way they have explained in the documentation is amazing and better than any tutorial you can ask for." }, { "code": null, "e": 33498, "s": 33327, "text": "Now implementing the same prediction and update function in c++ using this new weapon(library) we have found to deal with the algebra part in the process.Prediction Step:" }, { "code": "void KalmanFilter::Predict(){ x = F * x; MatrixXd Ft = F.transpose(); P = F * P * Ft + Q;}", "e": 33598, "s": 33498, "text": null }, { "code": null, "e": 33689, "s": 33598, "text": "With that, we were able to calculate the predicted value of X and the covariance matrix P." }, { "code": null, "e": 33702, "s": 33689, "text": "Update Step:" }, { "code": null, "e": 33758, "s": 33702, "text": "So for lidar, the measurement function looks like this:" }, { "code": null, "e": 33803, "s": 33758, "text": "It also can be represented in a matrix form:" }, { "code": null, "e": 33835, "s": 33803, "text": "Representation in a Matrix form" }, { "code": null, "e": 34001, "s": 33835, "text": "H is the measurement function that maps the state to the measurement and helps in calculating the Error (y) by comparing the measurement(z) with our prediction(H*x)." }, { "code": "void KalmanFilter::Update(const VectorXd& z){ VectorXd z_pred = H * x; VectorXd y = z - z_pred; MatrixXd Ht = H.transpose(); MatrixXd S = H * P * Ht + R; MatrixXd Si = S.inverse(); MatrixXd PHt = P * Ht; MatrixXd K = PHt * Si; // new estimate x = x + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P = (I - K * H) * P;}", "e": 34395, "s": 34001, "text": null }, { "code": null, "e": 34401, "s": 34395, "text": "Code:" }, { "code": "// create a 4D state vector, we don't know yet the values of the x statex = VectorXd(4); // state covariance matrix PP = MatrixXd(4, 4);P << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1000, 0, 0, 0, 0, 1000; // measurement covarianceR = MatrixXd(2, 2);R << 0.0225, 0, 0, 0.0225; // measurement matrixH = MatrixXd(2, 4);H << 1, 0, 0, 0, 0, 1, 0, 0; // the initial transition matrix FF = MatrixXd(4, 4);F << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1; // set the acceleration noise componentsnoise_ax = 5;noise_ay = 5;", "e": 34938, "s": 34401, "text": null }, { "code": null, "e": 35168, "s": 34938, "text": "The reason why I didn’t initialize the matrices at first is that that is not the main part while we are writing a Kalman filter. First, we should know how the two main function works. then come the initialization and other stuff." }, { "code": null, "e": 35185, "s": 35168, "text": "Some drawbacks :" }, { "code": null, "e": 35484, "s": 35185, "text": "We are making this Kalman filter model in order to deal with lidar data that can be dealt with a linear function to predict. Well, we don’t use the only Lidar in a Self-driving car. we also use Radar and to use it we need to make some adjustments in the same code but for starters, this is perfect." }, { "code": null, "e": 35836, "s": 35484, "text": "We are assuming that the vehicle traced is moving at a constant velocity which is a big assumption thus we will be using a CTRV model which stands for Constant turn rate and velocity magnitude model and while dealing with that we will see a whole new approach to complete the task called the Unscented Kalman filter.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 35849, "s": 35836, "text": "simmytarika5" }, { "code": null, "e": 35857, "s": 35849, "text": "Project" }, { "code": null, "e": 35864, "s": 35857, "text": "Python" }, { "code": null, "e": 35962, "s": 35864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36023, "s": 35962, "text": "How to Convert Any Website to Android App in Android Studio?" }, { "code": null, "e": 36065, "s": 36023, "text": "C++ program for Complex Number Calculator" }, { "code": null, "e": 36115, "s": 36065, "text": "GUI Application for the Student Management System" }, { "code": null, "e": 36169, "s": 36115, "text": "How to create Text Editor using Javascript and HTML ?" }, { "code": null, "e": 36213, "s": 36169, "text": "Python | ToDo GUI Application using Tkinter" }, { "code": null, "e": 36241, "s": 36213, "text": "Read JSON file using Python" }, { "code": null, "e": 36291, "s": 36241, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 36313, "s": 36291, "text": "Python map() function" }, { "code": null, "e": 36357, "s": 36313, "text": "How to get column names in Pandas dataframe" } ]